text
stringlengths
3
1.05M
# noqa: D100 import numpy as np def max_index(X): """Return the index of the maximum in a numpy array. Parameters ---------- X : ndarray of shape (n_samples, n_features) The input array. Returns ------- i : int The row index of the maximum. j : int The column index of the maximum. Raises ------ ValueError If the input is not a numpy error or if the shape is not 2D. """ if X is None or type(X) is not np.ndarray: raise ValueError( "The input array X is None or not a numpy array.") if len(X.shape) != 2: raise ValueError( "The shape is not 2D.") s = X.shape[0] result = np.argmax(X) i = result // s j = result % s return i, j def wallis_product(n_terms): """Implement the Wallis product to compute an approximation of pi. See: https://en.wikipedia.org/wiki/Wallis_product """ x = 2 for n in range(1, n_terms + 1): x *= ((4 * n ** 2) / (4 * n ** 2 - 1)) return x
#!/usr/bin/env python import unittest, re from unittest import TestCase from plasTeX.TeX import TeX from plasTeX import Macro class Verbatim(TestCase): def testVerbatim(self): intext = 'line one\nline two' input = 'hi \\begin{verbatim}\n%s\n\\end{verbatim} bye' % intext s = TeX() s.input(input) output = s.parse() output.normalize() text = ''.join(output.childNodes[1].childNodes).strip() assert intext == text, '"%s" != "%s"' % (intext, text) def testVerb(self): intext = r' verbatim \tt text ' input = r'hi \verb+%s+ bye' % intext s = TeX() s.input(input) output = s.parse() output.normalize() text = ''.join(output.childNodes[1].childNodes) assert intext == text, '"%s" != "%s"' % (intext, text) def testVerbStar(self): intext = r' verbatim \tt text ' input = r'hi \verb*+%s+ bye' % intext s = TeX() s.input(input) output = s.parse() output.normalize() text = ''.join(output.childNodes[1].childNodes) assert intext == text, '"%s" != "%s"' % (intext, text) if __name__ == '__main__': unittest.main()
var _c_l_2_non_linear_filter_8cpp = [ [ "CLNonLinearFilterFixture", "_c_l_2_non_linear_filter_8cpp.xhtml#a4f51783dfb1dc97681b4a518f62ea892", null ], [ "DATA_TEST_CASE", "_c_l_2_non_linear_filter_8cpp.xhtml#af47ccf8173fbf22b22f0649949789046", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_non_linear_filter_8cpp.xhtml#a6a1601ba8c6ddb69c605270a72bb67e6", null ], [ "FIXTURE_DATA_TEST_CASE", "_c_l_2_non_linear_filter_8cpp.xhtml#a4484cf41bcf89df8e91b70f39d99db91", null ] ];
/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". */ /* $Header: ranlib.h,v 2.3 90/10/25 11:18:34 ceriel Exp $ */ #ifndef __RANLIB_H_INCLUDED #define __RANLIB_H_INCLUDED #ifndef SYMDEF # define SYMDEF "__.SYMDEF" #endif /* SYMDEF */ /* * Structure of the SYMDEF table of contents for an archive. * SYMDEF begins with a long giving the number of ranlib * structures that immediately follow, and then continues with a string * table consisting of a long giving the number of bytes of * strings that follow and then the strings themselves. */ struct ranlib { union { char *ran__ptr; /* symbol name (in core) */ long ran__off; /* symbol name (in file) */ } ran_u; #define ran_ptr ran_u.ran__ptr #define ran_off ran_u.ran__off long ran_pos; /* library member is at this position */ }; #define SZ_RAN 8 #define SF_RAN "44" #endif /* __RANLIB_H_INCLUDED */
import logging import time from subprocess import run import pytest from seldon_e2e_utils import ( API_AMBASSADOR, API_ISTIO_GATEWAY, assert_model, assert_model_during_op, get_pod_name_for_sdep, initial_rest_request, rest_request_ambassador, retry_run, to_resources_path, wait_for_pod_shutdown, wait_for_rollout, wait_for_status, ) with_api_gateways = pytest.mark.parametrize( "api_gateway", [API_AMBASSADOR, API_ISTIO_GATEWAY], ids=["ambas", "istio"] ) @pytest.mark.sequential @pytest.mark.flaky(max_runs=5) @with_api_gateways class TestRollingHttp(object): # Test updating a model to a multi predictor model def test_rolling_update5(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace) logging.warning("Initial request") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph6.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(50): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert (res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0]) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ) if (not r.status_code == 200) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ): break time.sleep(1) assert i < 100 logging.warning("Success for test_rolling_update5") run(f"kubectl delete -f ../resources/graph1.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph6.json -n {namespace}", shell=True) # Test updating a model with a new image version as the only change def test_rolling_update6(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1svc.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace, expected_deployments=2) logging.warning("Initial request") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph2svc.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(100): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert (res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0]) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ) if (not r.status_code == 200) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ): break time.sleep(1) assert i < 100 logging.warning("Success for test_rolling_update6") run(f"kubectl delete -f ../resources/graph1svc.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph2svc.json -n {namespace}", shell=True) # test changing the image version and the name of its container def test_rolling_update7(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1svc.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace, expected_deployments=2) logging.warning("Initial request") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph3svc.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(100): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert (res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0]) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ) if (not r.status_code == 200) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ): break time.sleep(1) assert i < 100 logging.warning("Success for test_rolling_update7") run(f"kubectl delete -f ../resources/graph1svc.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph3svc.json -n {namespace}", shell=True) # Test updating a model with a new resource request but same image def test_rolling_update8(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1svc.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace, expected_deployments=2) r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph4svc.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(50): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] time.sleep(1) assert i == 49 logging.warning("Success for test_rolling_update8") run(f"kubectl delete -f ../resources/graph1svc.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph4svc.json -n {namespace}", shell=True) # Test updating a model with a multi deployment new model def test_rolling_update9(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1svc.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace, expected_deployments=2) r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph5svc.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(50): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] time.sleep(1) assert i == 49 logging.warning("Success for test_rolling_update9") run(f"kubectl delete -f ../resources/graph1svc.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph5svc.json -n {namespace}", shell=True) # Test updating a model to a multi predictor model def test_rolling_update10(self, namespace, api_gateway): retry_run(f"kubectl apply -f ../resources/graph1svc.json -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace, expected_deployments=2) r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] retry_run(f"kubectl apply -f ../resources/graph6svc.json -n {namespace}") r = initial_rest_request("mymodel", namespace, endpoint=api_gateway) assert r.status_code == 200 assert r.json()["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0] i = 0 for i in range(50): r = rest_request_ambassador("mymodel", namespace, api_gateway) assert r.status_code == 200 res = r.json() assert (res["data"]["tensor"]["values"] == [1.0, 2.0, 3.0, 4.0]) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ) if (not r.status_code == 200) or ( res["data"]["tensor"]["values"] == [5.0, 6.0, 7.0, 8.0] ): break time.sleep(1) assert i < 100 logging.warning("Success for test_rolling_update10") run(f"kubectl delete -f ../resources/graph1svc.json -n {namespace}", shell=True) run(f"kubectl delete -f ../resources/graph6svc.json -n {namespace}", shell=True) @pytest.mark.flaky(max_runs=3) @with_api_gateways @pytest.mark.parametrize( "from_deployment,to_deployment,change", [ ("graph1.json", "graph2.json", True), # New image version ( "graph1.json", "graph3.json", True, ), # New image version and new name of container ("graph1.json", "graph4.json", True), # New resource request but same image ("graph1.json", "graph5.json", True), # Update with multi-deployment new model ("graph1.json", "graph8.json", True), # From v1alpha2 to v1 ("graph7.json", "graph8.json", False), # From v1alpha3 to v1 ], ) def test_rolling_deployment( namespace, api_gateway, from_deployment, to_deployment, change ): from_file_path = to_resources_path(from_deployment) retry_run(f"kubectl apply -f {from_file_path} -n {namespace}") wait_for_status("mymodel", namespace) wait_for_rollout("mymodel", namespace) assert_model("mymodel", namespace, initial=True, endpoint=api_gateway) old_pod_name = get_pod_name_for_sdep("mymodel", namespace)[0] to_file_path = to_resources_path(to_deployment) def _update_model(): retry_run(f"kubectl apply -f {to_file_path} -n {namespace}") if change: wait_for_pod_shutdown(old_pod_name, namespace) wait_for_status("mymodel", namespace) time.sleep(2) # Wait a little after deployment marked Available assert_model_during_op(_update_model, "mymodel", namespace, endpoint=api_gateway) delete_cmd = f"kubectl delete --ignore-not-found -n {namespace}" run(f"{delete_cmd} -f {from_file_path}", shell=True) run(f"{delete_cmd} -f {to_file_path}", shell=True)
Drop.prototype.watchWindow = function() { $(window).on('resize scroll', () => { this.tick(); }); return this; }; Drop.prototype.watchDrag = function() { $(this.data.anchor).on('drag dragstart dragstop', () => { this.tick(); }); return this; };
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """TPU Estimator Signalling Tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.contrib.tpu.python.tpu import tpu_estimator from tensorflow.python import data as dataset_lib from tensorflow.python.client import session from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.platform import test def make_input_fn(num_samples): a = np.linspace(0, 100.0, num=num_samples) b = np.reshape(np.array(a, dtype=np.float32), (len(a), 1)) def input_fn(params): batch_size = params['batch_size'] da1 = dataset_lib.Dataset.from_tensor_slices(a) da2 = dataset_lib.Dataset.from_tensor_slices(b) dataset = dataset_lib.Dataset.zip((da1, da2)) dataset = dataset.map(lambda fa, fb: {'a': fa, 'b': fb}) dataset = dataset.batch(batch_size) return dataset return input_fn, (a, b) def make_input_fn_with_labels(num_samples): a = np.linspace(0, 100.0, num=num_samples) b = np.reshape(np.array(a, dtype=np.float32), (len(a), 1)) def input_fn(params): batch_size = params['batch_size'] da1 = dataset_lib.Dataset.from_tensor_slices(a) da2 = dataset_lib.Dataset.from_tensor_slices(b) dataset = dataset_lib.Dataset.zip((da1, da2)) dataset = dataset.map(lambda fa, fb: ({'a': fa}, fb)) dataset = dataset.batch(batch_size) return dataset return input_fn, (a, b) class TPUEstimatorStoppingSignalsTest(test.TestCase): def test_normal_output_without_signals(self): num_samples = 4 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) features = dataset.make_one_shot_iterator().get_next() # With tf.data.Dataset.batch, the batch is None, i.e., dynamic shape. self.assertIsNone(features['a'].shape.as_list()[0]) with session.Session() as sess: result = sess.run(features) self.assertAllEqual(a[:batch_size], result['a']) self.assertAllEqual(b[:batch_size], result['b']) # This run should work as num_samples / batch_size = 2. result = sess.run(features) self.assertAllEqual(a[batch_size:num_samples], result['a']) self.assertAllEqual(b[batch_size:num_samples], result['b']) with self.assertRaises(errors.OutOfRangeError): # Given num_samples and batch_size, this run should fail. sess.run(features) def test_output_with_stopping_signals(self): num_samples = 4 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) inputs = tpu_estimator._InputsWithStoppingSignals(dataset, batch_size) hook = inputs.dataset_initializer_hook() features, _ = inputs.features_and_labels() signals = inputs.signals() # With tf.data.Dataset.batch, the batch is None, i.e., dynamic shape. self.assertIsNone(features['a'].shape.as_list()[0]) with session.Session() as sess: hook.begin() hook.after_create_session(sess, coord=None) result, evaluated_signals = sess.run([features, signals]) self.assertAllEqual(a[:batch_size], result['a']) self.assertAllEqual(b[:batch_size], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # This run should work as num_samples / batch_size = 2. result, evaluated_signals = sess.run([features, signals]) self.assertAllEqual(a[batch_size:num_samples], result['a']) self.assertAllEqual(b[batch_size:num_samples], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # This run should work, *but* see STOP ('1') as signals _, evaluated_signals = sess.run([features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) with self.assertRaises(errors.OutOfRangeError): sess.run(features) class TPUEstimatorStoppingSignalsWithPaddingTest(test.TestCase): def test_num_samples_divisible_by_batch_size(self): num_samples = 4 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) inputs = tpu_estimator._InputsWithStoppingSignals(dataset, batch_size, add_padding=True) hook = inputs.dataset_initializer_hook() features, _ = inputs.features_and_labels() signals = inputs.signals() # With padding, all shapes are static now. self.assertEqual(batch_size, features['a'].shape.as_list()[0]) with session.Session() as sess: hook.begin() hook.after_create_session(sess, coord=None) result, evaluated_signals = sess.run([features, signals]) self.assertAllEqual(a[:batch_size], result['a']) self.assertAllEqual(b[:batch_size], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([0.] * batch_size, evaluated_signals['padding_mask']) # This run should work as num_samples / batch_size = 2. result, evaluated_signals = sess.run([features, signals]) self.assertAllEqual(a[batch_size:num_samples], result['a']) self.assertAllEqual(b[batch_size:num_samples], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([0.] * batch_size, evaluated_signals['padding_mask']) # This run should work, *but* see STOP ('1') as signals _, evaluated_signals = sess.run([features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) with self.assertRaises(errors.OutOfRangeError): sess.run(features) def test_num_samples_not_divisible_by_batch_size(self): num_samples = 5 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn_with_labels(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) inputs = tpu_estimator._InputsWithStoppingSignals(dataset, batch_size, add_padding=True) hook = inputs.dataset_initializer_hook() features, labels = inputs.features_and_labels() signals = inputs.signals() # With padding, all shapes are static. self.assertEqual(batch_size, features['a'].shape.as_list()[0]) with session.Session() as sess: hook.begin() hook.after_create_session(sess, coord=None) evaluated_features, evaluated_labels, evaluated_signals = ( sess.run([features, labels, signals])) self.assertAllEqual(a[:batch_size], evaluated_features['a']) self.assertAllEqual(b[:batch_size], evaluated_labels) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([0.] * batch_size, evaluated_signals['padding_mask']) # This run should work as num_samples / batch_size >= 2. evaluated_features, evaluated_labels, evaluated_signals = ( sess.run([features, labels, signals])) self.assertAllEqual(a[batch_size:2*batch_size], evaluated_features['a']) self.assertAllEqual(b[batch_size:2*batch_size], evaluated_labels) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([0.] * batch_size, evaluated_signals['padding_mask']) # This is the final partial batch. evaluated_features, evaluated_labels, evaluated_signals = ( sess.run([features, labels, signals])) real_batch_size = num_samples % batch_size # Assert the real part. self.assertAllEqual(a[2*batch_size:num_samples], evaluated_features['a'][:real_batch_size]) self.assertAllEqual(b[2*batch_size:num_samples], evaluated_labels[:real_batch_size]) # Assert the padded part. self.assertAllEqual([0.0] * (batch_size - real_batch_size), evaluated_features['a'][real_batch_size:]) self.assertAllEqual([[0.0]] * (batch_size - real_batch_size), evaluated_labels[real_batch_size:]) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) padding = ([.0] * real_batch_size + [1.] * (batch_size - real_batch_size)) self.assertAllEqual(padding, evaluated_signals['padding_mask']) # This run should work, *but* see STOP ('1') as signals _, evaluated_signals = sess.run([features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) with self.assertRaises(errors.OutOfRangeError): sess.run(features) def test_slice(self): num_samples = 3 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) inputs = tpu_estimator._InputsWithStoppingSignals(dataset, batch_size, add_padding=True) hook = inputs.dataset_initializer_hook() features, _ = inputs.features_and_labels() signals = inputs.signals() sliced_features = ( tpu_estimator._PaddingSignals.slice_tensor_or_dict( features, signals)) with session.Session() as sess: hook.begin() hook.after_create_session(sess, coord=None) result, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual(a[:batch_size], result['a']) self.assertAllEqual(b[:batch_size], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # This is the final partial batch. result, evaluated_signals = sess.run([sliced_features, signals]) self.assertEqual(1, len(result['a'])) self.assertAllEqual(a[batch_size:num_samples], result['a']) self.assertAllEqual(b[batch_size:num_samples], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # This run should work, *but* see STOP ('1') as signals _, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) with self.assertRaises(errors.OutOfRangeError): sess.run(sliced_features) def test_slice_with_multi_invocations_per_step(self): num_samples = 3 batch_size = 2 params = {'batch_size': batch_size} input_fn, (a, b) = make_input_fn(num_samples=num_samples) with ops.Graph().as_default(): dataset = input_fn(params) inputs = tpu_estimator._InputsWithStoppingSignals( dataset, batch_size, add_padding=True, num_invocations_per_step=2) hook = inputs.dataset_initializer_hook() features, _ = inputs.features_and_labels() signals = inputs.signals() sliced_features = ( tpu_estimator._PaddingSignals.slice_tensor_or_dict(features, signals)) with session.Session() as sess: hook.begin() hook.after_create_session(sess, coord=None) result, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual(a[:batch_size], result['a']) self.assertAllEqual(b[:batch_size], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # This is the final partial batch. result, evaluated_signals = sess.run([sliced_features, signals]) self.assertEqual(1, len(result['a'])) self.assertAllEqual(a[batch_size:num_samples], result['a']) self.assertAllEqual(b[batch_size:num_samples], result['b']) self.assertAllEqual([[0.]] * batch_size, evaluated_signals['stopping']) # We should see 3 continuous batches with STOP ('1') as signals and all # of them have mask 1. _, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([1.] * batch_size, evaluated_signals['padding_mask']) _, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([1.] * batch_size, evaluated_signals['padding_mask']) _, evaluated_signals = sess.run([sliced_features, signals]) self.assertAllEqual([[1.]] * batch_size, evaluated_signals['stopping']) self.assertAllEqual([1.] * batch_size, evaluated_signals['padding_mask']) with self.assertRaises(errors.OutOfRangeError): sess.run(sliced_features) if __name__ == '__main__': test.main()
/** * Created by macbook on 17/5/2. */
// Copyright 2010 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. // // Author: onufry@google.com (Jakub Onufry Wojtaszczyk) // Author: ptab@google.com (Piotr Tabor) // // Basic expression types by arity. #ifndef SUPERSONIC_EXPRESSION_INFRASTRUCTURE_BASIC_EXPRESSIONS_H_ #define SUPERSONIC_EXPRESSION_INFRASTRUCTURE_BASIC_EXPRESSIONS_H_ #include <string> using std::string; #include "supersonic/utils/macros.h" #include "supersonic/utils/scoped_ptr.h" #include "supersonic/base/exception/result.h" #include "supersonic/base/infrastructure/types.h" #include "supersonic/expression/base/expression.h" #include "supersonic/expression/infrastructure/bound_expression_creators.h" namespace supersonic { // ---------------------------------------------------------------------------- // Internal building blocks. // Base class for expressions taking a single child expression. // It will bind it's child and call CreateBoundUnaryExpression to bind the // expression itself. class BufferAllocator; class TupleSchema; class UnaryExpression : public Expression { public: virtual ~UnaryExpression() {} virtual FailureOrOwned<BoundExpression> DoBind( const TupleSchema& input_schema, BufferAllocator* allocator, rowcount_t max_row_count) const; protected: explicit UnaryExpression(const Expression* const child_expression) : child_expression_(child_expression) { } protected: scoped_ptr<const Expression> child_expression_; private: // Should bind expression knowing that its child is already bound. // The returned expression should be ready to use. virtual FailureOrOwned<BoundExpression> CreateBoundUnaryExpression( const TupleSchema& input_schema, BufferAllocator* const allocator, rowcount_t row_capacity, BoundExpression* child) const = 0; DISALLOW_COPY_AND_ASSIGN(UnaryExpression); }; // Base class for binary expressions with simple (one-attribute) children. // It will bind it's children and call CreateBoundBinaryExpression to bind // expression itself. class BinaryExpression : public Expression { public: virtual ~BinaryExpression() {} virtual FailureOrOwned<BoundExpression> DoBind( const TupleSchema& input_schema, BufferAllocator* allocator, rowcount_t max_row_count) const; protected: BinaryExpression(const Expression* const left, const Expression* const right) : left_(left), right_(right) { } scoped_ptr<const Expression> left_; scoped_ptr<const Expression> right_; private: // Should bind expression knowing that its childern are already bound. // The returned expression should be ready to use. virtual FailureOrOwned<BoundExpression> CreateBoundBinaryExpression( const TupleSchema& input_schema, BufferAllocator* const allocator, rowcount_t row_capacity, BoundExpression* left, BoundExpression* right) const = 0; DISALLOW_COPY_AND_ASSIGN(BinaryExpression); }; // Base class for ternary expressions with simple (one-attribute) children. // It will bind it's children and call CreateBoundTernaryExpression to bind // expression itself. class TernaryExpression : public Expression { public: virtual ~TernaryExpression() {} virtual FailureOrOwned<BoundExpression> DoBind( const TupleSchema& input_schema, BufferAllocator* allocator, rowcount_t max_row_count) const; protected: TernaryExpression(const Expression* const left, const Expression* const middle, const Expression* const right) : left_(left), middle_(middle), right_(right) { } scoped_ptr<const Expression> left_; scoped_ptr<const Expression> middle_; scoped_ptr<const Expression> right_; private: // Should bind expression knowing that its childern are already bound. // The returned expression should be ready to use. virtual FailureOrOwned<BoundExpression> CreateBoundTernaryExpression( const TupleSchema& input_schema, BufferAllocator* const allocator, rowcount_t row_capacity, BoundExpression* left, BoundExpression* middle, BoundExpression* right) const = 0; DISALLOW_COPY_AND_ASSIGN(TernaryExpression); }; // The methods below create an expression that delegates binding to the given // bound expression factory method. // It is a common case that expression might be defined as combination of // other expressions. In such a situation a bound factory method need to be // defined that uses the other bound factory methods for composition. If you // need to define the (not bound) expression that describes such an operation, // the methods do the job for you. // In the description_pattern "$0" will be replaced with description of the // child (ex. "FINGERPRINT($0)"). Expression* CreateExpressionForExistingBoundFactory( const Expression* const child, BoundUnaryExpressionFactory bound_expression_factory, const string& description_pattern); // In the description_pattern "$0" and "$1" will be replaced with description of // the left and right child (ex. "CONTAINS($0, $1)"). Expression* CreateExpressionForExistingBoundFactory( const Expression* const left, const Expression* const right, BoundBinaryExpressionFactory bound_expression_factory, const string& description_pattern); // In the description_pattern "$0", "$1" and "$2" will be replaced with the // descriptions of the left, middle and right child respectively. Expression* CreateExpressionForExistingBoundFactory( const Expression* const left, const Expression* const middle, const Expression* const right, BoundTernaryExpressionFactory bound_expression_factory, const string& description_pattern); } // namespace supersonic #endif // SUPERSONIC_EXPRESSION_INFRASTRUCTURE_BASIC_EXPRESSIONS_H_
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"say_hello": "00_core.ipynb", "HelloSayer": "00_core.ipynb"} modules = ["core.py"] doc_url = "https://Rakeshsuku.github.io/my_nbdev_tutorial/" git_url = "https://github.com/Rakeshsuku/my_nbdev_tutorial/tree/master/" def custom_doc_links(name): return None
/* * Variables, Data Types, and Typing */ let wordData = "Word List"; console.log(wordData); let subTotal = 100; let tax = subTotal * 0.07; let totalWithTax = tax + subTotal; let obj = { key1: "value 1", key2: 3, boolean: true, obj2: { obj2key1: "value of inner object", }, }; console.log(obj.obj2.obj2key1); let var1 = "2"; let var2 = 5; let result = var1 + var2 let add = 1 + 2; let sub = 2 - 1; let mult = 2*4; let division = 4 / 2; let mod = 5 % 2; let string = "String 1 " + "String 2"; console.log(string);
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: liangliangyy @license: MIT Licence @contact: liangliangyy@gmail.com @site: https://www.lylinux.net/ @software: PyCharm @file: commonapi.py @time: 2017/9/2 上午1:43 """ import requests import json import logging logger = logging.getLogger(__name__) class TuLing(): def __init__(self): self.__key__ = '2f1446eb0321804291b0a1e217c25bb5' self.__appid__ = 137762 def __build_req_url(self, content): return 'http://www.tuling123.com/openapi/api?key=%s&info=%s&userid=%s' % ( self.__key__, content, self.__appid__) def UserAgent(self, url): rsp = requests.get(url) return rsp.content def getdata(self, content): try: requrl = self.__build_req_url(content) res = self.UserAgent(requrl).decode('utf-8') jsons = json.loads(res, encoding='utf-8') if str(jsons["code"]) == '100000': return jsons["text"] except Exception as e: logger.error(e) return "哎呀,出错啦。"
# Copyright 2010-2014, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. { 'variables': { 'relative_dir': 'usage_stats', 'gen_out_dir': '<(SHARED_INTERMEDIATE_DIR)/<(relative_dir)', }, 'targets': [ { 'target_name': 'usage_stats_uploader', 'type': 'static_library', 'sources': [ 'upload_util.cc', 'usage_stats_uploader.cc', 'usage_stats_updater.cc', ], 'dependencies': [ '../base/base.gyp:base', '../base/base.gyp:config_file_stream', '../base/base.gyp:encryptor', '../config/config.gyp:config_handler', '../config/config.gyp:config_protocol', '../config/config.gyp:stats_config_util', '../net/net.gyp:http_client', '../session/session_base.gyp:keymap', '../storage/storage.gyp:storage', 'usage_stats_base.gyp:gen_usage_stats_list#host', 'usage_stats_base.gyp:usage_stats', 'usage_stats_base.gyp:usage_stats_protocol', ], 'xcode_settings' : { 'SDKROOT': 'iphoneos', 'IPHONEOS_DEPLOYMENT_TARGET': '7.0', 'ARCHS': '$(ARCHS_UNIVERSAL_IPHONE_OS)', }, }, ], }
var express = require('express'); var router = express.Router(); const Instatouch = require('instatouch'); router.get('/', function (req, res, next) { res.send('respond with a resource'); }); router.post('/', function (req, res, next) { let options = { endCursor: epochToId(dateToEpoch(new Date(req.body.toYear, req.body.toMonth, req.body.toDay, 10, 33, 30, 0))), session: "sessionid=9172858944%3AQ72coMNjTByeNG%3A21" } Instatouch.location(req.body.location, options).then((data) => { res.render('feed', { data: data.collector }) }).catch((err) => console.log("error", err)) }); function epochToId(n) { return Math.round((n * 0.008388608 - 11024476.5839159095) * 1000000000000); } function dateToEpoch(d) { return (d.getTime() - d.getMilliseconds()) / 1000; } module.exports = router;
""" Goal: Delegate requests to the `/api` path to the appropriate controller @authors: Andrei Sura <sura.andrei@gmail.com> """ import collections from binascii import unhexlify from flask import request from flask_login import login_required from flask_login import current_user from olass import utils from olass.main import app from olass.models.linkage_entity import LinkageEntity from olass.models.oauth_access_token_entity import OauthAccessTokenEntity from .oauth import oauth as auth log = app.logger @app.route('/api/', methods=['POST', 'GET']) @app.route('/api/hello', methods=['POST', 'GET']) @login_required def say_hello(): """ Say hello """ return utils.jsonify_success({ 'message': 'Hello {}! You are logged in.'.format(current_user.email) }) @app.route('/api/me', methods=['POST', 'GET']) @auth.require_oauth() def me(): user = request.oauth.user return utils.jsonify_success({ 'user': user.serialize(), 'client': request.oauth.client.serialize() }) def get_partner_from_token(access_token): """ Walk the token->client->user->partner chain so we can connect the the `LinkageEntity` row to a `PartnerEntity` """ tok = OauthAccessTokenEntity.query.filter_by( access_token=access_token).one_or_none() log.debug("get_partner_from_token found: {}".format(tok)) return tok.client.user.partner @app.route('/api/save', methods=['POST', 'GET']) @auth.require_oauth() def api_save_patient_hashes(): """ For each chunk save a new uuid or return an existing one from the database. == Example of input json: { "data": { "1": { "1": "b2cdaea3d7c9891b2ed94d1973fe5085183e4bb4bd87b672e066a456ee67bd38" }, "2": { "1": "345b192ae4093dcbc5c914bdcb5e8c41e58162475a295c88b1ce594bd3dd78f7", "2": "1dcce10470c0ea73a8a6287f69f4f862c5e13faea7c11104fae07dbc8d5ce56e" }, "3": { "1": "995b192ae4093dcbc5c914bdcb5e8c41e58162475a295c88b1ce594bd3dd78f7" } } } == To find the rows in the database: select hex(linkage_uuid), hex(linkage_hash) from linkage order by linkage_id; """ auth_pieces = request.headers.get('Authorization').split(' ') log.debug("Authorization_header: {}".format(auth_pieces)) access_token = auth_pieces[1].strip() partner = get_partner_from_token(access_token) json = request.get_json(silent=False) if not json: err = "Invalid json object specified" log.error(err) return utils.jsonify_error(err) result = collections.defaultdict(dict) json_data = json['data'] # patient chunks are received in groups for pat_id, pat_chunks in json_data.items(): # Since there is a chance of duplicate chunks find uniques chunks = list(set(chunk for chunk_num, chunk in pat_chunks.items())) chunks_cache = LinkageEntity.get_chunks_cache(chunks) uuids = LinkageEntity.get_distinct_uuids_for_chunks(chunks_cache) log.debug("Found [{}] matching uuids from [{}] chunks of patient " "[{}]".format(len(uuids), len(chunks), pat_id)) added_date = utils.get_db_friendly_date_time() if len(uuids) == 0: binary_uuid = utils.get_uuid_bin() hex_uuid = utils.hexlify(binary_uuid) log.debug("Generate [{}] for pat_id[{}]".format(pat_id, hex_uuid)) elif len(uuids) >= 1: hex_uuid = uuids.pop() binary_uuid = unhexlify(hex_uuid.encode('utf-8')) # after pop() the list with one item is empty if not uuids: log.debug("Reuse [{}] for pat_id[{}]".format(pat_id, hex_uuid)) else: log.warning("More than one uuid for chunks attributed to " "[{}] patient [{}]" .format(partner.partner_code, pat_id)) log.warning("\n==>chunks: {}\n==> uuids: {}" .format(chunks, uuids)) # update the response json result[pat_id] = {"uuid": hex_uuid} for i, chunk in enumerate(chunks): if chunks_cache.get(chunk): log.debug("Skip chunk [{}] - already linked".format(chunk)) continue # link every chunk to the same uuid binary_hash = unhexlify(chunk.encode('utf-8')) LinkageEntity.create( partner_id=partner.id, linkage_uuid=binary_uuid, linkage_hash=binary_hash, linkage_added_at=added_date) log.debug("Created link [{}] for [{}]".format(i, chunk)) return utils.jsonify_success(result)
#ifndef __FL_VALUATOR_C__ #define __FL_VALUATOR_C__ #ifdef __cplusplus // always include the FL/*.H headers before local headers // Fl_Valuator is included transitively and needed for // the callback mechanism included below to work. #include "FL/Fl.H" #include "FL/Fl_Valuator.H" #include "Fl_CallbackC.h" EXPORT { class Fl_DerivedValuator : public Fl_Valuator { fl_Valuator_Virtual_Funcs* overriddenFuncs; void* other_data; public: void* get_other_data(); void set_other_data(void*); void destroy_data(); void draw_box(); void draw_box(Fl_Boxtype t, Fl_Color c); void draw_box(Fl_Boxtype t, int x,int y,int w,int h, Fl_Color c); void draw_backdrop(); void draw_focus(); void draw_focus(Fl_Boxtype t, int x,int y,int w,int h); void draw_label(); void draw_label(int x,int y,int w,int h,Fl_Align alignment); virtual void draw(); virtual int handle(int event); void resize_super(int x, int y, int w, int h); virtual void resize(int x, int y, int w, int h); virtual void show(); virtual void hide(); virtual Fl_Window* as_window(); virtual Fl_Gl_Window* as_gl_window(); virtual int format(char* format); Fl_DerivedValuator(int X, int Y, int W, int H, const char *l, fl_Valuator_Virtual_Funcs* funcs); Fl_DerivedValuator(int X, int Y, int W, int H, fl_Valuator_Virtual_Funcs* funcs); ~Fl_DerivedValuator(); }; #endif #ifndef INTERNAL_LINKAGE typedef enum Valuator_Type { FL_VERTICALC = 0, FL_HORIZONTALC = 1 } Valuator_Type; #endif FL_EXPORT_C_HEADER(int,Fl_Valuator_handle,(fl_Widget self, int event)); FL_EXPORT_C_HEADER(int,Fl_Valuator_handle_super,(fl_Widget self, int event)); FL_EXPORT_C_HEADER(fl_Group,Fl_Valuator_parent,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_parent,(fl_Valuator valuator, fl_Group grp)); FL_EXPORT_C_HEADER(uchar,Fl_Valuator_type,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_type,(fl_Valuator valuator, uchar t)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_box,(fl_Valuator Valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_box_with_tc,(fl_Valuator Valuator,Fl_Boxtype t, Fl_Color c)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_box_with_txywhc,(fl_Valuator Valuator,Fl_Boxtype t, int x,int y,int w,int h, Fl_Color c)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_backdrop,(fl_Valuator Valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_focus,(fl_Valuator Valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_focus_with_txywh,(fl_Valuator Valuator,Fl_Boxtype t, int x,int y,int w,int h)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_label,(fl_Valuator Valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_x,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_y,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_w,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_h,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_align,(fl_Valuator valuator, Fl_Align alignment)); FL_EXPORT_C_HEADER(Fl_Align,Fl_Valuator_align,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(Fl_Boxtype,Fl_Valuator_box,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_box,(fl_Valuator valuator, Fl_Boxtype new_box)); FL_EXPORT_C_HEADER(Fl_Color,Fl_Valuator_color,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_color,(fl_Valuator valuator, Fl_Color bg)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_color_with_bg_sel,(fl_Valuator valuator,Fl_Color bg, Fl_Color a)); FL_EXPORT_C_HEADER(Fl_Color,Fl_Valuator_selection_color,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_selection_color,(fl_Valuator valuator, Fl_Color a)); FL_EXPORT_C_HEADER(const char*,Fl_Valuator_label,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_copy_label,(fl_Valuator valuator, const char* new_label)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_label,(fl_Valuator valuator, const char* text)); FL_EXPORT_C_HEADER(Fl_Labeltype,Fl_Valuator_labeltype,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_labeltype,(fl_Valuator valuator, Fl_Labeltype a)); FL_EXPORT_C_HEADER(Fl_Color,Fl_Valuator_labelcolor,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_labelcolor,(fl_Valuator valuator, Fl_Color c)); FL_EXPORT_C_HEADER(Fl_Font,Fl_Valuator_labelfont,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_labelfont,(fl_Valuator valuator, Fl_Font c)); FL_EXPORT_C_HEADER(Fl_Fontsize,Fl_Valuator_labelsize,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_labelsize,(fl_Valuator valuator, Fl_Fontsize pix)); FL_EXPORT_C_HEADER(fl_Image,Fl_Valuator_image,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_image,(fl_Valuator valuator, fl_Image pix)); FL_EXPORT_C_HEADER(fl_Image,Fl_Valuator_deimage,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_deimage,(fl_Valuator valuator, fl_Image pix)); FL_EXPORT_C_HEADER(const char*,Fl_Valuator_tooltip,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_copy_tooltip,(fl_Valuator valuator, const char* text)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_tooltip,(fl_Valuator valuator, const char* text)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_callback_with_user_data,(fl_Valuator valuator, fl_Callback* cb, void* p)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_callback,(fl_Valuator valuator, fl_Callback* cb)); FL_EXPORT_C_HEADER(void*,Fl_Valuator_other_data,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_other_data,(fl_Valuator valuator, void* v)); FL_EXPORT_C_HEADER(void*,Fl_Valuator_user_data,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_user_data,(fl_Valuator valuator, void* v)); FL_EXPORT_C_HEADER(long,Fl_Valuator_argument,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_argument,(fl_Valuator valuator, long v)); FL_EXPORT_C_HEADER(Fl_When,Fl_Valuator_when,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_when,(fl_Valuator valuator, uchar i)); FL_EXPORT_C_HEADER(unsigned int,Fl_Valuator_visible,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_visible_r,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_show_super,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_show,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_hide_super,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_hide,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_visible,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_visible,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(unsigned int,Fl_Valuator_active,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_active_r,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_activate,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_deactivate,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(unsigned int,Fl_Valuator_output,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_output,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_output,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(unsigned int,Fl_Valuator_takesevents,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_changed,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_changed,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_take_focus,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_visible_focus,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_visible_focus,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_modify_visible_focus,(fl_Valuator valuator, int v)); FL_EXPORT_C_HEADER(unsigned int,Fl_Valuator_visible_focus,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_contains,(fl_Valuator valuator, fl_Widget w)); FL_EXPORT_C_HEADER(int,Fl_Valuator_inside,(fl_Valuator valuator, fl_Widget w)); FL_EXPORT_C_HEADER(void,Fl_Valuator_redraw,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_redraw_label,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(uchar,Fl_Valuator_damage,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_damage_with_bitmask,(fl_Valuator valuator, uchar c)); FL_EXPORT_C_HEADER(void,Fl_Valuator_clear_damage,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_damage_with_text,(fl_Valuator valuator, uchar c)); FL_EXPORT_C_HEADER(void,Fl_Valuator_damage_inside_widget,(fl_Valuator valuator, uchar c, int x , int y , int w, int h)); FL_EXPORT_C_HEADER(void,Fl_Valuator_draw_label_with_xywh_alignment,(fl_Valuator valuator, int x , int y , int w, int h, Fl_Align alignment)); FL_EXPORT_C_HEADER(void,Fl_Valuator_measure_label,(fl_Valuator valuator, int* ww , int* hh)); FL_EXPORT_C_HEADER(fl_Window,Fl_Valuator_window,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(fl_Window,Fl_Valuator_top_window,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(fl_Window ,Fl_Valuator_top_window_offset,(fl_Valuator valuator, int* xoff, int* yoff)); FL_EXPORT_C_HEADER(fl_Gl_Window,Fl_Valuator_as_gl_window_super,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(fl_Gl_Window,Fl_Valuator_as_gl_window,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_resize_super,(fl_Table table,int X, int Y, int W, int H)); FL_EXPORT_C_HEADER(void,Fl_Valuator_resize,(fl_Table table,int X, int Y, int W, int H)); FL_EXPORT_C_HEADER(fl_Valuator_Virtual_Funcs*,Fl_Valuator_default_virtual_funcs,()); FL_EXPORT_C_HEADER(fl_Valuator,Fl_Valuator_New_WithLabel,(int x, int y, int w, int h, const char* label)); FL_EXPORT_C_HEADER(fl_Valuator,Fl_OverriddenValuator_New_WithLabel,(int x, int y, int w, int h, const char* label, fl_Valuator_Virtual_Funcs* funcs)); FL_EXPORT_C_HEADER(fl_Valuator ,Fl_Valuator_New,(int x, int y, int w, int h)); FL_EXPORT_C_HEADER(fl_Valuator ,Fl_OverriddenValuator_New,(int x, int y, int w, int h, fl_Valuator_Virtual_Funcs* funcs)); FL_EXPORT_C_HEADER(void,Fl_Valuator_Destroy,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_bounds,(fl_Valuator valuator, double a, double b)); FL_EXPORT_C_HEADER(double,Fl_Valuator_minimum,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_minimum,(fl_Valuator valuator, double a)); FL_EXPORT_C_HEADER(double,Fl_Valuator_maximum,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_maximum,(fl_Valuator valuator, double a)); FL_EXPORT_C_HEADER(void,Fl_Valuator_range,(fl_Valuator valuator, double a, double b)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_step,(fl_Valuator valuator, int a)); FL_EXPORT_C_HEADER(void,Fl_Valuator_set_step_with_a_b,(fl_Valuator valuator, double a, int b)); FL_EXPORT_C_HEADER(void,Fl_Valuator_step_with_s,(fl_Valuator valuator, double s)); FL_EXPORT_C_HEADER(double,Fl_Valuator_step,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(void,Fl_Valuator_precision,(fl_Valuator valuator, int precision)); FL_EXPORT_C_HEADER(double,Fl_Valuator_value,(fl_Valuator valuator)); FL_EXPORT_C_HEADER(int,Fl_Valuator_set_value,(fl_Valuator valuator, double v)); FL_EXPORT_C_HEADER(int,Fl_Valuator_format,(fl_Valuator valuator, char* format)); FL_EXPORT_C_HEADER(double,Fl_Valuator_round,(fl_Valuator valuator, double v)); FL_EXPORT_C_HEADER(double,Fl_Valuator_clamp,(fl_Valuator valuator, double v)); FL_EXPORT_C_HEADER(double,Fl_Valuator_increment,(fl_Valuator valuator, double v, int n)); #ifdef __cplusplus } #endif #endif /* __FL_VALUATOR_C__ */
// @flow import React, { Component } from 'react' import { Platform, Text, TouchableWithoutFeedback, View } from 'react-native' import { type LoginUserInfo } from '../../../common/actions/PreviousUsersActions.js' import s from '../../../common/locales/strings.js' import DeleteUserConnector from '../../../native/connectors/abSpecific/DeleteUserConnector' import PinKeypadConnector from '../../../native/connectors/abSpecific/PinKeypadConnector' import * as Assets from '../../assets/' import { LogoImageHeader, UserListItem } from '../../components/abSpecific' import { BackgroundImage, Button, DropDownList, HeaderParentButtons, ImageButton } from '../../components/common' import FourDigitConnector from '../../connectors/abSpecific/FourDigitConnector' type Props = { styles: Object, username: string, userDetails: Object, userList: Array<LoginUserInfo>, touch: boolean | string, loginSuccess: boolean, launchUserLoginWithTouchId(Object): void, changeUser(string): void, launchDeleteModal(): void, gotoLoginPage(): void, isTouchIdDisabled: boolean, appId?: string, backgroundImage?: any, primaryLogo?: any, primaryLogoCallback?: () => void, parentButton?: Object, showModal: boolean } type State = { loggingIn: boolean, pin: string, username: string, focusOn: string } export default class PinLogInScreenComponent extends Component<Props, State> { constructor(props: Props) { super(props) this.state = { pin: '', loggingIn: false, username: '', // User we are deleting focusOn: 'pin' } } componentDidMount() { if (this.props.username && this.props.touch !== 'FaceID') { this.props.launchUserLoginWithTouchId({ username: this.props.username }) } } relaunchTouchId = () => { this.props.launchUserLoginWithTouchId({ username: this.props.username }) } renderModal = (style: Object) => { if (this.props.showModal) { return ( <DeleteUserConnector style={style.modal.skip} username={this.state.username} /> ) } return null } render() { const { PinLoginScreenStyle } = this.props.styles return ( <View style={PinLoginScreenStyle.container}> <BackgroundImage src={this.props.backgroundImage || Assets.LOGIN_BACKGROUND} style={PinLoginScreenStyle.backgroundImage} content={this.renderOverImage()} /> </View> ) } renderOverImage() { const { PinLoginScreenStyle } = this.props.styles if (this.props.loginSuccess) { return null } return ( <View style={PinLoginScreenStyle.featureBoxContainer}> <HeaderParentButtons parentButton={{ text: s.strings.exit_pin, callback: this.exitPin.bind(this) }} styles={this.props.styles.HeaderParentButtons} appId={this.props.appId} /> <TouchableWithoutFeedback onPress={this.hideDrop.bind(this)}> <View style={PinLoginScreenStyle.featureBox}> <LogoImageHeader style={PinLoginScreenStyle.logoHeader} src={this.props.primaryLogo} callback={this.props.primaryLogoCallback} /> <View style={PinLoginScreenStyle.featureBoxBody}> {this.renderBottomHalf(PinLoginScreenStyle)} </View> {this.renderModal(PinLoginScreenStyle)} </View> </TouchableWithoutFeedback> <View style={PinLoginScreenStyle.spacer_full} /> {this.props.userDetails.pinEnabled && ( <PinKeypadConnector style={PinLoginScreenStyle.keypad} /> )} </View> ) } renderBottomHalf(style: Object) { if (this.state.focusOn === 'pin') { return ( <View style={style.innerView}> <Button onPress={this.showDrop.bind(this)} label={this.props.username} downStyle={style.usernameButton.downStyle} downTextStyle={style.usernameButton.downTextStyle} upStyle={style.usernameButton.upStyle} upTextStyle={style.usernameButton.upTextStyle} /> {this.props.userDetails.pinEnabled && ( <FourDigitConnector style={style.fourPin} /> )} {!this.props.userDetails.pinEnabled && <View style={style.spacer} />} {this.renderTouchImage()} <Text style={style.touchImageText}> {this.renderTouchImageText()} </Text> </View> ) } return ( <View style={style.innerView}> <DropDownList style={style.listView} data={this.getDropdownItems()} renderRow={this.renderItems.bind(this)} /> </View> ) } exitPin() { this.props.gotoLoginPage() } getDropdownItems(): string[] { const { userList, touch } = this.props return userList .filter(user => user.pinEnabled || (touch && user.touchEnabled)) .map(user => user.username) } renderItems(item: Object) { const { PinLoginScreenStyle } = this.props.styles return ( <UserListItem data={item.item} style={PinLoginScreenStyle.listItem} onClick={this.selectUser.bind(this)} onDelete={this.deleteUser.bind(this)} /> ) } deleteUser(arg: string) { this.setState({ focusOn: 'pin', username: arg }) this.props.launchDeleteModal() } selectUser(arg: string) { this.props.launchUserLoginWithTouchId({ username: arg }) this.props.changeUser(arg) this.setState({ focusOn: 'pin' }) } showDrop() { this.setState({ focusOn: 'List' }) } hideDrop() { this.setState({ focusOn: 'pin' }) } renderTouchImage = () => { const { touch, userDetails } = this.props const { touchEnabled } = userDetails if (touchEnabled && touch === 'FaceID') { return ( <ImageButton style={{}} source={Assets.FACE_ID} onPress={this.relaunchTouchId} disabled={this.props.isTouchIdDisabled} /> ) } if (touchEnabled && touch === 'TouchID') { return ( <ImageButton style={{}} source={Assets.TOUCH_ID} onPress={this.relaunchTouchId} disabled={this.props.isTouchIdDisabled} /> ) } if (!touchEnabled || !touch) { return null } return null } renderTouchImageText = () => { const { touch, userDetails } = this.props const { touchEnabled } = userDetails if (touchEnabled && touch === 'FaceID') { return s.strings.use_faceId } if (touchEnabled && touch === 'TouchID' && Platform.OS === 'ios') { return s.strings.use_touchId } if (touchEnabled && touch === 'TouchID' && Platform.OS !== 'ios') { return s.strings.use_fingerprint } return '' } }
import { makeExecutableSchema, addErrorLoggingToSchema } from 'graphql-tools' import { PubSub } from 'graphql-subscriptions' import log from '../../log' import schema from './schema_def.graphqls' export const pubsub = new PubSub(); const resolvers = { Query: { count(ignored1, ignored2, context) { return context.Count.getCount(); }, }, Mutation: { addCount(_, { amount }, context) { return context.Count.addCount(amount) .then(() => context.Count.getCount()) .then(count => { pubsub.publish('countUpdated', count); return count; }); }, }, Subscription: { countUpdated(amount) { return amount; } } }; const executableSchema = makeExecutableSchema({ typeDefs: schema, resolvers, }); addErrorLoggingToSchema(executableSchema, { log: (e) => log.error(e) }); export default executableSchema;
var about_btn = document.querySelector('#info_icon'); var about_modal = document.querySelector('#about_modal'); var close_modal_btn = document.querySelector('#close_modal_btn'); var mySwiper = null; var storyObj = null; var language = null; var audioElement = null; var audio_is_playing = false; //////////////////////////// fetch("./json/config.json") .then(function(res){ return (res.json()); }) .then(function(data) { language = data.language; get_story_json(language); }) ////////////////////////////////// function get_story_json(language){ var json_name = null; if (language == "en"){ json_name = "./json/story_en.json"; } else if (language == "heb"){ json_name = "./json/story_heb.json"; document.querySelector('#html_tag').lang="heb"; document.querySelector('#html_tag').dir ="rtl"; document.querySelector('#swiper_container').dir ="rtl"; } //Init only after language detected. mySwiper = new Swiper('.swiper-container'); init_tap_action(); fetch(json_name) .then(function(res){ return (res.json()); }) .then(function(data) { storyObj = data; load_pages(); }) } ////////////////////// function load_pages(){ var num_of_pages = storyObj.story.number_of_pages; for (var i=0;i<num_of_pages;i++){ var img_src = storyObj.story.pages[i].image_url; var img_alt = storyObj.story.pages[i].image_alt; var text = storyObj.story.pages[i].text; var str = '<div class="content_area">'; str += '<img src="' + img_src + '" alt="' + img_alt + '">'; str += '<div class="story_text">' + text + '</div>'; str += '</div></div>'; mySwiper.appendSlide('<div class="swiper-slide">' + str + '</div>'); } document.querySelector('#about_title').innerHTML = storyObj.story.about.title; document.querySelector('#about_description').innerHTML = storyObj.story.about.description; document.querySelector('#about_credits_title').innerHTML = storyObj.story.about.credits_title; document.querySelector('#about_credits_text').innerHTML = storyObj.story.about.credits_text; audioElement = new Audio(storyObj.story.pages[0].audio); } //////////////////////////////////////////////// about_btn.addEventListener('click', function(){ about_modal.classList.add('is-active'); }) ////////////////////////////////////////////////////// close_modal_btn.addEventListener('click', function(){ about_modal.classList.remove('is-active'); }) /////////////////////////// function init_tap_action(){ mySwiper.on('tap', function () { //note: check if called one on real mobile if (audioElement.paused) { console.log('audioElement') audioElement.play(); audio_is_playing = true; } else { audioElement.pause(); audio_is_playing = false; } }); }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/util/internal/testdata/timestamp_duration.proto #ifndef PROTOBUF_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto__INCLUDED #define PROTOBUF_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto__INCLUDED #include <string> #include <google/protobuf/stubs/common.h> #if GOOGLE_PROTOBUF_VERSION < 3001000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3001000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/timestamp.pb.h> #include <google/protobuf/duration.pb.h> // @@protoc_insertion_point(includes) namespace google { namespace protobuf { namespace testing { // Internal implementation detail -- do not call these. void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); class DurationType; class TimeStampType; class TimestampDuration; class TimestampDurationTestCases; // =================================================================== class TimestampDurationTestCases : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.testing.TimestampDurationTestCases) */ { public: TimestampDurationTestCases(); virtual ~TimestampDurationTestCases(); TimestampDurationTestCases(const TimestampDurationTestCases& from); inline TimestampDurationTestCases& operator=(const TimestampDurationTestCases& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const TimestampDurationTestCases& default_instance(); static const TimestampDurationTestCases* internal_default_instance(); void Swap(TimestampDurationTestCases* other); // implements Message ---------------------------------------------- inline TimestampDurationTestCases* New() const { return New(NULL); } TimestampDurationTestCases* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const TimestampDurationTestCases& from); void MergeFrom(const TimestampDurationTestCases& from); void Clear(); bool IsInitialized() const; size_t ByteSizeLong() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(TimestampDurationTestCases* other); void UnsafeMergeFrom(const TimestampDurationTestCases& from); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .google.protobuf.testing.TimeStampType epoch = 1; bool has_epoch() const; void clear_epoch(); static const int kEpochFieldNumber = 1; const ::google::protobuf::testing::TimeStampType& epoch() const; ::google::protobuf::testing::TimeStampType* mutable_epoch(); ::google::protobuf::testing::TimeStampType* release_epoch(); void set_allocated_epoch(::google::protobuf::testing::TimeStampType* epoch); // optional .google.protobuf.testing.TimeStampType epoch2 = 2; bool has_epoch2() const; void clear_epoch2(); static const int kEpoch2FieldNumber = 2; const ::google::protobuf::testing::TimeStampType& epoch2() const; ::google::protobuf::testing::TimeStampType* mutable_epoch2(); ::google::protobuf::testing::TimeStampType* release_epoch2(); void set_allocated_epoch2(::google::protobuf::testing::TimeStampType* epoch2); // optional .google.protobuf.testing.TimeStampType mintime = 3; bool has_mintime() const; void clear_mintime(); static const int kMintimeFieldNumber = 3; const ::google::protobuf::testing::TimeStampType& mintime() const; ::google::protobuf::testing::TimeStampType* mutable_mintime(); ::google::protobuf::testing::TimeStampType* release_mintime(); void set_allocated_mintime(::google::protobuf::testing::TimeStampType* mintime); // optional .google.protobuf.testing.TimeStampType maxtime = 4; bool has_maxtime() const; void clear_maxtime(); static const int kMaxtimeFieldNumber = 4; const ::google::protobuf::testing::TimeStampType& maxtime() const; ::google::protobuf::testing::TimeStampType* mutable_maxtime(); ::google::protobuf::testing::TimeStampType* release_maxtime(); void set_allocated_maxtime(::google::protobuf::testing::TimeStampType* maxtime); // optional .google.protobuf.testing.TimeStampType timeval1 = 5; bool has_timeval1() const; void clear_timeval1(); static const int kTimeval1FieldNumber = 5; const ::google::protobuf::testing::TimeStampType& timeval1() const; ::google::protobuf::testing::TimeStampType* mutable_timeval1(); ::google::protobuf::testing::TimeStampType* release_timeval1(); void set_allocated_timeval1(::google::protobuf::testing::TimeStampType* timeval1); // optional .google.protobuf.testing.TimeStampType timeval2 = 6; bool has_timeval2() const; void clear_timeval2(); static const int kTimeval2FieldNumber = 6; const ::google::protobuf::testing::TimeStampType& timeval2() const; ::google::protobuf::testing::TimeStampType* mutable_timeval2(); ::google::protobuf::testing::TimeStampType* release_timeval2(); void set_allocated_timeval2(::google::protobuf::testing::TimeStampType* timeval2); // optional .google.protobuf.testing.TimeStampType timeval3 = 7; bool has_timeval3() const; void clear_timeval3(); static const int kTimeval3FieldNumber = 7; const ::google::protobuf::testing::TimeStampType& timeval3() const; ::google::protobuf::testing::TimeStampType* mutable_timeval3(); ::google::protobuf::testing::TimeStampType* release_timeval3(); void set_allocated_timeval3(::google::protobuf::testing::TimeStampType* timeval3); // optional .google.protobuf.testing.TimeStampType timeval4 = 8; bool has_timeval4() const; void clear_timeval4(); static const int kTimeval4FieldNumber = 8; const ::google::protobuf::testing::TimeStampType& timeval4() const; ::google::protobuf::testing::TimeStampType* mutable_timeval4(); ::google::protobuf::testing::TimeStampType* release_timeval4(); void set_allocated_timeval4(::google::protobuf::testing::TimeStampType* timeval4); // optional .google.protobuf.testing.TimeStampType timeval5 = 9; bool has_timeval5() const; void clear_timeval5(); static const int kTimeval5FieldNumber = 9; const ::google::protobuf::testing::TimeStampType& timeval5() const; ::google::protobuf::testing::TimeStampType* mutable_timeval5(); ::google::protobuf::testing::TimeStampType* release_timeval5(); void set_allocated_timeval5(::google::protobuf::testing::TimeStampType* timeval5); // optional .google.protobuf.testing.TimeStampType timeval6 = 10; bool has_timeval6() const; void clear_timeval6(); static const int kTimeval6FieldNumber = 10; const ::google::protobuf::testing::TimeStampType& timeval6() const; ::google::protobuf::testing::TimeStampType* mutable_timeval6(); ::google::protobuf::testing::TimeStampType* release_timeval6(); void set_allocated_timeval6(::google::protobuf::testing::TimeStampType* timeval6); // optional .google.protobuf.testing.TimeStampType timeval7 = 11; bool has_timeval7() const; void clear_timeval7(); static const int kTimeval7FieldNumber = 11; const ::google::protobuf::testing::TimeStampType& timeval7() const; ::google::protobuf::testing::TimeStampType* mutable_timeval7(); ::google::protobuf::testing::TimeStampType* release_timeval7(); void set_allocated_timeval7(::google::protobuf::testing::TimeStampType* timeval7); // optional .google.protobuf.Timestamp timeval8 = 12; bool has_timeval8() const; void clear_timeval8(); static const int kTimeval8FieldNumber = 12; const ::google::protobuf::Timestamp& timeval8() const; ::google::protobuf::Timestamp* mutable_timeval8(); ::google::protobuf::Timestamp* release_timeval8(); void set_allocated_timeval8(::google::protobuf::Timestamp* timeval8); // optional .google.protobuf.testing.DurationType zero_duration = 101; bool has_zero_duration() const; void clear_zero_duration(); static const int kZeroDurationFieldNumber = 101; const ::google::protobuf::testing::DurationType& zero_duration() const; ::google::protobuf::testing::DurationType* mutable_zero_duration(); ::google::protobuf::testing::DurationType* release_zero_duration(); void set_allocated_zero_duration(::google::protobuf::testing::DurationType* zero_duration); // optional .google.protobuf.testing.DurationType min_duration = 102; bool has_min_duration() const; void clear_min_duration(); static const int kMinDurationFieldNumber = 102; const ::google::protobuf::testing::DurationType& min_duration() const; ::google::protobuf::testing::DurationType* mutable_min_duration(); ::google::protobuf::testing::DurationType* release_min_duration(); void set_allocated_min_duration(::google::protobuf::testing::DurationType* min_duration); // optional .google.protobuf.testing.DurationType max_duration = 103; bool has_max_duration() const; void clear_max_duration(); static const int kMaxDurationFieldNumber = 103; const ::google::protobuf::testing::DurationType& max_duration() const; ::google::protobuf::testing::DurationType* mutable_max_duration(); ::google::protobuf::testing::DurationType* release_max_duration(); void set_allocated_max_duration(::google::protobuf::testing::DurationType* max_duration); // optional .google.protobuf.testing.DurationType duration1 = 104; bool has_duration1() const; void clear_duration1(); static const int kDuration1FieldNumber = 104; const ::google::protobuf::testing::DurationType& duration1() const; ::google::protobuf::testing::DurationType* mutable_duration1(); ::google::protobuf::testing::DurationType* release_duration1(); void set_allocated_duration1(::google::protobuf::testing::DurationType* duration1); // optional .google.protobuf.testing.DurationType duration2 = 105; bool has_duration2() const; void clear_duration2(); static const int kDuration2FieldNumber = 105; const ::google::protobuf::testing::DurationType& duration2() const; ::google::protobuf::testing::DurationType* mutable_duration2(); ::google::protobuf::testing::DurationType* release_duration2(); void set_allocated_duration2(::google::protobuf::testing::DurationType* duration2); // optional .google.protobuf.testing.DurationType duration3 = 106; bool has_duration3() const; void clear_duration3(); static const int kDuration3FieldNumber = 106; const ::google::protobuf::testing::DurationType& duration3() const; ::google::protobuf::testing::DurationType* mutable_duration3(); ::google::protobuf::testing::DurationType* release_duration3(); void set_allocated_duration3(::google::protobuf::testing::DurationType* duration3); // optional .google.protobuf.testing.DurationType duration4 = 107; bool has_duration4() const; void clear_duration4(); static const int kDuration4FieldNumber = 107; const ::google::protobuf::testing::DurationType& duration4() const; ::google::protobuf::testing::DurationType* mutable_duration4(); ::google::protobuf::testing::DurationType* release_duration4(); void set_allocated_duration4(::google::protobuf::testing::DurationType* duration4); // optional .google.protobuf.Duration duration5 = 108; bool has_duration5() const; void clear_duration5(); static const int kDuration5FieldNumber = 108; const ::google::protobuf::Duration& duration5() const; ::google::protobuf::Duration* mutable_duration5(); ::google::protobuf::Duration* release_duration5(); void set_allocated_duration5(::google::protobuf::Duration* duration5); // @@protoc_insertion_point(class_scope:google.protobuf.testing.TimestampDurationTestCases) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::testing::TimeStampType* epoch_; ::google::protobuf::testing::TimeStampType* epoch2_; ::google::protobuf::testing::TimeStampType* mintime_; ::google::protobuf::testing::TimeStampType* maxtime_; ::google::protobuf::testing::TimeStampType* timeval1_; ::google::protobuf::testing::TimeStampType* timeval2_; ::google::protobuf::testing::TimeStampType* timeval3_; ::google::protobuf::testing::TimeStampType* timeval4_; ::google::protobuf::testing::TimeStampType* timeval5_; ::google::protobuf::testing::TimeStampType* timeval6_; ::google::protobuf::testing::TimeStampType* timeval7_; ::google::protobuf::Timestamp* timeval8_; ::google::protobuf::testing::DurationType* zero_duration_; ::google::protobuf::testing::DurationType* min_duration_; ::google::protobuf::testing::DurationType* max_duration_; ::google::protobuf::testing::DurationType* duration1_; ::google::protobuf::testing::DurationType* duration2_; ::google::protobuf::testing::DurationType* duration3_; ::google::protobuf::testing::DurationType* duration4_; ::google::protobuf::Duration* duration5_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void InitAsDefaultInstance(); }; extern ::google::protobuf::internal::ExplicitlyConstructed<TimestampDurationTestCases> TimestampDurationTestCases_default_instance_; // ------------------------------------------------------------------- class TimeStampType : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.testing.TimeStampType) */ { public: TimeStampType(); virtual ~TimeStampType(); TimeStampType(const TimeStampType& from); inline TimeStampType& operator=(const TimeStampType& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const TimeStampType& default_instance(); static const TimeStampType* internal_default_instance(); void Swap(TimeStampType* other); // implements Message ---------------------------------------------- inline TimeStampType* New() const { return New(NULL); } TimeStampType* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const TimeStampType& from); void MergeFrom(const TimeStampType& from); void Clear(); bool IsInitialized() const; size_t ByteSizeLong() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(TimeStampType* other); void UnsafeMergeFrom(const TimeStampType& from); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .google.protobuf.Timestamp timestamp = 1; bool has_timestamp() const; void clear_timestamp(); static const int kTimestampFieldNumber = 1; const ::google::protobuf::Timestamp& timestamp() const; ::google::protobuf::Timestamp* mutable_timestamp(); ::google::protobuf::Timestamp* release_timestamp(); void set_allocated_timestamp(::google::protobuf::Timestamp* timestamp); // @@protoc_insertion_point(class_scope:google.protobuf.testing.TimeStampType) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::Timestamp* timestamp_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void InitAsDefaultInstance(); }; extern ::google::protobuf::internal::ExplicitlyConstructed<TimeStampType> TimeStampType_default_instance_; // ------------------------------------------------------------------- class DurationType : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.testing.DurationType) */ { public: DurationType(); virtual ~DurationType(); DurationType(const DurationType& from); inline DurationType& operator=(const DurationType& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const DurationType& default_instance(); static const DurationType* internal_default_instance(); void Swap(DurationType* other); // implements Message ---------------------------------------------- inline DurationType* New() const { return New(NULL); } DurationType* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const DurationType& from); void MergeFrom(const DurationType& from); void Clear(); bool IsInitialized() const; size_t ByteSizeLong() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(DurationType* other); void UnsafeMergeFrom(const DurationType& from); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .google.protobuf.Duration duration = 1; bool has_duration() const; void clear_duration(); static const int kDurationFieldNumber = 1; const ::google::protobuf::Duration& duration() const; ::google::protobuf::Duration* mutable_duration(); ::google::protobuf::Duration* release_duration(); void set_allocated_duration(::google::protobuf::Duration* duration); // @@protoc_insertion_point(class_scope:google.protobuf.testing.DurationType) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::Duration* duration_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void InitAsDefaultInstance(); }; extern ::google::protobuf::internal::ExplicitlyConstructed<DurationType> DurationType_default_instance_; // ------------------------------------------------------------------- class TimestampDuration : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:google.protobuf.testing.TimestampDuration) */ { public: TimestampDuration(); virtual ~TimestampDuration(); TimestampDuration(const TimestampDuration& from); inline TimestampDuration& operator=(const TimestampDuration& from) { CopyFrom(from); return *this; } static const ::google::protobuf::Descriptor* descriptor(); static const TimestampDuration& default_instance(); static const TimestampDuration* internal_default_instance(); void Swap(TimestampDuration* other); // implements Message ---------------------------------------------- inline TimestampDuration* New() const { return New(NULL); } TimestampDuration* New(::google::protobuf::Arena* arena) const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const TimestampDuration& from); void MergeFrom(const TimestampDuration& from); void Clear(); bool IsInitialized() const; size_t ByteSizeLong() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const { return InternalSerializeWithCachedSizesToArray(false, output); } int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; void InternalSwap(TimestampDuration* other); void UnsafeMergeFrom(const TimestampDuration& from); private: inline ::google::protobuf::Arena* GetArenaNoVirtual() const { return _internal_metadata_.arena(); } inline void* MaybeArenaPtr() const { return _internal_metadata_.raw_arena_ptr(); } public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional .google.protobuf.Timestamp ts = 1; bool has_ts() const; void clear_ts(); static const int kTsFieldNumber = 1; const ::google::protobuf::Timestamp& ts() const; ::google::protobuf::Timestamp* mutable_ts(); ::google::protobuf::Timestamp* release_ts(); void set_allocated_ts(::google::protobuf::Timestamp* ts); // optional .google.protobuf.Duration dur = 2; bool has_dur() const; void clear_dur(); static const int kDurFieldNumber = 2; const ::google::protobuf::Duration& dur() const; ::google::protobuf::Duration* mutable_dur(); ::google::protobuf::Duration* release_dur(); void set_allocated_dur(::google::protobuf::Duration* dur); // repeated .google.protobuf.Timestamp rep_ts = 3; int rep_ts_size() const; void clear_rep_ts(); static const int kRepTsFieldNumber = 3; const ::google::protobuf::Timestamp& rep_ts(int index) const; ::google::protobuf::Timestamp* mutable_rep_ts(int index); ::google::protobuf::Timestamp* add_rep_ts(); ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >* mutable_rep_ts(); const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >& rep_ts() const; // @@protoc_insertion_point(class_scope:google.protobuf.testing.TimestampDuration) private: ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_; ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp > rep_ts_; ::google::protobuf::Timestamp* ts_; ::google::protobuf::Duration* dur_; mutable int _cached_size_; friend void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto_impl(); friend void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); friend void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto(); void InitAsDefaultInstance(); }; extern ::google::protobuf::internal::ExplicitlyConstructed<TimestampDuration> TimestampDuration_default_instance_; // =================================================================== // =================================================================== #if !PROTOBUF_INLINE_NOT_IN_HEADERS // TimestampDurationTestCases // optional .google.protobuf.testing.TimeStampType epoch = 1; inline bool TimestampDurationTestCases::has_epoch() const { return this != internal_default_instance() && epoch_ != NULL; } inline void TimestampDurationTestCases::clear_epoch() { if (GetArenaNoVirtual() == NULL && epoch_ != NULL) delete epoch_; epoch_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::epoch() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.epoch) return epoch_ != NULL ? *epoch_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_epoch() { if (epoch_ == NULL) { epoch_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.epoch) return epoch_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_epoch() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.epoch) ::google::protobuf::testing::TimeStampType* temp = epoch_; epoch_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_epoch(::google::protobuf::testing::TimeStampType* epoch) { delete epoch_; epoch_ = epoch; if (epoch) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.epoch) } // optional .google.protobuf.testing.TimeStampType epoch2 = 2; inline bool TimestampDurationTestCases::has_epoch2() const { return this != internal_default_instance() && epoch2_ != NULL; } inline void TimestampDurationTestCases::clear_epoch2() { if (GetArenaNoVirtual() == NULL && epoch2_ != NULL) delete epoch2_; epoch2_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::epoch2() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.epoch2) return epoch2_ != NULL ? *epoch2_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_epoch2() { if (epoch2_ == NULL) { epoch2_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.epoch2) return epoch2_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_epoch2() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.epoch2) ::google::protobuf::testing::TimeStampType* temp = epoch2_; epoch2_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_epoch2(::google::protobuf::testing::TimeStampType* epoch2) { delete epoch2_; epoch2_ = epoch2; if (epoch2) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.epoch2) } // optional .google.protobuf.testing.TimeStampType mintime = 3; inline bool TimestampDurationTestCases::has_mintime() const { return this != internal_default_instance() && mintime_ != NULL; } inline void TimestampDurationTestCases::clear_mintime() { if (GetArenaNoVirtual() == NULL && mintime_ != NULL) delete mintime_; mintime_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::mintime() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.mintime) return mintime_ != NULL ? *mintime_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_mintime() { if (mintime_ == NULL) { mintime_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.mintime) return mintime_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_mintime() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.mintime) ::google::protobuf::testing::TimeStampType* temp = mintime_; mintime_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_mintime(::google::protobuf::testing::TimeStampType* mintime) { delete mintime_; mintime_ = mintime; if (mintime) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.mintime) } // optional .google.protobuf.testing.TimeStampType maxtime = 4; inline bool TimestampDurationTestCases::has_maxtime() const { return this != internal_default_instance() && maxtime_ != NULL; } inline void TimestampDurationTestCases::clear_maxtime() { if (GetArenaNoVirtual() == NULL && maxtime_ != NULL) delete maxtime_; maxtime_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::maxtime() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.maxtime) return maxtime_ != NULL ? *maxtime_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_maxtime() { if (maxtime_ == NULL) { maxtime_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.maxtime) return maxtime_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_maxtime() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.maxtime) ::google::protobuf::testing::TimeStampType* temp = maxtime_; maxtime_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_maxtime(::google::protobuf::testing::TimeStampType* maxtime) { delete maxtime_; maxtime_ = maxtime; if (maxtime) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.maxtime) } // optional .google.protobuf.testing.TimeStampType timeval1 = 5; inline bool TimestampDurationTestCases::has_timeval1() const { return this != internal_default_instance() && timeval1_ != NULL; } inline void TimestampDurationTestCases::clear_timeval1() { if (GetArenaNoVirtual() == NULL && timeval1_ != NULL) delete timeval1_; timeval1_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval1() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval1) return timeval1_ != NULL ? *timeval1_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval1() { if (timeval1_ == NULL) { timeval1_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval1) return timeval1_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval1() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval1) ::google::protobuf::testing::TimeStampType* temp = timeval1_; timeval1_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval1(::google::protobuf::testing::TimeStampType* timeval1) { delete timeval1_; timeval1_ = timeval1; if (timeval1) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval1) } // optional .google.protobuf.testing.TimeStampType timeval2 = 6; inline bool TimestampDurationTestCases::has_timeval2() const { return this != internal_default_instance() && timeval2_ != NULL; } inline void TimestampDurationTestCases::clear_timeval2() { if (GetArenaNoVirtual() == NULL && timeval2_ != NULL) delete timeval2_; timeval2_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval2() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval2) return timeval2_ != NULL ? *timeval2_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval2() { if (timeval2_ == NULL) { timeval2_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval2) return timeval2_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval2() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval2) ::google::protobuf::testing::TimeStampType* temp = timeval2_; timeval2_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval2(::google::protobuf::testing::TimeStampType* timeval2) { delete timeval2_; timeval2_ = timeval2; if (timeval2) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval2) } // optional .google.protobuf.testing.TimeStampType timeval3 = 7; inline bool TimestampDurationTestCases::has_timeval3() const { return this != internal_default_instance() && timeval3_ != NULL; } inline void TimestampDurationTestCases::clear_timeval3() { if (GetArenaNoVirtual() == NULL && timeval3_ != NULL) delete timeval3_; timeval3_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval3() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval3) return timeval3_ != NULL ? *timeval3_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval3() { if (timeval3_ == NULL) { timeval3_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval3) return timeval3_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval3() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval3) ::google::protobuf::testing::TimeStampType* temp = timeval3_; timeval3_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval3(::google::protobuf::testing::TimeStampType* timeval3) { delete timeval3_; timeval3_ = timeval3; if (timeval3) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval3) } // optional .google.protobuf.testing.TimeStampType timeval4 = 8; inline bool TimestampDurationTestCases::has_timeval4() const { return this != internal_default_instance() && timeval4_ != NULL; } inline void TimestampDurationTestCases::clear_timeval4() { if (GetArenaNoVirtual() == NULL && timeval4_ != NULL) delete timeval4_; timeval4_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval4() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval4) return timeval4_ != NULL ? *timeval4_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval4() { if (timeval4_ == NULL) { timeval4_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval4) return timeval4_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval4() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval4) ::google::protobuf::testing::TimeStampType* temp = timeval4_; timeval4_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval4(::google::protobuf::testing::TimeStampType* timeval4) { delete timeval4_; timeval4_ = timeval4; if (timeval4) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval4) } // optional .google.protobuf.testing.TimeStampType timeval5 = 9; inline bool TimestampDurationTestCases::has_timeval5() const { return this != internal_default_instance() && timeval5_ != NULL; } inline void TimestampDurationTestCases::clear_timeval5() { if (GetArenaNoVirtual() == NULL && timeval5_ != NULL) delete timeval5_; timeval5_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval5() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval5) return timeval5_ != NULL ? *timeval5_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval5() { if (timeval5_ == NULL) { timeval5_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval5) return timeval5_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval5() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval5) ::google::protobuf::testing::TimeStampType* temp = timeval5_; timeval5_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval5(::google::protobuf::testing::TimeStampType* timeval5) { delete timeval5_; timeval5_ = timeval5; if (timeval5) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval5) } // optional .google.protobuf.testing.TimeStampType timeval6 = 10; inline bool TimestampDurationTestCases::has_timeval6() const { return this != internal_default_instance() && timeval6_ != NULL; } inline void TimestampDurationTestCases::clear_timeval6() { if (GetArenaNoVirtual() == NULL && timeval6_ != NULL) delete timeval6_; timeval6_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval6() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval6) return timeval6_ != NULL ? *timeval6_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval6() { if (timeval6_ == NULL) { timeval6_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval6) return timeval6_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval6() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval6) ::google::protobuf::testing::TimeStampType* temp = timeval6_; timeval6_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval6(::google::protobuf::testing::TimeStampType* timeval6) { delete timeval6_; timeval6_ = timeval6; if (timeval6) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval6) } // optional .google.protobuf.testing.TimeStampType timeval7 = 11; inline bool TimestampDurationTestCases::has_timeval7() const { return this != internal_default_instance() && timeval7_ != NULL; } inline void TimestampDurationTestCases::clear_timeval7() { if (GetArenaNoVirtual() == NULL && timeval7_ != NULL) delete timeval7_; timeval7_ = NULL; } inline const ::google::protobuf::testing::TimeStampType& TimestampDurationTestCases::timeval7() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval7) return timeval7_ != NULL ? *timeval7_ : *::google::protobuf::testing::TimeStampType::internal_default_instance(); } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::mutable_timeval7() { if (timeval7_ == NULL) { timeval7_ = new ::google::protobuf::testing::TimeStampType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval7) return timeval7_; } inline ::google::protobuf::testing::TimeStampType* TimestampDurationTestCases::release_timeval7() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval7) ::google::protobuf::testing::TimeStampType* temp = timeval7_; timeval7_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval7(::google::protobuf::testing::TimeStampType* timeval7) { delete timeval7_; timeval7_ = timeval7; if (timeval7) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval7) } // optional .google.protobuf.Timestamp timeval8 = 12; inline bool TimestampDurationTestCases::has_timeval8() const { return this != internal_default_instance() && timeval8_ != NULL; } inline void TimestampDurationTestCases::clear_timeval8() { if (GetArenaNoVirtual() == NULL && timeval8_ != NULL) delete timeval8_; timeval8_ = NULL; } inline const ::google::protobuf::Timestamp& TimestampDurationTestCases::timeval8() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.timeval8) return timeval8_ != NULL ? *timeval8_ : *::google::protobuf::Timestamp::internal_default_instance(); } inline ::google::protobuf::Timestamp* TimestampDurationTestCases::mutable_timeval8() { if (timeval8_ == NULL) { timeval8_ = new ::google::protobuf::Timestamp; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.timeval8) return timeval8_; } inline ::google::protobuf::Timestamp* TimestampDurationTestCases::release_timeval8() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.timeval8) ::google::protobuf::Timestamp* temp = timeval8_; timeval8_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_timeval8(::google::protobuf::Timestamp* timeval8) { delete timeval8_; if (timeval8 != NULL && timeval8->GetArena() != NULL) { ::google::protobuf::Timestamp* new_timeval8 = new ::google::protobuf::Timestamp; new_timeval8->CopyFrom(*timeval8); timeval8 = new_timeval8; } timeval8_ = timeval8; if (timeval8) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.timeval8) } // optional .google.protobuf.testing.DurationType zero_duration = 101; inline bool TimestampDurationTestCases::has_zero_duration() const { return this != internal_default_instance() && zero_duration_ != NULL; } inline void TimestampDurationTestCases::clear_zero_duration() { if (GetArenaNoVirtual() == NULL && zero_duration_ != NULL) delete zero_duration_; zero_duration_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::zero_duration() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.zero_duration) return zero_duration_ != NULL ? *zero_duration_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_zero_duration() { if (zero_duration_ == NULL) { zero_duration_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.zero_duration) return zero_duration_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_zero_duration() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.zero_duration) ::google::protobuf::testing::DurationType* temp = zero_duration_; zero_duration_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_zero_duration(::google::protobuf::testing::DurationType* zero_duration) { delete zero_duration_; zero_duration_ = zero_duration; if (zero_duration) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.zero_duration) } // optional .google.protobuf.testing.DurationType min_duration = 102; inline bool TimestampDurationTestCases::has_min_duration() const { return this != internal_default_instance() && min_duration_ != NULL; } inline void TimestampDurationTestCases::clear_min_duration() { if (GetArenaNoVirtual() == NULL && min_duration_ != NULL) delete min_duration_; min_duration_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::min_duration() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.min_duration) return min_duration_ != NULL ? *min_duration_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_min_duration() { if (min_duration_ == NULL) { min_duration_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.min_duration) return min_duration_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_min_duration() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.min_duration) ::google::protobuf::testing::DurationType* temp = min_duration_; min_duration_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_min_duration(::google::protobuf::testing::DurationType* min_duration) { delete min_duration_; min_duration_ = min_duration; if (min_duration) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.min_duration) } // optional .google.protobuf.testing.DurationType max_duration = 103; inline bool TimestampDurationTestCases::has_max_duration() const { return this != internal_default_instance() && max_duration_ != NULL; } inline void TimestampDurationTestCases::clear_max_duration() { if (GetArenaNoVirtual() == NULL && max_duration_ != NULL) delete max_duration_; max_duration_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::max_duration() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.max_duration) return max_duration_ != NULL ? *max_duration_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_max_duration() { if (max_duration_ == NULL) { max_duration_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.max_duration) return max_duration_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_max_duration() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.max_duration) ::google::protobuf::testing::DurationType* temp = max_duration_; max_duration_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_max_duration(::google::protobuf::testing::DurationType* max_duration) { delete max_duration_; max_duration_ = max_duration; if (max_duration) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.max_duration) } // optional .google.protobuf.testing.DurationType duration1 = 104; inline bool TimestampDurationTestCases::has_duration1() const { return this != internal_default_instance() && duration1_ != NULL; } inline void TimestampDurationTestCases::clear_duration1() { if (GetArenaNoVirtual() == NULL && duration1_ != NULL) delete duration1_; duration1_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::duration1() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.duration1) return duration1_ != NULL ? *duration1_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_duration1() { if (duration1_ == NULL) { duration1_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.duration1) return duration1_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_duration1() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.duration1) ::google::protobuf::testing::DurationType* temp = duration1_; duration1_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_duration1(::google::protobuf::testing::DurationType* duration1) { delete duration1_; duration1_ = duration1; if (duration1) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.duration1) } // optional .google.protobuf.testing.DurationType duration2 = 105; inline bool TimestampDurationTestCases::has_duration2() const { return this != internal_default_instance() && duration2_ != NULL; } inline void TimestampDurationTestCases::clear_duration2() { if (GetArenaNoVirtual() == NULL && duration2_ != NULL) delete duration2_; duration2_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::duration2() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.duration2) return duration2_ != NULL ? *duration2_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_duration2() { if (duration2_ == NULL) { duration2_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.duration2) return duration2_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_duration2() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.duration2) ::google::protobuf::testing::DurationType* temp = duration2_; duration2_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_duration2(::google::protobuf::testing::DurationType* duration2) { delete duration2_; duration2_ = duration2; if (duration2) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.duration2) } // optional .google.protobuf.testing.DurationType duration3 = 106; inline bool TimestampDurationTestCases::has_duration3() const { return this != internal_default_instance() && duration3_ != NULL; } inline void TimestampDurationTestCases::clear_duration3() { if (GetArenaNoVirtual() == NULL && duration3_ != NULL) delete duration3_; duration3_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::duration3() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.duration3) return duration3_ != NULL ? *duration3_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_duration3() { if (duration3_ == NULL) { duration3_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.duration3) return duration3_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_duration3() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.duration3) ::google::protobuf::testing::DurationType* temp = duration3_; duration3_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_duration3(::google::protobuf::testing::DurationType* duration3) { delete duration3_; duration3_ = duration3; if (duration3) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.duration3) } // optional .google.protobuf.testing.DurationType duration4 = 107; inline bool TimestampDurationTestCases::has_duration4() const { return this != internal_default_instance() && duration4_ != NULL; } inline void TimestampDurationTestCases::clear_duration4() { if (GetArenaNoVirtual() == NULL && duration4_ != NULL) delete duration4_; duration4_ = NULL; } inline const ::google::protobuf::testing::DurationType& TimestampDurationTestCases::duration4() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.duration4) return duration4_ != NULL ? *duration4_ : *::google::protobuf::testing::DurationType::internal_default_instance(); } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::mutable_duration4() { if (duration4_ == NULL) { duration4_ = new ::google::protobuf::testing::DurationType; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.duration4) return duration4_; } inline ::google::protobuf::testing::DurationType* TimestampDurationTestCases::release_duration4() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.duration4) ::google::protobuf::testing::DurationType* temp = duration4_; duration4_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_duration4(::google::protobuf::testing::DurationType* duration4) { delete duration4_; duration4_ = duration4; if (duration4) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.duration4) } // optional .google.protobuf.Duration duration5 = 108; inline bool TimestampDurationTestCases::has_duration5() const { return this != internal_default_instance() && duration5_ != NULL; } inline void TimestampDurationTestCases::clear_duration5() { if (GetArenaNoVirtual() == NULL && duration5_ != NULL) delete duration5_; duration5_ = NULL; } inline const ::google::protobuf::Duration& TimestampDurationTestCases::duration5() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDurationTestCases.duration5) return duration5_ != NULL ? *duration5_ : *::google::protobuf::Duration::internal_default_instance(); } inline ::google::protobuf::Duration* TimestampDurationTestCases::mutable_duration5() { if (duration5_ == NULL) { duration5_ = new ::google::protobuf::Duration; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDurationTestCases.duration5) return duration5_; } inline ::google::protobuf::Duration* TimestampDurationTestCases::release_duration5() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDurationTestCases.duration5) ::google::protobuf::Duration* temp = duration5_; duration5_ = NULL; return temp; } inline void TimestampDurationTestCases::set_allocated_duration5(::google::protobuf::Duration* duration5) { delete duration5_; if (duration5 != NULL && duration5->GetArena() != NULL) { ::google::protobuf::Duration* new_duration5 = new ::google::protobuf::Duration; new_duration5->CopyFrom(*duration5); duration5 = new_duration5; } duration5_ = duration5; if (duration5) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDurationTestCases.duration5) } inline const TimestampDurationTestCases* TimestampDurationTestCases::internal_default_instance() { return &TimestampDurationTestCases_default_instance_.get(); } // ------------------------------------------------------------------- // TimeStampType // optional .google.protobuf.Timestamp timestamp = 1; inline bool TimeStampType::has_timestamp() const { return this != internal_default_instance() && timestamp_ != NULL; } inline void TimeStampType::clear_timestamp() { if (GetArenaNoVirtual() == NULL && timestamp_ != NULL) delete timestamp_; timestamp_ = NULL; } inline const ::google::protobuf::Timestamp& TimeStampType::timestamp() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimeStampType.timestamp) return timestamp_ != NULL ? *timestamp_ : *::google::protobuf::Timestamp::internal_default_instance(); } inline ::google::protobuf::Timestamp* TimeStampType::mutable_timestamp() { if (timestamp_ == NULL) { timestamp_ = new ::google::protobuf::Timestamp; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimeStampType.timestamp) return timestamp_; } inline ::google::protobuf::Timestamp* TimeStampType::release_timestamp() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimeStampType.timestamp) ::google::protobuf::Timestamp* temp = timestamp_; timestamp_ = NULL; return temp; } inline void TimeStampType::set_allocated_timestamp(::google::protobuf::Timestamp* timestamp) { delete timestamp_; if (timestamp != NULL && timestamp->GetArena() != NULL) { ::google::protobuf::Timestamp* new_timestamp = new ::google::protobuf::Timestamp; new_timestamp->CopyFrom(*timestamp); timestamp = new_timestamp; } timestamp_ = timestamp; if (timestamp) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimeStampType.timestamp) } inline const TimeStampType* TimeStampType::internal_default_instance() { return &TimeStampType_default_instance_.get(); } // ------------------------------------------------------------------- // DurationType // optional .google.protobuf.Duration duration = 1; inline bool DurationType::has_duration() const { return this != internal_default_instance() && duration_ != NULL; } inline void DurationType::clear_duration() { if (GetArenaNoVirtual() == NULL && duration_ != NULL) delete duration_; duration_ = NULL; } inline const ::google::protobuf::Duration& DurationType::duration() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.DurationType.duration) return duration_ != NULL ? *duration_ : *::google::protobuf::Duration::internal_default_instance(); } inline ::google::protobuf::Duration* DurationType::mutable_duration() { if (duration_ == NULL) { duration_ = new ::google::protobuf::Duration; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.DurationType.duration) return duration_; } inline ::google::protobuf::Duration* DurationType::release_duration() { // @@protoc_insertion_point(field_release:google.protobuf.testing.DurationType.duration) ::google::protobuf::Duration* temp = duration_; duration_ = NULL; return temp; } inline void DurationType::set_allocated_duration(::google::protobuf::Duration* duration) { delete duration_; if (duration != NULL && duration->GetArena() != NULL) { ::google::protobuf::Duration* new_duration = new ::google::protobuf::Duration; new_duration->CopyFrom(*duration); duration = new_duration; } duration_ = duration; if (duration) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.DurationType.duration) } inline const DurationType* DurationType::internal_default_instance() { return &DurationType_default_instance_.get(); } // ------------------------------------------------------------------- // TimestampDuration // optional .google.protobuf.Timestamp ts = 1; inline bool TimestampDuration::has_ts() const { return this != internal_default_instance() && ts_ != NULL; } inline void TimestampDuration::clear_ts() { if (GetArenaNoVirtual() == NULL && ts_ != NULL) delete ts_; ts_ = NULL; } inline const ::google::protobuf::Timestamp& TimestampDuration::ts() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDuration.ts) return ts_ != NULL ? *ts_ : *::google::protobuf::Timestamp::internal_default_instance(); } inline ::google::protobuf::Timestamp* TimestampDuration::mutable_ts() { if (ts_ == NULL) { ts_ = new ::google::protobuf::Timestamp; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDuration.ts) return ts_; } inline ::google::protobuf::Timestamp* TimestampDuration::release_ts() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDuration.ts) ::google::protobuf::Timestamp* temp = ts_; ts_ = NULL; return temp; } inline void TimestampDuration::set_allocated_ts(::google::protobuf::Timestamp* ts) { delete ts_; if (ts != NULL && ts->GetArena() != NULL) { ::google::protobuf::Timestamp* new_ts = new ::google::protobuf::Timestamp; new_ts->CopyFrom(*ts); ts = new_ts; } ts_ = ts; if (ts) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDuration.ts) } // optional .google.protobuf.Duration dur = 2; inline bool TimestampDuration::has_dur() const { return this != internal_default_instance() && dur_ != NULL; } inline void TimestampDuration::clear_dur() { if (GetArenaNoVirtual() == NULL && dur_ != NULL) delete dur_; dur_ = NULL; } inline const ::google::protobuf::Duration& TimestampDuration::dur() const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDuration.dur) return dur_ != NULL ? *dur_ : *::google::protobuf::Duration::internal_default_instance(); } inline ::google::protobuf::Duration* TimestampDuration::mutable_dur() { if (dur_ == NULL) { dur_ = new ::google::protobuf::Duration; } // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDuration.dur) return dur_; } inline ::google::protobuf::Duration* TimestampDuration::release_dur() { // @@protoc_insertion_point(field_release:google.protobuf.testing.TimestampDuration.dur) ::google::protobuf::Duration* temp = dur_; dur_ = NULL; return temp; } inline void TimestampDuration::set_allocated_dur(::google::protobuf::Duration* dur) { delete dur_; if (dur != NULL && dur->GetArena() != NULL) { ::google::protobuf::Duration* new_dur = new ::google::protobuf::Duration; new_dur->CopyFrom(*dur); dur = new_dur; } dur_ = dur; if (dur) { } else { } // @@protoc_insertion_point(field_set_allocated:google.protobuf.testing.TimestampDuration.dur) } // repeated .google.protobuf.Timestamp rep_ts = 3; inline int TimestampDuration::rep_ts_size() const { return rep_ts_.size(); } inline void TimestampDuration::clear_rep_ts() { rep_ts_.Clear(); } inline const ::google::protobuf::Timestamp& TimestampDuration::rep_ts(int index) const { // @@protoc_insertion_point(field_get:google.protobuf.testing.TimestampDuration.rep_ts) return rep_ts_.Get(index); } inline ::google::protobuf::Timestamp* TimestampDuration::mutable_rep_ts(int index) { // @@protoc_insertion_point(field_mutable:google.protobuf.testing.TimestampDuration.rep_ts) return rep_ts_.Mutable(index); } inline ::google::protobuf::Timestamp* TimestampDuration::add_rep_ts() { // @@protoc_insertion_point(field_add:google.protobuf.testing.TimestampDuration.rep_ts) return rep_ts_.Add(); } inline ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >* TimestampDuration::mutable_rep_ts() { // @@protoc_insertion_point(field_mutable_list:google.protobuf.testing.TimestampDuration.rep_ts) return &rep_ts_; } inline const ::google::protobuf::RepeatedPtrField< ::google::protobuf::Timestamp >& TimestampDuration::rep_ts() const { // @@protoc_insertion_point(field_list:google.protobuf.testing.TimestampDuration.rep_ts) return rep_ts_; } inline const TimestampDuration* TimestampDuration::internal_default_instance() { return &TimestampDuration_default_instance_.get(); } #endif // !PROTOBUF_INLINE_NOT_IN_HEADERS // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace testing } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_google_2fprotobuf_2futil_2finternal_2ftestdata_2ftimestamp_5fduration_2eproto__INCLUDED
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:37:01 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <MediaRemote/MediaRemote-Structs.h> #import <MediaRemote/MRCoreUtilsPairingSession.h> @interface MRCoreUtilsSystemPairingSession : MRCoreUtilsPairingSession +(id)pairingManager; +(BOOL)systemPairingAvailable; +(id)globalPairingQueue; -(BOOL)shouldRetry; -(id)removePeer; -(id)updatePeer; -(id)updateMediaRemotePairedDevice:(id)arg1 ; -(id)pairedPeerDevices; -(id)mediaRemotePairedDevices; -(void*)_createPeerDeviceFromPairedPeer:(id)arg1 ; -(id)initializePairingSession:(PairingSessionPrivateRef)arg1 ; -(BOOL)shouldAutoRetryPairingExchange:(id)arg1 ; -(id)addPeer; -(id)pairedPeerDevice; -(id)pairedPeerFromPeerDevice:(void*)arg1 ; @end
var ex__get__object__truth__vector_8c = [ [ "ex_get_object_truth_vector", "ex__get__object__truth__vector_8c.html#a1591cc35b01b6546f9367b4420be6862", null ] ];
""" pyTransient_problem """ # ============================================================================= # Imports # ============================================================================= import warnings import os import numpy as np from collections import OrderedDict import time from .base import TACSProblem import tacs.TACS class TransientProblem(TACSProblem): def __init__(self, name, tInit, tFinal, numSteps, assembler, comm, outputViewer=None, meshLoader=None, options={}): """ The main purpose of this class is to represent all relevant information for a transient analysis. This will include information defining the loading condition as well as various other pieces of information. Parameters ---------- name : str Name of this tacs problem tInit : float Starting time for transient problem integration tFinal : float Ending time for transient problem integration numSteps : int Number of time steps for transient problem integration assembler : assembler Cython object responsible for creating and setting tacs objects used to solve problem comm : MPI Intracomm The comm object on which to create the pyTACS object. outputViewer : TACSToFH5 object Cython object used to write out f5 files that can be converted and used for postprocessing. meshLoader : pyMeshLoader object pyMeshLoader object used to create the assembler. options : dict Dictionary holding problem-specific option parameters. """ # python object name self.objectName = 'TransientProblem' # Problem name self.name = name # Defualt setup for common problem class objects super().__init__(assembler, comm, outputViewer, meshLoader) # Set time interval parmeters self.tInit = tInit self.tFinal = tFinal self.numSteps = numSteps # Default Option List defOpts = { 'outputdir': [str, './'], # Solution Options 'timeIntegrator': [str, 'BDF'], 'integrationOrder': [int, 2], 'L2Convergence': [float, 1e-12], 'L2ConvergenceRel': [float, 1e-12], 'jacAssemblyFreq': [int, 1], 'useMonitor': [bool, False], 'monitorFrequency': [int, 10], # Output Options 'outputFrequency': [int, 0], 'writeSolution': [bool, True], 'numberSolutions': [bool, True], 'printTiming': [bool, False], 'printLevel': [int, 0], } # Process the default options which are added to self.options # under the 'defaults' key. Make sure the key are lower case self.options = {} def_keys = defOpts.keys() self.options['defaults'] = {} for key in def_keys: self.options['defaults'][key.lower()] = defOpts[key] self.options[key.lower()] = defOpts[key] # Set user-defined options for key in options: self.setOption(key, options[key]) # Create problem-specific variables self._createVariables() # Set output viewer for integrator self.integrator.setFH5(self.outputViewer) outputFreq = self.getOption('outputFrequency') self.integrator.setOutputFrequency(outputFreq) outputDir = self.getOption('outputDir') self.integrator.setOutputPrefix(outputDir) def _createVariables(self): """ Internal to create the objects required by TACS Integrator """ self.callCounter = -1 # Create a force vector for each time step self.F = [self.assembler.createVec() for i in range(self.numSteps + 1)] # Auxillary element object for applying tractions/pressure self.auxElems = [tacs.TACS.AuxElements() for i in range(self.numSteps + 1)] # Create the BDF integrator solver order = self.getOption('integrationOrder') solverType = self.getOption('timeIntegrator') # Chose solver type if solverType.upper() == 'BDF': self.integrator = tacs.TACS.BDFIntegrator(self.assembler, self.tInit, self.tFinal, float(self.numSteps), order) elif solverType.upper() == 'DIRK': self.integrator = tacs.TACS.DIRKIntegrator(self.assembler, self.tInit, self.tFinal, float(self.numSteps), order) printLevel = self.getOption('printLevel') self.integrator.setPrintLevel(printLevel) # Set solver tolerances atol = self.getOption('L2Convergence') self.integrator.setAbsTol(atol) rtol = self.getOption('L2ConvergenceRel') self.integrator.setRelTol(rtol) # Jacobian assembly frequency jacFreq = self.getOption('jacAssemblyFreq') self.integrator.setJacAssemblyFreq(jacFreq) def getNumTimeSteps(self): """ Get the number of timesteps used in time integration for this problem. Returns ---------- numSteps : int Number of time steps. """ # Should this really be numSteps + 1 ? return self.numSteps def getTimeSteps(self): """ Get the discrete time step slices used in time integration. Returns ---------- numSteps : int Number of time steps. """ timeSteps = np.linspace(self.tInit, self.tFinal, self.numSteps + 1) return timeSteps ####### Load adding methods ######## def addLoadToComponents(self, timeStep, compIDs, F, averageLoad=False): """" The function is used to add a *FIXED TOTAL LOAD* on one or more components, defined by COMPIDs, at a specifc time instance. The purpose of this routine is to add loads that remain fixed throughout an optimization. An example would be an engine load. This routine determines all the unqiue nodes in the FE model that are part of the the requested components, then takes the total 'force' by F and divides by the number of nodes. This average load is then applied to the nodes. Parameters ---------- timeStep : int Time step index to apply load to. compIDs : list[int] or int The components with added loads. Use pyTACS selectCompIDs method to determine this. F : Numpy 1d or 2d array length (varsPerNodes) or (numNodeIDs, varsPerNodes) Vector(s) of 'force' to apply to each components. If only one force vector is provided, force will be copied uniformly across all components. averageLoad : bool Flag to determine whether load should be split evenly across all components (True) or copied and applied individually to each component (False). Defaults to False. Notes ----- The units of the entries of the 'force' vector F are not necesarily physical forces and their interpretation depends on the physics problem being solved and the dofs included in the model. A couple of examples of force vector components for common problem are listed below: In Heat Conduction with varsPerNode = 1 F = [Qdot] # heat rate In Elasticity with varsPerNode = 3, F = [fx, fy, fz] # forces In Elasticity with varsPerNode = 6, F = [fx, fy, fz, mx, my, mz] # forces + moments In Thermoelasticity with varsPerNode = 4, F = [fx, fy, fz, Qdot] # forces + heat rate In Thermoelasticity with varsPerNode = 7, F = [fx, fy, fz, mx, my, mz, Qdot] # forces + moments + heat rate """ self._addLoadToComponents(self.F[timeStep], compIDs, F, averageLoad) def addLoadToNodes(self, timeStep, nodeIDs, F, nastranOrdering=False): """ The function is used to add a fixed point load of F to the selected node IDs at a specified time instance. Parameters ---------- timeStep : int Time step index to apply load to. nodeIDs : list[int] The nodes IDs with added loads. F : Numpy 1d or 2d array length (varsPerNodes) or (numNodeIDs, varsPerNodes) Array of force vectors, one for each node. If only one force vector is provided, force will be copied uniformly across all nodes. nastranOrdering : bool Flag signaling whether nodeIDs are in TACS (default) or NASTRAN (grid IDs in bdf file) ordering Notes ----- The units of the entries of the 'force' vector F are not necesarily physical forces and their interpretation depends on the physics problem being solved and the dofs included in the model. A couple of examples of force vector components for common problem are listed below: In Heat Conduction with varsPerNode = 1 F = [Qdot] # heat rate In Elasticity with varsPerNode = 3, F = [fx, fy, fz] # forces In Elasticity with varsPerNode = 6, F = [fx, fy, fz, mx, my, mz] # forces + moments In Thermoelasticity with varsPerNode = 4, F = [fx, fy, fz, Qdot] # forces + heat rate In Thermoelasticity with varsPerNode = 7, F = [fx, fy, fz, mx, my, mz, Qdot] # forces + moments + heat rate """ self._addLoadToNodes(self.F[timeStep], nodeIDs, F, nastranOrdering) def addLoadToRHS(self, timeStep, Fapplied): """" The function is used to add a *FIXED TOTAL LOAD* directly to the right hand side vector given the equation below: M*udotdot + K*u = f Where: K : Stiffness matrix for problem u : State variables for problem M : Mass matrix for problem udotdot : Second time derivitive of state variables for problem f : Right-hand side vector to add loads to Parameters ---------- timeStep : int Time step index to apply load to. Fapplied : ndarray or BVec Distributed array containing loads to applied to RHS of the problem. """ self._addLoadToRHS(self.F[timeStep], Fapplied) def addTractionToComponents(self, timeStep, compIDs, tractions, faceIndex=0): """ The function is used to add a *FIXED TOTAL TRACTION* on one or more components, defined by COMPIDs, at specified time instance. The purpose of this routine is to add loads that remain fixed throughout an optimization. Parameters ---------- timeStep : int Time step index to apply load to. compIDs : list[int] or int The components with added loads. Use pyTACS selectCompIDs method to determine this. tractions : Numpy array length 1 or compIDs Array of traction vectors for each components faceIndex : int Indicates which face (side) of element to apply traction to. Note: not required for certain elements (i.e. shells) """ self._addTractionToComponents(self.auxElems[timeStep], compIDs, tractions, faceIndex) def addTractionToElements(self, timeStep, elemIDs, tractions, faceIndex=0, nastranOrdering=False): """ The function is used to add a fixed traction to the selected element IDs at specified time instance. Tractions can be specified on an element by element basis (if tractions is a 2d array) or set to a uniform value (if tractions is a 1d array) Parameters ---------- timeStep : int Time step index to apply load to. elemIDs : list[int] The global element ID numbers for which to apply the traction. tractions : Numpy 1d or 2d array length varsPerNodes or (elemIDs, varsPerNodes) Array of traction vectors for each element faceIndex : int Indicates which face (side) of element to apply traction to. Note: not required for certain elements (i.e. shells) nastranOrdering : bool Flag signaling whether elemIDs are in TACS (default) or NASTRAN ordering """ self._addTractionToElements(self.auxElems[timeStep], elemIDs, tractions, faceIndex, nastranOrdering) def addPressureToComponents(self, timeStep, compIDs, pressures, faceIndex=0): """ The function is used to add a *FIXED TOTAL PRESSURE* on one or more components, defined by COMPIDs, at specified time instance. The purpose of this routine is to add loads that remain fixed throughout an optimization. An example would be a fuel load. Parameters ---------- timeStep : int Time step index to apply load to. compIDs : list[int] or int The components with added loads. Use pyTACS selectCompIDs method to determine this. pressures : Numpy array length 1 or compIDs Array of pressure values for each components faceIndex : int Indicates which face (side) of element to apply pressure to. Note: not required for certain elements (i.e. shells) """ self._addPressureToComponents(self.auxElems[timeStep], compIDs, pressures, faceIndex) def addPressureToElements(self, timeStep, elemIDs, pressures, faceIndex=0, nastranOrdering=False): """ The function is used to add a fixed presure to the selected element IDs at specified time instance. Pressures can be specified on an element by element basis (if pressures is an array) or set to a uniform value (if pressures is a scalar) Parameters ---------- timeStep : int Time step index to apply load to. elemIDs : list[int] The global element ID numbers for which to apply the pressure. pressures : Numpy array length 1 or elemIDs Array of pressure values for each element faceIndex : int Indicates which face (side) of element to apply pressure to. Note: not required for certain elements (i.e. shells) nastranOrdering : bool Flag signaling whether elemIDs are in TACS (default) or NASTRAN ordering """ self._addPressureToElements(self.auxElems[timeStep], elemIDs, pressures, faceIndex, nastranOrdering) ####### Transient solver methods ######## def _updateAssemblerVars(self): """ Make sure that the assembler is using the input variables associated with this problem """ self.assembler.setDesignVars(self.x) self.assembler.setNodes(self.Xpts) def solve(self): """ Solve the time integrated transient problem. The forces must already be set. """ startTime = time.time() self.callCounter += 1 setupProblemTime = time.time() # Set problem vars to assembler self._updateAssemblerVars() initSolveTime = time.time() # Loop over every time step and solve transient problem for i in range(self.numSteps + 1): # Set the auxilliary elements for this time step (tractions/pressures) self.assembler.setAuxElements(self.auxElems[i]) self.integrator.iterate(i, forces=self.F[i]) solveTime = time.time() # If timing was was requested print it, if the solution is nonlinear # print this information automatically if prinititerations was requested. if self.getOption('printTiming'): self.pp('+--------------------------------------------------+') self.pp('|') self.pp('| TACS Solve Times:') self.pp('|') self.pp('| %-30s: %10.3f sec' % ('TACS Setup Time', setupProblemTime - startTime)) self.pp('| %-30s: %10.3f sec' % ('TACS Solve Init Time', initSolveTime - setupProblemTime)) self.pp('| %-30s: %10.3f sec' % ('TACS Solve Time', solveTime - initSolveTime)) self.pp('|') self.pp('| %-30s: %10.3f sec' % ('TACS Total Solution Time', solveTime - startTime)) self.pp('+--------------------------------------------------+') return ####### Function eval/sensitivity methods ######## def evalFunctions(self, funcs, evalFuncs=None, ignoreMissing=False): """ This is the main routine for returning useful information from pytacs. The functions corresponding to the strings in EVAL_FUNCS are evaluated and updated into the provided dictionary. Parameters ---------- funcs : dict Dictionary into which the functions are saved. evalFuncs : iterable object containing strings. If not none, use these functions to evaluate. ignoreMissing : bool Flag to supress checking for a valid function. Please use this option with caution. Examples -------- >>> funcs = {} >>> transientProblem.solve() >>> transientProblem.evalFunctions(funcs, ['mass']) >>> funcs >>> # Result will look like (if TransientProblem has name of 'c1'): >>> # {'cl_mass':12354.10} """ startTime = time.time() # Set problem vars to assembler self._updateAssemblerVars() if evalFuncs is None: evalFuncs = sorted(list(self.functionList)) else: evalFuncs = sorted(list(evalFuncs)) if not ignoreMissing: for f in evalFuncs: if not f in self.functionList: raise Error("Supplied function '%s' has not been added " "using addFunction()." % f) setupProblemTime = time.time() # Fast parallel function evaluation of structural funcs: handles = [self.functionList[f] for f in evalFuncs if f in self.functionList] # Set functions for integrator self.integrator.setFunctions(handles) # Evaluate functions funcVals = self.integrator.evalFunctions(handles) functionEvalTime = time.time() # Assign function values to appropriate dictionary i = 0 for f in evalFuncs: if f in self.functionList: key = self.name + '_%s' % f funcs[key] = funcVals[i] i += 1 dictAssignTime = time.time() if self.getOption('printTiming'): self.pp('+--------------------------------------------------+') self.pp('|') self.pp('| TACS Function Times:') self.pp('|') self.pp('| %-30s: %10.3f sec' % ('TACS Function Setup Time', setupProblemTime - startTime)) self.pp('| %-30s: %10.3f sec' % ('TACS Function Eval Time', functionEvalTime - setupProblemTime)) self.pp('| %-30s: %10.3f sec' % ('TACS Dict Time', dictAssignTime - functionEvalTime)) self.pp('|') self.pp('| %-30s: %10.3f sec' % ('TACS Function Time', dictAssignTime - startTime)) self.pp('+--------------------------------------------------+') def evalFunctionsSens(self, funcsSens, evalFuncs=None): """ This is the main routine for returning useful (sensitivity) information from problem. The derivatives of the functions corresponding to the strings in EVAL_FUNCS are evaluated and updated into the provided dictionary. Parameters ---------- funcsSens : dict Dictionary into which the derivatives are saved. evalFuncs : iterable object containing strings The functions the user wants returned Examples -------- >>> funcsSens = {} >>> transientProblem.evalFunctionsSens(funcsSens, ['mass']) >>> funcs >>> # Result will look like (if TransientProblem has name of 'c1'): >>> # {'c1_mass':{'struct':[1.234, ..., 7.89]} """ startTime = time.time() # Set problem vars to assembler self._updateAssemblerVars() if evalFuncs is None: evalFuncs = sorted(list(self.functionList)) else: evalFuncs = sorted(list(evalFuncs)) for f in evalFuncs: if f not in self.functionList: raise self.TACSError("Supplied function has not been added " "using addFunction()") # Fast parallel function evaluation of structural funcs: handles = [self.functionList[f] for f in evalFuncs if f in self.functionList] # Set functions for integrator self.integrator.setFunctions(handles) # integrate adjoints backwards in time from step = numSteps # to step = 0 for i in range(self.numSteps, -1, -1): self.assembler.setAuxElements(self.auxElems[i]) self.integrator.initAdjoint(i) self.integrator.iterateAdjoint(i) self.integrator.postAdjoint(i) adjointFinishedTime = time.time() # Recast sensititivities into dict for user for i, f in enumerate(evalFuncs): key = self.name + '_%s' % f # Finalize sensitivity arrays across all procs dvSens = self.integrator.getGradient(i) dvSens.beginSetValues() dvSens.endSetValues() xptSens = self.integrator.getXptGradient(i) xptSens.beginSetValues() xptSens.endSetValues() # Return sensitivities as array in sens dict funcsSens[key] = {self.varName: dvSens.getArray().copy(), self.coordName: xptSens.getArray().copy()} totalSensitivityTime = time.time() if self.getOption('printTiming'): self.pp('+--------------------------------------------------+') self.pp('|') self.pp('| TACS Adjoint Times:') print('|') print('| %-30s: %10.3f sec' % ('Adjoint solve time', adjointFinishedTime - startTime)) print('|') print('| %-30s: %10.3f sec' % ('Complete Sensitivity Time', totalSensitivityTime - startTime)) print('+--------------------------------------------------+') ####### Post processing methods ######## def getVariables(self, timeStep, states=None, dstates=None, ddstates=None): """ Return the current state values for the current problem Parameters ---------- timeStep : int Time step index to get state variables for. states : BVec or ndarray or None If states is not None, place the state variables into this array (optional). dstates : BVec or ndarray or None If dstates is not None, place the time derivitive of the state variables into this array (optional). ddstates : BVec or ndarray or None If ddstates is not None, place the second time derivitive of the state variables into this array (optional). Returns -------- time: float The time at specified step states : ndarray The state variables. dstates : BVec or ndarray or None The time derivitive of the state variables. ddstates : BVec or ndarray or None The second time derivitive of the state variables. """ # Get BVecs for time instance time, q, qdot, qddot = self.integrator.getStates(timeStep) # Convert to arrays qArray = q.getArray() qdotArray = qdot.getArray() qddotArray = qddot.getArray() # Inplace assignment if vectors were provided if isinstance(states, tacs.TACS.Vec): states.copyValues(q) elif isinstance(states, np.ndarray): states[:] = qArray if isinstance(dstates, tacs.TACS.Vec): dstates.copyValues(qdot) elif isinstance(dstates, np.ndarray): dstates[:] = qdotArray if isinstance(ddstates, tacs.TACS.Vec): ddstates.copyValues(qddot) elif isinstance(ddstates, np.ndarray): ddstates[:] = qddotArray # Return arrays return time, qArray, qdotArray, qddotArray def writeSolution(self, timeSteps=None): """ This is a generic shell function that writes the output file(s). The intent is that the user or calling program can call this function and pyTACS writes all the files that the user has defined. It is recommended that this function is used along with the associated logical flags in the options to determine the desired writing procedure Parameters ---------- timeStep : int or list[int] or None Time step index or indices to get state variables for. If None, returns a solution for all time steps. Defaults to None. """ # Unless the writeSolution option is off write actual file: if self.getOption('writeSolution'): # Check input outputDir = self.getOption('outputDir') baseName = self.name if self.getOption('numberSolutions'): baseName = baseName + '_%3.3d' % self.callCounter base = os.path.join(outputDir, baseName) + '.f5' # Write specific time step out if timeSteps is not None: timeSteps = np.atleast_1d(timeSteps) for timeStep in timeSteps: self.integrator.writeStepToF5(timeStep) # Write all time steps out else: self.integrator.writeSolutionToF5()
/* This Software is provided under the Zope Public License (ZPL) Version 2.1. Copyright (c) 2009, 2010 by the mingw-w64 project See the AUTHORS file for the list of contributors to the mingw-w64 project. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define _NEW_COMPLEX_DOUBLE 1 #include "expm1.def.h"
import os from ....utils import in_temporary_directory from ....utils import assert_files_exist from ....utils import catkin_success from ....utils import redirected_stdio from ....workspace_assertions import assert_workspace_initialized from ....workspace_assertions import assert_no_warnings TEST_DIR = os.path.dirname(__file__) RESOURCES_DIR = os.path.join(os.path.dirname(__file__), '..', '..', 'resources') @in_temporary_directory def test_build_eclipse(): cwd = os.getcwd() source_space = os.path.join(cwd, 'src') print("Creating source directory: %s" % source_space) os.mkdir(source_space) with redirected_stdio() as (out, err): assert catkin_success( ['create', 'pkg', '--rosdistro', 'hydro', '-p', source_space, 'pkg_a']), 'create pkg' assert catkin_success( ['build', '--no-notify', '--no-status', '--verbose', '--cmake-args', '-GEclipse CDT4 - Unix Makefiles']) assert_no_warnings(out) assert_workspace_initialized('.') assert_files_exist(os.path.join(cwd, 'build', 'pkg_a'), ['.project', '.cproject'])
/* * TOPPERS ATK2 * Toyohashi Open Platform for Embedded Real-Time Systems * Automotive Kernel Version 2 * * Copyright (C) 2011-2015 by Center for Embedded Computing Systems * Graduate School of Information Science, Nagoya Univ., JAPAN * Copyright (C) 2011-2015 by FUJI SOFT INCORPORATED, JAPAN * Copyright (C) 2011-2013 by Spansion LLC, USA * Copyright (C) 2011-2015 by NEC Communication Systems, Ltd., JAPAN * Copyright (C) 2011-2015 by Panasonic Advanced Technology Development Co., Ltd., JAPAN * Copyright (C) 2011-2014 by Renesas Electronics Corporation, JAPAN * Copyright (C) 2011-2015 by Sunny Giken Inc., JAPAN * Copyright (C) 2011-2015 by TOSHIBA CORPORATION, JAPAN * Copyright (C) 2011-2015 by Witz Corporation * Copyright (C) 2014-2015 by AISIN COMCRUISE Co., Ltd., JAPAN * Copyright (C) 2014-2015 by eSOL Co.,Ltd., JAPAN * Copyright (C) 2014-2015 by SCSK Corporation, JAPAN * Copyright (C) 2015 by SUZUKI MOTOR CORPORATION * * 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ * ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改 * 変・再配布(以下,利用と呼ぶ)することを無償で許諾する. * (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作 * 権表示,この利用条件および下記の無保証規定が,そのままの形でソー * スコード中に含まれていること. * (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使 * 用できる形で再配布する場合には,再配布に伴うドキュメント(利用 * 者マニュアルなど)に,上記の著作権表示,この利用条件および下記 * の無保証規定を掲載すること. * (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使 * 用できない形で再配布する場合には,次のいずれかの条件を満たすこ * と. * (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著 * 作権表示,この利用条件および下記の無保証規定を掲載すること. * (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに * 報告すること. * (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損 * 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること. * また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理 * 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを * 免責すること. * * 本ソフトウェアは,AUTOSAR(AUTomotive Open System ARchitecture)仕 * 様に基づいている.上記の許諾は,AUTOSARの知的財産権を許諾するもので * はない.AUTOSARは,AUTOSAR仕様に基づいたソフトウェアを商用目的で利 * 用する者に対して,AUTOSARパートナーになることを求めている. * * 本ソフトウェアは,無保証で提供されているものである.上記著作権者お * よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的 * に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ * アの利用により直接的または間接的に生じたいかなる損害に関しても,そ * の責任を負わない. * * $Id: Compiler_Cfg.h 425 2015-12-07 08:06:19Z witz-itoyo $ */ #ifndef TOPPERS_COMPILER_CFG_H #define TOPPERS_COMPILER_CFG_H /* * ATK2共通定義 */ #ifndef UINT_C #define UINT_C(val) (val ## U) /* 符号無し整数型の定数を作るマクロ */ #endif /* UINT_C */ /* * 型に関する情報を取り出すためのマクロ */ #ifndef offsetof #define offsetof(structure, field) ((uintptr) & (((structure *) 0)->field)) #endif /* offsetof */ #ifndef alignof #define alignof(type) offsetof(struct { uint8 field1; type field2; }, field2) #endif /* alignof */ #ifndef ALIGNED_TYPE /* アラインメントのチェック */ #define ALIGNED_TYPE(addr, type) (boolean) ((((uintptr) (addr)) & (alignof(type) - 1U)) == 0U) #endif /* ALIGNED_TYPE */ #endif /* TOPPERS_COMPILER_CFG_H */
class Solution: def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool: return ''.join(word1) == ''.join(word2)
/** * @license * Copyright (c) 2018 amCharts (Antanas Marcelionis, Martynas Majeris) * * This sofware is provided under multiple licenses. Please see below for * links to appropriate usage. * * Free amCharts linkware license. Details and conditions: * https://github.com/amcharts/amcharts4/blob/master/LICENSE * * One of the amCharts commercial licenses. Details and pricing: * https://www.amcharts.com/online-store/ * https://www.amcharts.com/online-store/licenses-explained/ * * If in doubt, contact amCharts at contact@amcharts.com * * PLEASE DO NOT REMOVE THIS COPYRIGHT NOTICE. * @hidden */ am4internal_webpackJsonp(["5a29"], { h34k: function (n, o, t) { "use strict"; Object.defineProperty(o, "__esModule", { value: !0 }); var i = { AD: { country: "Andorra", continent_code: "EU", continent: "Europe", maps: ["andorraLow", "andorraHigh"] }, AE: { country: "United Arab Emirates", continent_code: "AS", continent: "Asia", maps: ["uaeLow", "uaeHigh"] }, AF: { country: "Afghanistan", continent_code: "AS", continent: "Asia", maps: [] }, AG: { country: "Antigua and Barbuda", continent_code: "NA", continent: "North America", maps: ["antiguaBarbudaLow", "antiguaBarbudaHigh"] }, AI: { country: "Anguilla", continent_code: "NA", continent: "North America", maps: ["anguillaLow", "anguillaHigh"] }, AL: { country: "Albania", continent_code: "EU", continent: "Europe", maps: ["albaniaLow", "albaniaHigh"] }, AM: { country: "Armenia", continent_code: "EU", continent: "Europe", maps: ["armeniaLow", "armeniaHigh"] }, AO: { country: "Angola", continent_code: "AF", continent: "Africa", maps: ["angolaLow", "angolaHigh"] }, AQ: { country: "Antarctica", continent_code: "AN", continent: "Antarctica", maps: [] }, AR: { country: "Argentina", continent_code: "SA", continent: "South America", maps: ["argentinaLow", "argentinaHigh"] }, AS: { country: "American Samoa", continent_code: "OC", continent: "Oceania", maps: ["americanSamoaLow", "americanSamoaHigh"] }, AT: { country: "Austria", continent_code: "EU", continent: "Europe", maps: ["austriaLow", "austriaHigh"] }, AU: { country: "Australia", continent_code: "OC", continent: "Oceania", maps: ["australiaLow", "australiaHigh"] }, AW: { country: "Aruba", continent_code: "NA", continent: "North America", maps: ["arubaLow", "arubaHigh"] }, AX: { country: "Aland Islands", continent_code: "EU", continent: "Europe", maps: [] }, AZ: { country: "Azerbaijan", continent_code: "EU", continent: "Europe", maps: ["azerbaijanLow", "azerbaijanHigh"] }, BA: { country: "Bosnia and Herzegovina", continent_code: "EU", continent: "Europe", maps: ["bosniaHerzegovinaLow", "bosniaHerzegovinaHigh", "bosniaHerzegovinaCantonsLow", "bosniaHerzegovinaCantonsHigh"] }, BB: { country: "Barbados", continent_code: "NA", continent: "North America", maps: ["barbadosLow", "barbadosHigh"] }, BD: { country: "Bangladesh", continent_code: "AS", continent: "Asia", maps: ["bangladeshLow", "bangladeshHigh"] }, BE: { country: "Belgium", continent_code: "EU", continent: "Europe", maps: ["belgiumLow", "belgiumHigh"] }, BF: { country: "Burkina Faso", continent_code: "AF", continent: "Africa", maps: ["burkinaFasoLow", "burkinaFasoHigh"] }, BG: { country: "Bulgaria", continent_code: "EU", continent: "Europe", maps: ["bulgariaLow", "bulgariaHigh"] }, BH: { country: "Bahrain", continent_code: "AS", continent: "Asia", maps: ["bahrainLow", "bahrainHigh"] }, BI: { country: "Burundi", continent_code: "AF", continent: "Africa", maps: ["burundiLow", "burundiHigh"] }, BJ: { country: "Benin", continent_code: "AF", continent: "Africa", maps: ["beninLow", "beninHigh"] }, BL: { country: "Saint Barthelemy", continent_code: "NA", continent: "North America", maps: [] }, BM: { country: "Bermuda", continent_code: "NA", continent: "North America", maps: ["bermudaLow", "bermudaHigh"] }, BN: { country: "Brunei Darussalam", continent_code: "AS", continent: "Asia", maps: ["bruneiDarussalamLow", "bruneiDarussalamHigh"] }, BO: { country: "Bolivia, Plurinational State of", continent_code: "SA", continent: "South America", maps: ["boliviaLow", "boliviaHigh"] }, BQ: { country: "Bonaire, Sint Eustatius and Saba", continent_code: "NA", continent: "North America", maps: ["bonaireSintEustatiusSabaLow", "bonaireSintEustatiusSabaHigh"] }, BR: { country: "Brazil", continent_code: "SA", continent: "South America", maps: ["brazilLow", "brazilHigh"] }, BS: { country: "Bahamas", continent_code: "NA", continent: "North America", maps: ["bahamasLow", "bahamasHigh"] }, BT: { country: "Bhutan", continent_code: "AS", continent: "Asia", maps: ["bhutanLow", "bhutanHigh"] }, BV: { country: "Bouvet Island", continent_code: "AN", continent: "Antarctica", maps: [] }, BW: { country: "Botswana", continent_code: "AF", continent: "Africa", maps: ["botswanaLow", "botswanaHigh"] }, BY: { country: "Belarus", continent_code: "EU", continent: "Europe", maps: ["belarusLow", "belarusHigh"] }, BZ: { country: "Belize", continent_code: "NA", continent: "North America", maps: ["belizeLow", "belizeHigh"] }, CA: { country: "Canada", continent_code: "NA", continent: "North America", maps: ["canadaLow", "canadaHigh"] }, CC: { country: "Cocos (Keeling) Islands", continent_code: "AS", continent: "Asia", maps: ["cocosKeelingLow", "cocosKeelingHigh"] }, CD: { country: "Congo, the Democratic Republic of the", continent_code: "AF", continent: "Africa", maps: ["congoDRLow", "congoDRHigh"] }, CF: { country: "Central African Republic", continent_code: "AF", continent: "Africa", maps: ["centralAfricanRepublicLow", "centralAfricanRepublicHigh"] }, CG: { country: "Congo", continent_code: "AF", continent: "Africa", maps: ["congoLow", "congoHigh"] }, CH: { country: "Switzerland", continent_code: "EU", continent: "Europe", maps: ["switzerlandLow", "switzerlandHigh"] }, CI: { country: "Cote d'Ivoire", continent_code: "AF", continent: "Africa", maps: [] }, CK: { country: "Cook Islands", continent_code: "OC", continent: "Oceania", maps: [] }, CL: { country: "Chile", continent_code: "SA", continent: "South America", maps: ["chileLow", "chileHigh"] }, CM: { country: "Cameroon", continent_code: "AF", continent: "Africa", maps: ["cameroonLow", "cameroonHigh"] }, CN: { country: "China", continent_code: "AS", continent: "Asia", maps: ["chinaLow", "chinaHigh"] }, CO: { country: "Colombia", continent_code: "SA", continent: "South America", maps: ["colombiaLow", "colombiaHigh", "colombiaMuniLow", "colombiaMuniHigh"] }, CR: { country: "Costa Rica", continent_code: "NA", continent: "North America", maps: ["costaRicaLow", "costaRicaHigh"] }, CU: { country: "Cuba", continent_code: "NA", continent: "North America", maps: [] }, CV: { country: "Cape Verde", continent_code: "AF", continent: "Africa", maps: ["capeVerdeLow", "capeVerdeHigh"] }, CW: { country: "Curacao", continent_code: "NA", continent: "North America", maps: ["curacaoLow", "curacaoHigh"] }, CX: { country: "Christmas Island", continent_code: "AS", continent: "Asia", maps: [] }, CY: { country: "Cyprus", continent_code: "EU", continent: "Europe", maps: ["cyprusLow", "cyprusHigh", "cyprusNorthCyprusLow", "cyprusNorthCyprusHigh"] }, CZ: { country: "Czech Republic", continent_code: "EU", continent: "Europe", maps: ["czechiaLow", "czechiaHigh"] }, DE: { country: "Germany", continent_code: "EU", continent: "Europe", maps: ["germanyLow", "germanyHigh"] }, DJ: { country: "Djibouti", continent_code: "AF", continent: "Africa", maps: ["djiboutiLow", "djiboutiHigh"] }, DK: { country: "Denmark", continent_code: "EU", continent: "Europe", maps: ["denmarkLow", "denmarkHigh"] }, DM: { country: "Dominica", continent_code: "NA", continent: "North America", maps: ["dominicaLow", "dominicaHigh"] }, DO: { country: "Dominican Republic", continent_code: "NA", continent: "North America", maps: ["dominicanRepublicLow", "dominicanRepublicHigh", "dominicanRepublicMuniLow", "dominicanRepublicMuniHigh"] }, DZ: { country: "Algeria", continent_code: "AF", continent: "Africa", maps: ["algeriaLow", "algeriaHigh"] }, EC: { country: "Ecuador", continent_code: "SA", continent: "South America", maps: ["ecuadorLow", "ecuadorHigh"] }, EE: { country: "Estonia", continent_code: "EU", continent: "Europe", maps: ["estoniaLow", "estoniaHigh"] }, EG: { country: "Egypt", continent_code: "AF", continent: "Africa", maps: ["egyptLow", "egyptHigh"] }, EH: { country: "Western Sahara", continent_code: "AF", continent: "Africa", maps: [] }, ER: { country: "Eritrea", continent_code: "AF", continent: "Africa", maps: ["eritreaLow", "eritreaHigh"] }, ES: { country: "Spain", continent_code: "EU", continent: "Europe", maps: ["spainLow", "spainHigh", "spainProvincesLow", "spainProvincesHigh"] }, ET: { country: "Ethiopia", continent_code: "AF", continent: "Africa", maps: ["ethiopiaLow", "ethiopiaHigh"] }, FI: { country: "Finland", continent_code: "EU", continent: "Europe", maps: ["finlandLow", "finlandHigh"] }, FJ: { country: "Fiji", continent_code: "OC", continent: "Oceania", maps: ["fijiEastLow", "fijiEastHigh", "fijiWestLow", "fijiWestHigh"] }, FK: { country: "Falkland Islands (Malvinas)", continent_code: "SA", continent: "South America", maps: [] }, FM: { country: "Micronesia, Federated States of", continent_code: "OC", continent: "Oceania", maps: [] }, FO: { country: "Faroe Islands", continent_code: "EU", continent: "Europe", maps: ["faroeIslandsLow", "faroeIslandsHigh"] }, FR: { country: "France", continent_code: "EU", continent: "Europe", maps: ["franceLow", "franceHigh", "franceDepartmentsLow", "franceDepartmentsHigh"] }, GA: { country: "Gabon", continent_code: "AF", continent: "Africa", maps: ["gabonLow", "gabonHigh"] }, GB: { country: "United Kingdom", continent_code: "EU", continent: "Europe", maps: ["ukLow", "ukHigh", "ukCountiesLow", "ukCountiesHigh", "ukCountriesLow", "ukCountriesHigh"] }, "GB-CHA": { country: "Channel Islands", continent_code: "EU", continent: "Europe", maps: ["channelIslandsLow", "channelIslandsHigh"] }, GD: { country: "Grenada", continent_code: "NA", continent: "North America", maps: [] }, GE: { country: "Georgia", continent_code: "EU", continent: "Europe", maps: ["georgiaLow", "georgiaHigh", "georgiaSouthOssetiaLow", "georgiaSouthOssetiaHigh"] }, GF: { country: "French Guiana", continent_code: "SA", continent: "South America", maps: ["frenchGuianaLow", "frenchGuianaHigh"] }, GG: { country: "Guernsey", continent_code: "EU", continent: "Europe", maps: [] }, GH: { country: "Ghana", continent_code: "AF", continent: "Africa", maps: ["ghanaLow", "ghanaHigh"] }, GI: { country: "Gibraltar", continent_code: "EU", continent: "Europe", maps: [] }, GL: { country: "Greenland", continent_code: "NA", continent: "North America", maps: ["greenlandLow", "greenlandHigh"] }, GM: { country: "Gambia", continent_code: "AF", continent: "Africa", maps: ["gambiaLow", "gambiaHigh"] }, GN: { country: "Guinea", continent_code: "AF", continent: "Africa", maps: ["guineaLow", "guineaHigh"] }, GP: { country: "Guadeloupe", continent_code: "NA", continent: "North America", maps: [] }, GQ: { country: "Equatorial Guinea", continent_code: "AF", continent: "Africa", maps: ["equatorialGuineaLow", "equatorialGuineaHigh"] }, GR: { country: "Greece", continent_code: "EU", continent: "Europe", maps: ["greeceLow", "greeceHigh"] }, GS: { country: "South Georgia and the South Sandwich Islands", continent_code: "AN", continent: "Antarctica", maps: [] }, GT: { country: "Guatemala", continent_code: "NA", continent: "North America", maps: [] }, GU: { country: "Guam", continent_code: "OC", continent: "Oceania", maps: [] }, GW: { country: "Guinea-Bissau", continent_code: "AF", continent: "Africa", maps: ["guineaBissauLow", "guineaBissauHigh"] }, GY: { country: "Guyana", continent_code: "SA", continent: "South America", maps: ["guyanaLow", "guyanaHigh"] }, HK: { country: "Hong Kong", continent_code: "AS", continent: "Asia", maps: ["hongKongLow", "hongKongHigh"] }, HM: { country: "Heard Island and McDonald Islands", continent_code: "AN", continent: "Antarctica", maps: [] }, HN: { country: "Honduras", continent_code: "NA", continent: "North America", maps: ["hondurasLow", "hondurasHigh"] }, HR: { country: "Croatia", continent_code: "EU", continent: "Europe", maps: ["croatiaLow", "croatiaHigh"] }, HT: { country: "Haiti", continent_code: "NA", continent: "North America", maps: [] }, HU: { country: "Hungary", continent_code: "EU", continent: "Europe", maps: ["hungaryLow", "hungaryHigh"] }, ID: { country: "Indonesia", continent_code: "AS", continent: "Asia", maps: ["indonesiaLow", "indonesiaHigh"] }, IE: { country: "Ireland", continent_code: "EU", continent: "Europe", maps: ["irelandLow", "irelandHigh"] }, IL: { country: "Israel", continent_code: "AS", continent: "Asia", maps: ["israelLow", "israelHigh", "israelPalestineLow", "israelPalestineHigh"] }, IM: { country: "Isle of Man", continent_code: "EU", continent: "Europe", maps: [] }, IN: { country: "India", continent_code: "AS", continent: "Asia", maps: ["india2020Low", "india2020High", "india2019Low", "india2019High", "indiaLow", "indiaHigh"] }, IO: { country: "British Indian Ocean Territory", continent_code: "AS", continent: "Asia", maps: ["britishIndianOceanTerritoryLow", "britishIndianOceanTerritoryHigh"] }, IQ: { country: "Iraq", continent_code: "AS", continent: "Asia", maps: ["iraqLow", "iraqHigh"] }, IR: { country: "Iran, Islamic Republic of", continent_code: "AS", continent: "Asia", maps: ["iranLow", "iranHigh"] }, IS: { country: "Iceland", continent_code: "EU", continent: "Europe", maps: ["icelandLow", "icelandHigh"] }, IT: { country: "Italy", continent_code: "EU", continent: "Europe", maps: ["italyLow", "italyHigh"] }, JE: { country: "Jersey", continent_code: "EU", continent: "Europe", maps: [] }, JM: { country: "Jamaica", continent_code: "NA", continent: "North America", maps: [] }, JO: { country: "Jordan", continent_code: "AS", continent: "Asia", maps: [] }, JP: { country: "Japan", continent_code: "AS", continent: "Asia", maps: ["japanLow", "japanHigh"] }, KE: { country: "Kenya", continent_code: "AF", continent: "Africa", maps: ["kenyaLow", "kenyaHigh"] }, KG: { country: "Kyrgyzstan", continent_code: "AS", continent: "Asia", maps: ["kyrgyzstanLow", "kyrgyzstanHigh"] }, KH: { country: "Cambodia", continent_code: "AS", continent: "Asia", maps: ["cambodiaLow", "cambodiaHigh"] }, KI: { country: "Kiribati", continent_code: "OC", continent: "Oceania", maps: [] }, KM: { country: "Comoros", continent_code: "AF", continent: "Africa", maps: ["comorosLow", "comorosHigh"] }, KN: { country: "Saint Kitts and Nevis", continent_code: "NA", continent: "North America", maps: [] }, KP: { country: "Korea, Democratic People's Republic of", continent_code: "AS", continent: "Asia", maps: ["northKoreaLow", "northKoreaHigh"] }, KR: { country: "Korea, Republic of", continent_code: "AS", continent: "Asia", maps: ["southKoreaLow", "southKoreaHigh"] }, KT: { country: "Saint Kitts and Nevis", continent_code: "AS", continent: "Asia", maps: ["stKittsNevisLow", "stKittsNevisHigh"] }, KW: { country: "Kuwait", continent_code: "AS", continent: "Asia", maps: ["kuwaitLow", "kuwaitHigh"] }, KY: { country: "Cayman Islands", continent_code: "NA", continent: "North America", maps: ["caymanIslandsLow", "caymanIslandsHigh"] }, KZ: { country: "Kazakhstan", continent_code: "EU", continent: "Europe", maps: ["kazakhstanLow", "kazakhstanHigh"] }, LA: { country: "Lao People's Democratic Republic", continent_code: "AS", continent: "Asia", maps: ["laosLow", "laosHigh"] }, LB: { country: "Lebanon", continent_code: "AS", continent: "Asia", maps: [] }, LC: { country: "Saint Lucia", continent_code: "NA", continent: "North America", maps: ["saintLuciaLow", "saintLuciaHigh"] }, LI: { country: "Liechtenstein", continent_code: "EU", continent: "Europe", maps: ["liechtensteinLow", "liechtensteinHigh"] }, LK: { country: "Sri Lanka", continent_code: "AS", continent: "Asia", maps: ["sriLankaLow", "sriLankaHigh"] }, LR: { country: "Liberia", continent_code: "AF", continent: "Africa", maps: [] }, LS: { country: "Lesotho", continent_code: "AF", continent: "Africa", maps: [] }, LT: { country: "Lithuania", continent_code: "EU", continent: "Europe", maps: ["lithuaniaLow", "lithuaniaHigh"] }, LU: { country: "Luxembourg", continent_code: "EU", continent: "Europe", maps: ["luxembourgLow", "luxembourgHigh"] }, LV: { country: "Latvia", continent_code: "EU", continent: "Europe", maps: ["latviaLow", "latviaHigh"] }, LY: { country: "Libya", continent_code: "AF", continent: "Africa", maps: ["libyaLow", "libyaHigh"] }, MA: { country: "Morocco", continent_code: "AF", continent: "Africa", maps: ["moroccoLow", "moroccoHigh"] }, MC: { country: "Monaco", continent_code: "EU", continent: "Europe", maps: [] }, MD: { country: "Moldova, Republic of", continent_code: "EU", continent: "Europe", maps: ["moldovaLow", "moldovaHigh"] }, ME: { country: "Montenegro", continent_code: "EU", continent: "Europe", maps: ["montenegroLow", "montenegroHigh"] }, MF: { country: "Saint Martin (French Part)", continent_code: "NA", continent: "North America", maps: [] }, MG: { country: "Madagascar", continent_code: "AF", continent: "Africa", maps: ["madagascarProvinceLow", "madagascarProvinceHigh", "madagascarRegionLow", "madagascarRegionHigh"] }, MH: { country: "Marshall Islands", continent_code: "OC", continent: "Oceania", maps: [] }, MK: { country: "North Macedonia", continent_code: "EU", continent: "Europe", maps: ["northMacedoniaLow", "northMacedoniaHigh"] }, ML: { country: "Mali", continent_code: "AF", continent: "Africa", maps: ["maliLow", "maliHigh"] }, MM: { country: "Myanmar", continent_code: "AS", continent: "Asia", maps: ["myanmarLow", "myanmarHigh"] }, MN: { country: "Mongolia", continent_code: "AS", continent: "Asia", maps: ["mongoliaLow", "mongoliaHigh"] }, MO: { country: "Macao", continent_code: "AS", continent: "Asia", maps: [] }, MP: { country: "Northern Mariana Islands", continent_code: "OC", continent: "Oceania", maps: [] }, MQ: { country: "Martinique", continent_code: "NA", continent: "North America", maps: [] }, MR: { country: "Mauritania", continent_code: "AF", continent: "Africa", maps: ["mauritaniaLow", "mauritaniaHigh"] }, MS: { country: "Montserrat", continent_code: "NA", continent: "North America", maps: [] }, MT: { country: "Malta", continent_code: "EU", continent: "Europe", maps: ["maltaLow", "maltaHigh"] }, MU: { country: "Mauritius", continent_code: "AF", continent: "Africa", maps: [] }, MV: { country: "Maldives", continent_code: "AS", continent: "Asia", maps: ["maldivesLow", "maldivesHigh", "maldivesIslandsLow", "maldivesIslandsHigh"] }, MW: { country: "Malawi", continent_code: "AF", continent: "Africa", maps: ["malawiLow", "malawiHigh"] }, MX: { country: "Mexico", continent_code: "NA", continent: "North America", maps: ["mexicoLow", "mexicoHigh"] }, MY: { country: "Malaysia", continent_code: "AS", continent: "Asia", maps: ["malaysiaLow", "malaysiaHigh"] }, MZ: { country: "Mozambique", continent_code: "AF", continent: "Africa", maps: ["mozambiqueLow", "mozambiqueHigh"] }, NA: { country: "Namibia", continent_code: "AF", continent: "Africa", maps: ["namibiaLow", "namibiaHigh"] }, NC: { country: "New Caledonia", continent_code: "OC", continent: "Oceania", maps: [] }, NE: { country: "Niger", continent_code: "AF", continent: "Africa", maps: ["nigerLow", "nigerHigh"] }, NF: { country: "Norfolk Island", continent_code: "OC", continent: "Oceania", maps: [] }, NG: { country: "Nigeria", continent_code: "AF", continent: "Africa", maps: ["nigeriaLow", "nigeriaHigh"] }, NI: { country: "Nicaragua", continent_code: "NA", continent: "North America", maps: ["nicaraguaLow", "nicaraguaHigh"] }, NL: { country: "Netherlands", continent_code: "EU", continent: "Europe", maps: ["netherlandsLow", "netherlandsHigh"] }, NO: { country: "Norway", continent_code: "EU", continent: "Europe", maps: ["norwayLow", "norwayHigh"] }, NP: { country: "Nepal", continent_code: "AS", continent: "Asia", maps: ["nepalLow", "nepalHigh"] }, NR: { country: "Nauru", continent_code: "OC", continent: "Oceania", maps: [] }, NU: { country: "Niue", continent_code: "OC", continent: "Oceania", maps: [] }, NZ: { country: "New Zealand", continent_code: "OC", continent: "Oceania", maps: ["newZealandLow", "newZealandHigh"] }, OM: { country: "Oman", continent_code: "AS", continent: "Asia", maps: ["omanLow", "omanHigh"] }, PA: { country: "Panama", continent_code: "NA", continent: "North America", maps: ["panamaLow", "panamaHigh"] }, PE: { country: "Peru", continent_code: "SA", continent: "South America", maps: ["peruLow", "peruHigh"] }, PF: { country: "French Polynesia", continent_code: "OC", continent: "Oceania", maps: [] }, PG: { country: "Papua New Guinea", continent_code: "OC", continent: "Oceania", maps: [] }, PH: { country: "Philippines", continent_code: "AS", continent: "Asia", maps: ["philippinesLow", "philippinesHigh"] }, PK: { country: "Pakistan", continent_code: "AS", continent: "Asia", maps: ["pakistanLow", "pakistanHigh"] }, PL: { country: "Poland", continent_code: "EU", continent: "Europe", maps: ["polandLow", "polandHigh"] }, PM: { country: "Saint Pierre and Miquelon", continent_code: "NA", continent: "North America", maps: ["stPierreMiquelonLow", "stPierreMiquelonHigh"] }, PN: { country: "Pitcairn", continent_code: "OC", continent: "Oceania", maps: [] }, PR: { country: "Puerto Rico", continent_code: "NA", continent: "North America", maps: ["puertoRicoLow", "puertoRicoHigh"] }, PS: { country: "Palestinian, State of", continent_code: "AS", continent: "Asia", maps: ["palestineLow", "palestineHigh"] }, PT: { country: "Portugal", continent_code: "EU", continent: "Europe", maps: ["portugalLow", "portugalHigh", "portugalRegionsLow", "portugalRegionsHigh"] }, PW: { country: "Palau", continent_code: "OC", continent: "Oceania", maps: [] }, PY: { country: "Paraguay", continent_code: "SA", continent: "South America", maps: ["paraguayLow", "paraguayHigh"] }, QA: { country: "Qatar", continent_code: "AS", continent: "Asia", maps: ["qatarLow", "qatarHigh"] }, RE: { country: "Reunion", continent_code: "AF", continent: "Africa", maps: [] }, RO: { country: "Romania", continent_code: "EU", continent: "Europe", maps: ["romaniaLow", "romaniaHigh"] }, RS: { country: "Serbia", continent_code: "EU", continent: "Europe", maps: ["serbiaLow", "serbiaHigh", "serbiaNoKosovoLow", "serbiaNoKosovoHigh"] }, RU: { country: "Russian Federation", continent_code: "EU", continent: "Europe", maps: ["russiaLow", "russiaHigh", "russiaCrimeaLow", "russiaCrimeaHigh"] }, RW: { country: "Rwanda", continent_code: "AF", continent: "Africa", maps: ["rwandaLow", "rwandaHigh"] }, SA: { country: "Saudi Arabia", continent_code: "AS", continent: "Asia", maps: ["saudiArabiaLow", "saudiArabiaHigh"] }, SB: { country: "Solomon Islands", continent_code: "OC", continent: "Oceania", maps: ["solomonIslandsLow", "solomonIslandsHigh"] }, SC: { country: "Seychelles", continent_code: "AF", continent: "Africa", maps: ["seychellesLow", "seychellesHigh"] }, SD: { country: "Sudan", continent_code: "AF", continent: "Africa", maps: ["sudanLow", "sudanHigh"] }, SE: { country: "Sweden", continent_code: "EU", continent: "Europe", maps: ["swedenLow", "swedenHigh"] }, SG: { country: "Singapore", continent_code: "AS", continent: "Asia", maps: ["singaporeLow", "singaporeHigh"] }, SH: { country: "Saint Helena, Ascension and Tristan da Cunha", continent_code: "AF", continent: "Africa", maps: ["saintHelenaLow", "saintHelenaHigh"] }, SI: { country: "Slovenia", continent_code: "EU", continent: "Europe", maps: ["sloveniaLow", "sloveniaHigh", "sloveniaRegionsLow", "sloveniaRegionsHigh"] }, SJ: { country: "Svalbard and Jan Mayen", continent_code: "EU", continent: "Europe", maps: ["svalbardLow", "svalbardHigh"] }, SK: { country: "Slovakia", continent_code: "EU", continent: "Europe", maps: ["slovakiaLow", "slovakiaHigh"] }, SL: { country: "Sierra Leone", continent_code: "AF", continent: "Africa", maps: ["sierraLeoneLow", "sierraLeoneHigh"] }, SM: { country: "San Marino", continent_code: "EU", continent: "Europe", maps: ["sanMarinoLow", "sanMarinoHigh"] }, SN: { country: "Senegal", continent_code: "AF", continent: "Africa", maps: ["senegalLow", "senegalHigh"] }, SO: { country: "Somalia", continent_code: "AF", continent: "Africa", maps: ["somaliaLow", "somaliaHigh"] }, SR: { country: "Suriname", continent_code: "SA", continent: "South America", maps: ["surinameLow", "surinameHigh"] }, SS: { country: "South Sudan", continent_code: "AF", continent: "Africa", maps: ["southSudanLow", "southSudanHigh", "southSudan2015Low", "southSudan2015High"] }, ST: { country: "Sao Tome and Principe", continent_code: "AF", continent: "Africa", maps: ["saoTomePrincipeLow", "saoTomePrincipeHigh"] }, SV: { country: "El Salvador", continent_code: "NA", continent: "North America", maps: ["elSalvadorLow", "elSalvadorHigh"] }, SX: { country: "Sint Maarten (Dutch Part)", continent_code: "NA", continent: "North America", maps: [] }, SY: { country: "Syrian Arab Republic", continent_code: "AS", continent: "Asia", maps: ["syriaLow", "syriaHigh"] }, SZ: { country: "Swaziland", continent_code: "AF", continent: "Africa", maps: ["eswatiniLow", "eswatiniHigh"] }, TC: { country: "Turks and Caicos Islands", continent_code: "NA", continent: "North America", maps: [] }, TD: { country: "Chad", continent_code: "AF", continent: "Africa", maps: ["chadLow", "chadHigh"] }, TF: { country: "French Southern Territories", continent_code: "AN", continent: "Antarctica", maps: [] }, TG: { country: "Togo", continent_code: "AF", continent: "Africa", maps: ["togoLow", "togoHigh"] }, TH: { country: "Thailand", continent_code: "AS", continent: "Asia", maps: ["thailandLow", "thailandHigh"] }, TJ: { country: "Tajikistan", continent_code: "AS", continent: "Asia", maps: ["tajikistanLow", "tajikistanHigh"] }, TK: { country: "Tokelau", continent_code: "OC", continent: "Oceania", maps: [] }, TL: { country: "Timor-Leste", continent_code: "AS", continent: "Asia", maps: ["timorLesteLow", "timorLesteHigh"] }, TM: { country: "Turkmenistan", continent_code: "AS", continent: "Asia", maps: ["turkmenistanLow", "turkmenistanHigh"] }, TN: { country: "Tunisia", continent_code: "AF", continent: "Africa", maps: ["tunisiaLow", "tunisiaHigh"] }, TO: { country: "Tonga", continent_code: "OC", continent: "Oceania", maps: [] }, TR: { country: "Turkey", continent_code: "EU", continent: "Europe", maps: ["turkeyLow", "turkeyHigh"] }, TT: { country: "Trinidad and Tobago", continent_code: "NA", continent: "North America", maps: [] }, TV: { country: "Tuvalu", continent_code: "OC", continent: "Oceania", maps: [] }, TW: { country: "Taiwan", continent_code: "AS", continent: "Asia", maps: [] }, TZ: { country: "Tanzania, United Republic of", continent_code: "AF", continent: "Africa", maps: ["tanzaniaLow", "tanzaniaHigh"] }, UA: { country: "Ukraine", continent_code: "EU", continent: "Europe", maps: ["ukraineLow", "ukraineHigh"] }, UG: { country: "Uganda", continent_code: "AF", continent: "Africa", maps: [] }, UM: { country: "United States Minor Outlying Islands", continent_code: "OC", continent: "Oceania", maps: [] }, US: { country: "United States", continent_code: "NA", continent: "North America", maps: ["usaLow", "usaHigh", "usaTerritoriesLow", "usaTerritoriesHigh", "usaTerritories2Low", "usaTerritories2High"] }, UY: { country: "Uruguay", continent_code: "SA", continent: "South America", maps: [] }, UZ: { country: "Uzbekistan", continent_code: "AS", continent: "Asia", maps: ["uzbekistanLow", "uzbekistanHigh"] }, VA: { country: "Holy See (Vatican City State)", continent_code: "EU", continent: "Europe", maps: ["vaticanLow", "vaticanHigh"] }, VC: { country: "Saint Vincent and the Grenadines", continent_code: "NA", continent: "North America", maps: ["saintVincentLow", "saintVincentHigh"] }, VE: { country: "Venezuela, Bolivarian Republic of", continent_code: "SA", continent: "South America", maps: ["venezuelaLow", "venezuelaHigh"] }, VG: { country: "Virgin Islands, British", continent_code: "NA", continent: "North America", maps: [] }, VI: { country: "Virgin Islands, U.S.", continent_code: "NA", continent: "North America", maps: [] }, VN: { country: "Viet Nam", continent_code: "AS", continent: "Asia", maps: ["vietnamLow", "vietnamHigh"] }, VU: { country: "Vanuatu", continent_code: "OC", continent: "Oceania", maps: [] }, WF: { country: "Wallis and Futuna", continent_code: "OC", continent: "Oceania", maps: [] }, WS: { country: "Samoa", continent_code: "OC", continent: "Oceania", maps: ["samoaLow", "samoaHigh"] }, YE: { country: "Yemen", continent_code: "AS", continent: "Asia", maps: ["yemenLow", "yemenHigh"] }, YT: { country: "Mayotte", continent_code: "AF", continent: "Africa", maps: [] }, ZA: { country: "South Africa", continent_code: "AF", continent: "Africa", maps: ["southAfricaLow", "southAfricaHigh"] }, ZM: { country: "Zambia", continent_code: "AF", continent: "Africa", maps: ["zambiaLow", "zambiaHigh"] }, ZW: { country: "Zimbabwe", continent_code: "AF", continent: "Africa", maps: ["zimbabweLow", "zimbabweHigh"] }, XK: { country: "Kosovo", continent_code: "EU", continent: "Europe", maps: ["kosovoLow", "kosovoHigh"] } }; window.am4geodata_data_countries2 = i } }, ["h34k"]); //# sourceMappingURL=countries2.js.map
/* american fuzzy lop - LD_PRELOAD for fuzzing argv in binaries ------------------------------------------------------------ Copyright 2019 Kjell Braden <afflux@pentabarf.de> 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 */ #define _GNU_SOURCE /* for RTLD_NEXT */ #include <dlfcn.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "argv-fuzz-inl.h" int __libc_start_main(int (*main)(int, char **, char **), int argc, char **argv, void (*init)(void), void (*fini)(void), void (*rtld_fini)(void), void *stack_end) { int (*orig)(int (*main)(int, char **, char **), int argc, char **argv, void (*init)(void), void (*fini)(void), void (*rtld_fini)(void), void *stack_end); int sub_argc; char **sub_argv; (void)argc; (void)argv; orig = dlsym(RTLD_NEXT, __func__); if (!orig) { fprintf(stderr, "hook did not find original %s: %s\n", __func__, dlerror()); exit(EXIT_FAILURE); } sub_argv = afl_init_argv(&sub_argc); return orig(main, sub_argc, sub_argv, init, fini, rtld_fini, stack_end); }
import sys import time import rospy import rosutils import numpy as np from scipy.spatial.transform import Rotation if len(sys.argv) > 1: master_uri = sys.argv[1] else: master_uri = "http://localhost:11311" node = rosutils.RosNode("exploration_stack", master_uri, wait_time=1.5) node.stopSimulation() rospy.sleep(1.0) node.startSimulation() rospy.sleep(1.0) print("simulation started.") node.initArmPose() node.handOpenPose() scales = np.linspace(1.0, 2.0, 10) depth_prev = [] depth_next = [] rgb_prev = [] rgb_next = [] for obj_i in range(1, 6): for s_i in scales: for obj_j in range(6, 11): for s_j in scales: start = time.time() print(obj_i, s_i, obj_j, s_j) size_i = s_i * 0.1 size_j = s_j * 0.1 loc_i = [-0.75, -0.15, 0.7+size_i/2] loc_j = [-0.75, 0.16, 0.7+size_j/2] node.generateObject(obj_i, s_i, loc_i) node.generateObject(obj_j, s_j, loc_j) depth_prev.append(node.getDepthImage(8)) rgb_prev.append(node.getRGBImage()) if obj_j == 4: quat = Rotation.from_euler("z", 90, degrees=True).as_quat().tolist() else: quat = [0., 0., 0., 1.] node.handOpenPose() node.move([-0.75, 0.16, 1.0]+quat) if obj_j in [2, 3, 5]: multiplier = 0.95 else: multiplier = 0.75 node.move([-0.75, 0.16, 0.7+multiplier*size_j]+quat) node.handGraspPose() node.move([-0.75, 0.16, 0.7+size_i+size_j+0.05]+quat) node.move([-0.75, -0.15, 0.7+size_i+size_j+0.05]+quat) node.handOpenPose() node.initArmPose() node.wait(1.0) depth_next.append(node.getDepthImage(8)) rgb_next.append(node.getRGBImage()) node.stopSimulation() rospy.sleep(2) node.startSimulation() rospy.sleep(2) end = time.time() print(end-start) np.save("data/exploration_second/depth_prev.npy", depth_prev) np.save("data/exploration_second/depth_next.npy", depth_next) np.save("data/exploration_second/rgb_prev.npy", rgb_prev) np.save("data/exploration_second/rgb_next.npy", rgb_next) node.stopSimulation() print("simulation stopped.")
# Copyright (c) 2014 The Bitcoin Core developers # Copyright (c) 2014-2015 The Dash developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Helpful routines for regression testing # # Add python-bitcoinrpc to module search path: import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc")) from decimal import Decimal, ROUND_DOWN import json import random import shutil import subprocess import time import re from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import * def p2p_port(n): return 11000 + n + os.getpid()%999 def rpc_port(n): return 12000 + n + os.getpid()%999 def check_json_precision(): """Make sure json library being used does not lose precision converting BTC values""" n = Decimal("20000000.00000003") satoshis = int(json.loads(json.dumps(float(n)))*1.0e8) if satoshis != 2000000000000003: raise RuntimeError("JSON encode/decode loses precision") def sync_blocks(rpc_connections): """ Wait until everybody has the same block count """ while True: counts = [ x.getblockcount() for x in rpc_connections ] if counts == [ counts[0] ]*len(counts): break time.sleep(1) def sync_mempools(rpc_connections): """ Wait until everybody has the same transactions in their memory pools """ while True: pool = set(rpc_connections[0].getrawmempool()) num_match = 1 for i in range(1, len(rpc_connections)): if set(rpc_connections[i].getrawmempool()) == pool: num_match = num_match+1 if num_match == len(rpc_connections): break time.sleep(1) bitcoind_processes = {} def initialize_datadir(dirname, n): datadir = os.path.join(dirname, "node"+str(n)) if not os.path.isdir(datadir): os.makedirs(datadir) with open(os.path.join(datadir, "dash.conf"), 'w') as f: f.write("regtest=1\n"); f.write("rpcuser=rt\n"); f.write("rpcpassword=rt\n"); f.write("port="+str(p2p_port(n))+"\n"); f.write("rpcport="+str(rpc_port(n))+"\n"); return datadir def initialize_chain(test_dir): """ Create (or copy from cache) a 200-block-long chain and 4 wallets. dashd and dash-cli must be in search path. """ if not os.path.isdir(os.path.join("cache", "node0")): devnull = open("/dev/null", "w+") # Create cache directories, run dashds: for i in range(4): datadir=initialize_datadir("cache", i) args = [ os.getenv("BITCOIND", "dashd"), "-keypool=1", "-datadir="+datadir, "-discover=0" ] if i > 0: args.append("-connect=127.0.0.1:"+str(p2p_port(0))) bitcoind_processes[i] = subprocess.Popen(args) subprocess.check_call([ os.getenv("BITCOINCLI", "dash-cli"), "-datadir="+datadir, "-rpcwait", "getblockcount"], stdout=devnull) devnull.close() rpcs = [] for i in range(4): try: url = "http://rt:rt@127.0.0.1:%d"%(rpc_port(i),) rpcs.append(AuthServiceProxy(url)) except: sys.stderr.write("Error connecting to "+url+"\n") sys.exit(1) # Create a 200-block-long chain; each of the 4 nodes # gets 25 mature blocks and 25 immature. # blocks are created with timestamps 156 seconds apart, starting # at 1 Jan 2015 block_time = 1420070400 for i in range(2): for peer in range(4): for j in range(25): set_node_times(rpcs, block_time) rpcs[peer].setgenerate(True, 1) block_time += 156 # Must sync before next peer starts generating blocks sync_blocks(rpcs) # Shut them down, and clean up cache directories: stop_nodes(rpcs) wait_bitcoinds() for i in range(4): os.remove(log_filename("cache", i, "debug.log")) os.remove(log_filename("cache", i, "db.log")) os.remove(log_filename("cache", i, "peers.dat")) os.remove(log_filename("cache", i, "fee_estimates.dat")) for i in range(4): from_dir = os.path.join("cache", "node"+str(i)) to_dir = os.path.join(test_dir, "node"+str(i)) shutil.copytree(from_dir, to_dir) initialize_datadir(test_dir, i) # Overwrite port/rpcport in dash.conf def initialize_chain_clean(test_dir, num_nodes): """ Create an empty blockchain and num_nodes wallets. Useful if a test case wants complete control over initialization. """ for i in range(num_nodes): datadir=initialize_datadir(test_dir, i) def _rpchost_to_args(rpchost): '''Convert optional IP:port spec to rpcconnect/rpcport args''' if rpchost is None: return [] match = re.match('(\[[0-9a-fA-f:]+\]|[^:]+)(?::([0-9]+))?$', rpchost) if not match: raise ValueError('Invalid RPC host spec ' + rpchost) rpcconnect = match.group(1) rpcport = match.group(2) if rpcconnect.startswith('['): # remove IPv6 [...] wrapping rpcconnect = rpcconnect[1:-1] rv = ['-rpcconnect=' + rpcconnect] if rpcport: rv += ['-rpcport=' + rpcport] return rv def start_node(i, dirname, extra_args=None, rpchost=None): """ Start a dashd and return RPC connection to it """ datadir = os.path.join(dirname, "node"+str(i)) args = [ os.getenv("BITCOIND", "dashd"), "-datadir="+datadir, "-keypool=1", "-discover=0", "-rest" ] if extra_args is not None: args.extend(extra_args) bitcoind_processes[i] = subprocess.Popen(args) devnull = open("/dev/null", "w+") subprocess.check_call([ os.getenv("BITCOINCLI", "dash-cli"), "-datadir="+datadir] + _rpchost_to_args(rpchost) + ["-rpcwait", "getblockcount"], stdout=devnull) devnull.close() url = "http://rt:rt@%s:%d" % (rpchost or '127.0.0.1', rpc_port(i)) proxy = AuthServiceProxy(url) proxy.url = url # store URL on proxy for info return proxy def start_nodes(num_nodes, dirname, extra_args=None, rpchost=None): """ Start multiple dashds, return RPC connections to them """ if extra_args is None: extra_args = [ None for i in range(num_nodes) ] return [ start_node(i, dirname, extra_args[i], rpchost) for i in range(num_nodes) ] def log_filename(dirname, n_node, logname): return os.path.join(dirname, "node"+str(n_node), "regtest", logname) def stop_node(node, i): node.stop() bitcoind_processes[i].wait() del bitcoind_processes[i] def stop_nodes(nodes): for node in nodes: node.stop() del nodes[:] # Emptying array closes connections as a side effect def set_node_times(nodes, t): for node in nodes: node.setmocktime(t) def wait_bitcoinds(): # Wait for all bitcoinds to cleanly exit for bitcoind in bitcoind_processes.values(): bitcoind.wait() bitcoind_processes.clear() def connect_nodes(from_connection, node_num): ip_port = "127.0.0.1:"+str(p2p_port(node_num)) from_connection.addnode(ip_port, "onetry") # poll until version handshake complete to avoid race conditions # with transaction relaying while any(peer['version'] == 0 for peer in from_connection.getpeerinfo()): time.sleep(0.1) def connect_nodes_bi(nodes, a, b): connect_nodes(nodes[a], b) connect_nodes(nodes[b], a) def find_output(node, txid, amount): """ Return index to output of txid with value amount Raises exception if there is none. """ txdata = node.getrawtransaction(txid, 1) for i in range(len(txdata["vout"])): if txdata["vout"][i]["value"] == amount: return i raise RuntimeError("find_output txid %s : %s not found"%(txid,str(amount))) def gather_inputs(from_node, amount_needed, confirmations_required=1): """ Return a random set of unspent txouts that are enough to pay amount_needed """ assert(confirmations_required >=0) utxo = from_node.listunspent(confirmations_required) random.shuffle(utxo) inputs = [] total_in = Decimal("0.00000000") while total_in < amount_needed and len(utxo) > 0: t = utxo.pop() total_in += t["amount"] inputs.append({ "txid" : t["txid"], "vout" : t["vout"], "address" : t["address"] } ) if total_in < amount_needed: raise RuntimeError("Insufficient funds: need %d, have %d"%(amount_needed, total_in)) return (total_in, inputs) def make_change(from_node, amount_in, amount_out, fee): """ Create change output(s), return them """ outputs = {} amount = amount_out+fee change = amount_in - amount if change > amount*2: # Create an extra change output to break up big inputs change_address = from_node.getnewaddress() # Split change in two, being careful of rounding: outputs[change_address] = Decimal(change/2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN) change = amount_in - amount - outputs[change_address] if change > 0: outputs[from_node.getnewaddress()] = change return outputs def send_zeropri_transaction(from_node, to_node, amount, fee): """ Create&broadcast a zero-priority transaction. Returns (txid, hex-encoded-txdata) Ensures transaction is zero-priority by first creating a send-to-self, then using it's output """ # Create a send-to-self with confirmed inputs: self_address = from_node.getnewaddress() (total_in, inputs) = gather_inputs(from_node, amount+fee*2) outputs = make_change(from_node, total_in, amount+fee, fee) outputs[self_address] = float(amount+fee) self_rawtx = from_node.createrawtransaction(inputs, outputs) self_signresult = from_node.signrawtransaction(self_rawtx) self_txid = from_node.sendrawtransaction(self_signresult["hex"], True) vout = find_output(from_node, self_txid, amount+fee) # Now immediately spend the output to create a 1-input, 1-output # zero-priority transaction: inputs = [ { "txid" : self_txid, "vout" : vout } ] outputs = { to_node.getnewaddress() : float(amount) } rawtx = from_node.createrawtransaction(inputs, outputs) signresult = from_node.signrawtransaction(rawtx) txid = from_node.sendrawtransaction(signresult["hex"], True) return (txid, signresult["hex"]) def random_zeropri_transaction(nodes, amount, min_fee, fee_increment, fee_variants): """ Create a random zero-priority transaction. Returns (txid, hex-encoded-transaction-data, fee) """ from_node = random.choice(nodes) to_node = random.choice(nodes) fee = min_fee + fee_increment*random.randint(0,fee_variants) (txid, txhex) = send_zeropri_transaction(from_node, to_node, amount, fee) return (txid, txhex, fee) def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants): """ Create a random transaction. Returns (txid, hex-encoded-transaction-data, fee) """ from_node = random.choice(nodes) to_node = random.choice(nodes) fee = min_fee + fee_increment*random.randint(0,fee_variants) (total_in, inputs) = gather_inputs(from_node, amount+fee) outputs = make_change(from_node, total_in, amount, fee) outputs[to_node.getnewaddress()] = float(amount) rawtx = from_node.createrawtransaction(inputs, outputs) signresult = from_node.signrawtransaction(rawtx) txid = from_node.sendrawtransaction(signresult["hex"], True) return (txid, signresult["hex"], fee) def assert_equal(thing1, thing2): if thing1 != thing2: raise AssertionError("%s != %s"%(str(thing1),str(thing2))) def assert_greater_than(thing1, thing2): if thing1 <= thing2: raise AssertionError("%s <= %s"%(str(thing1),str(thing2))) def assert_raises(exc, fun, *args, **kwds): try: fun(*args, **kwds) except exc: pass except Exception as e: raise AssertionError("Unexpected exception raised: "+type(e).__name__) else: raise AssertionError("No exception raised")
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/fishing/bait/base/shared_bait_base.iff" result.attribute_template_id = -1 result.stfName("item_n","fishing_bait") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
import setuptools setuptools.setup( name="SimpleCalc-CodeJack", # Replace with your own username version="0.0.1", author="CodeJack", author_email="chandanrajsingh19@gmail.com", description="Calculator in PyQt5", long_description="A simple calculator made using PyQt5", long_description_content_type="text/markdown", url="https://github.com/codejack-CR/SimpleCalc", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], python_requires='>=3.6', )
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # pylint: disable=protected-access import collections import datetime import logging import os import random import string import tempfile import unittest.mock as mock import uuid from unittest import TestCase import elasticsearch.exceptions from esrally import config, metrics, track, exceptions, paths from esrally.metrics import GlobalStatsCalculator from esrally.track import Task, Operation, Challenge, Track class MockClientFactory: def __init__(self, cfg): self._es = mock.create_autospec(metrics.EsClient) def create(self): return self._es class DummyIndexTemplateProvider: def __init__(self, cfg): pass def metrics_template(self): return "metrics-test-template" def races_template(self): return "races-test-template" def results_template(self): return "results-test-template" class StaticClock: NOW = 1453362707 @staticmethod def now(): return StaticClock.NOW @staticmethod def stop_watch(): return StaticStopWatch() class StaticStopWatch: def start(self): pass def stop(self): pass def split_time(self): return 0 def total_time(self): return 0 class TransportErrors: err_return_codes = {502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 429: "Too Many Requests"} def __init__(self, max_err_responses=10): self.max_err_responses = max_err_responses # allow duplicates in list of error codes self.rnd_err_codes = [ random.choice(list(TransportErrors.err_return_codes)) for _ in range(self.max_err_responses) ] @property def code_list(self): return self.rnd_err_codes @property def side_effects(self): side_effect_list = [ elasticsearch.exceptions.TransportError(rnd_code, TransportErrors.err_return_codes[rnd_code]) for rnd_code in self.rnd_err_codes ] side_effect_list.append("success") return side_effect_list class ExtractUserTagsTests(TestCase): def test_no_tags_returns_empty_dict(self): cfg = config.Config() self.assertEqual(0, len(metrics.extract_user_tags_from_config(cfg))) def test_missing_comma_raises_error(self): cfg = config.Config() cfg.add(config.Scope.application, "race", "user.tag", "invalid") with self.assertRaises(exceptions.SystemSetupError) as ctx: metrics.extract_user_tags_from_config(cfg) self.assertEqual("User tag keys and values have to separated by a ':'. Invalid value [invalid]", ctx.exception.args[0]) def test_missing_value_raises_error(self): cfg = config.Config() cfg.add(config.Scope.application, "race", "user.tag", "invalid1,invalid2") with self.assertRaises(exceptions.SystemSetupError) as ctx: metrics.extract_user_tags_from_config(cfg) self.assertEqual("User tag keys and values have to separated by a ':'. Invalid value [invalid1,invalid2]", ctx.exception.args[0]) def test_extracts_proper_user_tags(self): cfg = config.Config() cfg.add(config.Scope.application, "race", "user.tag", "os:Linux,cpu:ARM") self.assertDictEqual({"os": "Linux", "cpu": "ARM"}, metrics.extract_user_tags_from_config(cfg)) class EsClientTests(TestCase): class TransportMock: def __init__(self, hosts): self.hosts = hosts class ClientMock: def __init__(self, hosts): self.transport = EsClientTests.TransportMock(hosts) @mock.patch("esrally.client.EsClientFactory") def test_config_opts_parsing(self, client_esclientfactory): cfg = config.Config() _datastore_host = ".".join([str(random.randint(1, 254)) for _ in range(4)]) _datastore_port = random.randint(1024, 65535) _datastore_secure = random.choice(["True", "true"]) _datastore_user = "".join([random.choice(string.ascii_letters) for _ in range(8)]) _datastore_password = "".join([random.choice(string.ascii_letters + string.digits + "_-@#$/") for _ in range(12)]) _datastore_verify_certs = random.choice([True, False]) cfg.add(config.Scope.applicationOverride, "reporting", "datastore.host", _datastore_host) cfg.add(config.Scope.applicationOverride, "reporting", "datastore.port", _datastore_port) cfg.add(config.Scope.applicationOverride, "reporting", "datastore.secure", _datastore_secure) cfg.add(config.Scope.applicationOverride, "reporting", "datastore.user", _datastore_user) cfg.add(config.Scope.applicationOverride, "reporting", "datastore.password", _datastore_password) if not _datastore_verify_certs: cfg.add(config.Scope.applicationOverride, "reporting", "datastore.ssl.verification_mode", "none") metrics.EsClientFactory(cfg) expected_client_options = { "use_ssl": True, "timeout": 120, "basic_auth_user": _datastore_user, "basic_auth_password": _datastore_password, "verify_certs": _datastore_verify_certs } client_esclientfactory.assert_called_with( hosts=[{"host": _datastore_host, "port": _datastore_port}], client_options=expected_client_options ) def test_raises_sytem_setup_error_on_connection_problems(self): def raise_connection_error(): raise elasticsearch.exceptions.ConnectionError("unit-test") client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9200"}])) with self.assertRaises(exceptions.SystemSetupError) as ctx: client.guarded(raise_connection_error) self.assertEqual("Could not connect to your Elasticsearch metrics store. Please check that it is running on host [127.0.0.1] at " "port [9200] or fix the configuration in [%s/rally.ini]." % paths.rally_confdir(), ctx.exception.args[0]) def test_raises_sytem_setup_error_on_authentication_problems(self): def raise_authentication_error(): raise elasticsearch.exceptions.AuthenticationException("unit-test") client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9243"}])) with self.assertRaises(exceptions.SystemSetupError) as ctx: client.guarded(raise_authentication_error) self.assertEqual("The configured user could not authenticate against your Elasticsearch metrics store running on host [127.0.0.1] " "at port [9243] (wrong password?). Please fix the configuration in [%s/rally.ini]." % paths.rally_confdir(), ctx.exception.args[0]) def test_raises_sytem_setup_error_on_authorization_problems(self): def raise_authorization_error(): raise elasticsearch.exceptions.AuthorizationException("unit-test") client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9243"}])) with self.assertRaises(exceptions.SystemSetupError) as ctx: client.guarded(raise_authorization_error) self.assertEqual("The configured user does not have enough privileges to run the operation [raise_authorization_error] against " "your Elasticsearch metrics store running on host [127.0.0.1] at port [9243]. Please adjust your x-pack " "configuration or specify a user with enough privileges in the configuration in [%s/rally.ini]." % paths.rally_confdir(), ctx.exception.args[0]) def test_raises_rally_error_on_unknown_problems(self): def raise_unknown_error(): raise elasticsearch.exceptions.SerializationError("unit-test") client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9243"}])) with self.assertRaises(exceptions.RallyError) as ctx: client.guarded(raise_unknown_error) self.assertEqual("An unknown error occurred while running the operation [raise_unknown_error] against your Elasticsearch metrics " "store on host [127.0.0.1] at port [9243].", ctx.exception.args[0]) def test_retries_on_various_transport_errors(self): @mock.patch("random.random") @mock.patch("esrally.time.sleep") def test_transport_error_retries(side_effect, expected_logging_calls, expected_sleep_calls, mocked_sleep, mocked_random): # should return on first success operation = mock.Mock(side_effect=side_effect) # Disable additional randomization time in exponential backoff calls mocked_random.return_value = 0 client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9243"}])) logger = logging.getLogger("esrally.metrics") with mock.patch.object(logger, "debug") as mocked_debug_logger: test_result = client.guarded(operation) mocked_sleep.assert_has_calls(expected_sleep_calls) mocked_debug_logger.assert_has_calls( expected_logging_calls, any_order=True ) self.assertEqual("success", test_result) max_retry = 10 all_err_codes = TransportErrors.err_return_codes transport_errors = TransportErrors(max_err_responses=max_retry) rnd_err_codes = transport_errors.code_list rnd_side_effects = transport_errors.side_effects rnd_mocked_logger_calls = [] # The sec to sleep for 10 transport errors is # [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] ~> 17.05min in total sleep_slots = [float(2 ** i) for i in range(0, max_retry)] mocked_sleep_calls = [mock.call(sleep_slots[i]) for i in range(0, max_retry)] for rnd_err_idx, rnd_err_code in enumerate(rnd_err_codes): # List of logger.debug calls to expect rnd_mocked_logger_calls.append( mock.call("%s (code: %d) in attempt [%d/%d]. Sleeping for [%f] seconds.", all_err_codes[rnd_err_code], rnd_err_code, rnd_err_idx + 1, max_retry + 1, sleep_slots[rnd_err_idx]) ) # pylint: disable=no-value-for-parameter test_transport_error_retries(rnd_side_effects, rnd_mocked_logger_calls, mocked_sleep_calls) @mock.patch("esrally.time.sleep") def test_fails_after_too_many_errors(self, mocked_sleep): def random_transport_error(rnd_resp_code): raise elasticsearch.exceptions.TransportError(rnd_resp_code, TransportErrors.err_return_codes[rnd_resp_code]) client = metrics.EsClient(EsClientTests.ClientMock([{"host": "127.0.0.1", "port": "9243"}])) rnd_code = random.choice(list(TransportErrors.err_return_codes)) with self.assertRaises(exceptions.RallyError) as ctx: client.guarded(random_transport_error, rnd_code) self.assertEqual("A transport error occurred while running the operation " "[random_transport_error] against your Elasticsearch metrics " "store on host [127.0.0.1] at port [9243].", ctx.exception.args[0]) class EsMetricsTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "6ebc6e53-ee20-4b0c-99b4-09697987e9f4" def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "system", "env.name", "unittest") self.cfg.add(config.Scope.application, "track", "params", {"shard-count": 3}) self.metrics_store = metrics.EsMetricsStore(self.cfg, client_factory_class=MockClientFactory, index_template_provider_class=DummyIndexTemplateProvider, clock=StaticClock) # get hold of the mocked client... self.es_mock = self.metrics_store._client self.es_mock.exists.return_value = False def test_put_value_without_meta_info(self): throughput = 5000 self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append", "defaults", create=True) self.metrics_store.put_value_cluster_level("indexing_throughput", throughput, "docs/s") expected_doc = { "@timestamp": StaticClock.NOW * 1000, "race-id": EsMetricsTests.RACE_ID, "race-timestamp": "20160131T000000Z", "relative-time": 0, "environment": "unittest", "sample-type": "normal", "track": "test", "track-params": { "shard-count": 3 }, "challenge": "append", "car": "defaults", "name": "indexing_throughput", "value": throughput, "unit": "docs/s", "meta": {} } self.metrics_store.close() self.es_mock.exists.assert_called_with(index="rally-metrics-2016-01") self.es_mock.create_index.assert_called_with(index="rally-metrics-2016-01") self.es_mock.bulk_index.assert_called_with(index="rally-metrics-2016-01", doc_type="_doc", items=[expected_doc]) def test_put_value_with_explicit_timestamps(self): throughput = 5000 self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append", "defaults", create=True) self.metrics_store.put_value_cluster_level(name="indexing_throughput", value=throughput, unit="docs/s", absolute_time=0, relative_time=10) expected_doc = { "@timestamp": 0, "race-id": EsMetricsTests.RACE_ID, "race-timestamp": "20160131T000000Z", "relative-time": 10000000, "environment": "unittest", "sample-type": "normal", "track": "test", "track-params": { "shard-count": 3 }, "challenge": "append", "car": "defaults", "name": "indexing_throughput", "value": throughput, "unit": "docs/s", "meta": {} } self.metrics_store.close() self.es_mock.exists.assert_called_with(index="rally-metrics-2016-01") self.es_mock.create_index.assert_called_with(index="rally-metrics-2016-01") self.es_mock.bulk_index.assert_called_with(index="rally-metrics-2016-01", doc_type="_doc", items=[expected_doc]) def test_put_value_with_meta_info(self): throughput = 5000 # add a user-defined tag self.cfg.add(config.Scope.application, "race", "user.tag", "intention:testing,disk_type:hdd") self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append", "defaults", create=True) # Ensure we also merge in cluster level meta info self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "source_revision", "abc123") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node0", "os_name", "Darwin") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node0", "os_version", "15.4.0") # Ensure we separate node level info by node self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node1", "os_name", "Linux") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node1", "os_version", "4.2.0-18-generic") self.metrics_store.put_value_node_level("node0", "indexing_throughput", throughput, "docs/s") expected_doc = { "@timestamp": StaticClock.NOW * 1000, "race-id": EsMetricsTests.RACE_ID, "race-timestamp": "20160131T000000Z", "relative-time": 0, "environment": "unittest", "sample-type": "normal", "track": "test", "track-params": { "shard-count": 3 }, "challenge": "append", "car": "defaults", "name": "indexing_throughput", "value": throughput, "unit": "docs/s", "meta": { "tag_intention": "testing", "tag_disk_type": "hdd", "source_revision": "abc123", "os_name": "Darwin", "os_version": "15.4.0" } } self.metrics_store.close() self.es_mock.exists.assert_called_with(index="rally-metrics-2016-01") self.es_mock.create_index.assert_called_with(index="rally-metrics-2016-01") self.es_mock.bulk_index.assert_called_with(index="rally-metrics-2016-01", doc_type="_doc", items=[expected_doc]) def test_put_doc_no_meta_data(self): self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append", "defaults", create=True) self.metrics_store.put_doc(doc={ "name": "custom_metric", "total": 1234567, "per-shard": [17, 18, 1289, 273, 222], "unit": "byte" }) expected_doc = { "@timestamp": StaticClock.NOW * 1000, "race-id": EsMetricsTests.RACE_ID, "race-timestamp": "20160131T000000Z", "relative-time": 0, "environment": "unittest", "track": "test", "track-params": { "shard-count": 3 }, "challenge": "append", "car": "defaults", "name": "custom_metric", "total": 1234567, "per-shard": [17, 18, 1289, 273, 222], "unit": "byte" } self.metrics_store.close() self.es_mock.exists.assert_called_with(index="rally-metrics-2016-01") self.es_mock.create_index.assert_called_with(index="rally-metrics-2016-01") self.es_mock.bulk_index.assert_called_with(index="rally-metrics-2016-01", doc_type="_doc", items=[expected_doc]) def test_put_doc_with_metadata(self): # add a user-defined tag self.cfg.add(config.Scope.application, "race", "user.tag", "intention:testing,disk_type:hdd") self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append", "defaults", create=True) # Ensure we also merge in cluster level meta info self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "source_revision", "abc123") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node0", "os_name", "Darwin") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node0", "os_version", "15.4.0") # Ensure we separate node level info by node self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node1", "os_name", "Linux") self.metrics_store.add_meta_info(metrics.MetaInfoScope.node, "node1", "os_version", "4.2.0-18-generic") self.metrics_store.put_doc(doc={ "name": "custom_metric", "total": 1234567, "per-shard": [17, 18, 1289, 273, 222], "unit": "byte" }, level=metrics.MetaInfoScope.node, node_name="node0", meta_data={ "node_type": "hot" }) expected_doc = { "@timestamp": StaticClock.NOW * 1000, "race-id": EsMetricsTests.RACE_ID, "race-timestamp": "20160131T000000Z", "relative-time": 0, "environment": "unittest", "track": "test", "track-params": { "shard-count": 3 }, "challenge": "append", "car": "defaults", "name": "custom_metric", "total": 1234567, "per-shard": [17, 18, 1289, 273, 222], "unit": "byte", "meta": { "tag_intention": "testing", "tag_disk_type": "hdd", "source_revision": "abc123", "os_name": "Darwin", "os_version": "15.4.0", "node_type": "hot" } } self.metrics_store.close() self.es_mock.exists.assert_called_with(index="rally-metrics-2016-01") self.es_mock.create_index.assert_called_with(index="rally-metrics-2016-01") self.es_mock.bulk_index.assert_called_with(index="rally-metrics-2016-01", doc_type="_doc", items=[expected_doc]) def test_get_value(self): throughput = 5000 search_result = { "hits": { "total": 1, "hits": [ { "_source": { "@timestamp": StaticClock.NOW * 1000, "value": throughput } } ] } } self.es_mock.search = mock.MagicMock(return_value=search_result) self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") expected_query = { "query": { "bool": { "filter": [ { "term": { "race-id": EsMetricsTests.RACE_ID } }, { "term": { "name": "indexing_throughput" } } ] } } } actual_throughput = self.metrics_store.get_one("indexing_throughput") self.es_mock.search.assert_called_with(index="rally-metrics-2016-01", body=expected_query) self.assertEqual(throughput, actual_throughput) def test_get_per_node_value(self): index_size = 5000 search_result = { "hits": { "total": 1, "hits": [ { "_source": { "@timestamp": StaticClock.NOW * 1000, "value": index_size } } ] } } self.es_mock.search = mock.MagicMock(return_value=search_result) self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") expected_query = { "query": { "bool": { "filter": [ { "term": { "race-id": EsMetricsTests.RACE_ID } }, { "term": { "name": "final_index_size_bytes" } }, { "term": { "meta.node_name": "rally-node-3" } } ] } } } actual_index_size = self.metrics_store.get_one("final_index_size_bytes", node_name="rally-node-3") self.es_mock.search.assert_called_with(index="rally-metrics-2016-01", body=expected_query) self.assertEqual(index_size, actual_index_size) def test_get_mean(self): mean_throughput = 1734 search_result = { "hits": { "total": 1, }, "aggregations": { "metric_stats": { "count": 17, "min": 1208, "max": 1839, "avg": mean_throughput, "sum": 28934 } } } self.es_mock.search = mock.MagicMock(return_value=search_result) self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") expected_query = { "query": { "bool": { "filter": [ { "term": { "race-id": EsMetricsTests.RACE_ID } }, { "term": { "name": "indexing_throughput" } } ] } }, "size": 0, "aggs": { "metric_stats": { "stats": { "field": "value" } } } } actual_mean_throughput = self.metrics_store.get_mean("indexing_throughput") self.es_mock.search.assert_called_with(index="rally-metrics-2016-01", body=expected_query) self.assertEqual(mean_throughput, actual_mean_throughput) def test_get_median(self): median_throughput = 30535 search_result = { "hits": { "total": 1, }, "aggregations": { "percentile_stats": { "values": { "50.0": median_throughput } } } } self.es_mock.search = mock.MagicMock(return_value=search_result) self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") expected_query = { "query": { "bool": { "filter": [ { "term": { "race-id": EsMetricsTests.RACE_ID } }, { "term": { "name": "indexing_throughput" } } ] } }, "size": 0, "aggs": { "percentile_stats": { "percentiles": { "field": "value", "percents": ["50.0"] } } } } actual_median_throughput = self.metrics_store.get_median("indexing_throughput") self.es_mock.search.assert_called_with(index="rally-metrics-2016-01", body=expected_query) self.assertEqual(median_throughput, actual_median_throughput) def test_get_error_rate_implicit_zero(self): self.assertEqual(0.0, self._get_error_rate(buckets=[ { "key": 1, "key_as_string": "true", "doc_count": 0 } ])) def test_get_error_rate_explicit_zero(self): self.assertEqual(0.0, self._get_error_rate(buckets=[ { "key": 0, "key_as_string": "false", "doc_count": 0 }, { "key": 1, "key_as_string": "true", "doc_count": 500 } ])) def test_get_error_rate_implicit_one(self): self.assertEqual(1.0, self._get_error_rate(buckets=[ { "key": 0, "key_as_string": "false", "doc_count": 123 } ])) def test_get_error_rate_explicit_one(self): self.assertEqual(1.0, self._get_error_rate(buckets=[ { "key": 0, "key_as_string": "false", "doc_count": 123 }, { "key": 1, "key_as_string": "true", "doc_count": 0 } ])) def test_get_error_rate_mixed(self): self.assertEqual(0.5, self._get_error_rate(buckets=[ { "key": 0, "key_as_string": "false", "doc_count": 500 }, { "key": 1, "key_as_string": "true", "doc_count": 500 } ])) def test_get_error_rate_additional_unknown_key(self): self.assertEqual(0.25, self._get_error_rate(buckets=[ { "key": 0, "key_as_string": "false", "doc_count": 500 }, { "key": 1, "key_as_string": "true", "doc_count": 1500 }, { "key": 2, "key_as_string": "undefined_for_test", "doc_count": 13700 } ])) def _get_error_rate(self, buckets): search_result = { "hits": { "total": 1, }, "aggregations": { "error_rate": { "buckets": buckets } } } self.es_mock.search = mock.MagicMock(return_value=search_result) self.metrics_store.open(EsMetricsTests.RACE_ID, EsMetricsTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") expected_query = { "query": { "bool": { "filter": [ { "term": { "race-id": EsMetricsTests.RACE_ID } }, { "term": { "name": "service_time" } }, { "term": { "task": "scroll_query" } } ] } }, "size": 0, "aggs": { "error_rate": { "terms": { "field": "meta.success" } } } } actual_error_rate = self.metrics_store.get_error_rate("scroll_query") self.es_mock.search.assert_called_with(index="rally-metrics-2016-01", body=expected_query) return actual_error_rate class EsRaceStoreTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "6ebc6e53-ee20-4b0c-99b4-09697987e9f4" class DictHolder: def __init__(self, d): self.d = d def as_dict(self): return self.d def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "system", "env.name", "unittest-env") self.cfg.add(config.Scope.application, "system", "time.start", EsRaceStoreTests.RACE_TIMESTAMP) self.cfg.add(config.Scope.application, "system", "race.id", FileRaceStoreTests.RACE_ID) self.race_store = metrics.EsRaceStore(self.cfg, client_factory_class=MockClientFactory, index_template_provider_class=DummyIndexTemplateProvider, ) # get hold of the mocked client... self.es_mock = self.race_store.client def test_find_existing_race_by_race_id(self): self.es_mock.search.return_value = { "hits": { "total": { "value": 1, "relation": "eq" }, "hits": [ { "_source": { "rally-version": "0.4.4", "environment": "unittest", "race-id": EsRaceStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "pipeline": "from-sources", "track": "unittest", "challenge": "index", "track-revision": "abc1", "car": "defaults", "results": { "young_gc_time": 100, "old_gc_time": 5, } } } ] } } race = self.race_store.find_by_race_id(race_id=EsRaceStoreTests.RACE_ID) self.assertEqual(race.race_id, EsRaceStoreTests.RACE_ID) def test_does_not_find_missing_race_by_race_id(self): self.es_mock.search.return_value = { "hits": { "total": { "value": 0, "relation": "eq" }, "hits": [] } } with self.assertRaisesRegex(exceptions.NotFound, r"No race with race id \[.*\]"): self.race_store.find_by_race_id(race_id="some invalid race id") def test_store_race(self): schedule = [ track.Task("index #1", track.Operation("index", track.OperationType.Bulk)) ] t = track.Track(name="unittest", indices=[track.Index(name="tests", types=["_doc"])], challenges=[track.Challenge(name="index", default=True, schedule=schedule)]) race = metrics.Race(rally_version="0.4.4", rally_revision="123abc", environment_name="unittest", race_id=EsRaceStoreTests.RACE_ID, race_timestamp=EsRaceStoreTests.RACE_TIMESTAMP, pipeline="from-sources", user_tags={"os": "Linux"}, track=t, track_params={"shard-count": 3}, challenge=t.default_challenge, car="defaults", car_params={"heap_size": "512mb"}, plugin_params=None, track_revision="abc1", team_revision="abc12333", distribution_version="5.0.0", distribution_flavor="default", revision="aaaeeef", results=EsRaceStoreTests.DictHolder( { "young_gc_time": 100, "old_gc_time": 5, "op_metrics": [ { "task": "index #1", "operation": "index", "throughput": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" } } ] }) ) self.race_store.store_race(race) expected_doc = { "rally-version": "0.4.4", "rally-revision": "123abc", "environment": "unittest", "race-id": EsRaceStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "pipeline": "from-sources", "user-tags": { "os": "Linux" }, "track": "unittest", "track-params": { "shard-count": 3 }, "challenge": "index", "track-revision": "abc1", "car": "defaults", "car-params": { "heap_size": "512mb" }, "cluster": { "revision": "aaaeeef", "distribution-version": "5.0.0", "distribution-flavor": "default", "team-revision": "abc12333", }, "results": { "young_gc_time": 100, "old_gc_time": 5, "op_metrics": [ { "task": "index #1", "operation": "index", "throughput": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" } } ] } } self.es_mock.index.assert_called_with(index="rally-races-2016-01", doc_type="_doc", id=EsRaceStoreTests.RACE_ID, item=expected_doc) class EsResultsStoreTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "6ebc6e53-ee20-4b0c-99b4-09697987e9f4" def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "system", "env.name", "unittest") self.cfg.add(config.Scope.application, "system", "time.start", EsRaceStoreTests.RACE_TIMESTAMP) self.results_store = metrics.EsResultsStore(self.cfg, client_factory_class=MockClientFactory, index_template_provider_class=DummyIndexTemplateProvider, ) # get hold of the mocked client... self.es_mock = self.results_store.client def test_store_results(self): schedule = [ track.Task("index #1", track.Operation("index", track.OperationType.Bulk)) ] t = track.Track(name="unittest-track", indices=[track.Index(name="tests", types=["_doc"])], challenges=[track.Challenge( name="index", default=True, meta_data={"saturation": "70% saturated"}, schedule=schedule)], meta_data={"track-type": "saturation-degree", "saturation": "oversaturation"}) race = metrics.Race(rally_version="0.4.4", rally_revision="123abc", environment_name="unittest", race_id=EsResultsStoreTests.RACE_ID, race_timestamp=EsResultsStoreTests.RACE_TIMESTAMP, pipeline="from-sources", user_tags={"os": "Linux"}, track=t, track_params=None, challenge=t.default_challenge, car="4gheap", car_params=None, plugin_params={"some-param": True}, track_revision="abc1", team_revision="123ab", distribution_version="5.0.0", distribution_flavor="oss", results=metrics.GlobalStats( { "young_gc_time": 100, "old_gc_time": 5, "op_metrics": [ { "task": "index #1", "operation": "index", # custom op-metric which will override the defaults provided by the race "meta": { "track-type": "saturation-degree", "saturation": "70% saturated", "op-type": "bulk" }, "throughput": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" } } ] }) ) self.results_store.store_results(race) expected_docs = [ { "rally-version": "0.4.4", "rally-revision": "123abc", "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": "oss", "distribution-version": "5.0.0", "distribution-major-version": 5, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "plugin-params": { "some-param": True }, "active": True, "name": "old_gc_time", "value": { "single": 5 }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated" } }, { "rally-version": "0.4.4", "rally-revision": "123abc", "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": "oss", "distribution-version": "5.0.0", "distribution-major-version": 5, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "plugin-params": { "some-param": True }, "active": True, "name": "throughput", "task": "index #1", "operation": "index", "value": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated", "op-type": "bulk" } }, { "rally-version": "0.4.4", "rally-revision": "123abc", "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": "oss", "distribution-version": "5.0.0", "distribution-major-version": 5, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "plugin-params": { "some-param": True }, "active": True, "name": "young_gc_time", "value": { "single": 100 }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated" } } ] self.es_mock.bulk_index.assert_called_with(index="rally-results-2016-01", doc_type="_doc", items=expected_docs) def test_store_results_with_missing_version(self): schedule = [ track.Task("index #1", track.Operation("index", track.OperationType.Bulk)) ] t = track.Track(name="unittest-track", indices=[track.Index(name="tests", types=["_doc"])], challenges=[track.Challenge( name="index", default=True, meta_data={"saturation": "70% saturated"}, schedule=schedule)], meta_data={"track-type": "saturation-degree", "saturation": "oversaturation"}) race = metrics.Race(rally_version="0.4.4", rally_revision=None, environment_name="unittest", race_id=EsResultsStoreTests.RACE_ID, race_timestamp=EsResultsStoreTests.RACE_TIMESTAMP, pipeline="from-sources", user_tags={"os": "Linux"}, track=t, track_params=None, challenge=t.default_challenge, car="4gheap", car_params=None, plugin_params=None, track_revision="abc1", team_revision="123ab", distribution_version=None, distribution_flavor=None, results=metrics.GlobalStats( { "young_gc_time": 100, "old_gc_time": 5, "op_metrics": [ { "task": "index #1", "operation": "index", # custom op-metric which will override the defaults provided by the race "meta": { "track-type": "saturation-degree", "saturation": "70% saturated", "op-type": "bulk" }, "throughput": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" } } ] }) ) self.results_store.store_results(race) expected_docs = [ { "rally-version": "0.4.4", "rally-revision": None, "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": None, "distribution-version": None, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "active": True, "name": "old_gc_time", "value": { "single": 5 }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated" } }, { "rally-version": "0.4.4", "rally-revision": None, "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": None, "distribution-version": None, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "active": True, "name": "throughput", "task": "index #1", "operation": "index", "value": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated", "op-type": "bulk" } }, { "rally-version": "0.4.4", "rally-revision": None, "environment": "unittest", "race-id": EsResultsStoreTests.RACE_ID, "race-timestamp": "20160131T000000Z", "distribution-flavor": None, "distribution-version": None, "user-tags": { "os": "Linux" }, "track": "unittest-track", "team-revision": "123ab", "track-revision": "abc1", "challenge": "index", "car": "4gheap", "active": True, "name": "young_gc_time", "value": { "single": 100 }, "meta": { "track-type": "saturation-degree", "saturation": "70% saturated" } } ] self.es_mock.bulk_index.assert_called_with(index="rally-results-2016-01", doc_type="_doc", items=expected_docs) class InMemoryMetricsStoreTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "6ebc6e53-ee20-4b0c-99b4-09697987e9f4" def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "system", "env.name", "unittest") self.cfg.add(config.Scope.application, "track", "params", {}) self.metrics_store = metrics.InMemoryMetricsStore(self.cfg, clock=StaticClock) def tearDown(self): del self.metrics_store del self.cfg def test_get_value(self): throughput = 5000 self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.put_value_cluster_level("indexing_throughput", 1, "docs/s", sample_type=metrics.SampleType.Warmup) self.metrics_store.put_value_cluster_level("indexing_throughput", throughput, "docs/s") self.metrics_store.put_value_cluster_level("final_index_size", 1000, "GB") self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertEqual(1, self.metrics_store.get_one("indexing_throughput", sample_type=metrics.SampleType.Warmup)) self.assertEqual(throughput, self.metrics_store.get_one("indexing_throughput", sample_type=metrics.SampleType.Normal)) def test_get_percentile(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) for i in range(1, 1001): self.metrics_store.put_value_cluster_level("query_latency", float(i), "ms") self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assert_equal_percentiles("query_latency", [100.0], {100.0: 1000.0}) self.assert_equal_percentiles("query_latency", [99.0], {99.0: 990.0}) self.assert_equal_percentiles("query_latency", [99.9], {99.9: 999.0}) self.assert_equal_percentiles("query_latency", [0.0], {0.0: 1.0}) self.assert_equal_percentiles("query_latency", [99, 99.9, 100], {99: 990.0, 99.9: 999.0, 100: 1000.0}) def test_get_mean(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) for i in range(1, 100): self.metrics_store.put_value_cluster_level("query_latency", float(i), "ms") self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertAlmostEqual(50, self.metrics_store.get_mean("query_latency")) def test_get_median(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) for i in range(1, 1001): self.metrics_store.put_value_cluster_level("query_latency", float(i), "ms") self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertAlmostEqual(500.5, self.metrics_store.get_median("query_latency")) def assert_equal_percentiles(self, name, percentiles, expected_percentiles): actual_percentiles = self.metrics_store.get_percentiles(name, percentiles=percentiles) self.assertEqual(len(expected_percentiles), len(actual_percentiles)) for percentile, actual_percentile_value in actual_percentiles.items(): self.assertAlmostEqual(expected_percentiles[percentile], actual_percentile_value, places=1, msg=str(percentile) + "th percentile differs") def test_externalize_and_bulk_add(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.put_value_cluster_level("final_index_size", 1000, "GB") self.assertEqual(1, len(self.metrics_store.docs)) memento = self.metrics_store.to_externalizable() self.metrics_store.close() del self.metrics_store self.metrics_store = metrics.InMemoryMetricsStore(self.cfg, clock=StaticClock) self.assertEqual(0, len(self.metrics_store.docs)) self.metrics_store.bulk_add(memento) self.assertEqual(1, len(self.metrics_store.docs)) self.assertEqual(1000, self.metrics_store.get_one("final_index_size")) def test_meta_data_per_document(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.add_meta_info(metrics.MetaInfoScope.cluster, None, "cluster-name", "test") self.metrics_store.put_value_cluster_level("final_index_size", 1000, "GB", meta_data={ "fs-block-size-bytes": 512 }) self.metrics_store.put_value_cluster_level("final_bytes_written", 1, "TB", meta_data={ "io-batch-size-kb": 4 }) self.assertEqual(2, len(self.metrics_store.docs)) self.assertEqual({ "cluster-name": "test", "fs-block-size-bytes": 512 }, self.metrics_store.docs[0]["meta"]) self.assertEqual({ "cluster-name": "test", "io-batch-size-kb": 4 }, self.metrics_store.docs[1]["meta"]) def test_get_error_rate_zero_without_samples(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertEqual(0.0, self.metrics_store.get_error_rate("term-query", sample_type=metrics.SampleType.Normal)) def test_get_error_rate_by_sample_type(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Warmup, meta_data={"success": False}) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": True}) self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertEqual(1.0, self.metrics_store.get_error_rate("term-query", sample_type=metrics.SampleType.Warmup)) self.assertEqual(0.0, self.metrics_store.get_error_rate("term-query", sample_type=metrics.SampleType.Normal)) def test_get_error_rate_mixed(self): self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults", create=True) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": True}) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": True}) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": False}) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": True}) self.metrics_store.put_value_cluster_level("service_time", 3.0, "ms", task="term-query", sample_type=metrics.SampleType.Normal, meta_data={"success": True}) self.metrics_store.close() self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-no-conflicts", "defaults") self.assertEqual(0.0, self.metrics_store.get_error_rate("term-query", sample_type=metrics.SampleType.Warmup)) self.assertEqual(0.2, self.metrics_store.get_error_rate("term-query", sample_type=metrics.SampleType.Normal)) class FileRaceStoreTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "6ebc6e53-ee20-4b0c-99b4-09697987e9f4" class DictHolder: def __init__(self, d): self.d = d def as_dict(self): return self.d def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "node", "root.dir", os.path.join(tempfile.gettempdir(), str(uuid.uuid4()))) self.cfg.add(config.Scope.application, "system", "env.name", "unittest-env") self.cfg.add(config.Scope.application, "system", "list.races.max_results", 100) self.cfg.add(config.Scope.application, "system", "time.start", FileRaceStoreTests.RACE_TIMESTAMP) self.cfg.add(config.Scope.application, "system", "race.id", FileRaceStoreTests.RACE_ID) self.race_store = metrics.FileRaceStore(self.cfg) def test_race_not_found(self): with self.assertRaisesRegex(exceptions.NotFound, r"No race with race id \[.*\]"): # did not store anything yet self.race_store.find_by_race_id(FileRaceStoreTests.RACE_ID) def test_store_race(self): schedule = [ track.Task("index #1", track.Operation("index", track.OperationType.Bulk)) ] t = track.Track(name="unittest", indices=[track.Index(name="tests", types=["_doc"])], challenges=[track.Challenge(name="index", default=True, schedule=schedule)]) race = metrics.Race(rally_version="0.4.4", rally_revision="123abc", environment_name="unittest", race_id=FileRaceStoreTests.RACE_ID, race_timestamp=FileRaceStoreTests.RACE_TIMESTAMP, pipeline="from-sources", user_tags={"os": "Linux"}, track=t, track_params={"clients": 12}, challenge=t.default_challenge, car="4gheap", car_params=None, plugin_params=None, track_revision="abc1", team_revision="abc12333", distribution_version="5.0.0", distribution_flavor="default", revision="aaaeeef", results=FileRaceStoreTests.DictHolder( { "young_gc_time": 100, "old_gc_time": 5, "op_metrics": [ { "task": "index #1", "operation": "index", "throughput": { "min": 1000, "median": 1250, "max": 1500, "unit": "docs/s" } } ] }) ) self.race_store.store_race(race) retrieved_race = self.race_store.find_by_race_id(race_id=FileRaceStoreTests.RACE_ID) self.assertEqual(race.race_id, retrieved_race.race_id) self.assertEqual(race.race_timestamp, retrieved_race.race_timestamp) self.assertEqual(1, len(self.race_store.list())) class StatsCalculatorTests(TestCase): def test_calculate_global_stats(self): cfg = config.Config() cfg.add(config.Scope.application, "system", "env.name", "unittest") cfg.add(config.Scope.application, "system", "time.start", datetime.datetime.now()) cfg.add(config.Scope.application, "system", "race.id", "6ebc6e53-ee20-4b0c-99b4-09697987e9f4") cfg.add(config.Scope.application, "reporting", "datastore.type", "in-memory") cfg.add(config.Scope.application, "mechanic", "car.names", ["unittest_car"]) cfg.add(config.Scope.application, "mechanic", "car.params", {}) cfg.add(config.Scope.application, "mechanic", "plugin.params", {}) cfg.add(config.Scope.application, "race", "user.tag", "") cfg.add(config.Scope.application, "race", "pipeline", "from-sources-skip-build") cfg.add(config.Scope.application, "track", "params", {}) index = track.Task(name="index #1", operation=track.Operation(name="index", operation_type=track.OperationType.Bulk, params=None)) challenge = track.Challenge(name="unittest", schedule=[index], default=True) t = track.Track("unittest", "unittest-track", challenges=[challenge]) store = metrics.metrics_store(cfg, read_only=False, track=t, challenge=challenge) store.put_value_cluster_level("throughput", 500, unit="docs/s", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("throughput", 1000, unit="docs/s", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("throughput", 1000, unit="docs/s", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("throughput", 2000, unit="docs/s", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("latency", 2800, unit="ms", task="index #1", operation_type=track.OperationType.Bulk, sample_type=metrics.SampleType.Warmup) store.put_value_cluster_level("latency", 200, unit="ms", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("latency", 220, unit="ms", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("latency", 225, unit="ms", task="index #1", operation_type=track.OperationType.Bulk) store.put_value_cluster_level("service_time", 250, unit="ms", task="index #1", operation_type=track.OperationType.Bulk, sample_type=metrics.SampleType.Warmup, meta_data={"success": False}) store.put_value_cluster_level("service_time", 190, unit="ms", task="index #1", operation_type=track.OperationType.Bulk, meta_data={"success": True}) store.put_value_cluster_level("service_time", 200, unit="ms", task="index #1", operation_type=track.OperationType.Bulk, meta_data={"success": False}) store.put_value_cluster_level("service_time", 210, unit="ms", task="index #1", operation_type=track.OperationType.Bulk, meta_data={"success": True}) store.put_doc(doc={ "name": "ml_processing_time", "job": "benchmark_ml_job_1", "min": 2.2, "mean": 12.3, "median": 17.2, "max": 36.0, "unit": "ms" }, level=metrics.MetaInfoScope.cluster) stats = metrics.calculate_results(store, metrics.create_race(cfg, t, challenge)) del store opm = stats.metrics("index #1") self.assertEqual(collections.OrderedDict( [("min", 500), ("mean", 1125), ("median", 1000), ("max", 2000), ("unit", "docs/s")]), opm["throughput"]) self.assertEqual(collections.OrderedDict( [("50_0", 220), ("100_0", 225), ("mean", 215), ("unit", "ms")]), opm["latency"]) self.assertEqual(collections.OrderedDict( [("50_0", 200), ("100_0", 210), ("mean", 200), ("unit", "ms")]), opm["service_time"]) self.assertAlmostEqual(0.3333333333333333, opm["error_rate"]) self.assertEqual(1, len(stats.ml_processing_time)) self.assertEqual("benchmark_ml_job_1", stats.ml_processing_time[0]["job"]) self.assertEqual(2.2, stats.ml_processing_time[0]["min"]) self.assertEqual(12.3, stats.ml_processing_time[0]["mean"]) self.assertEqual(17.2, stats.ml_processing_time[0]["median"]) self.assertEqual(36.0, stats.ml_processing_time[0]["max"]) self.assertEqual("ms", stats.ml_processing_time[0]["unit"]) def test_calculate_system_stats(self): cfg = config.Config() cfg.add(config.Scope.application, "system", "env.name", "unittest") cfg.add(config.Scope.application, "system", "time.start", datetime.datetime.now()) cfg.add(config.Scope.application, "system", "race.id", "6ebc6e53-ee20-4b0c-99b4-09697987e9f4") cfg.add(config.Scope.application, "reporting", "datastore.type", "in-memory") cfg.add(config.Scope.application, "mechanic", "car.names", ["unittest_car"]) cfg.add(config.Scope.application, "mechanic", "car.params", {}) cfg.add(config.Scope.application, "mechanic", "plugin.params", {}) cfg.add(config.Scope.application, "race", "user.tag", "") cfg.add(config.Scope.application, "race", "pipeline", "from-sources-skip-build") cfg.add(config.Scope.application, "track", "params", {}) index = track.Task(name="index #1", operation=track.Operation(name="index", operation_type=track.OperationType.Bulk, params=None)) challenge = track.Challenge(name="unittest", schedule=[index], default=True) t = track.Track("unittest", "unittest-track", challenges=[challenge]) store = metrics.metrics_store(cfg, read_only=False, track=t, challenge=challenge) store.add_meta_info(metrics.MetaInfoScope.node, "rally-node-0", "node_name", "rally-node-0") store.put_value_node_level("rally-node-0", "final_index_size_bytes", 2048, unit="bytes") # ensure this value will be filtered as it does not belong to our node store.put_value_node_level("rally-node-1", "final_index_size_bytes", 4096, unit="bytes") stats = metrics.calculate_system_results(store, "rally-node-0") del store self.assertEqual([ { "node": "rally-node-0", "name": "index_size", "value": 2048, "unit": "bytes" } ], stats.node_metrics) def select(l, name, operation=None, job=None, node=None): for item in l: if item["name"] == name and item.get("operation") == operation and item.get("node") == node and item.get("job") == job: return item return None class GlobalStatsCalculatorTests(TestCase): RACE_TIMESTAMP = datetime.datetime(2016, 1, 31) RACE_ID = "fb26018b-428d-4528-b36b-cf8c54a303ec" def setUp(self): self.cfg = config.Config() self.cfg.add(config.Scope.application, "system", "env.name", "unittest") self.cfg.add(config.Scope.application, "track", "params", {}) self.metrics_store = metrics.InMemoryMetricsStore(self.cfg, clock=StaticClock) def tearDown(self): del self.metrics_store del self.cfg def test_add_administrative_task_with_error_rate_in_report(self): op = Operation(name='delete-index', operation_type='DeleteIndex', params={'include-in-reporting': False}) task = Task('delete-index', operation=op, schedule='deterministic') challenge = Challenge(name='append-fast-with-conflicts', schedule=[task], meta_data={}) self.metrics_store.open(InMemoryMetricsStoreTests.RACE_ID, InMemoryMetricsStoreTests.RACE_TIMESTAMP, "test", "append-fast-with-conflicts", "defaults", create=True) self.metrics_store.put_doc(doc={"@timestamp": 1595896761994, "relative-time": 283382, "race-id": "fb26018b-428d-4528-b36b-cf8c54a303ec", "race-timestamp": "20200728T003905Z", "environment": "local", "track": "geonames", "challenge": "append-fast-with-conflicts", "car": "defaults", "name": "service_time", "value": 72.67997100007051, "unit": "ms", "sample-type": "normal", "meta": {"source_revision": "7f634e9f44834fbc12724506cc1da681b0c3b1e3", "distribution_version": "7.6.0", "distribution_flavor": "oss", "success": False}, "task": "delete-index", "operation": "delete-index", "operation-type": "DeleteIndex"}) result = GlobalStatsCalculator(store=self.metrics_store, track=Track(name='geonames', meta_data={}), challenge=challenge)() assert "delete-index" in [op_metric.get('task') for op_metric in result.op_metrics] class GlobalStatsTests(TestCase): def test_as_flat_list(self): d = { "op_metrics": [ { "task": "index #1", "operation": "index", "throughput": { "min": 450, "median": 450, "max": 452, "unit": "docs/s" }, "latency": { "50": 340, "100": 376, }, "service_time": { "50": 341, "100": 376 }, "error_rate": 0.0, "meta": { "clients": 8, "phase": "idx" } }, { "task": "search #2", "operation": "search", "throughput": { "min": 9, "median": 10, "max": 12, "unit": "ops/s" }, "latency": { "50": 99, "100": 111, }, "service_time": { "50": 98, "100": 110 }, "error_rate": 0.1 } ], "ml_processing_time": [ { "job": "job_1", "min": 3.3, "mean": 5.2, "median": 5.8, "max": 12.34 }, { "job": "job_2", "min": 3.55, "mean": 4.2, "median": 4.9, "max": 9.4 }, ], "young_gc_time": 68, "young_gc_count": 7, "old_gc_time": 0, "old_gc_count": 0, "merge_time": 3702, "merge_time_per_shard": { "min": 40, "median": 3702, "max": 3900, "unit": "ms" }, "merge_count": 2, "refresh_time": 596, "refresh_time_per_shard": { "min": 48, "median": 89, "max": 204, "unit": "ms" }, "refresh_count": 10, "flush_time": None, "flush_time_per_shard": {}, "flush_count": 0 } s = metrics.GlobalStats(d) metric_list = s.as_flat_list() self.assertEqual({ "name": "throughput", "task": "index #1", "operation": "index", "value": { "min": 450, "median": 450, "max": 452, "unit": "docs/s" }, "meta": { "clients": 8, "phase": "idx" } }, select(metric_list, "throughput", operation="index")) self.assertEqual({ "name": "service_time", "task": "index #1", "operation": "index", "value": { "50": 341, "100": 376 }, "meta": { "clients": 8, "phase": "idx" } }, select(metric_list, "service_time", operation="index")) self.assertEqual({ "name": "latency", "task": "index #1", "operation": "index", "value": { "50": 340, "100": 376 }, "meta": { "clients": 8, "phase": "idx" } }, select(metric_list, "latency", operation="index")) self.assertEqual({ "name": "error_rate", "task": "index #1", "operation": "index", "value": { "single": 0.0 }, "meta": { "clients": 8, "phase": "idx" } }, select(metric_list, "error_rate", operation="index")) self.assertEqual({ "name": "throughput", "task": "search #2", "operation": "search", "value": { "min": 9, "median": 10, "max": 12, "unit": "ops/s" } }, select(metric_list, "throughput", operation="search")) self.assertEqual({ "name": "service_time", "task": "search #2", "operation": "search", "value": { "50": 98, "100": 110 } }, select(metric_list, "service_time", operation="search")) self.assertEqual({ "name": "latency", "task": "search #2", "operation": "search", "value": { "50": 99, "100": 111 } }, select(metric_list, "latency", operation="search")) self.assertEqual({ "name": "error_rate", "task": "search #2", "operation": "search", "value": { "single": 0.1 } }, select(metric_list, "error_rate", operation="search")) self.assertEqual({ "name": "ml_processing_time", "job": "job_1", "value": { "min": 3.3, "mean": 5.2, "median": 5.8, "max": 12.34 } }, select(metric_list, "ml_processing_time", job="job_1")) self.assertEqual({ "name": "ml_processing_time", "job": "job_2", "value": { "min": 3.55, "mean": 4.2, "median": 4.9, "max": 9.4 } }, select(metric_list, "ml_processing_time", job="job_2")) self.assertEqual({ "name": "young_gc_time", "value": { "single": 68 } }, select(metric_list, "young_gc_time")) self.assertEqual({ "name": "young_gc_count", "value": { "single": 7 } }, select(metric_list, "young_gc_count")) self.assertEqual({ "name": "old_gc_time", "value": { "single": 0 } }, select(metric_list, "old_gc_time")) self.assertEqual({ "name": "old_gc_count", "value": { "single": 0 } }, select(metric_list, "old_gc_count")) self.assertEqual({ "name": "merge_time", "value": { "single": 3702 } }, select(metric_list, "merge_time")) self.assertEqual({ "name": "merge_time_per_shard", "value": { "min": 40, "median": 3702, "max": 3900, "unit": "ms" } }, select(metric_list, "merge_time_per_shard")) self.assertEqual({ "name": "merge_count", "value": { "single": 2 } }, select(metric_list, "merge_count")) self.assertEqual({ "name": "refresh_time", "value": { "single": 596 } }, select(metric_list, "refresh_time")) self.assertEqual({ "name": "refresh_time_per_shard", "value": { "min": 48, "median": 89, "max": 204, "unit": "ms" } }, select(metric_list, "refresh_time_per_shard")) self.assertEqual({ "name": "refresh_count", "value": { "single": 10 } }, select(metric_list, "refresh_count")) self.assertIsNone(select(metric_list, "flush_time")) self.assertIsNone(select(metric_list, "flush_time_per_shard")) self.assertEqual({ "name": "flush_count", "value": { "single": 0 } }, select(metric_list, "flush_count")) class SystemStatsTests(TestCase): def test_as_flat_list(self): d = { "node_metrics": [ { "node": "rally-node-0", "name": "startup_time", "value": 3.4 }, { "node": "rally-node-1", "name": "startup_time", "value": 4.2 }, { "node": "rally-node-0", "name": "index_size", "value": 300 * 1024 * 1024 }, { "node": "rally-node-1", "name": "index_size", "value": 302 * 1024 * 1024 }, { "node": "rally-node-0", "name": "bytes_written", "value": 817 * 1024 * 1024 }, { "node": "rally-node-1", "name": "bytes_written", "value": 833 * 1024 * 1024 }, ], } s = metrics.SystemStats(d) metric_list = s.as_flat_list() self.assertEqual({ "node": "rally-node-0", "name": "startup_time", "value": { "single": 3.4 } }, select(metric_list, "startup_time", node="rally-node-0")) self.assertEqual({ "node": "rally-node-1", "name": "startup_time", "value": { "single": 4.2 } }, select(metric_list, "startup_time", node="rally-node-1")) self.assertEqual({ "node": "rally-node-0", "name": "index_size", "value": { "single": 300 * 1024 * 1024 } }, select(metric_list, "index_size", node="rally-node-0")) self.assertEqual({ "node": "rally-node-1", "name": "index_size", "value": { "single": 302 * 1024 * 1024 } }, select(metric_list, "index_size", node="rally-node-1")) self.assertEqual({ "node": "rally-node-0", "name": "bytes_written", "value": { "single": 817 * 1024 * 1024 } }, select(metric_list, "bytes_written", node="rally-node-0")) self.assertEqual({ "node": "rally-node-1", "name": "bytes_written", "value": { "single": 833 * 1024 * 1024 } }, select(metric_list, "bytes_written", node="rally-node-1"))
import statistics from rest_framework import serializers from foundation.models import TimeSeriesDatum, Sensor class DashboardSerializer(serializers.BaseSerializer): def get_values(self, sensor_name, instrument): sensor = Sensor.objects.get( name=sensor_name, instrument=instrument, ) values = TimeSeriesDatum.objects.filter(sensor=sensor).values_list('value', flat=True) return values def get_statistics(self, values): try: mean = statistics.mean(values) except Exception as e: mean = "NF" try: median = statistics.median(values) except Exception as e: median = "NF" try: mode = statistics.mode(values) except Exception as e: mode = "NF" return { 'mean': mean, 'median': median, 'mode': mode } def to_representation(self, instruments): """ Get the list of instruments and perform our computations. """ results = [] for instrument in instruments: temp_values = self.get_values("Temperature", instrument) hum_values = self.get_values("Humidity", instrument) pressure_values = self.get_values("Pressure", instrument) co2_values = self.get_values("Co2", instrument) tvoc_values = self.get_values("TVOC", instrument) results.append({ 'id': instrument.id, 'name': instrument.name, 'temperature': self.get_statistics(temp_values), 'humidity': self.get_statistics(hum_values), 'pressure': self.get_statistics(pressure_values), 'co2': self.get_statistics(co2_values), 'tvoc': self.get_statistics(tvoc_values), }) return { 'results': results, 'count': instruments.count() }
from distutils.core import setup from setuptools import find_packages version = '0.2.1.dev0' CLASSIFIERS = [ 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Topic :: Software Development', ] install_requires = [ 'Django>=1.9', 'django-appconf', ] setup( name="django-cookie-consent", description="Django cookie consent application", version=version, author="Informatika Mihelac", author_email="bmihelac@mihelac.org", url="https://github.com/bmihelac/django-cookie-consent", packages=find_packages(exclude=["tests"]), include_package_data=True, install_requires=install_requires, classifiers=CLASSIFIERS, )
import '@brightspace-ui/core/components/button/button-subtle.js'; import '@brightspace-ui/core/components/colors/colors.js'; import './d2l-note'; /** * Import LitElement base class, html helper function, * and TypeScript decorators **/ import { html, LitElement } from 'lit-element'; import { bodyStandardStyles } from '@brightspace-ui/core/components/typography/styles.js'; import { langResources } from './lang'; import { LocalizeMixin } from '@brightspace-ui/core/mixins/localize-mixin.js'; import { repeat } from 'lit-html/directives/repeat'; /** * d2l-note component created with lit-element * * # Usage * ```html * <d2l-notes * id="notes" * dateformat="medium" * editstring="Edit Note" * deletestring="Delete Note" * privatelabel="Private" * addnotestring="Add" * savenotestring="Save" * discardnotestring="Discard" * editplaceholder="Placeholder for d2l-note-edit" * > * <div slot="description">Description for d2l-note-edit</div> * </d2l-notes> * <script> * document.getElementById('notes').description = (note) => note ? html`<p>Description for note</p>` : html`<p>Description for notes</p>`; * document.getElementById('notes').settings = (note) => note ? html`<div>Settings for note</div>` : html`<div>Settings for notes</div>`; * document.getElementById('notes').notes = [{ * user: { * name: 'Username', * pic: { * url: 'url', * requireTokenAuth: true, * }, * }, * token: 'foozleberries', * showAvatar: true, * me: false, * createdAt: '2019-04-23T17:08:33.839Z', * updatedAt: '2019-04-24T17:08:33.839Z', * text: 'Note', * canEdit: true, * canDelete: true, * private: true, * contextmenulabel: 'Context Menu' * }]; * </script> * ``` */ export class D2LNotes extends LocalizeMixin(LitElement) { static get properties() { return { /** * Array of notes to pass to d2l-note elements */ notes: { type: Array }, /** * Indicates this user can create new notes */ cancreate: { type: Boolean }, /** * d2l-note-edit placeholder to show when creating */ editplaceholder: { type: String }, /** * TemplateResult containing description for d2l-note's in edit state and d2l-note-edit */ description: { type: Object }, /** * TemplateResult containing settings for d2l-note's in edit state and d2l-note-edit */ settings: { type: Object }, /** * Show the loadmore button regardless of number of items */ hasmore: { type: Boolean }, /** * Load more/less collapsed state */ collapsed: { type: Boolean }, /** * Number of items to show before showing the load more button */ collapsedsize: { type: Number }, /** * dateformat in d2l-note's */ dateformat: { type: String }, /** * override loadmore button text */ loadmorestring: { type: String }, /** * override loadless button text */ loadlessstring: { type: String }, /** * editstring in d2l-note's */ editstring: { type: String }, /** * deletestring in d2l-note's */ deletestring: { type: String }, /** * privatelabel in d2l-note's */ privatelabel: { type: String }, /** * addnotestring in d2l-note-edit */ addnotestring: { type: String }, /** * savenotestring in d2l-note's */ savenotestring: { type: String }, /** * discardnotestring in d2l-note's and d2l-note-edit */ discardnotestring: { type: String }, /** * string to show when there are no notes to show. Set to '' to not show anything */ emptystring: { type: String }, /** * label for the 'enter notes' area, overridden by emptystring if there are no existing notes. Does not render if undefined */ enternotestring: { type: String }, }; } constructor() { super(); this.notes = []; this.cancreate = false; this.editplaceholder = ''; this.description = () => html`<div></div>`; this.settings = () => html`<div></div>`; this.hasmore = false; this.collapsed = true; this.collapsedsize = 4; /** * Fired when load more is tapped * @fires d2l-notes-load-more */ this.EVENT_LOAD_MORE = 'd2l-notes-load-more'; /** * Fired when load less is tapped * @fires d2l-notes-load-less */ this.EVENT_LOAD_LESS = 'd2l-notes-load-less'; } static async getLocalizeResources(langs) { for (let i = 0; i < langs.length; i++) { if (langResources[langs[i]]) { return { resources: langResources[langs[i]], language: langs[i], }; } } } static get styles() { return bodyStandardStyles; } /** * Implement `render` to define a template for your element. */ render() { const hasmore = this.hasmore || this.notes.length > this.collapsedsize; const notes = this.notes && this.collapsed ? this.notes.slice(0, this.collapsedsize) : this.notes; /** * Use JavaScript expressions to include property values in * the element template. */ return html` <style> :host { --d2l-notes-note-margin-top: 6px; --d2l-notes-note-margin-bottom: 12px; --d2l-notes-hr-margin-bottom: 18px; --d2l-notes-ol-margin-bottom: 24px; --d2l-notes-load-more-margin-bottom: 36px; } :host { display: block; } .d2l-typography { line-height: 0; } ol { margin: 0; padding: 0; /* (paragraph separation) 8px + (load more/less border) 1px + (load more/less padding) 8px = 17px */ margin-bottom: calc(var(--d2l-notes-ol-margin-bottom) - 17px); @apply --d2l-notes-ol; } li { display: block; margin-top: var(--d2l-notes-note-margin-top); margin-bottom: var(--d2l-notes-note-margin-bottom); @apply --d2l-notes-li; } li:first-child { margin-top: 0; @apply --d2l-notes-li-first; } li:last-child { margin-bottom: 0; @apply --d2l-notes-li-last; } hr { /* (paragraph separation) 8px */ margin-top: calc(var(--d2l-notes-ol-margin-bottom) - 8px); margin-bottom: var(--d2l-notes-hr-margin-bottom); @apply --d2l-notes-hr; } .d2l-notes-more-less { display: flex; width: 100%; align-items: center; /* load more/less padding (8px) - load more/less border (1px) = 9px */ margin-bottom: calc(var(--d2l-notes-load-more-margin-bottom) - 9px); @apply --d2l-notes-more-less; } .d2l-notes-load-more-less { flex: 0 1 auto; @apply --d2l-notes-more-less-button; } .d2l-notes-more-less-separator { flex: 1; border-top: solid 1px var(--d2l-color-celestine); @apply --d2l-notes-more-less-separator; } .d2l-notes-enter-note-string, .d2l-note-emptystring { line-height: 1; margin-bottom: 0.6rem; } </style> <div class="d2l-typography"> ${notes.length > 0 ? html` <ol>${repeat(notes, (note) => html` <li> <d2l-note .id=${note.id ? note.id : ''} .user=${note.user} .href=${note.href} .token=${note.token} .showavatar=${typeof note.showAvatar === 'boolean' ? note.showAvatar : true} .me=${note.me ? note.me : false} .createdat=${note.createdAt} .updatedat=${note.updatedAt} .text=${note.text} .canedit=${note.canEdit ? note.canEdit : false} .candelete=${note.canDelete ? note.canDelete : false} .private=${note.private ? note.private : false} .dateformat=${this.dateformat} .contextmenulabel=${note.contextmenulabel} .editstring=${this.editstring} .deletestring=${this.deletestring} .privatelabel=${this.privatelabel} .addnotestring=${this.addnotestring} .savenotestring=${this.savenotestring} .discardnotestring=${this.discardnotestring} .editplaceholder=${this.editplaceholder} > <div slot="description">${this.description(note)}</div> <div slot="settings">${this.settings(note)}</div> </d2l-note> </li> `)} </ol>` : (this.emptystring === '' ? '' : html`<div class="d2l-body-standard d2l-note-emptystring">${this.emptystring !== undefined || this.enternotestring !== undefined ? this.emptystring || this.enternotestring : this.localize('empty')}</div>`)} ${hasmore ? html` <div class="d2l-notes-more-less" @click=${this.handleMoreLess} @tap=${this.handleMoreLess} > <div class="d2l-notes-more-less-separator"></div> <d2l-button-subtle class="d2l-notes-load-more-less" text="${(this.hasmore || this.collapsed) ? this.loadmorestring ? this.loadmorestring : this.localize('more') : this.loadlessstring ? this.loadlessstring : this.localize('less')}" ></d2l-button-subtle> <div class="d2l-notes-more-less-separator"></div> </div> ` : null} ${(hasmore || this.notes.length) && this.cancreate ? html`<hr>` : null} ${this.cancreate ? html`${notes.length > 0 && this.enternotestring !== undefined ? html`<div class='d2l-notes-enter-note-string'>${this.enternotestring}</div>` : html``} <d2l-note-edit new placeholder="${this.editplaceholder}"> <slot class="d2l-body-standard" name="description" slot="description"><div>${this.description()}</div></slot> <div slot="settings">${this.settings()}</div> </d2l-note-edit>` : null} </div> `; } handleMoreLess() { if (this.hasmore || this.collapsed) { this.dispatchEvent(new CustomEvent(this.EVENT_LOAD_MORE, { bubbles: true, composed: true })); this.collapsed = false; } else { this.dispatchEvent(new CustomEvent(this.EVENT_LOAD_LESS, { bubbles: true, composed: true })); this.collapsed = true; } } } customElements.define('d2l-notes', D2LNotes);
const assert = require('assert'); const { Buffer } = require('buffer'); const algosdk = require('../index'); const group = require('../src/group'); describe('Sign', () => { /* eslint-disable no-console */ const originalLogFunction = console.log; let logs; beforeEach(() => { logs = ''; // Mock console.log to suppress logs during tests console.log = (msg) => { logs += `${msg}\n`; }; }); afterEach(function Cleanup() { // Unmock console.log console.log = originalLogFunction; // Unsuppress logs if the test failed if (this.currentTest.state === 'failed') { console.log(logs); } }); /* eslint-enable no-console */ it('should not modify input arrays', () => { const appArgs = [Uint8Array.from([1, 2]), Uint8Array.from([3, 4])]; const appAccounts = [ '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', ]; const appForeignApps = [17, 200]; const appForeignAssets = [7, 8, 9]; const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array(0), type: 'appl', appIndex: 5, appArgs, appAccounts, appForeignApps, appForeignAssets, }; const txn = new algosdk.Transaction(o); assert.deepStrictEqual(appArgs, [ Uint8Array.from([1, 2]), Uint8Array.from([3, 4]), ]); assert.deepStrictEqual(appAccounts, [ '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', ]); assert.deepStrictEqual(appForeignApps, [17, 200]); assert.deepStrictEqual(appForeignAssets, [7, 8, 9]); assert.ok(txn.appArgs !== appArgs); assert.ok(txn.appAccounts !== appAccounts); assert.ok(txn.appForeignApps !== appForeignApps); assert.ok(txn.appForeignAssets !== appForeignAssets); }); it('should not complain on a missing note', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array(0), }; assert.doesNotThrow(() => new algosdk.Transaction(o)); }); it('should respect min tx fee', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 0, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array([123, 12, 200]), }; const txn = new algosdk.Transaction(o); assert.equal(txn.fee, 1000); // 1000 is the v5 min txn fee const txnEnc = txn.get_obj_for_encoding(); assert.equal(txnEnc.fee, 1000); }); it('should not complain on a missing genesisID', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array([123, 12, 200]), }; assert.doesNotThrow(() => new algosdk.Transaction(o)); }); it('should not complain on an empty genesisID', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, amount: 847, firstRound: 51, lastRound: 61, note: new Uint8Array([123, 12, 200]), genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', genesisID: '', }; assert.doesNotThrow(() => new algosdk.Transaction(o)); }); it('should complain if note isnt Uint8Array', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: 'new Uint8Array(0)', }; assert.throws( () => new algosdk.Transaction(o), (err) => err.toString() === 'Error: note must be a Uint8Array.' ); }); it('should be able to prettyprint and go toString without throwing', () => { const o = { from: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', to: '7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q', fee: 10, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array(0), }; const txn = new algosdk.Transaction(o); // assert package recommends just calling prettyPrint over using assert.doesNotThrow txn.prettyPrint(); // should not throw txn.toString(); // also should not throw }); describe('should correctly serialize and deserialize from msgpack representation', () => { it('should correctly serialize and deserialize from msgpack representation', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', to: 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', fee: 10, amount: 847, firstRound: 51, lastRound: 61, note: new Uint8Array([123, 12, 200]), genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', genesisID: '', }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize from msgpack representation with flat fee', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', to: 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', fee: 2063, amount: 847, firstRound: 51, lastRound: 61, note: new Uint8Array([123, 12, 200]), genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', genesisID: '', flatFee: true, }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize a key registration transaction from msgpack representation', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', fee: 10, firstRound: 51, lastRound: 61, note: new Uint8Array([123, 12, 200]), genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', voteKey: '5/D4TQaBHfnzHI2HixFV9GcdUaGFwgCQhmf0SVhwaKE=', selectionKey: 'oImqaSLjuZj63/bNSAjd+eAh5JROOJ6j1cY4eGaJGX4=', voteFirst: 123, voteLast: 456, voteKeyDilution: 1234, genesisID: '', type: 'keyreg', }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize an asset configuration transaction from msgpack representation', () => { const address = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const o = { from: address, fee: 10, firstRound: 322575, lastRound: 323575, genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', assetIndex: 1234, assetManager: address, assetReserve: address, assetFreeze: address, assetClawback: address, type: 'acfg', }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize an asset creation transaction from msgpack representation', () => { const address = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const o = { from: address, fee: 10, firstRound: 322575, lastRound: 323575, genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', assetTotal: 1000, assetDefaultFrozen: true, assetUnitName: 'tests', assetName: 'testcoin', assetURL: 'testURL', assetMetadataHash: new Uint8Array( Buffer.from('ZkFDUE80blJnTzU1ajFuZEFLM1c2U2djNEFQa2N5Rmg=', 'base64') ), assetManager: address, assetReserve: address, assetFreeze: address, assetClawback: address, type: 'acfg', }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize an asset transfer transaction from msgpack representation', () => { const address = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const o = { type: 'axfer', from: address, to: address, amount: 100, fee: 10, firstRound: 322575, lastRound: 323575, genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', assetIndex: 1234, assetRevocationTarget: address, closeRemainderTo: address, }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize an asset freeze transaction from msgpack representation', () => { const address = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const o = { from: address, fee: 10, firstRound: 322575, lastRound: 323575, genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', type: 'afrz', freezeAccount: address, assetIndex: 1, freezeState: true, }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('reserializes correctly no genesis ID', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', to: 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', fee: 10, amount: 847, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array([123, 12, 200]), }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('reserializes correctly zero amount', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', to: 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', fee: 10, amount: 0, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array([123, 12, 200]), }; const expectedTxn = new algosdk.Transaction(o); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); }); it('should correctly serialize and deserialize group object', () => { const o = { from: 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU', to: 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM', fee: 10, amount: 0, firstRound: 51, lastRound: 61, genesisHash: 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI=', note: new Uint8Array([123, 12, 200]), }; const tx = new algosdk.Transaction(o); { const expectedTxg = new group.TxGroup([tx.rawTxID(), tx.rawTxID()]); const encRep = expectedTxg.get_obj_for_encoding(); const encTxg = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxg); const decTxg = group.TxGroup.from_obj_for_encoding(decEncRep); const reencRep = decTxg.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); } { const expectedTxn = tx; expectedTxn.group = tx.rawTxID(); const encRep = expectedTxn.get_obj_for_encoding(); const encTxn = algosdk.encodeObj(encRep); const decEncRep = algosdk.decodeObj(encTxn); const decTxn = algosdk.Transaction.from_obj_for_encoding(decEncRep); const reencRep = decTxn.get_obj_for_encoding(); assert.deepStrictEqual(reencRep, encRep); } }); }); describe('transaction making functions', () => { it('should be able to use helper to make a payment transaction', () => { const from = 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU'; const to = 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM'; const fee = 10; const amount = 847; const firstRound = 51; const lastRound = 61; const note = new Uint8Array([123, 12, 200]); const genesisHash = 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI='; const genesisID = ''; const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; let closeRemainderTo; const o = { from, to, fee, amount, closeRemainderTo, firstRound, lastRound, note, genesisHash, genesisID, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makePaymentTxn( from, to, fee, amount, closeRemainderTo, firstRound, lastRound, note, genesisHash, genesisID, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make a payment transaction with BigInt amount', () => { const from = 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU'; const to = 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM'; const fee = 10; const amount = 0xffffffffffffffffn; const firstRound = 51; const lastRound = 61; const note = new Uint8Array([123, 12, 200]); const genesisHash = 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI='; const genesisID = ''; const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; let closeRemainderTo; const o = { from, to, fee, amount, closeRemainderTo, firstRound, lastRound, note, genesisHash, genesisID, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makePaymentTxn( from, to, fee, amount, closeRemainderTo, firstRound, lastRound, note, genesisHash, genesisID, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should throw if payment amount is too large', () => { const from = 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU'; const to = 'UCE2U2JC4O4ZR6W763GUQCG57HQCDZEUJY4J5I6VYY4HQZUJDF7AKZO5GM'; const fee = 10; const amount = 0x10000000000000000n; const firstRound = 51; const lastRound = 61; const note = new Uint8Array([123, 12, 200]); const genesisHash = 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI='; const genesisID = ''; const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; let closeRemainderTo; const o = { from, to, fee, amount, closeRemainderTo, firstRound, lastRound, note, genesisHash, genesisID, reKeyTo: rekeyTo, }; assert.throws( () => new algosdk.Transaction(o), new Error('Amount must be a positive number and smaller than 2^64-1') ); }); it('should be able to use helper to make a keyreg transaction', () => { const from = 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU'; const fee = 10; const firstRound = 51; const lastRound = 61; const note = new Uint8Array([123, 12, 200]); const genesisHash = 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI='; const genesisID = ''; const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const voteKey = '5/D4TQaBHfnzHI2HixFV9GcdUaGFwgCQhmf0SVhwaKE='; const selectionKey = 'oImqaSLjuZj63/bNSAjd+eAh5JROOJ6j1cY4eGaJGX4='; const voteKeyDilution = 1234; const voteFirst = 123; const voteLast = 456; const o = { from, fee, firstRound, lastRound, note, genesisHash, voteKey, selectionKey, voteFirst, voteLast, voteKeyDilution, genesisID, reKeyTo: rekeyTo, type: 'keyreg', }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeKeyRegistrationTxn( from, fee, firstRound, lastRound, note, genesisHash, genesisID, voteKey, selectionKey, voteFirst, voteLast, voteKeyDilution, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make a nonparticipating keyreg transaction', () => { const from = 'XMHLMNAVJIMAW2RHJXLXKKK4G3J3U6VONNO3BTAQYVDC3MHTGDP3J5OCRU'; const fee = 10; const firstRound = 51; const lastRound = 61; const note = new Uint8Array([123, 12, 200]); const genesisHash = 'JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI='; const genesisID = ''; const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const voteKey = '5/D4TQaBHfnzHI2HixFV9GcdUaGFwgCQhmf0SVhwaKE='; const selectionKey = 'oImqaSLjuZj63/bNSAjd+eAh5JROOJ6j1cY4eGaJGX4='; const voteKeyDilution = 1234; const voteFirst = 123; const voteLast = 456; const nonParticipation = true; const o = { from, fee, firstRound, lastRound, note, genesisHash, nonParticipation, genesisID, reKeyTo: rekeyTo, type: 'keyreg', }; assert.throws( () => new algosdk.Transaction({ ...o, voteKey, selectionKey, voteFirst, voteLast, voteKeyDilution, }), new Error( 'nonParticipation is true but participation params are present.' ) ); const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeKeyRegistrationTxn( from, fee, firstRound, lastRound, note, genesisHash, genesisID, undefined, undefined, undefined, undefined, undefined, rekeyTo, nonParticipation ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make an asset create transaction', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const defaultFrozen = false; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const total = 100; const decimals = 0; const reserve = addr; const freeze = addr; const clawback = addr; const unitName = 'tst'; const assetName = 'testcoin'; const assetURL = 'testURL'; const assetMetadataHash = new Uint8Array( Buffer.from('dGVzdGhhc2gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', 'base64') ); const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, note, genesisHash, assetTotal: total, assetDecimals: decimals, assetDefaultFrozen: defaultFrozen, assetUnitName: unitName, assetName, assetURL, assetMetadataHash, assetManager: addr, assetReserve: reserve, assetFreeze: freeze, assetClawback: clawback, genesisID, reKeyTo: rekeyTo, type: 'acfg', }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetCreateTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, total, decimals, defaultFrozen, addr, reserve, freeze, clawback, unitName, assetName, assetURL, assetMetadataHash, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make an asset create transaction with BigInt total', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const defaultFrozen = false; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const total = 0xffffffffffffffffn; const decimals = 0; const reserve = addr; const freeze = addr; const clawback = addr; const unitName = 'tst'; const assetName = 'testcoin'; const assetURL = 'testURL'; const assetMetadataHash = new Uint8Array( Buffer.from('dGVzdGhhc2gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', 'base64') ); const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, note, genesisHash, assetTotal: total, assetDecimals: decimals, assetDefaultFrozen: defaultFrozen, assetUnitName: unitName, assetName, assetURL, assetMetadataHash, assetManager: addr, assetReserve: reserve, assetFreeze: freeze, assetClawback: clawback, genesisID, reKeyTo: rekeyTo, type: 'acfg', }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetCreateTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, total, decimals, defaultFrozen, addr, reserve, freeze, clawback, unitName, assetName, assetURL, assetMetadataHash, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should throw if asset creation total is too large', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const defaultFrozen = false; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const total = 0x10000000000000000n; const decimals = 0; const reserve = addr; const freeze = addr; const clawback = addr; const unitName = 'tst'; const assetName = 'testcoin'; const assetURL = 'testURL'; const assetMetadataHash = new Uint8Array( Buffer.from('dGVzdGhhc2gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=', 'base64') ); const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, note, genesisHash, assetTotal: total, assetDecimals: decimals, assetDefaultFrozen: defaultFrozen, assetUnitName: unitName, assetName, assetURL, assetMetadataHash, assetManager: addr, assetReserve: reserve, assetFreeze: freeze, assetClawback: clawback, genesisID, reKeyTo: rekeyTo, type: 'acfg', }; assert.throws( () => new algosdk.Transaction(o), new Error( 'Total asset issuance must be a positive number and smaller than 2^64-1' ) ); }); it('should fail to make an asset create transaction with an invalid assetMetadataHash', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const defaultFrozen = false; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const total = 100; const decimals = 0; const reserve = addr; const freeze = addr; const clawback = addr; const unitName = 'tst'; const assetName = 'testcoin'; const assetURL = 'testURL'; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const txnTemplate = { from: addr, fee, firstRound, lastRound, note, genesisHash, assetTotal: total, assetDecimals: decimals, assetDefaultFrozen: defaultFrozen, assetUnitName: unitName, assetName, assetURL, assetManager: addr, assetReserve: reserve, assetFreeze: freeze, assetClawback: clawback, genesisID, reKeyTo: rekeyTo, type: 'acfg', }; assert.doesNotThrow(() => { const txnParams = { assetMetadataHash: '', ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.throws(() => { const txnParams = { assetMetadataHash: 'abc', ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.doesNotThrow(() => { const txnParams = { assetMetadataHash: 'fACPO4nRgO55j1ndAK3W6Sgc4APkcyFh', ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.throws(() => { const txnParams = { assetMetadataHash: 'fACPO4nRgO55j1ndAK3W6Sgc4APkcyFh1', ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.doesNotThrow(() => { const txnParams = { assetMetadataHash: new Uint8Array(0), ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.throws(() => { const txnParams = { assetMetadataHash: new Uint8Array([1, 2, 3]), ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.doesNotThrow(() => { const txnParams = { assetMetadataHash: new Uint8Array(32), ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); assert.throws(() => { const txnParams = { assetMetadataHash: new Uint8Array(33), ...txnTemplate, }; return new algosdk.Transaction(txnParams); }); }); it('should be able to use helper to make an asset config transaction', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const assetIndex = 1234; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const manager = addr; const reserve = addr; const freeze = addr; const clawback = addr; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, genesisHash, genesisID, assetIndex, assetManager: manager, assetReserve: reserve, assetFreeze: freeze, assetClawback: clawback, type: 'acfg', note, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetConfigTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, assetIndex, manager, reserve, freeze, clawback, true, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should throw when disobeying strict address checking in make asset config', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const assetIndex = 1234; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const manager = addr; let reserve; let freeze; const clawback = addr; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); let threw = false; try { algosdk.makeAssetConfigTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, assetIndex, manager, reserve, freeze, clawback ); } catch { threw = true; } assert.deepStrictEqual(true, threw); }); it('should be able to use helper to make an asset destroy transaction', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const assetIndex = 1234; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, genesisHash, genesisID, assetIndex, type: 'acfg', note, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetDestroyTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, assetIndex, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make an asset transfer transaction', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const sender = addr; const recipient = addr; const revocationTarget = addr; const closeRemainderTo = addr; const assetIndex = 1234; const amount = 100; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { type: 'axfer', from: sender, to: recipient, amount, fee, firstRound, lastRound, genesisHash, genesisID, assetIndex, note, assetRevocationTarget: revocationTarget, closeRemainderTo, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetTransferTxn( sender, recipient, closeRemainderTo, revocationTarget, fee, amount, firstRound, lastRound, note, genesisHash, genesisID, assetIndex, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to make an asset freeze transaction', () => { const addr = 'BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4'; const fee = 10; const assetIndex = 1234; const genesisHash = 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI='; const creator = addr; const freezeTarget = addr; const genesisID = ''; const firstRound = 322575; const lastRound = 322575; const freezeState = true; const note = new Uint8Array([123, 12, 200]); const rekeyTo = 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM'; const o = { from: addr, fee, firstRound, lastRound, genesisHash, type: 'afrz', freezeAccount: freezeTarget, assetIndex, creator, freezeState, note, genesisID, reKeyTo: rekeyTo, }; const expectedTxn = new algosdk.Transaction(o); const actualTxn = algosdk.makeAssetFreezeTxn( addr, fee, firstRound, lastRound, note, genesisHash, genesisID, assetIndex, freezeTarget, freezeState, rekeyTo ); assert.deepStrictEqual(expectedTxn, actualTxn); }); it('should be able to use helper to assign group ID to mixed Transaction and Dict', () => { const suggestedParams = { genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', genesisID: '', firstRound: 322575, lastRound: 322575 + 1000, fee: 1000, flatFee: true, }; const helperTx = algosdk.makePaymentTxnWithSuggestedParams( 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM', 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM', 1000, undefined, new Uint8Array(0), suggestedParams ); const dictTx = { from: 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM', to: 'GAQVB24XEPYOPBQNJQAE4K3OLNYTRYD65ZKR3OEW5TDOOGL7MDKABXHHTM', fee: 1000, flatFee: true, amount: 0, firstRound: 322575, lastRound: 322575 + 1000, genesisID: '', genesisHash: 'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=', type: 'pay', }; // Store both transactions const txns = [helperTx, dictTx]; // Group both transactions const txgroup = algosdk.assignGroupID(txns); assert.deepStrictEqual(txgroup[0].group, txgroup[1].group); }); }); });
import os from setuptools import setup, find_packages def get_long_description(): this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() return long_description def parse_requirements(file): return sorted(set( line.partition('#')[0].strip() for line in open(os.path.join(os.path.dirname(__file__), file)) ) - set('')) def get_version(): for line in open(os.path.join(os.path.dirname(__file__), 'eolearn', 'core', '__init__.py')): if line.find("__version__") >= 0: version = line.split("=")[1].strip() version = version.strip('"').strip("'") return version setup(name='eo-learn-core', python_requires='>=3.5,<3.7', version=get_version(), description='Core Machine Learning Framework at Sinergise', long_description=get_long_description(), long_description_content_type='text/markdown', url='https://github.com/sentinel-hub/eo-learn', author='Sinergise EO research team', author_email='info@sinergise.com', license='MIT', packages=find_packages(), package_data={'eolearn': ['core/report_templates/report.html']}, include_package_data=True, install_requires=parse_requirements("requirements.txt"), zip_safe=False)
import logging from pathlib import Path import random from odfuzz.restrictions import RestrictionsGroup from odfuzz.entities import DirectBuilder from odfuzz.fuzzer import SingleQueryable logger = logging.getLogger("testDirectBuilder") logger.setLevel(logging.CRITICAL) #logger is needed not for the test but as part of DirectBuilder constructor def test_expected_integration_sample(): """ This test is example of intended usage of DirectBuilder class and fixture of its API since will be used in external tools see https://github.com/SAP/odfuzz/issues/37 """ path_to_metadata = Path(__file__).parent.joinpath("metadata-northwind-v2.xml") metadata_file_contents = path_to_metadata.read_bytes() # do not pass metadata as python string but read as bytes, usually ends with Unicode vs xml encoding mismatch. restrictions = RestrictionsGroup(None) builder = DirectBuilder(metadata_file_contents, restrictions,"GET") entities = builder.build() ''' uncomment for code sample purposes print('\n entity count: ', len(entities.all()) ) for x in entities.all(): print(x.__class__.__name__, ' -- ', x.entity_set) print('\n--End of listing the parsed entities--') ''' queryable_factory = SingleQueryable for queryable in entities.all(): URL_COUNT_PER_ENTITYSET = len(queryable.entity_set.entity_type.proprties()) * 1 #Leaving as 1 instead of default 20, so the test output is more understandable and each property has one URL generated ''' uncomment for code sample purposes print('Population range for entity \'{}\' - {} - is set to {}'.format(queryable.entity_set.name, queryable.__class__, URL_COUNT_PER_ENTITYSET)) ''' for _ in range(URL_COUNT_PER_ENTITYSET): q = queryable_factory(queryable, logger, 1) queries = q.generate() ''' uncomment for code sample purposes print(queries[0].query_string) #hardcoded 0, since SingleQueryable is used and therefore generate only one URL ''' assert queries[0].query_string != "" def builder(method): path_to_metadata = Path(__file__).parent.joinpath("metadata-northwind-v2.xml") metadata_file_contents = path_to_metadata.read_bytes() restrictions = RestrictionsGroup(None) builder = DirectBuilder(metadata_file_contents, restrictions,method) entities = builder.build() queryable_factory = SingleQueryable return entities, queryable_factory def test_direct_builder_http_get(): get_entities , queryable_factory = builder("GET") queries_list = [] queries_list.clear() for queryable in get_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries, body = q.generate() queries_list.append(queries.query_string) queries_list=set(queries_list) choice = queries_list.pop() assert ("filter" in choice or "expand" in choice or "startswith" in choice or "replace" in choice or "substring" in choice or "inlinecount" in choice) == True def test_direct_builder_http_delete(): del_entities , queryable_factory = builder("DELETE") queries_list = [] queries_list.clear() for queryable in del_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries,body = q.generate() queries_list.append(queries.query_string) queries_list=set(queries_list) choice = queries_list.pop() assert ("filter" in choice or "expand" in choice or "startswith" in choice or "replace" in choice or "substring" in choice or "inlinecount" in choice) == False def test_direct_builder_http_put_url(): random.seed(20) put_entities , queryable_factory = builder("PUT") queries_list = [] queries_list.clear() for queryable in put_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries,body = q.generate() queries_list.append(queries.query_string) queries_list=queries_list choice = random.choice(queries_list) assert "Orders(OrderID=264879099)?sap-client=500" == choice def test_direct_builder_http_post_url(): random.seed(20) post_entities , queryable_factory = builder("POST") queries_list = [] queries_list.clear() for queryable in post_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries,body = q.generate() queries_list.append(queries.query_string) queries_list=queries_list choice = random.choice(queries_list) assert "Suppliers?sap-client=500" == choice def test_direct_builder_body_generation(): random.seed(20) dir_entities , queryable_factory = builder("PUT") body_list = [] body_list.clear() for queryable in dir_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries,body = q.generate() body_list.append(body) assert random.choice(body_list) == "{\"OrderID\": 264879099, \"CustomerID\": \"PE\", \"EmployeeID\": 1232571814, \"OrderDate\": \"/Date(129712006108)/\", \"RequiredDate\": \"/Date(190417733358)/\", \"ShippedDate\": \"/Date(144052759134)/\", \"ShipVia\": -1121991714, \"Freight\": \"77202251625.6257m\", \"ShipName\": \"\\u00e8r\\u00fefy\\u00f4\\u2020hpD\\u00ff:fVK\\u00e1\\u00f1\\u201d\\u00da^:\", \"ShipAddress\": \"\\u0081\\u00c7\\u00d0F\\u00f0\\u2014\", \"ShipCity\": \"\\u00f6\\u00a1rsH\\u00f6\\u00ac*$\\u00fe\\u00d5\\u00f3\\u00a8\", \"ShipRegion\": \"\\u00eb\", \"ShipPostalCode\": \"d\\u00f2\\u00ae\\u00ff\\u00ea\", \"ShipCountry\": \"ZS\\u00fd\\u0192\\u00c0\"}" def test_direct_builder_http_merge_body(): random.seed(20) merge_entities , queryable_factory = builder("MERGE") body_list = [] body_list.clear() for queryable in merge_entities.all(): entityset_urls_count = len(queryable.entity_set.entity_type.proprties()) for _ in range(entityset_urls_count): q = queryable_factory(queryable, logger, 1) queries,body = q.generate() body_list.append(body) assert body_list[10] == "{\"PostalCode\": \"L\\u00ccN\\u00d2>ge\"}"
#!/usr/bin/env node 'use strict'; const program = require('commander'); const colors = require('colors'); const GasTest = require('../lib/gas-test'); const util = require('../lib/util'); program .option('-o, --output <path>', 'path to result file') .option('-s, --settings <path>', 'path to settins for test', './gas-test.json') .option('-c, --credentials <path>', 'path to credentials file', util.getDefaultCredentialPath()) .option('-r, --reporter <type>', 'type of reporter', 'json') .option('-n, --suppress_console', 'no output to console') .parse(process.argv); util.readJsonFromFile(program.settings).then(settings => { const options = { settings: settings, credentials: program.credentials }; const test = new GasTest(options); test.run([program.reporter]).then(value => { return Promise.all([writeToConsole(value), writeToFile(value)]); }).catch(e => { if (e) { console.error(e); } process.exit(1); }); }); function writeToFile(value) { if (program.output) { if (program.reporter === 'json') { value = JSON.stringify(value); } return util.writeToFile(program.output, value); } } function writeToConsole(json) { if (program.suppress_console) { return; } const writeError = error => { if (error.message) { console.log(` ${colors.red(error.message)}`); } console.log(` ${colors.green('+ expected')} ${colors.red('- actual')}`); const expected = colors.green(`+${error.expected}`); const actual = colors.red(`+${error.actual}`); console.log(` ${expected}`); console.log(` ${actual}`); }; return new Promise((resolve, reject) => { const results = json.results || []; const stats = json.stats; let title; results.map(result => { if (title != result.title) { title = result.title; console.log(' %s', result.title); } console.log(' %s %s', result.failure ? colors.red('✖') : colors.green('✓'), colors.gray(result.name)); if (result.error) { writeError(result.error); } }); const passing = colors.green(`${stats.passes} passing`); const duration = colors.gray(`(${stats.duration}ms)`); console.log(''); console.log(` ${passing} ${duration}`); if (stats.failures) { const failing = colors.red(`${stats.failures} failing`); console.log(` ${failing}`); } stats.failures === 0 ? resolve(0) : reject(); }); }
/* * Copyright (C) 2021 by Intel Corporation * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #ifndef GATHER_VINSERT_H__ #define GATHER_VINSERT_H__ #include <stdbool.h> #include <stddef.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif void gather_vinsert(int32_t *in, int32_t *out, uint32_t *index, size_t len); bool gather_vinsert_check(int32_t *in, int32_t *out, uint32_t *index, size_t len); #ifdef __cplusplus } #endif #endif
import functools import caproto as ca import trio from trio import socket from ..server import AsyncLibraryLayer from ..server.common import (VirtualCircuit as _VirtualCircuit, Context as _Context, LoopExit, DisconnectedCircuit) from .util import open_memory_channel from .._utils import safe_getsockname class ServerExit(Exception): ... class Event: """ The class wraps `trio.Event` and implements `Event.clear()` method that is used in the code, but deprecated in `trio`. The event is cleared by creating the new event that if the event is set. If the event is not set, then old event is left. The class is not intended to be thread safe. """ def __init__(self): self._create_event() def _create_event(self): self._event = trio.Event() def set(self): self._event.set() def clear(self): """ Clearing of the event is implemented by creating a new event if the event is set. It is assumed that if the event is set, then it is not waited on. """ if self._event.is_set(): self._create_event() def is_set(self): return self._event.is_set() async def wait(self, timeout=None): if timeout is not None: with trio.move_on_after(timeout): await self._event.wait() return True return False else: await self._event.wait() return True def _universal_queue(max_len=1000): class UniversalQueue: def __init__(self): self._send, self._recv = open_memory_channel(max_len) def put(self, value): trio.from_thread.run(self._send.send, value) async def async_put(self, value): await self._send.send(value) def get(self): return trio.from_thread.run(self._recv.receive) async def async_get(self): return await self._recv.receive() return UniversalQueue class TrioAsyncLayer(AsyncLibraryLayer): def __init__(self): self.ThreadsafeQueue = _universal_queue() name = 'trio' ThreadsafeQueue = None Event = Event library = trio class VirtualCircuit(_VirtualCircuit): "Wraps a caproto.VirtualCircuit with a trio client." TaskCancelled = trio.Cancelled def __init__(self, circuit, client, context): super().__init__(circuit, client, context) self._raw_lock = trio.Lock() self.nursery = context.nursery self.QueueFull = trio.WouldBlock self.command_chan = open_memory_channel(ca.MAX_COMMAND_BACKLOG) # For compatibility with server common: self.command_queue = self.command_chan.send self.new_command_condition = trio.Condition() self.subscription_chan = open_memory_channel(ca.MAX_TOTAL_SUBSCRIPTION_BACKLOG) # For compatibility with server common: self.subscription_queue = self.subscription_chan.send self.write_event = Event() self.events_on = trio.Event() async def run(self): await self.nursery.start(self.command_queue_loop) await self.nursery.start(self.subscription_queue_loop) async def command_queue_loop(self, task_status): self.write_event.set() send, recv = self.command_chan async with send: async with recv: task_status.started() try: async for command in recv: response = await self._command_queue_iteration(command) if response is not None: await self.send(*response) await self._wake_new_command() except DisconnectedCircuit: await self._on_disconnect() self.circuit.disconnect() await self.context.circuit_disconnected(self) except trio.Cancelled: ... except LoopExit: ... async def subscription_queue_loop(self, task_status): task_status.started() await super().subscription_queue_loop() async def get_from_sub_queue(self, timeout=None): # Timeouts work very differently between our server implementations, # so we do this little stub in its own method. _, recv = self.subscription_chan if timeout is None: return await recv.receive() with trio.move_on_after(timeout): return await recv.receive() async def _on_disconnect(self): """Executed when disconnection detected""" await super()._on_disconnect() self.client.close() async def _start_write_task(self, handle_write): self.nursery.start_soon(handle_write) async def _wake_new_command(self): async with self.new_command_condition: self.new_command_condition.notify_all() class Context(_Context): CircuitClass = VirtualCircuit async_layer = TrioAsyncLayer ServerExit = ServerExit TaskCancelled = trio.Cancelled def __init__(self, pvdb, interfaces=None): super().__init__(pvdb, interfaces) self.nursery = None self.command_chan = open_memory_channel(ca.MAX_COMMAND_BACKLOG) self.command_bundle_queue = self.command_chan.send self.subscription_chan = open_memory_channel(ca.MAX_TOTAL_SUBSCRIPTION_BACKLOG) self.subscription_queue = self.subscription_chan.send self.beacon_sock = ca.bcast_socket(socket) async def broadcaster_udp_server_loop(self, task_status): for interface in self.interfaces: udp_sock = ca.bcast_socket(socket) self.broadcaster.server_addresses.append( safe_getsockname(udp_sock)) try: await udp_sock.bind((interface, self.ca_server_port)) except Exception: self.log.exception('UDP bind failure on interface %r', interface) raise self.log.debug('UDP socket bound on %s:%d', interface, self.ca_server_port) self.udp_socks[interface] = udp_sock for interface, udp_sock in self.udp_socks.items(): self.log.debug('Broadcasting on %s:%d', interface, self.ca_server_port) self.nursery.start_soon(self._core_broadcaster_loop, udp_sock) task_status.started() async def broadcaster_queue_loop(self, task_status): send, recv = self.command_chan async with send: async with recv: try: task_status.started() async for addr, commands in recv: await super()._broadcaster_queue_iteration(addr, commands) except trio.Cancelled: ... except LoopExit: ... async def subscription_queue_loop(self, task_status): send, recv = self.subscription_chan async with send: async with recv: task_status.started() async for item in recv: sub_specs, metadata, values, flags, sub = item await self._subscription_queue_iteration( sub_specs, metadata, values, flags, sub) async def broadcast_beacon_loop(self, task_status): task_status.started() await super().broadcast_beacon_loop() async def server_accept_loop(self, listen_sock, *, task_status): try: listen_sock.listen() task_status.started() while True: client_sock, addr = await listen_sock.accept() self.nursery.start_soon(self.tcp_handler, client_sock, addr) finally: listen_sock.close() async def run(self, *, log_pv_names=False): 'Start the server' self.log.info('Trio server starting up...') try: async with trio.open_nursery() as self.nursery: for address in ca.get_beacon_address_list(): sock = ca.bcast_socket(socket) await sock.connect(address) interface, _ = safe_getsockname(sock) self.beacon_socks[address] = (interface, sock) async def make_socket(interface, port): s = trio.socket.socket() await s.bind((interface, port)) return s res = await self._bind_tcp_sockets_with_consistent_port_number( make_socket) self.port, self.tcp_sockets = res await self.nursery.start(self.broadcaster_udp_server_loop) await self.nursery.start(self.broadcaster_queue_loop) await self.nursery.start(self.subscription_queue_loop) await self.nursery.start(self.broadcast_beacon_loop) # Only after all loops have been started, begin listening: for interface, listen_sock in self.tcp_sockets.items(): self.log.info("Listening on %s:%d", interface, self.port) await self.nursery.start(self.server_accept_loop, listen_sock) async_lib = TrioAsyncLayer() for name, method in self.startup_methods.items(): self.log.debug('Calling startup method %r', name) async def startup(task_status): task_status.started() await method(async_lib) await self.nursery.start(startup) self.log.info('Server startup complete.') if log_pv_names: self.log.info('PVs available:\n%s', '\n'.join(self.pvdb)) except trio.Cancelled: self.log.info('Server task cancelled. Will shut down.') finally: self.log.info('Server exiting....') async_lib = TrioAsyncLayer() async with trio.open_nursery() as nursery: for name, method in self.shutdown_methods.items(): self.log.debug('Calling shutdown method %r', name) async def shutdown(task_status): task_status.started() await method(async_lib) await nursery.start(shutdown) for sock in self.tcp_sockets.values(): sock.close() for sock in self.udp_socks.values(): sock.close() for _interface, sock in self.beacon_socks.values(): sock.close() def stop(self): 'Stop the server' nursery = self.nursery if nursery is None: return nursery.cancel_scope.cancel() async def start_server(pvdb, *, interfaces=None, log_pv_names=False): '''Start a trio server with a given PV database''' ctx = Context(pvdb, interfaces=interfaces) return (await ctx.run(log_pv_names=log_pv_names)) def run(pvdb, *, interfaces=None, log_pv_names=False): """ A synchronous function that runs server, catches KeyboardInterrupt at exit. """ try: return trio.run( functools.partial( start_server, pvdb, interfaces=interfaces, log_pv_names=log_pv_names)) except KeyboardInterrupt: return
/** * --- Day 9: Smoke Basin --- These caves seem to be lava tubes. Parts are even still volcanically active; small hydrothermal vents release smoke into the caves that slowly settles like rain. If you can model how the smoke flows through the caves, you might be able to avoid it and be that much safer. The submarine generates a heightmap of the floor of the nearby caves for you (your puzzle input). Smoke flows to the lowest point of the area it's in. For example, consider the following heightmap: 2199943210 3987894921 9856789892 8767896789 9899965678 Each number corresponds to the height of a particular location, where 9 is the highest and 0 is the lowest a location can be. Your first goal is to find the low points - the locations that are lower than any of its adjacent locations. Most locations have four adjacent locations (up, down, left, and right); locations on the edge or corner of the map have three or two adjacent locations, respectively. (Diagonal locations do not count as adjacent.) In the above example, there are four low points, all highlighted: two are in the first row (a 1 and a 0), one is in the third row (a 5), and one is in the bottom row (also a 5). All other locations on the heightmap have some lower adjacent location, and so are not low points. The risk level of a low point is 1 plus its height. In the above example, the risk levels of the low points are 2, 1, 6, and 6. The sum of the risk levels of all low points in the heightmap is therefore 15. Find all of the low points on your heightmap. What is the sum of the risk levels of all low points on your heightmap? */ const testInput = [ '2199943210', '3987894921', '9856789892', '8767896789', '9899965678', ]; const testMap = testInput.map((row) => row.split('').map((el) => parseInt(el))); // First find locations that are lower than any of the adjacent points. // Adjacent points are points up/down/left/right of the current point. const fs = require('fs'); const input = fs.readFileSync('./input/day9.txt', 'utf-8').split('\n'); // Create numeric point map of rows/cols const pointMap = input.map((row) => row.split('').map((el) => parseInt(el))); console.log( 'Part 1 Answer: Total Risk Level of Lowest Map Points: ', lowestPoints(pointMap)[0] ); // 545 /** * Calculates and returns the Risk Level of the terrain as well as an object containing the lowest points in the terrain * * @param {Numbers[][]} pointMap Height Map of terrain, each entry is an array of numbers representing the terrain height at that row, column position. * @returns {[Number, {[key: string]: Number}]} The first entry is the risk level of the lowest points in the input map, * the second entry is an object with keys being the locations of the lowest points and the values being the corresponding height of the lowest points */ function lowestPoints(pointMap) { const lowest = {}; let riskLevel = 0; const rowMax = pointMap.length; const colMax = pointMap[0].length; // Iterate through pointMap and locate points lower than their surroundings: for (let i = 0; i < rowMax; i += 1) { for (let j = 0; j < colMax; j += 1) { const pointVal = pointMap[i][j]; // Determine if current point is lower than its surroundings: if (i - 1 >= 0 && pointMap[i - 1][j] <= pointVal) { continue; } else if (i + 1 < rowMax && pointMap[i + 1][j] <= pointVal) { continue; } else if (j - 1 >= 0 && pointMap[i][j - 1] <= pointVal) { continue; } else if (j + 1 < colMax && pointMap[i][j + 1] <= pointVal) { continue; } // If we reach here this point is lower than all its surroundings: lowest[[i, j]] = pointVal; riskLevel += pointVal + 1; } } return [riskLevel, lowest]; } /** * --- Part Two --- Next, you need to find the largest basins so you know what areas are most important to avoid. A basin is all locations that eventually flow downward to a single low point. Therefore, every low point has a basin, although some basins are very small. Locations of height 9 do not count as being in any basin, and all other locations will always be part of exactly one basin. The size of a basin is the number of locations within the basin, including the low point. The example above has four basins. The top-left basin, size 3: 2199943210 3987894921 9856789892 8767896789 9899965678 The top-right basin, size 9: 2199943210 3987894921 9856789892 8767896789 9899965678 The middle basin, size 14: 2199943210 3987894921 9856789892 8767896789 9899965678 The bottom-right basin, size 9: 2199943210 3987894921 9856789892 8767896789 9899965678 Find the three largest basins and multiply their sizes together. In the above example, this is 9 * 14 * 9 = 1134. What do you get if you multiply together the sizes of the three largest basins? */ // Use BFS/DFS to find all points associated with each basin console.log( 'Part 2 Answer: Multiplied sizes of three largest basins on map: ', mapBasins(pointMap) ); // 950600 /** * Calculates and returns sizes of the three largest basins in the map multiplied together * * @param {Numbers[][]} pointMap Height Map of terrain, each entry is an array of numbers representing the terrain height at that row, column position. * @returns {Number} Size of the three largest basins multipled together */ function mapBasins(pointMap) { // Get locations of lowest points in the input const lowPoints = lowestPoints(pointMap)[1]; const biggest = [0, 0, 0]; // For each low point, map its basin and add its basin size to lowPoints object: const rowMax = pointMap.length; const colMax = pointMap[0].length; Object.keys(lowPoints).forEach((coords) => { const [startRow, startCol] = coords.split(',').map((el) => parseInt(el)); const stack = [[startRow, startCol]]; let size = 1; pointMap[startRow][startCol] = 9; // Find all points associated with this low point: while (stack.length) { const [row, col] = stack.pop(); // console.log(pointMap, row, col, stack); // Add any valid surrounding points to stack: for (let inc = -1; inc < 2; inc += 2) { // Check up/down: if ( row + inc >= 0 && row + inc < rowMax && pointMap[row + inc][col] !== 9 ) { stack.push([row + inc, col]); size += 1; pointMap[row + inc][col] = 9; } // Check left/right: if ( col + inc >= 0 && col + inc < colMax && pointMap[row][col + inc] !== 9 ) { stack.push([row, col + inc]); size += 1; pointMap[row][col + inc] = 9; } } } // Track the size of each basin and the size of the three largest basins lowPoints[coords] = size; if (size > biggest[2]) { biggest[0] = biggest[1]; biggest[1] = biggest[2]; biggest[2] = size; } else if (size > biggest[1]) { biggest[0] = biggest[1]; biggest[1] = size; } else if (size > biggest[0]) { biggest[0] = size; } }); // Return product of 3 largest basins return biggest.reduce((accum, el) => (accum *= el), 1); }
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var jasminePatch = require('../jasmine/patch'); jasminePatch.apply(); },{"../jasmine/patch":2}],2:[function(require,module,exports){ (function (global){ 'use strict'; // Patch jasmine's it and fit functions so that the `done` callback always resets the zone // to the jasmine zone, which should be the root zone. (angular/zone.js#91) function apply() { if (!global.zone) { throw new Error('zone.js does not seem to be installed'); } if (!global.zone.isRootZone()) { throw new Error('The jasmine patch should be called from the root zone'); } var jasmineZone = global.zone; var originalIt = global.it; var originalFit = global.fit; global.it = function zoneResettingIt(description, specFn, timeOut) { if (specFn.length) { originalIt(description, function zoneResettingSpecFn(originalDone) { specFn(function zoneResettingDone() { jasmineZone.run(originalDone); }); }, timeOut); } else { originalIt(description, specFn, timeOut); } }; global.fit = function zoneResettingFit(description, specFn, timeOut) { if (specFn.length) { originalFit(description, function zoneResettingSpecFn(originalDone) { specFn(function zoneResettingDone() { jasmineZone.run(originalDone); }); }, timeOut); } else { originalFit(description, specFn, timeOut); } }; // global beforeEach to check if we always start from the root zone beforeEach(function() { expect(global.zone.isRootZone()).toBe(true); }); } if (global.jasmine) { module.exports = { apply: apply }; } else { module.exports = { apply: function() { } }; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}]},{},[1]);
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sstream> #include <arpa/inet.h> #include <string> #include "data_def.h" class NetworkTool { public: static NetworkTool* get_instance() { if (s_instance == NULL) { s_instance = new NetworkTool(); } return s_instance; } static int destroy_instance() { if (s_instance != NULL) { delete s_instance; } return 0; } int connect_server() { struct sockaddr_in server_address; if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("create socket error!\n"); return -1; } memset(&server_address, 0, sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(8897); if(inet_pton(AF_INET, ip_addr.c_str(), &server_address.sin_addr) <= 0) { printf("inet_pton error!\n"); return -1; } if(connect(socket_fd, (sockaddr *)&server_address, sizeof(server_address)) == -1) { printf("connect error!\n"); return -1; } return 0; } int disconnect_server() { close(socket_fd); socket_fd = -1; return 0; } int login(std::string user_name, UserData * user_data); int get_frame_sync_data(FrameSyncData * sync_data); int push_frame_upda_data(FrameUpdaData * upda_data); int start_game_req(); int start_game_resp(); private: Json::Value value; Json::Reader reader; int socket_fd; std::string ip_addr; char * buff; NetworkTool() { buff = NULL; buff = new char[5000]; socket_fd = -1; ip_addr = "127.0.0.1"; } ~NetworkTool() { if (buff != NULL) delete [] buff; } static NetworkTool* s_instance; };
import logging import os log_level = getattr(logging, os.getenv('LOG_LEVEL', 'DEBUG')) fmt = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s' logging.basicConfig(level=log_level, format=fmt) def make_logger(file_path='NO_FILE'): file_name = file_path.split("/")[-1] return logging.getLogger(file_name)
# -*- coding: utf-8 -*- # Author: Florian Mayer <florian.mayer@bitsrc.org> """ Offer a callable object that dispatches based on arbitrary conditions and function signature. That means, whenever it is called, it finds the registered methods that match the input's signature and then checks for user-defined conditions and types. First, we need to create a new ConditionalDispatch >>> from sunpy.util.cond_dispatch import ConditionalDispatch >>> fun = ConditionalDispatch() We then can start adding branches, in this case we add a branch for even integers, in which case the function applied is a multiplication by three. >>> fun.add(lambda x: 3 * x, lambda x: x % 2 == 0, [int]) By adding the other branch (odd), the function can be used for all integers. In the case of an odd integer, we double the input. Please note that the system has no way of verifying the conditions are mutually exclusive. In some cases it can even be useful to use not mutually exclusive conditions, in which case the branch that was added the earliest is executed. >>> fun.add(lambda x: 2 * x, lambda x: x % 2 == 1, [int]) We can verify this is working. >>> fun(2) 6 >>> fun(3) 6 And that using a float, e.g., does not. >>> fun(3.2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/florian/Projects/sunpy/sunpy/util/cond_dispatch.py", line 128, in __call__ "There are no functions matching your input parameter " TypeError: There are no functions matching your input parameter signature. We can then add a branch for floats, giving the condition None that means that this branch is always executed for floats. >>> fun.add(lambda y: 5 * y, None, [float]) Also note that the float branch takes y, while the integer branch takes x. Thus, if the user explicitly passes fun(x=1) using a keyword argument, only the integer branch is considered. This can be useful if the user wants control over which kind of data they are passing the the function. >>> fun(2.0) 10.0 >>> fun(y=2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/florian/Projects/sunpy/sunpy/util/cond_dispatch.py", line 128, in __call__ "There are no functions matching your input parameter " TypeError: There are no functions matching your input parameter signature. >>> fun(y=2.5) 12.5 >>> fun(x=2) 6 >>> fun(x=2.5) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/florian/Projects/sunpy/sunpy/util/cond_dispatch.py", line 128, in __call__ "There are no functions matching your input parameter " TypeError: There are no functions matching your input parameter signature. """ import inspect from itertools import chain, repeat __all__ = ['run_cls', 'matches_types', 'arginize', 'correct_argspec', 'matches_signature', 'ConditionalDispatch', 'fmt_argspec_types'] def run_cls(name): """ run_cls("foo")(cls, *args, **kwargs) -> cls.foo(*args, **kwargs) """ fun = lambda cls, *args, **kwargs: getattr(cls, name)(*args, **kwargs) fun.__name__ = str(name) fun.run_cls = True return fun def matches_types(fun, types, args, kwargs): """ See if args and kwargs match are instances of types. types are given in the order they are defined in the function. kwargs are automatically converted into that order. """ return all( isinstance(obj, cls) for obj, cls in zip( arginize(fun, args, kwargs), types ) ) def arginize(fun, a, kw): """ Turn args and kwargs into args by considering the function signature. """ argspec = correct_argspec(fun) args = argspec.args varargs = argspec.varargs defaults = argspec.defaults if varargs is not None: raise ValueError names = args[len(a):] if defaults: defs = dict(zip(args[-len(defaults):], defaults)) else: defs = {} return list(a) + [kw.get(name, defs.get(name, None)) for name in names] def correct_argspec(fun): """ Remove first argument if method is bound. """ fullargspec = inspect.getfullargspec(fun) if inspect.ismethod(fun): fullargspec = fullargspec[1:] return fullargspec def matches_signature(fun, a, kw): """ Check whether function can be called with a as args and kw as kwargs. """ argspec = correct_argspec(fun) args = argspec.args varargs = argspec.varargs keywords = argspec.varkw defaults = argspec.defaults if varargs is None and len(a) > len(args): return False skw = set(kw) sargs = set(args[len(a):]) # There mayn't be unexpected parameters unless there is a **kwargs # in fun's signature. if keywords is None and skw - sargs != set(): return False rest = set(args[len(a):]) - set(kw) # If there are any arguments that weren't passed but do not have # defaults, the signature does not match. defs = set() if defaults is None else set(defaults) if keywords is None and rest > defs: return False return True class ConditionalDispatch(object): def __init__(self): self.funcs = [] self.nones = [] @classmethod def from_existing(cls, cond_dispatch): new = cls() new.funcs = cond_dispatch.funcs[:] new.nones = cond_dispatch.nones[:] return new def add_dec(self, condition): def _dec(fun): self.add(fun, condition) return fun return _dec def add(self, fun, condition=None, types=None, check=True): """ Add fun to ConditionalDispatch under the condition that the arguments must match. If condition is left out, the function is executed for every input that matches the signature. Functions are considered in the order they are added, but ones with condition=None are considered as the last: that means, a function with condition None serves as an else branch for that signature. conditions must be mutually exclusive because otherwise which will be executed depends on the order they are added in. Function signatures of fun and condition must match (if fun is bound, the bound parameter needs to be left out in condition). """ if condition is None: self.nones.append((fun, types)) elif check and correct_argspec(fun) != correct_argspec(condition): raise ValueError( "Signature of condition must match signature of fun." ) else: self.funcs.append((fun, condition, types)) def __call__(self, *args, **kwargs): matched = False for fun, condition, types in self.funcs: if (matches_signature(condition, args, kwargs) and (types is None or matches_types(condition, types, args, kwargs))): matched = True if condition(*args, **kwargs): return fun(*args, **kwargs) for fun, types in self.nones: if (matches_signature(fun, args, kwargs) and (types is None or matches_types(fun, types, args, kwargs))): return fun(*args, **kwargs) if matched: raise TypeError( "Your input did not fulfill the condition for any function." ) else: raise TypeError( "There are no functions matching your input parameter " "signature." ) def wrapper(self): return lambda *args, **kwargs: self(*args, **kwargs) def get_signatures(self, prefix="", start=0): """ Return an iterator containing all possible function signatures. If prefix is given, use it as function name in signatures, else leave it out. If start is given, leave out first n elements. If start is -1, leave out first element if the function was created by run_cls. """ for fun, condition, types in self.funcs: if start == -1: st = getattr(fun, 'run_cls', 0) else: st = start if types is not None: yield prefix + fmt_argspec_types(condition, types, st) else: args, varargs, keywords, defaults = correct_argspec(condition) args = args[st:] yield prefix + inspect.formatargspec( args, varargs, keywords, defaults ) for fun, types in self.nones: if types is not None: yield prefix + fmt_argspec_types(fun, types, st) else: args, varargs, keywords, defaults = correct_argspec(condition) args = args[st:] yield prefix + inspect.formatargspec( args, varargs, keywords, defaults ) def generate_docs(self): fns = (item[0] for item in chain(self.funcs, self.nones)) return '\n\n'.join("{0} -> :py:meth:`{1}`".format(sig, fun.__name__) for sig, fun in # The 1 prevents the cls from incorrectly being shown in the # documentation. zip(self.get_signatures("create", -1), fns) ) def fmt_argspec_types(fun, types, start=0): args, varargs, keywords, defaults = correct_argspec(fun) args = args[start:] types = types[start:] NULL = object() if defaults is None: defaults = [] defs = chain(repeat(NULL, len(args) - len(defaults)), defaults) spec = [] for key, value, type_ in zip(args, defs, types): # This is a work around for a bug introduced during Python 3 porting. # for some reason the type was being passed in as a length 1 tuple. # This extracts the type under that condition. SM 6/10/15 if isinstance(type_, tuple) and len(type_) == 1: type_ = type_[0] if value is NULL: spec.append("{0}: {1}".format(key, type_.__name__)) else: spec.append("{0}: {1} = {2}".format(key, type_.__name__, value)) if varargs is not None: spec.append('*{!s}'.format(varargs)) if keywords is not None: spec.append('**{!s}'.format(keywords)) return '(' + ', '.join(spec) + ')'
import os from tqdm import tqdm import numpy as np import pandas as pd import torch import networkx as nx from torch_geometric.data import Data, InMemoryDataset import torch_geometric.transforms as T from rdkit import Chem, RDConfig from rdkit.Chem import ChemicalFeatures from utils import Complete, angle, area_triangle, cal_dist def load_dataset(path, specify_target): # apply transform class SpecifyTarget(object): def __call__(self, data): data.y = data.y[specify_target].view(-1) return data transform = T.Compose([SpecifyTarget(), Complete(), T.Distance(norm=True)]) print('Check split dataset...') save_path = path + 'train_valid_test.ckpt' if os.path.isfile(save_path): trn, val, test = torch.load(save_path) trn.transform = transform val.transform = transform test.transform = transform return trn, val, test print('Load dataset...') dataset = QM9Dataset(root=path).shuffle() print('Split the dataset...') one_tenth = len(dataset) // 10 test_dataset = dataset[: one_tenth] valid_dataset = dataset[one_tenth: one_tenth * 2] train_dataset = dataset[one_tenth * 2:] assert len(train_dataset) + len(valid_dataset) + len(test_dataset) == len(dataset) print('Save dataset...') torch.save([train_dataset, valid_dataset, test_dataset], save_path) return load_dataset(path, specify_target) class QM9Dataset(InMemoryDataset): def __init__(self, root, transform=None, pre_transform=None, pre_filter=None): super(QM9Dataset, self).__init__(root, transform, pre_transform, pre_filter) self.data, self.slices = torch.load(self.processed_paths[0]) @property def raw_file_names(self): return ['gdb9.sdf', 'gdb9.sdf.csv'] @property def processed_file_names(self): return 'processed_qm9.pt' def download(self): pass def process(self): data_path = self.raw_paths[0] target_path = self.raw_paths[1] self.property_names = ['mu', 'alpha', 'homo', 'lumo', 'gap', 'r2', 'zpve', 'u0', 'u298', 'h298', 'g298', 'cv'] self.target = pd.read_csv(target_path, index_col='mol_id') self.target = self.target[self.property_names] supplier = Chem.SDMolSupplier(data_path, removeHs=False) data_list = [] for i, mol in tqdm(enumerate(supplier)): data = self.mol2graph(mol) if data is not None: data.y = torch.FloatTensor(self.target.iloc[i, :]) data_list.append(data) if self.pre_filter is not None: data_list = [data for data in data_list if self.pre_filter(data)] if self.pre_transform is not None: data_list = [self.pre_transform(data) for data in data_list] data, slices = self.collate(data_list) torch.save((data, slices), self.processed_paths[0]) def get_nodes(self, g): feat = [] for n, d in g.nodes(data=True): h_t = [] h_t += [int(d['a_type'] == x) for x in ['H', 'C', 'N', 'O', 'F', 'Cl', 'S']] h_t.append(d['a_num']) h_t.append(d['acceptor']) h_t.append(d['donor']) h_t.append(int(d['aromatic'])) h_t += [int(d['hybridization'] == x) \ for x in (Chem.rdchem.HybridizationType.SP, \ Chem.rdchem.HybridizationType.SP2, Chem.rdchem.HybridizationType.SP3)] h_t.append(d['num_h']) # 5 more h_t.append(d['formal_charge']) h_t.append(d['explicit_valence']) h_t.append(d['implicit_valence']) h_t.append(d['num_explicit_hs']) h_t.append(d['num_radical_electrons']) feat.append((n, h_t)) feat.sort(key=lambda item: item[0]) node_attr = torch.FloatTensor([item[1] for item in feat]) return node_attr def get_edges(self, g): e = {} for n1, n2, d in g.edges(data=True): e_t = [int(d['b_type'] == x) for x in (Chem.rdchem.BondType.SINGLE, \ Chem.rdchem.BondType.DOUBLE, \ Chem.rdchem.BondType.TRIPLE, \ Chem.rdchem.BondType.AROMATIC)] e_t.append(d['anglemax']) e_t.append(d['anglesum']) e_t.append(d['anglemean']) e_t.append(d['areamax']) e_t.append(d['areasum']) e_t.append(d['areamean']) e_t.append(d['dikmax']) e_t.append(d['diksum']) e_t.append(d['dikmean']) e_t.append(d['dij1']) e_t.append(d['dij2']) e[(n1, n2)] = e_t edge_index = torch.LongTensor(list(e.keys())).transpose(0, 1) edge_attr = torch.FloatTensor(list(e.values())) return edge_index, edge_attr def mol2graph(self, mol): if mol is None: return None g = nx.DiGraph() # Create nodes assert len(mol.GetConformers()) == 1 geom = mol.GetConformers()[0].GetPositions() for i in range(mol.GetNumAtoms()): atom_i = mol.GetAtomWithIdx(i) g.add_node(i, a_type=atom_i.GetSymbol(), a_num=atom_i.GetAtomicNum(), acceptor=0, # 0 for placeholder donor=0, aromatic=atom_i.GetIsAromatic(), hybridization=atom_i.GetHybridization(), num_h=atom_i.GetTotalNumHs(includeNeighbors=True), # 5 more node features formal_charge=atom_i.GetFormalCharge(), explicit_valence=atom_i.GetExplicitValence(), implicit_valence=atom_i.GetImplicitValence(), num_explicit_hs=atom_i.GetNumExplicitHs(), num_radical_electrons=atom_i.GetNumRadicalElectrons(), ) # Electron donor and acceptor fdef_name = os.path.join(RDConfig.RDDataDir, 'BaseFeatures.fdef') factory = ChemicalFeatures.BuildFeatureFactory(fdef_name) feats = factory.GetFeaturesForMol(mol) for f in range(len(feats)): if feats[f].GetFamily() == 'Donor': for atom_id in feats[f].GetAtomIds(): g.nodes[atom_id]['donor'] = 1 elif feats[f].GetFamily() == 'Acceptor': for atom_id in feats[f].GetAtomIds(): g.nodes[atom_id]['acceptor'] = 1 # Read Edges for i in range(mol.GetNumAtoms()): for j in range(mol.GetNumAtoms()): e_ij = mol.GetBondBetweenAtoms(i, j) if e_ij is not None: # cal angle and area assert mol.GetNumAtoms() == len(geom) angles_ijk = [] areas_ijk = [] dists_ik = [] for neighbor in mol.GetAtomWithIdx(j).GetNeighbors(): k = neighbor.GetIdx() if mol.GetBondBetweenAtoms(j, k) is not None and i != k: vector1 = geom[j] - geom[i] vector2 = geom[k] - geom[i] angles_ijk.append(angle(vector1, vector2)) areas_ijk.append(area_triangle(vector1, vector2)) dists_ik.append(cal_dist(geom[i], geom[k])) angles_ijk = np.array(angles_ijk) if angles_ijk != [] else np.array([0.]) areas_ijk = np.array(areas_ijk) if areas_ijk != [] else np.array([0.]) dists_ik = np.array(dists_ik) if dists_ik != [] else np.array([0.]) dist_ij1 = cal_dist(geom[i], geom[j], ord=1) dist_ij2 = cal_dist(geom[i], geom[j], ord=2) g.add_edge(i, j, b_type=e_ij.GetBondType(), anglemax=angles_ijk.max(), anglesum=angles_ijk.sum(), anglemean=angles_ijk.mean(), areamax=areas_ijk.max(), areasum=areas_ijk.sum(), areamean=areas_ijk.mean(), dikmax=dists_ik.max(), diksum=dists_ik.sum(), dikmean=dists_ik.mean(), dij1=dist_ij1, dij2=dist_ij2, ) # Build pyg data node_attr = self.get_nodes(g) edge_index, edge_attr = self.get_edges(g) pos = torch.FloatTensor(geom) data = Data( x=node_attr, pos=pos, edge_index=edge_index, edge_attr=edge_attr, y=None, # None as a placeholder # name=mol.GetProp('_Name'), ) return data if __name__ == '__main__': dataset = QM9Dataset('../dataset_qm9/')
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. class KeyDetail(object): def __init__(self, keyId, keyName, keyVersionCount, keyVersionList, rotationCycle=None): """ :param keyId: KeyID :param keyName: Key名称 :param rotationCycle: (Optional) 轮换周期 :param keyVersionCount: Key版本的个数 :param keyVersionList: Key版本详情的列表 """ self.keyId = keyId self.keyName = keyName self.rotationCycle = rotationCycle self.keyVersionCount = keyVersionCount self.keyVersionList = keyVersionList
(function(angular, _){ "use strict"; /** * @ngdoc module * * @name mfl.setup.controllers.documents * * @description * Contains all the controllers used for county setup */ angular.module("mfl.setup.controllers.documents", ["mfl.setup.api"]) /** * @ngdoc controller * * @name mfl.setup.controller.documents.list * * @description * The controller used to list the documents */ .controller("mfl.setup.controllers.documents.list", ["$scope", function ($scope) { $scope.title = { icon: "", name: "Manage Documents" }; $scope.filters = { "fields": "id,name,description,fyl" }; $scope.action = [ { func : "ui-sref='setup.documents.create'" + " requires-user-feature='is_staff'" + " requires-permission='common.view_documentupload'", class: "btn btn-primary", tipmsg: "Add document", wording: "Add Document" } ]; }]) /** * @ngdoc controller * * @name mfl.setup.controller.documents.edit * * @description * The controller used to edit a document */ .controller("mfl.setup.controllers.documents.edit", ["$scope", "adminApi", "$stateParams", "$state", "$window", function ($scope, adminApi, $stateParams, $state, $window) { $scope.state = !_.isUndefined($stateParams.document_id); $scope.title = { icon: "", name: "Manage Documents" }; $scope.action = [ { func: "ng-show='state' ui-sref='setup.documents.edit.delete({"+ "document_id:document.id})'" + " requires-user-feature='is_staff'" + " requires-permission='common.delete_documentupload'", class: "btn btn-danger", wording: "Delete", tipmsg: "Delete Document" } ]; $scope.wrapper = adminApi.documents; $scope.document = { "id": "", "name": "", "description": "", "file_url": "", "file": null }; var success_fxn = function() {$state.go("setup.documents");}; var error_fxn = function(config) {$scope.errors = _.omit(config.data, "error_msg");}; var is_update = !!$stateParams.document_id; if (is_update) { adminApi.documents.get($stateParams.document_id) .then(function (config) { $scope.document = { "id": config.data.id, "name": config.data.name, "description": config.data.description, "file_url": config.data.fyl, "file": null }; $scope.deleteText = $scope.document.name; }, error_fxn); } var validateFile = function (frm_field, fyl_obj) { var max_size = (100 * 1024 * 1024); // 100MB var min_size = (1 * 1024); // 1KB if (angular.isObject(fyl_obj)) { var errors = []; if (fyl_obj.size > max_size) { errors.push("The file is too big"); } if (fyl_obj.size < min_size) { errors.push("The file is too small"); } if (_.isEmpty(errors)) { return true; } $scope.errors = {}; $scope.errors[frm_field.$name] = errors; return false; } $scope.errors = {}; $scope.errors[frm_field.$name] = ["This field is required"]; return false; }; $scope.fileUpdated = function (elem, fyl) { $scope.document.file = fyl; validateFile(elem, fyl); }; $scope.save = function (frm) { var f = $window.$("input[type='file'][name='fyl']")[0].files[0]; var payload = { "name": $scope.document.name, "description": $scope.document.description }; if (is_update && !f) { // use json if the file is not updated adminApi.documents.update($scope.document.id, payload) .then(success_fxn, error_fxn); } else { // use multipart form for everything else if (validateFile(frm.fyl, f)) { var url = adminApi.documents.makeUrl(adminApi.documents.apiBaseUrl); if ($scope.document.id) { url += $scope.document.id + "/"; } adminApi.uploadFile(url, f, "fyl", payload, is_update) .then(success_fxn, error_fxn); } } }; $scope.remove = function () { adminApi.documents.remove($scope.document.id) .then(success_fxn, error_fxn); }; $scope.cancel = function () { $state.go("setup.documents.edit", {"document_id": $scope.document.id}); }; }] ); })(window.angular, window._);
// Copyright 2009 the Sputnik authors. All rights reserved. /** * No matter how control leaves the embedded 'Statement', * the scope chain is always restored to its former state * * @path ch12/12.10/S12.10_A3.4_T1.js * @description Using "with" statement within iteration statement, leading to normal completion * @noStrict */ this.p1 = 1; var result = "result"; var myObj = { p1: 'a', value: 'myObj_value', valueOf : function(){return 'obj_valueOf';} } do { with(myObj){ p1 = 'x1'; } } while(false); ////////////////////////////////////////////////////////////////////////////// //CHECK#1 if(p1 !== 1){ $ERROR('#1: p1 === 1. Actual: p1 ==='+ p1 ); } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if(myObj.p1 !== "x1"){ $ERROR('#2: myObj.p1 === "x1". Actual: myObj.p1 ==='+ myObj.p1 ); } // //////////////////////////////////////////////////////////////////////////////
# Django settings for powwow project. DEBUG = False TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Angel Ramboi', 'angel.ramboi@gmail.com'), ) MANAGERS = ADMINS APP_URL = '' # the apps absolute url CONFLUENCE_USER = '' CONFLUENCE_PASS = '' CONFLUENCE_API = '' JIRA_URL = '' # api base uri JIRA_API = '%s/api/2.0.alpha1' % JIRA_URL # this is different depending on the jira version JIRA_AUTH = '%s/auth/1' % JIRA_URL JIRA_BROWSE_URL = '' JIRA_USER = '' JIRA_PASS = '' GITHUB_USER = '' GITHUB_TOKEN = '' GITHUB_API = 'https://api.github.com' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'powwow.db', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'uy1@lnm2)5dli$%tc497lf1=988%&(_0b=fg65#^3(79a(+-1*' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'powwow.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'south', 'powwow.apps', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } } # Load extra configuration try: import extraconfig except ImportError: pass else: extraconfig.load('powwow.extraconfig', __name__)
import Link from 'next/link'; import Code from './code'; import withFrame from './frame'; const CLI = () => ( <Code lang="none"> <span className="hljs-keyword">▲</span> {' ~/my-site '} <span className="hljs-keyword">yarn build</span> {` yarn run v1.9.4 warning package.json: No license field $ next build `} <span className="hljs-keyword">✨ Done in 6.89s.</span> {` `} <span className="hljs-keyword">▲</span> {' ~/my-site '} <span className="hljs-keyword">yarn export</span> {` ... > exporting path: /about > exporting path: /index > exporting path: /_error > exporting path: / `} <span className="hljs-keyword">✨ Done in 0.79s.</span> </Code> ); const PackageFile = () => ( <Code lang="json">{`{ "scripts": { "dev": "next", "build": "next build", "start": "next start", "export": "next export" }, "dependencies": { "next": "^6.1.2", "react": "^16.5.1", "react-dom": "^16.5.1" } } `}</Code> ); const IndexPage = withFrame(({ A }) => ( <div> <h1>My Awesome Static Blog</h1> <A tab="file:///.../my-site/out/about/index.html">About</A> </div> )); const AboutPage = withFrame(({ A }) => ( <div> <p>This is the about page</p> <A tab="file:///.../my-site/out/index.html">Go home</A> </div> )); export default { type: ['editor', 'browser'], tabs: ['Terminal', 'Website'], editor1: { editorTabs: ['$ ~/my-site', 'package.json'], editorMapping: { '$ ~/my-site': CLI, 'package.json': PackageFile } }, browser2: { browserTabs: [ 'file:///.../my-site/out/index.html', 'file:///.../my-site/out/about/index.html' ], browserMapping: { 'file:///.../my-site/out/index.html': IndexPage, 'file:///.../my-site/out/about/index.html': AboutPage } }, note: ( <> <p> Export your Next.js website to static HTML, with zero cost. The export app supports almost every feature of Next.js including dynamic urls, prefetching, preloading and dynamic imports. </p> <p> With the{' '} <Link href="/docs#static-html-export"> <a> <code>exportPathMap</code> </a> </Link>{' '} configuration, you can specify the routes and queries for the static export, copy custom files like <code>robots.txt</code> or generate a <code>sitemap.xml</code>. </p> </> ) };
/* printk() - kernel printf() Author: Kees J. Bot * 15 Jan 1994 */ #define nil 0 #include <stdarg.h> #include <limits.h> #define isdigit(c) ((unsigned) ((c) - '0') < (unsigned) 10) #if !__STDC__ /* Classic C stuff, ignore. */ void putk(); void printk(fmt) char *fmt; #else /* Printk() uses putk() to print characters. */ void putk(int c); void printk(const char *fmt, ...) #endif { int c; enum { LEFT, RIGHT } adjust; enum { LONG, INT } intsize; int fill; int width, max, len, base; static char X2C_tab[]= "0123456789ABCDEF"; static char x2c_tab[]= "0123456789abcdef"; char *x2c; char *p; long i; unsigned long u; char temp[8 * sizeof(long) / 3 + 2]; va_list argp; va_start(argp, fmt); while ((c= *fmt++) != 0) { if (c != '%') { /* Ordinary character. */ putk(c); continue; } /* Format specifier of the form: * %[adjust][fill][width][.max]keys */ c= *fmt++; adjust= RIGHT; if (c == '-') { adjust= LEFT; c= *fmt++; } fill= ' '; if (c == '0') { fill= '0'; c= *fmt++; } width= 0; if (c == '*') { /* Width is specified as an argument, e.g. %*d. */ width= va_arg(argp, int); c= *fmt++; } else if (isdigit(c)) { /* A number tells the width, e.g. %10d. */ do { width= width * 10 + (c - '0'); } while (isdigit(c= *fmt++)); } max= INT_MAX; if (c == '.') { /* Max field length coming up. */ if ((c= *fmt++) == '*') { max= va_arg(argp, int); c= *fmt++; } else if (isdigit(c)) { max= 0; do { max= max * 10 + (c - '0'); } while (isdigit(c= *fmt++)); } } /* Set a few flags to the default. */ x2c= x2c_tab; i= 0; base= 10; intsize= INT; if (c == 'l' || c == 'L') { /* "Long" key, e.g. %ld. */ intsize= LONG; c= *fmt++; } if (c == 0) break; switch (c) { /* Decimal. Note that %D is treated as %ld. */ case 'D': intsize= LONG; case 'd': i= intsize == LONG ? va_arg(argp, long) : va_arg(argp, int); u= i < 0 ? -i : i; goto int2ascii; /* Octal. */ case 'O': intsize= LONG; case 'o': base= 010; goto getint; /* Hexadecimal. %X prints upper case A-F, not %lx. */ case 'X': x2c= X2C_tab; case 'x': base= 0x10; goto getint; /* Unsigned decimal. */ case 'U': intsize= LONG; case 'u': getint: u= intsize == LONG ? va_arg(argp, unsigned long) : va_arg(argp, unsigned int); int2ascii: p= temp + sizeof(temp)-1; *p= 0; do { *--p= x2c[u % base]; } while ((u /= base) > 0); goto string_length; /* A character. */ case 'c': p= temp; *p= va_arg(argp, int); len= 1; goto string_print; /* Simply a percent. */ case '%': p= temp; *p= '%'; len= 1; goto string_print; /* A string. The other cases will join in here. */ case 's': p= va_arg(argp, char *); string_length: for (len= 0; p[len] != 0 && len < max; len++) {} string_print: width -= len; if (i < 0) width--; if (fill == '0' && i < 0) putk('-'); if (adjust == RIGHT) { while (width > 0) { putk(fill); width--; } } if (fill == ' ' && i < 0) putk('-'); while (len > 0) { putk((unsigned char) *p++); len--; } while (width > 0) { putk(fill); width--; } break; /* Unrecognized format key, echo it back. */ default: putk('%'); putk(c); } } /* Mark the end with a null (should be something else, like -1). */ putk(0); va_end(argp); } /* * $PchHeader: /mount/hd2/minix/lib/minix/other/RCS/printk.c,v 1.2 1994/09/07 18:45:05 philip Exp $ */
from . import acmg from . import allele from . import allelereport from . import alleleassessment from . import analysis from . import annotationjob from . import attachment from . import broadcast from . import config from . import customannotation from . import geneassessment from . import overview from . import reference from . import referenceassessment from . import search from . import user from . import ui from . import genepanel from . import igv from . import workflow from . import filterconfig
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=8 sts=4 et sw=4 tw=99: * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef vm_Stack_h #define vm_Stack_h #include "mozilla/Atomics.h" #include "mozilla/Maybe.h" #include "mozilla/MemoryReporting.h" #include "mozilla/Variant.h" #include "jsfun.h" #include "jsscript.h" #include "jsutil.h" #include "asmjs/AsmJSFrameIterator.h" #include "gc/Rooting.h" #include "jit/JitFrameIterator.h" #ifdef CHECK_OSIPOINT_REGISTERS #include "jit/Registers.h" // for RegisterDump #endif #include "js/RootingAPI.h" #include "vm/ArgumentsObject.h" #include "vm/SavedFrame.h" struct JSCompartment; namespace JS { namespace dbg { class AutoEntryMonitor; } // namespace dbg } // namespace JS namespace js { class ArgumentsObject; class AsmJSModule; class InterpreterRegs; class CallObject; class FrameIter; class ScopeObject; class ScriptFrameIter; class SPSProfiler; class InterpreterFrame; class StaticBlockObject; class ClonedBlockObject; class ScopeCoordinate; class SavedFrame; namespace jit { class CommonFrameLayout; } // VM stack layout // // A JSRuntime's stack consists of a linked list of activations. Every activation // contains a number of scripted frames that are either running in the interpreter // (InterpreterActivation) or JIT code (JitActivation). The frames inside a single // activation are contiguous: whenever C++ calls back into JS, a new activation is // pushed. // // Every activation is tied to a single JSContext and JSCompartment. This means we // can reconstruct a given context's stack by skipping activations belonging to other // contexts. This happens whenever an embedding enters the JS engine on cx1 and // then, from a native called by the JS engine, reenters the VM on cx2. // Interpreter frames (InterpreterFrame) // // Each interpreter script activation (global or function code) is given a // fixed-size header (js::InterpreterFrame). The frame contains bookkeeping // information about the activation and links to the previous frame. // // The values after an InterpreterFrame in memory are its locals followed by its // expression stack. InterpreterFrame::argv_ points to the frame's arguments. // Missing formal arguments are padded with |undefined|, so the number of // arguments is always >= the number of formals. // // The top of an activation's current frame's expression stack is pointed to by // the activation's "current regs", which contains the stack pointer 'sp'. In // the interpreter, sp is adjusted as individual values are pushed and popped // from the stack and the InterpreterRegs struct (pointed to by the // InterpreterActivation) is a local var of js::Interpret. enum MaybeCheckAliasing { CHECK_ALIASING = true, DONT_CHECK_ALIASING = false }; enum MaybeCheckLexical { CheckLexical = true, DontCheckLexical = false }; /*****************************************************************************/ namespace jit { class BaselineFrame; class RematerializedFrame; } // namespace jit /* * Pointer to either a ScriptFrameIter::Data, an InterpreterFrame, or a Baseline * JIT frame. * * The Debugger may cache ScriptFrameIter::Data as a bookmark to reconstruct a * ScriptFrameIter without doing a full stack walk. * * There is no way to directly create such an AbstractFramePtr. To do so, the * user must call ScriptFrameIter::copyDataAsAbstractFramePtr(). * * ScriptFrameIter::abstractFramePtr() will never return an AbstractFramePtr * that is in fact a ScriptFrameIter::Data. * * To recover a ScriptFrameIter settled at the location pointed to by an * AbstractFramePtr, use the THIS_FRAME_ITER macro in Debugger.cpp. As an * aside, no asScriptFrameIterData() is provided because C++ is stupid and * cannot forward declare inner classes. */ class AbstractFramePtr { friend class FrameIter; uintptr_t ptr_; enum { Tag_ScriptFrameIterData = 0x0, Tag_InterpreterFrame = 0x1, Tag_BaselineFrame = 0x2, Tag_RematerializedFrame = 0x3, TagMask = 0x3 }; public: AbstractFramePtr() : ptr_(0) {} MOZ_IMPLICIT AbstractFramePtr(InterpreterFrame* fp) : ptr_(fp ? uintptr_t(fp) | Tag_InterpreterFrame : 0) { MOZ_ASSERT_IF(fp, asInterpreterFrame() == fp); } MOZ_IMPLICIT AbstractFramePtr(jit::BaselineFrame* fp) : ptr_(fp ? uintptr_t(fp) | Tag_BaselineFrame : 0) { MOZ_ASSERT_IF(fp, asBaselineFrame() == fp); } MOZ_IMPLICIT AbstractFramePtr(jit::RematerializedFrame* fp) : ptr_(fp ? uintptr_t(fp) | Tag_RematerializedFrame : 0) { MOZ_ASSERT_IF(fp, asRematerializedFrame() == fp); } static AbstractFramePtr FromRaw(void* raw) { AbstractFramePtr frame; frame.ptr_ = uintptr_t(raw); return frame; } bool isScriptFrameIterData() const { return !!ptr_ && (ptr_ & TagMask) == Tag_ScriptFrameIterData; } bool isInterpreterFrame() const { return (ptr_ & TagMask) == Tag_InterpreterFrame; } InterpreterFrame* asInterpreterFrame() const { MOZ_ASSERT(isInterpreterFrame()); InterpreterFrame* res = (InterpreterFrame*)(ptr_ & ~TagMask); MOZ_ASSERT(res); return res; } bool isBaselineFrame() const { return (ptr_ & TagMask) == Tag_BaselineFrame; } jit::BaselineFrame* asBaselineFrame() const { MOZ_ASSERT(isBaselineFrame()); jit::BaselineFrame* res = (jit::BaselineFrame*)(ptr_ & ~TagMask); MOZ_ASSERT(res); return res; } bool isRematerializedFrame() const { return (ptr_ & TagMask) == Tag_RematerializedFrame; } jit::RematerializedFrame* asRematerializedFrame() const { MOZ_ASSERT(isRematerializedFrame()); jit::RematerializedFrame* res = (jit::RematerializedFrame*)(ptr_ & ~TagMask); MOZ_ASSERT(res); return res; } void* raw() const { return reinterpret_cast<void*>(ptr_); } bool operator ==(const AbstractFramePtr& other) const { return ptr_ == other.ptr_; } bool operator !=(const AbstractFramePtr& other) const { return ptr_ != other.ptr_; } explicit operator bool() const { return !!ptr_; } inline JSObject* scopeChain() const; inline CallObject& callObj() const; inline bool initFunctionScopeObjects(JSContext* cx); inline void pushOnScopeChain(ScopeObject& scope); inline JSCompartment* compartment() const; inline bool hasCallObj() const; inline bool isFunctionFrame() const; inline bool isModuleFrame() const; inline bool isGlobalFrame() const; inline bool isEvalFrame() const; inline bool isDebuggerEvalFrame() const; inline bool hasCachedSavedFrame() const; inline void setHasCachedSavedFrame(); inline JSScript* script() const; inline JSFunction* fun() const; inline JSFunction* maybeFun() const; inline JSFunction* callee() const; inline Value calleev() const; inline Value& thisArgument() const; inline Value newTarget() const; inline bool isNonEvalFunctionFrame() const; inline bool isNonStrictDirectEvalFrame() const; inline bool isStrictEvalFrame() const; inline unsigned numActualArgs() const; inline unsigned numFormalArgs() const; inline Value* argv() const; inline bool hasArgs() const; inline bool hasArgsObj() const; inline ArgumentsObject& argsObj() const; inline void initArgsObj(ArgumentsObject& argsobj) const; inline bool createSingleton() const; inline bool copyRawFrameSlots(AutoValueVector* vec) const; inline Value& unaliasedLocal(uint32_t i); inline Value& unaliasedFormal(unsigned i, MaybeCheckAliasing checkAliasing = CHECK_ALIASING); inline Value& unaliasedActual(unsigned i, MaybeCheckAliasing checkAliasing = CHECK_ALIASING); template <class Op> inline void unaliasedForEachActual(JSContext* cx, Op op); inline bool prevUpToDate() const; inline void setPrevUpToDate() const; inline void unsetPrevUpToDate() const; inline bool isDebuggee() const; inline void setIsDebuggee(); inline void unsetIsDebuggee(); inline HandleValue returnValue() const; inline void setReturnValue(const Value& rval) const; inline bool freshenBlock(JSContext* cx) const; inline void popBlock(JSContext* cx) const; inline void popWith(JSContext* cx) const; friend void GDBTestInitAbstractFramePtr(AbstractFramePtr&, void*); friend void GDBTestInitAbstractFramePtr(AbstractFramePtr&, InterpreterFrame*); friend void GDBTestInitAbstractFramePtr(AbstractFramePtr&, jit::BaselineFrame*); friend void GDBTestInitAbstractFramePtr(AbstractFramePtr&, jit::RematerializedFrame*); }; class NullFramePtr : public AbstractFramePtr { public: NullFramePtr() : AbstractFramePtr() { } }; /*****************************************************************************/ /* Flags specified for a frame as it is constructed. */ enum InitialFrameFlags { INITIAL_NONE = 0, INITIAL_CONSTRUCT = 0x20, /* == InterpreterFrame::CONSTRUCTING, asserted below */ }; enum ExecuteType { EXECUTE_GLOBAL = 0x1, /* == InterpreterFrame::GLOBAL */ EXECUTE_MODULE = 0x4, /* == InterpreterFrame::GLOBAL */ EXECUTE_DIRECT_EVAL = 0x8, /* == InterpreterFrame::EVAL */ EXECUTE_INDIRECT_EVAL = 0x9, /* == InterpreterFrame::GLOBAL | EVAL */ EXECUTE_DEBUG = 0x18, /* == InterpreterFrame::EVAL | DEBUGGER_EVAL */ }; /*****************************************************************************/ class InterpreterFrame { public: enum Flags : uint32_t { /* Primary frame type */ GLOBAL = 0x1, /* frame pushed for a global script */ FUNCTION = 0x2, /* frame pushed for a scripted call */ MODULE = 0x4, /* frame pushed for a module */ /* Frame subtypes */ EVAL = 0x8, /* frame pushed for eval() or debugger eval */ /* * Frame pushed for debugger eval. * - Don't bother to JIT it, because it's probably short-lived. * - It is required to have a scope chain object outside the * js::ScopeObject hierarchy: either a global object, or a * DebugScopeObject (not a ScopeObject, despite the name) * - If evalInFramePrev_ is set, then this frame was created for an * "eval in frame" call, which can push a successor to any live * frame; so its logical "prev" frame is not necessarily the * previous frame in memory. Iteration should treat * evalInFramePrev_ as this frame's previous frame. */ DEBUGGER_EVAL = 0x10, CONSTRUCTING = 0x20, /* frame is for a constructor invocation */ RESUMED_GENERATOR = 0x40, /* frame is for a resumed generator invocation */ /* (0x80 is unused) */ /* Function prologue state */ HAS_CALL_OBJ = 0x100, /* CallObject created for needsCallObject function */ HAS_ARGS_OBJ = 0x200, /* ArgumentsObject created for needsArgsObj script */ /* Lazy frame initialization */ HAS_RVAL = 0x800, /* frame has rval_ set */ HAS_SCOPECHAIN = 0x1000, /* frame has scopeChain_ set */ /* Debugger state */ PREV_UP_TO_DATE = 0x4000, /* see DebugScopes::updateLiveScopes */ /* * See comment above 'isDebuggee' in jscompartment.h for explanation of * invariants of debuggee compartments, scripts, and frames. */ DEBUGGEE = 0x8000, /* Execution is being observed by Debugger */ /* Used in tracking calls and profiling (see vm/SPSProfiler.cpp) */ HAS_PUSHED_SPS_FRAME = 0x10000, /* SPS was notified of enty */ /* * If set, we entered one of the JITs and ScriptFrameIter should skip * this frame. */ RUNNING_IN_JIT = 0x20000, /* Miscellaneous state. */ CREATE_SINGLETON = 0x40000, /* Constructed |this| object should be singleton. */ /* * If set, this frame has been on the stack when * |js::SavedStacks::saveCurrentStack| was called, and so there is a * |js::SavedFrame| object cached for this frame. */ HAS_CACHED_SAVED_FRAME = 0x80000, }; private: mutable uint32_t flags_; /* bits described by Flags */ union { /* describes what code is executing in a */ JSScript* script; /* global frame */ JSFunction* fun; /* function frame, pre GetScopeChain */ ModuleObject* module; /* module frame */ } exec; union { /* describes the arguments of a function */ unsigned nactual; /* for non-eval frames */ JSScript* evalScript; /* the script of an eval-in-function */ } u; mutable JSObject* scopeChain_; /* if HAS_SCOPECHAIN, current scope chain */ Value rval_; /* if HAS_RVAL, return value of the frame */ ArgumentsObject* argsObj_; /* if HAS_ARGS_OBJ, the call's arguments object */ /* * Previous frame and its pc and sp. Always nullptr for * InterpreterActivation's entry frame, always non-nullptr for inline * frames. */ InterpreterFrame* prev_; jsbytecode* prevpc_; Value* prevsp_; void* unused; /* * For an eval-in-frame DEBUGGER_EVAL frame, the frame in whose scope * we're evaluating code. Iteration treats this as our previous frame. */ AbstractFramePtr evalInFramePrev_; Value* argv_; /* If hasArgs(), points to frame's arguments. */ LifoAlloc::Mark mark_; /* Used to release memory for this frame. */ static void staticAsserts() { JS_STATIC_ASSERT(offsetof(InterpreterFrame, rval_) % sizeof(Value) == 0); JS_STATIC_ASSERT(sizeof(InterpreterFrame) % sizeof(Value) == 0); } /* * The utilities are private since they are not able to assert that only * unaliased vars/formals are accessed. Normal code should prefer the * InterpreterFrame::unaliased* members (or InterpreterRegs::stackDepth for * the usual "depth is at least" assertions). */ Value* slots() const { return (Value*)(this + 1); } Value* base() const { return slots() + script()->nfixed(); } friend class FrameIter; friend class InterpreterRegs; friend class InterpreterStack; friend class jit::BaselineFrame; /* * Frame initialization, called by InterpreterStack operations after acquiring * the raw memory for the frame: */ /* Used for Invoke and Interpret. */ void initCallFrame(JSContext* cx, InterpreterFrame* prev, jsbytecode* prevpc, Value* prevsp, JSFunction& callee, JSScript* script, Value* argv, uint32_t nactual, InterpreterFrame::Flags flags); /* Used for global and eval frames. */ void initExecuteFrame(JSContext* cx, HandleScript script, AbstractFramePtr prev, const Value& newTargetValue, HandleObject scopeChain, ExecuteType type); public: /* * Frame prologue/epilogue * * Every stack frame must have 'prologue' called before executing the * first op and 'epilogue' called after executing the last op and before * popping the frame (whether the exit is exceptional or not). * * For inline JS calls/returns, it is easy to call the prologue/epilogue * exactly once. When calling JS from C++, Invoke/Execute push the stack * frame but do *not* call the prologue/epilogue. That means Interpret * must call the prologue/epilogue for the entry frame. This scheme * simplifies jit compilation. * * An important corner case is what happens when an error occurs (OOM, * over-recursed) after pushing the stack frame but before 'prologue' is * called or completes fully. To simplify usage, 'epilogue' does not assume * 'prologue' has completed and handles all the intermediate state details. */ bool prologue(JSContext* cx); void epilogue(JSContext* cx); bool checkReturn(JSContext* cx, HandleValue thisv); bool initFunctionScopeObjects(JSContext* cx); /* * Initialize local variables of newly-pushed frame. 'var' bindings are * initialized to undefined and lexical bindings are initialized to * JS_UNINITIALIZED_LEXICAL. */ void initLocals(); /* * Stack frame type * * A stack frame may have one of three types, which determines which * members of the frame may be accessed and other invariants: * * global frame: execution of global code or an eval in global code * function frame: execution of function code or an eval in a function * module frame: execution of a module */ bool isFunctionFrame() const { return !!(flags_ & FUNCTION); } bool isGlobalFrame() const { return !!(flags_ & GLOBAL); } bool isModuleFrame() const { return !!(flags_ & MODULE); } /* * Eval frames * * As noted above, global and function frames may optionally be 'eval * frames'. Eval code shares its parent's arguments which means that the * arg-access members of InterpreterFrame may not be used for eval frames. * Search for 'hasArgs' below for more details. * * A further sub-classification of eval frames is whether the frame was * pushed for an ES5 strict-mode eval(). */ bool isEvalFrame() const { return flags_ & EVAL; } bool isEvalInFunction() const { return (flags_ & (EVAL | FUNCTION)) == (EVAL | FUNCTION); } bool isNonEvalFunctionFrame() const { return (flags_ & (FUNCTION | EVAL)) == FUNCTION; } inline bool isStrictEvalFrame() const { return isEvalFrame() && script()->strict(); } bool isNonStrictEvalFrame() const { return isEvalFrame() && !script()->strict(); } bool isNonGlobalEvalFrame() const; bool isNonStrictDirectEvalFrame() const { return isNonStrictEvalFrame() && isNonGlobalEvalFrame(); } /* * Previous frame * * A frame's 'prev' frame is either null or the previous frame pointed to * by cx->regs->fp when this frame was pushed. Often, given two prev-linked * frames, the next-frame is a function or eval that was called by the * prev-frame, but not always: the prev-frame may have called a native that * reentered the VM through JS_CallFunctionValue on the same context * (without calling JS_SaveFrameChain) which pushed the next-frame. Thus, * 'prev' has little semantic meaning and basically just tells the VM what * to set cx->regs->fp to when this frame is popped. */ InterpreterFrame* prev() const { return prev_; } AbstractFramePtr evalInFramePrev() const { MOZ_ASSERT(isEvalFrame()); return evalInFramePrev_; } /* * (Unaliased) locals and arguments * * Only non-eval function frames have arguments. The arguments pushed by * the caller are the 'actual' arguments. The declared arguments of the * callee are the 'formal' arguments. When the caller passes less actual * arguments, missing formal arguments are padded with |undefined|. * * When a local/formal variable is "aliased" (accessed by nested closures, * dynamic scope operations, or 'arguments), the canonical location for * that value is the slot of an activation object (scope or arguments). * Currently, aliased locals don't have stack slots assigned to them, but * all formals are given slots in *both* the stack frame and heap objects, * even though, as just described, only one should ever be accessed. Thus, * it is up to the code performing an access to access the correct value. * These functions assert that accesses to stack values are unaliased. */ inline Value& unaliasedLocal(uint32_t i); bool hasArgs() const { return isNonEvalFunctionFrame(); } inline Value& unaliasedFormal(unsigned i, MaybeCheckAliasing = CHECK_ALIASING); inline Value& unaliasedActual(unsigned i, MaybeCheckAliasing = CHECK_ALIASING); template <class Op> inline void unaliasedForEachActual(Op op); bool copyRawFrameSlots(AutoValueVector* v); unsigned numFormalArgs() const { MOZ_ASSERT(hasArgs()); return fun()->nargs(); } unsigned numActualArgs() const { MOZ_ASSERT(hasArgs()); return u.nactual; } /* Watch out, this exposes a pointer to the unaliased formal arg array. */ Value* argv() const { MOZ_ASSERT(hasArgs()); return argv_; } /* * Arguments object * * If a non-eval function has script->needsArgsObj, an arguments object is * created in the prologue and stored in the local variable for the * 'arguments' binding (script->argumentsLocal). Since this local is * mutable, the arguments object can be overwritten and we can "lose" the * arguments object. Thus, InterpreterFrame keeps an explicit argsObj_ field so * that the original arguments object is always available. */ ArgumentsObject& argsObj() const; void initArgsObj(ArgumentsObject& argsobj); JSObject* createRestParameter(JSContext* cx); /* * Scope chain * * In theory, the scope chain would contain an object for every lexical * scope. However, only objects that are required for dynamic lookup are * actually created. * * Given that an InterpreterFrame corresponds roughly to a ES5 Execution Context * (ES5 10.3), InterpreterFrame::varObj corresponds to the VariableEnvironment * component of a Exection Context. Intuitively, the variables object is * where new bindings (variables and functions) are stored. One might * expect that this is either the Call object or scopeChain.globalObj for * function or global code, respectively, however the JSAPI allows calls of * Execute to specify a variables object on the scope chain other than the * call/global object. This allows embeddings to run multiple scripts under * the same global, each time using a new variables object to collect and * discard the script's global variables. */ inline HandleObject scopeChain() const; inline ScopeObject& aliasedVarScope(ScopeCoordinate sc) const; inline GlobalObject& global() const; inline CallObject& callObj() const; inline JSObject& varObj() const; inline ClonedBlockObject& extensibleLexicalScope() const; inline void pushOnScopeChain(ScopeObject& scope); inline void popOffScopeChain(); inline void replaceInnermostScope(ScopeObject& scope); /* * For blocks with aliased locals, these interfaces push and pop entries on * the scope chain. The "freshen" operation replaces the current block * with a fresh copy of it, to implement semantics providing distinct * bindings per iteration of a for-loop. */ bool pushBlock(JSContext* cx, StaticBlockObject& block); void popBlock(JSContext* cx); bool freshenBlock(JSContext* cx); /* * With * * Entering/leaving a |with| block pushes/pops an object on the scope chain. * Pushing uses pushOnScopeChain, popping should use popWith. */ void popWith(JSContext* cx); /* * Script * * All function and global frames have an associated JSScript which holds * the bytecode being executed for the frame. This script/bytecode does * not reflect any inlining that has been performed by the method JIT. * If other frames were inlined into this one, the script/pc reflect the * point of the outermost call. Inlined frame invariants: * * - Inlined frames have the same scope chain as the outer frame. * - Inlined frames have the same strictness as the outer frame. * - Inlined frames can only make calls to other JIT frames associated with * the same VMFrame. Other calls force expansion of the inlined frames. */ JSScript* script() const { if (isFunctionFrame()) return isEvalFrame() ? u.evalScript : fun()->nonLazyScript(); MOZ_ASSERT(isGlobalFrame() || isModuleFrame()); return exec.script; } /* Return the previous frame's pc. */ jsbytecode* prevpc() { MOZ_ASSERT(prev_); return prevpc_; } /* Return the previous frame's sp. */ Value* prevsp() { MOZ_ASSERT(prev_); return prevsp_; } /* * Function * * All function frames have an associated interpreted JSFunction. The * function returned by fun() and maybeFun() is not necessarily the * original canonical function which the frame's script was compiled * against. */ JSFunction* fun() const { MOZ_ASSERT(isFunctionFrame()); return exec.fun; } JSFunction* maybeFun() const { return isFunctionFrame() ? fun() : nullptr; } /* Module */ ModuleObject* module() const { MOZ_ASSERT(isModuleFrame()); return exec.module; } ModuleObject* maybeModule() const { return isModuleFrame() ? module() : nullptr; } /* * Return the 'this' argument passed to a non-eval function frame. This is * not necessarily the frame's this-binding, for instance non-strict * functions will box primitive 'this' values and thisArgument() will * return the original, unboxed Value. */ Value& thisArgument() const { MOZ_ASSERT(isNonEvalFunctionFrame()); return argv()[-1]; } /* * Callee * * Only function frames have a callee. An eval frame in a function has the * same callee as its containing function frame. maybeCalleev can be used * to return a value that is either the callee object (for function frames) or * null (for global frames). */ JSFunction& callee() const { MOZ_ASSERT(isFunctionFrame()); return calleev().toObject().as<JSFunction>(); } const Value& calleev() const { MOZ_ASSERT(isFunctionFrame()); return mutableCalleev(); } const Value& maybeCalleev() const { Value& calleev = flags_ & (EVAL | GLOBAL) ? ((Value*)this)[-1] : argv()[-2]; MOZ_ASSERT(calleev.isObjectOrNull()); return calleev; } Value& mutableCalleev() const { MOZ_ASSERT(isFunctionFrame()); if (isEvalFrame()) return ((Value*)this)[-1]; return argv()[-2]; } /* * New Target * * Only function frames have a meaningful newTarget. An eval frame in a * function will have a copy of the newTarget of the enclosing function * frame. */ Value newTarget() const { MOZ_ASSERT(isFunctionFrame()); if (isEvalFrame()) return ((Value*)this)[-2]; if (callee().isArrow()) return callee().getExtendedSlot(FunctionExtended::ARROW_NEWTARGET_SLOT); if (isConstructing()) { unsigned pushedArgs = Max(numFormalArgs(), numActualArgs()); return argv()[pushedArgs]; } return UndefinedValue(); } /* * Frame compartment * * A stack frame's compartment is the frame's containing context's * compartment when the frame was pushed. */ inline JSCompartment* compartment() const; /* Profiler flags */ bool hasPushedSPSFrame() { return !!(flags_ & HAS_PUSHED_SPS_FRAME); } void setPushedSPSFrame() { flags_ |= HAS_PUSHED_SPS_FRAME; } void unsetPushedSPSFrame() { flags_ &= ~HAS_PUSHED_SPS_FRAME; } /* Return value */ bool hasReturnValue() const { return flags_ & HAS_RVAL; } MutableHandleValue returnValue() { if (!hasReturnValue()) rval_.setUndefined(); return MutableHandleValue::fromMarkedLocation(&rval_); } void markReturnValue() { flags_ |= HAS_RVAL; } void setReturnValue(const Value& v) { rval_ = v; markReturnValue(); } void clearReturnValue() { rval_.setUndefined(); markReturnValue(); } void resumeGeneratorFrame(JSObject* scopeChain) { MOZ_ASSERT(script()->isGenerator()); MOZ_ASSERT(isNonEvalFunctionFrame()); flags_ |= HAS_CALL_OBJ | HAS_SCOPECHAIN; scopeChain_ = scopeChain; } /* * Other flags */ InitialFrameFlags initialFlags() const { JS_STATIC_ASSERT((int)INITIAL_NONE == 0); JS_STATIC_ASSERT((int)INITIAL_CONSTRUCT == (int)CONSTRUCTING); uint32_t mask = CONSTRUCTING; MOZ_ASSERT((flags_ & mask) != mask); return InitialFrameFlags(flags_ & mask); } void setConstructing() { flags_ |= CONSTRUCTING; } bool isConstructing() const { return !!(flags_ & CONSTRUCTING); } void setResumedGenerator() { flags_ |= RESUMED_GENERATOR; } bool isResumedGenerator() const { return !!(flags_ & RESUMED_GENERATOR); } /* * These two queries should not be used in general: the presence/absence of * the call/args object is determined by the static(ish) properties of the * JSFunction/JSScript. These queries should only be performed when probing * a stack frame that may be in the middle of the prologue (during which * time the call/args object are created). */ inline bool hasCallObj() const; bool hasCallObjUnchecked() const { return flags_ & HAS_CALL_OBJ; } bool hasArgsObj() const { MOZ_ASSERT(script()->needsArgsObj()); return flags_ & HAS_ARGS_OBJ; } void setCreateSingleton() { MOZ_ASSERT(isConstructing()); flags_ |= CREATE_SINGLETON; } bool createSingleton() const { MOZ_ASSERT(isConstructing()); return flags_ & CREATE_SINGLETON; } bool isDebuggerEvalFrame() const { return !!(flags_ & DEBUGGER_EVAL); } bool prevUpToDate() const { return !!(flags_ & PREV_UP_TO_DATE); } void setPrevUpToDate() { flags_ |= PREV_UP_TO_DATE; } void unsetPrevUpToDate() { flags_ &= ~PREV_UP_TO_DATE; } bool isDebuggee() const { return !!(flags_ & DEBUGGEE); } void setIsDebuggee() { flags_ |= DEBUGGEE; } inline void unsetIsDebuggee(); bool hasCachedSavedFrame() const { return flags_ & HAS_CACHED_SAVED_FRAME; } void setHasCachedSavedFrame() { flags_ |= HAS_CACHED_SAVED_FRAME; } public: void mark(JSTracer* trc); void markValues(JSTracer* trc, unsigned start, unsigned end); void markValues(JSTracer* trc, Value* sp, jsbytecode* pc); // Entered Baseline/Ion from the interpreter. bool runningInJit() const { return !!(flags_ & RUNNING_IN_JIT); } void setRunningInJit() { flags_ |= RUNNING_IN_JIT; } void clearRunningInJit() { flags_ &= ~RUNNING_IN_JIT; } }; static const size_t VALUES_PER_STACK_FRAME = sizeof(InterpreterFrame) / sizeof(Value); static inline InterpreterFrame::Flags ToFrameFlags(InitialFrameFlags initial) { return InterpreterFrame::Flags(initial); } static inline InitialFrameFlags InitialFrameFlagsFromConstructing(bool b) { return b ? INITIAL_CONSTRUCT : INITIAL_NONE; } static inline bool InitialFrameFlagsAreConstructing(InitialFrameFlags initial) { return !!(initial & INITIAL_CONSTRUCT); } /*****************************************************************************/ class InterpreterRegs { public: Value* sp; jsbytecode* pc; private: InterpreterFrame* fp_; public: InterpreterFrame* fp() const { return fp_; } unsigned stackDepth() const { MOZ_ASSERT(sp >= fp_->base()); return sp - fp_->base(); } Value* spForStackDepth(unsigned depth) const { MOZ_ASSERT(fp_->script()->nfixed() + depth <= fp_->script()->nslots()); return fp_->base() + depth; } /* For generators. */ void rebaseFromTo(const InterpreterRegs& from, InterpreterFrame& to) { fp_ = &to; sp = to.slots() + (from.sp - from.fp_->slots()); pc = from.pc; MOZ_ASSERT(fp_); } void popInlineFrame() { pc = fp_->prevpc(); unsigned spForNewTarget = fp_->isResumedGenerator() ? 0 : fp_->isConstructing(); sp = fp_->prevsp() - fp_->numActualArgs() - 1 - spForNewTarget; fp_ = fp_->prev(); MOZ_ASSERT(fp_); } void prepareToRun(InterpreterFrame& fp, JSScript* script) { pc = script->code(); sp = fp.slots() + script->nfixed(); fp_ = &fp; } void setToEndOfScript(); MutableHandleValue stackHandleAt(int i) { return MutableHandleValue::fromMarkedLocation(&sp[i]); } HandleValue stackHandleAt(int i) const { return HandleValue::fromMarkedLocation(&sp[i]); } friend void GDBTestInitInterpreterRegs(InterpreterRegs&, js::InterpreterFrame*, JS::Value*, uint8_t*); }; /*****************************************************************************/ class InterpreterStack { friend class InterpreterActivation; static const size_t DEFAULT_CHUNK_SIZE = 4 * 1024; LifoAlloc allocator_; // Number of interpreter frames on the stack, for over-recursion checks. static const size_t MAX_FRAMES = 50 * 1000; static const size_t MAX_FRAMES_TRUSTED = MAX_FRAMES + 1000; size_t frameCount_; inline uint8_t* allocateFrame(JSContext* cx, size_t size); inline InterpreterFrame* getCallFrame(JSContext* cx, const CallArgs& args, HandleScript script, InterpreterFrame::Flags* pflags, Value** pargv); void releaseFrame(InterpreterFrame* fp) { frameCount_--; allocator_.release(fp->mark_); } public: InterpreterStack() : allocator_(DEFAULT_CHUNK_SIZE), frameCount_(0) { } ~InterpreterStack() { MOZ_ASSERT(frameCount_ == 0); } // For execution of eval or global code. InterpreterFrame* pushExecuteFrame(JSContext* cx, HandleScript script, const Value& newTargetValue, HandleObject scopeChain, ExecuteType type, AbstractFramePtr evalInFrame); // Called to invoke a function. InterpreterFrame* pushInvokeFrame(JSContext* cx, const CallArgs& args, InitialFrameFlags initial); // The interpreter can push light-weight, "inline" frames without entering a // new InterpreterActivation or recursively calling Interpret. bool pushInlineFrame(JSContext* cx, InterpreterRegs& regs, const CallArgs& args, HandleScript script, InitialFrameFlags initial); void popInlineFrame(InterpreterRegs& regs); bool resumeGeneratorCallFrame(JSContext* cx, InterpreterRegs& regs, HandleFunction callee, HandleValue newTarget, HandleObject scopeChain); inline void purge(JSRuntime* rt); size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const { return allocator_.sizeOfExcludingThis(mallocSizeOf); } }; void MarkInterpreterActivations(JSRuntime* rt, JSTracer* trc); /*****************************************************************************/ namespace detail { class GenericInvokeArgs : public JS::CallArgs { protected: AutoValueVector v_; explicit GenericInvokeArgs(JSContext* cx) : v_(cx) {} bool init(JSContext* cx, unsigned argc, bool construct) { if (argc > ARGS_LENGTH_MAX) { JS_ReportErrorNumber(cx, GetErrorMessage, nullptr, JSMSG_TOO_MANY_ARGUMENTS); return false; } MOZ_ASSERT(2 + argc + construct > argc); // no overflow if (!v_.resize(2 + argc + construct)) return false; *static_cast<JS::CallArgs*>(this) = CallArgsFromVp(argc, v_.begin()); constructing_ = construct; return true; } }; } // namespace detail class InvokeArgs : public detail::GenericInvokeArgs { public: explicit InvokeArgs(JSContext* cx) : detail::GenericInvokeArgs(cx) {} bool init(JSContext* cx, unsigned argc) { return detail::GenericInvokeArgs::init(cx, argc, false); } }; class ConstructArgs : public detail::GenericInvokeArgs { public: explicit ConstructArgs(JSContext* cx) : detail::GenericInvokeArgs(cx) {} bool init(JSContext* cx, unsigned argc) { return detail::GenericInvokeArgs::init(cx, argc, true); } }; template <class Args, class Arraylike> inline bool FillArgumentsFromArraylike(JSContext* cx, Args& args, const Arraylike& arraylike) { uint32_t len = arraylike.length(); if (!args.init(cx, len)) return false; for (uint32_t i = 0; i < len; i++) args[i].set(arraylike[i]); return true; } template <> struct DefaultHasher<AbstractFramePtr> { typedef AbstractFramePtr Lookup; static js::HashNumber hash(const Lookup& key) { return size_t(key.raw()); } static bool match(const AbstractFramePtr& k, const Lookup& l) { return k == l; } }; /*****************************************************************************/ // SavedFrame caching to minimize stack walking. // // SavedFrames are hash consed to minimize expensive (with regards to both space // and time) allocations in the face of many stack frames that tend to share the // same older tail frames. Despite that, in scenarios where we are frequently // saving the same or similar stacks, such as when the Debugger's allocation // site tracking is enabled, these older stack frames still get walked // repeatedly just to create the lookup structs to find their corresponding // SavedFrames in the hash table. This stack walking is slow, and we would like // to minimize it. // // We have reserved a bit on most of SpiderMonkey's various frame // representations (the exceptions being asm and inlined ion frames). As we // create SavedFrame objects for live stack frames in SavedStacks::insertFrames, // we set this bit and append the SavedFrame object to the cache. As we walk the // stack, if we encounter a frame that has this bit set, that indicates that we // have already captured a SavedFrame object for the given stack frame (but not // necessarily the current pc) during a previous call to insertFrames. We know // that the frame's parent was also captured and has its bit set as well, but // additionally we know the parent was captured at its current pc. For the // parent, rather than continuing the expensive stack walk, we do a quick and // cache-friendly linear search through the frame cache. Upon finishing search // through the frame cache, stale entries are removed. // // The frame cache maintains the invariant that its first E[0] .. E[j-1] // entries are live and sorted from oldest to younger frames, where 0 < j < n // and n = the length of the cache. When searching the cache, we require // that we are considering the youngest live frame whose bit is set. Every // cache entry E[i] where i >= j is a stale entry. Consider the following // scenario: // // P > Q > R > S Initial stack, bits not set. // P* > Q* > R* > S* Capture a SavedFrame stack, set bits. // P* > Q* > R* Return from S. // P* > Q* Return from R. // P* > Q* > T Call T, its bit is not set. // // The frame cache was populated with [P, Q, R, S] when we captured a // SavedFrame stack, but because we returned from frames R and S, their // entries in the frame cache are now stale. This fact is unbeknownst to us // because we do not observe frame pops. Upon capturing a second stack, we // start stack walking at the youngest frame T, which does not have its bit // set and must take the hash table lookup slow path rather than the frame // cache short circuit. Next we proceed to Q and find that it has its bit // set, and it is therefore the youngest live frame with its bit set. We // search through the frame cache from oldest to youngest and find the cache // entry matching Q. We know that T is the next younger live frame from Q // and that T does not have an entry in the frame cache because its bit was // not set. Therefore, we have found entry E[j-1] and the subsequent entries // are stale and should be purged from the frame cache. // // We have a LiveSavedFrameCache for each activation to minimize the number of // entries that must be scanned through, and to avoid the headaches of // maintaining a cache for each compartment and invalidating stale cache entries // in the presence of cross-compartment calls. class LiveSavedFrameCache : public JS::Traceable { public: using FramePtr = mozilla::Variant<AbstractFramePtr, jit::CommonFrameLayout*>; private: struct Entry { FramePtr framePtr; jsbytecode* pc; RelocatablePtr<SavedFrame*> savedFrame; Entry(FramePtr& framePtr, jsbytecode* pc, SavedFrame* savedFrame) : framePtr(framePtr) , pc(pc) , savedFrame(savedFrame) { } }; using EntryVector = Vector<Entry, 0, SystemAllocPolicy>; EntryVector* frames; LiveSavedFrameCache(const LiveSavedFrameCache&) = delete; LiveSavedFrameCache& operator=(const LiveSavedFrameCache&) = delete; public: explicit LiveSavedFrameCache() : frames(nullptr) { } LiveSavedFrameCache(LiveSavedFrameCache&& rhs) : frames(rhs.frames) { MOZ_ASSERT(this != &rhs, "self-move disallowed"); rhs.frames = nullptr; } ~LiveSavedFrameCache() { if (frames) { js_delete(frames); frames = nullptr; } } bool initialized() const { return !!frames; } bool init(JSContext* cx) { frames = js_new<EntryVector>(); if (!frames) { JS_ReportOutOfMemory(cx); return false; } return true; } static mozilla::Maybe<FramePtr> getFramePtr(FrameIter& iter); static void trace(LiveSavedFrameCache* cache, JSTracer* trc); void find(JSContext* cx, FrameIter& frameIter, MutableHandleSavedFrame frame) const; bool insert(JSContext* cx, FramePtr& framePtr, jsbytecode* pc, HandleSavedFrame savedFrame); }; static_assert(sizeof(LiveSavedFrameCache) == sizeof(uintptr_t), "Every js::Activation has a LiveSavedFrameCache, so we need to be pretty careful " "about avoiding bloat. If you're adding members to LiveSavedFrameCache, maybe you " "should consider figuring out a way to make js::Activation have a " "LiveSavedFrameCache* instead of a Rooted<LiveSavedFrameCache>."); /*****************************************************************************/ class InterpreterActivation; class AsmJSActivation; namespace jit { class JitActivation; } // namespace jit // This class is separate from Activation, because it calls JSCompartment::wrap() // which can GC and walk the stack. It's not safe to do that within the // JitActivation constructor. class MOZ_RAII ActivationEntryMonitor { JSContext* cx_; // The entry point monitor that was set on cx_->runtime() when this // ActivationEntryMonitor was created. JS::dbg::AutoEntryMonitor* entryMonitor_; explicit ActivationEntryMonitor(JSContext* cx); ActivationEntryMonitor(const ActivationEntryMonitor& other) = delete; void operator=(const ActivationEntryMonitor& other) = delete; Value asyncStack(JSContext* cx); public: ActivationEntryMonitor(JSContext* cx, InterpreterFrame* entryFrame); ActivationEntryMonitor(JSContext* cx, jit::CalleeToken entryToken); inline ~ActivationEntryMonitor(); }; class Activation { protected: JSContext* cx_; JSCompartment* compartment_; Activation* prev_; Activation* prevProfiling_; // Counter incremented by JS_SaveFrameChain on the top-most activation and // decremented by JS_RestoreFrameChain. If > 0, ScriptFrameIter should stop // iterating when it reaches this activation (if GO_THROUGH_SAVED is not // set). size_t savedFrameChain_; // Counter incremented by JS::HideScriptedCaller and decremented by // JS::UnhideScriptedCaller. If > 0 for the top activation, // DescribeScriptedCaller will return null instead of querying that // activation, which should prompt the caller to consult embedding-specific // data structures instead. size_t hideScriptedCallerCount_; // The cache of SavedFrame objects we have already captured when walking // this activation's stack. Rooted<LiveSavedFrameCache> frameCache_; // Youngest saved frame of an async stack that will be iterated during stack // capture in place of the actual stack of previous activations. Note that // the stack of this activation is captured entirely before this is used. // // Usually this is nullptr, meaning that normal stack capture will occur. // When this is set, the stack of any previous activation is ignored. Rooted<SavedFrame*> asyncStack_; // Value of asyncCause to be attached to asyncStack_. RootedString asyncCause_; // True if the async call was explicitly requested, e.g. via // callFunctionWithAsyncStack. bool asyncCallIsExplicit_; enum Kind { Interpreter, Jit, AsmJS }; Kind kind_; inline Activation(JSContext* cx, Kind kind); inline ~Activation(); public: JSContext* cx() const { return cx_; } JSCompartment* compartment() const { return compartment_; } Activation* prev() const { return prev_; } Activation* prevProfiling() const { return prevProfiling_; } inline Activation* mostRecentProfiling(); bool isInterpreter() const { return kind_ == Interpreter; } bool isJit() const { return kind_ == Jit; } bool isAsmJS() const { return kind_ == AsmJS; } inline bool isProfiling() const; void registerProfiling(); void unregisterProfiling(); InterpreterActivation* asInterpreter() const { MOZ_ASSERT(isInterpreter()); return (InterpreterActivation*)this; } jit::JitActivation* asJit() const { MOZ_ASSERT(isJit()); return (jit::JitActivation*)this; } AsmJSActivation* asAsmJS() const { MOZ_ASSERT(isAsmJS()); return (AsmJSActivation*)this; } void saveFrameChain() { savedFrameChain_++; } void restoreFrameChain() { MOZ_ASSERT(savedFrameChain_ > 0); savedFrameChain_--; } bool hasSavedFrameChain() const { return savedFrameChain_ > 0; } void hideScriptedCaller() { hideScriptedCallerCount_++; } void unhideScriptedCaller() { MOZ_ASSERT(hideScriptedCallerCount_ > 0); hideScriptedCallerCount_--; } bool scriptedCallerIsHidden() const { return hideScriptedCallerCount_ > 0; } static size_t offsetOfPrevProfiling() { return offsetof(Activation, prevProfiling_); } SavedFrame* asyncStack() { return asyncStack_; } JSString* asyncCause() { return asyncCause_; } bool asyncCallIsExplicit() const { return asyncCallIsExplicit_; } inline LiveSavedFrameCache* getLiveSavedFrameCache(JSContext* cx); private: Activation(const Activation& other) = delete; void operator=(const Activation& other) = delete; }; // This variable holds a special opcode value which is greater than all normal // opcodes, and is chosen such that the bitwise or of this value with any // opcode is this value. static const jsbytecode EnableInterruptsPseudoOpcode = -1; static_assert(EnableInterruptsPseudoOpcode >= JSOP_LIMIT, "EnableInterruptsPseudoOpcode must be greater than any opcode"); static_assert(EnableInterruptsPseudoOpcode == jsbytecode(-1), "EnableInterruptsPseudoOpcode must be the maximum jsbytecode value"); class InterpreterFrameIterator; class RunState; class InterpreterActivation : public Activation { friend class js::InterpreterFrameIterator; InterpreterRegs regs_; InterpreterFrame* entryFrame_; size_t opMask_; // For debugger interrupts, see js::Interpret. #ifdef DEBUG size_t oldFrameCount_; #endif public: inline InterpreterActivation(RunState& state, JSContext* cx, InterpreterFrame* entryFrame); inline ~InterpreterActivation(); inline bool pushInlineFrame(const CallArgs& args, HandleScript script, InitialFrameFlags initial); inline void popInlineFrame(InterpreterFrame* frame); inline bool resumeGeneratorFrame(HandleFunction callee, HandleValue newTarget, HandleObject scopeChain); InterpreterFrame* current() const { return regs_.fp(); } InterpreterRegs& regs() { return regs_; } InterpreterFrame* entryFrame() const { return entryFrame_; } size_t opMask() const { return opMask_; } bool isProfiling() const { return false; } // If this js::Interpret frame is running |script|, enable interrupts. void enableInterruptsIfRunning(JSScript* script) { if (regs_.fp()->script() == script) enableInterruptsUnconditionally(); } void enableInterruptsUnconditionally() { opMask_ = EnableInterruptsPseudoOpcode; } void clearInterruptsMask() { opMask_ = 0; } }; // Iterates over a thread's activation list. If given a runtime, iterate over // the runtime's main thread's activation list. class ActivationIterator { uint8_t* jitTop_; protected: Activation* activation_; private: void settle(); public: explicit ActivationIterator(JSRuntime* rt); ActivationIterator& operator++(); Activation* operator->() const { return activation_; } Activation* activation() const { return activation_; } uint8_t* jitTop() const { MOZ_ASSERT(activation_->isJit()); return jitTop_; } bool done() const { return activation_ == nullptr; } }; namespace jit { class BailoutFrameInfo; // A JitActivation is used for frames running in Baseline or Ion. class JitActivation : public Activation { uint8_t* prevJitTop_; JitActivation* prevJitActivation_; JSContext* prevJitJSContext_; bool active_; // The lazy link stub reuse the frame pushed for calling a function as an // exit frame. In a few cases, such as after calls from asm.js, we might // have an entry frame followed by an exit frame. This pattern can be // assimilated as a fake exit frame (unwound frame), in which case we skip // marking during a GC. To ensure that we do mark the stack as expected we // have to keep a flag set by the LazyLink VM function to safely mark the // stack if a GC happens during the link phase. bool isLazyLinkExitFrame_; // Rematerialized Ion frames which has info copied out of snapshots. Maps // frame pointers (i.e. jitTop) to a vector of rematerializations of all // inline frames associated with that frame. // // This table is lazily initialized by calling getRematerializedFrame. typedef Vector<RematerializedFrame*> RematerializedFrameVector; typedef HashMap<uint8_t*, RematerializedFrameVector> RematerializedFrameTable; RematerializedFrameTable* rematerializedFrames_; // This vector is used to remember the outcome of the evaluation of recover // instructions. // // RInstructionResults are appended into this vector when Snapshot values // have to be read, or when the evaluation has to run before some mutating // code. Each RInstructionResults belongs to one frame which has to bailout // as soon as we get back to it. typedef Vector<RInstructionResults, 1> IonRecoveryMap; IonRecoveryMap ionRecovery_; // If we are bailing out from Ion, then this field should be a non-null // pointer which references the BailoutFrameInfo used to walk the inner // frames. This field is used for all newly constructed JitFrameIterators to // read the innermost frame information from this bailout data instead of // reading it from the stack. BailoutFrameInfo* bailoutData_; // When profiling is enabled, these fields will be updated to reflect the // last pushed frame for this activation, and if that frame has been // left for a call, the native code site of the call. mozilla::Atomic<void*, mozilla::Relaxed> lastProfilingFrame_; mozilla::Atomic<void*, mozilla::Relaxed> lastProfilingCallSite_; static_assert(sizeof(mozilla::Atomic<void*, mozilla::Relaxed>) == sizeof(void*), "Atomic should have same memory format as underlying type."); void clearRematerializedFrames(); #ifdef CHECK_OSIPOINT_REGISTERS protected: // Used to verify that live registers don't change between a VM call and // the OsiPoint that follows it. Protected to silence Clang warning. uint32_t checkRegs_; RegisterDump regs_; #endif public: explicit JitActivation(JSContext* cx, bool active = true); ~JitActivation(); bool isActive() const { return active_; } void setActive(JSContext* cx, bool active = true); bool isProfiling() const; uint8_t* prevJitTop() const { return prevJitTop_; } JitActivation* prevJitActivation() const { return prevJitActivation_; } static size_t offsetOfPrevJitTop() { return offsetof(JitActivation, prevJitTop_); } static size_t offsetOfPrevJitJSContext() { return offsetof(JitActivation, prevJitJSContext_); } static size_t offsetOfPrevJitActivation() { return offsetof(JitActivation, prevJitActivation_); } static size_t offsetOfActiveUint8() { MOZ_ASSERT(sizeof(bool) == 1); return offsetof(JitActivation, active_); } #ifdef CHECK_OSIPOINT_REGISTERS void setCheckRegs(bool check) { checkRegs_ = check; } static size_t offsetOfCheckRegs() { return offsetof(JitActivation, checkRegs_); } static size_t offsetOfRegs() { return offsetof(JitActivation, regs_); } #endif // Look up a rematerialized frame keyed by the fp, rematerializing the // frame if one doesn't already exist. A frame can only be rematerialized // if an IonFrameIterator pointing to the nearest uninlined frame can be // provided, as values need to be read out of snapshots. // // The inlineDepth must be within bounds of the frame pointed to by iter. RematerializedFrame* getRematerializedFrame(JSContext* cx, const JitFrameIterator& iter, size_t inlineDepth = 0); // Look up a rematerialized frame by the fp. If inlineDepth is out of // bounds of what has been rematerialized, nullptr is returned. RematerializedFrame* lookupRematerializedFrame(uint8_t* top, size_t inlineDepth = 0); // Remove all rematerialized frames associated with the fp top from the // Debugger. void removeRematerializedFramesFromDebugger(JSContext* cx, uint8_t* top); bool hasRematerializedFrame(uint8_t* top, size_t inlineDepth = 0) { return !!lookupRematerializedFrame(top, inlineDepth); } // Remove a previous rematerialization by fp. void removeRematerializedFrame(uint8_t* top); void markRematerializedFrames(JSTracer* trc); // Register the results of on Ion frame recovery. bool registerIonFrameRecovery(RInstructionResults&& results); // Return the pointer to the Ion frame recovery, if it is already registered. RInstructionResults* maybeIonFrameRecovery(JitFrameLayout* fp); // If an Ion frame recovery exists for the |fp| frame exists, then remove it // from the activation. void removeIonFrameRecovery(JitFrameLayout* fp); void markIonRecovery(JSTracer* trc); // Return the bailout information if it is registered. const BailoutFrameInfo* bailoutData() const { return bailoutData_; } // Register the bailout data when it is constructed. void setBailoutData(BailoutFrameInfo* bailoutData); // Unregister the bailout data when the frame is reconstructed. void cleanBailoutData(); // Return the bailout information if it is registered. bool isLazyLinkExitFrame() const { return isLazyLinkExitFrame_; } // Register the bailout data when it is constructed. void setLazyLinkExitFrame(bool isExitFrame) { isLazyLinkExitFrame_ = isExitFrame; } static size_t offsetOfLastProfilingFrame() { return offsetof(JitActivation, lastProfilingFrame_); } void* lastProfilingFrame() { return lastProfilingFrame_; } void setLastProfilingFrame(void* ptr) { lastProfilingFrame_ = ptr; } static size_t offsetOfLastProfilingCallSite() { return offsetof(JitActivation, lastProfilingCallSite_); } void* lastProfilingCallSite() { return lastProfilingCallSite_; } void setLastProfilingCallSite(void* ptr) { lastProfilingCallSite_ = ptr; } }; // A filtering of the ActivationIterator to only stop at JitActivations. class JitActivationIterator : public ActivationIterator { void settle() { while (!done() && !activation_->isJit()) ActivationIterator::operator++(); } public: explicit JitActivationIterator(JSRuntime* rt) : ActivationIterator(rt) { settle(); } JitActivationIterator& operator++() { ActivationIterator::operator++(); settle(); return *this; } // Returns the bottom and top addresses of the current JitActivation. void jitStackRange(uintptr_t*& min, uintptr_t*& end); }; } // namespace jit // Iterates over the frames of a single InterpreterActivation. class InterpreterFrameIterator { InterpreterActivation* activation_; InterpreterFrame* fp_; jsbytecode* pc_; Value* sp_; public: explicit InterpreterFrameIterator(InterpreterActivation* activation) : activation_(activation), fp_(nullptr), pc_(nullptr), sp_(nullptr) { if (activation) { fp_ = activation->current(); pc_ = activation->regs().pc; sp_ = activation->regs().sp; } } InterpreterFrame* frame() const { MOZ_ASSERT(!done()); return fp_; } jsbytecode* pc() const { MOZ_ASSERT(!done()); return pc_; } Value* sp() const { MOZ_ASSERT(!done()); return sp_; } InterpreterFrameIterator& operator++(); bool done() const { return fp_ == nullptr; } }; // An AsmJSActivation is part of two activation linked lists: // - the normal Activation list used by FrameIter // - a list of only AsmJSActivations that is signal-safe since it is accessed // from the profiler at arbitrary points // // An eventual goal is to remove AsmJSActivation and to run asm.js code in a // JitActivation interleaved with Ion/Baseline jit code. This would allow // efficient calls back and forth but requires that we can walk the stack for // all kinds of jit code. class AsmJSActivation : public Activation { AsmJSModule& module_; AsmJSActivation* prevAsmJS_; AsmJSActivation* prevAsmJSForModule_; void* entrySP_; void* resumePC_; uint8_t* fp_; uint32_t packedExitReason_; public: AsmJSActivation(JSContext* cx, AsmJSModule& module); ~AsmJSActivation(); inline JSContext* cx(); AsmJSModule& module() const { return module_; } AsmJSActivation* prevAsmJS() const { return prevAsmJS_; } bool isProfiling() const { return true; } // Returns a pointer to the base of the innermost stack frame of asm.js code // in this activation. uint8_t* fp() const { return fp_; } // Returns the reason why asm.js code called out of asm.js code. wasm::ExitReason exitReason() const { return wasm::ExitReason::unpack(packedExitReason_); } // Read by JIT code: static unsigned offsetOfContext() { return offsetof(AsmJSActivation, cx_); } static unsigned offsetOfResumePC() { return offsetof(AsmJSActivation, resumePC_); } // Written by JIT code: static unsigned offsetOfEntrySP() { return offsetof(AsmJSActivation, entrySP_); } static unsigned offsetOfFP() { return offsetof(AsmJSActivation, fp_); } static unsigned offsetOfPackedExitReason() { return offsetof(AsmJSActivation, packedExitReason_); } // Read/written from SIGSEGV handler: void setResumePC(void* pc) { resumePC_ = pc; } void* resumePC() const { return resumePC_; } }; // A FrameIter walks over the runtime's stack of JS script activations, // abstracting over whether the JS scripts were running in the interpreter or // different modes of compiled code. // // FrameIter is parameterized by what it includes in the stack iteration: // - The SavedOption controls whether FrameIter stops when it finds an // activation that was set aside via JS_SaveFrameChain (and not yet restored // by JS_RestoreFrameChain). (Hopefully this will go away.) // - The ContextOption determines whether the iteration will view frames from // all JSContexts or just the given JSContext. (Hopefully this will go away.) // - When provided, the optional JSPrincipal argument will cause FrameIter to // only show frames in globals whose JSPrincipals are subsumed (via // JSSecurityCallbacks::subsume) by the given JSPrincipal. // // Additionally, there are derived FrameIter types that automatically skip // certain frames: // - ScriptFrameIter only shows frames that have an associated JSScript // (currently everything other than asm.js stack frames). When !hasScript(), // clients must stick to the portion of the // interface marked below. // - NonBuiltinScriptFrameIter additionally filters out builtin (self-hosted) // scripts. class FrameIter { public: enum SavedOption { STOP_AT_SAVED, GO_THROUGH_SAVED }; enum ContextOption { CURRENT_CONTEXT, ALL_CONTEXTS }; enum DebuggerEvalOption { FOLLOW_DEBUGGER_EVAL_PREV_LINK, IGNORE_DEBUGGER_EVAL_PREV_LINK }; enum State { DONE, INTERP, JIT, ASMJS }; // Unlike ScriptFrameIter itself, ScriptFrameIter::Data can be allocated on // the heap, so this structure should not contain any GC things. struct Data { JSContext * cx_; SavedOption savedOption_; ContextOption contextOption_; DebuggerEvalOption debuggerEvalOption_; JSPrincipals * principals_; State state_; jsbytecode * pc_; InterpreterFrameIterator interpFrames_; ActivationIterator activations_; jit::JitFrameIterator jitFrames_; unsigned ionInlineFrameNo_; AsmJSFrameIterator asmJSFrames_; Data(JSContext* cx, SavedOption savedOption, ContextOption contextOption, DebuggerEvalOption debuggerEvalOption, JSPrincipals* principals); Data(const Data& other); }; MOZ_IMPLICIT FrameIter(JSContext* cx, SavedOption = STOP_AT_SAVED); FrameIter(JSContext* cx, ContextOption, SavedOption, DebuggerEvalOption = FOLLOW_DEBUGGER_EVAL_PREV_LINK); FrameIter(JSContext* cx, ContextOption, SavedOption, DebuggerEvalOption, JSPrincipals*); FrameIter(const FrameIter& iter); MOZ_IMPLICIT FrameIter(const Data& data); MOZ_IMPLICIT FrameIter(AbstractFramePtr frame); bool done() const { return data_.state_ == DONE; } // ------------------------------------------------------- // The following functions can only be called when !done() // ------------------------------------------------------- FrameIter& operator++(); JSCompartment* compartment() const; Activation* activation() const { return data_.activations_.activation(); } bool isInterp() const { MOZ_ASSERT(!done()); return data_.state_ == INTERP; } bool isJit() const { MOZ_ASSERT(!done()); return data_.state_ == JIT; } bool isAsmJS() const { MOZ_ASSERT(!done()); return data_.state_ == ASMJS; } inline bool isIon() const; inline bool isBaseline() const; inline bool isPhysicalIonFrame() const; bool isFunctionFrame() const; bool isGlobalFrame() const; bool isEvalFrame() const; bool isNonEvalFunctionFrame() const; bool hasArgs() const { return isNonEvalFunctionFrame(); } // These two methods may not be called with asm frames. inline bool hasCachedSavedFrame() const; inline void setHasCachedSavedFrame(); ScriptSource* scriptSource() const; const char* scriptFilename() const; const char16_t* scriptDisplayURL() const; unsigned computeLine(uint32_t* column = nullptr) const; JSAtom* functionDisplayAtom() const; bool mutedErrors() const; bool hasScript() const { return !isAsmJS(); } // ----------------------------------------------------------- // The following functions can only be called when hasScript() // ----------------------------------------------------------- inline JSScript* script() const; bool isConstructing() const; jsbytecode* pc() const { MOZ_ASSERT(!done()); return data_.pc_; } void updatePcQuadratic(); // The function |calleeTemplate()| returns either the function from which // the current |callee| was cloned or the |callee| if it can be read. As // long as we do not have to investigate the scope chain or build a new // frame, we should prefer to use |calleeTemplate| instead of |callee|, as // requesting the |callee| might cause the invalidation of the frame. (see // js::Lambda) JSFunction* calleeTemplate() const; JSFunction* callee(JSContext* cx) const; JSFunction* maybeCallee(JSContext* cx) const { return isFunctionFrame() ? callee(cx) : nullptr; } bool matchCallee(JSContext* cx, HandleFunction fun) const; unsigned numActualArgs() const; unsigned numFormalArgs() const; Value unaliasedActual(unsigned i, MaybeCheckAliasing = CHECK_ALIASING) const; template <class Op> inline void unaliasedForEachActual(JSContext* cx, Op op); JSObject* scopeChain(JSContext* cx) const; CallObject& callObj(JSContext* cx) const; bool hasArgsObj() const; ArgumentsObject& argsObj() const; // Get the original |this| value passed to this function. May not be the // actual this-binding (for instance, derived class constructors will // change their this-value later and non-strict functions will box // primitives). Value thisArgument(JSContext* cx) const; Value newTarget() const; Value returnValue() const; void setReturnValue(const Value& v); // These are only valid for the top frame. size_t numFrameSlots() const; Value frameSlotValue(size_t index) const; // Ensures that we have rematerialized the top frame and its associated // inline frames. Can only be called when isIon(). bool ensureHasRematerializedFrame(JSContext* cx); // True when isInterp() or isBaseline(). True when isIon() if it // has a rematerialized frame. False otherwise false otherwise. bool hasUsableAbstractFramePtr() const; // ----------------------------------------------------------- // The following functions can only be called when isInterp(), // isBaseline(), or isIon(). Further, abstractFramePtr() can // only be called when hasUsableAbstractFramePtr(). // ----------------------------------------------------------- AbstractFramePtr abstractFramePtr() const; AbstractFramePtr copyDataAsAbstractFramePtr() const; Data* copyData() const; // This can only be called when isInterp(): inline InterpreterFrame* interpFrame() const; // This can only be called when isPhysicalIonFrame(): inline jit::CommonFrameLayout* physicalIonFrame() const; // This is used to provide a raw interface for debugging. void* rawFramePtr() const; private: Data data_; jit::InlineFrameIterator ionInlineFrames_; void popActivation(); void popInterpreterFrame(); void nextJitFrame(); void popJitFrame(); void popAsmJSFrame(); void settleOnActivation(); }; class ScriptFrameIter : public FrameIter { void settle() { while (!done() && !hasScript()) FrameIter::operator++(); } public: explicit ScriptFrameIter(JSContext* cx, SavedOption savedOption = STOP_AT_SAVED) : FrameIter(cx, savedOption) { settle(); } ScriptFrameIter(JSContext* cx, ContextOption cxOption, SavedOption savedOption, DebuggerEvalOption debuggerEvalOption = FOLLOW_DEBUGGER_EVAL_PREV_LINK) : FrameIter(cx, cxOption, savedOption, debuggerEvalOption) { settle(); } ScriptFrameIter(JSContext* cx, ContextOption cxOption, SavedOption savedOption, DebuggerEvalOption debuggerEvalOption, JSPrincipals* prin) : FrameIter(cx, cxOption, savedOption, debuggerEvalOption, prin) { settle(); } ScriptFrameIter(const ScriptFrameIter& iter) : FrameIter(iter) { settle(); } explicit ScriptFrameIter(const FrameIter::Data& data) : FrameIter(data) { settle(); } explicit ScriptFrameIter(AbstractFramePtr frame) : FrameIter(frame) { settle(); } ScriptFrameIter& operator++() { FrameIter::operator++(); settle(); return *this; } }; #ifdef DEBUG bool SelfHostedFramesVisible(); #else static inline bool SelfHostedFramesVisible() { return false; } #endif /* A filtering of the FrameIter to only stop at non-self-hosted scripts. */ class NonBuiltinFrameIter : public FrameIter { void settle(); public: explicit NonBuiltinFrameIter(JSContext* cx, FrameIter::SavedOption opt = FrameIter::STOP_AT_SAVED) : FrameIter(cx, opt) { settle(); } NonBuiltinFrameIter(JSContext* cx, FrameIter::ContextOption contextOption, FrameIter::SavedOption savedOption, FrameIter::DebuggerEvalOption debuggerEvalOption = FrameIter::FOLLOW_DEBUGGER_EVAL_PREV_LINK) : FrameIter(cx, contextOption, savedOption, debuggerEvalOption) { settle(); } NonBuiltinFrameIter(JSContext* cx, FrameIter::ContextOption contextOption, FrameIter::SavedOption savedOption, FrameIter::DebuggerEvalOption debuggerEvalOption, JSPrincipals* principals) : FrameIter(cx, contextOption, savedOption, debuggerEvalOption, principals) { settle(); } NonBuiltinFrameIter(JSContext* cx, JSPrincipals* principals) : FrameIter(cx, FrameIter::ALL_CONTEXTS, FrameIter::GO_THROUGH_SAVED, FrameIter::FOLLOW_DEBUGGER_EVAL_PREV_LINK, principals) { settle(); } explicit NonBuiltinFrameIter(const FrameIter::Data& data) : FrameIter(data) {} NonBuiltinFrameIter& operator++() { FrameIter::operator++(); settle(); return *this; } }; /* A filtering of the ScriptFrameIter to only stop at non-self-hosted scripts. */ class NonBuiltinScriptFrameIter : public ScriptFrameIter { void settle(); public: explicit NonBuiltinScriptFrameIter(JSContext* cx, ScriptFrameIter::SavedOption opt = ScriptFrameIter::STOP_AT_SAVED) : ScriptFrameIter(cx, opt) { settle(); } NonBuiltinScriptFrameIter(JSContext* cx, ScriptFrameIter::ContextOption contextOption, ScriptFrameIter::SavedOption savedOption, ScriptFrameIter::DebuggerEvalOption debuggerEvalOption = ScriptFrameIter::FOLLOW_DEBUGGER_EVAL_PREV_LINK) : ScriptFrameIter(cx, contextOption, savedOption, debuggerEvalOption) { settle(); } NonBuiltinScriptFrameIter(JSContext* cx, ScriptFrameIter::ContextOption contextOption, ScriptFrameIter::SavedOption savedOption, ScriptFrameIter::DebuggerEvalOption debuggerEvalOption, JSPrincipals* principals) : ScriptFrameIter(cx, contextOption, savedOption, debuggerEvalOption, principals) { settle(); } explicit NonBuiltinScriptFrameIter(const ScriptFrameIter::Data& data) : ScriptFrameIter(data) {} NonBuiltinScriptFrameIter& operator++() { ScriptFrameIter::operator++(); settle(); return *this; } }; /* * Blindly iterate over all frames in the current thread's stack. These frames * can be from different contexts and compartments, so beware. */ class AllFramesIter : public ScriptFrameIter { public: explicit AllFramesIter(JSContext* cx) : ScriptFrameIter(cx, ScriptFrameIter::ALL_CONTEXTS, ScriptFrameIter::GO_THROUGH_SAVED, ScriptFrameIter::IGNORE_DEBUGGER_EVAL_PREV_LINK) {} }; /* Popular inline definitions. */ inline JSScript* FrameIter::script() const { MOZ_ASSERT(!done()); if (data_.state_ == INTERP) return interpFrame()->script(); MOZ_ASSERT(data_.state_ == JIT); if (data_.jitFrames_.isIonJS()) return ionInlineFrames_.script(); return data_.jitFrames_.script(); } inline bool FrameIter::isIon() const { return isJit() && data_.jitFrames_.isIonJS(); } inline bool FrameIter::isBaseline() const { return isJit() && data_.jitFrames_.isBaselineJS(); } inline InterpreterFrame* FrameIter::interpFrame() const { MOZ_ASSERT(data_.state_ == INTERP); return data_.interpFrames_.frame(); } inline bool FrameIter::isPhysicalIonFrame() const { return isJit() && data_.jitFrames_.isIonScripted() && ionInlineFrames_.frameNo() == 0; } inline jit::CommonFrameLayout* FrameIter::physicalIonFrame() const { MOZ_ASSERT(isPhysicalIonFrame()); return data_.jitFrames_.current(); } } /* namespace js */ #endif /* vm_Stack_h */
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_CANVAS_H_ #define UI_GFX_CANVAS_H_ #include <vector> #include "base/basictypes.h" #include "base/memory/scoped_ptr.h" #include "base/string16.h" #include "skia/ext/platform_canvas.h" #include "skia/ext/refptr.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/shadow_value.h" namespace gfx { class Rect; class Font; class Point; class Size; class Transform; // Canvas is a SkCanvas wrapper that provides a number of methods for // common operations used throughout an application built using ui/gfx. // // All methods that take integer arguments (as is used throughout views) // end with Int. If you need to use methods provided by SkCanvas, you'll // need to do a conversion. In particular you'll need to use |SkIntToScalar()|, // or if converting from a scalar to an integer |SkScalarRound()|. // // A handful of methods in this class are overloaded providing an additional // argument of type SkXfermode::Mode. SkXfermode::Mode specifies how the // source and destination colors are combined. Unless otherwise specified, // the variant that does not take a SkXfermode::Mode uses a transfer mode // of kSrcOver_Mode. class UI_EXPORT Canvas { public: enum TruncateFadeMode { TruncateFadeTail, TruncateFadeHead, TruncateFadeHeadAndTail, }; // Specifies the alignment for text rendered with the DrawStringInt method. enum { TEXT_ALIGN_LEFT = 1 << 0, TEXT_ALIGN_CENTER = 1 << 1, TEXT_ALIGN_RIGHT = 1 << 2, // Specifies the text consists of multiple lines. MULTI_LINE = 1 << 3, // By default DrawStringInt does not process the prefix ('&') character // specially. That is, the string "&foo" is rendered as "&foo". When // rendering text from a resource that uses the prefix character for // mnemonics, the prefix should be processed and can be rendered as an // underline (SHOW_PREFIX), or not rendered at all (HIDE_PREFIX). SHOW_PREFIX = 1 << 4, HIDE_PREFIX = 1 << 5, // Prevent ellipsizing NO_ELLIPSIS = 1 << 6, // Specifies if words can be split by new lines. // This only works with MULTI_LINE. CHARACTER_BREAK = 1 << 7, // Instructs DrawStringInt() to render the text using RTL directionality. // In most cases, passing this flag is not necessary because information // about the text directionality is going to be embedded within the string // in the form of special Unicode characters. However, we don't insert // directionality characters into strings if the locale is LTR because some // platforms (for example, an English Windows XP with no RTL fonts // installed) don't support these characters. Thus, this flag should be // used to render text using RTL directionality when the locale is LTR. FORCE_RTL_DIRECTIONALITY = 1 << 8, // Similar to FORCE_RTL_DIRECTIONALITY, but left-to-right. // See FORCE_RTL_DIRECTIONALITY for details. FORCE_LTR_DIRECTIONALITY = 1 << 9, // Instructs DrawStringInt() to not use subpixel rendering. This is useful // when rendering text onto a fully- or partially-transparent background // that will later be blended with another image. NO_SUBPIXEL_RENDERING = 1 << 10, }; // Creates an empty canvas with scale factor of 1x. Canvas(); // Creates canvas with provided DIP |size| and |scale_factor|. // If this canvas is not opaque, it's explicitly cleared to transparent before // being returned. Canvas(const gfx::Size& size, ui::ScaleFactor scale_factor, bool is_opaque); // Constructs a canvas with the size and the scale factor of the // provided |image_rep|, and draws the |image_rep| into it. Canvas(const gfx::ImageSkiaRep& image_rep, bool is_opaque); virtual ~Canvas(); // Creates a gfx::Canvas backed by an |sk_canvas| with |scale_factor|. // |sk_canvas| is assumed to be already scaled based on |scale_factor| // so no additional scaling is applied. static Canvas* CreateCanvasWithoutScaling(SkCanvas* sk_canvas, ui::ScaleFactor scale_factor); // Recreates the backing platform canvas with DIP |size| and |scale_factor|. // If the canvas is not opaque, it is explicitly cleared. // This method is public so that canvas_skia_paint can recreate the platform // canvas after having initialized the canvas. // TODO(pkotwicz): Push the scale factor into skia::PlatformCanvas such that // this method can be private. void RecreateBackingCanvas(const gfx::Size& size, ui::ScaleFactor scale_factor, bool is_opaque); // Compute the size required to draw some text with the provided font. // Attempts to fit the text with the provided width and height. Increases // height and then width as needed to make the text fit. This method // supports multiple lines. On Skia only a line_height can be specified and // specifying a 0 value for it will cause the default height to be used. static void SizeStringInt(const string16& text, const gfx::Font& font, int* width, int* height, int line_height, int flags); // Returns the number of horizontal pixels needed to display the specified // |text| with |font|. static int GetStringWidth(const string16& text, const gfx::Font& font); // Returns the default text alignment to be used when drawing text on a // gfx::Canvas based on the directionality of the system locale language. // This function is used by gfx::Canvas::DrawStringInt when the text alignment // is not specified. // // This function returns either gfx::Canvas::TEXT_ALIGN_LEFT or // gfx::Canvas::TEXT_ALIGN_RIGHT. static int DefaultCanvasTextAlignment(); // Draws text with a 1-pixel halo around it of the given color. // On Windows, it allows ClearType to be drawn to an otherwise transparenct // bitmap for drag images. Drag images have only 1-bit of transparency, so // we don't do any fancy blurring. // On Linux, text with halo is created by stroking it with 2px |halo_color| // then filling it with |text_color|. // On Mac, NOTIMPLEMENTED. // TODO(dhollowa): Skia-native implementation is underway. Cut over to // that when ready. http::/crbug.com/109946 void DrawStringWithHalo(const string16& text, const gfx::Font& font, SkColor text_color, SkColor halo_color, int x, int y, int w, int h, int flags); // Extracts an ImageSkiaRep from the contents of this canvas. gfx::ImageSkiaRep ExtractImageRep() const; // Draws a dashed rectangle of the specified color. void DrawDashedRect(const gfx::Rect& rect, SkColor color); // Saves a copy of the drawing state onto a stack, operating on this copy // until a balanced call to Restore() is made. void Save(); // As with Save(), except draws to a layer that is blended with the canvas // at the specified alpha once Restore() is called. // |layer_bounds| are the bounds of the layer relative to the current // transform. void SaveLayerAlpha(uint8 alpha); void SaveLayerAlpha(uint8 alpha, const gfx::Rect& layer_bounds); // Restores the drawing state after a call to Save*(). It is an error to // call Restore() more times than Save*(). void Restore(); // Adds |rect| to the current clip. Returns true if the resulting clip is // non-empty. bool ClipRect(const gfx::Rect& rect); // Adds |path| to the current clip. Returns true if the resulting clip is // non-empty. bool ClipPath(const SkPath& path); // Returns the bounds of the current clip (in local coordinates) in the // |bounds| parameter, and returns true if it is non empty. bool GetClipBounds(gfx::Rect* bounds); void Translate(const gfx::Vector2d& offset); void Scale(int x_scale, int y_scale); // Fills the entire canvas' bitmap (restricted to current clip) with // specified |color| using a transfer mode of SkXfermode::kSrcOver_Mode. void DrawColor(SkColor color); // Fills the entire canvas' bitmap (restricted to current clip) with // specified |color| and |mode|. void DrawColor(SkColor color, SkXfermode::Mode mode); // Fills |rect| with |color| using a transfer mode of // SkXfermode::kSrcOver_Mode. void FillRect(const gfx::Rect& rect, SkColor color); // Fills |rect| with the specified |color| and |mode|. void FillRect(const gfx::Rect& rect, SkColor color, SkXfermode::Mode mode); // Draws a single pixel rect in the specified region with the specified // color, using a transfer mode of SkXfermode::kSrcOver_Mode. // // NOTE: if you need a single pixel line, use DrawLine. void DrawRect(const gfx::Rect& rect, SkColor color); // Draws a single pixel rect in the specified region with the specified // color and transfer mode. // // NOTE: if you need a single pixel line, use DrawLine. void DrawRect(const gfx::Rect& rect, SkColor color, SkXfermode::Mode mode); // Draws the given rectangle with the given |paint| parameters. void DrawRect(const gfx::Rect& rect, const SkPaint& paint); // Draw the given point with the given |paint| parameters. void DrawPoint(const gfx::Point& p, const SkPaint& paint); // Draws a single pixel line with the specified color. void DrawLine(const gfx::Point& p1, const gfx::Point& p2, SkColor color); // Draws a line with the given |paint| parameters. void DrawLine(const gfx::Point& p1, const gfx::Point& p2, const SkPaint& paint); // Draws a circle with the given |paint| parameters. void DrawCircle(const gfx::Point& center_point, int radius, const SkPaint& paint); // Draws the given rectangle with rounded corners of |radius| using the // given |paint| parameters. void DrawRoundRect(const gfx::Rect& rect, int radius, const SkPaint& paint); // Draws the given path using the given |paint| parameters. void DrawPath(const SkPath& path, const SkPaint& paint); // Draws an image with the origin at the specified location. The upper left // corner of the bitmap is rendered at the specified location. // Parameters are specified relative to current canvas scale not in pixels. // Thus, x is 2 pixels if canvas scale = 2 & |x| = 1. void DrawImageInt(const gfx::ImageSkia&, int x, int y); // Helper for DrawImageInt(..., paint) that constructs a temporary paint and // calls paint.setAlpha(alpha). void DrawImageInt(const gfx::ImageSkia&, int x, int y, uint8 alpha); // Draws an image with the origin at the specified location, using the // specified paint. The upper left corner of the bitmap is rendered at the // specified location. // Parameters are specified relative to current canvas scale not in pixels. // Thus, |x| is 2 pixels if canvas scale = 2 & |x| = 1. void DrawImageInt(const gfx::ImageSkia& image, int x, int y, const SkPaint& paint); // Draws a portion of an image in the specified location. The src parameters // correspond to the region of the bitmap to draw in the region defined // by the dest coordinates. // // If the width or height of the source differs from that of the destination, // the image will be scaled. When scaling down, a mipmap will be generated. // Set |filter| to use filtering for images, otherwise the nearest-neighbor // algorithm is used for resampling. // // An optional custom SkPaint can be provided. // Parameters are specified relative to current canvas scale not in pixels. // Thus, |x| is 2 pixels if canvas scale = 2 & |x| = 1. void DrawImageInt(const gfx::ImageSkia& image, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h, bool filter); void DrawImageInt(const gfx::ImageSkia& image, int src_x, int src_y, int src_w, int src_h, int dest_x, int dest_y, int dest_w, int dest_h, bool filter, const SkPaint& paint); // Draws an |image| with the top left corner at |x| and |y|, clipped to // |path|. // Parameters are specified relative to current canvas scale not in pixels. // Thus, x is 2 pixels if canvas scale = 2 & |x| = 1. void DrawImageInPath(const gfx::ImageSkia& image, int x, int y, const SkPath& path, const SkPaint& paint); // Draws text with the specified color, font and location. The text is // aligned to the left, vertically centered, clipped to the region. If the // text is too big, it is truncated and '...' is added to the end. void DrawStringInt(const string16& text, const gfx::Font& font, SkColor color, int x, int y, int w, int h); void DrawStringInt(const string16& text, const gfx::Font& font, SkColor color, const gfx::Rect& display_rect); // Draws text with the specified color, font and location. The last argument // specifies flags for how the text should be rendered. It can be one of // TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT or TEXT_ALIGN_LEFT. void DrawStringInt(const string16& text, const gfx::Font& font, SkColor color, int x, int y, int w, int h, int flags); // Similar to above DrawStringInt method but with text shadows support. // Currently it's only implemented for canvas skia. Specifying a 0 line_height // will cause the default height to be used. void DrawStringWithShadows(const string16& text, const gfx::Font& font, SkColor color, const gfx::Rect& text_bounds, int line_height, int flags, const ShadowValues& shadows); // Draws a dotted gray rectangle used for focus purposes. void DrawFocusRect(const gfx::Rect& rect); // Tiles the image in the specified region. // Parameters are specified relative to current canvas scale not in pixels. // Thus, |x| is 2 pixels if canvas scale = 2 & |x| = 1. void TileImageInt(const gfx::ImageSkia& image, int x, int y, int w, int h); void TileImageInt(const gfx::ImageSkia& image, int src_x, int src_y, int dest_x, int dest_y, int w, int h); void TileImageInt(const gfx::ImageSkia& image, int src_x, int src_y, float tile_scale_x, float tile_scale_y, int dest_x, int dest_y, int w, int h); // Returns a native drawing context for platform specific drawing routines to // use. Must be balanced by a call to EndPlatformPaint(). NativeDrawingContext BeginPlatformPaint(); // Signifies the end of platform drawing using the native drawing context // returned by BeginPlatformPaint(). void EndPlatformPaint(); // Apply transformation on the canvas. void Transform(const gfx::Transform& transform); // Draws the given string with the beginning and/or the end using a fade // gradient. When truncating the head // |desired_characters_to_truncate_from_head| specifies the maximum number of // characters that can be truncated. void DrawFadeTruncatingString( const string16& text, TruncateFadeMode truncate_mode, size_t desired_characters_to_truncate_from_head, const gfx::Font& font, SkColor color, const gfx::Rect& display_rect); skia::PlatformCanvas* platform_canvas() const { return owned_canvas_.get(); } SkCanvas* sk_canvas() const { return canvas_; } ui::ScaleFactor scale_factor() const { return scale_factor_; } private: Canvas(SkCanvas* canvas, ui::ScaleFactor scale_factor); // Test whether the provided rectangle intersects the current clip rect. bool IntersectsClipRectInt(int x, int y, int w, int h); bool IntersectsClipRect(const gfx::Rect& rect); // Returns the image rep which best matches the canvas |scale_factor_|. // Returns a null image rep if |image| contains no image reps. // Builds mip map for returned image rep if necessary. // // An optional additional user defined scale can be provided. const gfx::ImageSkiaRep& GetImageRepToPaint( const gfx::ImageSkia& image) const; const gfx::ImageSkiaRep& GetImageRepToPaint( const gfx::ImageSkia& image, float user_defined_scale_factor_x, float user_defined_scale_factor_y) const; // The device scale factor at which drawing on this canvas occurs. // An additional scale can be applied via Canvas::Scale(). However, // Canvas::Scale() does not affect |scale_factor_|. ui::ScaleFactor scale_factor_; skia::RefPtr<skia::PlatformCanvas> owned_canvas_; SkCanvas* canvas_; DISALLOW_COPY_AND_ASSIGN(Canvas); }; } // namespace gfx #endif // UI_GFX_CANVAS_H_
/* Assemble all pages for export */ export HomePage from "./HomePage/HomePage"; export LoginPage from "./LoginPage/LoginPage"; export SignUpPage from "./SignUpPage/SignUpPage"; export SignUpCompletedPage from "./SignUpCompetedFormPage/SignUpCompletedFormPage";
"""NCEAverage, serve as contrast """ import math import torch from torch import nn from alias_multinomial import AliasMethod class NCEAverage(nn.Module): def __init__(self, input_size, output_size, K, T=0.07, momentum=0.5): """ Args: input_size: n_features output_size: n_samples K: number of negatives to constrast for each positive T: temperature that modulates the distribution """ super(NCEAverage, self).__init__() self.output_size = output_size self.unigrams = torch.ones(self.output_size) self.multinomial = AliasMethod(self.unigrams) self.multinomial.cuda() self.K = K self.register_buffer('params', torch.FloatTensor([K, T, momentum])) stdv = 1. / math.sqrt(input_size / 3) self.register_buffer('memory_cdr', torch.rand(output_size, input_size).mul_(2 * stdv).add_(-stdv)) self.register_buffer('memory_vdj', torch.rand(output_size, input_size).mul_(2 * stdv).add_(-stdv)) def forward(self, cdr, vdj, index, idx=None): """ Args: cdr: out_features for cdr vdj: out_features for vdj index: torch.long for data ids """ K = int(self.params[0].item()) T = self.params[1].item() momentum = self.params[2].item() batch_size = cdr.size(0) output_size = self.memory_cdr.size(0) input_size = self.memory_cdr.size(1) # score computation if idx is None: idx = self.multinomial.draw(batch_size * (self.K + 1)).view(batch_size, -1) idx.select(1, 0).copy_(index.data) # sample weight_vdj = torch.index_select(self.memory_vdj, 0, idx.view(-1)).detach() weight_vdj = weight_vdj.view(batch_size, K + 1, input_size) out_cdr = torch.bmm(weight_vdj, cdr.view(batch_size, input_size, 1)) # sample weight_cdr = torch.index_select(self.memory_cdr, 0, idx.view(-1)).detach() weight_cdr = weight_cdr.view(batch_size, K + 1, input_size) out_vdj = torch.bmm(weight_cdr, vdj.view(batch_size, input_size, 1)) out_cdr = torch.div(out_cdr, T) out_vdj = torch.div(out_vdj, T) out_cdr = out_cdr.contiguous() out_vdj = out_vdj.contiguous() # # update memory with torch.no_grad(): cdr_pos = torch.index_select(self.memory_cdr, 0, index.view(-1)) cdr_pos.mul_(momentum) cdr_pos.add_(torch.mul(cdr, 1 - momentum)) cdr_norm = cdr_pos.pow(2).sum(1, keepdim=True).pow(0.5) updated_cdr = cdr_pos.div(cdr_norm) self.memory_cdr.index_copy_(0, index, updated_cdr) vdj_pos = torch.index_select(self.memory_vdj, 0, index.view(-1)) vdj_pos.mul_(momentum) vdj_pos.add_(torch.mul(vdj, 1 - momentum)) vdj_norm = vdj_pos.pow(2).sum(1, keepdim=True).pow(0.5) updated_vdj = vdj_pos.div(vdj_norm) self.memory_vdj.index_copy_(0, index, updated_vdj) return out_cdr, out_vdj # Loss functions, adapted from the CMC github class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class NCESoftmaxLoss(nn.Module): """Softmax cross-entropy loss""" def __init__(self): super(NCESoftmaxLoss, self).__init__() #super spicified that only call the init function from NCESoftmasLoss #rather than nn.Module. self.criterion = nn.CrossEntropyLoss() def forward(self, x): bsz = x.shape[0] x = x.squeeze() label = torch.zeros([bsz]).cuda().long() loss = self.criterion(x, label) return loss
// // INActivateCarSignalIntentResponse.h // Intents // // Copyright © 2016 Apple Inc. All rights reserved. // #import <Intents/INIntentResponse.h> #import <Intents/INCarSignalOptions.h> typedef NS_ENUM(NSInteger, INActivateCarSignalIntentResponseCode) { INActivateCarSignalIntentResponseCodeUnspecified = 0, INActivateCarSignalIntentResponseCodeReady, INActivateCarSignalIntentResponseCodeInProgress, INActivateCarSignalIntentResponseCodeSuccess, INActivateCarSignalIntentResponseCodeFailure, INActivateCarSignalIntentResponseCodeFailureRequiringAppLaunch, } API_AVAILABLE(ios(10.3), watchos(3.2)) API_UNAVAILABLE(macosx); NS_ASSUME_NONNULL_BEGIN API_AVAILABLE(ios(10.3), watchos(3.2)) API_UNAVAILABLE(macosx) @interface INActivateCarSignalIntentResponse : INIntentResponse - (id)init NS_UNAVAILABLE; // The app extension has the option of capturing its private state as an NSUserActivity and returning it as the 'currentActivity'. // If the the app is launched, an NSUserActivity will be passed in with the private state. The NSUserActivity may also be used to query the app's UI extension (if provided) for a view controller representing the current intent handling state. // In the case of app launch, the NSUserActivity will have its activityType set to the name of the intent. This intent object will also be available in the NSUserActivity.interaction property. - (instancetype)initWithCode:(INActivateCarSignalIntentResponseCode)code userActivity:(nullable NSUserActivity *)userActivity NS_DESIGNATED_INITIALIZER; @property (readonly, NS_NONATOMIC_IOSONLY) INActivateCarSignalIntentResponseCode code; @property (readwrite, assign, NS_NONATOMIC_IOSONLY) INCarSignalOptions signals; @end NS_ASSUME_NONNULL_END
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, April 28, 2021 at 9:11:47 PM Mountain Standard Time * Operating System: Version 14.5 (Build 18L204) * Image Source: /System/Library/PrivateFrameworks/MediaFoundation.framework/MediaFoundation * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ @interface MediaFoundation.FailedInitialLoadingTransitionState : _UKNOWN_SUPERCLASS_ { play; } @end
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com> # License: BSD 3 clause import numpy as np import pytest def approx(v, abs=1e-15): return pytest.approx(v, abs) def parameter_test_with_min( class_tested, parameter, valid_val, invalid_type_val, invalid_val, min_value=None, min_value_strict=None, min_value_str=None, mandatory=False, fixed_type=None, required_args=None, ): """Tests for an attribute of integer type Parameters ---------- valid_val A valid value for the parameter invalid_type_val A value with invalid type invalid_val A value which is invalid because of its value parameter min_value mandatory Returns ------- """ if required_args is None: required_args = {} def get_params(param, val): """If the parameter is not 'n_classes', we need to specify `n_classes`, since it's mandatory to create the class """ required_args[param] = val return required_args # If the parameter is mandatory, we check that an exception is raised # if not passed to the constructor if mandatory: with pytest.raises(TypeError) as exc_info: class_tested() assert exc_info.type is TypeError assert ( exc_info.value.args[0] == "__init__() missing 1 required " "positional argument: '%s'" % parameter ) if min_value is not None and min_value_strict is not None: raise ValueError( "You can't set both `min_value` and " "`min_value_strict` at the same time" ) clf = class_tested(**get_params(parameter, valid_val)) assert getattr(clf, parameter) == valid_val # If valid_val is valid, than valid_val + 1 is also valid setattr(clf, parameter, valid_val + 1) assert getattr(clf, parameter, valid_val + 1) with pytest.raises( ValueError, match="`%s` must be of type `%s`" % (parameter, fixed_type.__name__), ): setattr(clf, parameter, invalid_type_val) with pytest.raises( ValueError, match="`%s` must be of type `%s`" % (parameter, fixed_type.__name__), ): class_tested(**get_params(parameter, invalid_type_val)) if min_value is not None: with pytest.raises( ValueError, match="`%s` must be >= %s" % (parameter, min_value_str) ): setattr(clf, parameter, invalid_val) with pytest.raises( ValueError, match="`%s` must be >= %s" % (parameter, min_value_str) ): class_tested(**get_params(parameter, invalid_val)) if min_value_strict is not None: with pytest.raises( ValueError, match="`%s` must be > %s" % (parameter, min_value_str) ): setattr(clf, parameter, invalid_val) with pytest.raises( ValueError, match="`%s` must be > %s" % (parameter, min_value_str) ): class_tested(**get_params(parameter, invalid_val)) clf = class_tested(**get_params(parameter, valid_val)) # TODO: we should not need to change the dtype here X = np.random.randn(2, 2) y = np.array([0.0, 1.0]) clf.partial_fit(X, y) with pytest.raises( ValueError, match="You cannot modify `%s` " "after calling `partial_fit`" % parameter, ): setattr(clf, parameter, valid_val) def parameter_test_with_type( class_tested, parameter, valid_val, invalid_type_val, mandatory, fixed_type ): # TODO: code it pass
const mongoose = require('mongoose'); const Todo = mongoose.Schema({ name:{ type: String, unique: false }, description: { type: String, unique: false }, postedBy:{ type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true } }); module.exports = mongoose.model('Todo', Todo);
from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from ccdemo.users.forms import UserChangeForm, UserCreationForm User = get_user_model() @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = (("User", {"fields": ("name",)}),) + auth_admin.UserAdmin.fieldsets list_display = ["username", "name", "is_superuser"] search_fields = ["name"]
import json import re import mechanize from unidecode import unidecode from urllib2 import quote br = mechanize.Browser() def send_query(query): try: return br.open(query) except: #print "Error: Cannot execute query = "+query return 0 ### MAIN print "########### Geotravel ###########" json_data=open('Vietnam_SelCities.geojson') data = json.load(json_data) json_data.close() for city in data["features"]: cityName = unidecode(city["properties"]["name"]) escaped_string = quote(cityName) success = send_query("http://wikitravel.org/en/"+escaped_string) if success: print "City "+cityName + ":\t\thttp://wikitravel.org/en/"+escaped_string else: print "City "+cityName+":\t\tNot supported" print "########### END ###########"
webpackJsonp([1],{"+29q":function(t,e,r){t.exports=r.p+"img/ill1.d0aa45c.svg"},"+h1q":function(t,e){},"026T":function(t,e){t.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/Pg0KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE5LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPg0KPHN2ZyB2ZXJzaW9uPSIxLjEiIGlkPSJDYXBhXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSIwIDAgMzYwIDM2MCIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMzYwIDM2MDsiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGcgaWQ9IlhNTElEXzEwODhfIj4NCgk8cG9seWdvbiBpZD0iWE1MSURfMTEwNF8iIHN0eWxlPSJmaWxsOiNDRENERDA7IiBwb2ludHM9IjI0MCw1MCAyNDAsODAgMzMwLDgwIDMzMCwxODYuNTUxIDMzMCwyMTguMzg2IDMzMCwyODAgMjQwLDI4MCAyNDAsMzEwIA0KCQkzNjAsMzEwIDM2MCw1MCAJIi8+DQoJPHJlY3QgaWQ9IlhNTElEXzExMDVfIiB4PSIxMjAiIHk9IjUwIiBzdHlsZT0iZmlsbDojRUJFQkVDOyIgd2lkdGg9IjEyMCIgaGVpZ2h0PSIzMCIvPg0KCTxwb2x5Z29uIGlkPSJYTUxJRF8xMTA2XyIgc3R5bGU9ImZpbGw6I0VCRUJFQzsiIHBvaW50cz0iMTUxLjc1LDI4MCAxMjAsMjgwIDEyMCwzMTAgMjQwLDMxMCAyNDAsMjgwIAkiLz4NCgk8cG9seWdvbiBpZD0iWE1MSURfMTEwN18iIHN0eWxlPSJmaWxsOiNDRENERDA7IiBwb2ludHM9IjMwLDI4MCAzMCwxMTEuODM2IDMwLDgwIDEyMCw4MCAxMjAsNTAgMCw1MCAwLDMxMCAxMjAsMzEwIDEyMCwyODAgCSIvPg0KCTxwYXRoIGlkPSJYTUxJRF8xMTA4XyIgc3R5bGU9ImZpbGw6IzY0QzM3RDsiIGQ9Ik0xMzUsMTY1YzAtNS4yNDcsMC45MDctMTAuMjgsMi41NTgtMTQuOTYzTDMwLDExMS44MzZWMjgwaDkwbDI3LjMzNS03OC44OTkNCgkJQzE0MC4zMzcsMTg5LjY5OSwxMzUsMTc3LjA1NCwxMzUsMTY1eiIvPg0KCTxwYXRoIGlkPSJYTUxJRF8xMTA5XyIgc3R5bGU9ImZpbGw6IzY0QzM3RDsiIGQ9Ik0xODAsMjQwYzAsMC00LjUyNy00LjAyNi0xMC43MDctMTAuNjM1TDE1MS43NSwyODBIMjQwaDkwdi02MS42MTQNCgkJbC0xMDcuNTA1LTM4LjE4MkMyMTMuMDM3LDIxMC42MzEsMTgwLDI0MCwxODAsMjQweiIvPg0KCTxwYXRoIGlkPSJYTUxJRF8xMTEwXyIgc3R5bGU9ImZpbGw6Izk5RUZGMjsiIGQ9Ik0xNDcuMzM1LDIwMS4xMDFMMTIwLDI4MGgzMS43NWwxNy41NDMtNTAuNjM1DQoJCUMxNjIuNjk1LDIyMi4zMDksMTU0LjIxNCwyMTIuMzA4LDE0Ny4zMzUsMjAxLjEwMXoiLz4NCgk8cGF0aCBpZD0iWE1MSURfMTExMV8iIHN0eWxlPSJmaWxsOiM3OEI5RUI7IiBkPSJNMzAsODBsMTI4LjMwOCw0NS41NzFDMTY0Ljc0MiwxMjIuMDIzLDE3Mi4xMzQsMTIwLDE4MCwxMjANCgkJYzE4Ljg2OCwwLDM1LjAxNSwxMS42MTgsNDEuNzAxLDI4LjA4NkwzMzAsMTg2LjU1MVY4MGgtOTBIMTIwSDMweiIvPg0KCTxwYXRoIGlkPSJYTUxJRF8xMTEyXyIgc3R5bGU9ImZpbGw6I0ZGREE0NDsiIGQ9Ik0xNTguMzA4LDEyNS41NzFMMzAsODB2MzEuODM2bDEwNy41NTgsMzguMjAxDQoJCUMxNDEuMjUxLDEzOS41NjEsMTQ4LjcwNiwxMzAuODY0LDE1OC4zMDgsMTI1LjU3MXoiLz4NCgk8cGF0aCBpZD0iWE1MSURfMTExM18iIHN0eWxlPSJmaWxsOiNGRkRBNDQ7IiBkPSJNMjI1LDE2NWMwLDUuMDEtMC45MjUsMTAuMTIxLTIuNTA1LDE1LjIwNEwzMzAsMjE4LjM4NnYtMzEuODM1bC0xMDguMjk5LTM4LjQ2NA0KCQlDMjIzLjgyMiwxNTMuMzEsMjI1LDE1OS4wMTYsMjI1LDE2NXoiLz4NCgk8cGF0aCBpZD0iWE1MSURfMTExNF8iIHN0eWxlPSJmaWxsOiNGRjUwMjM7IiBkPSJNMTM3LjU1OCwxNTAuMDM3QzEzNS45MDcsMTU0LjcyLDEzNSwxNTkuNzUzLDEzNSwxNjUNCgkJYzAsMTIuMDU0LDUuMzM3LDI0LjY5OSwxMi4zMzUsMzYuMTAxYzYuODc5LDExLjIwOCwxNS4zNiwyMS4yMDgsMjEuOTU4LDI4LjI2NUMxNzUuNDczLDIzNS45NzQsMTgwLDI0MCwxODAsMjQwdi02MA0KCQljLTguMjg0LDAtMTUtNi43MTYtMTUtMTVzNi43MTYtMTUsMTUtMTV2LTMwYy03Ljg2NiwwLTE1LjI1OCwyLjAyMy0yMS42OTIsNS41NzFDMTQ4LjcwNiwxMzAuODY0LDE0MS4yNTEsMTM5LjU2MSwxMzcuNTU4LDE1MC4wMzcNCgkJeiIvPg0KCTxwYXRoIGlkPSJYTUxJRF8xMTE1XyIgc3R5bGU9ImZpbGw6I0JGM0MxQTsiIGQ9Ik0xOTUsMTY1YzAsOC4yODQtNi43MTYsMTUtMTUsMTV2NjBjMCwwLDMzLjAzNy0yOS4zNjksNDIuNDk1LTU5Ljc5Ng0KCQlDMjI0LjA3NSwxNzUuMTIxLDIyNSwxNzAuMDEsMjI1LDE2NWMwLTUuOTg0LTEuMTc4LTExLjY5LTMuMjk5LTE2LjkxNEMyMTUuMDE1LDEzMS42MTgsMTk4Ljg2OCwxMjAsMTgwLDEyMHYzMA0KCQlDMTg4LjI4NCwxNTAsMTk1LDE1Ni43MTYsMTk1LDE2NXoiLz4NCgk8Y2lyY2xlIGlkPSJYTUxJRF8xMTE2XyIgc3R5bGU9ImZpbGw6I0ZGRkZGRjsiIGN4PSIxODAiIGN5PSIxNjUiIHI9IjE1Ii8+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8L3N2Zz4NCg=="},"1e2O":function(t,e,r){t.exports=r.p+"img/flower-card.b11b0c2.jpeg"},"2WO5":function(t,e,r){t.exports=r.p+"img/ชา กาแฟ และโกโก้.c3a5ad5.jpeg"},"2oNb":function(t,e,r){t.exports=r.p+"img/หัตถกรรม.474219e.jpeg"},"2tzC":function(t,e){},"3+hF":function(t,e,r){t.exports=r.p+"img/login-logo.649db65.jpeg"},"34Nt":function(t,e,r){t.exports=r.p+"img/fruitree.4a08213.jpeg"},"3jyg":function(t,e){},"3rT5":function(t,e){},"4BYA":function(t,e,r){t.exports=r.p+"img/content-1.0074234.jpeg"},"4jaN":function(t,e){},"4uZN":function(t,e,r){t.exports=r.p+"img/corn-card.44809d5.jpeg"},"5ELs":function(t,e){},"5HHC":function(t,e,r){t.exports=r.p+"img/flower-card-2.33493d6.jpeg"},"5S8a":function(t,e,r){t.exports=r.p+"img/พืชท้องถิ่น.2a53b31.jpeg"},"6fdq":function(t,e){},"6pYU":function(t,e){},"6seM":function(t,e,r){t.exports=r.p+"img/ปศุสัตว์ และประมงค์.25cb886.jpeg"},"7zck":function(t,e){},"8ZCl":function(t,e,r){t.exports=r.p+"img/ผัก.650141f.jpeg"},"9+Ew":function(t,e){t.exports="data:image/svg+xml;base64,PHN2ZyBjbGFzcz0id2F2ZSIgc3R5bGU9InBvaW50ZXItZXZlbnRzOiBub25lIiBmaWxsPSIjMDc0ZDY2IiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTkyMCA3NSI+Cgk8ZGVmcz4KCQk8Y2xpcFBhdGggaWQ9ImEiPgoJCQk8cmVjdCBjbGFzcz0iYSIgd2lkdGg9IjE5MjAiIGhlaWdodD0iNzUiIC8+CgkJPC9jbGlwUGF0aD4KCQk8c3R5bGU+CgkJCS5he2ZpbGw6bm9uZTt9CgkJCS5ie2NsaXAtcGF0aDogdXJsKCNhKTt9CgkJCS5kIHtvcGFjaXR5OiAwLjU7IGlzb2xhdGlvbjogaXNvbGF0ZTt9CgkJPC9zdHlsZT4KCTwvZGVmcz4KCTx0aXRsZT4KCQl3YXZlCgk8L3RpdGxlPgoJPGcgY2xhc3M9ImIiPgoJCTxwYXRoIGNsYXNzPSJjIiBkPSJNMTk2MywzMjdILTEwNVY2NUEyNjQ3LjQ5LDI2NDcuNDksMCwwLDEsNDMxLDE5YzIxNy43LDMuNSwyMzkuNiwzMC44LDQ3MCwzNiwyOTcuMyw2LjcsMzY3LjUtMzYuMiw2NDItMjhhMjUxMS40MSwyNTExLjQxLDAsMCwxLDQyMCw0OCIgLz4KCTwvZz4KCTxnIGNsYXNzPSJiIj4KCQk8cGF0aCBjbGFzcz0iZCIgZD0iTS0xMjcsNDA0SDE5NjNWNDRjLTE0MC4xLTI4LTM0My4zLTQ2LjctNTY2LDIyLTc1LjUsMjMuMy0xMTguNSw0NS45LTE2Miw2NC00OC42LDIwLjItNDA0LjcsMTI4LTc4NCwwQzM1NS4yLDk3LjcsMzQxLjYsNzguMywyMzUsNTAsODYuNiwxMC42LTQxLjgsNi45LTEyNywxMCIgLz4KCTwvZz4KCTxnIGNsYXNzPSJiIj4KCQk8cGF0aCBjbGFzcz0iZCIgZD0iTTE5NzksNDYyLTE1NSw0NDZWMTA2QzI1MS44LDIwLjIsNTc2LjYsMTUuOSw4MDUsMzBjMTY3LjQsMTAuMywzMjIuMywzMi45LDY4MCw1NiwyMDcsMTMuNCwzNzgsMjAuMyw0OTQsMjQiIC8+Cgk8L2c+Cgk8ZyBjbGFzcz0iYiI+CgkJPHBhdGggY2xhc3M9ImQiIGQ9Ik0xOTk4LDQ4NEgtMjQzVjEwMGM0NDUuOCwyNi44LDc5NC4yLTQuMSwxMDM1LTM5LDE0MS0yMC40LDIzMS4xLTQwLjEsMzc4LTQ1LDM0OS42LTExLjYsNjM2LjcsNzMuOCw4MjgsMTUwIiAvPgoJPC9nPgo8L3N2Zz4K"},"93jX":function(t,e,r){t.exports=r.p+"img/icon1.6fddce4.png"},"9D+C":function(t,e,r){t.exports=r.p+"img/dryfood-card.cb244d2.jpeg"},"9iO8":function(t,e,r){t.exports=r.p+"img/flower-card-3.d1b1128.jpeg"},AIOO:function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAADQAAAA0AF5Y8+UAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAIpQTFRF////AAD/RliVSVeSSFyQRlmTRleRSFmWR1qSSFmUR1mTR1iUSFqSR1qTR1mUR1mTSFiSR1iTR1iUR1mTR1qTRlmUR1mUR1qSR1qTRlmTR1mTRliTRlmTR1mTR1iTR1mTR1qTR1mTR1mTRlmTR1mTR1mTR1mTR1mTR1mUR1mTRlmTR1mTR1mTR1mTDzUfHgAAAC10Uk5TAAEdIycoLC42OVNdYG9wdnyChZCXmJ2iqLXCx9LV2+Dh4uPk5ebn8PL09vz+lXQN5AAAAJhJREFUKM910scSwjAMRdEbSCAU04LpmN6t//89VsnISfx2mrN5I4nEOC+1eGcSjLTG4NrB4dvBE4y/5bCf9Y4iIgF8cwA2DZgSgQ6QTmavOryBrBw0nIBRDMZN2NsFMLDWfkLoUmYVg20IaQWHEHbFHMiLYt1o9WxvJfKIwT0GtwDUoa4KvD7tRYHTz3BWYFDvUy3RO5P8AZLpTyodVpEmAAAAAElFTkSuQmCC"},AShl:function(t,e,r){t.exports=r.p+"img/พืชท้องถิ่น.3238ee2.jpeg"},AYtb:function(t,e){},BkM8:function(t,e,r){t.exports=r.p+"img/slider2.b3a6509.jpg"},C4HF:function(t,e){t.exports="data:image/svg+xml;base64,PHN2ZyBjbGFzcz0id2F2ZSIgc3R5bGU9InBvaW50ZXItZXZlbnRzOiBub25lIiBmaWxsPSJ3aGl0ZSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgdmlld0JveD0iMCAwIDE5MjAgNzUiPgoJPGRlZnM+CgkJPGNsaXBQYXRoIGlkPSJhIj4KCQkJPHJlY3QgY2xhc3M9ImEiIHdpZHRoPSIxOTIwIiBoZWlnaHQ9Ijc1IiAvPgoJCTwvY2xpcFBhdGg+CgkJPHN0eWxlPgoJCQkuYXtmaWxsOm5vbmU7fQoJCQkuYntjbGlwLXBhdGg6IHVybCgjYSk7fQoJCQkuZCB7b3BhY2l0eTogMC41OyBpc29sYXRpb246IGlzb2xhdGU7fQoJCTwvc3R5bGU+Cgk8L2RlZnM+Cgk8dGl0bGU+CgkJd2F2ZQoJPC90aXRsZT4KCTxnIGNsYXNzPSJiIj4KCQk8cGF0aCBjbGFzcz0iYyIgZD0iTTE5NjMsMzI3SC0xMDVWNjVBMjY0Ny40OSwyNjQ3LjQ5LDAsMCwxLDQzMSwxOWMyMTcuNywzLjUsMjM5LjYsMzAuOCw0NzAsMzYsMjk3LjMsNi43LDM2Ny41LTM2LjIsNjQyLTI4YTI1MTEuNDEsMjUxMS40MSwwLDAsMSw0MjAsNDgiIC8+Cgk8L2c+Cgk8ZyBjbGFzcz0iYiI+CgkJPHBhdGggY2xhc3M9ImQiIGQ9Ik0tMTI3LDQwNEgxOTYzVjQ0Yy0xNDAuMS0yOC0zNDMuMy00Ni43LTU2NiwyMi03NS41LDIzLjMtMTE4LjUsNDUuOS0xNjIsNjQtNDguNiwyMC4yLTQwNC43LDEyOC03ODQsMEMzNTUuMiw5Ny43LDM0MS42LDc4LjMsMjM1LDUwLDg2LjYsMTAuNi00MS44LDYuOS0xMjcsMTAiIC8+Cgk8L2c+Cgk8ZyBjbGFzcz0iYiI+CgkJPHBhdGggY2xhc3M9ImQiIGQ9Ik0xOTc5LDQ2Mi0xNTUsNDQ2VjEwNkMyNTEuOCwyMC4yLDU3Ni42LDE1LjksODA1LDMwYzE2Ny40LDEwLjMsMzIyLjMsMzIuOSw2ODAsNTYsMjA3LDEzLjQsMzc4LDIwLjMsNDk0LDI0IiAvPgoJPC9nPgoJPGcgY2xhc3M9ImIiPgoJCTxwYXRoIGNsYXNzPSJkIiBkPSJNMTk5OCw0ODRILTI0M1YxMDBjNDQ1LjgsMjYuOCw3OTQuMi00LjEsMTAzNS0zOSwxNDEtMjAuNCwyMzEuMS00MC4xLDM3OC00NSwzNDkuNi0xMS42LDYzNi43LDczLjgsODI4LDE1MCIgLz4KCTwvZz4KPC9zdmc+Cg=="},"DM+Z":function(t,e,r){t.exports=r.p+"img/deal1.34dd409.jpg"},DPYr:function(t,e,r){t.exports=r.p+"img/dried.72ef03e.jpeg"},DkYy:function(t,e,r){t.exports=r.p+"img/content.1ca1ad2.jpeg"},EQEi:function(t,e){t.exports="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDE1LjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgLS0+CjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+CjxzdmcgdmVyc2lvbj0iMS4xIiBpZD0iTGF5ZXJfMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIxOTIwcHgiIGhlaWdodD0iMzA0cHgiIHZpZXdCb3g9IjAgMCAxOTIwIDMwNCIgZW5hYmxlLWJhY2tncm91bmQ9Im5ldyAwIDAgMTkyMCAzMDQiIHhtbDpzcGFjZT0icHJlc2VydmUiPgoJPHBhdGggZmlsbD0iI2Y2ZjZmNiIgZD0iTTAsMjc0YzAsMCwxOTUuMjgtMTc0LDU3OS4yOC0xMjRzNTgwLjE0Ny03Ni40MDgsNzM2LTEwOEMxNDYzLjI4LDEyLDE5MjAsMCwxOTIwLDB2MzA0SDBWMjc0eiIgLz4KPC9zdmc+Cg=="},EVLe:function(t,e){t.exports="data:image/svg+xml;base64,PHN2ZyBpZD0iU3ZnanNTdmcxMDAxIiB3aWR0aD0iMjg4IiBoZWlnaHQ9IjI4OCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpzdmdqcz0iaHR0cDovL3N2Z2pzLmNvbS9zdmdqcyI+Cgk8ZGVmcyBpZD0iU3ZnanNEZWZzMTAwMiI+Cgk8L2RlZnM+Cgk8ZyBpZD0iU3ZnanNHMTAwOCIgdHJhbnNmb3JtPSJtYXRyaXgoMC45MTY3LDAsMCwwLjkxNjcsMTEuOTk0ODMwNDQwMTM5NzY1LDEyLjE0MjYxOTI3MTI3ODM5MikiPgoJCTxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjI4OCIgaGVpZ2h0PSIyODgiIHZpZXdCb3g9IjAgMCAzMiAzMiI+CgkJCTxkZWZzPgoJCQkJPGxpbmVhckdyYWRpZW50IGlkPSJhIj4KCQkJCQk8c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiMyMDI5NTYiPgoJCQkJCTwvc3RvcD4KCQkJCQk8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyODNlNzkiPgoJCQkJCTwvc3RvcD4KCQkJCTwvbGluZWFyR3JhZGllbnQ+CgkJCQk8bGluZWFyR3JhZGllbnQgaWQ9ImIiIHgxPSIxLjk5OCIgeDI9IjI4IiB5MT0iMTYuMTk3IiB5Mj0iMTYuMTk3IiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeGxpbms6aHJlZj0iI2EiPgoJCQkJPC9saW5lYXJHcmFkaWVudD4KCQkJPC9kZWZzPgoJCQk8cGF0aCBmaWxsPSJ1cmwoI2IpIiBkPSJNIDE1Ljk2MDkzOCAyLjM5NjQ4NDQgQyAxNS4xMzMwOTkgMi40MzAyNTE1IDE0LjMxNzg4NiAyLjc2NjUzNzUgMTMuNjkxNDA2IDMuMzkyNTc4MSBDIDEzLjYwMzYwNCAzLjQwMTQ4NTggMTMuNTE0NTUzIDMuNDAyMyAxMy40Mjc3MzQgMy40MTc5Njg4IEMgMTIuNzAwODYyIDMuNTQ5MDU4MyAxMi4wMjI2ODkgMy45MjMyODc0IDExLjUwMTk1MyA0LjUwMTk1MzEgQSAwLjUwMDA1IDAuNTAwMDUgMCAwIDAgMTEuMjY3NTc4IDQuOTE3OTY4OCBBIDAuNTAwMDUgMC41MDAwNSAwIDAgMCAxMS4yNjc1NzggNC45Mjk2ODc1IEEgMC41MDAwNSAwLjUwMDA1IDAgMCAwIDExLjI2NzU3OCA0Ljk0MTQwNjIgQSAwLjUwMDA1IDAuNTAwMDUgMCAwIDAgMTEuNDY0ODQ0IDUuMzM5ODQzOCBDIDEyLjE1NzAyNSA2LjA3MDI0OSAxMi42MjQ4NDQgNy4wMDc5MTg3IDEyLjg0Mzc1IDggTCAxMi40NjQ4NDQgOCBBIDAuNTAwMDQ5OTQgMC41MDAwNDk5NCAwIDEgMCAxMi40NjQ4NDQgOSBBIDAuNTAwMDQ5OTQgMC41MDAwNDk5NCAwIDEgMCAxMi40NjQ4NDQgMTAgQSAwLjUwMDA0OTk0IDAuNTAwMDQ5OTQgMCAwIDAgMTIuMzMyMDMxIDEwLjk4MjQyMiBDIDEyLjExNTcyMyAxMS40MDYwMTMgMTEuODYyMDAyIDExLjc5NjA2MiAxMS41NDg4MjggMTIuMTY5OTIyIEMgMTAuNzE2NTEyIDEzLjE2MzYyMiA5LjU0ODEyNDYgMTQuMTMwMDQ0IDguNDcwNzAzMSAxNS43NzczNDQgQyA2LjI2MDE5OTEgMTkuMTU3MDQ0IDYuNDc0Njg0IDI0LjQwMDk4NCA5LjU2ODM1OTQgMjcuMzk2NDg0IEMgMTIuNDc2NDQ0IDMwLjM2MzY4NCAxNy4zODMwMjkgMzAuODQ3NTEyIDIwLjgzNTkzOCAyOC41NzAzMTIgQyAyNC40MTUzMzIgMjYuMzQ1NzEyIDI1Ljk1NzI2NiAyMS41MzgxMTIgMjQuMzg0NzY2IDE3LjYzMjgxMiBDIDIzLjQyMjkyNiAxNC45ODM5MTMgMjEuMTM5MiAxMy4zMzc3MTkgMTkuODM5ODQ0IDExLjYzNjcxOSBDIDE5LjY1NTE0OSAxMS4zOTQ5NDggMTkuNDk3MDA3IDExLjE1MjMyOSAxOS4zNTU0NjkgMTAuOTEwMTU2IEEgMC41MDAwNDk5NCAwLjUwMDA0OTk0IDAgMCAwIDE5LjA2MjUgMTAgQSAwLjUwMDA0OTk0IDAuNTAwMDQ5OTQgMCAxIDAgMTkuMDYyNSA5IEEgMC41MDAwNDk5NCAwLjUwMDA0OTk0IDAgMSAwIDE5LjA2MjUgOCBMIDE4LjkzNzUgOCBDIDE5LjE0MTIzNSA3LjIxNzU5MjggMTkuNTc5ODc3IDYuMzE4NzcyNCAyMC40MDgyMDMgNS4yMzQzNzUgQSAwLjUwMDIwODg5IDAuNTAwMjA4ODkgMCAwIDAgMjAuNDYwOTM4IDUuMTQ4NDM3NSBBIDAuNTAxNDYzMzIgMC40OTg5NzUyNCA2MC4wMDA2MTkgMCAwIDIwLjY0NDUzMSA0LjM3NSBDIDIwLjIxOTQ4NCAzLjg0NDYgMTkuNjU1MzAzIDMuNDY0NzE4OCAxOS4wMzcxMDkgMy4yNjE3MTg4IEMgMTguNzU0Njg3IDMuMTY5MDIyMSAxOC40NjA3MDYgMy4xMTgxNDg0IDE4LjE2MjEwOSAzLjEwMTU2MjUgQyAxNy41MTE5ODUgMi42MDUyODA5IDE2LjczMzY2MiAyLjM2NDUwMTggMTUuOTYwOTM4IDIuMzk2NDg0NCB6IE0gMTYuMDAxOTUzIDMuMzg4NjcxOSBDIDE2LjI1ODMyMSAzLjM3Nzk3MTIgMTYuNTE0MDc3IDMuNDE1ODkwOCAxNi43NjM2NzIgMy40ODgyODEyIEEgMC41MDE4ODQ1MSAwLjQ5OTM5NDM0IDYwLjAwMDYxOSAwIDAgMTYuNzYxNzE5IDMuNDkwMjM0NCBBIDAuNTAxODg0NTEgMC40OTkzOTQzNCA2MC4wMDA2MTkgMCAwIDE3LjM1NTQ2OSA0LjE3NzczNDQgQyAxNy41NDI5ODcgNC4xMjY5ODQxIDE3LjczMzQ4NSA0LjEwNDY2MTYgMTcuOTIxODc1IDQuMDk5NjA5NCBBIDAuNTAwMDUgMC41MDAwNSAwIDAgMCAxOC4wOTU3MDMgNC4xMDE1NjI1IEMgMTguNjM2MTc0IDQuMTI2NDQxOSAxOS4xNTUwNzYgNC4zMzA5NTY3IDE5LjU2ODM1OSA0LjY5MzM1OTQgQyAxOC42NDI0MDkgNS45MTk1ODM1IDE4LjEwMzE0NCA3LjAwNzU1NzQgMTcuODkyNTc4IDggTCAxMy44NzEwOTQgOCBDIDEzLjY2MjgzNCA2Ljg4NzA3MDcgMTMuMTcyNDY3IDUuODM2NTY0NyAxMi40NDMzNTkgNC45NjI4OTA2IEMgMTMuMjEzMzg1IDQuMjgzMTMzNyAxNC4zMjk4NTMgNC4xNTg1OTIxIDE1LjI0MDIzNCA0LjY4OTQ1MzEgQSAwLjUwMDA1IDAuNTAwMDUgMCAxIDAgMTUuNzQ0MTQxIDMuODI2MTcxOSBDIDE1LjU2NjQ3OSAzLjcyMjU4ODUgMTUuMzgyOTc3IDMuNjM2NzY2OSAxNS4xOTUzMTIgMy41NjgzNTk0IEMgMTUuNDU0MTcyIDMuNDYyMTQ0NCAxNS43MjY3NTggMy40MDAxNTg0IDE2LjAwMTk1MyAzLjM4ODY3MTkgeiBNIDIyLjk2NDg0NCA4LjUyNzM0MzggTCAyMi45NjQ4NDQgOC41MjkyOTY5IEMgMjIuMzE2MjQgOC41NTYyOTY5IDIxLjY4MTEwMyA4LjgxODM4MTIgMjEuMTg1NTQ3IDkuMzAwNzgxMiBDIDIxLjEyODQxNyA5LjMxMDc4MTIgMjEuMDcwNDI0IDkuMzEwNDA2MiAyMS4wMTM2NzIgOS4zMTY0MDYyIEMgMjAuODUxOTcgOS4zNDU0MDYyIDIwLjY5NjM2NCA5LjQwMTQzNzUgMjAuNTQyOTY5IDkuNDYwOTM3NSBDIDIwLjU0NDU2OSA5LjQ3NTkzNzUgMjAuNTU0NzQ4IDkuNDg4OTA2MyAyMC41NTQ2ODggOS41MDM5MDYyIEMgMjAuNTU0MDE5IDkuNjc0NDA2MiAyMC40MzI2MTMgOS44MzA0NDY5IDIwLjM3MzA0NyA5Ljk5ODA0NjkgQyAyMC40MzY2MzcgMTAuMTc4MDQ3IDIwLjU2MDkyIDEwLjM0OTE1IDIwLjU1NjY0MSAxMC41MzEyNSBDIDIwLjU1NjMwNCAxMC41NDcyNSAyMC41NDc2NzUgMTAuNTYyMTI1IDIwLjU0Njg3NSAxMC41NzgxMjUgQyAyMS4wODMwNjQgMTAuMjE0NDI1IDIxLjc3NTI1IDEwLjE2Mjg1OSAyMi4zNTkzNzUgMTAuNTA1ODU5IEEgMC41MDAyOTQ5NyAwLjUwMDI5NDk3IDAgMSAwIDIyLjg2NTIzNCA5LjY0MjU3ODEgQyAyMi44MTIzODQgOS42MTE1NzgxIDIyLjc1NzI1OSA5LjU4NzU0NjkgMjIuNzAzMTI1IDkuNTYwNTQ2OSBDIDIyLjk0NTUxIDkuNTA1NTQ2OSAyMy4xOTU3NjcgOS41MTA1NDY5IDIzLjQzOTQ1MyA5LjU2MDU0NjkgQSAwLjUwMjMwNjQxIDAuNDk4MjU4NTkgNjAuMDAxNjI0IDAgMCAyNC4wNzAzMTIgMTAuMTIxMDk0IEMgMjQuNjAwMjUxIDkuOTc2NzkzOCAyNS4xNDUzOTQgMTAuMTA0MDk0IDI1LjU2NjQwNiAxMC40MzM1OTQgQyAyNC44NzY4NjcgMTEuMzczNTk0IDI0LjQ3NTcwMiAxMi4yMTgzNDEgMjQuMzI2MTcyIDEyLjk5NDE0MSBMIDIyLjQzMTY0MSAxMi45OTQxNDEgQyAyMi43MzQ4OTUgMTMuMzEzNTQxIDIzLjAzMDc2NCAxMy42MzEzNDEgMjMuMzM1OTM4IDEzLjk5NDE0MSBDIDIzLjYwMDMxOSAxNC4zMDg0NDEgMjMuODU2ODMzIDE0LjY0MDM0MSAyNC4xMDM1MTYgMTQuOTk0MTQxIEwgMjQuNTAxOTUzIDE0Ljk5NDE0MSBDIDI0LjY4MDg1NSAxNS40NTkyNDEgMjQuOTM2NTI5IDE1Ljg4ODIwMyAyNS4yMzYzMjggMTYuMjgzMjAzIEMgMjYuMzU0MjUgMTcuNzU1ODAzIDI3Ljk2Nzc0NiAxOC45NDc1MTYgMjguNTg1OTM4IDIwLjY2NjAxNiBDIDI4LjU4NzczNyAyMC42NzYwMTYgMjguNTg5Njk3IDIwLjY3NzU5NCAyOC41OTE3OTcgMjAuNjgzNTk0IEMgMjkuNjI5ODU3IDIzLjI2NjY5NCAyOC41Nzc1MjcgMjYuNTY1NTUgMjYuMjI4NTE2IDI4LjAzMTI1IEwgMjYuMjE0ODQ0IDI4LjA0MTAxNiBDIDI1LjAxNjMwNCAyOC44Mzc3MTYgMjMuNTI0MzU3IDI5LjEwNTk1IDIyLjA5OTYwOSAyOC45MDYyNSBDIDIxLjg2NjI3OSAyOS4wODQ0NSAyMS42MjMwMTIgMjkuMjUyOTU2IDIxLjM3MTA5NCAyOS40MTAxNTYgQyAyMS4yMTkwNjQgMjkuNTEwMTU2IDIxLjA2MDcxMyAyOS41OTcyIDIwLjkwNDI5NyAyOS42ODc1IEMgMjIuODQ5NTA3IDMwLjI2NzIgMjUuMDM2ODg3IDMwLjAxODQ0NyAyNi43NjM2NzIgMjguODczMDQ3IEMgMjkuNTUyNjYyIDI3LjEyNzY0NyAzMC43NDYzMzEgMjMuMzc3NDU5IDI5LjUyMTQ4NCAyMC4zMTgzNTkgQyAyOC43Njk4OTIgMTguMjQyMjU5IDI3LjAwNzc4OSAxNi45NjU5ODcgMjYuMDMxMjUgMTUuNjc5Njg4IEMgMjUuODQ0MjA2IDE1LjQzMzI4OCAyNS42OTY3MTcgMTUuMTkxOTY2IDI1LjU3MjI2NiAxNC45NDcyNjYgQyAyNi4wMDU0NDQgMTQuNzUxNzY2IDI1LjkyOTE5MiAxMy45ODU4NDEgMjUuMzQxNzk3IDEzLjk5NDE0MSBBIDAuNTAwMDQ5OTQgMC41MDAwNDk5NCAwIDEgMCAyNS4zNTU0NjkgMTIuOTk0MTQxIEMgMjUuNTAzOTU2IDEyLjQwNjk0MSAyNS44MzIxMjQgMTEuNzI0MTI1IDI2LjQ2NDg0NCAxMC44OTA2MjUgQyAyNi40NzI5NDQgMTAuODgwNjI1IDI2LjQ3MTM0NiAxMC44NjkzNzUgMjYuNDc4NTE2IDEwLjg1OTM3NSBBIDAuNTAyMDc3MTMgMC40OTgwMzExNSA2MC4wMDE2MjQgMCAwIDI2LjY0MjU3OCAxMC4wOTE3OTcgQyAyNi4zMDMwOTUgOS42NjU0OTY5IDI1Ljg1Mzk0MSA5LjM2MDU2NTYgMjUuMzU5Mzc1IDkuMTk3MjY1NiBDIDI1LjE0NjI3MyA5LjEyNzI2NTYgMjQuOTI0MTQ4IDkuMDg5ODE4NyAyNC42OTkyMTkgOS4wNzQyMTg4IEMgMjQuMTg1MDcyIDguNjg5NjE4NyAyMy41NzI3OTYgOC41MDIwNDM3IDIyLjk2NDg0NCA4LjUyNzM0MzggeiBNIDguOTY2Nzk2OSA4LjUyOTI5NjkgQyA4LjMxODE5MzYgOC41NTYyOTY5IDcuNjgxMjA1MSA4LjgxODM4MTIgNy4xODU1NDY5IDkuMzAwNzgxMiBDIDcuMTI4MjY1OSA5LjMxMDc4MTIgNy4wNzA0MjQ0IDkuMzEwNDA2MiA3LjAxMzY3MTkgOS4zMTY0MDYyIEMgNi40MzgwNzQgOS40MjA4MDYyIDUuOTAwNDE3MyA5LjcxNzYyODEgNS40ODYzMjgxIDEwLjE3MzgyOCBDIDUuMzQ4OTQ4NSAxMC4yNjU4MjggNS4yNjU2Mjc0IDEwLjQxODg4NCA1LjI2MzY3MTkgMTAuNTgzOTg0IEwgNS4yNjM2NzE5IDEwLjU5Mzc1IEwgNS4yNjM2NzE5IDEwLjYwMzUxNiBDIDUuMjYyMjYxOSAxMC43NTc5MTYgNS4zMzIxNzY5IDEwLjkwNDIgNS40NTMxMjUgMTEgQyA1Ljk2NjU4NDQgMTEuNTQ4MyA2LjMwOTkwOTkgMTIuMjU1OTUzIDYuNDcwNzAzMSAxMy4wMDE5NTMgTCA2LjI5ODgyODEgMTMuMDAxOTUzIEMgNi4yODE5MTIxIDEzLjAwMTA1MyA2LjI2NDk2MjkgMTMuMDAxMDUzIDYuMjQ4MDQ2OSAxMy4wMDE5NTMgQyA1LjYwOTIyNDggMTMuMDQ2OTUzIDUuNjM2OTY3OCAxMy45OTQxNTMgNi4yNzczNDM4IDE0LjAwMTk1MyBDIDYuMjY3NTgzOCAxNC4wMDE2NTMgNi4yNTc4MTA5IDE0LjAwMTY1MyA2LjI0ODA0NjkgMTQuMDAxOTUzIEMgNS42NDkzOTQyIDE0LjAzNDk1MyA1LjYwMzQ1NjQgMTQuOTAwNDk0IDYuMTk1MzEyNSAxNC45OTYwOTQgQyA2LjAyMjU0MyAxNS40MDM5OTQgNS43OTI4MDA2IDE1Ljc1MDkwMyA1LjUwNTg1OTQgMTYuMDk1NzAzIEMgNC44NzkxNjc5IDE2Ljg0ODYwMyAzLjk3ODA0MzQgMTcuNjAwNTEyIDMuMTQ0NTMxMiAxOC44ODI4MTIgQyAxLjQyMjIzNTEgMjEuNTMyNjEyIDEuNTg3NDEzIDI1LjYxMjk0NCA0IDI3Ljk2NDg0NCBDIDUuODA3NzA5OCAyOS44MTk4NDQgOC41OTcxNjYgMzAuNDMxMDY2IDExLjAxNzU3OCAyOS42OTcyNjYgQyAxMC42MDgwOTEgMjkuNDY1NzY2IDEwLjIxNTMxIDI5LjIwMjA1NiA5LjgzOTg0MzggMjguOTEwMTU2IEMgNy45OTQxMDY4IDI5LjE2NjM1NiA2LjAxOTA2NSAyOC42MDkwNzIgNC43MTA5Mzc1IDI3LjI2MzY3MiBMIDQuNzAxMTcxOSAyNy4yNTM5MDYgQyAyLjY5NjI4MzIgMjUuMzA0MzA2IDIuNTM5NTQwMSAyMS42NDc2MzQgMy45ODI0MjE5IDE5LjQyNzczNCBDIDQuNzMyMTE5MiAxOC4yNzQzMzQgNS41NjQ0ODQgMTcuNTg4Mzc1IDYuMjc1MzkwNiAxNi43MzQzNzUgQyA2LjY3NzY2OTggMTYuMjUxMTc1IDcuMDExNDk2NyAxNS42ODcxNTMgNy4yMzgyODEyIDE1LjAwMTk1MyBMIDcuODAwNzgxMiAxNS4wMDE5NTMgQyA4LjA0NDY3MDEgMTQuNjQ1MjUzIDguMjg5NjA3MiAxNC4zMDIyNTMgOC41MzMyMDMxIDE0LjAwMTk1MyBDIDguODMzMzkwNSAxMy42MzE4NTMgOS4xMjI4MzU0IDEzLjMwNDI1MyA5LjQwNDI5NjkgMTMuMDAxOTUzIEwgNy41MDM5MDYyIDEzLjAwMTk1MyBDIDcuMzUzOTMyNSAxMi4xNDI5NTMgNi45OTAxNTY4IDExLjMyNjA3MiA2LjQ0NzI2NTYgMTAuNjM4NjcyIEMgNi45OTM3MTA3IDEwLjIxMTk3MiA3Ljc0MDM3NzggMTAuMTQ2NjY2IDguMzU5Mzc1IDEwLjUwOTc2NiBDIDguOTM0ODY0NCAxMC44NDY4NjYgOS40NDA2MzY1IDkuOTgzNzg0NCA4Ljg2NTIzNDQgOS42NDY0ODQ0IEMgOC44MTAzNDY0IDkuNjE0NDg0NCA4Ljc1MTU1OCA5LjU5NDQwNjMgOC42OTUzMTI1IDkuNTY2NDA2MiBDIDguOTM0OTE1IDkuNTEwNDA2MiA5LjE4MjQwMzUgOS41MTM0MDYyIDkuNDIzODI4MSA5LjU2NjQwNjIgQyA5LjM2MzExMDEgOS45MzY0MDYyIDkuNzE0Njg1NyAxMC4yNDIzMDYgMTAuMDcwMzEyIDEwLjEyODkwNiBDIDEwLjQxMTg2MiAxMC4wMzU5MDYgMTAuNzU4MzggMTAuMDYyNzgxIDExLjA3NjE3MiAxMC4xNzU3ODEgQyAxMS4xMDMyNTIgMTAuMTE3NzgxIDExLjEzMTIzNCAxMC4wNTkzIDExLjE1MjM0NCAxMCBDIDExLjA5MjczNCA5LjgzMDMgMTAuOTcxOTggOS42NzA2NDY5IDEwLjk3MjY1NiA5LjQ5ODA0NjkgQyAxMC45NzMxNDEgOS4zNzQyNDY5IDExLjAzMzkwNiA5LjI1NzA3MTkgMTEuMDkxNzk3IDkuMTM4NjcxOSBDIDEwLjk2NDU0OCA5LjExMDY3MTkgMTAuODM1MDU1IDkuMDk1OTg0NCAxMC43MDUwNzggOS4wODM5ODQ0IEMgMTAuMTkwMDg1IDguNjk2Mzg0NCA5LjU3Njk4MzEgOC41MDc4MDMxIDguOTY2Nzk2OSA4LjUzMzIwMzEgTCA4Ljk2Njc5NjkgOC41MjkyOTY5IHogTSAxMy40Mjk2ODggMTEgTCAxOC4yODUxNTYgMTEgQyAxOC40OTYyNDggMTEuNDM1NjQ5IDE4Ljc0OTYxNCAxMS44NTMwNTUgMTkuMDQ2ODc1IDEyLjI0MjE4OCBDIDIwLjQ4Nzc1NiAxNC4xMjgzODcgMjIuNjIxMjkxIDE1LjY5MTMxNiAyMy40NDkyMTkgMTcuOTc4NTE2IEEgMC41MDAwNSAwLjUwMDA1IDAgMCAwIDIzLjQ1NTA3OCAxNy45OTYwOTQgQyAyNC44NDEzMjYgMjEuNDI0Mjk0IDIzLjQ0MzY3OCAyNS43Nzg5NjMgMjAuMzAyNzM0IDI3LjcyNjU2MiBBIDAuNTAwMDUgMC41MDAwNSAwIDAgMCAyMC4yOTEwMTYgMjcuNzM2MzI4IEMgMTcuMjU5NzI4IDI5LjczODcyOCAxMi44MjU1OSAyOS4yOTk5MTIgMTAuMjc3MzQ0IDI2LjY5NTMxMiBBIDAuNTAwMDUgMC41MDAwNSAwIDAgMCAxMC4yNjc1NzggMjYuNjg1NTQ3IEMgNy41ODI3NjQzIDI0LjA5MDg0NyA3LjM3NzQ5NDcgMTkuMjc3NzI1IDkuMzA2NjQwNiAxNi4zMjgxMjUgQyAxMC4yOTk2NjggMTQuODA5OTI1IDExLjM5OTQ3MiAxMy45MDkxNTMgMTIuMzE2NDA2IDEyLjgxNDQ1MyBDIDEyLjc1OTEgMTIuMjg1OTgyIDEzLjE0NTI1MyAxMS43MDAwMDMgMTMuNDI5Njg4IDExIHogTSAxNC4yMDMxMjUgMTcuODM5ODQ0IEMgMTMuODE4MzIgMTcuODM5ODQ0IDEzLjQzMzQ3NiAxNy45ODU1OTQgMTMuMTQyNTc4IDE4LjI3NzM0NCBDIDEyLjU2MDc4NCAxOC44NjA3NDQgMTIuNTYwNzkxIDE5LjgyMDc5NyAxMy4xNDI1NzggMjAuNDA0Mjk3IEMgMTMuNzI0MzggMjAuOTg3Nzk3IDE0LjY4MTg3NyAyMC45ODc3OTcgMTUuMjYzNjcyIDIwLjQwNDI5NyBDIDE1Ljg0NTQ4NyAxOS44MjA3OTcgMTUuODQ1NDczIDE4Ljg2MDc0NCAxNS4yNjM2NzIgMTguMjc3MzQ0IEMgMTQuOTcyNzY3IDE3Ljk4NTU5NCAxNC41ODc5MyAxNy44Mzk4NDQgMTQuMjAzMTI1IDE3LjgzOTg0NCB6IE0gMTguOTc4NTE2IDE3Ljg0MTc5NyBBIDAuNTAwMDQ5OTEgMC41MDAwNDk5MSAwIDAgMCAxOC42MzQ3NjYgMTcuOTk0MTQxIEwgMTIuNjU4MjAzIDIzLjk4ODI4MSBBIDAuNTAwMDQ5OTEgMC41MDAwNDk5MSAwIDEgMCAxMy4zNjUyMzQgMjQuNjk1MzEyIEwgMTkuMzQzNzUgMTguNjk5MjE5IEEgMC41MDAwNDk5MSAwLjUwMDA0OTkxIDAgMCAwIDE4Ljk3ODUxNiAxNy44NDE3OTcgeiBNIDE0LjIwMzEyNSAxOC44MzU5MzggQyAxNC4zMzAyODUgMTguODM1OTM4IDE0LjQ1NjUzNSAxOC44ODU5MjggMTQuNTU2NjQxIDE4Ljk4NjMyOCBDIDE0Ljc1Njg0NSAxOS4xODcxMjggMTQuNzU2ODQ1IDE5LjQ5NjQ2NiAxNC41NTY2NDEgMTkuNjk3MjY2IEMgMTQuMzU2NDQ0IDE5Ljg5Nzk2NiAxNC4wNDk4MTMgMTkuODk4MDY2IDEzLjg0OTYwOSAxOS42OTcyNjYgQyAxMy42NDk0MTIgMTkuNDk2NDY2IDEzLjY0OTQxMiAxOS4xODcxMjggMTMuODQ5NjA5IDE4Ljk4NjMyOCBDIDEzLjk0OTcxMSAxOC44ODU5MjggMTQuMDc1OTY1IDE4LjgzNTkzOCAxNC4yMDMxMjUgMTguODM1OTM4IHogTSAxNy45OTYwOTQgMjEuODQ1NzAzIEMgMTcuNjExMjkxIDIxLjg0NTcwMyAxNy4yMjY0NDggMjEuOTkxNDUzIDE2LjkzNTU0NyAyMi4yODMyMDMgQyAxNi4zNTQ4NDEgMjIuODY2ODExIDE2LjM1NDEzNSAyMy44MjcxMjMgMTYuOTM1NTQ3IDI0LjQxMDE1NiBDIDE3LjUxNzM0OSAyNC45OTM2NTYgMTguNDc0ODMyIDI0Ljk5MjI1NiAxOS4wNTY2NDEgMjQuNDEwMTU2IEMgMTkuNjM4NDQyIDIzLjgyNjY1NiAxOS42Mzg0NDIgMjIuODY2NzAzIDE5LjA1NjY0MSAyMi4yODMyMDMgQyAxOC43NjU3NCAyMS45OTE0NTMgMTguMzgwODk3IDIxLjg0NTcwMyAxNy45OTYwOTQgMjEuODQ1NzAzIHogTSAxNy45OTYwOTQgMjIuODM5ODQ0IEMgMTguMTIzMjUzIDIyLjgzOTg0NCAxOC4yNTE0NiAyMi44ODk4MzQgMTguMzUxNTYyIDIyLjk5MDIzNCBDIDE4LjU1MTc2NiAyMy4xOTEwMzQgMTguNTUxNzY3IDIzLjUwMDM3MiAxOC4zNTE1NjIgMjMuNzAxMTcyIEMgMTguMTUxMzUyIDIzLjkwMTk3MiAxNy44NDA4MjkgMjMuOTAzMzcyIDE3LjY0MDYyNSAyMy43MDExNzIgQyAxNy40NDA4MjkgMjMuNTAwNzczIDE3LjQ0MzU1MSAyMy4xOTEwNzEgMTcuNjQyNTc4IDIyLjk5MDIzNCBDIDE3Ljc0MjY4IDIyLjg4OTgzNCAxNy44Njg5MzQgMjIuODM5ODQ0IDE3Ljk5NjA5NCAyMi44Mzk4NDQgeiAiIGNvbG9yPSIjMDAwIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC13ZWlnaHQ9IjQwMCIgb3ZlcmZsb3c9InZpc2libGUiIHdoaXRlLXNwYWNlPSJub3JtYWwiIHN0eWxlPSJsaW5lLWhlaWdodDpub3JtYWw7dGV4dC1pbmRlbnQ6MDt0ZXh0LWFsaWduOnN0YXJ0O3RleHQtZGVjb3JhdGlvbi1saW5lOm5vbmU7dGV4dC1kZWNvcmF0aW9uLXN0eWxlOnNvbGlkO3RleHQtZGVjb3JhdGlvbi1jb2xvcjojMDAwO3RleHQtdHJhbnNmb3JtOm5vbmU7YmxvY2stcHJvZ3Jlc3Npb246dGI7aXNvbGF0aW9uOmF1dG87bWl4LWJsZW5kLW1vZGU6bm9ybWFsIj4KCQkJPC9wYXRoPgoJCTwvc3ZnPgoJPC9nPgo8L3N2Zz4K"},EYnv:function(t,e){},EyTm:function(t,e,r){t.exports=r.p+"img/cover5.f116a1a.jpeg"},F4eg:function(t,e,r){t.exports=r.p+"img/cover4.fb93dc2.jpeg"},GRcx:function(t,e){},GTGI:function(t,e,r){t.exports=r.p+"img/ผักและสมุนไพร.d5de866.jpeg"},Hkpp:function(t,e){},IX1A:function(t,e,r){t.exports=r.p+"img/deal4.4bb1400.jpg"},K9np:function(t,e,r){t.exports=r.p+"img/fruit.8a698a2.jpeg"},KeGb:function(t,e){},L9eN:function(t,e,r){t.exports=r.p+"img/fruit-3.619ad35.jpeg"},LXWu:function(t,e,r){var o={"./ข้าวและธัญพืช.jpeg":"xQfL","./ชา กาแฟ และโกโก้.jpeg":"x3G2","./ปศุสัตว์ และประมงค์.jpeg":"UW+1","./ผลิตภัณฑ์แปรรูป.jpeg":"s7bB","./ผักและสมุนไพร.jpeg":"sr7T","./ผักและสมุนไพร2.jpeg":"l25F","./พืชท้องถิ่น.jpeg":"AShl","./หัตถกรรม.jpeg":"SYUG","./ไม้ดอกไม้ประดับ.jpeg":"VWvK","./ไม้ผล.jpeg":"XFLb"};function a(t){return r(i(t))}function i(t){var e=o[t];if(!(e+1))throw new Error("Cannot find module '"+t+"'.");return e}a.keys=function(){return Object.keys(o)},a.resolve=i,t.exports=a,a.id="LXWu"},LaW6:function(t,e,r){t.exports=r.p+"img/vega-card-2.a051bc9.jpeg"},MKGl:function(t,e,r){t.exports=r.p+"img/vega-card.2468c28.jpeg"},Mm10:function(t,e,r){t.exports=r.p+"img/cover2.d91d0aa.jpeg"},N9tS:function(t,e,r){t.exports=r.p+"img/localplant.fc03c0d.jpeg"},NHnr:function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var o=r("7+uW"),a=r("3EgV"),i=r.n(a);r("7zck"),r("Ui3i");o.default.use(i.a);var s=new i.a({theme:{themes:{light:{primary:"#2D3753",secondary:"#2D3753",accent:"#3AE3D6",error:"#f44336",info:"#074d66",success:"#7a904a",warning:"#f78012"}}}}),n={props:{start:Boolean}},l={render:function(){var t=this.$createElement,e=this._self._c||t;return this.start?e("div",{staticClass:"spin"},[this._m(0)]):this._e()},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"ring"},[e("div",{staticClass:"lds-ellipsis"},[e("div"),this._v(" "),e("div"),this._v(" "),e("div"),this._v(" "),e("div")])])}]};var c={name:"App",components:{Spinner:r("VU/8")(n,l,!1,function(t){r("6fdq")},"data-v-c47908ce",null).exports},data:function(){return{spin:{isLoading:!1}}},provide:function(){return{mySpinner:this.spin}}},u={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",{attrs:{id:"app"}},[e("Spinner",{attrs:{start:this.spin.isLoading}}),this._v(" "),e("router-view")],1)},staticRenderFns:[]},d=r("VU/8")(c,u,!1,null,null,null).exports,m=r("FMNc"),p=r.n(m),v=r("/ocq"),g=r("mtWM"),h=r.n(g),f={data:function(){return{dialog:!1,videoId:"i8IvvHJssWE",features:[{img:r("PM2Y"),title:"Design Limpo",text:"Lorem ipsum dolor sit amet consectetur adipisicing elit."},{img:r("93jX"),title:"Dados Seguros",text:"Lorem ipsum dolor sit amet consectetur adipisicing elit."},{img:r("fWV0"),title:"Código Aberto",text:"Lorem ipsum dolor sit amet consectetur adipisicing elit."}],newsProduct:[]}},watch:{dialog:function(t){t||this.pause()}},methods:{productDetail:function(t){this.$router.push({name:"ProductDetail",params:{idProductOfMemberMk:t}})},getNewProduct:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getNewProduct.php").then(function(e){0!==e.data.productMk&&(t.newsProduct=e.data.productMk,console.log("newsProduct",t.newsProduct))}).catch(function(t){console.log(t)})},ready:function(t){this.player=t.target},playing:function(t){},change:function(){this.videoId="another video id"},stop:function(){this.player.stopVideo()},pause:function(){this.player.pauseVideo()}},mounted:function(){this.getNewProduct()}},M={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("section",{attrs:{id:"hero"}},[o("v-parallax",{attrs:{dark:"",src:r("F4eg"),height:"600",jumbotron:""}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{attrs:{cols:"10"}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{attrs:{cols:"12",md:"6",xl:"8"}},[o("h1",{staticClass:"display-2 font-weight-bold mb-4"},[t._v("ของดีบนดอยออนไลน์")]),t._v(" "),o("v-btn",{staticClass:"mt-5",attrs:{rounded:"",outlined:"",large:"",dark:""},on:{click:function(e){return t.$vuetify.goTo("#features")}}},[t._v("\n ดูสินค้าแนะนำ\n "),o("v-icon",{staticClass:"ml-2"},[t._v("mdi-arrow-down")])],1)],1),t._v(" "),o("v-col",{staticClass:"hidden-sm-and-down",attrs:{cols:"12",md:"6",xl:"4"}})],1)],1)],1),t._v(" "),o("div",{staticClass:"svg-border-waves text-white"},[o("v-img",{attrs:{src:r("C4HF")}})],1)],1),t._v(" "),o("div",[o("v-container",[o("v-row",{attrs:{"no-gutters":""}},[o("v-card-title",[o("h3",[t._v("สินค้าใหม่")])]),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("v-row",{attrs:{cols:"12",align:"center",justify:"space-around"}},t._l(t.newsProduct,function(e,r){return o("v-col",{key:r,staticClass:"text-center",staticStyle:{cursor:"pointer"},attrs:{md:"3",sm:"6"},on:{click:function(r){return t.productDetail(e.idProductOfMemberMk)}}},[o("v-hover",{scopedSlots:t._u([{key:"default",fn:function(r){var a=r.hover;return[o("v-card",{staticClass:"card",class:{up:a},attrs:{rounded:"",elevation:a?24:6}},[o("v-img",{staticClass:"white--text align mx-auto",attrs:{rounded:"",src:e.titleImg,height:"200",width:"400"}}),t._v(" "),o("h4",{staticClass:"text-center grey--text text--darken-4"},[t._v(t._s(e.nameArgi))]),t._v(" "),o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n ดูรายละเอียด\n ")])],1)]}}],null,!0)})],1)}),1)],1)],1)],1)],1),t._v(" "),o("v-dialog",{attrs:{"max-width":"640px"},model:{value:t.dialog,callback:function(e){t.dialog=e},expression:"dialog"}},[o("v-card",[o("youtube",{attrs:{"video-id":t.videoId},on:{ready:t.ready,playing:t.playing}})],1)],1),t._v(" "),t._m(0)],1)},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"svg-border-waves"},[e("img",{attrs:{src:r("EQEi")}})])}]};var y=r("VU/8")(f,M,!1,function(t){r("KeGb"),r("R06a"),r("4jaN")},null,null).exports,b={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("section",{attrs:{id:"about"}},[o("v-container",{attrs:{fluid:""}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{attrs:{cols:"10"}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{attrs:{cols:"12",md:"7"}},[o("h1",{staticClass:"font-weight-light display-2"},[t._v("ตรวจสอบราคาของผลผลิต")]),t._v(" "),o("v-btn",{staticClass:"ma-2",attrs:{color:"info",large:""},on:{click:function(e){return t.$router.push({name:"Market"})}}},[t._v("\n สถานการณ์ราคาผลผลิต\n ")]),t._v(" "),o("v-row",[o("v-col",{staticClass:"d-flex align-center",attrs:{cols:"12"}},[o("v-img",{staticClass:"mr-4",attrs:{src:r("EVLe"),"max-width":"60px"}}),t._v(" "),o("p",{staticClass:"text-justify"},[t._v("\n ตรวจสอบราคาสินค้าตลาดไท ประเภท ไม้ผล, เนื้อสัตว์ ปลา &\n อาหารทะเล, ตลาดข้าวสาร, ตลาดพืชไร่, อาหารแห้ง &\n สินค้าเบ็ลเตล็ด, ดอกไม้ ต้นไม้ & สัตว์เลี้ยง\n ")])],1),t._v(" "),o("v-col",{staticClass:"d-flex align-center",attrs:{cols:"12"}},[o("v-img",{staticClass:"mr-4",attrs:{src:r("rOEL"),"max-width":"60px"}}),t._v(" "),o("p",{staticClass:"text-justify"},[t._v("\n ตรวจสอบราคาสินค้าตลาดสี่มุมเมือง ประเภท ผัก, ไม้ผล, พืชไร่,\n ของแห้งของดอง, ของสดของชำ, ดอกไม้สังฆสังภัณฑ์\n ")])],1),t._v(" "),o("v-col",{staticClass:"d-flex align-center",attrs:{cols:"12"}},[o("v-img",{staticClass:"mr-4",attrs:{src:r("qiuY"),"max-width":"60px"}}),t._v(" "),o("p",{staticClass:"text-justify"},[t._v("\n ตรวจสอบราคาสินค้าตลาดศรีเมือง ประเภท ผัก,\n ผักพืชไร่เมืองหนาว, ไม้ผล, ไม้ผลพืชไร่, ไม้ดอกไม้ประดับ\n ")])],1)],1)],1),t._v(" "),o("v-col",{staticClass:"d-none d-md-flex",attrs:{cols:"12",md:"5"}},[o("v-img",{staticClass:"d-block ml-auto mr-auto",attrs:{src:r("+29q"),"max-width":"400px"}})],1)],1)],1)],1)],1)],1)},staticRenderFns:[]};var x=r("VU/8")(null,b,!1,function(t){r("Hkpp")},"data-v-3980b6df",null).exports,I={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("section",{style:{},attrs:{id:"download"}},[o("v-container",{attrs:{fluid:""}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{attrs:{cols:"10"}},[o("v-row",{attrs:{align:"center",justify:"center"}},[o("v-col",{staticClass:"hidden-xs-only",attrs:{sm:"4"}},[o("v-img",{staticClass:"d-block ml-auto mr-auto",attrs:{src:r("026T"),"max-width":"350px"}})],1),t._v(" "),o("v-col",{staticClass:"text-left",attrs:{cols:"12",sm:"8"}},[o("h2",{staticClass:"display-2 mb-2"},[t._v("ค้นหาแหล่งสินค้า")]),t._v(" "),o("h4",{staticClass:"font-weight-light"},[t._v("\n ค้นหาแหล่งสินค้าจากหมวดสินค้าหลัก ข้าวและธัญพืช, ผักและสมุนไพร,\n ไม้ผล, ชา กาแฟ และโกโก้, พืชท้องถิ่น, ไม้ดอกไม้ประดับ, ปศุสัตว์\n และประมงค์, ผลิตภัณฑ์แปรรูป, หัตถกรรม\n ")]),t._v(" "),o("v-btn",{staticClass:"mt-4",attrs:{rounded:"",outlined:"",large:"",color:"black"},on:{click:function(e){return t.$router.push({name:"FindProduct"})}}},[t._v("\n ค้นหาแหล่งสินค้า\n ")])],1)],1)],1)],1)],1)],1)},staticRenderFns:[]};var N=r("VU/8")(null,I,!1,function(t){r("jQqh")},"data-v-7fcca0c0",null).exports,w=r("bOdI"),D=r.n(w),A={data:function(){return{page:1,sugProductPage:1,perPageNews:3,perPage:3,newsPage:1,planos:[{title:"Básico",price:"R$100,00",img:"f1.png"},{title:"Padrão",price:"R$150,00",img:"f2.png"},{title:"Premium",price:"R$250,00",img:"f3.png"}],suggestProduct:[],newsContent:[],contentsData:[]}},computed:{size:function(){var t={md:"large",xl:"x-large"}[this.$vuetify.breakpoint.name];return t?D()({},t,!0):{}},visiblePages:function(){return this.contentsData.slice((this.page-1)*this.perPage,this.page*this.perPage)},visibleNewsPages:function(){return this.newsContent.slice((this.newsPage-1)*this.perPage,this.newsPage*this.perPage)},visibleNewsProductPages:function(){return this.suggestProduct.slice((this.sugProductPage-1)*this.perPageNews,this.sugProductPage*this.perPageNews)}},methods:{getContentFirstPage:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContentFirstPage.php").then(function(e){e.data.content.length>0&&(console.log(e.data),t.contentsData=e.data.content,t.contentsData=t.contentsData.filter(function(t,e){return"แนะนำผลผลิต"===t.contentTypeTitle&&"1"===t.contentPublish}),t.contentsData.map(function(t){return t.contentImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/"+t.contentImg}),t.contentsData.reverse(),console.log("getContentFirstPage",t.contentsData))}).catch(function(t){console.log(t)})},productDetail:function(t){this.$router.push({name:"ProductDetail",params:{idProductOfMemberMk:t}})},getContent:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContent.php").then(function(e){e.data.content.length>0&&(t.newsContent=e.data.content.filter(function(t){return"ข่าวประชาสัมพันธ์"===t.contentTypeTitle&&"1"===t.contentPublish})),t.newsContent.map(function(t,e){t.contentImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/"+t.contentImg}),t.newsContent.reverse(),console.log("newsContent",t.newsContent)}).catch(function(t){console.log(t)})},getSuggestProduct:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getSuggestProduct.php").then(function(e){0!==e.data.suggestProduct&&(t.suggestProduct=e.data.suggestProduct,console.log("suggestProduct",t.suggestProduct))}).catch(function(t){console.log(t)})}},mounted:function(){this.getContent(),this.getSuggestProduct(),this.getContentFirstPage()}},C={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("section",{staticClass:"pb-8",attrs:{id:"features"}},[r("v-container",{attrs:{fluid:""}},[r("v-row",{attrs:{align:"center",justify:"center"}},[r("v-col",{attrs:{cols:"10"}},[r("v-card",{staticStyle:{width:"100%"}},[r("h1",{staticClass:"text-center pt-6 font-weight-bold"},[t._v("สินค้าแนะนำ")]),t._v(" "),r("v-divider",{staticClass:"my-6"}),t._v(" "),r("v-row",{staticClass:"text-center"},t._l(t.visibleNewsProductPages,function(e){return r("v-col",{key:e.idProductOfMemberMk,staticClass:"col-12 col-sm-6 col-md-4"},[r("div",{staticClass:"flex-center"},[r("v-card-text",[r("div",{staticClass:"flex-center"},[r("v-img",{attrs:{src:e.titleImg,height:"250",width:"200"}})],1),t._v(" "),r("div",{staticClass:"font-weight-bold text-uppercase my-2"},[r("h3",[t._v(t._s(e.nameArgi))])]),t._v(" "),r("v-divider",{staticClass:"my-2"}),t._v(" "),r("div",{staticClass:"text-uppercase blue--text"},[t._v(t._s(e.groupName||"-"))]),t._v(" "),r("v-divider",{staticClass:"my-2"}),t._v(" "),r("div",{staticClass:"text-uppercase text-h4 mt-6 blue--text"},[t._v(t._s(e.priceBegin===e.priceEnd?"฿"+e.priceEnd:"฿"+e.priceBegin+" - ฿"+e.priceEnd)+" / "+t._s(e.nameUnit))]),t._v(" "),r("v-btn",{staticClass:"mt-6",attrs:{rounded:"",outlined:"",color:"blue"},on:{click:function(r){return t.productDetail(e.idProductOfMemberMk)}}},[t._v("\n ดูรายละเอียดเพิ่มเติม\n ")])],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?r("v-divider",{staticStyle:{"margin-right":"-2px"},attrs:{vertical:""}}):t._e()],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?t._e():r("v-divider",{staticClass:"mx-4"})],1)}),1)],1)],1)],1),t._v(" "),r("div",{staticClass:"text-center mb-3"},[r("v-pagination",{attrs:{length:Math.ceil(t.suggestProduct.length/t.perPageNews)},model:{value:t.sugProductPage,callback:function(e){t.sugProductPage=e},expression:"sugProductPage"}})],1)],1),t._v(" "),r("v-container",{attrs:{fluid:""}},[r("v-row",{attrs:{align:"center",justify:"center"}},[r("v-col",{attrs:{cols:"10"}},[r("v-card",{staticStyle:{width:"100%"}},[r("h1",{staticClass:"text-center pt-6 font-weight-bold"},[t._v("ข่าวประชาสัมพันธ์")]),t._v(" "),r("v-divider",{staticClass:"my-6"}),t._v(" "),r("v-row",{staticClass:"text-center"},t._l(t.visibleNewsPages,function(e){return r("v-col",{key:e.contentId,staticClass:"col-12 col-sm-6 col-md-4"},[r("div",{staticClass:"flex-center"},[r("v-card-text",[r("div",{staticClass:"flex-center"},[r("v-img",{attrs:{src:e.contentImg,height:"250",width:"200"}})],1),t._v(" "),r("div",{staticClass:"font-weight-bold text-uppercase my-2"},[r("h3",[t._v(t._s(e.contentTitle))])]),t._v(" "),r("v-divider",{staticClass:"my-2"}),t._v(" "),r("v-btn",{staticClass:"mt-6",attrs:{rounded:"",outlined:"",color:"blue",to:{name:"Post",params:{id:e.contentId}}}},[t._v("\n ดูรายละเอียดเพิ่มเติม\n ")])],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?r("v-divider",{staticStyle:{"margin-right":"-2px"},attrs:{vertical:""}}):t._e()],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?t._e():r("v-divider",{staticClass:"mx-4"})],1)}),1)],1)],1)],1),t._v(" "),r("div",{staticClass:"text-center mb-3"},[r("v-pagination",{attrs:{length:Math.ceil(t.newsContent.length/t.perPage)},model:{value:t.newsPage,callback:function(e){t.newsPage=e},expression:"newsPage"}})],1)],1),t._v(" "),r("v-container",{attrs:{fluid:""}},[r("v-row",{attrs:{align:"center",justify:"center"}},[r("v-col",{attrs:{cols:"10"}},[r("v-card",{staticStyle:{width:"100%"}},[r("h1",{staticClass:"text-center pt-6 font-weight-bold"},[t._v("แนะนำผลผลิต")]),t._v(" "),r("v-divider",{staticClass:"my-6"}),t._v(" "),r("v-row",{staticClass:"text-center"},t._l(t.visiblePages,function(e){return r("v-col",{key:e.contentId,staticClass:"col-12 col-sm-6 col-md-4"},[r("div",{staticClass:"flex-center"},[r("v-card-text",[r("div",{staticClass:"flex-center"},[r("v-img",{attrs:{src:e.contentImg,height:"250",width:"200"}})],1),t._v(" "),r("div",{staticClass:"font-weight-bold text-uppercase my-2"},[r("h3",[t._v(t._s(e.contentTitle))])]),t._v(" "),r("v-divider",{staticClass:"my-2"}),t._v(" "),r("v-btn",{staticClass:"mt-6",attrs:{rounded:"",outlined:"",color:"blue",to:{name:"Post",params:{id:e.contentId}}}},[t._v("\n ดูรายละเอียดเพิ่มเติม\n ")])],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?r("v-divider",{staticStyle:{"margin-right":"-2px"},attrs:{vertical:""}}):t._e()],1),t._v(" "),t.$vuetify.breakpoint.smAndUp?t._e():r("v-divider",{staticClass:"mx-4"})],1)}),1)],1)],1)],1),t._v(" "),r("div",{staticClass:"text-center mb-3"},[r("v-pagination",{attrs:{length:Math.ceil(t.contentsData.length/t.perPage)},model:{value:t.newsPage,callback:function(e){t.newsPage=e},expression:"newsPage"}})],1)],1),t._v(" "),r("div",{staticClass:"svg-border-rounded text-light"},[r("svg",{attrs:{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 1440 320",preserveAspectRatio:"none",fill:"currentColor"}},[r("path",{attrs:{d:"M0,64L80,90.7C160,117,320,171,480,181.3C640,192,800,160,960,138.7C1120,117,1280,107,1360,101.3L1440,96L1440,320L1360,320C1280,320,1120,320,960,320C800,320,640,320,480,320C320,320,160,320,80,320L0,320Z"}})])])],1)},staticRenderFns:[]};var _={render:function(){var t=this.$createElement,e=this._self._c||t;return e("section",{staticClass:"pb-8",attrs:{id:"contact"}},[e("v-container",{attrs:{fluid:""}}),this._v(" "),e("div",{staticClass:"svg-border-waves text-white"},[e("v-img",{attrs:{src:r("9+Ew")}})],1)],1)},staticRenderFns:[]};var T={components:{home:y,about:x,shopping:N,suggest:r("VU/8")(A,C,!1,function(t){r("UPOJ")},"data-v-0c8c7955",null).exports,news:r("VU/8")({data:function(){return{}},methods:{submit:function(){}}},_,!1,function(t){r("3jyg")},"data-v-e6ac09c0",null).exports},data:function(){return{newsPage:1,page:1,sugProductPage:1,perPageNews:8,perPage:3,slideShowImg:[],contentsData:[],newsContent:[],suggestProduct:[],items:[{title:"Click Me"},{title:"Click Me"},{title:"Click Me"},{title:"Click Me 2"}],argiItems:[],activeBtn:1,colors:["indigo","warning","pink darken-2","red lighten-1","deep-purple accent-4"],slides:["First","Second","Third","Fourth","Fifth"]}},computed:{visiblePages:function(){return this.contentsData.slice((this.page-1)*this.perPage,this.page*this.perPage)},visibleNewsPages:function(){return this.newsContent.slice((this.newsPage-1)*this.perPage,this.newsPage*this.perPage)},visibleNewsProductPages:function(){return this.suggestProduct.slice((this.sugProductPage-1)*this.perPageNews,this.sugProductPage*this.perPageNews)}},methods:{productDetail:function(t){this.$router.push({name:"ProductDetail",params:{idProductOfMemberMk:t}})},getContentFirstPage:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContentFirstPage.php").then(function(e){e.data.content.length>0&&(console.log(e.data),t.contentsData=e.data.content,t.contentsData=t.contentsData.filter(function(t,e){return"แนะนำผลผลิต"===t.contentTypeTitle&&"1"===t.contentPublish}),t.contentsData.map(function(t){return t.contentImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/"+t.contentImg}),t.contentsData.reverse(),console.log("getContentFirstPage",t.contentsData))}).catch(function(t){console.log(t)})},getContent:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContent.php").then(function(e){e.data.content.length>0&&(t.newsContent=e.data.content.filter(function(t){return"ข่าวประชาสัมพันธ์"===t.contentTypeTitle&&"1"===t.contentPublish})),t.newsContent.map(function(t,e){t.contentImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/"+t.contentImg}),t.newsContent.reverse(),console.log("newsContent",t.newsContent)}).catch(function(t){console.log(t)})},getTypeOfArgi:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllTypeOfArgiTD.php").then(function(e){e.data.typeOfArgi.length>0&&(t.argiItems=e.data.typeOfArgi,t.argiItems=t.argiItems.filter(function(t,e){return null!==t.nameTypeOfArgi_MK}),console.log("getAllTypeOfArgiTD",t.argiItems))}).catch(function(t){console.log(t)})},getSuggestProduct:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getSuggestProduct.php").then(function(e){0!==e.data.suggestProduct&&(t.suggestProduct=e.data.suggestProduct,console.log("suggestProduct",t.suggestProduct))}).catch(function(t){console.log(t)})},getSlideShowImg:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/slideshow/getAllSlideShow.php").then(function(e){t.slideShowImg=e.data.slideShowImg}).catch(function(t){console.log(t)})}},mounted:function(){this.getContent(),this.getContentFirstPage(),this.getTypeOfArgi(),this.getSuggestProduct(),this.getSlideShowImg(),window.scroll(0,0)}},k={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",[e("home"),this._v(" "),e("about"),this._v(" "),e("shopping"),this._v(" "),e("suggest"),this._v(" "),e("news")],1)},staticRenderFns:[]};var j=r("VU/8")(T,k,!1,function(t){r("2tzC")},null,null).exports,O=r("Xxa5"),L=r.n(O),F=r("exGp"),z=r.n(F),S=r("Gu7T"),E=r.n(S),U=h.a.create({baseURL:"https://farmtd.hrdi.or.th/farmdd/admin/api/",headers:{"Content-Type":"application/json"}}),P={name:"ProductList",props:{productMk:Array},data:function(){return{page:1,perPage:12,pageChoose:0}},computed:{totalPage:function(){return this.pageChoose=Math.ceil(this.productMk.length/this.perPage),Math.ceil(this.productMk.length/this.perPage)},visibleContentPages:function(){return this.page>this.pageChoose&&(this.page=1),window.scroll(0,0),this.productMk.slice((this.page-1)*this.perPage,this.page*this.perPage)}},methods:{changePage:function(t){this.pageChoose=t,console.log("event",t)},productDetail:function(t){this.$router.push({name:"ProductDetail",params:{idProductOfMemberMk:t}})}}},Q={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",[r("div",{staticClass:"row text-center"},t._l(t.visibleContentPages,function(e,o){return r("div",{key:o,staticClass:"col-md-4 col-sm-6 col-xs-12"},[r("v-hover",{scopedSlots:t._u([{key:"default",fn:function(o){var a=o.hover;return[r("v-card",{staticClass:"mx-auto",attrs:{color:"grey lighten-4","max-width":"600",height:"100%"}},[r("v-img",{staticClass:"white--text align-end",attrs:{"aspect-ratio":16/9,height:"200px",src:e.titleImg,"lazy-src":e.titleImg},scopedSlots:t._u([{key:"placeholder",fn:function(){return[r("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[r("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!0)},[t._v(" "),r("v-expand-transition",[a?r("div",{staticClass:"\n d-flex\n transition-fast-in-fast-out\n white\n darken-4\n v-card--reveal\n display-3\n ",staticStyle:{height:"100%"}},[a?r("v-btn",{attrs:{color:"primary",outlined:""},on:{click:function(r){return t.productDetail(e.idProductOfMemberMk)}}},[t._v("รายละเอียด")]):t._e()],1):t._e()])],1),t._v(" "),r("v-card-text",{staticClass:"pa-0"},[r("v-row",{attrs:{cols:"12",justify:"center"}},[r("v-card-title",{staticClass:"indigo--text text--darken-4 font-weight-black"},[t._v("\n "+t._s(e.nameArgi)+"\n ")])],1),t._v(" "),r("v-card-subtitle",{staticClass:"font-weight-bold pt-0"},[r("h4",[t._v(t._s(e.groupName))])]),t._v(" "),r("v-row",{attrs:{justify:"center"}},[r("v-chip",{staticClass:"body-2 green white--text mb-1"},[r("h5",[t._v(t._s(e.nameTypeOfArgiMk))])])],1),t._v(" "),r("v-row",{attrs:{justify:"center"}},[r("span",{staticClass:"body-1 font-weight-black pa-1"},[t._v(t._s(e.priceBegin===e.priceEnd?e.priceEnd+"฿":e.priceBegin+"฿ - "+e.priceEnd+"฿")+"\n / "+t._s(e.nameUnit))])])],1)],1)]}}],null,!0)})],1)}),0),t._v(" "),r("v-row",{staticClass:"mt-3",attrs:{align:"center",justify:"center"}},[r("v-pagination",{attrs:{length:t.totalPage},on:{input:function(e){return t.changePage(e)}},model:{value:t.page,callback:function(e){t.page=e},expression:"page"}})],1)],1)},staticRenderFns:[]};var B={components:{ProductList:r("VU/8")(P,Q,!1,function(t){r("3rT5")},null,null).exports},inject:["mySpinner"],data:function(){return{isLoading:!1,productName:"",productMk:[],cloneProductMk:[],typeOfStand:[],countType:{first:0,second:0,third:0,fourth:0,fifth:0},standSelected:[],typeItemsSelected:0,range:[0,1e3],select:"ตัวกรองการค้นหา",options:["ตัวกรองการค้นหา","ราคา: ต่ำ ถึง สูง","ราคา: สูง ถึง ต่ำ"],typeItems:[],page:1,perPage:12,sellerMember:[],breadcrums:[{text:"แสดงสินค้าจากประเภทเกษตรกร",disabled:!1,href:"#"},{text:"ทั้งหมด",disabled:!1,href:"#"}],month:[],min:0,max:1e3}},computed:{filterProduct:function(){return this.farmerFilter(this.filterRange(this.filterMonth(this.filterByStand(this.filterName(this.sortByPrice(this.productMk))))))},checkProductSize:function(){if(0===this.productMk.length&&!1===this.mySpinner.isLoading)return!0},filterProductsByRange:function(){var t=this;return this.productMk.filter(function(e){return e.priceBegin>0&&(e.priceEnd,t.range),e})}},methods:{pageEmit:function(t){this.page=t,console.log("pageEmit",this.page)},filterName:function(t){var e=this;return console.log(this.page),t.filter(function(t){return t.nameArgi.match(e.productName)})},filterByStand:function(t){var e=this;return t.filter(function(t){return t.idTypeOfStand.includes(e.standSelected)})},filterMonth:function(t){var e=this;return t.filter(function(t){return t.monthOfProduct.split(",").map(function(t){return+t}).sort(function(t,e){return t-e}).toString().includes(e.month.map(function(t){return+t}).sort(function(t,e){return t-e}).toString())})},filterRange:function(t){var e=this;return t.filter(function(t){return parseInt(t.priceBegin)>=e.min&&parseInt(t.priceEnd)<=e.max?t:""})},changeFarmer:function(t){this.page=1,this.productName="",this.month=[],this.standSelected=[],this.min=0,this.max=1e3},farmerFilter:function(t){var e=this;return t.filter(function(t){return 0!==parseInt(e.typeItemsSelected)&&void 0!==e.typeItemsSelected?parseInt(t.idTypeOfSellerMk)===e.typeItemsSelected:e.productMk=[].concat(E()(e.cloneProductMk))})},sortByPrice:function(t){return t.sort("ราคา: ต่ำ ถึง สูง"===this.select||"ตัวกรองการค้นหา"===this.select?function(t,e){return parseFloat(t.priceEnd)-parseFloat(e.priceEnd)}:function(t,e){return parseFloat(e.priceEnd)-parseFloat(t.priceEnd)})},getAllProduct:function(){var t=this;U.get("product/getAllProduct.php").then(function(e){0!==e.data.productMk&&(e.data.productMk.reverse(),t.productMk=e.data.productMk,t.cloneProductMk=e.data.productMk,console.log("productMk",t.productMk.map(function(t){return t.idAgri})),t.sellerMember.map(function(e,r){switch(e.idTypeOfSeller_MK){case"1":t.countType.first++;break;case"2":t.countType.second++;break;case"3":t.countType.third++;break;case"4":t.countType.fourth++;break;case"5":t.countType.fifth++}}),t.mySpinner.isLoading=!t.mySpinner.isLoading,console.log("countType",t.countType))}).catch(function(t){console.log(t)})},getTypeOfSeller:function(){var t=this;U.get("member/getTypeOfSeller.php").then(function(e){0!==e.data.sellerType&&(t.typeItems=e.data.sellerType,t.typeItems.unshift({idTypeOfSellerMk:"0",nameTypeOfSeller:"แสดงทุกประเภท"}),console.log("typeItems",t.typeItems))}).catch(function(t){console.log(t)})},getAllSellerMember:function(){var t=this;U.get("member/getAllSellerMember.php").then(function(e){t.sellerMember=e.data.sellerUser,console.log("SellerUser",t.sellerMember)}).then(function(){t.getAllProduct()}).catch(function(t){console.log(t)})},getTypeOfStand:function(){var t=this;U.get("product/getTypeOfStand.php").then(function(e){t.typeOfStand=e.data.typeOfStand,t.typeOfStand.shift(),console.log("typeOfStand",t.typeOfStand)}).catch(function(t){console.log(t)})}},mounted:function(){var t=this;return z()(L.a.mark(function e(){return L.a.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return t.mySpinner.isLoading=!t.mySpinner.isLoading,e.next=3,t.getTypeOfStand();case 3:return e.next=5,t.getTypeOfSeller();case 5:return e.next=7,t.getAllSellerMember();case 7:case"end":return e.stop()}},e,t)}))()}},Y={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",[r("v-container",[r("div",{staticClass:"row"},[r("div",{staticClass:"col-md-3 col-sm-3 col-xs-12"},[r("v-card",{attrs:{outlined:""}},[r("v-card-title",{staticClass:"green darken-1 white--text"},[t._v("ประเภทเกษตรกร")]),t._v(" "),r("v-divider"),t._v(" "),void 0,t._v(" "),r("v-list",[r("v-list-item-group",{attrs:{color:"green"},model:{value:t.typeItemsSelected,callback:function(e){t.typeItemsSelected=e},expression:"typeItemsSelected"}},t._l(t.typeItems,function(e,o){return r("v-list-item",{key:o,attrs:{value:e.idTypeOfSellerMk},on:{click:function(e){return t.changeFarmer(t.typeItemsSelected)}}},[r("v-list-item-content",[r("v-list-item-title",{staticClass:"pa-3"},[r("v-row",{attrs:{cols:"12"}},[t._v("\n "+t._s(e.nameTypeOfSeller)),r("v-spacer"),t._v("\n "+t._s("เกษตรกรรายเดี่ยว"===e.nameTypeOfSeller?"("+t.countType.first+")":"วิสาหกิจชุมชน"===e.nameTypeOfSeller?"("+t.countType.second+")":"สหกรณ์"===e.nameTypeOfSeller?"("+t.countType.third+")":"กลุ่มเกษตรกร"===e.nameTypeOfSeller?"("+t.countType.fourth+")":"กลุ่มไม่เป็นทางการ"===e.nameTypeOfSeller?"("+t.countType.fifth+")":"")+"\n ")],1)],1)],1)],1)}),1)],1),t._v(" "),r("v-divider"),t._v(" "),r("v-card-title",{staticClass:"green darken-1 white--text"},[t._v("เงื่อนไขการค้นหา")]),t._v(" "),r("v-card-title",[t._v("ช่วงราคา")]),t._v(" "),r("v-row",{staticClass:"pa-2",attrs:{dense:""}},[r("v-col",{attrs:{cols:"12",sm:"5"}},[r("v-text-field",{attrs:{label:"ขั้นต่ำ",outlined:"",dense:""},model:{value:t.min,callback:function(e){t.min=e},expression:"min"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"2"}},[r("p",{staticClass:"pt-2 text-center"},[t._v("ถึง")])]),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"5"}},[r("v-text-field",{attrs:{label:"สูงสุด",outlined:"",dense:""},model:{value:t.max,callback:function(e){t.max=e},expression:"max"}})],1)],1),t._v(" "),r("v-divider"),t._v(" "),r("v-card-title",{staticClass:"pb-0"},[t._v("ค้นหาสินค้าในเดือน")]),t._v(" "),r("v-container",{staticClass:"pt-0 mx-auto",attrs:{fluid:""}},[r("v-row",[r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ม.ค.",value:"1","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"เม.ย.",value:"4","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ก.พ.",value:"2","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"พ.ค.",value:"5","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"มี.ค.",value:"3","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"มิ.ย.",value:"6","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ก.ค.",value:"7","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ต.ค.",value:"10","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ส.ค.",value:"8","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"พ.ย.",value:"11","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ก.ย.",value:"9","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ธ.ค.",value:"12","hide-details":""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1)],1)],1),t._v(" "),r("v-card-title",{staticClass:"pb-0"},[t._v("ค้นหาจากมาตรฐาน")]),t._v(" "),r("v-container",{staticClass:"pt-0 pa-4"},t._l(t.typeOfStand,function(e){return r("v-row",{key:e.idTypeOfStand,staticClass:"mx-auto",attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:e.nameTypeOfStand,value:e.nameTypeOfStand,"hide-details":""},model:{value:t.standSelected,callback:function(e){t.standSelected=e},expression:"standSelected"}})],1)}),1)],2)],1),t._v(" "),r("div",{staticClass:"col-md-9 col-sm-9 col-xs-12"},[r("v-row",{attrs:{dense:""}},[r("v-col",{staticClass:"pl-6 pt-6",attrs:{cols:"12",sm:"8"}}),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4"}},[r("v-text-field",{attrs:{label:"ค้นหาสินค้าจากชื่อ",dense:""},scopedSlots:t._u([{key:"append",fn:function(){return[r("v-btn",{staticClass:"ma-0",attrs:{depressed:"",tile:"",color:"primary"}},[r("v-icon",[t._v("mdi-magnify")])],1)]},proxy:!0}]),model:{value:t.productName,callback:function(e){t.productName=e},expression:"productName"}}),t._v(" "),r("v-select",{staticClass:"pa-0",staticStyle:{"margin-bottom":"-20px"},attrs:{items:t.options,outlined:"",dense:""},model:{value:t.select,callback:function(e){t.select=e},expression:"select"}})],1)],1),t._v(" "),r("v-breadcrumbs",{staticClass:"pb-1 body-1 font-weight-bold",attrs:{items:t.breadcrums}}),t._v(" "),r("v-divider"),t._v(" "),t.isLoading?r("v-row",{staticClass:"pa-5",attrs:{justify:"center"}},[r("h1",[t._v("ไม่พบข้อมูล...")])]):t._e(),t._v(" "),t.isLoading?r("v-row",{staticClass:"pa-5",attrs:{justify:"center"}},[r("v-progress-linear",{attrs:{color:"primary",indeterminate:"",height:"25"}})],1):t._e(),t._v(" "),r("ProductList",{attrs:{productMk:t.filterProduct}})],1)])])],1)},staticRenderFns:[]};var R=r("VU/8")(B,Y,!1,function(t){r("g2dD")},null,null).exports,Z={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",[o("v-container",[o("div",{staticClass:"row"},[o("div",{staticClass:"col-md-5 col-sm-5 col-xs-12"},[o("v-carousel",[o("v-carousel-item",{attrs:{src:r("fRiH")}}),t._v(" "),o("v-carousel-item",{attrs:{src:r("BkM8")}}),t._v(" "),o("v-carousel-item",{attrs:{src:r("uAlE")}}),t._v(" "),o("v-carousel-item",{attrs:{src:r("NSMX")}})],1)],1),t._v(" "),o("div",{staticClass:"col-md-7 col-sm-7 col-xs-12"},[o("v-breadcrumbs",{staticClass:"pb-0",attrs:{items:t.breadcrums}}),t._v(" "),o("div",{staticClass:"pl-6"},[o("p",{staticClass:"display-1 mb-0"},[t._v("Modern Black T-Shirt")]),t._v(" "),o("v-card-actions",{staticClass:"pa-0"},[o("p",{staticClass:"headline font-weight-light pt-3"},[t._v("$65.00 "),o("del",{staticClass:"subtitle-1 font-weight-thin"},[t._v("$80.00")])]),t._v(" "),o("v-spacer"),t._v(" "),o("v-rating",{attrs:{"background-color":"warning lighten-3",color:"warning",dense:""},model:{value:t.rating,callback:function(e){t.rating=e},expression:"rating"}}),t._v(" "),o("span",{staticClass:"body-2\tfont-weight-thin"},[t._v(" 25 REVIEWS")])],1),t._v(" "),o("p",{staticClass:"subtitle-1 font-weight-thin"},[t._v("\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Tincidunt arcu non sodales neque sodales ut etiam. Lectus arcu bibendum at varius vel pharetra. Morbi tristique senectus et netus et malesuada.\n ")]),t._v(" "),o("p",{staticClass:"title"},[t._v("SIZE")]),t._v(" "),o("v-radio-group",{attrs:{row:""},model:{value:t.row,callback:function(e){t.row=e},expression:"row"}},[o("v-radio",{attrs:{label:"XS",value:"XS"}}),t._v(" "),o("v-radio",{attrs:{label:"S",value:"s"}}),t._v(" "),o("v-radio",{attrs:{label:"M",value:"m"}}),t._v(" "),o("v-radio",{attrs:{label:"L",value:"l"}}),t._v(" "),o("v-radio",{attrs:{label:"XL",value:"xl"}})],1),t._v(" "),o("p",{staticClass:"title"},[t._v("ITEMS")]),t._v(" "),o("v-text-field",{staticStyle:{width:"100px"},attrs:{outlined:"",value:1,dense:""}}),t._v(" "),o("v-btn",{staticClass:"primary white--text",attrs:{outlined:"",tile:"",dense:""}},[o("v-icon",[t._v("mdi-cart")]),t._v(" ADD TO CART")],1),t._v(" "),o("v-btn",{staticClass:"ml-4",attrs:{outlined:"",tile:""}},[t._v("ADD TO WISHLIST")])],1)],1)]),t._v(" "),o("div",{staticClass:"row"},[o("div",{staticClass:"col-sm-12 col-xs-12 col-md-12"},[o("v-tabs",[o("v-tab",[t._v("Description")]),t._v(" "),o("v-tab",[t._v("Materials")]),t._v(" "),o("v-tab",[t._v("REVIEWS")]),t._v(" "),o("v-tab-item",[o("p",{staticClass:"pt-10 subtitle-1 font-weight-thin"},[t._v("\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et\n dolore magna aliqua. Ultricies mi eget mauris pharetra et. Vel pretium lectus quam id leo in vitae turpis\n massa. Orci dapibus ultrices in iaculis nunc. At auctor urna nunc id cursus metus. Integer feugiat\n scelerisque varius morbi enim nunc. Aliquam sem et tortor consequat id porta nibh venenatis cras.\n Pellentesque pulvinar pellentesque habitant morbi tristique senectus et netus. Malesuada nunc vel risus\n commodo viverra maecenas. Neque volutpat ac tincidunt vitae semper quis.\n ")])]),t._v(" "),o("v-tab-item",[o("p",{staticClass:"pt-10 subtitle-1 font-weight-thin"},[t._v("\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et\n dolore magna aliqua. Ultricies mi eget mauris pharetra et. Vel pretium lectus quam id leo in vitae turpis\n massa. Orci dapibus ultrices in iaculis nunc. At auctor urna nunc id cursus metus. Integer feugiat\n scelerisque varius morbi enim nunc. Aliquam sem et tortor consequat id porta nibh venenatis cras.\n Pellentesque pulvinar pellentesque habitant morbi tristique senectus et netus. Malesuada nunc vel risus\n commodo viverra maecenas. Neque volutpat ac tincidunt vitae semper quis.\n ")])]),t._v(" "),o("v-tab-item",[o("v-list",{attrs:{"three-line":"true",avatar:"true"}},[o("v-list-item-group",{attrs:{color:"primary"},model:{value:t.item,callback:function(e){t.item=e},expression:"item"}},t._l(t.items,function(e,r){return o("v-list-item",{key:r,attrs:{inactive:"true"}},[o("v-list-item-avatar",[o("v-img",{attrs:{src:e.avatar}})],1),t._v(" "),o("v-list-item-content",[o("v-list-item-title",{domProps:{innerHTML:t._s(e.title)}}),o("v-rating",{attrs:{"background-color":"warning lighten-3",color:"warning",dense:""},model:{value:t.rating,callback:function(e){t.rating=e},expression:"rating"}}),t._v(" "),o("v-list-item-subtitle",{domProps:{innerHTML:t._s(e.subtitle)}})],1)],1)}),1)],1)],1)],1),t._v(" "),o("v-card-text",{staticClass:"pa-0 pt-4",attrs:{tile:"",outlined:""}},[o("p",{staticClass:"subtitle-1 font-weight-light pt-3 text-center"},[t._v("YOU MIGHT ALSO LIKE")]),t._v(" "),o("v-divider"),t._v(" "),o("div",{staticClass:"row text-center"},[o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("DM+Z")}},[o("v-card-title",[t._v("Bags & Purses ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 60% + Extra 10%")]),t._v(" "),o("div",[t._v("Baggit, Zara, Fossil")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1),t._v(" "),o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("uMNc")}},[o("v-card-title",[t._v("T-Shirt ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 50%")]),t._v(" "),o("div",[t._v("Zara, Selected, Celio")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1),t._v(" "),o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("kx0P")}},[o("v-card-title",[t._v("Jeans ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 60% + Extra 10%")]),t._v(" "),o("div",[t._v("Jack & Jones, Levis")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1),t._v(" "),o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("jYSa")}},[o("v-card-title",[t._v("Shirts ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 60% + Extra 10%")]),t._v(" "),o("div",[t._v("Nike, Adidas, Puma")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1),t._v(" "),o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("IX1A")}},[o("v-card-title",[t._v("Shoes ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 60% + Extra 10%")]),t._v(" "),o("div",[t._v("Nike, Adidas, Puma")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1),t._v(" "),o("div",{staticClass:"col-md-2 col-sm-4 col-xs-12 text-center"},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(e){var a=e.hover;return[o("v-card",{attrs:{elevation:a?16:2}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"200px",src:r("pqEl")}},[o("v-card-title",[t._v("Jackets ")])],1),t._v(" "),o("v-card-text",{staticClass:"text--primary text-center"},[o("div",[t._v("Upto 60% + Extra 10%")]),t._v(" "),o("div",[t._v("Nike, Adidas, Puma")])]),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{outlined:"",color:"info"}},[t._v("\n Explore\n ")])],1)],1)]}}])})],1)])],1)],1)])]),t._v(" "),o("v-card",{staticClass:"accent"},[o("v-container",[o("v-row",{attrs:{"no-gutters":""}},[o("v-col",{staticClass:"col-12 col-md-4 col-sm-12"},[o("v-row",[o("v-col",{staticClass:"col-12 col-sm-3 pr-4 hidden-sm-only",attrs:{align:"right"}},[o("v-icon",{staticClass:"display-2"},[t._v("mdi-truck")])],1),t._v(" "),o("v-col",{staticClass:"col-12 col-sm-9 pr-4"},[o("h3",{staticClass:"font-weight-light"},[t._v("FREE SHIPPING & RETURN")]),t._v(" "),o("p",{staticClass:"font-weight-thin"},[t._v("Free Shipping over $300")])])],1)],1),t._v(" "),o("v-col",{staticClass:"col-12 col-md-4 col-sm-12"},[o("v-row",[o("v-col",{staticClass:"col-12 col-sm-3 pr-4",attrs:{align:"right"}},[o("v-icon",{staticClass:"display-2"},[t._v("mdi-cash-usd")])],1),t._v(" "),o("v-col",{staticClass:"col-12 col-sm-9 pr-4"},[o("h3",{staticClass:"font-weight-light"},[t._v("MONEY BACK GUARANTEE")]),t._v(" "),o("p",{staticClass:"font-weight-thin"},[t._v("30 Days Money Back Guarantee")])])],1)],1),t._v(" "),o("v-col",{staticClass:"col-12 col-md-4 col-sm-12"},[o("v-row",[o("v-col",{staticClass:"col-12 col-sm-3 pr-4",attrs:{align:"right"}},[o("v-icon",{staticClass:"display-2"},[t._v("mdi-headset")])],1),t._v(" "),o("v-col",{staticClass:"col-12 col-sm-9 pr-4"},[o("h3",{staticClass:"font-weight-light"},[t._v("020-800-456-747")]),t._v(" "),o("p",{staticClass:"font-weight-thin"},[t._v("24/7 Available Support")])])],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},G=r("VU/8")({data:function(){return{rating:4.5,breadcrums:[{text:"Home",disabled:!1,href:"breadcrumbs_home"},{text:"Clothing",disabled:!1,href:"breadcrumbs_clothing"},{text:"T-Shirts",disabled:!0,href:"breadcrumbs_shirts"}],item:5,items:[{avatar:"https://cdn.vuetifyjs.com/images/lists/1.jpg",title:"Lorem ipsum dolor?",subtitle:"<span class='text--primary'>Ali Connors</span> &mdash; Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nisl tincidunt eget nullam non. Tincidunt arcu non sodales neque sodales ut etiam. Lectus arcu bibendum at varius vel pharetra. Morbi tristique senectus et netus et malesuada.\n\n"},{avatar:"https://cdn.vuetifyjs.com/images/lists/2.jpg",title:'Lorem ipsum dolor <span class="grey--text text--lighten-1">4</span>',subtitle:"<span class='text--primary'>to Alex, Scott, Jennifer</span> &mdash; Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore"},{avatar:"https://cdn.vuetifyjs.com/images/lists/3.jpg",title:"Lorem ipsum dolor",subtitle:"<span class='text--primary'>Sandra Adams</span> &mdash; Lorem ipsum dolor sit amet, consectetur adipiscing elit"},{avatar:"https://cdn.vuetifyjs.com/images/lists/4.jpg",title:"Lorem ipsum dolor",subtitle:""},{avatar:"https://cdn.vuetifyjs.com/images/lists/5.jpg",title:"Lorem ipsum dolor",subtitle:"<span class='text--primary'>Britta Holt</span> &mdash; Lorem ipsum dolor sit amet, consectetur adipiscing elit"}]}}},Z,!1,null,null,null).exports,J={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",[o("v-container",[o("p",{staticClass:"display-3 font-weight-light\ttext-center pa-4"},[t._v("Read About Fashion")]),t._v(" "),o("div",{staticClass:"row"},[o("div",{staticClass:"col-md-4 col-sm-4 col-xs-12"},[o("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400",outlined:"",tile:"",href:"/post"}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"400px",src:r("BkM8")}},[o("v-card-title",[t._v("Top 10 Fashion of the Week")])],1),t._v(" "),o("v-card-subtitle",{staticClass:"pb-0"},[t._v("Lorem ipsum")]),t._v(" "),o("v-card-text",{staticClass:"text--primary"},[o("div",[t._v("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nibh venenatis cras sed felis eget velit aliquet sagittis id. Enim praesent elementum facilisis leo vel fringilla est ullamcorper.\n\n ")])]),t._v(" "),o("v-card-actions",[o("v-btn",{attrs:{color:"orange",text:""}},[t._v("\n Read More\n ")])],1)],1)],1),t._v(" "),o("div",{staticClass:"col-md-4 col-sm-3 col-xs-12"},[o("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400",outlined:"",tile:"",href:"/post"}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"400px",src:r("uAlE")}},[o("v-card-title",[t._v("Best brands for fashion")])],1),t._v(" "),o("v-card-subtitle",{staticClass:"pb-0"},[t._v("Lorem ipsum")]),t._v(" "),o("v-card-text",{staticClass:"text--primary"},[o("div",[t._v("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nibh venenatis cras sed felis eget velit aliquet sagittis id. Enim praesent elementum facilisis leo vel fringilla est ullamcorper.\n\n ")])]),t._v(" "),o("v-card-actions",[o("v-btn",{attrs:{color:"orange",text:""}},[t._v("\n Read More\n ")])],1)],1)],1),t._v(" "),o("div",{staticClass:"col-md-4 col-sm-3 col-xs-12"},[o("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400",outlined:"",tile:"",href:"/post"}},[o("v-img",{staticClass:"white--text align-end",attrs:{height:"400px",src:r("fRiH")}},[o("v-card-title",[t._v("Fashion Tips & Tricks")])],1),t._v(" "),o("v-card-subtitle",{staticClass:"pb-0"},[t._v("Lorem ipsum")]),t._v(" "),o("v-card-text",{staticClass:"text--primary"},[o("div",[t._v("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nibh venenatis cras sed felis eget velit aliquet sagittis id. Enim praesent elementum facilisis leo vel fringilla est ullamcorper.\n\n ")])]),t._v(" "),o("v-card-actions",[o("v-btn",{attrs:{color:"orange",text:""}},[t._v("\n Read More\n ")])],1)],1)],1)])])],1)},staticRenderFns:[]},V=r("VU/8")(null,J,!1,null,null,null).exports,$={data:function(){return{paramsId:0,error:{isError:!1,errorMsg:""},uri:"",marketName:"",marketType:"",showCard:{showVega:!1,showMeat:!1},isTaiMarket:!1,taiFunction:!1,isCornerMarket:!1,isSriMarket:!1,cornerFunction:!1,isLoad:!1,product:[],search:"",vegaSelect:["ตลาดผลไม้ฤดูกาล","ตลาดผลไม้รวม","ตลาดส้ม","ตลาดแตงโม","ลานผัก","ตลาดผลไม้นานาชาติ และตลาดคอนเทนเนอร์","ลานผัก (โซนผักปลีก)","ตลาดผัก"],meatSelect:["ตลาดสด","ตลาดปลาน้ำจืด","ตลาดอาหารทะเล"],riceSelect:["ตลาดข้าวสาร"],fieldSelect:["ตลาดพืชไร่"],dryFoodSelect:["ตลาดอาหารแห้ง","ตลาดสินค้าเบ็ดเตล็ด"],plantSelect:["ตลาดต้นไม้","ตลาดดอกไม้","ตลาดสัตว์เลี้ยง"],headerProps:{sortByText:"Custom sort by"},headers:[]}},methods:{getColor:function(t){return"-"===t.charAt(0)?"red":"0.00"===t.substring(0,4)?"grey":"green"},checkDif:function(t){return"-"===t.charAt(0)?"mdi-arrow-down":"0.00"===t.substring(0,4)?"mdi-minus":"mdi-arrow-up"},getProductData:function(t,e){var r=this;this.product=[],this.headers=[{text:"ชื่อสินค้า",value:"post_title"},{text:"ราคา / กิโลกรัม",value:"range_value"},{text:"ราคาเพิ่ม / ลด",value:"priceDif"}],this.uri=t,this.marketName=e,""!==this.uri&&(this.isTaiMarket=!1,this.showCard.showVega=!1,this.isCornerMarket=!1,this.taiFunction=!0,this.cornerFunction=!1,h.a.get(this.uri).then(function(t){r.product=t.data.posts,t.data.posts.map(function(t,e){r.product[e].post_title=t.post_title.substring(10),r.product[e].range_value=r.product[e].acf.recent_price.low_price.concat(" - ").concat(r.product[e].acf.recent_price.high_price.concat(" บาท")),r.product[e].priceDif=(100*t.acf.recent_price.difference).toFixed(2).concat(" %")}),r.isLoad=!1,console.log(r.product)}).catch(function(t){t&&(r.isLoad=!1)}))},showTable:function(){switch(this.isLoad=!0,this.marketName){case"ตลาดผลไม้ฤดูกาล":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7324&per_page=500","ตลาดไท > ตลาดผลไม้ฤดูกาล");break;case"ตลาดผลไม้รวม":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7326&per_page=500","ตลาดไท > ตลาดผลไม้รวม");break;case"ตลาดส้ม":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7331&per_page=500","ตลาดไท > ตลาดส้ม");break;case"ตลาดแตงโม":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7334&per_page=500","ตลาดไท > ตลาดแตงโม");break;case"ลานผัก":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=4951&per_page=500","ตลาดไท > ลานผัก");break;case"ตลาดผลไม้นานาชาติ และตลาดคอนเทนเนอร์":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7318&per_page=500","ตลาดไท > ตลาดผลไม้นานาชาติ และตลาดคอนเทนเนอร์");break;case"ลานผัก (โซนผักปลีก)":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7306&per_page=500","ลานผัก (โซนผักปลีก)");break;case"ตลาดผัก":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7310&per_page=500","ตลาดผัก");break;case"ตลาดสด":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10132&per_page=500","ตลาดสด");break;case"ตลาดปลาน้ำจืด":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10133&per_page=500","ตลาดปลาน้ำจืด");break;case"ตลาดอาหารทะเล":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10134&per_page=500","ตลาดอาหารทะเล");break;case"ตลาดข้าวสาร":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7353&per_page=500","ตลาดข้าวสาร");break;case"ตลาดข้าวสาร":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7324&per_page=500","ตลาดข้าวสาร");break;case"ตลาดพืชไร่":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7364&per_page=500","ตลาดพืชไร่");break;case"ตลาดอาหารแห้ง":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10135&per_page=500","ตลาดอาหารแห้ง");break;case"ตลาดสินค้าเบ็ดเตล็ด":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10136&per_page=500","ตลาดสินค้าเบ็ดเตล็ด");break;case"ตลาดต้นไม้":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7375&per_page=500","ตลาดต้นไม้");break;case"ตลาดดอกไม้":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=7398&per_page=500","ตลาดดอกไม้");break;case"ตลาดสัตว์เลี้ยง":this.getProductData("https://cms.talaadthai.com/wp-json/tlt/v1/products_from_subcat_id?id=10130&per_page=500","ตลาดสัตว์เลี้ยง")}},showCornerTable:function(t){if(this.cornerFunction=!0,this.isLoad=!0,this.isCornerMarket=!1,this.taiFunction=!1,this.product=[],this.headers=[{text:"รูปสินค้า",value:"img"},{text:"ราคาสินค้าวันที่",value:"price_date"},{text:"ชื่อสินค้า",value:"post_title"},{text:"ใหญ่",value:"priceL"},{text:"กลาง",value:"priceM"},{text:"เล็ก",value:"priceS"}],"ผัก"===t){this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[1],sortOrder:"PriceL desc",toRow:500})}else if("ผลไม้"===t){this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[2],sortOrder:"PriceL desc",toRow:500})}else if("พืชไร่"===t){this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[3],sortOrder:"PriceL desc",toRow:500})}else if("ของแห้งของดอง"===t){this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[4],sortOrder:"PriceL desc",toRow:500})}else if("ของสดของชำ"===t){this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[5],sortOrder:"PriceL desc",toRow:500})}else{if("ดอกไม้สังฆภัณฑ์"!==t)return;this.getCornerData({fromRow:1,selectedMarket:[],selectedProductGroup:[6],sortOrder:"PriceL desc",toRow:500})}},getCornerData:function(t){var e=this;h.a.post("https://www.simummuangmarket.com/api/product/frontend/search",t).then(function(t){e.product=t.data.data,t.data.data.map(function(t,r){e.product[r].post_title=t.ProductNameTH,null!=t.PriceL?e.product[r].priceL=t.PriceL+"".concat(" Bath / "+t.UnitNameTH):e.product[r].priceL="-",null!=t.PriceM?e.product[r].priceM=t.PriceM+"".concat(" Bath / "+t.UnitNameTH):e.product[r].priceM="-",null!=t.PriceS?e.product[r].priceS=t.PriceS+"".concat(" Bath / "+t.UnitNameTH):e.product[r].priceS="-",null!=t.PriceDate?e.product[r].price_date=t.PriceDate.replace(/T.*/,"").split("-").reverse().join("/"):e.product[r].price_date="-",null===t.LargeImageUrl?e.product[r].img="https://www.simummuangmarket.com/img/img-default.png":e.product[r].img="https://www.simummuangmarket.com"+t.LargeImageUrl}),console.log(e.product),e.isLoad=!1}).catch(function(t){t&&(e.isLoad=!1)})},showSriTable:function(t){var e=this;switch(this.cornerFunction=!1,this.isLoad=!0,this.isSriMarket=!1,this.taiFunction=!1,this.product=[],this.headers=[{text:"ชื่อสินค้า",value:"post_title"},{text:"ราคาสินค้า",value:"price"},{text:"หน่วยสินค้า",value:"priceDesc"}],t){case"ผัก":this.paramsId=1;break;case"ผักพืชไร่เมืองหนาว":this.paramsId=2;break;case"ผลไม้":this.paramsId=3;break;case"ผลไม้พืชไร่":this.paramsId=4;break;case"ไม้ดอกไม้ประดับ":this.paramsId=5}h.a.get("https://hrdi-api.herokuapp.com/vegatable/"+this.paramsId).then(function(t){console.log(t.data),e.product=t.data,e.product=[].concat(E()(t.data.filter(function(t){return!t.includes("00")&&"กิโลกรัม"!==t&&"กำ"!==t&&"หัว"!==t&&"ลูก"!==t&&"ร้อยละ"!==t&&"แพ็ค"!==t&&"หวี"!==t&&"กล่อง"!==t}))).map(function(t,e){return{post_title:t}}),t.data.filter(function(t){return t.includes("00")}).map(function(t,r){e.product[r].price=t}),t.data.filter(function(t){return!t.includes("00")&&"กิโลกรัม"===t||"กำ"===t||"หัว"===t||"ลูก"===t||"ร้อยละ"===t||"ร้อยละ"===t||"แพ็ค"===t||"หวี"===t||"กล่อง"===t}).map(function(t,r){e.product[r].priceDesc=t}),e.isLoad=!1})},toggleCard:function(t){switch(t){case"isTaiMarket":this.isTaiMarket=!this.isTaiMarket,this.isCornerMarket=!1,this.isSriMarket=!1;break;case"isCornerMarket":this.isTaiMarket=!1,this.isCornerMarket=!this.isCornerMarket,this.isSriMarket=!1;break;case"isSriMarket":this.isTaiMarket=!1,this.isCornerMarket=!1,this.isSriMarket=!this.isSriMarket}}},created:function(){}},H={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",[o("v-container",{staticClass:"mt-0"},[o("h1",{staticClass:"font-weight-light text-center pa-4"},[t._v("สถานการณ์ราคาผลผลิต")]),t._v(" "),o("v-row",{attrs:{align:"center",cols:"12"}},[o("v-btn",{staticClass:"ml-1",on:{click:function(e){return t.toggleCard("isTaiMarket")}}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-store")]),t._v(" ตลาดไท\n ")],1),t._v(" "),o("v-btn",{staticClass:"ml-1",on:{click:function(e){return t.toggleCard("isCornerMarket")}}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-store")]),t._v("ตลาดสี่มุมเมือง\n ")],1),t._v(" "),o("v-btn",{staticClass:"ml-1",on:{click:function(e){return t.toggleCard("isSriMarket")}}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-store")]),t._v("ตลาดศรีเมือง\n ")],1)],1),t._v(" "),t.isTaiMarket?o("v-row",{staticClass:"pa-5 col-md-12",attrs:{align:"center",justify:"center"}},[o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("W4HE"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผักและผลไม้\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.vegaSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("PQwa"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n เนื้อสัตว์ ปลา & อาหารทะเล\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.meatSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("qG1N"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ตลาดข้าวสาร\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.riceSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("4uZN"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ตลาดพืชไร่\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.fieldSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("9D+C"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n อาหารแห้ง & สินค้าเบ็ดเตล็ด\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.dryFoodSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("1e2O"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ดอกไม้ ต้นไม้ & สัตว์เลี้ยง\n ")]),t._v(" "),o("v-col",[o("v-select",{attrs:{items:t.plantSelect,label:"เลือกสินค้า"},on:{change:function(e){return t.showTable()}},model:{value:t.marketName,callback:function(e){t.marketName=e},expression:"marketName"}})],1)],1)],1):t._e(),t._v(" "),t.isCornerMarket?o("v-row",{staticClass:"pa-5 col-md-12",attrs:{align:"center",justify:"center"}},[o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("LaW6"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผัก\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("ผัก")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("K9np"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผลไม้\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("ผลไม้")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("wsk5"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n พืชไร่\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("พืชไร่")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("DPYr"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ของแห้งของดอง\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("ของแห้งของดอง")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("xgfO"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ของสดของชำ\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("ของสดของชำ")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("5HHC"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ดอกไม้สังฆภัณฑ์\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showCornerTable("ดอกไม้สังฆภัณฑ์")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1)],1):t._e(),t._v(" "),t.isSriMarket?o("v-row",{staticClass:"pa-5 col-md-12",attrs:{justify:"center"}},[o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("j/kf"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผัก\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showSriTable("ผัก")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("s3/3"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผักพืชไร่เมืองหนาว\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showSriTable("ผักพืชไร่เมืองหนาว")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("s2z8"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผลไม้\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showSriTable("ผลไม้")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"ml-2 mt-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("L9eN"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ผลไม้พืชไร่\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showSriTable("ผลไม้พืชไร่")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1),t._v(" "),o("v-card",{staticClass:"mt-2 ml-2",attrs:{"max-width":"300"}},[o("v-img",{attrs:{src:r("9iO8"),height:"200px"}}),t._v(" "),o("v-card-title",[t._v("\n ไม้ดอกไม้ประดับ\n ")]),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.showSriTable("ผลไม้พืชไร่")}}},[t._v("\n เลือกสินค้า\n ")])],1)],1)],1):t._e(),t._v(" "),o("div",{staticClass:"row"},[o("div",{staticClass:"col-lg-12 mb-5"},[o("v-card",[o("v-card-title",[o("v-spacer"),t._v(" "),o("p"),t._v(" "),o("v-text-field",{attrs:{"append-icon":"mdi-magnify",label:"Search","single-line":"","hide-details":""},model:{value:t.search,callback:function(e){t.search=e},expression:"search"}})],1),t._v(" "),o("v-data-table",{attrs:{headers:t.headers,search:t.search,items:t.product,loading:t.isLoad,"loading-text":"กำลังค้นหา..."},scopedSlots:t._u([t.cornerFunction?{key:"item.img",fn:function(e){var r=e.item;return[o("div",{staticClass:"p-2"},[r.img?o("v-img",{attrs:{src:r.img,alt:r.post_title,width:"250px",height:"250px"}}):t._e()],1)]}}:null,t.taiFunction?{key:"item.priceDif",fn:function(e){var r=e.item;return[o("v-chip",{attrs:{color:t.getColor(r.priceDif),dark:""}},[o("v-icon",{staticClass:"mr-1",attrs:{"aria-hidden":"false"}},[t._v("\n "+t._s(t.checkDif(r.priceDif))+"\n ")]),t._v("\n "+t._s(r.priceDif)+"\n ")],1)]}}:null,{key:"no-data",fn:function(){return[t._v("\n ไม่พบข้อมูล\n ")]},proxy:!0}],null,!0)})],1)],1)])],1)],1)},staticRenderFns:[]};var q=r("VU/8")($,H,!1,function(t){r("6pYU")},null,null).exports,W={data:function(){return{editorConfig:{},contentData:[]}},methods:{toThaiDateString:function(t){var e=t.getFullYear()+543,r=["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม.","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"][t.getMonth()];return t.getDate()+" "+r+" "+e+" "+t.getHours().toString().padStart(2,"0")+":"+t.getMinutes().toString().padStart(2,"0")+":"+t.getSeconds().toString().padStart(2,"0")+" น."}},mounted:function(){var t=this,e=this.$route.params.id;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContentById.php?contentId="+e).then(function(e){if(console.log(e),e.data.content.length>0){var r=new Date(e.data.content[0].contentTime);t.contentData=e.data.content[0],t.contentData.contentTime=t.toThaiDateString(r),console.log(t.contentData)}}).catch(function(t){console.log(t)})},created:function(){}},X={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{attrs:{fluid:"","fill-height":""}},[r("v-layout",{attrs:{"align-start":"","justify-center":""}},[r("v-flex",{staticClass:"pa-5",attrs:{sm12:"",md9:"",lg12:""}},[r("v-row",{attrs:{cols:"12"}},[r("v-col",{attrs:{cols:"12"}},[r("p",{staticClass:"display-1 font-weight-light\ttext-center pa-4 pb-0"},[t._v(t._s(t.contentData.contentTitle))]),t._v(" "),r("p",{staticClass:"overline text-center"},[t._v("By "),r("b",[t._v(t._s(t.contentData.contentWriter))]),t._v(" | "+t._s(t.contentData.contentTime))]),t._v(" "),r("v-container",{attrs:{fluid:""}},[r("v-row",{attrs:{justify:"center"}},[r("v-col",{staticClass:"content",attrs:{md:"12",lg:"12"},domProps:{innerHTML:t._s(t.contentData.contentBody)}})],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]};var K=r("VU/8")(W,X,!1,function(t){r("va8I")},null,null).exports,tt={data:function(){return{month:[],baseUrl:"https://farmtd.hrdi.or.th/farmdd/admin/api/",productMk:[],productImgMk:[],sellerUser:[],area:{},areaText:""}},methods:{getProductImg:function(t){var e=this,r=new FormData;r.append("idProductOfMemberMk",t),h.a.post(this.baseUrl+"/product/getProductImg.php",r).then(function(t){console.log(t),0!==t.data.productImgMk&&(e.productImgMk=t.data.productImgMk,e.productImgMk.shift(),console.log("productImgMk",e.productImgMk))}).catch(function(t){console.log(t)})},getProductDetail:function(t){var e=this,r=new FormData;r.append("idProductOfMemberMk",t),h.a.post(this.baseUrl+"/product/getProductDetail.php",r).then(function(t){0!==t.data.productMk&&(e.productMk=t.data.productMk[0],e.month=e.productMk.monthOfProduct.split(","),console.log(e.month),console.log("productMk",e.productMk))}).then(function(){e.getSellerInfo()}).catch(function(t){console.log(t)})},getSellerInfo:function(){var t=this;console.log(this.productMk.idSellerMember);var e=new FormData;e.append("idSellerMember",this.productMk.idSellerMember),h.a.post(this.baseUrl+"/product/postFindSellerMk.php",e).then(function(e){0!==e.data.sellerUser&&(t.sellerUser=e.data.sellerUser[0],console.log("sellerUser",t.sellerUser))}).then(function(){t.getAllArea()}).catch(function(t){console.log(t)})},getAllArea:function(){var t=this;h.a.get(this.baseUrl+"/getAllArea.php").then(function(e){if(0!==e.data.area){var r=e.data.area.filter(function(e,r){return e.idArea===t.sellerUser.vLinkAreaDetailId_MK});t.area={idArea:r[0].areaName,areaName:r[0].areaName},console.log("area",t.area)}}).catch(function(t){console.log(t)})}},mounted:function(){var t=localStorage.idProductOfMemberMk;this.getProductDetail(t),this.getProductImg(t)},created:function(){}},et={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("v-container",[o("p",{staticClass:"display-1 indigo--text text--darken-4 font-weight-bold text-center pt-4 mb-0"},[t._v("\n "+t._s(t.productMk.nameArgi)+"\n ")]),t._v(" "),o("p",{staticClass:"overline text-center"},[t._v("หมวด "+t._s(t.productMk.nameTypeOfArgiMk))]),t._v(" "),o("v-divider"),t._v(" "),o("v-container",{staticClass:"pt-0",attrs:{fluid:""}},[o("v-row",[o("v-col",{staticClass:"d-flex child-flex pb-0",attrs:{cols:"6"}},[o("v-img",{attrs:{"max-height":"550","max-width":"550",src:t.productMk.titleImg,"lazy-src":t.productMk.imgTitle},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}])})],1),t._v(" "),o("v-col",{attrs:{cols:"6"}},[o("v-row",[o("h2",{staticClass:"indigo--text text--darken-4 mx-auto"},[t._v("\n เดือนที่มีสินค้า\n ")])]),t._v(" "),o("v-row",{attrs:{justify:"center"}},[o("v-card",{attrs:{flat:""}},[o("v-card-text",[o("v-container",{staticClass:"pa-0",attrs:{fluid:""}},[o("v-row",{attrs:{cols:"12",justify:"center"}},[o("v-col",[o("h3",[t._v("มค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"1","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("กพ")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"2","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("มีค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"3","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("เมย")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"4","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("พค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"5","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("มิ.ย.")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"6","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1)],1),t._v(" "),o("v-row",{attrs:{cols:"12",justify:"center"}},[o("v-col",[o("h3",[t._v("กค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"7","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("สค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"8","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("กย")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"9","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("ตค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"10","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("พย")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"11","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1),t._v(" "),o("v-col",[o("h3",[t._v("ธค")]),t._v(" "),o("v-checkbox",{attrs:{color:"green accent-4",value:"12","hide-details":"",readonly:""},model:{value:t.month,callback:function(e){t.month=e},expression:"month"}})],1)],1)],1)],1)],1)],1),t._v(" "),o("v-divider"),t._v(" "),o("v-row",{staticClass:"mt-2"},[o("h2",{staticClass:"indigo--text text--darken-4 mx-auto"},[t._v("\n รายละเอียดสินค้า\n ")])]),t._v(" "),o("v-row",{staticClass:"pa-5 body-1",attrs:{cols:"12"}},[o("v-col",{attrs:{cols:"12"}},[o("p",{staticClass:"body-1 font-weight-medium"},[t._v("\n "+t._s(t.productMk.detailOfProduct)+"\n ")])]),t._v(" "),o("v-row",{staticClass:"pa-2",attrs:{cols:"12"}},[o("v-col",[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("สายพันธ์ ")]),t._v(" "),o("h3",{staticClass:"green--text text--accent-4"},[t._v("\n "+t._s(t.productMk.speciesName||"-")+"\n ")])]),t._v(" "),o("v-col",[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("มาตรฐาน ")]),t._v(" "),o("h3",{staticClass:"green--text text--accent-4"},[t._v("\n "+t._s(t.productMk.codeGrade||"-")+"\n ")])])],1),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("ราคา ")]),t._v(" "),o("h2",{staticClass:"green--text text--accent-4"},[t._v("\n "+t._s(t.productMk.priceBegin===t.productMk.priceEnd?"฿"+t.productMk.priceEnd:"฿"+t.productMk.priceBegin+" - ฿"+t.productMk.priceEnd)+"\n / "+t._s(t.productMk.nameUnit)+"\n ")])])],1),t._v(" "),o("v-divider")],1),t._v(" "),o("v-row",t._l(t.productImgMk,function(e,r){return o("v-col",{key:r,staticClass:"d-flex child-flex",attrs:{cols:"1"}},[o("v-img",{attrs:{src:e.imgTitle,"lazy-src":e.imgTitle},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!0)})],1)}),1),t._v(" "),o("v-row",{staticClass:"mt-2"},[o("h2",{staticClass:"indigo--text text--darken-4 mx-auto"},[t._v("จัดจำหน่ายโดย")]),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold"},[t._v("ประเภทองค์กร :")]),t._v("\n "+t._s(t.sellerUser.nameTypeOfSeller)+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold"},[t._v("ชื่อองค์กร :")]),t._v("\n "+t._s(t.sellerUser.groupName||"-")+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold"},[t._v("ชื่อ :")]),t._v("\n "+t._s(t.sellerUser.firstName+" "+t.sellerUser.lastName)+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold"},[t._v("ที่อยู่ :")]),t._v("\n บ้านเลขที่ "+t._s(t.sellerUser.address||"-")+" หมู่\n "+t._s(t.sellerUser.moo||"-")+" ตำบล\n "+t._s(t.sellerUser.tamName||"-")+" จังหวัด\n "+t._s(t.sellerUser.provName||"-")+" "+t._s(t.sellerUser.postCode||" ")+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold"},[t._v("พื้นที่โครงการ :")]),t._v("\n "+t._s(t.area.areaName)+"\n ")]),t._v(" "),o("v-row",{attrs:{cols:"12"}},[o("v-col",[o("v-img",{attrs:{width:"24",src:r("AIOO")}}),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[t._v("\n "+t._s(t.sellerUser.facebookName||"-")+"\n ")])],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},rt=r("VU/8")(tt,et,!1,null,null,null).exports,ot={data:function(){return{page:1,perPage:6,contentType:[],contentData:[],productContent:[],selection:0}},computed:{visibleContentPages:function(){return this.contentData.slice((this.page-1)*this.perPage,this.page*this.perPage)}},methods:{toThaiDateString:function(t){var e=t.getFullYear()+543,r=["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม.","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"][t.getMonth()];return t.getDate()+" "+r+" "+e+" "+t.getHours().toString().padStart(2,"0")+":"+t.getMinutes().toString().padStart(2,"0")+":"+t.getSeconds().toString().padStart(2,"0")+" น."}},mounted:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/content/getContent.php").then(function(e){if(e.data.content.length>0){var r=e.data.content.filter(function(t){return"0"!==t.contentPublish});t.contentData=r,r.map(function(e,r){t.contentData[r].contentImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/"+e.contentImg}),t.contentData=t.contentData.filter(function(t){return"แนะนำผลผลิต"===t.contentTypeTitle}),t.contentData.reverse(),console.log(t.contentData)}}).catch(function(t){console.log(t)})}},at={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",[r("v-container",[r("p",{staticClass:"display-1 font-weight-light\ttext-center"}),t._v(" "),r("div",{staticClass:"row"},t._l(t.visibleContentPages,function(e){return r("div",{key:e.id,staticClass:"col-md-4 col-sm-4 col-md-4"},[r("v-hover",{scopedSlots:t._u([{key:"default",fn:function(o){var a=o.hover;return[r("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400",height:"100%",elevation:a?16:2}},[r("v-img",{staticClass:"white--text align-end",attrs:{height:"300px","max-width":"400",src:e.contentImg},on:{click:function(r){return t.$router.push({name:"Post",params:{id:e.contentId,page:1}})}}}),t._v(" "),r("v-card-title",{staticClass:"font-weight-bold"},[t._v("\n "+t._s(e.contentTitle)+"\n ")]),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(r){return t.$router.push({name:"Post",params:{id:e.contentId,page:1}})}}},[t._v("\n ดูเพิ่มเติม\n ")])],1)],1)]}}],null,!0)})],1)}),0),t._v(" "),r("div",{staticClass:"text-center mb-5"},[r("v-pagination",{attrs:{length:Math.ceil(t.contentData.length/t.perPage)},model:{value:t.page,callback:function(e){t.page=e},expression:"page"}})],1)])],1)},staticRenderFns:[]},it=r("VU/8")(ot,at,!1,null,null,null).exports,st={data:function(){return{fab:null,color:"",flat:null,drawer:!1,group:null,isMobile:!1,loginItem:{},items:[{title:"หน้าแรก",icon:"mdi-home"},{title:"ค้นหาเกษตรกร & สินค้า",icon:"mdi-account-supervisor"},{title:"ค้นหาแหล่งสินค้า",icon:"mdi-shopping"},{title:"สถานการณ์ราคาผลผลิต",icon:"mdi-store"},{title:"แนะนำผลผลิต",icon:"mdi-fruit-cherries"},{title:"เกี่ยวกับเรา",icon:"mdi-information"}],activeBtn:1}},computed:{},watch:{group:function(){this.drawer=!1},fab:function(t){t?(this.color="secondary",this.flat=!1):(this.color="transparent",this.flat=!0)}},methods:{onScroll:function(t){if("undefined"!=typeof window){var e=window.pageYOffset||t.target.scrollTop||0;this.fab=e>60}},toTop:function(){this.$vuetify.goTo(0)},showDrawer:function(){this.drawer=!this.drawer,window.scrollTo(0,0)},goToPage:function(t){switch(t){case"หน้าแรก":this.$router.push({name:"Home"});break;case"ค้นหาเกษตรกร & สินค้า":this.$router.push({name:"Shop"});break;case"ค้นหาแหล่งสินค้า":this.$router.push({name:"FindProduct"});break;case"สถานการณ์ราคาผลผลิต":this.$router.push({name:"Market"});break;case"แนะนำผลผลิต":this.$router.push({name:"Content",params:{id:"1"}});break;case"เกี่ยวกับเรา":this.$router.push({name:"AboutUs"})}console.log(t)},logout:function(){localStorage.clear(),this.$router.push({name:"Login"})}},mounted:function(){this.loginItem=localStorage,console.log("storageData",this.loginItem)}},nt={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-app",{attrs:{id:"inspire"}},[r("v-sheet",{staticClass:"overflow-hidden"},[r("v-navigation-drawer",{attrs:{app:"",absolute:"",temporary:""},model:{value:t.drawer,callback:function(e){t.drawer=e},expression:"drawer"}},[t.loginItem.user?r("v-list-item",[r("v-list-item-content",[r("router-link",{staticClass:"mr-3 mb-1",staticStyle:{"text-decoration":"none"},attrs:{to:"/userprofile"}},[r("v-list-item-title",[t._v(t._s(t.loginItem.firstName+" "+t.loginItem.lastName))])],1)],1)],1):t._e(),t._v(" "),r("v-divider"),t._v(" "),r("v-list",{attrs:{dense:""}},t._l(t.items,function(e){return r("v-list-item",{key:e.title,attrs:{link:""}},[r("v-list-item-icon",[r("v-icon",[t._v(t._s(e.icon))])],1),t._v(" "),r("v-list-item-content",[r("v-list-item-title",{on:{click:function(r){return t.goToPage(e.title)}}},[t._v(t._s(e.title))])],1)],1)}),1)],1)],1),t._v(" "),r("v-app-bar",{attrs:{"clipped-left":t.$vuetify.breakpoint.lgAndUp,fixed:"",app:"",color:"info",dark:""}},[t.$vuetify.breakpoint.xsOnly?r("v-app-bar-nav-icon",{on:{click:function(e){return e.stopPropagation(),t.showDrawer(e)}}}):t._e(),t._v(" "),r("v-toolbar-title",{staticStyle:{width:"350px"}},[r("router-link",{staticClass:"white--text",staticStyle:{"text-decoration":"none"},attrs:{to:"/"}},[t._v("\n ของดีบนดอย Online\n ")])],1),t._v(" "),r("v-spacer"),t._v(" "),!t.loginItem.user&&t.$vuetify.breakpoint.smAndUp?r("div",[r("v-icon",{staticClass:"mr-1"},[t._v("mdi-account-circle")]),t._v(" "),r("router-link",{staticStyle:{"text-decoration":"none"},attrs:{to:"/login"}},[r("span",{staticClass:"white--text"},[t._v("เข้าสู่ระบบ")])])],1):t._e(),t._v(" "),!t.loginItem.user&&t.$vuetify.breakpoint.xsOnly?r("v-row",{attrs:{col:"12"}},[r("router-link",{staticStyle:{"text-decoration":"none"},attrs:{to:"/login"}},[r("v-icon",{staticClass:"ml-2 mt-1"},[t._v("mdi-account-circle")]),t._v(" "),r("span",{staticClass:"white--text"},[t._v("Login")])],1)],1):t._e(),t._v(" "),t.loginItem.user&&t.$vuetify.breakpoint.smAndUp?r("v-row",{attrs:{align:"end"}},[r("v-spacer"),t._v(" "),r("v-icon",{staticClass:"mr-1 mb-1"},[t._v("mdi-account-circle")]),t._v(" "),r("router-link",{staticClass:"mr-3 mb-1",staticStyle:{"text-decoration":"none"},attrs:{to:"/userprofile"}},[r("span",{staticClass:"white--text"},[t._v("\n "+t._s(t.loginItem.firstName+" "+t.loginItem.lastName))])]),t._v(" "),r("v-btn",{staticClass:"mx-2",attrs:{fab:"",dark:"",small:"",color:"error"},on:{click:t.logout}},[r("v-icon",[t._v("mdi-logout")])],1)],1):t._e(),t._v(" "),t.loginItem.user&&t.$vuetify.breakpoint.xsOnly?r("v-row",{attrs:{align:"end"}},[r("v-spacer"),t._v(" "),r("v-row",{staticClass:"mr-5",attrs:{cols:"12"}},[r("v-col",{attrs:{cols:"6"}},[r("v-btn",{attrs:{fab:"",dark:"",small:"",color:"warning"},on:{click:function(e){return t.$router.push("/userprofile")}}},[r("v-icon",[t._v("mdi-account")])],1)],1),t._v(" "),r("v-col",{attrs:{cols:"6"}},[r("v-btn",{attrs:{fab:"",dark:"",small:"",color:"error"},on:{click:t.logout}},[r("v-icon",[t._v("mdi-logout")])],1)],1)],1)],1):t._e()],1),t._v(" "),r("v-content",[t.$vuetify.breakpoint.smAndUp?r("v-bottom-navigation",{attrs:{value:t.activeBtn,color:"primary",horizontal:"","active-class":"active"}},[r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/"}},[t._v("หน้าแรก")]),t._v(" "),r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/shop"}},[r("span",[t._v("ค้นหาเกษตรกร & สินค้า")])]),t._v(" "),r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/findproduct"}},[r("span",[t._v("ค้นหาแหล่งสินค้า")])]),t._v(" "),r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/market"}},[r("span",[t._v("สถานการณ์ราคาผลผลิต")])]),t._v(" "),r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/content/1"}},[r("span",[t._v("แนะนำผลผลิต")])]),t._v(" "),r("v-btn",{staticClass:"body-2 font-weight-bold",attrs:{to:"/aboutus"}},[r("span",[t._v("เกี่ยวกับเรา")])])],1):t._e()],1),t._v(" "),r("router-view"),t._v(" "),r("v-footer",{attrs:{padless:!0}},[r("v-card",{staticClass:"info white--text text-center",attrs:{flat:"",tile:"",width:"100%"}},[r("v-card-text",[r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-home")])],1),t._v(" "),r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/shop",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-account-supervisor")])],1),t._v(" "),r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/findproduct",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-shopping")])],1),t._v(" "),r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/market",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-store")])],1),t._v(" "),r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/content/1",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-fruit-cherries")])],1),t._v(" "),r("v-btn",{staticClass:"mx-4 white--text",attrs:{to:"/aboutus",icon:""}},[r("v-icon",{attrs:{size:"24px"}},[t._v("mdi-information")])],1)],1),t._v(" "),r("v-card-text",{staticClass:"white--text pt-0"}),t._v(" "),r("v-divider"),t._v(" "),r("v-card-text",{staticClass:"white--text"},[t._v("\n "+t._s((new Date).getFullYear())+" — "),r("strong",[t._v("ของดีบนดอย Online")]),t._v(" "),r("v-row",{staticClass:"mt-2",attrs:{justify:"center"}},[r("v-icon",{staticClass:"white--text mr-1 mb-1 ml-2",attrs:{size:"24px"}},[t._v("mdi-home")]),t._v("ที่อยู่: 65 หมู่ 1 ถ.สุเทพ ต.สุเทพ อ.เมือง จ.เชียงใหม่ 50200\n "),r("v-icon",{staticClass:"white--text mr-1 mb-1 ml-2",attrs:{size:"24px"}},[t._v("mdi-phone")]),t._v("โทรศัพท์: 053-328496-8\n ")],1),t._v(" "),r("v-row",{attrs:{justify:"center"}},[r("v-icon",{staticClass:"white--text mr-1 mb-1 ml-2",attrs:{size:"24px"}},[t._v("mdi-fax")]),t._v("โทรสาร: 053-328494, 053-328229\n "),r("v-icon",{staticClass:"white--text mr-1 mb-1 ml-2",attrs:{size:"24px"}},[t._v("mdi-email")]),t._v("info@hrdi.or.th\n ")],1)],1)],1)],1),t._v(" "),r("v-scale-transition",[r("v-btn",{directives:[{name:"show",rawName:"v-show",value:t.fab,expression:"fab"},{name:"scroll",rawName:"v-scroll",value:t.onScroll,expression:"onScroll"}],attrs:{fab:"",dark:"",fixed:"",bottom:"",right:"",color:"secondary"},on:{click:t.toTop}},[r("v-icon",[t._v("mdi-arrow-up")])],1)],1)],1)},staticRenderFns:[]};var lt=r("VU/8")(st,nt,!1,function(t){r("5ELs")},"data-v-2bede1f8",null).exports,ct=r("mvHQ"),ut=r.n(ct),dt={data:function(){return{valid:!1,login:{username:"",password:""},isEmtyp:!1,usernameRules:[function(t){return!!t||"Username is required"}],passwordRules:[function(t){return!!t||"Password is required"}]}},methods:{checkLogin:function(){var t=this;if(this.isEmtyp=!1,""!==this.login.username&&null!==this.login.username&&void 0!==this.login.username)if(""!==this.login.password&&null!==this.login.password&&void 0!==this.login.password){var e=new FormData;e.append("username",this.login.username),e.append("password",this.login.password);var r={};e.forEach(function(t,e){console.log(t),r[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/postUserLogin.php",ut()(r)).then(function(e){"0"===e.data.user[0].statusOfMember?t.$swal.fire({icon:"warning",title:"กรุณารอการยืนยันสมาชิกจากผู้ดูแลระบบ",showConfirmButton:!0,allowOutsideClick:!1}).then(function(){}):e.data.user.length>0&&("Buyer"===e.data.user[0].typeOfMember||"Normal"===e.data.user[0].typeOfMember?(localStorage.idMember=e.data.user[0].idBuyerMember,localStorage.user=e.data.user[0].username,localStorage.jwt=e.data.jwt,localStorage.firstName=e.data.user[0].firstName,localStorage.lastName=e.data.user[0].lastName,localStorage.typeOfMember=e.data.user[0].typeOfMember,t.$swal.fire({icon:"success",title:"เข้าสู่ระบบสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})):(localStorage.idMember=e.data.user[0].idSellerMember,localStorage.user=e.data.user[0].username,localStorage.jwt=e.data.jwt,localStorage.firstName=e.data.user[0].firstName,localStorage.lastName=e.data.user[0].lastName,localStorage.typeOfMember=e.data.user[0].typeOfMember,t.$swal.fire({icon:"success",title:"เข้าสู่ระบบสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})))}).catch(function(e){t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถ Login ได้",showConfirmButton:!1,timer:1500}).then(function(){t.isEmtyp=!0})})}else this.isEmtyp=!0;else this.isEmtyp=!0}},mounted:function(){window.scroll(0,0)}},mt={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("v-container",{attrs:{fluid:"","fill-height":""}},[o("v-layout",{attrs:{"align-center":"","justify-center":""}},[o("v-flex",{attrs:{sm12:"",md9:"",lg8:""}},[o("v-toolbar",{attrs:{dark:"",color:"primary"}},[o("v-toolbar-title",[t._v("ของดีบนดอย Login")])],1),t._v(" "),o("v-container",{staticClass:"grey lighten-5"},[t.isEmtyp?o("v-alert",{attrs:{type:"error",color:"red lighten-1"}},[t._v("\n ไม่สามารถเข้าสู่ระบบได้ กรุณาตรวจสอบ Username หรือ Password\n ")]):t._e(),t._v(" "),o("v-row",{attrs:{"no-gutters":""}},[o("v-col",{attrs:{cols:"12",sm:"6",md:"5"}},[o("v-card",[o("v-img",{staticClass:"white--text",attrs:{height:"300px",src:r("3+hF")}})],1)],1),t._v(" "),o("v-col",{attrs:{cols:"12",md:"4"}},[o("v-card-text",[o("v-form",[o("v-text-field",{attrs:{"prepend-icon":"mdi-account",name:"login",label:"Login",type:"text",rules:t.usernameRules},model:{value:t.login.username,callback:function(e){t.$set(t.login,"username",e)},expression:"login.username"}}),t._v(" "),o("v-text-field",{attrs:{"prepend-icon":"mdi-lock",name:"password",label:"Password",type:"password",rules:t.passwordRules},model:{value:t.login.password,callback:function(e){t.$set(t.login,"password",e)},expression:"login.password"}})],1)],1),t._v(" "),o("v-row",{staticClass:"ml-2"},[o("v-col",[o("router-link",{attrs:{to:"/login"}},[t._v("\n ลืมรหัสผ่าน\n ")])],1)],1),t._v(" "),o("v-row",{staticClass:"ml-1",attrs:{justify:"center"}},[o("v-card-actions",[o("v-btn",{staticClass:"mr-1",attrs:{color:"primary"},on:{click:function(e){return e.preventDefault(),t.checkLogin(e)}}},[o("v-icon",[t._v("mdi-login")]),t._v("เข้าสู่ระบบ\n ")],1),t._v(" "),o("v-btn",{staticClass:"ml-1",attrs:{color:"primary",to:"/register"}},[o("v-icon",[t._v("mdi-pen")]),t._v("สมัครสมาชิก\n ")],1),t._v(" "),o("v-spacer")],1)],1)],1),t._v(" "),o("v-col",{attrs:{justify:"center",cols:"12",md:"3"}},[o("v-card-text",[o("v-row",{attrs:{cols:"12",justify:"center"}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-account-details")]),t._v(" "),o("h3",[t._v("ขั้นตอนการสมัครสมาชิก")])],1),t._v(" "),o("v-row",{attrs:{justify:"center"}},[o("ol",{staticClass:"mt-3 font-weight-bold body-2"},[o("li",[t._v('คลิกเมนู "สมัครสมาชิก"')]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("เลือกประเภทสมาชิก ที่ต้องการสมัคร")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v('คลิกปุ่ม "ยอมรับข้อตกลง"')]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("กรอกข้อมูล")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v('คลิกปุ่ม "ยืนยันการสมัครสมาชิก"')]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("รอผู้ดูแลระบบ อนุมัติ")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("เข้าสู่ระบบ")])])])],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]};var pt=r("VU/8")(dt,mt,!1,function(t){r("OPaq")},"data-v-91bad8ac",null).exports,vt=r("ifoU"),gt=r.n(vt),ht={inject:["mySpinner"],data:function(){return{imagePreviewURL:null,isFormValid:!1,confirmPassword:"",buyerForm:{prefix:"",firstName:"",lastName:"",username:"",phoneNumber:"",email:"",idCard:"",password:"",img:[],provinceCode:"",typeOfMember:"",amphurCode:"",tambolCode:"",lineId:"",postcode:"",facebookName:"",address:"",moo:"",road:"",questionOfVisit:"",questionOfObjective:""},sellerForm:{idTypeOfSeller:"",prefix:"",firstName:"",lastName:"",username:"",phoneNumber:"",email:"",idCard:"",gender:"",password:"",vProvinceId:"",vLinkAreaDetailId:"",productType:[],postcode:"",address:"",img:[],moo:"",road:"",tambolCode:"",ampCode:"",zipcode:"",groupName:"",shopName:"",brandName:"",lineId:"",facebookName:""},isRegisForm:{buyer:!1,seller1:!1},isAgree:"",valid:!1,userType:"",isType:!0,isShowPolicy:!1,policy:{showBuyerPolicy:!1,showSellerPolicy:!1,title:"",titleColor:"",ruleTitle:"",firstRule:"",secRule:"",thirdRule:"",fourthRule:"",fifthRule:"",sixthRule:"",seventhRule:"",eigthRule:"",ninethRule:"",footer:""},prefix:[],area:[],sellType:[],amphur:[],tambol:[],province:[{provinceName:""}],targetName:[],targetFilter:[],allProvince:[],buyerAmphur:[],buyerTambol:[],isUsernameExist:!1,showEtc:{visit:!1,objective:!1},firstNameRules:[function(t){return!!t||"กรุณากรอกชื่อ"}],lastNameRules:[function(t){return!!t||"กรุณากรอกนามสกุล"}],imgRules:[function(t){return!!t||"กรุณาเลือกรูปภาพประจำตัว"},function(t){return!t||t.size<3e6||"ขนาดรูปภาพไม่สามารถเกิน 3 MB!"}],emailRules:[function(t){return/.+@.+/.test(t)||"อีเมลต้องอยู่ในรูปแบบที่ถูกต้อง"}],phoneRules:[function(t){return!t.length<10||"หมายเลขโทรศัพท์ต้องมีจำนวน 10 หลัก"},function(t){return!!t||"กรุณากรอกหมายเลขโทรศัพท์"}],passwordRules:[function(t){return!!t||"กรุณากรอกรหัสผ่าน"},function(t){return/[A-Z]+/.test(t)||"ต้องมีตัวอักษรตัวใหญ่ในรหัสผ่าน"},function(t){return/[0-9]/g.test(t)||"ตัองมีตัวเลขในรหัสผ่าน"},function(t){return t.length>=6||"รหัสผ่านต้องมีอย่างน้อย 6 ตัว"},function(t){return/^[a-zA-Z0-9äöüÄÖÜ]*$/.test(t)||"ไม่อนุญาตให้ใช้ตัวอักษรพิเศษ"},function(t){return(t||"").indexOf(" ")<0||"ไม่อนุญาตให้ใช้รหัสผ่านที่มีช่องว่าง"}]}},methods:{previewImg:function(t){var e=t;this.sellerForm.img=e,this.buyerForm.img=e,e?(this.imagePreviewURL=URL.createObjectURL(e),URL.revokeObjectURL(e)):this.imagePreviewURL=null},findTumbolByAmpCode:function(t,e){var r=this;this.tambol=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getTumbolByAmpProv.php?provinceId="+e+"&ampId="+t).then(function(t){t.data.tambol.length>0&&(r.tambol=t.data.tambol),console.log("getTumbolByAmpProv",r.tambol)})},getAmphurByProvince:function(t){var e=this;this.amphur=[],this.tambol=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAmphurById.php?provinceId="+t).then(function(t){t.data.amphur.length>0&&(e.amphur=t.data.amphur),console.log("getAmphurById",e.amphur)})},questionBuyer:function(t){this.showEtc.visit="อื่น ๆ"===t},checkUsername:function(t){var e=this;this.isUsernameExist=!1;var r=new FormData;r.append("username",t);var o={};r.forEach(function(t,e){o[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/checkUsername.php",ut()(o)).then(function(t){t.data.username[0].username.length>0&&(e.isUsernameExist=!0)})},questionObjBuyer:function(t){this.showEtc.objective="อื่น ๆ"===t},findAreaByProvince:function(t){var e=this;this.getAmphurByProvince(t),h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getVLinkTargetById.php?provinceId="+t).then(function(t){console.log("vTargetDetail",t.data.vTargetDetail),t.data.vTargetDetail.length>0&&(e.targetName=[].concat(E()(new gt.a(t.data.vTargetDetail.map(function(t){return[t.targetName,t]})).values())),e.getArea())})},getArea:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllArea.php").then(function(e){t.targetName=t.targetName.map(function(t){return t.targetId}),console.log("targetName",t.targetName),e.data.area.length>0&&(t.area=e.data.area),t.targetFilter=e.data.area.filter(function(e){return t.targetName.includes(e.idArea)}),console.log("targetFilter",t.targetFilter)})},checkLoginType:function(t){this.isType=!1,this.isShowPolicy=!0,"Buyer"===t&&(this.policy={showBuyerPolicy:!0,showSellerPolicy:!1,title:"ผู้ซื้อ",titleColor:"indigo--text",ruleTitle:"ผู้ขอสมัครสมาชิกซึ่งต่อไปนี้จะเรียกว่า ผู้สมัคร และเวบของดีบนดอยออนไลน์ ซึ่งอยู่ภายใต้การดูแลของสถาบันวิจัยและพัฒนาพื้นที่สูง ต่อไปนี้จะเรียกว่า สถาบันฯ กรุณาอ่านข้อตกลงด้านล่างนี้โดยละเอียด เพื่อรักษาสิทธิประโยชน์ในการเป็นสมาชิกของท่านตามเงื่อนไขดังนี้",firstRule:"1. การสมัครสมาชิก เวบของดีบนดอยออนไลน์ ไม่ต้องเสียค่าใช้จ่ายใดใดทั้งสิ้น",secRule:"2. ผู้สมัครจะต้องกรอกข้อมูลรายละเอียดต่างๆ ตามจริงให้ครบถ้วนเพื่อผลประโยชน์แก่ตัวผู้สมัคร หากตรวจพบว่า ข้อมูลของผู้สมัครไม่เป็นความจริง ทางสถาบันจะขอระงับการใช้งานของผู้สมัครโดยไม่ต้องแจ้งให้ทราบล่วงหน้า",thirdRule:"3. ผู้ใดแอบอ้างหรือการกระทำใดใด อันเป็นการละเมิดสิทธิส่วนบุคคล โดยใช้ข้อมูลของผู้อื่นมาแอบอ้างสมัครเป็นสมาชิก เพื่อให้ได้มาซึ่งการเป็นสมาชิก ถือเป็นความผิดต้องได้รับโทษตามกฏหมายที่กำหนดไว้",fourthRule:"4. ข้อมูลส่วนบุคคลของผู้สมัครที่ได้ลงทะเบียนหรือผ่านการใช้งานของเว็บไซต์ ของดีบนดอยออนไลน์ ทั้งหมดนั้น ผู้สมัครยอมรับและตกลงว่าเป็นสิทธิของสถาบันฯ ซึ่งผู้สมัครต้องอนุญาตให้สถาบัน ใช้ข้อมูลของผู้สมัครสมาชิกในงานที่เกี่ยวข้องกับการส่งเสริมอาชีพแก่เกษตรกรบนพื้นที่สูง",fifthRule:"5. ทางเว็บของดีบนดอยออนไลน์ ขอรับรองว่าจะเก็บข้อมูลของผู้สมัครไว้เป็นความลับอย่างดีที่สุด โดยจะไม่นำไปเผยแพร่ที่ใด และหรือเพื่อประโยชน์ทางการค้าหรือประโยชน์ทางด้านอื่นใดโดยไม่ได้รับอนุญาต นอกจากจะได้รับหมายศาลหรือหนังสือทางราชการ ซึ่งขึ้นอยู่กับดุลยพินิชของสถาบันวิจัยและพัฒนาพื้นที่สูง",sixthRule:"6. ผู้สมัครควรปฏิบัติตามข้อกำหนดและเงื่อนไขการให้บริการของเว็บไซต์ของดีบนดอยออนไลน์ โดยเคร่งครัด เพื่อความปลอดภัยในข้อมูลส่วนบุคคลของผู้สมัคร ในกรณีข้อมูลส่วนบุคคลดังกล่าวถูกโจรกรรมโดยวิธีการทางอิเล็กทรอนิกส์ หรือสูญหาย เสียหายอันเนื่องมาจากเหตุสุดวิสัย หรือไม่ว่ากรณีใดใดทั้งสิ้น ทางสถาบันขอสงวนสิทธิ์ในการปฏิเสธความรับผิดชอบจากเหตุดังกล่าวทั้งหมด",seventhRule:"7. ผู้สมัครจะต้องรักษารหัสผ่าน หรือชื่อเข้าใช้งานในระบบเป็นความลับ และหากมีผู้อื่นสามารถเข้าใช้งานจากชื่อของผู้สมัครได้ ทางสถาบัน จะไม่รับผิดชอบใดใดทั้งสิ้น",eigthRule:"8. ผู้สมัครยินยอมให้สถาบันฯ ตรวจสอบข้อมูลส่วนตัว และ หรือข้อมูลอื่นใดที่ผู้สมัครระบุในการสมัครสมาชิก หากสถาบันฯ ตรวจสอบพบว่า ข้อมูลที่ท่านให้ไม่ชัดเจน และหรือเป็นเท็จ ทางสถาบันฯ มีสิทธิ์ในการยกเลิกสมาชิกของผู้สมัครได้",footer:'ข้าพเจ้าผู้สมัคร ได้อ่านเงื่อนไขการสมัครแล้ว และยินยอมให้สถาบันฯ ตรวจสอบข้อมูลส่วนตัว และ/หรือข้อมูลใดที่ผู้สมัครระบุในการสมัครสมาชิก ถ้าผู้สมัครตกลงยินยอมผูกพันและปฏิบัติตามข้อตกลงและเงื่อนไขต่างๆ ตามที่ระบุไว้ในข้อตกลงดังกล่าว รวมทั้งข้อตกลงและเงื่อนไขอื่นๆที่ทางสถาบันฯ เห็นสมควร แต่ถ้าไม่ตกลง กรุณากด "ไม่ยอมรับ" เพื่อกลับไปยังหน้าหลัก'}),"Seller"===t&&(this.policy={showBuyerPolicy:!1,showSellerPolicy:!0,title:"ผู้ขาย",titleColor:"pink--text",ruleTitle:"ผู้ขอสมัครสมาชิกซึ่งต่อไปนี้จะเรียกว่า ผู้สมัคร และเวบของดีบนดอยออนไลน์ ซึ่งอยู่ภายใต้การดูแลของสถาบันวิจัยและพัฒนาพื้นที่สูง ต่อไปนี้จะเรียกว่า สถาบันฯ กรุณาอ่านข้อตกลงด้านล่างนี้โดยละเอียด เพื่อรักษาสิทธิประโยชน์ในการเป็นสมาชิกของท่านตามเงื่อนไขดังนี้",firstRule:"1. ผู้มีสิทธิ์สมัครสมาชิกสำหรับขายสินค้าและผลผลิต ต้องเป็นเกษตรกรที่อยู่ในขอบเขตพื้นที่ส่งเสริมของสถาบันวิจัยและพัฒนาพื้นที่สูงเท่านั้น",secRule:"2. การสมัครสมาชิก เวบของดีบนดอยออนไลน์ ไม่่ต้องเสียค่าใช้จ่ายใดๆทั้งสิ้น",thirdRule:"3. ผู้สมัครจะต้องกรอกข้อมูลรายละเอียดต่างๆ ตามจริงให้ครบถ้วนเพื่อผลประโยชน์แก่ตัวผู้สมัคร หากตรวจพบว่า ข้อมูลของผู้สมัครไม่เป็นความจริง ทางสถาบันจะขอระงับการใช้งานของผู้สมัครโดยไม่ต้องแจ้งให้ทราบล่วงหน้า",fourthRule:"4. ผู้ใดแอบอ้างหรือกระทำการใดใด อันเป็นการละเมิดสิทธิส่วนบุคคล โดยใช้ข้อมูลของผู้อื่นมาแอบอ้างเป็นสมาชิก เพื่อให้ได้มาซึ่งสิทธิการเป็นสมาชิก ถือเป็นความผิดต้องได้รับโทษตามที่กฏหมายกำหนดไว้",fifthRule:"5. ข้อมูลส่วนบุคคลของผู้สมัครที่ได้ลงทะเบียนหรือผ่านการใช้งานของเว็บไซต์ของ ของดีบนดอยออนไลน์ ทั้งหมดนั้น ผู้สมัครยอมรับและตกลงว่าเป็นสิทธิของสถาบันฯ ซึ่งผู้สมัครต้องอนุญาตให้สถาบัน ใช้ข้อมูลของผู้สมัครสมาชิกในงานที่เกี่ยวข้องกับการส่งเสริมอาชีพแก่เกษตรกรบนพื่นที่สูง",sixthRule:"6. ทางเว็บของดีบนดอยออนไลน์ ขอรับรองว่าจะเก็บข้อมูลของผู้สมัครไว้เป็นความลับอย่างดีที่สุด โดยจะไม่นำไปเผยแพร่ที่ใด และหรือเพื่อประโยชน์ทางการค้าหรือประโยชน์ทางด้านอื่นใดโดยไม่ได้รับอนุญาต นอกจากจะได้รับหมายศาลหรือหนังสือทางราชการ ซึ่งขึ้นอยู่กับดุลยพินิชของสถาบันวิจัยและพัฒนาพื้นที่สูง",seventhRule:"7. ผู้สมัครควรปฏิบัติตามข้อกำหนดและเงื่อนไขการให้บริการของเว็บไซต์ของดีบนดอยออนไลน์ โดยเคร่งครัด เพื่อความปลอดภัยในข้อมูลส่วนบุคคลของผู้สมัคร ในกรณีข้อมูลส่วนบุคคลดังกล่าวถูกโจรกรรมโดยวิธีการทางอิเล็กทรอนิกส์ หรือสูญหาย เสียหายอันเนื่องมาจากเหตุสุดวิสัย หรือไม่ว่ากรณีใดใดทั้งสิ้น ทางสถาบันขอสงวนสิทธิ์ในการปฏิเสธความรับผิดชอบจากเหตุดังกล่าวทั้งหมด",eigthRule:"8. ผู้สมัครจะต้องรักษารหัสผ่าน หรือชื่อเข้าใช้งานในระบบเป็นความลับ และหากมีผู้อื่นสามารถเข้าใช้งานจากชื่อของผู้สมัครได้ ทางสถาบัน จะไม่รับผิดชอบใดใดทั้งสิ้น",ninethRule:"9. ผู้สมัครยินยอมให้สถาบันฯ ตรวจสอบข้อมูลส่วนตัว และ หรือข้อมูลอื่นใดที่ผู้สมัครระบุในการสมัครสมาชิก หากสถาบันฯ ตรวจสอบพบว่า ข้อมูลที่ท่านให้ไม่ชัดเจน และหรือเป็นเท็จ ทางสถาบันฯ มีสิทธิ์ในการยกเลิกสมาชิกของผู้สมัครได้",footer:'ข้าพเจ้าผู้สมัคร ได้อ่านเงื่อนไขการสมัครแล้ว และยินยอมให้สถาบันฯ ตรวจสอบข้อมูลส่วนตัว และ/หรือข้อมูลใดที่ผู้สมัครระบุในการสมัครสมาชิก ถ้าผู้สมัครตกลงยินยอมผูกพันและปฏิบัติตามข้อตกลงและเงื่อนไขต่างๆ ตามที่ระบุไว้ในข้อตกลงดังกล่าว รวมทั้งข้อตกลงและเงื่อนไขอื่นๆที่ทางสถาบันฯ เห็นสมควร แต่ถ้าไม่ตกลง กรุณากด "ไม่ยอมรับ" เพื่อกลับไปยังหน้าหลัก'},console.log(this.policy))},checkBuyerRegister:function(){var t=this;if(this.mySpinner.isLoading=!this.mySpinner.isLoading,console.log(this.buyerForm),""!==this.buyerForm.prefix&&null!==this.buyerForm.prefix&&void 0!==this.buyerForm.prefix)if(""!==this.buyerForm.firstName&&null!==this.buyerForm.firstName&&void 0!==this.buyerForm.firstName)if(""!==this.buyerForm.lastName&&null!==this.buyerForm.lastName&&void 0!==this.buyerForm.lastName){var e=new FormData;e.append("address",this.buyerForm.address),e.append("amphurCode",this.buyerForm.amphurCode),e.append("email",this.buyerForm.email),e.append("facebookName",this.buyerForm.facebookName),e.append("firstName",this.buyerForm.firstName),e.append("idCard",this.buyerForm.idCard),e.append("firstName",this.buyerForm.firstName),e.append("gender",this.buyerForm.gender),e.append("img",this.buyerForm.img),e.append("typeOfMember",this.buyerForm.typeOfMember),e.append("postcode",this.buyerForm.postcode),e.append("lastName",this.buyerForm.lastName),e.append("lineId",this.buyerForm.lineId),e.append("moo",this.buyerForm.moo),e.append("password",this.buyerForm.password),e.append("phoneNumber",this.buyerForm.phoneNumber),e.append("prefix",this.buyerForm.prefix),e.append("provinceCode",this.buyerForm.provinceCode),e.append("questionOfObjective",this.buyerForm.questionOfObjective),e.append("questionOfVisit",this.buyerForm.questionOfVisit),e.append("road",this.buyerForm.road),e.append("tambolCode",this.buyerForm.tambolCode),e.append("username",this.buyerForm.username);var r={};e.forEach(function(t,e){console.log(t),r[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/postAddBuyerMember.php",e,{headers:{"Content-Type":"multipart/form-data"}}).then(function(e){"True"===e.data?(t.mySpinner.isLoading=!t.mySpinner.isLoading,t.$swal.fire({icon:"success",title:"สมัครสมาชิกทั่วไปสำเร็จ",text:"รอแอดมินตรวจสอบข้อมูลเพื่อยืนยันการสมัครสมาชิก",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Login"})})):(t.mySpinner.isLoading=!t.mySpinner.isLoading,t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถสมัครสมาชิกได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Login"})}))})}else this.alertCheck("กรุณากรอกนามสกุล");else this.alertCheck("กรุณากรอกชื่อ");else this.alertCheck("กรุณาเลือกคำนำหน้า")},acceptPolicyCheck:function(t,e){console.log(t),t&&"Unaccecpt"!==t&&null!==t?(this.isShowPolicy=!1,t&&"Buyer"===e&&(this.isRegisForm={buyer:!0,seller1:!1},console.log(this.isRegisForm)),t&&"Seller"===e&&(this.isRegisForm={buyer:!1,seller1:!0})):this.$swal.fire({icon:"warning",title:"กรุณาตรวจสอบ",text:"กรุณายอมรับข้อตกลง",allowOutsideClick:!1})},checkSellerRegister:function(){var t=this;if(this.mySpinner.isLoading=!this.mySpinner.isLoading,console.log(this.sellerForm),""!==this.sellerForm.prefix&&null!==this.sellerForm.prefix&&void 0!==this.sellerForm.prefix)if(""!==this.sellerForm.firstName&&null!==this.sellerForm.firstName&&void 0!==this.sellerForm.firstName)if(""!==this.sellerForm.lastName&&null!==this.sellerForm.lastName&&void 0!==this.sellerForm.lastName){var e=new FormData;e.append("address",this.sellerForm.address),e.append("ampCode",this.sellerForm.ampCode),e.append("brandName",this.sellerForm.brandName),e.append("tambolCode",this.sellerForm.tambolCode),e.append("email",this.sellerForm.email),e.append("facebookName",this.sellerForm.facebookName),e.append("firstName",this.sellerForm.firstName),e.append("gender",this.sellerForm.gender),e.append("groupName",this.sellerForm.groupName),e.append("idCard",this.sellerForm.idCard),e.append("idTypeOfSeller",this.sellerForm.idTypeOfSeller),e.append("lastName",this.sellerForm.lastName),e.append("lineId",this.sellerForm.lineId),e.append("postcode",this.buyerForm.postcode),e.append("moo",this.sellerForm.moo),e.append("img",this.sellerForm.img),e.append("password",this.sellerForm.password),e.append("phoneNumber",this.sellerForm.phoneNumber),e.append("prefix",this.sellerForm.prefix),e.append("productType",this.sellerForm.productType),e.append("road",this.sellerForm.road),e.append("shopName",this.sellerForm.shopName),e.append("username",this.sellerForm.username),e.append("vLinkAreaDetailId",this.sellerForm.vLinkAreaDetailId),e.append("vProvinceId",this.sellerForm.vProvinceId),e.append("zipcode",this.sellerForm.zipcode);var r={};e.forEach(function(t,e){console.log(t),r[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/postAddSellerMember.php",e,{headers:{"Content-Type":"multipart/form-data"}}).then(function(e){"True"===e.data?(t.mySpinner.isLoading=!t.mySpinner.isLoading,t.$swal.fire({icon:"success",title:"สมัครสมาชิกสำหรับผู้ขายสำเร็จ",text:"รอแอดมินตรวจสอบข้อมูลเพื่อยืนยันการสมัครสมาชิก",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Login"})})):(t.mySpinner.isLoading=!t.mySpinner.isLoading,t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถสมัครสมาชิกได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Login"})}))})}else this.alertCheck("กรุณากรอกนามสกุล");else this.alertCheck("กรุณากรอกชื่อ");else this.alertCheck("กรุณาเลือกคำนำหน้า")},alertCheck:function(t){this.$swal.fire({icon:"warning",title:t,allowOutsideClick:!1})},findTambolBuyer:function(t,e){var r=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerTambol.php?provinceId="+t+"&amphurId="+e).then(function(t){t.data.buyerTambol.length>0&&(r.buyerTambol=t.data.buyerTambol),console.log("getBuyerTambol",r.buyerTambol)})},findAmphurBuyer:function(t){var e=this;this.buyerAmphur=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerAmphur.php?provinceId="+t).then(function(t){e.buyerAmphur=t.data.buyerAmphur,console.log("getBuyerAmphur",e.buyerAmphur)})},getPrefix:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getPrefix.php").then(function(e){t.prefix=e.data.prefix,console.log("prefix",t.prefix)})},getProvince:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getVLinkProvince.php").then(function(e){e.data.vLinkProvince.length>0&&(t.province=[].concat(E()(new gt.a(e.data.vLinkProvince.map(function(t){return[t.provinceId,t]})).values()))),t.province=t.province.filter(function(t,e){return"เลย"!==t.provinceName&&"ลำปาง"!==t.provinceName&&"แพร่"!==t.provinceName}),console.log("province",t.province)})},seller2Revert:function(){this.isRegisForm={seller1:!0,seller2:!1,seller3:!1}},getSellerType:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getSellerType.php").then(function(e){t.sellType=e.data.sellType,console.log("sellType",t.sellType)})},getAllProvince:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllprovince.php").then(function(e){e.data.allProvince.length>0&&(t.allProvince=e.data.allProvince),console.log("getAllprovince",t.allProvince)})}},mounted:function(){this.getPrefix(),this.getProvince(),this.getSellerType(),this.getAllProvince()}},ft={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("v-container",{attrs:{fluid:"","fill-height":""}},[o("v-layout",{attrs:{"align-center":"","justify-center":""}},[o("v-flex",{attrs:{xs11:"",sm8:"",lg10:""}},[t.isType?o("v-row",{staticClass:"pa-5",attrs:{justify:"space-between"}},[o("v-card",{staticClass:"elevation-12 mb-5",attrs:{"max-width":"320"}},[o("v-toolbar",{attrs:{dark:"",color:"primary"}},[o("v-toolbar-title",[t._v("สมาชิกทั่วไป / ผู้เข้ามาซื้อสินค้า")])],1),t._v(" "),o("v-col",{staticClass:"md-6"},[o("v-img",{staticClass:"white--text align-end",attrs:{id:"rounded",height:"300px",src:r("3+hF")}})],1),t._v(" "),o("v-card-actions",[o("router-link",{attrs:{to:"register"}}),t._v(" "),o("v-spacer"),t._v(" "),o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.checkLoginType("Buyer")}}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-pen")]),t._v("สมัครสมาชิกทั่วไป\n ")],1)],1),t._v(" "),o("v-row",{staticClass:"pa-3"},[o("ul",{staticClass:"font-weight-bold body-1"},[o("li",{staticClass:"mt-1"},[t._v("\n สามารถซื้อสินค้า และติดต่อเกษตรกรแต่ละร้านค้าได้\n ")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("รับข่าวสารสิทธิพิเศษจากทางเว็บไซต์")])])])],1),t._v(" "),o("v-card",{staticClass:"elevation-12 mb-5",attrs:{"max-width":"320"}},[o("v-toolbar",{attrs:{dark:"",color:"primary"}},[o("v-toolbar-title",[t._v("สมาชิกผู้ขายสินค้า")])],1),t._v(" "),o("v-col",{staticClass:"md-6"},[o("v-img",{staticClass:"white--text align-end",attrs:{id:"rounded",height:"300px",src:r("3+hF")}})],1),t._v(" "),o("v-card-actions",[o("router-link",{attrs:{to:"register"}}),t._v(" "),o("v-spacer"),t._v(" "),o("v-btn",{attrs:{block:"",color:"primary"},on:{click:function(e){return t.checkLoginType("Seller")}}},[o("v-icon",{staticClass:"mr-1"},[t._v("mdi-pen")]),t._v("สมาชิกผู้ขายสินค้า\n ")],1)],1),t._v(" "),o("v-row",{staticClass:"pa-3"},[o("ul",{staticClass:"font-weight-bold body-1"},[o("li",{staticClass:"mt-1"},[t._v("สามารถนำสินค้ามาแนะนำและลงขายบนหน้าเวบได้")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("รับข่าวสารสิทธิพิเศษจากทางเว็บไซต์")])])])],1),t._v(" "),o("v-card",{staticClass:"elevation-12 mb-5",attrs:{"max-width":"320"}},[o("v-toolbar",{staticClass:"border",attrs:{light:"",rounded:"",color:"grey lighten-4"}},[o("v-toolbar-title",{staticClass:"font-weight-black"},[t._v("ผู้เยี่ยมชมไม่ได้สมัครสมาชิก")])],1),t._v(" "),o("v-col",{staticClass:"md-6"},[o("v-img",{staticClass:"white--text align-end",attrs:{id:"rounded",height:"300px",src:r("3+hF")}})],1),t._v(" "),o("v-row",{staticClass:"pa-3"},[o("ul",{staticClass:"font-weight-bold body-1"},[o("li",{staticClass:"mt-1"},[t._v("\n สามารถค้นหาข้อมูลสินค้า\n แต่ไม่สามารถติดต่อเกษตรกรเพื่อซื้อสินค้าได้\n ")]),t._v(" "),o("li",{staticClass:"mt-1"},[t._v("ไม่สามารถลงขายสินค้าได้")])])])],1)],1):t._e(),t._v(" "),t.isShowPolicy?o("p",{staticClass:"display-2 font-weight-light\ttext-center mt-5 mb-0"},[t._v("\n เงื่อนไขการสมัครสมาชิกสำหรับ\n "),o("span",{class:[t.policy.titleColor]},[t._v(t._s(t.policy.title))])]):t._e(),t._v(" "),t.isShowPolicy?o("v-row",{staticClass:"pa-5",attrs:{justify:"center"}},[t.policy.showBuyerPolicy?o("v-card",{staticClass:"elevation-12 mb-5"},[o("v-row",{staticClass:"pa-5"},[o("h3",[t._v(t._s(t.policy.ruleTitle))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.firstRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.secRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.thirdRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.fourthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.fifthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.sixthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.seventhRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.eigthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"red--text text--darken-1"},[t._v(t._s(t.policy.footer))])]),t._v(" "),o("v-row",{staticClass:"ml-5",attrs:{justify:"center",cols:"12"}},[o("v-radio-group",{staticClass:"font-weight-black",attrs:{row:""},model:{value:t.isAgree,callback:function(e){t.isAgree=e},expression:"isAgree"}},[o("v-col",[o("v-radio",{attrs:{label:"ไม่ยอมรับ (Unaccept)",value:"Unaccecpt"}})],1),t._v(" "),o("v-col",[o("v-radio",{attrs:{label:"ยอมรับ (Accept)",value:"Accept"}})],1)],1)],1),t._v(" "),o("v-row",{attrs:{justify:"center"}},[o("v-card-actions",[o("router-link",{attrs:{to:"register"}}),t._v(" "),o("v-btn",{attrs:{color:"primary"},on:{click:function(e){return t.acceptPolicyCheck(t.isAgree,"Buyer")}}},[t._v("ตกลง (OK)")]),t._v(" "),o("v-btn",{attrs:{color:"primary"},on:{click:function(e){return t.$router.push({name:"Home"})}}},[t._v("ยกเลิก (Cancel)")])],1)],1)],1):t._e(),t._v(" "),t.policy.showSellerPolicy?o("v-card",{staticClass:"elevation-12 mb-5"},[o("v-row",{staticClass:"pa-5"},[o("h3",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.ruleTitle))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.firstRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.secRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.thirdRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.fourthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.fifthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.sixthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.seventhRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.eigthRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"font-weight-light"},[t._v(t._s(t.policy.ninethRule))])]),t._v(" "),o("v-row",{staticClass:"pa-5"},[o("h4",{staticClass:"red--text text--darken-1"},[t._v(t._s(t.policy.footer))])]),t._v(" "),o("v-row",{staticClass:"ml-5",attrs:{justify:"center",cols:"12"}},[o("v-radio-group",{staticClass:"font-weight-black",attrs:{row:""},model:{value:t.isAgree,callback:function(e){t.isAgree=e},expression:"isAgree"}},[o("v-col",[o("v-radio",{attrs:{label:"ไม่ยอมรับ (Unaccept)",value:"Unaccecpt"}})],1),t._v(" "),o("v-col",[o("v-radio",{attrs:{label:"ยอมรับ (Accept)",value:"Accept"}})],1)],1)],1),t._v(" "),o("v-row",{attrs:{justify:"center"}},[o("v-card-actions",[o("router-link",{attrs:{to:"register"}}),t._v(" "),o("v-btn",{attrs:{color:"primary"},on:{click:function(e){return t.acceptPolicyCheck(t.isAgree,"Seller")}}},[t._v("ตกลง (OK)")]),t._v(" "),o("v-btn",{attrs:{color:"primary"},on:{click:function(e){return t.$router.push({name:"Home"})}}},[t._v("ยกเลิก (Cancel)")])],1)],1)],1):t._e()],1):t._e(),t._v(" "),t.isRegisForm.buyer?o("v-row",{attrs:{justify:"center"}},[o("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[o("v-card",{ref:"form"},[o("v-toolbar",{attrs:{dark:"",color:"primary"}},[o("v-toolbar-title",[t._v("สมัครสมาชิกสำหรับผู้เข้ามาซื้อสินค้า / ทั่วไป\n ")])],1),t._v(" "),o("v-card-text",[o("v-col",{attrs:{cols:"12"}},[o("v-row",{attrs:{md:"4"}},[o("v-col",[o("v-select",{attrs:{"prepend-icon":"mdi-account-box","item-text":"prefixNameTh","item-value":"idPrefix",items:t.prefix,rules:[function(t){return!!t||"กรุณาเลือกคำนำหน้า"}],label:"คำนำหน้า*",required:""},model:{value:t.buyerForm.prefix,callback:function(e){t.$set(t.buyerForm,"prefix",e)},expression:"buyerForm.prefix"}},[t._v("*")])],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-account",name:"firstName",label:"ชื่อ*",type:"text",rules:t.firstNameRules},model:{value:t.buyerForm.firstName,callback:function(e){t.$set(t.buyerForm,"firstName",e)},expression:"buyerForm.firstName"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{name:"lastName",label:"นามสกุล*",type:"text",rules:t.lastNameRules},model:{value:t.buyerForm.lastName,callback:function(e){t.$set(t.buyerForm,"lastName",e)},expression:"buyerForm.lastName"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"12",fluid:""}},[o("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n เพศ*\n ")]),t._v(" "),o("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาระบุเพศ"}]},model:{value:t.buyerForm.gender,callback:function(e){t.$set(t.buyerForm,"gender",e)},expression:"buyerForm.gender"}},[o("v-radio",{attrs:{label:"ชาย",value:"ชาย"}}),t._v(" "),o("v-radio",{attrs:{label:"หญิง",value:"หญิง"}})],1)],1)],1),t._v(" "),o("v-row",{attrs:{align:"center",justify:"center"}},[t.imagePreviewURL?o("v-img",{staticClass:"grey lighten-2 mb-2",attrs:{src:t.imagePreviewURL,"lazy-src":t.imagePreviewURL,"aspect-ratio":"1","max-width":"300","max-height":"300"},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)}):t._e()],1),t._v(" "),o("v-file-input",{attrs:{rules:t.imgRules,accept:"image/png, image/jpeg, image/bmp",placeholder:"เลือกรูปภาพประจำตัว",label:"รูปภาพโปรไฟล์","prepend-icon":"mdi-camera"},on:{change:t.previewImg},model:{value:t.buyerForm.img,callback:function(e){t.$set(t.buyerForm,"img",e)},expression:"buyerForm.img"}}),t._v(" "),o("v-text-field",{attrs:{"prepend-icon":"mdi-account-outline",type:"text",rules:[!t.isUsernameExist||"Username ถูกใช้งานไปแล้ว",function(t){return!!t||"กรุณากรอก Username"}],label:"Username*",required:""},on:{keyup:function(e){return t.checkUsername(t.buyerForm.username)}},model:{value:t.buyerForm.username,callback:function(e){t.$set(t.buyerForm,"username",e)},expression:"buyerForm.username"}}),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:t.passwordRules,label:"รหัสผ่าน*",required:""},model:{value:t.buyerForm.password,callback:function(e){t.$set(t.buyerForm,"password",e)},expression:"buyerForm.password"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:[t.buyerForm.password===t.confirmPassword||"รหัสผ่านไม่ตรงกัน",function(t){return!!t||"กรุณายืนยันรหัสผ่าน"}],label:"ยืนยันรหัสผ่าน*",required:""},model:{value:t.confirmPassword,callback:function(e){t.confirmPassword=e},expression:"confirmPassword"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"12"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-email",type:"email",label:"อีเมล"},model:{value:t.buyerForm.email,callback:function(e){t.$set(t.buyerForm,"email",e)},expression:"buyerForm.email"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-phone",counter:"",rules:t.phoneRules,label:"หมายเลขโทรศัพท์*",required:""},model:{value:t.buyerForm.phoneNumber,callback:function(e){t.$set(t.buyerForm,"phoneNumber",e)},expression:"buyerForm.phoneNumber"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-account-details",counter:"",maxlength:"13",label:"หมายเลขบัตรประชาชน"},model:{value:t.buyerForm.idCard,callback:function(e){t.$set(t.buyerForm,"idCard",e)},expression:"buyerForm.idCard"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-phone-plus",type:"text",label:"ไลน์ไอดี",required:""},model:{value:t.buyerForm.lineId,callback:function(e){t.$set(t.buyerForm,"lineId",e)},expression:"buyerForm.lineId"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-facebook",type:"text",label:"Facebook",required:""},model:{value:t.buyerForm.facebookName,callback:function(e){t.$set(t.buyerForm,"facebookName",e)},expression:"buyerForm.facebookName"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{label:"บ้านเลขที่",type:"text"},model:{value:t.buyerForm.address,callback:function(e){t.$set(t.buyerForm,"address",e)},expression:"buyerForm.address"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"หมู่ (ถ้ามี)",type:"text"},model:{value:t.buyerForm.moo,callback:function(e){t.$set(t.buyerForm,"moo",e)},expression:"buyerForm.moo"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"ถนน",type:"text"},model:{value:t.buyerForm.road,callback:function(e){t.$set(t.buyerForm,"road",e)},expression:"buyerForm.road"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"รหัสไปรณีย์",type:"text"},model:{value:t.buyerForm.postcode,callback:function(e){t.$set(t.buyerForm,"postcode",e)},expression:"buyerForm.postcode"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"4"}},[o("v-col",[o("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"name","item-value":"code",items:t.allProvince,rules:[function(t){return!!t||"กรุณาเลือกจังหวัด"}],label:"จังหวัด*",required:""},on:{change:function(e){return t.findAmphurBuyer(t.buyerForm.provinceCode)}},model:{value:t.buyerForm.provinceCode,callback:function(e){t.$set(t.buyerForm,"provinceCode",e)},expression:"buyerForm.provinceCode"}})],1),t._v(" "),o("v-col",[o("v-select",{attrs:{"item-text":"ampT","item-value":"ampCode",items:t.buyerAmphur,rules:[function(t){return!!t||"กรุณาเลือกอำเภอ"}],label:"อำเภอ*",required:""},on:{change:function(e){return t.findTambolBuyer(t.buyerForm.provinceCode,t.buyerForm.amphurCode)}},model:{value:t.buyerForm.amphurCode,callback:function(e){t.$set(t.buyerForm,"amphurCode",e)},expression:"buyerForm.amphurCode"}})],1),t._v(" "),o("v-col",[o("v-select",{attrs:{"item-text":"tamT","item-value":"tamCode",items:t.buyerTambol,rules:[function(t){return!!t||"กรุณาเลือกตำบล"}],label:"ตำบล*",required:""},model:{value:t.buyerForm.tambolCode,callback:function(e){t.$set(t.buyerForm,"tambolCode",e)},expression:"buyerForm.tambolCode"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"12",fluid:""}},[o("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ประเภทสมาชิก*\n ")]),t._v(" "),o("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาเลือกประเภทสมาชิก"}]},model:{value:t.buyerForm.typeOfMember,callback:function(e){t.$set(t.buyerForm,"typeOfMember",e)},expression:"buyerForm.typeOfMember"}},[o("v-radio",{attrs:{label:"สมาชิกทั่วไป",value:"Normal"}}),t._v(" "),o("v-radio",{attrs:{label:"สมาชิกผู้ซื้อ",value:"Buyer"}})],1)],1)],1),t._v(" "),o("v-row",{attrs:{md:"12",fluid:""}},[o("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n คุณรู้จักเว็บไซต์ของดีบนดอยได้อย่างไร*\n ")]),t._v(" "),o("v-radio-group",{attrs:{rules:[function(t){return!!t||"กรุณาเลือกตัวเลือก"}]},on:{change:function(e){return t.questionBuyer(t.buyerForm.questionOfVisit)}},model:{value:t.buyerForm.questionOfVisit,callback:function(e){t.$set(t.buyerForm,"questionOfVisit",e)},expression:"buyerForm.questionOfVisit"}},[o("v-radio",{attrs:{label:"ค้นหาจาก Google",value:"ค้นหาจาก Google"}}),t._v(" "),o("v-radio",{attrs:{label:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง",value:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง"}}),t._v(" "),o("v-radio",{attrs:{label:"เพื่อน / คนรู้จักแนะ",value:"เพื่อน / คนรู้จักแนะ"}}),t._v(" "),o("v-radio",{attrs:{label:"อื่น ๆ",value:"อื่น ๆ"}})],1),t._v(" "),t.showEtc.visit?o("v-text-field",{attrs:{outlined:"",type:"text",label:"เหตุผลอื่นๆ",rules:[function(t){return!!t||"กรุณากรอกเหตุผล"}]},model:{value:t.buyerForm.questionOfVisit,callback:function(e){t.$set(t.buyerForm,"questionOfVisit",e)},expression:"buyerForm.questionOfVisit"}}):t._e()],1),t._v(" "),o("v-col",{attrs:{md:"6"}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n วัตถุประสงค์ที่สมัครสมาชิก*\n ")]),t._v(" "),o("v-radio-group",{attrs:{rules:[function(t){return!!t||"กรุณาเลือกตัวเลือก"}]},on:{change:function(e){return t.questionObjBuyer(t.buyerForm.questionOfObjective)}},model:{value:t.buyerForm.questionOfObjective,callback:function(e){t.$set(t.buyerForm,"questionOfObjective",e)},expression:"buyerForm.questionOfObjective"}},[o("v-radio",{attrs:{label:"เข้ามาเยี่ยมชม",value:"เข้ามาเยี่ยมชม"}}),t._v(" "),o("v-radio",{attrs:{label:"เข้ามาซื้อผลผลิต",value:"เข้ามาซื้อผลผลิต"}}),t._v(" "),o("v-radio",{attrs:{label:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร",value:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร"}}),t._v(" "),o("v-radio",{attrs:{label:"อื่น ๆ",value:"อื่น ๆ"}}),t._v(" "),t.showEtc.objective?o("v-text-field",{staticClass:"mt-3",attrs:{outlined:"",type:"text",label:"เหตุผลอื่นๆ",rules:[function(t){return!!t||"กรุณากรอกเหตุผล"}]},model:{value:t.buyerForm.questionOfObjective,callback:function(e){t.$set(t.buyerForm,"questionOfObjective",e)},expression:"buyerForm.questionOfObjective"}}):t._e()],1)],1)],1)],1)],1),t._v(" "),o("v-card-actions",[o("v-row",[o("v-col",[o("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.go(-1)}}},[t._v("ย้อนกลับ")])],1),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:t.checkBuyerRegister}},[t._v("ยืนยันสมัครสมาชิก")])],1)],1)],1)],1)],1)],1):t._e(),t._v(" "),t.isRegisForm.seller1?o("v-row",{attrs:{justify:"center",dense:""}},[o("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[o("v-card",{ref:"form"},[o("v-toolbar",{attrs:{dark:"",color:"primary"}},[o("v-toolbar-title",[t._v("สมัครสมาชิกสำหรับผู้ขายสินค้า")])],1),t._v(" "),o("v-card-text",[o("v-col",{attrs:{cols:"12"}},[o("v-row",{attrs:{md:"4"}},[o("v-col",[o("v-select",{attrs:{"prepend-icon":"mdi-account-box","item-text":"prefixNameTh","item-value":"idPrefix",items:t.prefix,rules:[function(t){return!!t||"กรุณาเลือกคำนำหน้า"}],label:"คำนำหน้า*",required:""},model:{value:t.sellerForm.prefix,callback:function(e){t.$set(t.sellerForm,"prefix",e)},expression:"sellerForm.prefix"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-account",name:"firstName",label:"ชื่อ*",type:"text",rules:t.firstNameRules},model:{value:t.sellerForm.firstName,callback:function(e){t.$set(t.sellerForm,"firstName",e)},expression:"sellerForm.firstName"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{name:"lastName",label:"นามสกุล*",type:"text",rules:t.lastNameRules},model:{value:t.sellerForm.lastName,callback:function(e){t.$set(t.sellerForm,"lastName",e)},expression:"sellerForm.lastName"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"12",fluid:""}},[o("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n เพศ*\n ")]),t._v(" "),o("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาระบุเพศ"}]},model:{value:t.sellerForm.gender,callback:function(e){t.$set(t.sellerForm,"gender",e)},expression:"sellerForm.gender"}},[o("v-radio",{attrs:{label:"ชาย",value:"ชาย"}}),t._v(" "),o("v-radio",{attrs:{label:"หญิง",value:"หญิง"}})],1)],1)],1),t._v(" "),o("v-row",{attrs:{align:"center",justify:"center"}},[t.imagePreviewURL?o("v-img",{staticClass:"grey lighten-2 mb-2",attrs:{src:t.imagePreviewURL,"lazy-src":t.imagePreviewURL,"aspect-ratio":"1","max-width":"300","max-height":"300"},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)}):t._e()],1),t._v(" "),o("v-file-input",{attrs:{rules:t.imgRules,accept:"image/png, image/jpeg, image/bmp",placeholder:"เลือกรูปภาพประจำตัว",label:"รูปภาพโปรไฟล์","prepend-icon":"mdi-camera"},on:{change:t.previewImg},model:{value:t.sellerForm.img,callback:function(e){t.$set(t.sellerForm,"img",e)},expression:"sellerForm.img"}}),t._v(" "),o("v-text-field",{attrs:{"prepend-icon":"mdi-account-outline",type:"text",rules:[!t.isUsernameExist||"Username ถูกใช้งานไปแล้ว",function(t){return!!t||"กรุณากรอก Username"}],label:"Username*",required:""},on:{keyup:function(e){return t.checkUsername(t.sellerForm.username)}},model:{value:t.sellerForm.username,callback:function(e){t.$set(t.sellerForm,"username",e)},expression:"sellerForm.username"}}),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{autocomplete:"new-password","prepend-icon":"mdi-lock",type:"password",counter:"",rules:t.passwordRules,label:"รหัสผ่าน*",required:""},model:{value:t.sellerForm.password,callback:function(e){t.$set(t.sellerForm,"password",e)},expression:"sellerForm.password"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{autocomplete:"new-password","prepend-icon":"mdi-lock",type:"password",counter:"",rules:[t.sellerForm.password===t.confirmPassword||"รหัสผ่านไม่ตรงกัน",function(t){return!!t||"กรุณายืนยันรหัสผ่าน"}],label:"ยืนยันรหัสผ่าน*",required:""},model:{value:t.confirmPassword,callback:function(e){t.confirmPassword=e},expression:"confirmPassword"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"12"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-email",type:"email",label:"อีเมล"},model:{value:t.sellerForm.email,callback:function(e){t.$set(t.sellerForm,"email",e)},expression:"sellerForm.email"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-phone",counter:"",rules:t.phoneRules,label:"หมายเลขโทรศัพท์*",required:""},model:{value:t.sellerForm.phoneNumber,callback:function(e){t.$set(t.sellerForm,"phoneNumber",e)},expression:"sellerForm.phoneNumber"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-account-details",counter:"",maxlength:"13",label:"หมายเลขบัตรประชาชน"},model:{value:t.sellerForm.idCard,callback:function(e){t.$set(t.sellerForm,"idCard",e)},expression:"sellerForm.idCard"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-phone-plus",type:"text",label:"ไลน์ไอดี",required:""},model:{value:t.sellerForm.lineId,callback:function(e){t.$set(t.sellerForm,"lineId",e)},expression:"sellerForm.lineId"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{"prepend-icon":"mdi-facebook",type:"text",label:"Facebook"},model:{value:t.sellerForm.facebookName,callback:function(e){t.$set(t.sellerForm,"facebookName",e)},expression:"sellerForm.facebookName"}})],1)],1),t._v(" "),o("v-container",{staticClass:"my-0",attrs:{fluid:""}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ที่อยู่\n ")]),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{label:"บ้านเลขที่",type:"text"},model:{value:t.sellerForm.address,callback:function(e){t.$set(t.sellerForm,"address",e)},expression:"sellerForm.address"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"หมู่ (ถ้ามี)",type:"text"},model:{value:t.sellerForm.moo,callback:function(e){t.$set(t.sellerForm,"moo",e)},expression:"sellerForm.moo"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"ถนน",type:"text"},model:{value:t.sellerForm.road,callback:function(e){t.$set(t.sellerForm,"road",e)},expression:"sellerForm.road"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"รหัสไปรณีย์",type:"text"},model:{value:t.sellerForm.postcode,callback:function(e){t.$set(t.sellerForm,"postcode",e)},expression:"sellerForm.postcode"}})],1)],1),t._v(" "),o("v-row",{attrs:{md:"4"}},[o("v-col",[o("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"provinceName","item-value":"provinceId",items:t.province,rules:[function(t){return!!t||"กรุณาเลือกจังหวัด"}],label:"จังหวัด*",required:""},on:{change:function(e){return t.findAreaByProvince(t.sellerForm.vProvinceId)}},model:{value:t.sellerForm.vProvinceId,callback:function(e){t.$set(t.sellerForm,"vProvinceId",e)},expression:"sellerForm.vProvinceId"}})],1),t._v(" "),o("v-col",[o("v-select",{attrs:{"item-text":"ampT","item-value":"ampCode",items:t.amphur,rules:[function(t){return!!t||"กรุณาเลือกอำเภอ"}],label:"อำเภอ*",required:""},on:{change:function(e){return t.findTumbolByAmpCode(t.sellerForm.ampCode,t.sellerForm.vProvinceId)}},model:{value:t.sellerForm.ampCode,callback:function(e){t.$set(t.sellerForm,"ampCode",e)},expression:"sellerForm.ampCode"}})],1),t._v(" "),o("v-col",[o("v-select",{attrs:{"item-text":"tamT","item-value":"tamCode",items:t.tambol,rules:[function(t){return!!t||"กรุณาเลือกตำบล"}],label:"ตำบล*",required:""},model:{value:t.sellerForm.tambolCode,callback:function(e){t.$set(t.sellerForm,"tambolCode",e)},expression:"sellerForm.tambolCode"}})],1)],1),t._v(" "),o("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"areaName","item-value":"idArea",items:t.targetFilter,rules:[function(t){return!!t||"กรุณาเลือกศูนย์"}],label:"ชื่อศูนย์*",required:""},model:{value:t.sellerForm.vLinkAreaDetailId,callback:function(e){t.$set(t.sellerForm,"vLinkAreaDetailId",e)},expression:"sellerForm.vLinkAreaDetailId"}})],1),t._v(" "),o("v-select",{attrs:{"prepend-icon":"mdi-basket","item-text":"nameTypeOfSeller","item-value":"idTypeOfSeller",items:t.sellType,rules:[function(t){return!!t||"กรุณาเลือกลักษณะการจ่ายสินค้า"}],label:"ลักษณะการจำหน่ายสินค้า*",required:""},model:{value:t.sellerForm.idTypeOfSeller,callback:function(e){t.$set(t.sellerForm,"idTypeOfSeller",e)},expression:"sellerForm.idTypeOfSeller"}}),t._v(" "),o("v-text-field",{attrs:{label:"ชื่อกลุ่ม (ถ้ามี)",type:"text"},model:{value:t.sellerForm.groupName,callback:function(e){t.$set(t.sellerForm,"groupName",e)},expression:"sellerForm.groupName"}}),t._v(" "),o("v-row",{attrs:{md:"6"}},[o("v-col",[o("v-text-field",{attrs:{label:"ชื่อร้าน (ถ้ามี)",type:"text"},model:{value:t.sellerForm.shopName,callback:function(e){t.$set(t.sellerForm,"shopName",e)},expression:"sellerForm.shopName"}})],1),t._v(" "),o("v-col",[o("v-text-field",{attrs:{label:"ชื่อตราสินค้า (ถ้ามี)",type:"text"},model:{value:t.sellerForm.brandName,callback:function(e){t.$set(t.sellerForm,"brandName",e)},expression:"sellerForm.brandName"}})],1)],1),t._v(" "),o("v-container",{attrs:{fluid:""}},[o("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ชนิดสินค้าที่ต้องการจำหน่าย (เลือกได้มากกว่า 1 ชนิด)*\n ")]),t._v(" "),o("v-row",[o("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[o("v-checkbox",{attrs:{label:"ข้าวและธัญพืซ",value:"ข้าวและธัญพืซ"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"ผักและสมุนไพร",value:"ผักและสมุนไพร"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"ไม้ผล",value:"ไม้ผล"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1),t._v(" "),o("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[o("v-checkbox",{attrs:{label:"ไม้ดอกไม้ประดับ",value:"ไม้ดอกไม้ประดับ"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"ผลิตภัณฑ์แปรรูป",value:"ผลิตภัณฑ์แปรรูป"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"ชา กาแฟ และโกโก้",value:"ชา กาแฟ และโกโก้"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1),t._v(" "),o("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[o("v-checkbox",{attrs:{label:"หัตถกรรม",value:"หัตถกรรม"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"พืซท้องถิ่น",value:"พืซท้องถิ่น"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),o("v-checkbox",{attrs:{label:"ปศุสัตว์ และประมง",value:"ปศุสัตว์ และประมง"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1)],1)],1)],1)],1),t._v(" "),o("v-card-actions",[o("v-row",[o("v-col",[o("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.go(-1)}}},[t._v("ย้อนกลับ")])],1),t._v(" "),o("v-col",[o("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:t.checkSellerRegister}},[t._v("ยืนยันสมัครสมาชิก")])],1)],1)],1)],1)],1)],1):t._e()],1)],1)],1)},staticRenderFns:[]};var Mt=r("VU/8")(ht,ft,!1,function(t){r("GRcx")},"data-v-41ddebcd",null).exports,yt={data:function(){return{aboutContent:[]}},methods:{getAboutUs:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/aboutus/getAboutUs.php").then(function(e){t.aboutContent=e.data.aboutus[0],console.log(t.aboutContent)})}},mounted:function(){this.getAboutUs()}},bt={render:function(){var t=this.$createElement,e=this._self._c||t;return e("v-container",[e("p",{staticClass:"display-3 font-weight-bold text-center pa-4",staticStyle:{color:"#074d66"}},[this._v(this._s(this.aboutContent.aboutTitle))]),this._v(" "),e("v-container",{attrs:{fluid:""}},[e("v-row",[e("v-col",{staticClass:"content",attrs:{md:"12",lg:"12"},domProps:{innerHTML:this._s(this.aboutContent.aboutBody)}})],1)],1)],1)},staticRenderFns:[]};var xt=r("VU/8")(yt,bt,!1,function(t){r("ZzoQ")},null,null).exports,It=r("nrd6"),Nt=r("iI18"),wt={components:{LMap:Nt.a,LTileLayer:Nt.d,LMarker:Nt.b,LTooltip:Nt.e,LPopup:Nt.c},inject:["mySpinner"],data:function(){return{url:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",zoom:5.5,center:[17.87,100.9925],bounds:null,showAmount:!0,showDetails:!1,isShowListProduct:!1,selectedItem:1,productByArea:[],productMk:[],nameTypeOfArgiMk:"",nameOfArgi:"",area:[],markers:[],pane:"Test",productByArgi:[],productByArgiList:[],productParams:""}},methods:{productDetail:function(t){this.$router.push({name:"ProductDetail",params:{idProductOfMemberMk:t}})},backFromArea:function(){this.zoomUpdated(5.5),this.showAmount=!1,this.showDetails=!0,this.isShowListProduct=!1},showProduct:function(t,e,r,o){var a=this;console.log(r,o);var i={lat:r,lng:o};this.$refs.productMap.mapObject.flyTo(i,12);var s=new FormData;s.append("idSellerMember",t),s.append("idAgri",e),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/map/getProductFromArea.php",s).then(function(t){a.showDetails=!1,a.isShowListProduct=!0,a.productByArea=t.data.productByArea,console.log("productByArea",a.productByArea)}).catch(function(t){console.log(t)})},itemClick:function(t,e){window.scroll(0,0),this.nameOfArgi=t,this.getProductByArgi(t),this.showAmount=!1,this.showDetails=!0},back:function(){window.scroll(0,0),this.showAmount=!0,this.showDetails=!1},zoomUpdated:function(t){this.zoom=t},centerUpdated:function(t){this.center=t},boundsUpdated:function(t){this.bounds=t},getProductByArgi:function(t){var e=this;this.zoomUpdated(5.5);var r=new FormData;r.append("idAgri",t),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/map/getProductByArgi.php",r).then(function(t){0!==t.data.productByArgi&&(e.productByArgi=t.data.productByArgi,e.productByArgiList=e.productByArgi.filter(function(t,e,r){return r.findIndex(function(e){return e.idSellerMember===t.idSellerMember&&e.idSellerMember===t.idSellerMember})===e}),console.log("productByArgi",e.productByArgi),console.log("productByArgiList",e.productByArgiList),e.markers=e.productByArgiList.map(function(t,e){return{id:e,position:{lat:parseFloat(t.lat),lng:parseFloat(t.long)},tooltip:t.areaName,idArea:t.idArea,idAgri:t.idAgri,idSellerMember:t.idSellerMember,areaName:t.areaName,visible:!0,lat:parseFloat(t.lat),lng:parseFloat(t.long)}}),console.log("markers",e.markers))}).catch(function(t){console.log(t)})},productByType:function(){var t=this,e=new FormData;e.append("idTypeOfArgi",this.$route.params.idTypeOfArgi),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/map/getProductByType.php",e).then(function(e){0!==e.data.productMk&&(console.log("resProductMk",e.data.productMk),t.productMk=e.data.productMk,t.productMk=t.productMk.filter(function(t,e,r){return r.findIndex(function(e){return e.idAgri===t.idAgri&&e.idAgri===t.idAgri})===e}),t.mySpinner.isLoading=!t.mySpinner.isLoading,console.log("productMk",t.productMk))}).catch(function(t){console.log(t)})}},mounted:function(){window.scroll(0,0),this.mySpinner.isLoading=!this.mySpinner.isLoading,this.nameTypeOfArgiMk=this.$route.params.nameTypeOfArgi,this.productByType()}},Dt={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("v-container",{attrs:{fluid:"","fill-height":""}},[o("v-layout",{attrs:{"align-center":"","justify-center":""}},[o("v-flex",{staticClass:"pa-5",attrs:{sm12:"",md12:"",lg12:""}},[o("v-card",{attrs:{elevation:12}},[t.showAmount?o("v-img",{attrs:{align:"center",height:"250px",gradient:"to bottom, rgba(0,0,0,.1), rgba(0,0,0,.2)",src:r("LXWu")("./"+t.$route.params.nameTypeOfArgi+".jpeg")},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)},[t._v(" "),o("v-container",{attrs:{"fill-height":""}},[o("v-row",{staticClass:"mx-auto",attrs:{justify:"center",align:"center"}},[o("v-col",{attrs:{cols:"12",sm:"4",lg:"12"}},[o("h1",{staticClass:"white--text display-2"},[t._v("\n "+t._s(t.$route.params.nameTypeOfArgi)+"\n ")])])],1)],1)],1):t._e()],1),t._v(" "),o("v-row",{staticClass:"mt-2",attrs:{cols:"12"}},[t.showAmount&&t.$vuetify.breakpoint.smAndUp?o("v-col",{attrs:{cols:"6"}},[o("v-card",{attrs:{elevation:12}},[o("v-img",{attrs:{height:"650",align:"center",src:r("jBLA")("./"+t.$route.params.nameTypeOfArgi+".jpeg")},scopedSlots:t._u([{key:"placeholder",fn:function(){return[o("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[o("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)})],1)],1):t._e(),t._v(" "),t.showAmount?o("v-col",[o("v-card",{staticClass:"mx-auto",attrs:{tile:""}},[o("v-toolbar",{attrs:{color:"primary",dark:""}},[o("v-icon",{staticClass:"mr-2",on:{click:function(e){return t.$router.go(-1)}}},[t._v("mdi-arrow-left-thick")]),t._v(" "),o("v-icon",{staticClass:"mr-2"},[t._v("mdi-barn")]),t._v(" "),o("v-toolbar-title",[t._v("สินค้าประเภท "+t._s(t.nameTypeOfArgiMk))])],1),t._v(" "),o("v-list",[0!==t.productMk.length?o("v-list-item-group",{attrs:{color:"primary"}},t._l(t.productMk,function(e){return o("v-list-item",{key:e.idAgri,on:{click:function(r){return t.itemClick(e.idAgri,e.nameArgi)}}},[o("v-list-item-content",[o("v-list-item-title",{domProps:{textContent:t._s(e.idAgri)}})],1)],1)}),1):o("v-list-item-group",[o("v-list-item",[o("v-list-item-content",[o("v-list-item-title",[t._v("\n ไม่มีสินค้า\n ")])],1)],1)],1)],1)],1)],1):t._e(),t._v(" "),t.showDetails?o("v-row",{attrs:{md:"12"}},[o("v-col",{attrs:{cols:"12"}},[o("l-map",{ref:"productMap",staticStyle:{"z-index":"0",height:"400px",width:"100%"},attrs:{zoom:t.zoom,center:t.center},on:{"update:zoom":t.zoomUpdated,"update:center":t.centerUpdated,"update:bounds":t.boundsUpdated}},[o("l-tile-layer",{attrs:{url:t.url}}),t._v(" "),t._l(t.markers,function(e){return o("l-marker",{key:e.id,attrs:{visible:e.visible,"lat-lng":e.position,icon:e.icon},on:{"update:latLng":function(r){return t.$set(e,"position",r)},"update:lat-lng":function(r){return t.$set(e,"position",r)},click:function(r){return t.showProduct(e.idSellerMember,e.idAgri,e.lat,e.lng)}}},[o("l-tooltip",{attrs:{content:e.tooltip,options:{permanent:!0}}})],1)})],2)],1),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("v-card",{staticClass:"mx-auto",attrs:{tile:""}},[o("v-toolbar",{attrs:{color:"primary",dark:""}},[o("v-icon",{staticClass:"mr-2",on:{click:t.back}},[t._v("mdi-arrow-left-thick")]),t._v(" "),o("v-toolbar-title",[t._v("รายชื่อศูนย์ ["+t._s(t.nameOfArgi||"-")+"]")])],1),t._v(" "),o("v-simple-table",{scopedSlots:t._u([{key:"default",fn:function(){return[o("thead",[o("tr",[o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("ชื่อกลุ่ม")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("จังหวัด")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("ชื่อศูนย์")])])])]),t._v(" "),o("tbody",t._l(t.productByArgiList,function(e,r){return o("tr",{key:r,staticStyle:{cursor:"pointer"},on:{click:function(r){t.showProduct(e.idSellerMember,e.idAgri,parseFloat(e.lat),parseFloat(e.long))}}},[o("td",[t._v(t._s(e.groupName||"-"))]),t._v(" "),o("td",[t._v(t._s(e.provinceName))]),t._v(" "),o("td",[t._v(t._s(e.areaName))])])}),0)]},proxy:!0}],null,!1,3705310401)})],1)],1)],1):t._e(),t._v(" "),t.isShowListProduct?o("v-row",{attrs:{cols:"12"}},[o("v-col",{attrs:{cols:"12"}},[o("l-map",{ref:"productMap",staticStyle:{"z-index":"0",height:"400px",width:"100%"},attrs:{zoom:t.zoom,center:t.center},on:{"update:zoom":t.zoomUpdated,"update:center":t.centerUpdated,"update:bounds":t.boundsUpdated}},[o("l-tile-layer",{attrs:{url:t.url}}),t._v(" "),t._l(t.markers,function(e){return o("l-marker",{key:e.id,attrs:{visible:e.visible,"lat-lng":e.position,icon:e.icon},on:{"update:latLng":function(r){return t.$set(e,"position",r)},"update:lat-lng":function(r){return t.$set(e,"position",r)},click:function(r){return t.showProduct(e.idSellerMember,e.idAgri,e.lat,e.lng,e.areaName)}}},[o("l-tooltip",{attrs:{content:e.tooltip,options:{permanent:!0}}})],1)})],2)],1),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("v-col",[o("v-card",{staticClass:"mx-auto",attrs:{tile:""}},[o("v-toolbar",{attrs:{color:"primary",dark:""}},[o("v-icon",{staticClass:"mr-2",on:{click:function(e){return t.backFromArea()}}},[t._v("mdi-arrow-left-thick")]),t._v(" "),o("v-toolbar-title",[t._v("สินค้าภายในพื้นที่")])],1),t._v(" "),o("v-simple-table",{staticClass:"pa-5",scopedSlots:t._u([{key:"default",fn:function(){return[o("thead",[o("tr",[o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("รูปสินค้า")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("ชื่อสินค้า")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("สายพันธ์")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("รายละเอียดสินค้า")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("ราคา")])]),t._v(" "),o("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[o("h3",[t._v("ชื่อกลุ่ม")])])])]),t._v(" "),o("tbody",t._l(t.productByArea,function(e,r){return o("tr",{key:r,staticStyle:{cursor:"pointer"},on:{click:function(r){return t.productDetail(e.idProductOfMemberMk)}}},[o("td",[o("v-img",{attrs:{width:"100",height:"100",src:e.titleImg,"lazy-src":e.titleImg}})],1),t._v(" "),o("td",[t._v(t._s(e.idAgri))]),t._v(" "),o("td",[t._v(t._s(e.speciesName||"-"))]),t._v(" "),o("td",[t._v(t._s(e.detailOfProduct||"-"))]),t._v(" "),o("td",[t._v("\n "+t._s(e.priceBegin===e.priceEnd?"฿"+e.priceEnd:"฿"+e.priceBegin+" - ฿"+e.priceEnd)+"\n / "+t._s(e.nameUnit)+"\n ")]),t._v(" "),o("td",[t._v(t._s(e.groupName))])])}),0)]},proxy:!0}],null,!1,1964379273)})],1)],1)],1)],1):t._e()],1)],1)],1)],1)},staticRenderFns:[]};var At=r("VU/8")(wt,Dt,!1,function(t){r("+h1q")},"data-v-5f6a86ce",null).exports,Ct={inject:["mySpinner"],data:function(){return{baseUrl:"https://farmtd.hrdi.or.th/farmdd/admin/api/",productMk:[],page:1,perPage:6,contentType:[],contentData:[],newsContent:[],filterImg:[],productContent:[],argiItems:[],selection:0}},computed:{visiblePages:function(){return this.newsContent.slice((this.page-1)*this.perPage,this.page*this.perPage)},visibleContentPages:function(){return this.productContent.slice((this.page-1)*this.perPage,this.page*this.perPage)}},methods:{getTypeOfArgi:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllTypeOfArgiTD.php").then(function(e){e.data.typeOfArgi.length>0&&(t.argiItems=e.data.typeOfArgi,t.argiItems=t.argiItems.filter(function(t,e){return null!==t.nameTypeOfArgi_MK}),t.mySpinner.isLoading=!t.mySpinner.isLoading,console.log("getAllTypeOfArgiTD",t.argiItems))}).catch(function(t){console.log(t)})},toThaiDateString:function(t){var e=t.getFullYear()+543,r=["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม.","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"][t.getMonth()];return t.getDate()+" "+r+" "+e+" "+t.getHours().toString().padStart(2,"0")+":"+t.getMinutes().toString().padStart(2,"0")+":"+t.getSeconds().toString().padStart(2,"0")+" น."}},mounted:function(){this.mySpinner.isLoading=!this.mySpinner.isLoading,this.getTypeOfArgi()}},_t={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("div",[o("v-container",[o("v-row",{attrs:{"no-gutters":""}},[o("v-col",{attrs:{cols:12}},[o("v-card-text",{attrs:{tile:"",outlined:""}},[o("v-card-title",[o("h3",[t._v("หมวดสินค้าหลัก")])]),t._v(" "),o("v-divider"),t._v(" "),o("div",{staticClass:"row"},t._l(t.argiItems,function(e,a){return o("v-flex",{key:a,staticClass:"lg5-custom pa-3",attrs:{md4:""}},[o("v-hover",{attrs:{"open-delay":"200"},scopedSlots:t._u([{key:"default",fn:function(a){var i=a.hover;return[o("v-card",{attrs:{elevation:i?16:2}},[o("v-img",{staticClass:"white--text align",attrs:{src:r("jBLA")("./"+e.nameTypeOfArgi_MK+".jpeg"),height:"200px"}}),t._v(" "),o("v-card-text",[o("v-row",{attrs:{justify:"center"}},[o("h2",{staticClass:"green--text"},[t._v("\n "+t._s(e.nameTypeOfArgi_MK)+"\n ")])])],1),t._v(" "),o("div",{staticClass:"text-center"},[o("v-btn",{staticClass:"ma-2",attrs:{to:{name:"TypeList",params:{idTypeOfArgi:e.idTypeOfArgi,nameTypeOfArgi:e.nameTypeOfArgi_MK}},outlined:"",color:"info"}},[t._v("\n ดูเพิ่มเติม\n ")])],1)],1)]}}],null,!0)})],1)}),1)],1)],1)],1),t._v(" "),t._l(t.filterImg,function(t,e){return o("div",{key:e,staticClass:"col-md-3 col-sm-6 col-xs-12"},[o("v-img",{attrs:{height:"200px",src:t.imgTitle}})],1)})],2)],1)},staticRenderFns:[]},Tt=r("VU/8")(Ct,_t,!1,null,null,null).exports,kt={props:["file","imgIndex","chooseTitle"],data:function(){return{dataUrl:null,imgFile:this.file}},methods:{},created:function(){var t=this,e=new FileReader;console.log(this.imgFile),e.addEventListener("load",function(){t.dataUrl=e.result},!1),e.readAsDataURL(this.file)}},jt={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-col",{attrs:{md:"4"}},[t.dataUrl?r("v-img",{attrs:{src:t.dataUrl,alt:t.file.name}}):t._e(),t._v(" "),r("v-btn",{staticClass:"mt-2",attrs:{color:t.file.name===t.chooseTitle?"primary":""},on:{click:function(e){return t.$emit("chooseTitleImg",t.file.name,t.imgIndex)}}},[t._v("\n รูปปก\n ")]),t._v(" "),r("span",[t._v(t._s(t.file.index))])],1)},staticRenderFns:[]},Ot=r("VU/8")(kt,jt,!1,null,null,null).exports,Lt={components:{imgPreview:Ot},inject:["mySpinner"],data:function(){var t;return t={showAddProductBtn:!1,imagePreviewURL:"",isLoading:!1,isFormValid:!1,showContent:{seller:!1,buyer:!1,product:!1},activeBtn:0,typeOfArgi:[],argiTd:[],mini:!1,drawer:!0,userInfo:[],productMk:[],groupName:""},D()(t,"isLoading",!1),D()(t,"baseUrl","https://farmtd.hrdi.or.th/farmdd/admin/api/"),t},computed:{cardWidth:function(){return this.mini?56:256}},methods:{editProduct:function(t){this.$router.push({name:"EditProduct",params:{idProductOfMemberMk:t}})},errMsg:function(t){this.$swal.fire({icon:"info",title:t,showConfirmButton:!0,allowOutsideClick:!1}),this.remove(this.productForm.img.length-1)},findProductName:function(t){this.productByArgiType=[],this.productByArgiType=this.argiTd.filter(function(e){return e.TypeOfArgiIdTypeOfArgi===t}),console.log("productByArgiType",this.productByArgiType)},showAddProduct:function(){this.showContent={seller:!1,buyer:!1,product:!0}},getUserInfo:function(){var t=this;this.mySpinner.isLoading=!0;var e=new FormData;e.append("username",localStorage.user),"Seller"===localStorage.typeOfMember?(e.append("table","SellerMember_MK"),h.a.post(this.baseUrl+"member/postFindSellerInfo.php",e).then(function(e){0!==e.data.sellerUser&&(t.userInfo=e.data.sellerUser[0],t.userInfo.sellerImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/profile/"+e.data.sellerUser[0].sellerImg,t.showContent.seller=!0,"showProduct"===localStorage.showProduct&&(t.showContent.product=!0,t.showContent.buyer=!1,t.showContent.seller=!1),localStorage.showProduct="",console.log("userInfo",t.userInfo))}).catch(function(e){console.log(e),t.mySpinner.isLoading=!1})):h.a.post(this.baseUrl+"member/postFindUserInfo.php",e).then(function(e){0!==e.data.buyerUser&&(t.userInfo=e.data.buyerUser[0],t.userInfo.buyerImg="https://farmtd.hrdi.or.th/farmdd/admin/upload/profile/"+e.data.buyerUser[0].buyerImg,t.showContent.buyer=!0,t.mySpinner.isLoading=!1,console.log("userInfo",t.userInfo))}).catch(function(e){t.mySpinner.isLoading=!1,console.log(e)})},checkLogin:function(){""!==localStorage.idMember&&null!==localStorage.idMember&&void 0!==localStorage.idMember||this.$router.push({name:"Login"})},showUserProfile:function(){this.showContent.product=!1,"Seller"===localStorage.typeOfMember?this.showContent.seller=!0:this.showContent.buyer=!0},productMember:function(){var t=this;this.mySpinner.isLoading=!0;var e=localStorage.idMember,r=new FormData;r.append("idSellerMemberMk",e),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getProductBySeller.php",r).then(function(e){t.productMk=e.data.productMk,(t.groupName=""!==t.productMk[0].groupName)&&(t.groupName=t.productMk[0].groupName),console.log("productMk",t.productMk),t.mySpinner.isLoading=!1}).catch(function(e){t.mySpinner.isLoading=!1,console.log(e)})},scrollToTop:function(){window.scrollTo(0,0)}},mounted:function(){this.checkLogin(),this.getUserInfo(),"Seller"===localStorage.typeOfMember?(this.productMember(),this.showAddProductBtn=!0):this.showAddProductBtn=!1,this.scrollToTop()},created:function(){}},Ft={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{staticClass:"ma-0 d-flex flex-row align-start pa-0 align-stretch",attrs:{fluid:""}},[t.$vuetify.breakpoint.xsOnly?r("v-container",{attrs:{fluid:""}},[r("v-bottom-navigation",{staticStyle:{"overflow-x":"scroll"},attrs:{value:t.activeBtn,color:"primary","active-class":"active",horizontal:""}},[r("v-btn",{staticClass:"body-2 font-weight-bold",on:{click:function(e){return t.showUserProfile()}}},[r("span",{staticClass:"mt-1"},[t._v("ข้อมูลสมาชิก")])]),t._v(" "),t.showAddProductBtn?r("v-btn",{staticClass:"body-2 font-weight-bold",on:{click:function(e){return t.showAddProduct()}}},[r("span",{staticClass:"mt-1"},[t._v("สินค้า")])]):t._e()],1),t._v(" "),t.showContent.seller?r("v-col",[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{"max-width":"500"}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-avatar",{staticClass:"my-3",attrs:{size:"150"}},[r("img",{attrs:{src:t.userInfo.sellerImg}})]),t._v(" "),r("v-card-text",{staticClass:"headline text-md-center py-0"},[t._v(t._s(t.userInfo.firstName+t.userInfo.lastName))]),t._v(" "),r("v-card-text",{staticClass:"text-md-center pt-1 pb-4"},[t._v("\n ประเภทการจำหน่าย: "+t._s(t.userInfo.nameTypeOfSeller)+"\n ")])],1),t._v(" "),r("v-card-text",{staticClass:"text--primary text-center ma-2"},[r("v-row",[r("v-col",[t._v("เลขบัตรประชาชน : "+t._s(t.userInfo.idCard||"-"))]),t._v(" "),r("v-col",[t._v("หมายเลขโทรศัพท์ "+t._s(t.userInfo.phoneNumber||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("จังหวัด "+t._s(t.userInfo.provinceName||"-"))]),t._v(" "),r("v-col",[t._v("อำเภอ "+t._s(t.userInfo.amphurName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("หมู่ "+t._s(t.userInfo.moo||"-"))]),t._v(" "),r("v-col",[t._v("ถนน "+t._s(t.userInfo.road||"-"))]),t._v(" "),r("v-col",[t._v("ตำบล "+t._s(t.userInfo.tambolName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("พื้นที่โครงการ "+t._s(t.userInfo.areaName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("ชนิดสินค้าที่ต้องการจำหน่าย\n "+t._s(t.userInfo.productType||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("สถานะสมาชิก :\n "+t._s("1"===t.userInfo.statusOfMember?"ได้รับการยืนยันแล้ว":"ยังไม่ได้รับการยืนยัน"))])],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{color:"orange",text:"",to:"/editseller"}},[t._v("\n แก้ไขข้อมูล\n ")])],1)],1)],1)],1):t._e(),t._v(" "),t.showContent.buyer?r("v-col",[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400"}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-avatar",{staticClass:"my-3",attrs:{size:"150"}},[r("img",{attrs:{src:t.userInfo.buyerImg}})]),t._v(" "),r("v-card-text",{staticClass:"headline text-md-center py-0"},[t._v(t._s(t.userInfo.firstName+" "+t.userInfo.lastName))]),t._v(" "),r("v-card-text",{staticClass:"text-md-center pt-1 pb-4"},[t._v("ประเภทการจำหน่าย:\n "+t._s("Normal"===t.userInfo.typeOfMember?"สมาชิกทั่วไป":"สมาชิกผู้ซื้อ"))])],1),t._v(" "),r("v-card-text",{staticClass:"text--primary text-center ma-2"},[r("v-row",[r("v-col",[t._v("เลขบัตรประชาชน : "+t._s(t.userInfo.idCard||"-"))]),t._v(" "),r("v-col",[t._v("หมายเลขโทรศัพท์ "+t._s(t.userInfo.phoneNumber||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("จังหวัด "+t._s(t.userInfo.provinceName||"-"))]),t._v(" "),r("v-col",[t._v("อำเภอ "+t._s(t.userInfo.amphurName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("หมู่ "+t._s(t.userInfo.moo||"-"))]),t._v(" "),r("v-col",[t._v("ถนน "+t._s(t.userInfo.road||"-"))]),t._v(" "),r("v-col",[t._v("ตำบล "+t._s(t.userInfo.tambolName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("พื้นที่โครงการ "+t._s(t.userInfo.areaName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("ชนิดสินค้าที่ต้องการจำหน่าย\n "+t._s(t.userInfo.productType||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("สถานะสมาชิก :\n "+t._s("1"===t.userInfo.productType?"ได้รับการยืนยันแล้ว":"ยังไม่ได้รับการยืนยัน"))])],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{color:"orange",text:"",to:"/editprofile"}},[t._v("\n แก้ไขข้อมูล\n ")])],1)],1)],1)],1):t._e(),t._v(" "),t.showContent.product?r("v-row",{staticClass:"mt-3 mx-auto"},[r("v-btn",{attrs:{dark:"",color:"green",to:"addproduct"}},[t._v("เพิ่มสินค้า")]),t._v(" "),r("v-container",{attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{tile:""}},[r("v-toolbar",{attrs:{color:"primary",dark:""}},[r("v-toolbar-title",[t._v("รายการสินค้า")])],1),t._v(" "),r("v-simple-table",{staticClass:"pa-5",scopedSlots:t._u([{key:"default",fn:function(){return[r("thead",[r("tr",[r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("รูปสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ชื่อสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ชื่อองค์กร")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ราคา")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ประเภทสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ประเภทผู้ขาย")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("แก้ไขสินค้า")])])])]),t._v(" "),r("tbody",t._l(t.productMk,function(e,o){return r("tr",{key:o},[r("td",[r("v-img",{attrs:{width:"100",height:"100",src:e.titleImg,"lazy-src":e.titleImg}})],1),t._v(" "),r("td",[t._v(t._s(e.idAgri))]),t._v(" "),r("td",[t._v(t._s(e.groupName))]),t._v(" "),r("td",[t._v("\n "+t._s(e.priceBegin===e.priceEnd?"฿"+e.priceEnd:"฿"+e.priceBegin+" - ฿"+e.priceEnd)+"\n / "+t._s(e.nameUnit)+"\n ")]),t._v(" "),r("td",[t._v(t._s(e.nameTypeOfArgi))]),t._v(" "),r("td",[t._v(t._s(e.nameTypeOfSeller))]),t._v(" "),r("td",[r("v-btn",{attrs:{color:"primary"},on:{click:function(r){return t.editProduct(e.idProductOfMemberMk)}}},[t._v("แก้ไขสินค้า")])],1)])}),0)]},proxy:!0}],null,!1,171388757)})],1)],1)],1):t._e()],1):t._e(),t._v(" "),t.$vuetify.breakpoint.smAndUp?r("v-row",{attrs:{cols:"12"}},[r("v-col",{staticClass:"ma-0 pt-0 pb-0",attrs:{md:"2"}},[r("v-card",{attrs:{tile:"",height:"100%",width:"200"}},[r("v-navigation-drawer",{staticClass:"pa-1",attrs:{color:"primary",absolute:"",permanent:"",left:"","mini-variant":t.mini,dark:""},on:{"update:miniVariant":function(e){t.mini=e},"update:mini-variant":function(e){t.mini=e}},scopedSlots:t._u([{key:"prepend",fn:function(){return[r("v-list-item",{staticClass:"px-2"},[r("v-list-item-avatar",[r("img",{attrs:{src:t.userInfo.sellerImg?t.userInfo.sellerImg:t.userInfo.buyerImg}})]),t._v(" "),r("v-list-item-content",[r("v-list-item-title",[t._v(t._s(t.userInfo.firstName))])],1)],1)]},proxy:!0}],null,!1,912292182),model:{value:t.drawer,callback:function(e){t.drawer=e},expression:"drawer"}},[t._v(" "),r("v-divider"),t._v(" "),r("v-list",[r("v-list-item",{on:{click:function(e){return t.showUserProfile()}}},[r("v-list-item-icon",[r("v-icon",[t._v("mdi-account-box")])],1),t._v(" "),r("v-list-item-content",[r("v-list-item-title",[t._v("ข้อมูลสมาชิก")])],1)],1),t._v(" "),t.showAddProductBtn?r("v-list-item",{attrs:{link:""},on:{click:function(e){return t.showAddProduct()}}},[r("v-list-item-icon",[r("v-icon",[t._v("mdi-basket")])],1),t._v(" "),r("v-list-item-content",[r("v-list-item-title",[t._v("สินค้า")])],1)],1):t._e()],1)],1)],1)],1),t._v(" "),t.showContent.seller?r("v-col",[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{"max-width":"500"}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-avatar",{staticClass:"my-3",attrs:{size:"150"}},[r("img",{attrs:{src:t.userInfo.sellerImg}})]),t._v(" "),r("v-card-text",{staticClass:"headline text-md-center py-0"},[t._v(t._s(t.userInfo.firstName+t.userInfo.lastName))]),t._v(" "),r("v-card-text",{staticClass:"text-md-center pt-1 pb-4"},[t._v("ประเภทการจำหน่าย: "+t._s(t.userInfo.nameTypeOfSeller))])],1),t._v(" "),r("v-card-text",{staticClass:"text--primary text-center ma-2"},[r("v-row",[r("v-col",[t._v("เลขบัตรประชาชน : "+t._s(t.userInfo.idCard||"-"))]),t._v(" "),r("v-col",[t._v("หมายเลขโทรศัพท์ "+t._s(t.userInfo.phoneNumber||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("จังหวัด "+t._s(t.userInfo.provinceName||"-"))]),t._v(" "),r("v-col",[t._v("อำเภอ "+t._s(t.userInfo.amphurName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("หมู่ "+t._s(t.userInfo.moo||"-"))]),t._v(" "),r("v-col",[t._v("ถนน "+t._s(t.userInfo.road||"-"))]),t._v(" "),r("v-col",[t._v("ตำบล "+t._s(t.userInfo.tambolName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("พื้นที่โครงการ "+t._s(t.userInfo.areaName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("ชนิดสินค้าที่ต้องการจำหน่าย\n "+t._s(t.userInfo.productType||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("สถานะสมาชิก :\n "+t._s("1"===t.userInfo.statusOfMember?"ได้รับการยืนยันแล้ว":"ยังไม่ได้รับการยืนยัน"))])],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{color:"orange",text:"",to:"/editseller"}},[t._v("\n แก้ไขข้อมูล\n ")])],1)],1)],1)],1):t._e(),t._v(" "),t.showContent.buyer?r("v-col",[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{"max-width":"400"}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-avatar",{staticClass:"my-3",attrs:{size:"150"}},[r("img",{attrs:{src:t.userInfo.buyerImg}})]),t._v(" "),r("v-card-text",{staticClass:"headline text-md-center py-0"},[t._v(t._s(t.userInfo.firstName+" "+t.userInfo.lastName))]),t._v(" "),r("v-card-text",{staticClass:"text-md-center pt-1 pb-4"},[t._v("ประเภทการจำหน่าย:\n "+t._s("Normal"===t.userInfo.typeOfMember?"สมาชิกทั่วไป":"สมาชิกผู้ซื้อ"))])],1),t._v(" "),r("v-card-text",{staticClass:"text--primary text-center ma-2"},[r("v-row",[r("v-col",[t._v("เลขบัตรประชาชน : "+t._s(t.userInfo.idCard||"-"))]),t._v(" "),r("v-col",[t._v("หมายเลขโทรศัพท์ "+t._s(t.userInfo.phoneNumber||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("จังหวัด "+t._s(t.userInfo.provinceName||"-"))]),t._v(" "),r("v-col",[t._v("อำเภอ "+t._s(t.userInfo.amphurName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("หมู่ "+t._s(t.userInfo.moo||"-"))]),t._v(" "),r("v-col",[t._v("ถนน "+t._s(t.userInfo.road||"-"))]),t._v(" "),r("v-col",[t._v("ตำบล "+t._s(t.userInfo.tambolName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("พื้นที่โครงการ "+t._s(t.userInfo.areaName||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("ชนิดสินค้าที่ต้องการจำหน่าย\n "+t._s(t.userInfo.productType||"-"))])],1),t._v(" "),r("v-row",[r("v-col",[t._v("สถานะสมาชิก :\n "+t._s("1"===t.userInfo.productType?"ได้รับการยืนยันแล้ว":"ยังไม่ได้รับการยืนยัน"))])],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{color:"orange",text:"",to:"/editprofile"}},[t._v("\n แก้ไขข้อมูล\n ")])],1)],1)],1)],1):t._e(),t._v(" "),t.showContent.product?r("v-col",{staticClass:"mt-3 mx-auto",attrs:{cols:"8"}},[r("v-btn",{attrs:{dark:"",color:"green",to:"addproduct"}},[t._v("เพิ่มสินค้า")]),t._v(" "),r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-card",{staticClass:"mx-auto",attrs:{tile:""}},[r("v-toolbar",{attrs:{color:"primary",dark:""}},[r("v-toolbar-title",[t._v("รายการสินค้า")])],1),t._v(" "),r("v-simple-table",{staticClass:"pa-5",scopedSlots:t._u([{key:"default",fn:function(){return[r("thead",[r("tr",[r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("รูปสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ชื่อสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ชื่อองค์กร")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ราคา")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ประเภทสินค้า")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("ประเภทผู้ขาย")])]),t._v(" "),r("th",{staticClass:"text-left font-weight-black indigo--text text--darken-3"},[r("h3",[t._v("แก้ไขสินค้า")])])])]),t._v(" "),r("tbody",t._l(t.productMk,function(e,o){return r("tr",{key:o},[r("td",[r("v-img",{attrs:{width:"100",height:"100",src:e.titleImg,"lazy-src":e.titleImg}})],1),t._v(" "),r("td",[t._v(t._s(e.idAgri))]),t._v(" "),r("td",[t._v(t._s(e.groupName))]),t._v(" "),r("td",[t._v("\n "+t._s(e.priceBegin===e.priceEnd?"฿"+e.priceEnd:"฿"+e.priceBegin+" - ฿"+e.priceEnd)+"\n / "+t._s(e.nameUnit)+"\n ")]),t._v(" "),r("td",[t._v(t._s(e.nameTypeOfArgi))]),t._v(" "),r("td",[t._v(t._s(e.nameTypeOfSeller))]),t._v(" "),r("td",[r("v-btn",{attrs:{color:"primary"},on:{click:function(r){return t.editProduct(e.idProductOfMemberMk)}}},[t._v("แก้ไขสินค้า")])],1)])}),0)]},proxy:!0}],null,!1,171388757)})],1)],1)],1):t._e()],1):t._e()],1)},staticRenderFns:[]},zt=r("VU/8")(Lt,Ft,!1,null,null,null).exports;var St,Et={data:function(){var t;return t={imagePreviewURL:null,isFormValid:!1,prefix:[],confirmPassword:"",isUsernameExist:!1,buyerForm:{prefix:"",firstName:"",lastName:"",username:"",phoneNumber:"",email:"",idCard:"",password:"",img:[],provinceCode:"",typeOfMember:"",amphurCode:"",tambolCode:"",lineId:"",postcode:"",facebookName:"",address:"",moo:"",road:"",questionOfVisit:"",questionOfObjective:""},targetName:[],targetFilter:[],allProvince:[],buyerAmphur:[],buyerTambol:[],showEtc:{visit:!1,objective:!1}},D()(t,"isUsernameExist",!1),D()(t,"baseUrl","https://farmtd.hrdi.or.th/farmdd/admin/api/"),D()(t,"firstNameRules",[function(t){return!!t||"กรุณากรอกชื่อ"}]),D()(t,"lastNameRules",[function(t){return!!t||"กรุณากรอกนามสกุล"}]),D()(t,"emailRules",[function(t){return/.+@.+/.test(t)||"อีเมลต้องอยู่ในรูปแบบที่ถูกต้อง"}]),D()(t,"phoneRules",[function(t){return!t.length<10||"หมายเลขโทรศัพท์ต้องมีจำนวน 10 หลัก"},function(t){return!!t||"กรุณากรอกหมายเลขโทรศัพท์"},function(t){return/^0[0-9]{9}/.test(t)||"หมายเลขโทรศัพท์ต้องอยู่ในรูปแบบที่ถูกต้อง"}]),D()(t,"passwordRules",[function(t){return!!t||"กรุณากรอกรหัสผ่าน"},function(t){return/[A-Z]+/.test(t)||"ต้องมีตัวอักษรตัวใหญ่ในรหัสผ่าน"},function(t){return/[0-9]/g.test(t)||"ตัองมีตัวเลขในรหัสผ่าน"},function(t){return t.length>=6||"รหัสผ่านต้องมีอย่างน้อย 6 ตัว"},function(t){return/^[a-zA-Z0-9äöüÄÖÜ]*$/.test(t)||"ไม่อนุญาตให้ใช้ตัวอักษรพิเศษ"},function(t){return(t||"").indexOf(" ")<0||"ไม่อนุญาตให้ใช้รหัสผ่านที่มีช่องว่าง"}]),t},methods:{checkUsername:function(t){var e=this;this.isUsernameExist=!1;var r=new FormData;r.append("username",t);var o={};r.forEach(function(t,e){o[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/checkUsername.php",ut()(o)).then(function(t){t.data.username[0].username.length>0&&(e.isUsernameExist=!0)})},previewImg:function(t){var e=t;this.buyerForm.img=e,e?(this.imagePreviewURL=URL.createObjectURL(e),URL.revokeObjectURL(e)):this.imagePreviewURL=null},submitForm:function(){var t=this;if(console.log(this.buyerForm),""!==this.buyerForm.prefix)if(""!==this.buyerForm.firstName)if(""!==this.buyerForm.lastName)if(""!==this.buyerForm.gender)if(""!==this.buyerForm.username)if(this.buyerForm.username.indexOf(" ")>=0&&console.log("ไม่อนุญาติให้มีช่องว่างในรหัสผ่าน"),""!==this.buyerForm.password)if(""!==this.buyerForm.confirmPassword)if(""!==this.buyerForm.email)if(""!==this.buyerForm.phoneNumber)if(""!==this.buyerForm.provinceCode)if(""!==this.buyerForm.amphurCode)if(""!==this.buyerForm.tambolCode)if(""!==this.buyerForm.questionOfVisit&&""!==this.buyerForm.questionOfObjective){var e=new FormData;e.append("address",this.buyerForm.address),e.append("amphurCode",this.buyerForm.amphurCode),e.append("email",this.buyerForm.email),e.append("facebookName",this.buyerForm.facebookName),e.append("firstName",this.buyerForm.firstName),e.append("idCard",this.buyerForm.idCard),e.append("firstName",this.buyerForm.firstName),e.append("gender",this.buyerForm.gender),e.append("img",this.buyerForm.img),e.append("typeOfMember",this.buyerForm.typeOfMember),e.append("lastName",this.buyerForm.lastName),e.append("lineId",this.buyerForm.lineId),e.append("moo",this.buyerForm.moo),e.append("postcode",this.buyerForm.postcode),e.append("password",this.buyerForm.password),e.append("phoneNumber",this.buyerForm.phoneNumber),e.append("statusOfMember",this.buyerForm.statusOfMember),e.append("prefix",this.buyerForm.prefix),e.append("provinceCode",this.buyerForm.provinceCode),e.append("questionOfObjective",this.buyerForm.questionOfObjective),e.append("questionOfVisit",this.buyerForm.questionOfVisit),e.append("road",this.buyerForm.road),e.append("tambolCode",this.buyerForm.tambolCode),e.append("username",this.buyerForm.username);var r={};e.forEach(function(t,e){console.log(t),r[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/member/postUpdateBuyer.php",e,{headers:{"Content-Type":"multipart/form-data"}}).then(function(e){"True"===e.data?(console.log(e),t.$swal.fire({icon:"success",title:"แก้ไขสมาชิกทั่วไป / ผู้ซื้อสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})):t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถแก้ไขสมาชิกได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})})}else this.errAlert("กรุณาเลือกเหตุผล");else this.errAlert("กรุณาเลือกตำบล");else this.errAlert("กรุณาเลือกอำเภอ");else this.errAlert("กรุณาเลือกจังหวัด");else this.errAlert("กรุณากรอกหมายเลขโทรศัพท์");else this.errAlert("กรุณากรอกอีเมล");else this.errAlert("กรุณายืนยัน Password");else this.errAlert("กรุณากรอก Password");else this.errAlert("กรุณากรอก Username");else this.errAlert("กรุณากรอกเพศ");else this.errAlert("กรุณากรอกนามสกุล");else this.errAlert("กรุณากรอกชื่อ");else this.errAlert("กรุณาเลือกคำนำหน้า")},getPrefix:function(){var t=this;h.a.get(this.baseUrl+"getPrefix.php").then(function(e){t.prefix=e.data.prefix,console.log("prefix",t.prefix)})},checkLogin:function(){""!==localStorage.idMember&&null!==localStorage.idMember&&void 0!==localStorage.idMember||this.$router.push({name:"Login"})},questionBuyer:function(t){this.showEtc.visit="อื่น ๆ"===t},questionObjBuyer:function(t){this.showEtc.objective="อื่น ๆ"===t},onFileChange:function(t){var e=t.target.files[0];this.buyerForm.img=e,this.url=URL.createObjectURL(e)},errAlert:function(t){this.$swal.fire({icon:"info",title:t,showConfirmButton:!0,allowOutsideClick:!1})},findAmphurBuyer:function(t){var e=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerAmphur.php?provinceId="+t).then(function(t){t.data.buyerAmphur.length>0&&(e.buyerAmphur=t.data.buyerAmphur,e.buyerAmphurOption=e.buyerAmphur.map(function(t){return{value:t.ampCode,text:t.ampT}})),console.log("getBuyerAmphur",e.buyerAmphur)})},getAllProvince:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllprovince.php").then(function(e){e.data.allProvince.length>0&&(t.allProvince=e.data.allProvince,t.provinceOption=t.allProvince.map(function(t){return{value:t.code,text:t.name}})),console.log("getAllprovince",t.allProvince)})},findTambolBuyer:function(t,e){var r=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerTambol.php?provinceId="+t+"&amphurId="+e).then(function(t){t.data.buyerTambol.length>0&&(r.buyerTambol=t.data.buyerTambol,r.buyerTambolOption=r.buyerTambol.map(function(t){return{value:t.tamCode,text:t.tamT}})),console.log("getBuyerTambol",r.buyerTambol)})},getUserInfo:function(){var t=this,e=new FormData;e.append("username",localStorage.user),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/member/postBuyerFromId.php",e).then(function(e){0!==e.data.buyerUser[0]&&(t.imagePreviewURL="https://farmtd.hrdi.or.th/farmdd/admin/upload/profile/"+e.data.buyerUser[0].buyerImg,t.confirmPassword=e.data.buyerUser[0].pass,t.buyerForm={prefix:e.data.buyerUser[0].idPrefix,firstName:e.data.buyerUser[0].firstName,lastName:e.data.buyerUser[0].lastName,username:e.data.buyerUser[0].username,phoneNumber:e.data.buyerUser[0].phoneNumber,email:e.data.buyerUser[0].email,idCard:e.data.buyerUser[0].idCard,password:e.data.buyerUser[0].pass,gender:e.data.buyerUser[0].gender,provinceCode:e.data.buyerUser[0].provinceCode,typeOfMember:e.data.buyerUser[0].typeOfMember,statusOfMember:e.data.buyerUser[0].statusOfMember,amphurCode:e.data.buyerUser[0].ampCode,postcode:e.data.buyerUser[0].postCode,tambolCode:e.data.buyerUser[0].tamCode,lineId:e.data.buyerUser[0].lineID,facebookName:e.data.buyerUser[0].facebookName,address:e.data.buyerUser[0].address,moo:e.data.buyerUser[0].moo,road:e.data.buyerUser[0].road,questionOfVisit:e.data.buyerUser[0].questionOfVisit,questionOfObjective:e.data.buyerUser[0].questionOfObjective},t.findAmphurBuyer(t.buyerForm.provinceCode),t.findTambolBuyer(t.buyerForm.provinceCode,t.buyerForm.amphurCode),"ค้นหาจาก Google"!==t.buyerForm.questionOfVisit&&"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง"!==t.buyerForm.questionOfVisit&&"เพื่อน / คนรู้จักแนะนำ"!==t.buyerForm.questionOfVisit&&(t.showEtc.visit=!0),"เข้ามาเยี่ยมชม"!==t.buyerForm.questionOfObjective&&"เข้ามาซื้อผลผลิต"!==t.buyerForm.questionOfObjective&&"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร"!==t.buyerForm.questionOfObjective&&(t.showEtc.objective=!0),console.log("postBuyerFromId",e.data.buyerUser[0]),console.log("buyerForm",t.buyerForm))}).catch(function(t){console.log(t)})}},mounted:function(){this.checkLogin(),this.getPrefix(),this.getAllProvince(),this.getUserInfo()},created:function(){}},Ut={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{attrs:{fluid:"","fill-height":""}},[r("v-layout",{attrs:{"align-center":"","justify-center":""}},[r("v-flex",{attrs:{xs12:"",sm8:"",lg10:""}},[r("v-row",{attrs:{justify:"center"}},[r("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[r("v-card",{ref:"form"},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-toolbar-title",[t._v("สมัครสมาชิกสำหรับสมาชิกทั่วไป / ผู้ซื้อ")])],1),t._v(" "),r("v-card-text",[r("v-col",{attrs:{cols:"12"}},[r("v-row",[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-account-box","item-text":"prefixNameTh","item-value":"idPrefix",items:t.prefix,rules:[function(t){return!!t||"กรุณาเลือกคำนำหน้า"}],label:"คำนำหน้า*",required:""},model:{value:t.buyerForm.prefix,callback:function(e){t.$set(t.buyerForm,"prefix",e)},expression:"buyerForm.prefix"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-account",name:"firstName",label:"ชื่อ*",type:"text",rules:t.firstNameRules},model:{value:t.buyerForm.firstName,callback:function(e){t.$set(t.buyerForm,"firstName",e)},expression:"buyerForm.firstName"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{name:"lastName",label:"นามสกุล*",type:"text",rules:t.lastNameRules},model:{value:t.buyerForm.lastName,callback:function(e){t.$set(t.buyerForm,"lastName",e)},expression:"buyerForm.lastName"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"12",fluid:""}},[r("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n เพศ*\n ")]),t._v(" "),r("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาระบุเพศ"}]},model:{value:t.buyerForm.gender,callback:function(e){t.$set(t.buyerForm,"gender",e)},expression:"buyerForm.gender"}},[r("v-radio",{attrs:{label:"ชาย",value:"ชาย"}}),t._v(" "),r("v-radio",{attrs:{label:"หญิง",value:"หญิง"}})],1)],1)],1),t._v(" "),r("v-row",{attrs:{align:"center",justify:"center"}},[t.imagePreviewURL?r("v-img",{staticClass:"grey lighten-2 mb-2",attrs:{src:t.imagePreviewURL,"lazy-src":t.imagePreviewURL,"aspect-ratio":"1","max-width":"500","max-height":"300"},scopedSlots:t._u([{key:"placeholder",fn:function(){return[r("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[r("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)}):t._e()],1),t._v(" "),r("v-file-input",{attrs:{accept:"image/png, image/jpeg, image/bmp",placeholder:"เลือกรูปภาพประจำตัว",label:"รูปภาพโปรไฟล์","prepend-icon":"mdi-camera"},on:{change:t.previewImg},model:{value:t.buyerForm.img,callback:function(e){t.$set(t.buyerForm,"img",e)},expression:"buyerForm.img"}}),t._v(" "),r("v-text-field",{attrs:{"prepend-icon":"mdi-account-outline",type:"text",rules:[!t.isUsernameExist||"Username ถูกใช้งานไปแล้ว",function(t){return!!t||"กรุณากรอก Username"}],label:"Username*",required:""},on:{keyup:function(e){return t.checkUsername(t.buyerForm.username)}},model:{value:t.buyerForm.username,callback:function(e){t.$set(t.buyerForm,"username",e)},expression:"buyerForm.username"}}),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:t.passwordRules,label:"รหัสผ่าน*",required:""},model:{value:t.buyerForm.password,callback:function(e){t.$set(t.buyerForm,"password",e)},expression:"buyerForm.password"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:[t.buyerForm.password===t.confirmPassword||"รหัสผ่านไม่ตรงกัน",function(t){return!!t||"กรุณายืนยันรหัสผ่าน"}],label:"ยืนยันรหัสผ่าน*",required:""},model:{value:t.confirmPassword,callback:function(e){t.confirmPassword=e},expression:"confirmPassword"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"12"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-email",type:"email",label:"อีเมล",required:""},model:{value:t.buyerForm.email,callback:function(e){t.$set(t.buyerForm,"email",e)},expression:"buyerForm.email"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-phone",counter:"",maxlength:"10",rules:t.phoneRules,label:"หมายเลขโทรศัพท์*",required:""},model:{value:t.buyerForm.phoneNumber,callback:function(e){t.$set(t.buyerForm,"phoneNumber",e)},expression:"buyerForm.phoneNumber"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-account-details",counter:"",maxlength:"13",label:"หมายเลขบัตรประชาชน",required:""},model:{value:t.buyerForm.idCard,callback:function(e){t.$set(t.buyerForm,"idCard",e)},expression:"buyerForm.idCard"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-phone-plus",type:"text",label:"ไลน์ไอดี",required:""},model:{value:t.buyerForm.lineId,callback:function(e){t.$set(t.buyerForm,"lineId",e)},expression:"buyerForm.lineId"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-facebook",type:"text",label:"Facebook",required:""},model:{value:t.buyerForm.facebookName,callback:function(e){t.$set(t.buyerForm,"facebookName",e)},expression:"buyerForm.facebookName"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{label:"บ้านเลขที่",type:"text"},model:{value:t.buyerForm.address,callback:function(e){t.$set(t.buyerForm,"address",e)},expression:"buyerForm.address"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"หมู่ (ถ้ามี)",type:"text"},model:{value:t.buyerForm.moo,callback:function(e){t.$set(t.buyerForm,"moo",e)},expression:"buyerForm.moo"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"ถนน",type:"text"},model:{value:t.buyerForm.road,callback:function(e){t.$set(t.buyerForm,"road",e)},expression:"buyerForm.road"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"รหัสไปรณีย์",type:"text"},model:{value:t.buyerForm.postcode,callback:function(e){t.$set(t.buyerForm,"postcode",e)},expression:"buyerForm.postcode"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"4"}},[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"name","item-value":"code",items:t.allProvince,rules:[function(t){return!!t||"กรุณาเลือกจังหวัด"}],label:"จังหวัด*",required:""},on:{change:function(e){return t.findAmphurBuyer(t.buyerForm.provinceCode)}},model:{value:t.buyerForm.provinceCode,callback:function(e){t.$set(t.buyerForm,"provinceCode",e)},expression:"buyerForm.provinceCode"}})],1),t._v(" "),r("v-col",[r("v-select",{attrs:{"item-text":"ampT","item-value":"ampCode",items:t.buyerAmphur,rules:[function(t){return!!t||"กรุณาเลือกอำเภอ"}],label:"อำเภอ*",required:""},on:{change:function(e){return t.findTambolBuyer(t.buyerForm.provinceCode,t.buyerForm.amphurCode)}},model:{value:t.buyerForm.amphurCode,callback:function(e){t.$set(t.buyerForm,"amphurCode",e)},expression:"buyerForm.amphurCode"}})],1),t._v(" "),r("v-col",[r("v-select",{attrs:{"item-text":"tamT","item-value":"tamCode",items:t.buyerTambol,rules:[function(t){return!!t||"กรุณาเลือกตำบล"}],label:"ตำบล*",required:""},model:{value:t.buyerForm.tambolCode,callback:function(e){t.$set(t.buyerForm,"tambolCode",e)},expression:"buyerForm.tambolCode"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"12",fluid:""}},[r("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ประเภทสมาชิก*\n ")]),t._v(" "),r("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาเลือกประเภทสมาชิก"}]},model:{value:t.buyerForm.typeOfMember,callback:function(e){t.$set(t.buyerForm,"typeOfMember",e)},expression:"buyerForm.typeOfMember"}},[r("v-radio",{attrs:{label:"สมาชิกทั่วไป",value:"Normal"}}),t._v(" "),r("v-radio",{attrs:{label:"สมาชิกผู้ซื้อ",value:"Buyer"}})],1)],1)],1),t._v(" "),r("v-row",{attrs:{md:"12",fluid:""}},[r("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n คุณรู้จักเว็บไซต์ของดีบนดอยได้อย่างไร*\n ")]),t._v(" "),r("v-radio-group",{attrs:{rules:[function(t){return!!t||"กรุณาเลือกตัวเลือก"}]},on:{change:function(e){return t.questionBuyer(t.buyerForm.questionOfVisit)}},model:{value:t.buyerForm.questionOfVisit,callback:function(e){t.$set(t.buyerForm,"questionOfVisit",e)},expression:"buyerForm.questionOfVisit"}},[r("v-radio",{attrs:{label:"ค้นหาจาก Google",value:"ค้นหาจาก Google"}}),t._v(" "),r("v-radio",{attrs:{label:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง",value:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง"}}),t._v(" "),r("v-radio",{attrs:{label:"เพื่อน / คนรู้จักแนะ",value:"เพื่อน / คนรู้จักแนะ"}}),t._v(" "),r("v-radio",{attrs:{label:"อื่น ๆ",value:"อื่น ๆ"}})],1),t._v(" "),t.showEtc.visit?r("v-text-field",{attrs:{outlined:"",type:"text",label:"เหตุผลอื่นๆ",rules:[function(t){return!!t||"กรุณากรอกเหตุผล"}]},model:{value:t.buyerForm.questionOfVisit,callback:function(e){t.$set(t.buyerForm,"questionOfVisit",e)},expression:"buyerForm.questionOfVisit"}}):t._e()],1),t._v(" "),r("v-col",{attrs:{md:"6"}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n วัตถุประสงค์ที่สมัครสมาชิก*\n ")]),t._v(" "),r("v-radio-group",{attrs:{rules:[function(t){return!!t||"กรุณาเลือกตัวเลือก"}]},on:{change:function(e){return t.questionObjBuyer(t.buyerForm.questionOfObjective)}},model:{value:t.buyerForm.questionOfObjective,callback:function(e){t.$set(t.buyerForm,"questionOfObjective",e)},expression:"buyerForm.questionOfObjective"}},[r("v-radio",{attrs:{label:"เข้ามาเยี่ยมชม",value:"เข้ามาเยี่ยมชม"}}),t._v(" "),r("v-radio",{attrs:{label:"เข้ามาซื้อผลผลิต",value:"เข้ามาซื้อผลผลิต"}}),t._v(" "),r("v-radio",{attrs:{label:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร",value:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร"}}),t._v(" "),r("v-radio",{attrs:{label:"อื่น ๆ",value:"อื่น ๆ"}}),t._v(" "),t.showEtc.objective?r("v-text-field",{staticClass:"mt-3",attrs:{outlined:"",type:"text",label:"เหตุผลอื่นๆ",rules:[function(t){return!!t||"กรุณากรอกเหตุผล"}]},model:{value:t.buyerForm.questionOfObjective,callback:function(e){t.$set(t.buyerForm,"questionOfObjective",e)},expression:"buyerForm.questionOfObjective"}}):t._e()],1)],1)],1)],1)],1),t._v(" "),r("v-card-actions",[r("v-row",[r("v-col",[r("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.go(-1)}}},[t._v("ย้อนกลับ")])],1),t._v(" "),r("v-col",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:t.submitForm}},[t._v("ยืนยันการแก้ไข")])],1)],1)],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},Pt=r("VU/8")(Et,Ut,!1,null,null,null).exports,Qt={data:function(){var t;return t={imagePreviewURL:null,isFormValid:!1,checkboxOptions:[{text:"ข้าวและธัญพืซ",value:"ข้าวและธัญพืซ"},{text:"ผักและสมุนไพร",value:"ผักและสมุนไพร"},{text:"ไม้ผล",value:"ไม้ผล"}],checkboxOptions2:[{text:"ไม้ดอกไม้ประดับ",value:"ไม้ดอกไม้ประดับ"},{text:"ผลิตภัณฑ์แปรรูป",value:"ผลิตภัณฑ์แปรรูป"},{text:"ชา กาแฟ และโกโก้",value:"ชา กาแฟ และโกโก้"}],checkboxOptions3:[{text:"หัตถกรรม",value:"หัตถกรรม"},{text:"พืซท้องถิ่น",value:"พืซท้องถิ่น"},{text:"ปศุสัตว์ และประมง",value:"ปศุสัตว์ และประมง"}],confirmPassword:"",isDisabled:!1,url:null,isUsernameExist:!1,passwordMsg:"",targetFilter:[],sellerForm:{idTypeOfSeller:"",prefix:"",firstName:"",lastName:"",username:"",phoneNumber:"",email:"",idCard:"",gender:"",password:"",vProvinceId:"",vLinkAreaDetailId:"",productType:[],address:"",img:[],postcode:"",moo:"",road:"",tambolCode:"",ampCode:"",zipcode:"",statusOfMember:"",groupName:"",shopName:"",brandName:"",lineId:"",facebookName:""},allProvince:[],provinceOption:[],buyerAmphur:[],buyerAmphurOption:[],buyerTambol:[],area:[],sellType:[],amphur:[],tambol:[],province:[]},D()(t,"province",[{provinceName:""}]),D()(t,"buyerTambolOption",[]),D()(t,"vLinkAreaDetailIdOption",[]),D()(t,"idTypeOfSellerdOption",[]),D()(t,"sellType",[]),D()(t,"tambolOption",[]),D()(t,"ampOption",[]),D()(t,"genderOption",[{text:"ชาย",value:"ชาย"},{text:"หญิง",value:"หญิง"}]),D()(t,"qovOption",[{text:"ค้นหาจาก Google",value:"ค้นหาจาก Google"},{text:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง",value:"เข้ามาในเว็บไซต์ของสถาบันวิจัยและพัฒนาพื้นที่สูง"},{text:"เพื่อน / คนรู้จักแนะนำ",value:"เพื่อน / คนรู้จักแนะนำ"},{text:"อื่น ๆ",value:"อื่น ๆ"}]),D()(t,"objOption",[{text:"เข้ามาเยี่ยมชม",value:"เข้ามาเยี่ยมชม"},{text:"เข้ามาซื้อผลผลิต",value:"เข้ามาซื้อผลผลิต"},{text:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร",value:"เข้ามาอ่าน ติดตามข้อมูลข่าวสาร"},{text:"อื่น ๆ",value:"อื่น ๆ"}]),D()(t,"prefix",[]),D()(t,"firstNameRules",[function(t){return!!t||"กรุณากรอกชื่อ"}]),D()(t,"lastNameRules",[function(t){return!!t||"กรุณากรอกนามสกุล"}]),D()(t,"emailRules",[function(t){return/.+@.+/.test(t)||"อีเมลต้องอยู่ในรูปแบบที่ถูกต้อง"}]),D()(t,"phoneRules",[function(t){return!t.length<10||"หมายเลขโทรศัพท์ต้องมีจำนวน 10 หลัก"},function(t){return!!t||"กรุณากรอกหมายเลขโทรศัพท์"},function(t){return/^0[0-9]{9}/.test(t)||"หมายเลขโทรศัพท์ต้องอยู่ในรูปแบบที่ถูกต้อง"}]),D()(t,"passwordRules",[function(t){return!!t||"กรุณากรอกรหัสผ่าน"},function(t){return/[A-Z]+/.test(t)||"ต้องมีตัวอักษรตัวใหญ่ในรหัสผ่าน"},function(t){return/[0-9]/g.test(t)||"ตัองมีตัวเลขในรหัสผ่าน"},function(t){return t.length>=6||"รหัสผ่านต้องมีอย่างน้อย 6 ตัว"},function(t){return/^[a-zA-Z0-9äöüÄÖÜ]*$/.test(t)||"ไม่อนุญาตให้ใช้ตัวอักษรพิเศษ"},function(t){return(t||"").indexOf(" ")<0||"ไม่อนุญาตให้ใช้รหัสผ่านที่มีช่องว่าง"}]),t},methods:(St={previewImg:function(t){var e=t;this.buyerForm.img=e,e?(this.imagePreviewURL=URL.createObjectURL(e),URL.revokeObjectURL(e)):this.imagePreviewURL=null},findTumbolByAmpCode:function(t,e){var r=this;this.tambol=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getTumbolByAmpProv.php?provinceId="+e+"&ampId="+t).then(function(t){t.data.tambol.length>0&&(r.tambol=t.data.tambol,console.log("ampOption",r.ampOption)),console.log("getTumbolByAmpProv",r.tambol)})},findAmphurBuyer:function(t){var e=this;this.buyerAmphur=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerAmphur.php?provinceId="+t).then(function(t){e.buyerAmphur=t.data.buyerAmphur,console.log("getBuyerAmphur",e.buyerAmphur)})},getSellerType:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getSellerType.php").then(function(e){t.sellType=e.data.sellType,t.idTypeOfSellerdOption=t.sellType.map(function(t){return{value:t.idTypeOfSeller,text:t.nameTypeOfSeller}}),console.log("sellType",t.sellType)})},getProvince:function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getVLinkProvince.php").then(function(e){e.data.vLinkProvince.length>0&&(t.province=[].concat(E()(new gt.a(e.data.vLinkProvince.map(function(t){return[t.provinceId,t]})).values()))),t.province=t.province.filter(function(t,e){return"เลย"!==t.provinceName&&"ลำปาง"!==t.provinceName&&"แพร่"!==t.provinceName}),t.provinceOption=t.province.map(function(t){return{value:t.provinceId,text:t.provinceName}}),console.log("province",t.province)})},findAreaByProvince:function(t){var e=this;this.getAmphurByProvince(t),h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getVLinkTargetById.php?provinceId="+t).then(function(t){console.log("vTargetDetail",t.data.vTargetDetail),t.data.vTargetDetail.length>0&&(e.targetName=[].concat(E()(new gt.a(t.data.vTargetDetail.map(function(t){return[t.targetName,t]})).values())),e.getArea(),e.findTumbolByAmpCode(e.sellerForm.ampCode,e.sellerForm.vProvinceId))})},getAmphurByProvince:function(t){var e=this;this.amphur=[],this.tambol=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAmphurById.php?provinceId="+t).then(function(t){t.data.amphur.length>0&&(e.amphur=t.data.amphur,e.ampOption=t.data.amphur.map(function(t){return{value:t.ampCode,text:t.ampT}})),console.log("getAmphurById",e.amphur)})}},D()(St,"findTumbolByAmpCode",function(t,e){var r=this;this.tambol=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getTumbolByAmpProv.php?provinceId="+e+"&ampId="+t).then(function(t){t.data.tambol.length>0&&(r.tambol=t.data.tambol,r.tambolOption=t.data.tambol.map(function(t){return{value:t.tamCode,text:t.tamT}})),console.log("getTumbolByAmpProv",r.tambol)})}),D()(St,"checkUsername",function(t){var e=this;this.isUsernameExist=!1;var r=new FormData;r.append("username",t);var o={};r.forEach(function(t,e){o[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/checkUsername.php",ut()(o)).then(function(t){t.data.username[0].username.length>0&&(e.isUsernameExist=!0)})}),D()(St,"onFileChange",function(t){var e=t.target.files[0];this.sellerForm.img=e,this.url=URL.createObjectURL(e)}),D()(St,"errAlert",function(t){this.$swal.fire({icon:"info",title:t,showConfirmButton:!0,allowOutsideClick:!1})}),D()(St,"getPrefix",function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getPrefix.php").then(function(e){t.prefix=e.data.prefix,console.log(t.prefix)})}),D()(St,"submitForm",function(){var t=this;if(console.log(this.sellerForm),""!==this.sellerForm.prefix)if(""!==this.sellerForm.firstName)if(""!==this.sellerForm.lastName)if(""!==this.sellerForm.gender)if(""!==this.sellerForm.img)if(""!==this.sellerForm.username)if(this.sellerForm.username.indexOf(" ")>=0&&console.log("ไม่อนุญาติให้มีช่องว่างในรหัสผ่าน"),""!==this.sellerForm.password)if(""!==this.sellerForm.confirmPassword)if(""!==this.sellerForm.phoneNumber)if(""!==this.sellerForm.vProvinceId)if(""!==this.sellerForm.ampCode)if(""!==this.sellerForm.tambolCode)if(""!==this.sellerForm.vLinkAreaDetailId)if(""!==this.sellerForm.idTypeOfSeller)if(0!==this.sellerForm.productType.length){var e=new FormData;e.append("address",this.sellerForm.address),e.append("ampCode",this.sellerForm.ampCode),e.append("brandName",this.sellerForm.brandName),e.append("tambolCode",this.sellerForm.tambolCode),e.append("email",this.sellerForm.email),e.append("facebookName",this.sellerForm.facebookName),e.append("firstName",this.sellerForm.firstName),e.append("gender",this.sellerForm.gender),e.append("groupName",this.sellerForm.groupName),e.append("idCard",this.sellerForm.idCard),e.append("idTypeOfSeller",this.sellerForm.idTypeOfSeller),e.append("lastName",this.sellerForm.lastName),e.append("lineId",this.sellerForm.lineId),e.append("moo",this.sellerForm.moo),e.append("img",this.sellerForm.img),e.append("password",this.sellerForm.password),e.append("postcode",this.sellerForm.postcode),e.append("phoneNumber",this.sellerForm.phoneNumber),e.append("prefix",this.sellerForm.prefix),e.append("productType",this.sellerForm.productType),e.append("statusOfMember",this.sellerForm.statusOfMember),e.append("road",this.sellerForm.road),e.append("shopName",this.sellerForm.shopName),e.append("username",this.sellerForm.username),e.append("vLinkAreaDetailId",this.sellerForm.vLinkAreaDetailId),e.append("vProvinceId",this.sellerForm.vProvinceId),e.append("zipcode",this.sellerForm.zipcode);var r={};e.forEach(function(t,e){console.log(t),r[e]=t}),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/member/postUpdateSeller.php",e,{headers:{"Content-Type":"multipart/form-data"}}).then(function(e){"True"===e.data?t.$swal.fire({icon:"success",title:"แก้ไขข้อมูลผู้ขายสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})}):t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถแก้ไขสมาชิกได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})})}else this.errAlert("กรุณาเลือกชนิดสินค้าที่ต้องการจำหน่าย");else this.errAlert("กรุณาเลือกประเภทการจำหน่ายสินค้า");else this.errAlert("กรุณาเลือกชื่อศูนย์");else this.errAlert("กรุณาเลือกตำบล");else this.errAlert("กรุณาเลือกอำเภอ");else this.errAlert("กรุณาเลือกจังหวัด");else this.errAlert("กรุณากรอกหมายเลขโทรศัพท์");else this.errAlert("กรุณายืนยัน Password");else this.errAlert("กรุณากรอก Password");else this.errAlert("กรุณากรอก Username");else this.errAlert("กรุณาเลือกรูปภาพ");else this.errAlert("กรุณากรอกเพศ");else this.errAlert("กรุณากรอกนามสกุล");else this.errAlert("กรุณากรอกชื่อ");else this.errAlert("กรุณาเลือกคำนำหน้า")}),D()(St,"findAmphurBuyer",function(t){var e=this;this.buyerAmphur=[],h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerAmphur.php?provinceId="+t).then(function(t){e.buyerAmphur=t.data.buyerAmphur,e.buyerAmphurOption=e.buyerAmphur.map(function(t){return{value:t.ampCode,text:t.ampT}}),console.log("getBuyerAmphur",e.buyerAmphur)})}),D()(St,"findTambolBuyer",function(t,e){var r=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getBuyerTambol.php?provinceId="+t+"&amphurId="+e).then(function(t){t.data.buyerTambol.length>0&&(r.buyerTambol=t.data.buyerTambol,r.buyerTambolOption=r.buyerTambol.map(function(t){return{value:t.tamCode,text:t.tamT}})),console.log("getBuyerTambol",r.buyerTambol)})}),D()(St,"getArea",function(){var t=this;h.a.get("https://farmtd.hrdi.or.th/farmdd/admin/api/getAllArea.php").then(function(e){t.targetName=t.targetName.map(function(t){return t.targetId}),console.log("targetName",t.targetName),e.data.area.length>0&&(t.area=e.data.area),t.targetFilter=e.data.area.filter(function(e){return t.targetName.includes(e.idArea)}),t.vLinkAreaDetailIdOption=t.targetFilter.map(function(t){return{value:t.idArea,text:t.areaName}}),console.log("targetFilter",t.targetFilter)})}),D()(St,"getSellerFromId",function(){var t=this,e=new FormData;e.append("username",localStorage.user),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/member/postSellerFromId.php",e).then(function(e){if(0!==e.data.sellerUser[0]){var r=e.data.sellerUser[0];t.url="https://farmtd.hrdi.or.th/farmdd/admin/upload/profile/"+e.data.sellerUser[0].sellerImg,t.confirmPassword=r.password,t.sellerForm={idTypeOfSeller:r.idTypeOfSeller_MK,prefix:r.idPrefix,firstName:r.firstName,lastName:r.lastName,username:r.username,phoneNumber:r.phoneNumber,email:r.email,idCard:r.idCard,gender:r.gender,password:r.password,vProvinceId:r.vProvinceId_MK,vLinkAreaDetailId:r.vLinkAreaDetailId_MK,productType:r.productType.split(","),address:r.address,statusOfMember:r.statusOfMember,img:[],postcode:r.postCode,moo:r.moo,road:r.road,tambolCode:r.tambolCode,ampCode:r.ampCode,zipcode:r.postCode,groupName:r.groupName,shopName:r.shopName,brandName:r.brandName,lineId:r.lineID,facebookName:r.facebookName},t.findAreaByProvince(t.sellerForm.vProvinceId),console.log("sellerForm",t.sellerForm)}}).catch(function(t){console.log(t)})}),St),mounted:function(){var t=new URLSearchParams(window.location.search);this.sellerForm.username=t.get("username"),this.getPrefix(),this.getProvince(),this.getSellerType(),this.getSellerFromId()}},Bt={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{attrs:{fluid:"","full-height":""}},[r("v-layout",{attrs:{"align-center":"","justify-center":""}},[r("v-flex",{attrs:{xs12:"",sm8:"",lg10:""}},[r("v-row",{attrs:{justify:"center"}},[r("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[r("v-card",{ref:"form"},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-toolbar-title",[t._v("แก้ไขข้อมูลสมาชิกผู้ขายสินค้า")])],1),t._v(" "),r("v-card-text",[r("v-col",{attrs:{cols:"12"}},[r("v-row",{attrs:{md:"4"}},[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-account-box","item-text":"prefixNameTh","item-value":"idPrefix",items:t.prefix,rules:[function(t){return!!t||"กรุณาเลือกคำนำหน้า"}],label:"คำนำหน้า*",required:""},model:{value:t.sellerForm.prefix,callback:function(e){t.$set(t.sellerForm,"prefix",e)},expression:"sellerForm.prefix"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-account",name:"firstName",label:"ชื่อ*",type:"text",rules:t.firstNameRules},model:{value:t.sellerForm.firstName,callback:function(e){t.$set(t.sellerForm,"firstName",e)},expression:"sellerForm.firstName"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{name:"lastName",label:"นามสกุล*",type:"text",rules:t.lastNameRules},model:{value:t.sellerForm.lastName,callback:function(e){t.$set(t.sellerForm,"lastName",e)},expression:"sellerForm.lastName"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"12",fluid:""}},[r("v-col",{staticClass:"mr-0",attrs:{md:"6"}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n เพศ*\n ")]),t._v(" "),r("v-radio-group",{attrs:{row:"",rules:[function(t){return!!t||"กรุณาระบุเพศ"}]},model:{value:t.sellerForm.gender,callback:function(e){t.$set(t.sellerForm,"gender",e)},expression:"sellerForm.gender"}},[r("v-radio",{attrs:{label:"ชาย",value:"ชาย"}}),t._v(" "),r("v-radio",{attrs:{label:"หญิง",value:"หญิง"}})],1)],1)],1),t._v(" "),r("v-row",{attrs:{align:"center",justify:"center"}},[t.imagePreviewURL?r("v-img",{staticClass:"grey lighten-2 mb-2",attrs:{src:t.imagePreviewURL,"lazy-src":t.imagePreviewURL,"aspect-ratio":"1","max-width":"500","max-height":"300"},scopedSlots:t._u([{key:"placeholder",fn:function(){return[r("v-row",{staticClass:"fill-height ma-0",attrs:{align:"center",justify:"center"}},[r("v-progress-circular",{attrs:{indeterminate:"",color:"grey lighten-5"}})],1)]},proxy:!0}],null,!1,4034393411)}):t._e()],1),t._v(" "),r("v-file-input",{attrs:{accept:"image/png, image/jpeg, image/bmp",placeholder:"เลือกรูปภาพประจำตัว",label:"รูปภาพโปรไฟล์","prepend-icon":"mdi-camera"},on:{change:t.previewImg},model:{value:t.sellerForm.img,callback:function(e){t.$set(t.sellerForm,"img",e)},expression:"sellerForm.img"}}),t._v(" "),r("v-text-field",{attrs:{"prepend-icon":"mdi-account-outline",type:"text",rules:[!t.isUsernameExist||"Username ถูกใช้งานไปแล้ว",function(t){return!!t||"กรุณากรอก Username"}],label:"Username*",required:""},on:{keyup:function(e){return t.checkUsername(t.sellerForm.username)}},model:{value:t.sellerForm.username,callback:function(e){t.$set(t.sellerForm,"username",e)},expression:"sellerForm.username"}}),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:t.passwordRules,label:"รหัสผ่าน*",required:""},model:{value:t.sellerForm.password,callback:function(e){t.$set(t.sellerForm,"password",e)},expression:"sellerForm.password"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-lock",type:"password",counter:"",rules:[t.sellerForm.password===t.confirmPassword||"รหัสผ่านไม่ตรงกัน",function(t){return!!t||"กรุณายืนยันรหัสผ่าน"}],label:"ยืนยันรหัสผ่าน*",required:""},model:{value:t.confirmPassword,callback:function(e){t.confirmPassword=e},expression:"confirmPassword"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"12"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-email",type:"email",label:"อีเมล",required:""},model:{value:t.sellerForm.email,callback:function(e){t.$set(t.sellerForm,"email",e)},expression:"sellerForm.email"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-phone",counter:"",label:"หมายเลขโทรศัพท์",required:""},model:{value:t.sellerForm.phoneNumber,callback:function(e){t.$set(t.sellerForm,"phoneNumber",e)},expression:"sellerForm.phoneNumber"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-account-details",counter:"",maxlength:"13",label:"หมายเลขบัตรประชาชน"},model:{value:t.sellerForm.idCard,callback:function(e){t.$set(t.sellerForm,"idCard",e)},expression:"sellerForm.idCard"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-phone-plus",type:"text",label:"ไลน์ไอดี",required:""},model:{value:t.sellerForm.lineId,callback:function(e){t.$set(t.sellerForm,"lineId",e)},expression:"sellerForm.lineId"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{"prepend-icon":"mdi-facebook",type:"text",label:"Facebook"},model:{value:t.sellerForm.facebookName,callback:function(e){t.$set(t.sellerForm,"facebookName",e)},expression:"sellerForm.facebookName"}})],1)],1),t._v(" "),r("v-container",{staticClass:"my-0",attrs:{fluid:""}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ที่อยู่\n ")]),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{label:"บ้านเลขที่",type:"text"},model:{value:t.sellerForm.address,callback:function(e){t.$set(t.sellerForm,"address",e)},expression:"sellerForm.address"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"หมู่ (ถ้ามี)",type:"text"},model:{value:t.sellerForm.moo,callback:function(e){t.$set(t.sellerForm,"moo",e)},expression:"sellerForm.moo"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"ถนน",type:"text"},model:{value:t.sellerForm.road,callback:function(e){t.$set(t.sellerForm,"road",e)},expression:"sellerForm.road"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"รหัสไปรณีย์",type:"text"},model:{value:t.sellerForm.postcode,callback:function(e){t.$set(t.sellerForm,"postcode",e)},expression:"sellerForm.postcode"}})],1)],1),t._v(" "),r("v-row",{attrs:{md:"4"}},[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"provinceName","item-value":"provinceId",items:t.province,rules:[function(t){return!!t||"กรุณาเลือกจังหวัด"}],label:"จังหวัด*",required:""},on:{change:function(e){return t.findAreaByProvince(t.sellerForm.vProvinceId)}},model:{value:t.sellerForm.vProvinceId,callback:function(e){t.$set(t.sellerForm,"vProvinceId",e)},expression:"sellerForm.vProvinceId"}})],1),t._v(" "),r("v-col",[r("v-select",{attrs:{"item-text":"ampT","item-value":"ampCode",items:t.amphur,rules:[function(t){return!!t||"กรุณาเลือกอำเภอ"}],label:"อำเภอ*",required:""},on:{change:function(e){return t.findTumbolByAmpCode(t.sellerForm.ampCode,t.sellerForm.vProvinceId)}},model:{value:t.sellerForm.ampCode,callback:function(e){t.$set(t.sellerForm,"ampCode",e)},expression:"sellerForm.ampCode"}})],1),t._v(" "),r("v-col",[r("v-select",{attrs:{"item-text":"tamT","item-value":"tamCode",items:t.tambol,rules:[function(t){return!!t||"กรุณาเลือกตำบล"}],label:"ตำบล*",required:""},model:{value:t.sellerForm.tambolCode,callback:function(e){t.$set(t.sellerForm,"tambolCode",e)},expression:"sellerForm.tambolCode"}})],1)],1),t._v(" "),r("v-select",{attrs:{"prepend-icon":"mdi-map-marker-circle","item-text":"areaName","item-value":"idArea",items:t.targetFilter,rules:[function(t){return!!t||"กรุณาเลือกศูนย์"}],label:"ชื่อศูนย์*",required:""},model:{value:t.sellerForm.vLinkAreaDetailId,callback:function(e){t.$set(t.sellerForm,"vLinkAreaDetailId",e)},expression:"sellerForm.vLinkAreaDetailId"}})],1),t._v(" "),r("v-select",{attrs:{"prepend-icon":"mdi-basket","item-text":"nameTypeOfSeller","item-value":"idTypeOfSeller",items:t.sellType,rules:[function(t){return!!t||"กรุณาเลือกลักษณะการจ่ายสินค้า"}],label:"ลักษณะการจำหน่ายสินค้า*",required:""},model:{value:t.sellerForm.idTypeOfSeller,callback:function(e){t.$set(t.sellerForm,"idTypeOfSeller",e)},expression:"sellerForm.idTypeOfSeller"}}),t._v(" "),r("v-text-field",{attrs:{label:"ชื่อกลุ่ม (ถ้ามี)",type:"text"},model:{value:t.sellerForm.groupName,callback:function(e){t.$set(t.sellerForm,"groupName",e)},expression:"sellerForm.groupName"}}),t._v(" "),r("v-row",{attrs:{md:"6"}},[r("v-col",[r("v-text-field",{attrs:{label:"ชื่อร้าน (ถ้ามี)",type:"text"},model:{value:t.sellerForm.shopName,callback:function(e){t.$set(t.sellerForm,"shopName",e)},expression:"sellerForm.shopName"}})],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"ชื่อตราสินค้า (ถ้ามี)",type:"text"},model:{value:t.sellerForm.brandName,callback:function(e){t.$set(t.sellerForm,"brandName",e)},expression:"sellerForm.brandName"}})],1)],1),t._v(" "),r("v-container",{attrs:{fluid:""}},[r("p",{staticClass:"font-weight-black grey--text text--darken-4"},[t._v("\n ชนิดสินค้าที่ต้องการจำหน่าย (เลือกได้มากกว่า 1 ชนิด)*\n ")]),t._v(" "),r("v-row",[r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ข้าวและธัญพืซ",value:"ข้าวและธัญพืซ"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ผักและสมุนไพร",value:"ผักและสมุนไพร"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ไม้ผล",value:"ไม้ผล"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"ไม้ดอกไม้ประดับ",value:"ไม้ดอกไม้ประดับ"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ผลิตภัณฑ์แปรรูป",value:"ผลิตภัณฑ์แปรรูป"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ชา กาแฟ และโกโก้",value:"ชา กาแฟ และโกโก้"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1),t._v(" "),r("v-col",{attrs:{cols:"12",sm:"4",md:"4"}},[r("v-checkbox",{attrs:{label:"หัตถกรรม",value:"หัตถกรรม"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"พืซท้องถิ่น",value:"พืซท้องถิ่น"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}}),t._v(" "),r("v-checkbox",{attrs:{label:"ปศุสัตว์ และประมง",value:"ปศุสัตว์ และประมง"},model:{value:t.sellerForm.productType,callback:function(e){t.$set(t.sellerForm,"productType",e)},expression:"sellerForm.productType"}})],1)],1)],1)],1)],1),t._v(" "),r("v-card-actions",[r("v-row",[r("v-col",[r("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.push("/userprofile")}}},[t._v("ย้อนกลับ")])],1),t._v(" "),r("v-col",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:t.submitForm}},[t._v("ยืนยันการแก้ไข")])],1)],1)],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},Yt=r("VU/8")(Qt,Bt,!1,null,null,null).exports,Rt={components:{LMap:Nt.a,LTileLayer:Nt.d,LMarker:Nt.b,LPopup:Nt.c,LTooltip:Nt.e},inject:["mySpinner"],data:function(){return{queryId:null,month:[],baseUrl:"https://farmtd.hrdi.or.th/farmdd/admin/api/",productMk:[],productImgMk:[],sellerUser:[],selection:"มกราคม",monthTags:[{id:1,monthName:"มกราคม",isDiabled:!0},{id:2,monthName:"กุมภาพันธ์",isDiabled:!0},{id:3,monthName:"มีนาคม",isDiabled:!0},{id:4,monthName:"เมษายน",isDiabled:!0},{id:5,monthName:"พฤษภาคม",isDiabled:!0},{id:6,monthName:"มิถุนายน",isDiabled:!0},{id:7,monthName:"กรกฎาคม",isDiabled:!0},{id:8,monthName:"สิงหาคม",isDiabled:!0},{id:9,monthName:"กันยายน",isDiabled:!0},{id:10,monthName:"ตุลาคม",isDiabled:!0},{id:11,monthName:"พฤศจิกายน",isDiabled:!0},{id:12,monthName:"ธันวาคม",isDiabled:!0}],area:{},areaText:"",url:"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",zoom:6.5,center:[0,0],bounds:null,showAmount:!0,showDetails:!1,selectedItem:1,target:{},markers:[{id:null,position:{lat:null,lng:null},tooltip:null,visible:!0}]}},methods:{mapLink:function(){window.open("http://maps.google.com/?q="+this.target.lat+","+this.target.long+","+this.area.areaName,"_blank")},zoomUpdated:function(t){this.zoom=t},centerUpdated:function(t){this.center=t},boundsUpdated:function(t){this.bounds=t},getProductImg:function(t){var e=this,r=new FormData;r.append("idProductOfMemberMk",t),h.a.post(this.baseUrl+"/product/getProductImg.php",r).then(function(t){0!==t.data.productImgMk&&(e.productImgMk=t.data.productImgMk,e.productImgMk=e.productImgMk.filter(function(t){return t.imgTitle!==e.productMk.titleImg}),console.log("productImgMk",e.productImgMk))}).catch(function(t){e.mySpinner.isLoading=!1,console.log(t)})},getProductDetail:function(t){var e=this,r=new FormData;r.append("idProductOfMemberMk",t),h.a.post(this.baseUrl+"/product/getProductDetail.php",r).then(function(t){if(0!==t.data.productMk){e.productMk=t.data.productMk[0];var r=e.productMk.monthOfProduct.split(",").map(function(t){return parseInt(t,10)});r.sort(function(t,e){return t-e}),e.monthTags.map(function(t,e){r.map(function(e){e===t.id&&(t.isDiabled=!1)})}),console.log("monthTags",e.monthTags),console.log("productMk",e.productMk),e.mySpinner.isLoading=!1}}).then(function(){e.getSellerInfo(),e.getProductImg(e.queryId)}).catch(function(t){e.mySpinner.isLoading=!1,console.log(t)})},getSellerInfo:function(){var t=this;console.log(this.productMk.idSellerMember);var e=new FormData;e.append("idSellerMember",this.productMk.idSellerMember),h.a.post(this.baseUrl+"/product/postFindSellerMk.php",e).then(function(e){0!==e.data.sellerUser&&(t.sellerUser=e.data.sellerUser[0],console.log("sellerUser",t.sellerUser))}).then(function(){t.getAllArea()}).catch(function(e){t.mySpinner.isLoading=!1,console.log(e)})},getAllArea:function(){var t=this;h.a.get(this.baseUrl+"/getAllArea.php").then(function(e){if(0!==e.data.area){var r=e.data.area.filter(function(e,r){return e.idArea===t.sellerUser.vLinkAreaDetailId_MK});t.area={idArea:r[0].idArea,areaName:r[0].areaName,targetName:r[0].targetName},console.log("area",t.area)}}).then(function(e){t.getUserLL()}).catch(function(e){t.mySpinner.isLoading=!1,console.log(e)})},getUserLL:function(){var t=this,e=new FormData;e.append("idArea",this.area.idArea),h.a.post(this.baseUrl+"/product/getUserLL.php",e).then(function(e){if(0!==e.data.targetLL){t.target=e.data.targetLL[0];var r=parseFloat(e.data.targetLL[0].lat),o=parseFloat(e.data.targetLL[0].long);console.log("targetLL",t.target),t.center[0]=r,t.center[1]=o,t.markers[0].id=t.target.idArea,t.markers[0].position={lat:r,lng:o},t.markers[0].tooltip=t.target.targetName,console.log("marker",t.markers[0]),t.centerUpdated(t.markers[0].position)}}).catch(function(e){t.mySpinner.isLoading=!1,console.log(e)})}},mounted:function(){this.mySpinner.isLoading=!0,window.scroll(0,0),this.queryId=this.$route.params.idProductOfMemberMk,this.getProductDetail(this.queryId)},created:function(){}},Zt={render:function(){var t=this,e=t.$createElement,o=t._self._c||e;return o("v-container",{attrs:{fluid:"","fill-height":""}},[o("v-layout",{attrs:{"align-center":"","justify-center":""}},[o("v-flex",{attrs:{xs12:"",sm8:"",lg10:"",xl8:""}},[o("p",{staticClass:"\n display-1\n indigo--text\n text--darken-4\n font-weight-bold\n text-center\n pt-4\n mb-0\n "},[t._v("\n "+t._s(t.productMk.idAgri)+"\n ")]),t._v(" "),o("h1",{staticClass:"subtitle-2 text-center mt-2 font-weight-bold"},[t._v("\n หมวด "+t._s(t.productMk.nameTypeOfArgiMk)+"\n ")]),t._v(" "),o("v-btn",{staticClass:"mb-3",attrs:{outlined:""},on:{click:function(e){return t.$router.go(-1)}}},[o("v-icon",{staticClass:"mr-2"},[t._v("mdi-arrow-left")]),t._v("ย้อนกลับ")],1),t._v(" "),o("v-divider"),t._v(" "),o("v-row",[o("v-col",{staticClass:"d-flex child-flex pb-0",attrs:{cols:"6"}},[o("expandable-image",{attrs:{src:t.productMk.titleImg}})],1),t._v(" "),o("v-col",{attrs:{cols:"6"}},[o("v-row",{staticClass:"pa-5 body-1",attrs:{cols:"12"}},[o("v-row",{staticClass:"pa-2",attrs:{cols:"12"}},[o("v-col",[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("ชื่อสินค้า ")]),t._v(" "),o("h3",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.idAgri||"-")+"\n ")])]),t._v(" "),o("v-col",[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("สายพันธ์ุ ")]),t._v(" "),o("h3",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.speciesArgi||"-")+"\n ")])])],1),t._v(" "),o("v-col",{attrs:{cols:"12"}},[o("v-row",{staticClass:"my-2"},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("รายละเอียดสินค้า")])]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[t._v("\n "+t._s(t.productMk.detailOfProduct)+"\n ")])],1),t._v(" "),o("v-row",{staticClass:"pa-2",attrs:{cols:"12"}},[o("v-col",{attrs:{cols:"6"}},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("ขนาดบรรจุ ")]),t._v(" "),o("h2",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.sizeOfProduct||"-")+"\n ")])]),t._v(" "),o("v-col",{attrs:{cols:"6"}},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("ราคา ")]),t._v(" "),o("h2",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.priceBegin===t.productMk.priceEnd?t.productMk.priceEnd+"฿":t.productMk.priceBegin+"฿ - "+t.productMk.priceEnd+"฿")+"\n / "+t._s(t.productMk.nameUnit)+"\n ")])])],1),t._v(" "),o("v-row",{staticClass:"pa-2",attrs:{cols:"12"}},[o("v-col",{attrs:{cols:"6"}},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("\n มาตรฐานการผลิต \n ")]),t._v(" "),"ไม่มี"===t.productMk.idTypeOfStand?o("h2",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s("-")+"\n ")]):o("h2",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.idTypeOfStand||"-")+"\n ")])]),t._v(" "),o("v-col",{attrs:{cols:"6"}},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("\n การผลิตตามออเดอร์ \n ")]),t._v(" "),o("h2",{staticClass:"body-1 font-weight-medium mt-1"},[t._v("\n "+t._s(t.productMk.madeByOrder||"-")+"\n ")])])],1),t._v(" "),o("v-row",{attrs:{justify:"space-around"}},[o("v-row",{staticClass:"my-3 ml-3"},[o("h3",{staticClass:"indigo--text text--darken-4"},[t._v("เดือนที่มีสินค้า")])]),t._v(" "),o("v-col",{attrs:{cols:"12",sm:"10",md:"12"}},t._l(t.monthTags,function(e){return o("v-chip",{key:e.id,staticClass:"ma-2 green darken-1 white--text",attrs:{disabled:e.isDiabled,readonly:""}},[t._v("\n "+t._s(e.monthName)+"\n ")])}),1)],1)],1),t._v(" "),o("v-divider")],1)],1),t._v(" "),o("v-row",{staticClass:"mt-0 pa-0"},t._l(t.productImgMk,function(t,e){return o("v-col",{key:e,staticClass:"d-flex child-flex",attrs:{cols:"2"}},[o("expandable-image",{attrs:{src:t.imgTitle}})],1)}),1),t._v(" "),o("v-divider"),t._v(" "),o("v-row",{staticClass:"mt-2",attrs:{justify:"center",cols:"12"}},[o("v-col",{staticClass:"mx-auto pa-5",attrs:{cols:"6"}},[o("h2",{staticClass:"indigo--text text--darken-4 mx-auto mb-3"},[t._v("\n จัดจำหน่ายโดย\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold indigo--text text--darken-4"},[t._v("ประเภทองค์กร :")]),t._v("\n "+t._s(t.sellerUser.nameTypeOfSeller)+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold indigo--text text--darken-4"},[t._v("ชื่อกลุ่ม :")]),t._v("\n "+t._s(t.sellerUser.groupName||"-")+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold indigo--text text--darken-4"},[t._v("ที่อยู่ :")]),t._v("\n บ้านเลขที่ "+t._s(t.sellerUser.address||"-")+" หมู่\n "+t._s(t.sellerUser.moo||"-")+" ตำบล\n "+t._s(t.sellerUser.tamName||"-")+" อำเภอ\n "+t._s(t.sellerUser.ampName||"-")+" จังหวัด\n "+t._s(t.sellerUser.provName||"-")+" "+t._s(t.sellerUser.postCode||" ")+"\n ")]),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[o("span",{staticClass:"font-weight-bold indigo--text text--darken-4"},[t._v("เบอร์โทรศัพท์ :")]),t._v("\n "+t._s(t.sellerUser.phoneNumber||"-")+"\n ")]),t._v(" "),o("v-row",{attrs:{cols:"12"}},[o("v-col",{attrs:{cols:"12"}},[o("v-img",{attrs:{width:"24",src:r("AIOO")}}),t._v(" "),t.sellerUser.facebookName?o("p",[t._v("\n "+t._s(t.sellerUser.facebookName)+"\n ")]):o("p",{staticClass:"body-1 font-weight-medium"},[t._v("\n "+t._s(t.sellerUser.facebookName||"-")+"\n ")])],1),t._v(" "),o("v-col",[o("v-img",{attrs:{width:"24",src:r("pufY")}}),t._v(" "),o("p",{staticClass:"body-1 font-weight-medium"},[t._v("\n "+t._s(t.sellerUser.lineName||"-")+"\n ")])],1)],1)],1),t._v(" "),o("v-col",{attrs:{cols:"6"}},[o("v-row",[o("h2",{staticClass:"indigo--text text--darken-4 mx-auto"},[t._v("พื้นที่สินค้า")])]),t._v(" "),o("div",{staticStyle:{height:"500px",width:"100%"}},[o("l-map",{attrs:{zoom:t.zoom,center:t.center,options:{scrollWheelZoom:!1}},on:{"update:zoom":t.zoomUpdated,"update:center":t.centerUpdated,"update:bounds":t.boundsUpdated}},[o("l-tile-layer",{attrs:{url:t.url}}),t._v(" "),t._l(t.markers,function(e){return o("l-marker",{key:e.id,attrs:{visible:e.visible,"lat-lng":e.position,icon:e.icon},on:{"update:latLng":function(r){return t.$set(e,"position",r)},"update:lat-lng":function(r){return t.$set(e,"position",r)},click:function(e){return t.mapLink()}}},[o("l-tooltip",{attrs:{content:e.tooltip,options:{permanent:!0}}})],1)})],2)],1)],1)],1),t._v(" "),o("v-divider")],1)],1)],1)},staticRenderFns:[]};var Gt=r("VU/8")(Rt,Zt,!1,function(t){r("AYtb")},"data-v-41d671c1",null).exports,Jt=h.a.create({baseURL:"https://farmtd.hrdi.or.th/farmdd/admin/api/",headers:{"Content-Type":"application/json"}}),Vt=function(){return Jt.get("product/getUnitMk.php")},$t={components:{imgPreview:Ot},data:function(){return{unitMk:[],chooseTitle:null,chooseIndex:null,isFormValid:!1,isLoading:!1,formStep:{step1:!0,step2:!1},typeOfArgi:[],productForm:{idTypeOfArgi:"",idAgri:"",speciesArgi:"",detailOfProduct:"",sizeOfProduct:"",unit:"",priceBegin:"",idSellerMember:"",priceEnd:"",monthOfProduct:[],typeOfStand:"",madeByOrder:"",imgCurFiles:[],img:[]},productByArgiType:[],speciesItem:[],monthOfYear:[],typeOfStand:[],userInfo:[],argiTd:[],baseUrl:"https://farmtd.hrdi.or.th/farmdd/admin/api/"}},methods:{errMsg:function(t){this.$swal.fire({icon:"info",title:t,showConfirmButton:!0,allowOutsideClick:!1})},getTypeOFStand:function(){var t=this;h.a.get(this.baseUrl+"product/getTypeOfStand.php").then(function(e){t.typeOfStand=e.data.typeOfStand,console.log("gettypeOfStand",t.typeOfStand)}).catch(function(t){console.log(t)})},getArgiTd:function(){var t=this;h.a.get(this.baseUrl+"product/getArgiTd.php").then(function(e){t.argiTd=e.data.argiTd,console.log("getArgiTd",t.argiTd)}).catch(function(t){console.log(t)})},submitForm:function(){var t=this;if(this.productForm.img.length>5)this.errMsg("ไม่สามาถเพิ่มรูปภาพได้เกิน 5 รูป");else if(null!==this.chooseIndex){null===this.productForm.speciesArgi&&(this.productForm.speciesArgi=0),this.isLoading=!0,this.isFormValid=!0;var e=new FormData;e.append("idTypeOfArgi",this.productForm.idTypeOfArgi),e.append("detailOfProduct",this.productForm.detailOfProduct),e.append("idSellerMember",this.productForm.idSellerMember),e.append("idAgri",this.productForm.idAgri),e.append("madeByOrder",this.productForm.madeByOrder),e.append("monthOfProduct",this.productForm.monthOfProduct),e.append("priceBegin",this.productForm.priceBegin),e.append("priceEnd",this.productForm.priceEnd),e.append("sizeOfProduct",this.productForm.sizeOfProduct),e.append("speciesArgi",this.productForm.speciesArgi),e.append("typeOfStand",this.productForm.typeOfStand),e.append("titleImg",this.productForm.img[this.chooseIndex].name),e.append("unit",this.productForm.unit),e.append("suggestOption",0),e.append("publish",0);for(var r=0;r<this.productForm.img.length;r++){var o=this.productForm.img[r];e.append("img["+r+"]",o),console.log(o)}h.a.post(this.baseUrl+"product/postAddProduct.php",e,{maxContentLength:1/0,maxBodyLength:1/0,headers:{"Content-Type":"multipart/form-data"}}).then(function(e){console.log(e),"True"===e.data&&(t.isLoading=!1,localStorage.showProduct="showProduct",t.$swal.fire({icon:"success",title:"เพิ่มสินค้าสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})}))}).catch(function(e){e&&t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถเพิ่มสินค้าได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"UserProfile"})})})}else this.errMsg("กรุณาเลือกรูปภาพหน้าปก")},getMonthOfYear:function(){var t=this;h.a.get(this.baseUrl+"product/getMonthOfYear.php").then(function(e){t.monthOfYear=e.data.monthOfYear,console.log("getMonthOfYear",t.monthOfYear)}).catch(function(t){console.log(t)})},getUnitMk:function(){var t=this;Vt().then(function(e){t.unitMk=e.data.unitMk,console.log("unitMk",t.unitMk)}).catch(function(t){console.log(t)})},findSpecies:function(){var t=this,e=new FormData;e.append("agriId",this.productForm.idAgri),h.a.post(this.baseUrl+"product/postSpeciesByArgi.php",e).then(function(e){e.data.species&&(t.speciesItem=e.data.species,0===t.speciesItem.length&&(t.speciesItem[0]={agriId:t.productForm.idAgri,speciesId:0,speciesName:"ไม่มี"}),console.log("speciesItem",t.speciesItem))}).catch(function(t){console.log(t)})},findProductName:function(t){this.productByArgiType=[],this.productByArgiType=this.argiTd.filter(function(e){return e.TypeOfArgiIdTypeOfArgi===t}),console.log("productByArgiType",this.productByArgiType)},getTypeOfArgi:function(){var t=this;h.a.get(this.baseUrl+"product/getTypeArgi.php").then(function(e){0!==e.data.typeOfArgi&&(t.typeOfArgi=e.data.typeOfArgi,t.typeOfArgi=t.typeOfArgi.filter(function(t){return null!==t.nameTypeOfArgiMk}),console.log("typeOfArgi",t.typeOfArgi))}).catch(function(t){console.log(t)})},inputChanged:function(t){console.log("change",t),this.productForm.img=[].concat(E()(this.productForm.imgCurFiles),E()(this.productForm.img))},remove:function(t){this.productForm.img.splice(t,1),this.productForm.imgCurFiles.splice(t,1)},formStep2:function(){this.productForm.idSellerMember=localStorage.idMember,console.log(this.productForm),this.formStep.step1&&(this.formStep.step1=!1,this.formStep.step2=!0)},chooseTitleImg:function(t,e){this.chooseTitle=t,this.chooseIndex=e}},mounted:function(){this.getTypeOfArgi(),this.getArgiTd(),this.getUnitMk(),this.getMonthOfYear(),this.getTypeOFStand()}},Ht={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{attrs:{fluid:"","fill-height":""}},[r("v-layout",{attrs:{"align-center":"","justify-center":""}},[r("v-flex",{attrs:{xs12:"",sm8:"",lg10:""}},[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-row",{attrs:{justify:"center"}},[r("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[t.formStep.step1?r("v-card",{ref:"form",attrs:{"max-width":"1000"}},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-icon",{staticClass:"mr-2",on:{click:function(e){return t.$router.go(-1)}}},[t._v("mdi-arrow-left-thick")]),t._v(" "),r("v-toolbar-title",[t._v("เพิ่มสินค้า")])],1),t._v(" "),r("v-card-text",[r("v-col",{attrs:{cols:"12"}},[r("v-row",[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-format-list-bulleted-type","item-text":"nameTypeOfArgiMk","item-value":"idTypeOfArgi",items:t.typeOfArgi,rules:[function(t){return!!t||"กรุณาเลือกหมวดหมู่สินค้า"}],label:"หมวดหมู่สินค้า*",required:""},on:{change:function(e){return t.findProductName(t.productForm.idTypeOfArgi)}},model:{value:t.productForm.idTypeOfArgi,callback:function(e){t.$set(t.productForm,"idTypeOfArgi",e)},expression:"productForm.idTypeOfArgi"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ชื่อสินค้า*")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกชื่อสินค้า"}],dense:""},model:{value:t.productForm.idAgri,callback:function(e){t.$set(t.productForm,"idAgri",e)},expression:"productForm.idAgri"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("สายพันธ์ุ")]),t._v(" "),r("v-text-field",{attrs:{dense:""},model:{value:t.productForm.speciesArgi,callback:function(e){t.$set(t.productForm,"speciesArgi",e)},expression:"productForm.speciesArgi"}})],1)],1),t._v(" "),r("v-row",[r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("รายละเอียดสินค้า")]),t._v(" "),r("v-textarea",{attrs:{rules:[function(t){return!!t||"กรุณากรอกรายละเอียดสินค้า"}],type:"text",outlined:"",rows:"4"},model:{value:t.productForm.detailOfProduct,callback:function(e){t.$set(t.productForm,"detailOfProduct",e)},expression:"productForm.detailOfProduct"}})],1)],1),t._v(" "),r("v-row",[r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ขนาดบรรจุ")]),t._v(" "),r("v-text-field",{attrs:{type:"text",outlined:"",dense:""},model:{value:t.productForm.sizeOfProduct,callback:function(e){t.$set(t.productForm,"sizeOfProduct",e)},expression:"productForm.sizeOfProduct"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("หน่วย*")]),t._v(" "),r("v-select",{attrs:{"item-text":"nameUnit","item-value":"idUnit",items:t.unitMk,rules:[function(t){return!!t||"กรุณาเลือกหน่วย"}],outlined:"",dense:"",required:""},model:{value:t.productForm.unit,callback:function(e){t.$set(t.productForm,"unit",e)},expression:"productForm.unit"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ราคาเริ่มต้น")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกราคาเริ่มต้น"}],type:"number",number:"",outlined:"",dense:""},model:{value:t.productForm.priceBegin,callback:function(e){t.$set(t.productForm,"priceBegin",e)},expression:"productForm.priceBegin"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ราคาสิ้นสุด")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกราคาสิ้นสุด"}],type:"number",number:"",outlined:"",dense:""},model:{value:t.productForm.priceEnd,callback:function(e){t.$set(t.productForm,"priceEnd",e)},expression:"productForm.priceEnd"}})],1)],1),t._v(" "),r("v-row",[r("span",{staticClass:"body-1 font-weight-bold"},[t._v("ช่วงเวลาที่เก็บเกี่ยวผลผลิต")]),t._v(" "),r("div",{staticClass:"mr-4 ml-4 whiteback userGroupHeight"},[r("v-layout",{attrs:{row:"",wrap:""}},t._l(t.monthOfYear,function(e,o){return r("v-flex",{key:o,attrs:{xs4:""}},[r("v-checkbox",{attrs:{light:"",label:e.monthName,value:e.monthId},model:{value:t.productForm.monthOfProduct,callback:function(e){t.$set(t.productForm,"monthOfProduct",e)},expression:"productForm.monthOfProduct"}})],1)}),1)],1)]),t._v(" "),r("v-row",[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-format-list-bulleted-type","item-text":"nameTypeOfStand","item-value":"nameTypeOfStand",items:t.typeOfStand,rules:[function(t){return!!t||"กรุณาเลือกมาตรฐานผลผลิต"}],label:"มาตรฐานผลผลิต*",required:""},model:{value:t.productForm.typeOfStand,callback:function(e){t.$set(t.productForm,"typeOfStand",e)},expression:"productForm.typeOfStand"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"การผลิตตามออเดอร์",type:"text"},model:{value:t.productForm.madeByOrder,callback:function(e){t.$set(t.productForm,"madeByOrder",e)},expression:"productForm.madeByOrder"}})],1)],1)],1)],1),t._v(" "),r("v-card-actions",[r("v-row",[r("v-col",[r("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.push("/userprofile")}}},[t._v("ย้อนกลับ")])],1),t._v(" "),r("v-col",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:function(e){return t.formStep2()}}},[t._v("ถัดไป")])],1)],1)],1)],1):t._e(),t._v(" "),t.formStep.step2?r("v-card",{ref:"form",attrs:{width:"600","max-width":"1000"}},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-toolbar-title",[t._v("เพิ่มสินค้า")])],1),t._v(" "),r("v-card-text",[t.isLoading?r("v-col",{attrs:{cols:"12"}},[r("v-row",{attrs:{justify:"center"}},[r("v-progress-circular",{attrs:{size:350,color:"primary",indeterminate:""}})],1)],1):t._e(),t._v(" "),t.isLoading?t._e():r("v-col",{attrs:{cols:"12"}},[r("v-row",[r("v-col",{attrs:{cols:"12"}},[r("v-file-input",{ref:"file",attrs:{type:"file",accept:"image/*","small-chips":"","show-size":"",clearable:"",label:"เพิ่มรูปภาพ",multiple:"",dense:"",counter:""},on:{change:t.inputChanged},scopedSlots:t._u([{key:"selection",fn:function(e){var o=e.text,a=e.index;return[r("v-chip",{attrs:{small:"","text-color":"white",color:"#295671",close:""},on:{"click:close":function(e){return t.remove(a)}}},[t._v("\n "+t._s(o)+"\n ")])]}}],null,!1,2481944520),model:{value:t.productForm.imgCurFiles,callback:function(e){t.$set(t.productForm,"imgCurFiles",e)},expression:"productForm.imgCurFiles"}}),t._v(" "),r("span",{staticClass:"mb-2 body-2 font-weight-bold"},[t._v("รูปสินค้า (สูงสุด 5 รูป)")]),t._v(" "),r("v-row")],1)],1),t._v(" "),t.productForm.img.length?r("div",[r("h5",[t._v("รูปสินค้าที่เลือก")]),t._v(" "),t._l(t.productForm.img,function(e,o){return r("v-chip",{key:o,staticClass:"mr-1",on:{click:function(e){return t.remove(o)}}},[t._v("\n "+t._s(e.name)),r("v-icon",{staticClass:"ml-2"},[t._v("mdi-backspace-outline")])],1)}),t._v(" "),r("v-row",t._l(t.productForm.img,function(e,o){return r("img-preview",{key:e.name,attrs:{file:e,imgIndex:o,chooseTitle:t.chooseTitle},on:{chooseTitleImg:t.chooseTitleImg}})}),1)],2):t._e()],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:function(e){return t.submitForm()}}},[t._v("ยืนยันการเพิ่มสินค้า")])],1)],1):t._e()],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},qt=r("VU/8")($t,Ht,!1,null,null,null).exports,Wt={components:{imgPreview:Ot},data:function(){return{chooseTitle:null,chooseIndex:null,chooseImgType:null,isFormValid:!1,isLoading:!1,formStep:{step1:!0,step2:!1},typeOfArgi:[],productForm:{idTypeOfArgi:"",idAgri:"",speciesArgi:"",detailOfProduct:"",sizeOfProduct:"",unit:"",priceBegin:"",idSellerMember:"",priceEnd:"",monthOfProduct:[],typeOfStand:"",madeByOrder:"",imgCurFiles:[],img:[]},productByArgiType:[],speciesItem:[],unitMk:[],monthOfYear:[],typeOfStand:[],userInfo:[],argiTd:[],image_list:[],oldImg:[],baseUrl:"https://farmtd.hrdi.or.th/farmdd/admin/api/"}},methods:{previewMultiImage:function(t){var e=this,r=t.target,o=r.files.length,a=0;if(r.files)for(;o--;){var i=new FileReader;i.onload=function(t){e.preview_list.push(t.target.result)},this.productForm.img.push(r.files[a]),this.image_list.push(r.files[a]),i.readAsDataURL(r.files[a]),a++}console.log(this.productForm.img)},deleteOldImg:function(t,e){var r=this;1!==this.oldImg.length?e!==this.productForm.titleImg?this.$swal.fire({title:"ต้องการลบรูปสินค้าหรือไม่ ?",icon:"warning",showCancelButton:!0,confirmButtonColor:"#3085d6",cancelButtonColor:"#d33",confirmButtonText:"ยืนยัน",cancelButtonText:"ยกเลิก"}).then(function(e){if(e.isConfirmed){var o=new FormData;o.append("productImgId",t),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/product/postDeleteImgProduct.php",o).then(function(t){r.$swal.fire({icon:"success",title:"ลบรูปภาพสินค้าสำเร็จ",showConfirmButton:!1,timer:1e3}).then(function(t){r.getProductImg()})}).catch(function(t){r.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",showConfirmButton:!1,timer:1500}).then(function(t){window.location.reload()})})}}):this.errAlert("ไม่สามารถลบรูปภาพหน้าปกได้"):this.errAlert("ต้องมีรูปภาพอย่างน้อย 1 รูป")},getTypeOFStand:function(){var t=this;h.a.get(this.baseUrl+"product/getTypeOfStand.php").then(function(e){t.typeOfStand=e.data.typeOfStand,console.log("gettypeOfStand",t.typeOfStand)}).catch(function(t){console.log(t)})},getArgiTd:function(){var t=this;h.a.get(this.baseUrl+"product/getArgiTd.php").then(function(e){t.argiTd=e.data.argiTd,console.log("getArgiTd",t.argiTd)}).then(function(e){t.getProductDetail()}).catch(function(t){console.log(t)})},submitForm:function(){var t=this;this.isFormValid=!0,null===this.productForm.speciesArgi&&(this.productForm.speciesArgi="ไม่มี");var e=new FormData;if(e.append("idTypeOfArgi",this.productForm.idTypeOfArgi),e.append("detailOfProduct",this.productForm.detailOfProduct),e.append("idSellerMember",this.productForm.idSellerMember),e.append("idProductOfMemberMk",this.productForm.idProductOfMemberMk),e.append("idAgri",this.productForm.idAgri),e.append("madeByOrder",this.productForm.madeByOrder),e.append("monthOfProduct",this.productForm.monthOfProduct),e.append("priceBegin",this.productForm.priceBegin),e.append("priceEnd",this.productForm.priceEnd),e.append("sizeOfProduct",this.productForm.sizeOfProduct),e.append("speciesArgi",this.productForm.speciesArgi),e.append("typeOfStand",this.productForm.typeOfStand),e.append("unit",this.productForm.unit),"oldImg"===this.chooseImgType&&(e.append("titleImg",this.oldImg[this.chooseIndex].imgName),console.log("chooseImg",this.oldImg[this.chooseIndex].imgName)),"newImg"===this.chooseImgType&&null!==this.chooseIndex&&e.append("titleImg",this.productForm.img[this.chooseIndex].name),null===this.chooseIndex&&e.append("titleImg",this.productForm.titleImg.substring(54)),this.productForm.img.length>0){if(this.productForm.img.length>5||this.productForm.img.length+this.oldImg.length>5)return void this.errAlert("ไม่สามาถเพิ่มรูปภาพได้เกิน 5 รูป");for(var r=0,o=0;o<this.productForm.img.length;o++){var a=this.productForm.img[o];r+=a.size,e.append("img["+o+"]",a),console.log(a)}if(r>8e6)return void this.errAlert("ขนาดไฟล์รวมกันห้ามเกิน 8 MB")}this.isLoading=!0,h.a.post(this.baseUrl+"product/postUpdateProduct.php",e,{maxContentLength:1/0,maxBodyLength:1/0,headers:{"Content-Type":"multipart/form-data"}}).then(function(e){console.log(e),"True"===e.data&&(t.isLoading=!1,t.$swal.fire({icon:"success",title:"แก้ไขสินค้าสำเร็จ",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Home"})}))}).catch(function(e){e&&t.$swal.fire({icon:"error",title:"เกิดข้อผิดพลาด",text:"ไม่สามารถเพิ่มสินค้าได้",showConfirmButton:!1,timer:2e3}).then(function(){t.$router.push({name:"Home"})})})},errAlert:function(t){this.$swal.fire({icon:"info",title:t,showConfirmButton:!0,allowOutsideClick:!1})},getMonthOfYear:function(){var t=this;h.a.get(this.baseUrl+"product/getMonthOfYear.php").then(function(e){t.monthOfYear=e.data.monthOfYear,console.log("getMonthOfYear",t.monthOfYear)}).catch(function(t){console.log(t)})},getUnitMk:function(){var t=this;Vt().then(function(e){t.unitMk=e.data.unitMk,console.log("unitMk",t.unitMk)}).catch(function(t){console.log(t)})},findSpecies:function(){var t=this,e=new FormData;e.append("agriId",this.productForm.idAgri),h.a.post(this.baseUrl+"product/postSpeciesByArgi.php",e).then(function(e){e.data.species&&(t.speciesItem=e.data.species,0===t.speciesItem.length&&(t.speciesItem[0]={agriId:t.productForm.idAgri,speciesId:0,speciesName:"ไม่มี"}),console.log("speciesItem",t.speciesItem))}).catch(function(t){console.log(t)})},findProductName:function(t){this.productByArgiType=[],this.productByArgiType=this.argiTd.filter(function(e){return e.TypeOfArgiIdTypeOfArgi===t}),console.log("productByArgiType",this.productByArgiType)},getTypeOfArgi:function(){var t=this;h.a.get(this.baseUrl+"product/getTypeArgi.php").then(function(e){0!==e.data.typeOfArgi&&(t.typeOfArgi=e.data.typeOfArgi,t.typeOfArgi=t.typeOfArgi.filter(function(t){return null!==t.nameTypeOfArgiMk}),console.log("typeOfArgi",t.typeOfArgi))}).catch(function(t){console.log(t)})},inputChanged:function(t){console.log("change",t),this.productForm.img=[].concat(E()(this.productForm.imgCurFiles),E()(this.productForm.img))},remove:function(t){this.productForm.img.splice(t,1),this.productForm.imgCurFiles.splice(t,1)},formStep2:function(){this.productForm.idSellerMember=localStorage.idMember,console.log(this.productForm),this.formStep.step1&&(this.formStep.step1=!1,this.formStep.step2=!0)},getProductDetail:function(){var t=this,e=new FormData;e.append("idProductOfMemberMk",this.productForm.idProductOfMemberMk),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getProductDetail.php",e).then(function(e){0!==e.data.productMk.length&&(console.log(e.data.productMk),t.productForm=e.data.productMk[0],t.productForm.typeOfStand=e.data.productMk[0].idTypeOfStand,t.productForm.suggestOption=e.data.productMk[0].suggestSta,t.productForm.monthOfProduct=e.data.productMk[0].monthOfProduct.split(","),t.productForm.img=[],""!==t.productForm.speciesArgi&&t.findSpecies(),""!==t.productForm.idTypeOfArgi&&t.findProductName(t.productForm.idTypeOfArgi),console.log("productDetail",t.productForm))}).then(function(){t.getProductImg()}).catch(function(t){console.log(t)})},getProductImg:function(){var t=this,e=new FormData;e.append("idProductOfMemberMk",this.productForm.idProductOfMemberMk),h.a.post("https://farmtd.hrdi.or.th/farmdd/admin/api/product/getProductImg.php",e).then(function(e){t.oldImg=e.data.productImgMk,console.log("oldImg",t.oldImg)})},chooseTitleImg:function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"newImg";this.chooseTitle=t,this.chooseIndex=e,this.chooseImgType=r}},mounted:function(){this.productForm.idProductOfMemberMk=this.$route.params.idProductOfMemberMk,this.getTypeOfArgi(),this.getArgiTd(),this.getUnitMk(),this.getMonthOfYear(),this.getTypeOFStand()}},Xt={render:function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("v-container",{attrs:{fluid:"","fill-height":""}},[r("v-layout",{attrs:{"align-center":"","justify-center":""}},[r("v-flex",{attrs:{xs12:"",sm8:"",lg10:""}},[r("v-container",{staticClass:"mr-auto",attrs:{fluid:""}},[r("v-layout",{attrs:{column:"","align-center":""}},[r("v-row",{attrs:{justify:"center"}},[r("v-form",{model:{value:t.isFormValid,callback:function(e){t.isFormValid=e},expression:"isFormValid"}},[t.formStep.step1?r("v-card",{ref:"form",attrs:{"max-width":"1000"}},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-icon",{staticClass:"mr-2",on:{click:function(e){return t.$router.go(-1)}}},[t._v("mdi-arrow-left-thick")]),t._v(" "),r("v-toolbar-title",[t._v("แก้ไขสินค้า")])],1),t._v(" "),r("v-card-text",[r("v-col",{attrs:{cols:"12"}},[r("v-row",[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-format-list-bulleted-type","item-text":"nameTypeOfArgiMk","item-value":"idTypeOfArgi",items:t.typeOfArgi,rules:[function(t){return!!t||"กรุณาเลือกหมวดหมู่สินค้า"}],label:"หมวดหมู่สินค้า*",required:""},on:{change:function(e){return t.findProductName(t.productForm.idTypeOfArgi)}},model:{value:t.productForm.idTypeOfArgi,callback:function(e){t.$set(t.productForm,"idTypeOfArgi",e)},expression:"productForm.idTypeOfArgi"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ชื่อสินค้า*")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกชื่อสินค้า"}],dense:""},model:{value:t.productForm.idAgri,callback:function(e){t.$set(t.productForm,"idAgri",e)},expression:"productForm.idAgri"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("สายพันธ์ุ")]),t._v(" "),r("v-text-field",{attrs:{dense:""},model:{value:t.productForm.speciesArgi,callback:function(e){t.$set(t.productForm,"speciesArgi",e)},expression:"productForm.speciesArgi"}})],1)],1),t._v(" "),r("v-row",[r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("รายละเอียดสินค้า")]),t._v(" "),r("v-textarea",{attrs:{rules:[function(t){return!!t||"กรุณากรอกรายละเอียดสินค้า"}],type:"text",outlined:"",rows:"4"},model:{value:t.productForm.detailOfProduct,callback:function(e){t.$set(t.productForm,"detailOfProduct",e)},expression:"productForm.detailOfProduct"}})],1)],1),t._v(" "),r("v-row",[r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ขนาดบรรจุ")]),t._v(" "),r("v-text-field",{attrs:{type:"text",outlined:"",dense:""},model:{value:t.productForm.sizeOfProduct,callback:function(e){t.$set(t.productForm,"sizeOfProduct",e)},expression:"productForm.sizeOfProduct"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("หน่วย*")]),t._v(" "),r("v-select",{attrs:{"item-text":"nameUnit","item-value":"idUnit",items:t.unitMk,rules:[function(t){return!!t||"กรุณาเลือกหน่วย"}],outlined:"",dense:"",required:""},model:{value:t.productForm.unit,callback:function(e){t.$set(t.productForm,"unit",e)},expression:"productForm.unit"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ราคาเริ่มต้น")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกราคาเริ่มต้น"}],type:"number",number:"",outlined:"",dense:""},model:{value:t.productForm.priceBegin,callback:function(e){t.$set(t.productForm,"priceBegin",e)},expression:"productForm.priceBegin"}})],1),t._v(" "),r("v-col",[r("span",{staticClass:"body-2 font-weight-bold"},[t._v("ราคาสิ้นสุด")]),t._v(" "),r("v-text-field",{attrs:{rules:[function(t){return!!t||"กรุณากรอกราคาสิ้นสุด"}],type:"number",number:"",outlined:"",dense:""},model:{value:t.productForm.priceEnd,callback:function(e){t.$set(t.productForm,"priceEnd",e)},expression:"productForm.priceEnd"}})],1)],1),t._v(" "),r("v-row",[r("span",{staticClass:"body-1 font-weight-bold"},[t._v("ช่วงเวลาที่เก็บเกี่ยวผลผลิต")]),t._v(" "),r("div",{staticClass:"mr-4 ml-4 whiteback userGroupHeight"},[r("v-layout",{attrs:{row:"",wrap:""}},t._l(t.monthOfYear,function(e,o){return r("v-flex",{key:o,attrs:{xs4:""}},[r("v-checkbox",{attrs:{light:"",label:e.monthName,value:e.monthId},model:{value:t.productForm.monthOfProduct,callback:function(e){t.$set(t.productForm,"monthOfProduct",e)},expression:"productForm.monthOfProduct"}})],1)}),1)],1)]),t._v(" "),r("v-row",[r("v-col",[r("v-select",{attrs:{"prepend-icon":"mdi-format-list-bulleted-type","item-text":"nameTypeOfStand","item-value":"nameTypeOfStand",items:t.typeOfStand,rules:[function(t){return!!t||"กรุณาเลือกมาตรฐานผลผลิต"}],label:"มาตรฐานผลผลิต*",required:""},model:{value:t.productForm.typeOfStand,callback:function(e){t.$set(t.productForm,"typeOfStand",e)},expression:"productForm.typeOfStand"}},[t._v("*")])],1),t._v(" "),r("v-col",[r("v-text-field",{attrs:{label:"การผลิตตามออเดอร์",type:"text"},model:{value:t.productForm.madeByOrder,callback:function(e){t.$set(t.productForm,"madeByOrder",e)},expression:"productForm.madeByOrder"}})],1)],1)],1)],1),t._v(" "),r("v-card-actions",[r("v-row",[r("v-col",[r("v-btn",{staticClass:"blue-grey darken-1 white--text",attrs:{block:""},on:{click:function(e){return t.$router.push("/userprofile")}}},[t._v("ย้อนกลับ")])],1),t._v(" "),r("v-col",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:function(e){return t.formStep2()}}},[t._v("ถัดไป")])],1)],1)],1)],1):t._e(),t._v(" "),t.formStep.step2?r("v-card",{ref:"form",attrs:{width:"600","max-width":"1000"}},[r("v-toolbar",{attrs:{dark:"",color:"primary"}},[r("v-toolbar-title",[t._v("เพิ่มสินค้า")])],1),t._v(" "),r("v-card-text",[t.isLoading?r("v-col",{attrs:{cols:"12"}},[r("v-row",{attrs:{justify:"center"}},[r("v-progress-circular",{attrs:{size:350,color:"primary",indeterminate:""}})],1)],1):t._e(),t._v(" "),t.isLoading?t._e():r("v-col",{attrs:{cols:"12"}},[r("v-row",[r("v-col",{attrs:{cols:"12"}},[r("v-file-input",{ref:"file",attrs:{type:"file",accept:"image/*","small-chips":"","show-size":"",clearable:"",label:"เพิ่มรูปภาพ",multiple:"",dense:"",counter:""},on:{change:t.inputChanged},scopedSlots:t._u([{key:"selection",fn:function(e){var o=e.text,a=e.index;return[r("v-chip",{attrs:{small:"","text-color":"white",color:"#295671",close:""},on:{"click:close":function(e){return t.remove(a)}}},[t._v("\n "+t._s(o)+"\n ")])]}}],null,!1,2481944520),model:{value:t.productForm.imgCurFiles,callback:function(e){t.$set(t.productForm,"imgCurFiles",e)},expression:"productForm.imgCurFiles"}}),t._v(" "),r("span",{staticClass:"mb-2 body-2 font-weight-bold"},[t._v("รูปสินค้า (สูงสุด 5 รูป)")]),t._v(" "),r("v-row")],1)],1),t._v(" "),r("v-row",{attrs:{cols:"12"}},t._l(t.oldImg,function(e,o){return r("v-col",{key:o,staticClass:"mr-1"},[r("v-row",[r("img",{key:o,attrs:{src:e.imgTitle,width:"100",height:"100"}})]),t._v(" "),r("v-row",{staticClass:"mt-2"},[e.imgTitle===t.productForm.titleImg?r("v-chip",{staticClass:"mr-1",attrs:{color:"primary"}},[t._v("\n รูปปกเดิม\n ")]):r("v-chip",{staticClass:"mr-1",attrs:{color:e.imgTitle===t.chooseTitle?"primary":""},on:{click:function(r){return t.chooseTitleImg(e.imgTitle,o,"oldImg")}}},[t._v("\n รูปปก\n ")]),t._v(" "),r("v-chip",{on:{click:function(r){return t.deleteOldImg(e.productImgId,e.imgTitle)}}},[t._v("\n "+t._s(e.imgName)),r("v-icon",{staticClass:"ml-2"},[t._v("mdi-backspace-outline")])],1)],1)],1)}),1),t._v(" "),t.productForm.img.length?r("div",[r("h5",[t._v("รูปสินค้าที่เลือก")]),t._v(" "),t._l(t.productForm.img,function(e,o){return r("v-chip",{key:o,staticClass:"mr-1",on:{click:function(e){return t.remove(o)}}},[t._v("\n "+t._s(e.name)),r("v-icon",{staticClass:"ml-2"},[t._v("mdi-backspace-outline")])],1)}),t._v(" "),r("v-row",t._l(t.productForm.img,function(e,o){return r("img-preview",{key:e.name,attrs:{file:e,imgIndex:o,chooseTitle:t.chooseTitle},on:{chooseTitleImg:t.chooseTitleImg}})}),1)],2):t._e()],1)],1),t._v(" "),r("v-card-actions",[r("v-btn",{attrs:{block:"",color:"primary",disabled:!t.isFormValid},on:{click:function(e){return t.submitForm()}}},[t._v("ยืนยันการเพิ่มสินค้า")])],1)],1):t._e()],1)],1)],1)],1)],1)],1)],1)},staticRenderFns:[]},Kt=r("VU/8")(Wt,Xt,!1,null,null,null).exports;o.default.use(v.a);var te=new v.a({mode:"hash",linkActiveClass:"active",base:"/farmdd",routes:[{path:"/",component:lt,children:[{path:"/",component:j,name:"Home"},{path:"/shop",component:R,name:"Shop"},{path:"/addproduct",component:qt,name:"AddProduct"},{path:"/editproduct/:idProductOfMemberMk",component:Kt,name:"EditProduct"},{path:"/editprofile",component:Pt,name:"EditProfile"},{path:"/editprofile",component:Pt,name:"EditProfile"},{path:"/product",component:G,name:"Product"},{path:"/market",component:q,name:"Market"},{path:"/blog",component:V,name:"Blog"},{path:"/aboutus",component:xt,name:"AboutUs"},{path:"/userprofile",component:zt,name:"UserProfile"},{path:"/editseller",component:Yt,name:"EditSeller"},{path:"/findproduct",component:Tt,name:"FindProduct"},{path:"/typelist/:idTypeOfArgi/:nameTypeOfArgi",component:At,name:"TypeList"},{path:"/content/:page",component:it,name:"Content"},{path:"/productdetail/:idProductOfMemberMk",component:Gt,name:"ProductDetail"},{path:"/post/:id",component:K,name:"Post"},{path:"/register",component:Mt,name:"Register"},{path:"/cart",component:rt,name:"Cart"},{path:"/login",component:pt,name:"Login"}]}]}),ee=r("hz7P"),re=(r("UdIB"),r("EYnv"),r("q9lO")),oe=r.n(re);o.default.use(oe.a),delete It.Icon.Default.prototype._getIconUrl,It.Icon.Default.mergeOptions({iconRetinaUrl:r("qXhe"),iconUrl:r("TJ5S"),shadowUrl:r("wkq0")}),o.default.component("l-map",Nt.a),o.default.component("l-tile-layer",Nt.d),o.default.component("l-marker",Nt.b),o.default.use(p.a),o.default.use(ee.a),o.default.config.productionTip=!1,new o.default({el:"#app",router:te,vuetify:s,components:{App:d},template:"<App/>"})},NSMX:function(t,e,r){t.exports=r.p+"img/slider1.8a3a968.jpg"},OPaq:function(t,e){},Ot1l:function(t,e,r){t.exports=r.p+"img/field.c9a9c0d.jpeg"},PM2Y:function(t,e,r){t.exports=r.p+"img/icon2.7e36b0c.png"},PQwa:function(t,e,r){t.exports=r.p+"img/meat-card.cfed864.jpeg"},R06a:function(t,e){},RDci:function(t,e,r){t.exports=r.p+"img/slide-1.7c2f5d3.jpeg"},SYUG:function(t,e,r){t.exports=r.p+"img/หัตถกรรม.ca5959c.jpeg"},TJ5S:function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAApCAYAAADAk4LOAAAFgUlEQVR4Aa1XA5BjWRTN2oW17d3YaZtr2962HUzbDNpjszW24mRt28p47v7zq/bXZtrp/lWnXr337j3nPCe85NcypgSFdugCpW5YoDAMRaIMqRi6aKq5E3YqDQO3qAwjVWrD8Ncq/RBpykd8oZUb/kaJutow8r1aP9II0WmLKLIsJyv1w/kqw9Ch2MYdB++12Onxee/QMwvf4/Dk/Lfp/i4nxTXtOoQ4pW5Aj7wpici1A9erdAN2OH64x8OSP9j3Ft3b7aWkTg/Fm91siTra0f9on5sQr9INejH6CUUUpavjFNq1B+Oadhxmnfa8RfEmN8VNAsQhPqF55xHkMzz3jSmChWU6f7/XZKNH+9+hBLOHYozuKQPxyMPUKkrX/K0uWnfFaJGS1QPRtZsOPtr3NsW0uyh6NNCOkU3Yz+bXbT3I8G3xE5EXLXtCXbbqwCO9zPQYPRTZ5vIDXD7U+w7rFDEoUUf7ibHIR4y6bLVPXrz8JVZEql13trxwue/uDivd3fkWRbS6/IA2bID4uk0UpF1N8qLlbBlXs4Ee7HLTfV1j54APvODnSfOWBqtKVvjgLKzF5YdEk5ewRkGlK0i33Eofffc7HT56jD7/6U+qH3Cx7SBLNntH5YIPvODnyfIXZYRVDPqgHtLs5ABHD3YzLuespb7t79FY34DjMwrVrcTuwlT55YMPvOBnRrJ4VXTdNnYug5ucHLBjEpt30701A3Ts+HEa73u6dT3FNWwflY86eMHPk+Yu+i6pzUpRrW7SNDg5JHR4KapmM5Wv2E8Tfcb1HoqqHMHU+uWDD7zg54mz5/2BSnizi9T1Dg4QQXLToGNCkb6tb1NU+QAlGr1++eADrzhn/u8Q2YZhQVlZ5+CAOtqfbhmaUCS1ezNFVm2imDbPmPng5wmz+gwh+oHDce0eUtQ6OGDIyR0uUhUsoO3vfDmmgOezH0mZN59x7MBi++WDL1g/eEiU3avlidO671bkLfwbw5XV2P8Pzo0ydy4t2/0eu33xYSOMOD8hTf4CrBtGMSoXfPLchX+J0ruSePw3LZeK0juPJbYzrhkH0io7B3k164hiGvawhOKMLkrQLyVpZg8rHFW7E2uHOL888IBPlNZ1FPzstSJM694fWr6RwpvcJK60+0HCILTBzZLFNdtAzJaohze60T8qBzyh5ZuOg5e7uwQppofEmf2++DYvmySqGBuKaicF1blQjhuHdvCIMvp8whTTfZzI7RldpwtSzL+F1+wkdZ2TBOW2gIF88PBTzD/gpeREAMEbxnJcaJHNHrpzji0gQCS6hdkEeYt9DF/2qPcEC8RM28Hwmr3sdNyht00byAut2k3gufWNtgtOEOFGUwcXWNDbdNbpgBGxEvKkOQsxivJx33iow0Vw5S6SVTrpVq11ysA2Rp7gTfPfktc6zhtXBBC+adRLshf6sG2RfHPZ5EAc4sVZ83yCN00Fk/4kggu40ZTvIEm5g24qtU4KjBrx/BTTH8ifVASAG7gKrnWxJDcU7x8X6Ecczhm3o6YicvsLXWfh3Ch1W0k8x0nXF+0fFxgt4phz8QvypiwCCFKMqXCnqXExjq10beH+UUA7+nG6mdG/Pu0f3LgFcGrl2s0kNNjpmoJ9o4B29CMO8dMT4Q5ox8uitF6fqsrJOr8qnwNbRzv6hSnG5wP+64C7h9lp30hKNtKdWjtdkbuPA19nJ7Tz3zR/ibgARbhb4AlhavcBebmTHcFl2fvYEnW0ox9xMxKBS8btJ+KiEbq9zA4RthQXDhPa0T9TEe69gWupwc6uBUphquXgf+/FrIjweHQS4/pduMe5ERUMHUd9xv8ZR98CxkS4F2n3EUrUZ10EYNw7BWm9x1GiPssi3GgiGRDKWRYZfXlON+dfNbM+GgIwYdwAAAAASUVORK5CYII="},UPOJ:function(t,e){},"UW+1":function(t,e,r){t.exports=r.p+"img/ปศุสัตว์ และประมงค์.26dc4d5.jpeg"},UdIB:function(t,e){},Uhzn:function(t,e,r){t.exports=r.p+"img/cover.df23d59.jpeg"},VWvK:function(t,e,r){t.exports=r.p+"img/ไม้ดอกไม้ประดับ.28b44b9.jpeg"},W4HE:function(t,e,r){t.exports=r.p+"img/vega-card.2468c28.jpeg"},XFLb:function(t,e,r){t.exports=r.p+"img/ไม้ผล.2084a3c.jpeg"},XXIg:function(t,e,r){t.exports=r.p+"img/ข้าวและธัญพืช.44809d5.jpeg"},YwoB:function(t,e,r){t.exports=r.p+"img/cover3.861900b.jpeg"},ZzoQ:function(t,e){},fRiH:function(t,e,r){t.exports=r.p+"img/slider4.0e80ba7.jpg"},fWV0:function(t,e,r){t.exports=r.p+"img/icon3.247aff9.png"},ffJP:function(t,e,r){t.exports=r.p+"img/travel.17131eb.jpeg"},g2dD:function(t,e){},"j/kf":function(t,e,r){t.exports=r.p+"img/vega-card-3.da279ce.jpeg"},jBLA:function(t,e,r){var o={"./content-1.jpeg":"4BYA","./content.jpeg":"DkYy","./cover.jpeg":"Uhzn","./cover2.jpeg":"Mm10","./cover3.jpeg":"YwoB","./cover4.jpeg":"F4eg","./cover5.jpeg":"EyTm","./field.jpeg":"Ot1l","./fruitree.jpeg":"34Nt","./localplant.jpeg":"N9tS","./login-logo.jpeg":"3+hF","./slide-1.jpeg":"RDci","./travel.jpeg":"ffJP","./vega-card.jpeg":"MKGl","./vegatables1.jpeg":"zmdf","./ข้าวและธัญพืช.jpeg":"XXIg","./ชา กาแฟ และโกโก้.jpeg":"2WO5","./ปศุสัตว์ และประมงค์.jpeg":"6seM","./ผลิตภัณฑ์แปรรูป.jpeg":"m/As","./ผัก.jpeg":"8ZCl","./ผักและสมุนไพร.jpeg":"GTGI","./พืชท้องถิ่น.jpeg":"5S8a","./หัตถกรรม.jpeg":"2oNb","./ไม้ดอกไม้ประดับ.jpeg":"mlUp","./ไม้ผล.jpeg":"uYUO"};function a(t){return r(i(t))}function i(t){var e=o[t];if(!(e+1))throw new Error("Cannot find module '"+t+"'.");return e}a.keys=function(){return Object.keys(o)},a.resolve=i,t.exports=a,a.id="jBLA"},jQqh:function(t,e){},jYSa:function(t,e,r){t.exports=r.p+"img/5.983bddd.jpg"},kx0P:function(t,e,r){t.exports=r.p+"img/deal3.e9d6c61.jpg"},l25F:function(t,e,r){t.exports=r.p+"img/ผักและสมุนไพร2.a668898.jpeg"},"m/As":function(t,e,r){t.exports=r.p+"img/ผลิตภัณฑ์แปรรูป.6a0f299.jpeg"},mlUp:function(t,e,r){t.exports=r.p+"img/ไม้ดอกไม้ประดับ.0efeda6.jpeg"},pqEl:function(t,e,r){t.exports=r.p+"img/3.6bb2983.jpg"},pufY:function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAAC7AAAAuwGdWYJhAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAASlQTFRFAMIAAsICA8MDBMYEBcYFCcQJC8ULDMUMDsgOD8YPEMYQEsYSFMcUFMoUFscWF8gXF8oXGMgYH8wfI80jJ84nKs8qLc0tLs0uNM40OdA5OtA6O9A7QtJCQtRCR9VHStZKUtZSUthSVdZVVdhVVtdWWddZYtliYttiZNxkZ9tnZ9xnaN1ocd9xct9ydeB1eN94eeF5e997hOKEheKFh+SHiuSKk+aTluaWnemdn+ifoemhoumipOqkqeqpqeupq+urr+2vsOywse6xsu2ytO20tO60te21ue65vPC8w/HDxPHEyvLKzPPMzvPOz/TP0/XT1fXV1/XX1/bX2vfa3ffd4fjh5vnm6Pro6frp6/rr7fvt8fzx9f31+P34+v76/P78/f/9/v/+////qVDaCQAAAMhJREFUGBm1wXc3QnEAx+GvGVFWwkW2BmWFCJGRLQ0rpT7v/0Vwzu+e3Hvq355HHeG1ZofUIph5489HZkpOY+k6tsapX039Tzg8emTrusAlJ5sF71CulviuvJznYVrGDiwU2bjuuT3Yn4ykYFfGDYQKxLIDE4lkIJKCOxmHECoQy46f9SYDl0W4krEGYd/K9v0Smyfzo3FYl+Et4/I1KNtMDadFNS1/8m9LDsNHVYx6VG59c3s/QGVVrR5oHI+ojddnS235u9URv8YHQmbtGLByAAAAAElFTkSuQmCC"},qG1N:function(t,e,r){t.exports=r.p+"img/rice-card.936e5aa.jpeg"},qXhe:function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAABSCAMAAAAhFXfZAAAC91BMVEVMaXEzeak2f7I4g7g3g7cua5gzeKg8hJo3grY4g7c3grU0gLI2frE0daAubJc2gbQwd6QzeKk2gLMtd5sxdKIua5g1frA2f7IydaM0e6w2fq41fK01eqo3grgubJgta5cxdKI1f7AydaQydaMxc6EubJgvbJkwcZ4ubZkwcJwubZgubJcydqUydKIxapgubJctbJcubZcubJcvbJYubJcvbZkubJctbJctbZcubJg2f7AubJcrbZcubJcubJcua5g3grY0fq8ubJcubJdEkdEwhsw6i88vhswuhcsuhMtBjMgthMsrg8srgss6is8qgcs8i9A9iMYtg8spgcoogMo7hcMngMonf8olfso4gr8kfck5iM8jfMk4iM8he8k1fro7itAgesk2hs8eecgzfLcofssdeMg0hc4cd8g2hcsxeLQbdsgZdcgxeLImfcszhM0vda4xgckzhM4xg84wf8Yxgs4udKsvfcQucqhUndROmdM1fK0wcZ8vb5w0eqpQm9MzeKhXoNVcpdYydKNWn9VZotVKltJFjsIwcJ1Rms9OlslLmtH///8+kc9epdYzd6dbo9VHkMM2f7FHmNBClM8ydqVcpNY9hro3gLM9hLczealQmcw3fa46f7A8gLMxc6I3eagyc6FIldJMl9JSnNRSntNNl9JPnNJFi75UnM9ZodVKksg8kM45jc09e6ZHltFBk883gbRBh7pDk9EwcaBzn784g7dKkcY2i81Om9M7j85Llc81is09g7Q4grY/j9A0eqxKmdFFltBEjcXf6fFImdBCiLxJl9FGlNFBi78yiMxVndEvbpo6js74+vx+psPP3+o/ks5HkcpGmNCjwdZCkNDM3ehYoNJEls+lxNkxh8xHks0+jdC1zd5Lg6r+/v/H2ufz9/o3jM3t8/edvdM/k89Th61OiLBSjbZklbaTt9BfptdjmL1AicBHj8hGk9FAgK1dkLNTjLRekrdClc/k7fM0icy0y9tgp9c4jc2NtM9Dlc8zicxeXZn3AAAAQ3RSTlMAHDdTb4yPA+LtnEQmC4L2EmHqB7XA0d0sr478x4/Yd5i1zOfyPkf1sLVq4Nh3FvjxopQ2/STNuFzUwFIwxKaejILpIBEV9wAABhVJREFUeF6s1NdyFEcYBeBeoQIhRAkLlRDGrhIgY3BJL8CVeKzuyXFzzjkn5ZxzzuScg3PO8cKzu70JkO0LfxdTU//pM9vTu7Xgf6KqOVTb9X7toRrVEfBf1HTVjZccrT/2by1VV928Yty9ZbVuucdz90frG8DBjl9pVApbOstvmMuvVgaNXSfAAd6pGxpy6yxf5ph43pS/4f3uoaGm2rdu72S9xzOvMymkZFq/ptDrk90mhW7e4zl7HLzhxGWPR20xmSxJ/VqldG5m9XhaVOA1DadsNh3Pu5L2N6QtPO/32JpqQBVVk20oy/Pi2s23WEvyfHbe1thadVQttvm7Llf65gGmXK67XtupyoM7HQhmXdLS8oGWJNeOJ3C5fG5XCEJnkez3/oFdsvgJ4l2ANZwhrJKk/7OSXa+3Vw2WJMlKnGkobouYk6T0TyX30klOUnTD9HJ5qpckL3EW/w4XF3Xd0FGywXUrstrclVsqz5Pd/sXFYyDnPdrLcQODmGOK47IZb4CmibmMn+MYRzFZ5jg33ZL/EJrWcszHmANy3ARBK/IXtciJy8VsitPSdE3uuHxzougojcUdr8/32atnz/ev3f/K5wtpxUTpcaI45zusVDpYtZi+jg0oU9b3x74h7+n9ABvYEZeKaVq0sh0AtLKsFtqNBdeT0MrSzwwlq9+x6xAO4tgOtSzbCjrNQQiNvQUbUEubvzBUeGw26yDCsRHCoLkTHDa7IdOLIThs/gHvChszh2CimE8peRs47cxANI0lYNB5y1DljpOF0IhzBDPOZnDOqYYbeGKECbPzWnXludPphw5c2YBq5zlwXphIbO4VDCZ0gnPfUO1TwZoYwAs2ExPCedAu9DAjfQUjzITQb3jNj0KG2Sgt6BHaQUdYzWz+XmBktOHwanXjaSTcwwziBcuMOtwBmqPrTOxFQR/DRKKPqyur0aiW6cULYsx6tBm0jXpR/AUWR6HRq9WVW6MRhIq5jLyjbaCTDCijyYJNpCajdyobP/eTw0iexBAKkJ3gA5KcQb2zBXsIBckn+xVv8jkZSaEFHE+jFEleAEfayRU0MouNoBmB/L50Ai/HSLIHxcrpCvnhSQAuakKp2C/YbCylJjXRVy/z3+Kv/RrNcCo+WUzlVEhzKffnTQnxeN9fWF88fiNCUdSTsaufaChKWInHeysygfpIqagoakW+vV20J8uyl6TyNKEZWV4oRSPyCkWpgOLSbkCObT8o2r6tlG58HQquf6O0v50tB7JM7F4EORd2dx/K0w/KHsVkLPaoYrwgP/y7krr3SSMA4zj+OBgmjYkxcdIJQyQRKgg2viX9Hddi9UBb29LrKR7CVVEEEXWojUkXNyfTNDE14W9gbHJNuhjDettN3ZvbOvdOqCD3Jp/9l+/wJE+9PkYGjx/fqkys3S2rMozM/o2106rfMUINo6hVqz+eu/hd1c4xTg0TAfy5kV+4UG6+IthHTU9woWmxuKNbTfuCSfovBCxq7EtHqvYL4Sm6F8GVxsSXHMQ07TOi1DKtZxjWaaIyi4CXWjxPccUw8WVbMYY5wxC1mzEyXMJWkllpRloi+Kkoq69sxBTlElF6aAxYUbjXNlhlDZilDnM4U5SlN5biRsRHnbx3mbeWjEh4mEyiuJDl5XcWVmX5GvNkFgLWZM5qwsop4/AWfLhU1cR7k1VVvcYCWRkOI6Xy5gmnphCYIkvzuNYzHzosq2oNk2RtSs8khfUOfHIDgR6ysYBaMpl4uEgk2U/oJTs9AaTSwma7dT69geAE2ZpEjUsn2ieJNHeKfrI3EcAGJ2ZaNgVuC8EBctCLc57P5u5led6IOBkIYkuQMrmmjChs4VkfOerHqSBkPzZlhe06RslZ3zMjk2sscqKwY0RcjKK+LWbzd7KiHhkncs/siFJ+V5eXxD34B8nVuJEpGJNmxN2gH3vSvp7J70tF+D1Ej8qUJD1TkErAND2GZwTFg/LubvmgiBG3SOvdlsqFQrkEzJCL1rstlnVFROixZoDDSuXQFHESwVGlcuQcMb/b42NgjLowh5MTDFE3vNB5qStRIErdCQEh6pLPR92anSUb/wAIhldAaDMpGgAAAABJRU5ErkJggg=="},qiuY:function(t,e,r){t.exports=r.p+"img/icon3.50b65e9.svg"},rOEL:function(t,e){t.exports="data:image/svg+xml;base64,PHN2ZyBpZD0iU3ZnanNTdmcxMDE2IiB3aWR0aD0iMjg4IiBoZWlnaHQ9IjI4OCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpzdmdqcz0iaHR0cDovL3N2Z2pzLmNvbS9zdmdqcyI+Cgk8ZGVmcyBpZD0iU3ZnanNEZWZzMTAxNyI+Cgk8L2RlZnM+Cgk8ZyBpZD0iU3ZnanNHMTAxOCIgdHJhbnNmb3JtPSJtYXRyaXgoMC45MTY3LDAsMCwwLjkxNjcsMTEuOTk3MDUwMTgyNTMzMjU4LDExLjk5MzcxODkwMDY4MDUzNCkiPgoJCTxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjI4OCIgaGVpZ2h0PSIyODgiIHZpZXdCb3g9IjAgMCAzMiAzMiI+CgkJCTxkZWZzPgoJCQkJPGxpbmVhckdyYWRpZW50IGlkPSJhIj4KCQkJCQk8c3RvcCBvZmZzZXQ9IjAiIHN0b3AtY29sb3I9IiMyMDI5NTYiPgoJCQkJCTwvc3RvcD4KCQkJCQk8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiMyODNlNzkiPgoJCQkJCTwvc3RvcD4KCQkJCTwvbGluZWFyR3JhZGllbnQ+CgkJCQk8bGluZWFyR3JhZGllbnQgaWQ9ImIiIHgxPSIuOTk4IiB4Mj0iMjkiIHkxPSIxNS45OTgiIHkyPSIxNS45OTgiIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4bGluazpocmVmPSIjYSI+CgkJCQk8L2xpbmVhckdyYWRpZW50PgoJCQk8L2RlZnM+CgkJCTxwYXRoIGZpbGw9InVybCgjYikiIGQ9Ik0gOS41IDEgQyA4LjY3NzY0MzUgMSA4IDEuNjc3NyA4IDIuNSBMIDggNi41IEMgOCA3LjMyMjQgOC42Nzc2NDM1IDggOS41IDggTCAyNi41IDggQyAyNy4zMjIzNTYgOCAyOCA3LjMyMjQgMjggNi41IEwgMjggNC41ODU5Mzc1IEMgMjguMDAzMyA0LjU3NDgxNDYgMjguMDEyMzkzIDQuNTQwMTU4NSAyOC4wNDEwMTYgNC41IEMgMjguMTAwODg2IDQuNDEyIDI4LjIwNjc0MiA0LjI4MzkyNSAyOC4zMzc4OTEgNC4xNDA2MjUgQyAyOC42MDAxODcgMy44NTQxMjUgMjguOTY3MTg2IDMuNTAyNjY4OCAyOS4zMzU5MzggMy4xNjc5Njg4IEMgMzAuMDczNDM4IDIuNDk4NTY4OCAzMC44MTY0MDYgMS44OTI1NzgxIDMwLjgxNjQwNiAxLjg5MjU3ODEgQSAwLjUwMDA1IDAuNTAwMDUgMCAwIDAgMzAuNSAxIEwgOS41IDEgeiBNIDkuNSAyIEwgMjkuMTU2MjUgMiBDIDI4LjkzNTk5MyAyLjE5IDI4LjkxMDg3NCAyLjE5OTcyODEgMjguNjY0MDYyIDIuNDIzODI4MSBDIDI4LjI4MjgxOCAyLjc2OTgyODEgMjcuODk5ODEgMy4xMzI5Mzc1IDI3LjU5OTYwOSAzLjQ2MDkzNzUgQyAyNy40NDk1MDkgMy42MjQ4Mzc1IDI3LjMyMDk5MSAzLjc3NzM4NzUgMjcuMjE2Nzk3IDMuOTI5Njg3NSBDIDI3LjExMjYwMyA0LjA4MTk4NzUgMjcgNC4yMDUxIDI3IDQuNSBMIDI3IDYuNSBDIDI3IDYuNzg1NyAyNi43ODU2NjIgNyAyNi41IDcgTCA5LjUgNyBDIDkuMjE0MzM2NSA3IDkgNi43ODU3IDkgNi41IEwgOSAyLjUgQyA5IDIuMjE0NCA5LjIxNDMzNjUgMiA5LjUgMiB6IE0gMTUuNSA0IEEgMC41IDAuNSAwIDAgMCAxNSA0LjUgQSAwLjUgMC41IDAgMCAwIDE1LjUgNSBBIDAuNSAwLjUgMCAwIDAgMTYgNC41IEEgMC41IDAuNSAwIDAgMCAxNS41IDQgeiBNIDE3LjUgNCBBIDAuNSAwLjUgMCAwIDAgMTcgNC41IEEgMC41IDAuNSAwIDAgMCAxNy41IDUgQSAwLjUgMC41IDAgMCAwIDE4IDQuNSBBIDAuNSAwLjUgMCAwIDAgMTcuNSA0IHogTSAxOS41IDQgQSAwLjUgMC41IDAgMCAwIDE5IDQuNSBBIDAuNSAwLjUgMCAwIDAgMTkuNSA1IEEgMC41IDAuNSAwIDAgMCAyMCA0LjUgQSAwLjUgMC41IDAgMCAwIDE5LjUgNCB6IE0gMS41IDguOTk2MDkzOCBMIDEuNSA5IEEgMC41MDAwNSAwLjUwMDA1IDAgMCAwIDEuMTgzNTkzOCA5Ljg4ODY3MTkgQyAxLjE4MzU5MzggOS44ODg2NzE5IDEuOTI2NTYyMSAxMC40OTQ2NjMgMi42NjQwNjI1IDExLjE2NDA2MiBDIDMuMDMyODEyNyAxMS40OTg3NjMgMy4zOTk4MTI4IDExLjg1MDIxOSAzLjY2MjEwOTQgMTIuMTM2NzE5IEMgMy43OTMyNTc3IDEyLjI4MDAxOSAzLjg5OTExNjggMTIuNDA4NTk0IDMuOTU4OTg0NCAxMi40OTYwOTQgQyAzLjk4NzYyODUgMTIuNTM3NzIgMy45OTY3MTAxIDEyLjU3MjcxNyA0IDEyLjU4Mzk4NCBMIDQgMTQuNDk2MDk0IEMgNCAxNS4zMTg0OTQgNC42Nzc2NDQgMTUuOTk2MDk0IDUuNSAxNS45OTYwOTQgTCAyMi41IDE1Ljk5NjA5NCBDIDIzLjMyMjM1NyAxNS45OTYwOTQgMjQgMTUuMzE4NDk0IDI0IDE0LjQ5NjA5NCBMIDI0IDEwLjQ5NjA5NCBDIDI0IDkuNjczNzkzNyAyMy4zMjIzNTcgOC45OTYwOTM4IDIyLjUgOC45OTYwOTM4IEwgMS41IDguOTk2MDkzOCB6IE0gMi44NDM3NSAxMCBMIDIyLjUgMTAgQyAyMi43ODU2NjMgMTAgMjMgMTAuMjE0NCAyMyAxMC41IEwgMjMgMTQuNSBDIDIzIDE0Ljc4NTcgMjIuNzg1NjYzIDE1IDIyLjUgMTUgTCA1LjUgMTUgQyA1LjIxNDMzOCAxNSA1IDE0Ljc4NTcgNSAxNC41IEwgNSAxMi41IEMgNSAxMi4yMDUxIDQuODg3Mzk3MSAxMi4wODE5ODggNC43ODMyMDMxIDExLjkyOTY4OCBDIDQuNjc5MDA5MSAxMS43NzczODggNC41NTA0OTA3IDExLjYyNDgzOCA0LjQwMDM5MDYgMTEuNDYwOTM4IEMgNC4xMDAxOTA0IDExLjEzMjkzOCAzLjcxNzE4MzEgMTAuNzY5ODI4IDMuMzM1OTM3NSAxMC40MjM4MjggQyAzLjA4OTEyNjcgMTAuMTk5NzI4IDMuMDY0MDA2NyAxMC4xOSAyLjg0Mzc1IDEwIHogTSAxMS41IDEyIEEgMC41IDAuNSAwIDAgMCAxMSAxMi41IEEgMC41IDAuNSAwIDAgMCAxMS41IDEzIEEgMC41IDAuNSAwIDAgMCAxMiAxMi41IEEgMC41IDAuNSAwIDAgMCAxMS41IDEyIHogTSAxMy41IDEyIEEgMC41IDAuNSAwIDAgMCAxMyAxMi41IEEgMC41IDAuNSAwIDAgMCAxMy41IDEzIEEgMC41IDAuNSAwIDAgMCAxNCAxMi41IEEgMC41IDAuNSAwIDAgMCAxMy41IDEyIHogTSAxNS41IDEyIEEgMC41IDAuNSAwIDAgMCAxNSAxMi41IEEgMC41IDAuNSAwIDAgMCAxNS41IDEzIEEgMC41IDAuNSAwIDAgMCAxNiAxMi41IEEgMC41IDAuNSAwIDAgMCAxNS41IDEyIHogTSAxNy41IDE3IEMgMTYuNjc3NjQzIDE3IDE2IDE3LjY3NzcgMTYgMTguNSBMIDE2IDIxLjUgQyAxNiAyMi4zMjI0IDE2LjY3NzY0MyAyMyAxNy41IDIzIEwgMjYuNSAyMyBDIDI3LjMyMjM1NiAyMyAyOCAyMi4zMjI0IDI4IDIxLjUgTCAyOCAyMC41ODU5MzggQyAyOC4wMDMzIDIwLjU3NDgxNSAyOC4wMTIzOTMgMjAuNTQwMTU4IDI4LjA0MTAxNiAyMC41IEMgMjguMTAwODg2IDIwLjQxMiAyOC4yMDY3NDIgMjAuMjgzOTI1IDI4LjMzNzg5MSAyMC4xNDA2MjUgQyAyOC42MDAxODcgMTkuODU0MTI1IDI4Ljk2NzE4NiAxOS41MDI2NjkgMjkuMzM1OTM4IDE5LjE2Nzk2OSBDIDMwLjA3MzQzOCAxOC40OTg1NjkgMzAuODE2NDA2IDE3Ljg5MjU3OCAzMC44MTY0MDYgMTcuODkyNTc4IEEgMC41MDAwNSAwLjUwMDA1IDAgMCAwIDMwLjUgMTcgTCAxNy41IDE3IHogTSAxNy41IDE4IEwgMjkuMTU2MjUgMTggQyAyOC45MzU5OTMgMTguMTkgMjguOTEwODc0IDE4LjE5OTcyOCAyOC42NjQwNjIgMTguNDIzODI4IEMgMjguMjgyODE4IDE4Ljc2OTgyOCAyNy44OTk4MSAxOS4xMzI5MzggMjcuNTk5NjA5IDE5LjQ2MDkzOCBDIDI3LjQ0OTUwOSAxOS42MjQ4MzggMjcuMzIwOTkxIDE5Ljc3NzM4OCAyNy4yMTY3OTcgMTkuOTI5Njg4IEMgMjcuMTEyNjAzIDIwLjA4MTk4NyAyNyAyMC4yMDUxIDI3IDIwLjUgTCAyNyAyMS41IEMgMjcgMjEuNzg1NyAyNi43ODU2NjIgMjIgMjYuNSAyMiBMIDE3LjUgMjIgQyAxNy4yMTQzMzUgMjIgMTcgMjEuNzg1NyAxNyAyMS41IEwgMTcgMTguNSBDIDE3IDE4LjIxNDQgMTcuMjE0MzM3IDE4IDE3LjUgMTggeiBNIDIwIDE5LjUgQSAwLjUgMC41IDAgMCAwIDE5LjUgMjAgQSAwLjUgMC41IDAgMCAwIDIwIDIwLjUgQSAwLjUgMC41IDAgMCAwIDIwLjUgMjAgQSAwLjUgMC41IDAgMCAwIDIwIDE5LjUgeiBNIDIyIDE5LjUgQSAwLjUgMC41IDAgMCAwIDIxLjUgMjAgQSAwLjUgMC41IDAgMCAwIDIyIDIwLjUgQSAwLjUgMC41IDAgMCAwIDIyLjUgMjAgQSAwLjUgMC41IDAgMCAwIDIyIDE5LjUgeiBNIDI0IDE5LjUgQSAwLjUgMC41IDAgMCAwIDIzLjUgMjAgQSAwLjUgMC41IDAgMCAwIDI0IDIwLjUgQSAwLjUgMC41IDAgMCAwIDI0LjUgMjAgQSAwLjUgMC41IDAgMCAwIDI0IDE5LjUgeiBNIDEuNSAyMy45OTYwOTQgTCAxLjUgMjQgQSAwLjUwMDA1IDAuNTAwMDUgMCAwIDAgMS4xODM1OTM4IDI0Ljg4ODY3MiBDIDEuMTgzNTkzOCAyNC44ODg2NzIgMS45MjY1NjIxIDI1LjQ5NDY2MyAyLjY2NDA2MjUgMjYuMTY0MDYyIEMgMy4wMzI4MTI3IDI2LjQ5ODc2MyAzLjM5OTgxMjggMjYuODUwMjE5IDMuNjYyMTA5NCAyNy4xMzY3MTkgQyAzLjc5MzI1NzcgMjcuMjgwMDE5IDMuODk5MTE2OCAyNy40MDg1OTQgMy45NTg5ODQ0IDI3LjQ5NjA5NCBDIDMuOTg3NjI4NSAyNy41Mzc3MiAzLjk5NjcxMDEgMjcuNTcyNzE3IDQgMjcuNTgzOTg0IEwgNCAyOS40OTYwOTQgQyA0IDMwLjMxODQ5NCA0LjY3NzY0NCAzMC45OTYwOTQgNS41IDMwLjk5NjA5NCBMIDE4LjUgMzAuOTk2MDk0IEMgMTkuMzIyMzU3IDMwLjk5NjA5NCAyMCAzMC4zMTg0OTQgMjAgMjkuNDk2MDk0IEwgMjAgMjUuNDk2MDk0IEMgMjAgMjQuNjczNzk0IDE5LjMyMjM1NyAyMy45OTYwOTQgMTguNSAyMy45OTYwOTQgTCAxLjUgMjMuOTk2MDk0IHogTSAyLjg0Mzc1IDI1IEwgMTguNSAyNSBDIDE4Ljc4NTY2MyAyNSAxOSAyNS4yMTQ0IDE5IDI1LjUgTCAxOSAyOS41IEMgMTkgMjkuNzg1NyAxOC43ODU2NjMgMzAgMTguNSAzMCBMIDUuNSAzMCBDIDUuMjE0MzM4IDMwIDUgMjkuNzg1NyA1IDI5LjUgTCA1IDI3LjUgQyA1IDI3LjIwNTEgNC44ODczOTcxIDI3LjA4MTk4OCA0Ljc4MzIwMzEgMjYuOTI5Njg4IEMgNC42NzkwMDkxIDI2Ljc3NzM4OCA0LjU1MDQ5MDcgMjYuNjI0ODM4IDQuNDAwMzkwNiAyNi40NjA5MzggQyA0LjEwMDE5MDQgMjYuMTMyOTM4IDMuNzE3MTgzMSAyNS43Njk4MjggMy4zMzU5Mzc1IDI1LjQyMzgyOCBDIDMuMDg5MTI2NyAyNS4xOTk3MjggMy4wNjQwMDY3IDI1LjE5IDIuODQzNzUgMjUgeiBNIDEwLjUgMjcgQSAwLjUgMC41IDAgMCAwIDEwIDI3LjUgQSAwLjUgMC41IDAgMCAwIDEwLjUgMjggQSAwLjUgMC41IDAgMCAwIDExIDI3LjUgQSAwLjUgMC41IDAgMCAwIDEwLjUgMjcgeiBNIDEyLjUgMjcgQSAwLjUgMC41IDAgMCAwIDEyIDI3LjUgQSAwLjUgMC41IDAgMCAwIDEyLjUgMjggQSAwLjUgMC41IDAgMCAwIDEzIDI3LjUgQSAwLjUgMC41IDAgMCAwIDEyLjUgMjcgeiBNIDE0LjUgMjcgQSAwLjUgMC41IDAgMCAwIDE0IDI3LjUgQSAwLjUgMC41IDAgMCAwIDE0LjUgMjggQSAwLjUgMC41IDAgMCAwIDE1IDI3LjUgQSAwLjUgMC41IDAgMCAwIDE0LjUgMjcgeiAiIGNvbG9yPSIjMDAwIiBmb250LWZhbWlseT0ic2Fucy1zZXJpZiIgZm9udC13ZWlnaHQ9IjQwMCIgb3ZlcmZsb3c9InZpc2libGUiIHdoaXRlLXNwYWNlPSJub3JtYWwiIHN0eWxlPSJsaW5lLWhlaWdodDpub3JtYWw7dGV4dC1pbmRlbnQ6MDt0ZXh0LWFsaWduOnN0YXJ0O3RleHQtZGVjb3JhdGlvbi1saW5lOm5vbmU7dGV4dC1kZWNvcmF0aW9uLXN0eWxlOnNvbGlkO3RleHQtZGVjb3JhdGlvbi1jb2xvcjojMDAwO3RleHQtdHJhbnNmb3JtOm5vbmU7YmxvY2stcHJvZ3Jlc3Npb246dGI7aXNvbGF0aW9uOmF1dG87bWl4LWJsZW5kLW1vZGU6bm9ybWFsIj4KCQkJPC9wYXRoPgoJCTwvc3ZnPgoJPC9nPgo8L3N2Zz4K"},s2z8:function(t,e,r){t.exports=r.p+"img/fruit-2.6776c77.jpeg"},"s3/3":function(t,e,r){t.exports=r.p+"img/vega-card-4.53f7db3.jpeg"},s7bB:function(t,e,r){t.exports=r.p+"img/ผลิตภัณฑ์แปรรูป.774beb7.jpeg"},sr7T:function(t,e,r){t.exports=r.p+"img/ผักและสมุนไพร.7fd8f80.jpeg"},uAlE:function(t,e,r){t.exports=r.p+"img/slider3.6f27a30.jpg"},uMNc:function(t,e,r){t.exports=r.p+"img/deal2.01628a5.jpg"},uYUO:function(t,e,r){t.exports=r.p+"img/ไม้ผล.8a698a2.jpeg"},va8I:function(t,e){},wkq0:function(t,e){t.exports="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAApCAQAAAACach9AAACMUlEQVR4Ae3ShY7jQBAE0Aoz/f9/HTMzhg1zrdKUrJbdx+Kd2nD8VNudfsL/Th///dyQN2TH6f3y/BGpC379rV+S+qqetBOxImNQXL8JCAr2V4iMQXHGNJxeCfZXhSRBcQMfvkOWUdtfzlLgAENmZDcmo2TVmt8OSM2eXxBp3DjHSMFutqS7SbmemzBiR+xpKCNUIRkdkkYxhAkyGoBvyQFEJEefwSmmvBfJuJ6aKqKWnAkvGZOaZXTUgFqYULWNSHUckZuR1HIIimUExutRxwzOLROIG4vKmCKQt364mIlhSyzAf1m9lHZHJZrlAOMMztRRiKimp/rpdJDc9Awry5xTZCte7FHtuS8wJgeYGrex28xNTd086Dik7vUMscQOa8y4DoGtCCSkAKlNwpgNtphjrC6MIHUkR6YWxxs6Sc5xqn222mmCRFzIt8lEdKx+ikCtg91qS2WpwVfBelJCiQJwvzixfI9cxZQWgiSJelKnwBElKYtDOb2MFbhmUigbReQBV0Cg4+qMXSxXSyGUn4UbF8l+7qdSGnTC0XLCmahIgUHLhLOhpVCtw4CzYXvLQWQbJNmxoCsOKAxSgBJno75avolkRw8iIAFcsdc02e9iyCd8tHwmeSSoKTowIgvscSGZUOA7PuCN5b2BX9mQM7S0wYhMNU74zgsPBj3HU7wguAfnxxjFQGBE6pwN+GjME9zHY7zGp8wVxMShYX9NXvEWD3HbwJf4giO4CFIQxXScH1/TM+04kkBiAAAAAElFTkSuQmCC"},wsk5:function(t,e,r){t.exports=r.p+"img/field-card.55e41d6.jpeg"},x3G2:function(t,e,r){t.exports=r.p+"img/ชา กาแฟ และโกโก้.5a3a78f.jpeg"},xQfL:function(t,e,r){t.exports=r.p+"img/ข้าวและธัญพืช.dc5f93a.jpeg"},xgfO:function(t,e,r){t.exports=r.p+"img/fresh.eb1ab26.png"},zmdf:function(t,e,r){t.exports=r.p+"img/vegatables1.8a47871.jpeg"}},["NHnr"]); //# sourceMappingURL=app.5e42247cbcbe916c1d25.js.map
/** * @module Schemas/Core/Uniform * @desc Export the ThreeJs Uniform Model and Schema for Mongoose. * @author [Tristan Valcke]{@link https://github.com/Itee} * @license [BSD-3-Clause]{@link https://opensource.org/licenses/BSD-3-Clause} */
/* filter_sse2_intrinsics.c - SSE2 optimized filter functions * * Copyright (c) 2016-2017 Glenn Randers-Pehrson * Written by Mike Klein and Matt Sarett * Derived from arm/filter_neon_intrinsics.c * * Last changed in libpng 1.6.31 [(PENDING RELEASE)] * * This code is released under the libpng license. * For conditions of distribution and use, see the disclaimer * and license in png.h */ #include "pngpriv.h" #ifdef PNG_READ_SUPPORTED #if PNG_INTEL_SSE_IMPLEMENTATION > 0 #include <immintrin.h> /* Functions in this file look at most 3 pixels (a,b,c) to predict the 4th (d). * They're positioned like this: * prev: c b * row: a d * The Sub filter predicts d=a, Avg d=(a+b)/2, and Paeth predicts d to be * whichever of a, b, or c is closest to p=a+b-c. */ static __m128i load4(const void* p) { return _mm_cvtsi32_si128(*(const int*)p); } static void store4(void* p, __m128i v) { *(int*)p = _mm_cvtsi128_si32(v); } static __m128i load3(const void* p) { /* We'll load 2 bytes, then 1 byte, * then mask them together, and finally load into SSE. */ const png_uint_16* p01 = (png_const_uint_16p)p; const png_byte* p2 = (const png_byte*)(p01+1); png_uint_32 v012 = (png_uint_32)(*p01) | (png_uint_32)(*p2) << 16; return load4(&v012); } static void store3(void* p, __m128i v) { /* We'll pull from SSE as a 32-bit int, then write * its bottom two bytes, then its third byte. */ png_uint_32 v012; png_uint_16* p01; png_byte* p2; store4(&v012, v); p01 = (png_uint_16p)p; p2 = (png_byte*)(p01+1); *p01 = (png_uint_16)v012; *p2 = (png_byte)(v012 >> 16); } void png_read_filter_row_sub3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Sub filter predicts each pixel as the previous pixel, a. * There is no pixel to the left of the first pixel. It's encoded directly. * That works with our main loop if we just say that left pixel was zero. */ png_size_t rb; __m128i a, d = _mm_setzero_si128(); png_debug(1, "in png_read_filter_row_sub3_sse2"); rb = row_info->rowbytes; while (rb >= 4) { a = d; d = load4(row); d = _mm_add_epi8(d, a); store3(row, d); row += 3; rb -= 3; } if (rb > 0) { a = d; d = load3(row); d = _mm_add_epi8(d, a); store3(row, d); row += 3; rb -= 3; } PNG_UNUSED(prev) } void png_read_filter_row_sub4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Sub filter predicts each pixel as the previous pixel, a. * There is no pixel to the left of the first pixel. It's encoded directly. * That works with our main loop if we just say that left pixel was zero. */ png_size_t rb; __m128i a, d = _mm_setzero_si128(); png_debug(1, "in png_read_filter_row_sub4_sse2"); rb = row_info->rowbytes+4; while (rb > 4) { a = d; d = load4(row); d = _mm_add_epi8(d, a); store4(row, d); row += 4; rb -= 4; } PNG_UNUSED(prev) } void png_read_filter_row_avg3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Avg filter predicts each pixel as the (truncated) average of a and b. * There's no pixel to the left of the first pixel. Luckily, it's * predicted to be half of the pixel above it. So again, this works * perfectly with our loop if we make sure a starts at zero. */ png_size_t rb; const __m128i zero = _mm_setzero_si128(); __m128i b; __m128i a, d = zero; png_debug(1, "in png_read_filter_row_avg3_sse2"); rb = row_info->rowbytes; while (rb >= 4) { __m128i avg; b = load4(prev); a = d; d = load4(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store3(row, d); prev += 3; row += 3; rb -= 3; } if (rb > 0) { __m128i avg; b = load3(prev); a = d; d = load3(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store3(row, d); prev += 3; row += 3; rb -= 3; } } void png_read_filter_row_avg4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* The Avg filter predicts each pixel as the (truncated) average of a and b. * There's no pixel to the left of the first pixel. Luckily, it's * predicted to be half of the pixel above it. So again, this works * perfectly with our loop if we make sure a starts at zero. */ png_size_t rb; const __m128i zero = _mm_setzero_si128(); __m128i b; __m128i a, d = zero; png_debug(1, "in png_read_filter_row_avg4_sse2"); rb = row_info->rowbytes+4; while (rb > 4) { __m128i avg; b = load4(prev); a = d; d = load4(row ); /* PNG requires a truncating average, so we can't just use _mm_avg_epu8 */ avg = _mm_avg_epu8(a,b); /* ...but we can fix it up by subtracting off 1 if it rounded up. */ avg = _mm_sub_epi8(avg, _mm_and_si128(_mm_xor_si128(a,b), _mm_set1_epi8(1))); d = _mm_add_epi8(d, avg); store4(row, d); prev += 4; row += 4; rb -= 4; } } /* Returns |x| for 16-bit lanes. */ static __m128i abs_i16(__m128i x) { #if PNG_INTEL_SSE_IMPLEMENTATION >= 2 return _mm_abs_epi16(x); #else /* Read this all as, return x<0 ? -x : x. * To negate two's complement, you flip all the bits then add 1. */ __m128i is_negative = _mm_cmplt_epi16(x, _mm_setzero_si128()); /* Flip negative lanes. */ x = _mm_xor_si128(x, is_negative); /* +1 to negative lanes, else +0. */ x = _mm_sub_epi16(x, is_negative); return x; #endif } /* Bytewise c ? t : e. */ static __m128i if_then_else(__m128i c, __m128i t, __m128i e) { #if PNG_INTEL_SSE_IMPLEMENTATION >= 3 return _mm_blendv_epi8(e,t,c); #else return _mm_or_si128(_mm_and_si128(c, t), _mm_andnot_si128(c, e)); #endif } void png_read_filter_row_paeth3_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* Paeth tries to predict pixel d using the pixel to the left of it, a, * and two pixels from the previous row, b and c: * prev: c b * row: a d * The Paeth function predicts d to be whichever of a, b, or c is nearest to * p=a+b-c. * * The first pixel has no left context, and so uses an Up filter, p = b. * This works naturally with our main loop's p = a+b-c if we force a and c * to zero. * Here we zero b and d, which become c and a respectively at the start of * the loop. */ png_size_t rb; const __m128i zero = _mm_setzero_si128(); __m128i c, b = zero, a, d = zero; png_debug(1, "in png_read_filter_row_paeth3_sse2"); rb = row_info->rowbytes; while (rb >= 4) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ __m128i pa,pb,pc,smallest,nearest; c = b; b = _mm_unpacklo_epi8(load4(prev), zero); a = d; d = _mm_unpacklo_epi8(load4(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store3(row, _mm_packus_epi16(d,d)); prev += 3; row += 3; rb -= 3; } if (rb > 0) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ __m128i pa,pb,pc,smallest,nearest; c = b; b = _mm_unpacklo_epi8(load3(prev), zero); a = d; d = _mm_unpacklo_epi8(load3(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store3(row, _mm_packus_epi16(d,d)); prev += 3; row += 3; rb -= 3; } } void png_read_filter_row_paeth4_sse2(png_row_infop row_info, png_bytep row, png_const_bytep prev) { /* Paeth tries to predict pixel d using the pixel to the left of it, a, * and two pixels from the previous row, b and c: * prev: c b * row: a d * The Paeth function predicts d to be whichever of a, b, or c is nearest to * p=a+b-c. * * The first pixel has no left context, and so uses an Up filter, p = b. * This works naturally with our main loop's p = a+b-c if we force a and c * to zero. * Here we zero b and d, which become c and a respectively at the start of * the loop. */ png_size_t rb; const __m128i zero = _mm_setzero_si128(); __m128i pa,pb,pc,smallest,nearest; __m128i c, b = zero, a, d = zero; png_debug(1, "in png_read_filter_row_paeth4_sse2"); rb = row_info->rowbytes+4; while (rb > 4) { /* It's easiest to do this math (particularly, deal with pc) with 16-bit * intermediates. */ c = b; b = _mm_unpacklo_epi8(load4(prev), zero); a = d; d = _mm_unpacklo_epi8(load4(row ), zero); /* (p-a) == (a+b-c - a) == (b-c) */ pa = _mm_sub_epi16(b,c); /* (p-b) == (a+b-c - b) == (a-c) */ pb = _mm_sub_epi16(a,c); /* (p-c) == (a+b-c - c) == (a+b-c-c) == (b-c)+(a-c) */ pc = _mm_add_epi16(pa,pb); pa = abs_i16(pa); /* |p-a| */ pb = abs_i16(pb); /* |p-b| */ pc = abs_i16(pc); /* |p-c| */ smallest = _mm_min_epi16(pc, _mm_min_epi16(pa, pb)); /* Paeth breaks ties favoring a over b over c. */ nearest = if_then_else(_mm_cmpeq_epi16(smallest, pa), a, if_then_else(_mm_cmpeq_epi16(smallest, pb), b, c)); /* Note `_epi8`: we need addition to wrap modulo 255. */ d = _mm_add_epi8(d, nearest); store4(row, _mm_packus_epi16(d,d)); prev += 4; row += 4; rb -= 4; } } #endif /* PNG_INTEL_SSE_IMPLEMENTATION > 0 */ #endif /* READ */
# coding: utf-8 # # Behavioral Cloning # # ### Project 3 of Udacity's Self-Driving Car Engineer Nanodegree program # # This is the third project of the nanodegree in which you have to train a self-driving car to adapt to a human's driving style using a convolutional neural network which has to predict the steering angle using prerecorded training data of a human driver. # # ![](media/BehavioralCloning.png) # In[2]: from IPython.display import YouTubeVideo YouTubeVideo('Dx1JrIlXiDM') # ### Library import # In[3]: import csv import cv2 import numpy as np import matplotlib.pyplot as plt import pandas as pd get_ipython().run_line_magic('matplotlib', 'inline') import tensorflow as tf from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D from keras.optimizers import Adam # ## Training data configuration # In[4]: # learning_sets = ["Session_4_Track_1_Insane"] #learning_sets = ["Session_4_Track_1_Insane", "Session_1_Track_1", "Session_2_Track_1_Reverse", "Session_6_Bridge", # "Session_7_Bridge", "Session_8_Bridge", "Session_9_Track_1_Curves"] # Works, but curvey: # learning_sets = ["Session_4_Track_1_Insane", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge", "Session_9_Track_1_Curves"] # Works not, too perfect driving style: # learning_sets = ["Session_4_Track_1_Insane", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge"] # Works not, too perfect driving style: # learning_sets = ["Session_4_Track_1_Insane", "Session_1_Track_1", "Session_2_Track_1_Reverse", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge"] # Works not, too insensitive: # learning_sets = ["Session_1_Track_1", "Session_2_Track_1_Reverse", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge"] # Track 1 final - Perfect mix of driving styles: # learning_sets = ["Session_1_Track_1", "Session_2_Track_1_Reverse", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge", "Session_9_Track_1_Curves"] # Track 2: learning_sets = ["Session_5_Track_2_Great", "Session_3_Track_2", "Session_10_Track_2_Perfect"] #learning_sets = ["Session_1_Track_1", "Session_2_Track_1_Reverse", "Session_6_Bridge", "Session_7_Bridge", "Session_8_Bridge"] base_data_path = "training_data/" # ## Splitting the CSV data into file names and measurements # # Here we first of all read the CSV and prepare the relative paths to all images of all training sessions. # In[5]: image_filenames = [] # array of tuple of images for center/left/right measurements = [] # array of measurements for learning_set_path in learning_sets: print("Loading {}...".format(learning_set_path)) pdcsv = pd.read_csv(base_data_path+learning_set_path+"/driving_log.csv") print(pdcsv.shape) for index, line in pdcsv.iterrows(): source_path = line[0] filename_0 = source_path.split('/')[-1] source_path = line[1] filename_1 = source_path.split('/')[-1] source_path = line[2] filename_2 = source_path.split('/')[-1] base_path = base_data_path+learning_set_path+"/IMG/" image_filenames.append((base_path+filename_0, base_path+filename_1, base_path+filename_2)) measurement = float(line[3]) measurements.append(measurement) print("{} images and {} measurements prepared".format(len(image_filenames), len(measurements))) center_example = len(image_filenames)//2 # In[6]: def get_full_training_image_path(index, direction): """Returns the full path to an image at given index and using a specific direction index: The image index direction: The camera index. 0 = straight view camera, 1 = left side, 2 = right side """ return image_filenames[index][direction] # In[7]: print(get_full_training_image_path(center_example,0)) # ## Presenting example images # # Below you can see an image of all 3 cameras, the straight camera, the left camera and the right camera. # In[8]: columns = 3 rows = 1 total_samples = columns*rows fig = plt.figure(figsize=(columns*10,rows*10)) for i in range(total_samples): ax = fig.add_subplot(rows, columns, i + 1, xticks=[], yticks=[]) filename = get_full_training_image_path(center_example,i) cur_org = cv2.imread(filename) b,g,r = cv2.split(cur_org) # get b,g,r cur_org = cv2.merge([r,g,b]) # switch it to rgb ax.imshow(cur_org) # ## Image loading and augmentation # # Here we load all images to memory. To increase the amount of training data and be better prepared for steering corrections we use the images of all 3 "mounted" cameras with a slight adjustment of the desired angle to be predicted. # In[9]: augmented_images = [] augmented_measurements = [] for index, ifn in enumerate(image_filenames): for side in range(1): image = cv2.imread(get_full_training_image_path(index,side)) b,g,r = cv2.split(image) # get b,g,r image = cv2.merge([r,g,b]) # switch it to rgb measurement = measurements[index] if side==1: measurement += 0.1 if side==2: measurement -= 0.1 augmented_images.append(image) augmented_measurements.append(measurement) augmented_images.append(cv2.flip(image,1)) augmented_measurements.append(-measurement) print(len(augmented_images)) print(augmented_images[0].shape) # In[10]: columns = 3 rows = 1 total_samples = columns*rows fig = plt.figure(figsize=(columns*10,rows*10)) for i in range(total_samples): ax = fig.add_subplot(rows, columns, i + 1, xticks=[], yticks=[]) filename = get_full_training_image_path(center_example,i) cur_org = augmented_images[100] ax.imshow(cur_org) # ## Image cropping test # # To let the network focus on the really important parts of the image we crop away the upper and lower part of the image as the clouds likely won't help us to better predict the perfect steering angle. # In[11]: columns = 3 rows = 1 total_samples = columns*rows crop_percent_top = 0.2 crop_percent_bottom = 0.2 fig = plt.figure(figsize=(columns*10,rows*10)) for i in range(total_samples): ax = fig.add_subplot(rows, columns, i + 1, xticks=[], yticks=[]) filename = get_full_training_image_path(center_example,i) cur_org = augmented_images[100] width = cur_org.shape[1] height = cur_org.shape[0] top_off = int(crop_percent_top*height) rem_height = int(height-(crop_percent_bottom+crop_percent_top)*height) cur_org = cur_org[top_off:top_off+rem_height, :, :] ax.imshow(cur_org) print(augmented_images[0].shape) # ## Training and exporting the model # # When everything is prepared we feed all of this data into a convolutional neural network with 5 convolutional and 4 fully connected layers. # # Instead of using the neural network to try to categorize and image or detect something within it we use it to predict the steering angle. So for example if it detects lane lines pretty close the the left side of the vehicle it shall steer to the right and if it detects ones close to the right side it shall steer to the left. If it's perfectly in the center of the road it shall not steer at all. # In[12]: # Convert the training data to numpy tensors X_train = np.array(augmented_images) y_train = np.array(augmented_measurements) # Setup a sequential, convolutional network which predicts the optimum steering angle in different situations model = Sequential() # The original input image is cropped and normalized. Storing this in the model makes it possible to automatically # crop the image from the simulator as well model.add(Lambda(lambda x: x/127.5 - 1.0, input_shape=(160, 320, 3))) model.add(Cropping2D(cropping=((60,12),(0,0)))) # 5 convolutional layers, nVidia style, first three layers use a 5x5, the other two ones a 3x3 kernel model.add(Conv2D(24,(5,5),strides=(2,2),activation="relu")) model.add(Conv2D(36,(5,5),strides=(2,2),activation="relu")) model.add(Conv2D(48,(5,5),strides=(2,2),activation="relu")) model.add(Conv2D(64,(3,3),activation="relu")) model.add(Conv2D(64,(3,3),activation="relu")) # Flatten the data and add another 3 fully connected layers model.add(Flatten()) # To prevent overfitting enable dropout of 25% model.add(Dropout(0.25)) model.add(Dense(100)) # To prevent overfitting enable dropout of 25% model.add(Dropout(0.25)) model.add(Dense(50)) model.add(Dense(10)) model.add(Dense(1)) model.compile(loss='mse', optimizer=Adam()) model.fit(X_train, y_train, validation_split=0.2, shuffle=True, epochs=8) model.save('model.h5') # In[22]: from IPython.display import SVG from keras.utils.vis_utils import model_to_dot def plot_keras_model(model, show_shapes=True, show_layer_names=True): return SVG(model_to_dot(model, show_shapes=show_shapes, show_layer_names=show_layer_names).create(prog='dot',format='svg')) file = open('model.svg', 'w') file.write(svg_data.data) file.close() svg_data = plot_keras_model(model, show_shapes=True, show_layer_names=False) plot_keras_model(model, show_shapes=True, show_layer_names=False)
''' This module contains the execution context objects that are internal to the system. Not every property on these should be exposed to random Jane or Joe dagster user so we have a different layer of objects that encode the explicit public API in the user_context module ''' from collections import namedtuple from dagster import check from dagster.core.definitions.executable import ExecutablePipeline from dagster.core.definitions.mode import ModeDefinition from dagster.core.definitions.resource import ScopedResourcesBuilder from dagster.core.definitions.step_launcher import StepLauncher from dagster.core.errors import DagsterInvariantViolationError from dagster.core.log_manager import DagsterLogManager from dagster.core.storage.file_manager import FileManager from dagster.core.storage.pipeline_run import PipelineRun from dagster.core.system_config.objects import EnvironmentConfig class SystemPipelineExecutionContextData( namedtuple( '_SystemPipelineExecutionContextData', ( 'pipeline_run scoped_resources_builder environment_config pipeline ' 'mode_def system_storage_def instance intermediates_manager file_manager ' 'executor_config raise_on_error' ), ) ): ''' SystemPipelineExecutionContextData is the data that remains constant throughout the entire execution of a pipeline. ''' def __new__( cls, pipeline_run, scoped_resources_builder, environment_config, pipeline, mode_def, system_storage_def, instance, intermediates_manager, file_manager, executor_config, raise_on_error, ): from dagster.core.definitions.system_storage import SystemStorageDefinition from dagster.core.execution.config import ExecutorConfig from dagster.core.storage.intermediates_manager import IntermediatesManager from dagster.core.instance import DagsterInstance return super(SystemPipelineExecutionContextData, cls).__new__( cls, pipeline_run=check.inst_param(pipeline_run, 'pipeline_run', PipelineRun), scoped_resources_builder=check.inst_param( scoped_resources_builder, 'scoped_resources_builder', ScopedResourcesBuilder ), environment_config=check.inst_param( environment_config, 'environment_config', EnvironmentConfig ), pipeline=check.inst_param(pipeline, 'pipeline', ExecutablePipeline), mode_def=check.inst_param(mode_def, 'mode_def', ModeDefinition), system_storage_def=check.inst_param( system_storage_def, 'system_storage_def', SystemStorageDefinition ), instance=check.inst_param(instance, 'instance', DagsterInstance), intermediates_manager=check.inst_param( intermediates_manager, 'intermediates_manager', IntermediatesManager ), file_manager=check.inst_param(file_manager, 'file_manager', FileManager), executor_config=check.inst_param(executor_config, 'executor_config', ExecutorConfig), raise_on_error=check.bool_param(raise_on_error, 'raise_on_error'), ) @property def run_id(self): return self.pipeline_run.run_id @property def environment_dict(self): return self.environment_config.original_config_dict @property def pipeline_def(self): return self.pipeline.get_definition() class SystemPipelineExecutionContext(object): __slots__ = ['_pipeline_context_data', '_log_manager'] def __init__(self, pipeline_context_data, log_manager): self._pipeline_context_data = check.inst_param( pipeline_context_data, 'pipeline_context_data', SystemPipelineExecutionContextData ) self._log_manager = check.inst_param(log_manager, 'log_manager', DagsterLogManager) def for_step(self, step): from dagster.core.execution.plan.objects import ExecutionStep check.inst_param(step, 'step', ExecutionStep) return SystemStepExecutionContext( self._pipeline_context_data, self._log_manager.with_tags(**step.logging_tags), step, ) def for_type(self, dagster_type): return TypeCheckContext(self._pipeline_context_data, self.log, dagster_type) @property def executor_config(self): return self._pipeline_context_data.executor_config @property def pipeline_run(self): return self._pipeline_context_data.pipeline_run @property def scoped_resources_builder(self): return self._pipeline_context_data.scoped_resources_builder @property def run_id(self): return self._pipeline_context_data.run_id @property def environment_dict(self): return self._pipeline_context_data.environment_dict @property def environment_config(self): return self._pipeline_context_data.environment_config @property def logging_tags(self): return self._log_manager.logging_tags def has_tag(self, key): check.str_param(key, 'key') return key in self.logging_tags def get_tag(self, key): check.str_param(key, 'key') return self.logging_tags.get(key) @property def pipeline(self): return self._pipeline_context_data.pipeline @property def pipeline_def(self): return self._pipeline_context_data.pipeline_def @property def mode_def(self): return self._pipeline_context_data.mode_def @property def system_storage_def(self): return self._pipeline_context_data.system_storage_def @property def log(self): return self._log_manager @property def instance(self): return self._pipeline_context_data.instance @property def intermediates_manager(self): return self._pipeline_context_data.intermediates_manager @property def file_manager(self): return self._pipeline_context_data.file_manager @property def raise_on_error(self): return self._pipeline_context_data.raise_on_error class SystemStepExecutionContext(SystemPipelineExecutionContext): __slots__ = ['_step', '_resources', '_required_resource_keys', '_step_launcher'] def __init__(self, pipeline_context_data, log_manager, step): from dagster.core.execution.plan.objects import ExecutionStep from dagster.core.execution.resources_init import get_required_resource_keys_for_step self._step = check.inst_param(step, 'step', ExecutionStep) super(SystemStepExecutionContext, self).__init__(pipeline_context_data, log_manager) self._required_resource_keys = get_required_resource_keys_for_step( step, pipeline_context_data.pipeline_def, pipeline_context_data.system_storage_def, ) self._resources = self._pipeline_context_data.scoped_resources_builder.build( self._required_resource_keys ) step_launcher_resources = [ resource for resource in self._resources if isinstance(resource, StepLauncher) ] if len(step_launcher_resources) > 1: raise DagsterInvariantViolationError( 'Multiple required resources for solid {solid_name} have inherit StepLauncher' 'There should be at most one step launcher resource per solid.'.format( solid_name=step.solid_handle.name ) ) elif len(step_launcher_resources) == 1: self._step_launcher = step_launcher_resources[0] else: self._step_launcher = None self._log_manager = log_manager def for_compute(self): return SystemComputeExecutionContext(self._pipeline_context_data, self.log, self.step) @property def step(self): return self._step @property def step_launcher(self): return self._step_launcher @property def solid_handle(self): return self._step.solid_handle @property def solid_def(self): return self.solid.definition @property def solid(self): return self.pipeline_def.get_solid(self._step.solid_handle) @property def resources(self): return self._resources @property def required_resource_keys(self): return self._required_resource_keys @property def log(self): return self._log_manager class SystemComputeExecutionContext(SystemStepExecutionContext): @property def solid_config(self): solid_config = self.environment_config.solids.get(str(self.solid_handle)) return solid_config.config if solid_config else None class TypeCheckContext(SystemPipelineExecutionContext): '''The ``context`` object available to a type check function on a DagsterType. Attributes: log (DagsterLogManager): Centralized log dispatch from user code. resources (Any): An object whose attributes contain the resources available to this solid. run_id (str): The id of this pipeline run. ''' def __init__(self, pipeline_context_data, log_manager, dagster_type): super(TypeCheckContext, self).__init__(pipeline_context_data, log_manager) self._resources = self._pipeline_context_data.scoped_resources_builder.build( dagster_type.required_resource_keys ) self._log_manager = log_manager @property def resources(self): return self._resources
/** @file md.h @brief based on TRS-80 Virtual Disk Kit v1.7 for Windows by Miguel Dutra Linux port VDK-80-Linux done by Mike Gore, 2016 @par Tools to Read and Write files inside common TRS-80 emulator images @par Copyright &copy; 2016 Miguel Dutra, GPL License @par You are free to use this code under the terms of GPL please retain a copy of this notice in any code you use it in. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. @par Original Windows Code @see http://www.trs-80.com/wordpress/category/contributors/miguel-dutra/ @see http://www.trs-80.com/wordpress/dsk-and-dmk-image-utilities/ @see Miguel Dutra www.mdutra.com */ //--------------------------------------------------------------------------------- // Operating System Interface for MicroDOS and OS/80 III //--------------------------------------------------------------------------------- enum MD_FLAVOR { MD_MICRODOS, MD_OS80 }; class CMD: public COSI { protected: MD_FLAVOR m_Flavor; // MicroDOS flavor OSI_FILE m_Dir[2]; // MicroDOS directory-like structure BYTE m_nSides; // Number of disk sides BYTE m_nSectorsPerTrack; // Sectors per track BYTE m_nFile; // Currently selected file WORD m_wSectors; // Total number of disk sectors DWORD m_dwFilePos; // Current file position - Seek() WORD m_wSector; // Current relative sector - Seek() BYTE m_Buffer[1024]; // Generic buffer for operations on sectors public: CMD(); // Initialize member variables virtual ~CMD(); // Release allocated memory virtual DWORD Load(CVDI* pVDI, DWORD dwFlags); // Validate DOS version and define operating parameters virtual DWORD Dir(void** pFile, OSI_DIR nFlag = OSI_DIR_FIND_NEXT); // Return a pointer to the first/next directory entry virtual DWORD Open(void** pFile, const char cName[11]); // Return a pointer to the directory entry matching the file name virtual DWORD Create(void** pFile, OSI_FILE& File); // Create a new file with the indicated properties virtual DWORD Seek(void* pFile, DWORD dwPos); // Move the file pointer virtual DWORD Read(void* pFile, BYTE* pBuffer, DWORD& dwBytes); // Read data from file virtual DWORD Write(void* pFile, BYTE* pBuffer, DWORD& dwBytes); // Save data to file virtual DWORD Delete(void* pFile); // Delete the file virtual void GetDOS(OSI_DOS& DOS); // Get DOS information virtual DWORD SetDOS(OSI_DOS& DOS); // Set DOS information virtual void GetFile(void* pFile, OSI_FILE& File); // Get the file properties virtual DWORD SetFile(void* pFile, OSI_FILE& File); // Set the file properties (public) protected: virtual void CHS(WORD wSector, BYTE& pTrack, BYTE& pSide, BYTE& pSector); // Return the Cylinder/Head/Sector (CHS) of a given relative sector };
# Code listing #5 def fetch_url(url, ntries=3, timeout=30): """ Fetch a given url and return its contents. @params url - The URL to be fetched. ntries - The maximum number of retries. timeout - Timout per call in seconds. @returns On success - Contents of URL. On failure - (error_code, last_error) """ # This loop performs a network fetch of the URL, retrying upto # 'ntries' times in case of errors. In case the URL cant be # fetched, an error is returned. # Initialize all state count, result, error = 0, None, None while count < ntries: try: result = requests.get(url, timeout=timeout) except Exception as error: print('Caught exception', error, 'trying again after a while') # increment count count += 1 # sleep 1 second every time time.sleep(1) if result == None: print("Error, could not fetch URL",url) # Return a tuple of (<return code>, <lasterror>) return (2, error) # Return data of the URL return result.content
from tf_keras_1.finetune.imports import * from system.imports import * from tf_keras_1.finetune.level_14_master_main import prototype_master class prototype(prototype_master): ''' Main class for Mxnet Backend Args: verbose (int): Set verbosity levels 0 - Print Nothing 1 - Print desired details ''' @accepts("self", verbose=int, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def __init__(self, verbose=1): super().__init__(verbose=verbose); self.system_dict["library"] = "Keras"; self.custom_print("Keras Version: {}".format(keras.__version__)); self.custom_print("Tensorflow Version: {}".format(tf.__version__)); self.custom_print(""); ############################################################################################################################################### @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], eval_infer=None, resume_train=None, copy_from=None, pseudo_copy_from=None, summary=None, post_trace=True) @accepts("self", str, str, eval_infer=bool, resume_train=bool, copy_from=[list, bool], pseudo_copy_from=[list, bool], summary=bool, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Prototype(self, project_name, experiment_name, eval_infer=False, resume_train=False, copy_from=False, pseudo_copy_from=False, summary=False): ''' Create project and experiment for instantiation and running the experiments Args: project_name (str): Project Name experiment_name (str): Experiment Name eval_infer (bool): If set as True, model is loaded in evaluation mode resume_train (bool): If set as True, model is loaded from last checkpoint copy_from (list): [project, experiment] to copy from pseudo_copy_from (list): For creating sub-experiments while in hyper-parametric analysis state summary (list): Dummy variable Returns: None ''' self.set_system_project(project_name); self.set_system_experiment(experiment_name, eval_infer=eval_infer, resume_train=resume_train, copy_from=copy_from, pseudo_copy_from=pseudo_copy_from, summary=summary); self.custom_print("Experiment Details"); self.custom_print(" Project: {}".format(self.system_dict["project_name"])); self.custom_print(" Experiment: {}".format(self.system_dict["experiment_name"])); self.custom_print(" Dir: {}".format(self.system_dict["experiment_dir"])); self.custom_print(""); ################################################################################################################################################ ############################################################################################################################################### @warning_checks(None, dataset_path=None, path_to_csv=None, delimiter=None, model_name=None, freeze_base_network=None, num_epochs=["lt", 100], post_trace=True) @error_checks(None, dataset_path=["folder", "r"], path_to_csv=["file", "r"], delimiter=["in", [",", ";", "-", " "]], model_name=None, freeze_base_network=None, num_epochs=["gte", 1], post_trace=True) @accepts("self", dataset_path=[str, list, bool], path_to_csv=[str, list, bool], delimiter=str, model_name=str, freeze_base_network=bool, num_epochs=int, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Default(self, dataset_path=False, path_to_csv=False, delimiter=",", model_name="resnet18_v1", freeze_base_network=True, num_epochs=10): ''' Use monk in default (quick prototyping) mode Args: dataset_path (str, list): Path to Dataset folder 1) Single string if validation data does not exist 2) List [train_path, val_path] in case of separate train and val data path_to_csv (str, list): Path to csv file pointing towards images 1) Single string if validation data does not exist 2) List [train_path, val_path] in case of separate train and val data delimiter (str): Delimiter for csv file model_name (str): Base model name freeze_base_network (bool): If True base network is freezed num_epochs (int): Number of epochs to train the data Returns: None ''' if(self.system_dict["states"]["eval_infer"]): self.Dataset_Params(dataset_path=dataset_path, import_as_csv=import_as_csv, path_to_csv=path_to_csv, delimiter=delimiter); self.Dataset(); else: input_size=224; self.Dataset_Params(dataset_path=dataset_path, path_to_csv=path_to_csv, delimiter=delimiter, split=0.7, input_size=input_size, batch_size=4, shuffle_data=True, num_processors=psutil.cpu_count()); self.apply_random_horizontal_flip(probability=0.8, train=True, val=True); self.apply_mean_subtraction(mean=[0.485, 0.456, 0.406], train=True, val=True, test=True); self.Dataset(); self.Model_Params(model_name=model_name, freeze_base_network=freeze_base_network, use_gpu=True, gpu_memory_fraction=0.6, use_pretrained=True); self.Model(); model_name = self.system_dict["model"]["params"]["model_name"]; if("resnet" in model_name or "vgg" in model_name or "dense" in model_name or "xception" in model_name): self.optimizer_sgd(0.0001, momentum=0.9); self.lr_plateau_decrease(factor=0.1, patience=max(min(10, num_epochs//3), 1), verbose=True); self.loss_crossentropy(); elif("nas" in model_name): self.optimizer_rmsprop(0.0001, weight_decay=0.00004, momentum=0.9); self.lr_step_decrease(2, gamma=0.97); self.loss_crossentropy(); elif("mobile" in model_name): self.optimizer_sgd(0.0001, weight_decay=0.00004, momentum=0.9); self.lr_step_decrease(1, gamma=0.97); self.loss_crossentropy(); elif("inception" in model_name): self.optimizer_sgd(0.0001, weight_decay=0.0001, momentum=0.9); self.lr_step_decrease(1, gamma=0.9); self.loss_crossentropy(); self.Training_Params(num_epochs=num_epochs, display_progress=True, display_progress_realtime=True, save_intermediate_models=True, intermediate_model_prefix="intermediate_model_", save_training_logs=True); self.system_dict["hyper-parameters"]["status"] = True; save(self.system_dict); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Summary(self): ''' Print summary of entire project Args: None Returns: None ''' print_summary(self.system_dict["fname_relative"]); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Models(self): ''' List all base models supported. Args: None Returns: None ''' self.print_list_models(); ############################################################################################################################################### ## Will be depricated in v2.0 ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Layers(self): ''' List all layers available for appending the base model. Args: None Returns: None ''' self.print_list_layers_transfer_learning(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Layers_Transfer_Learning(self): ''' List all layers available for appending the base model. Args: None Returns: None ''' self.print_list_layers_transfer_learning(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Layers_Custom_Model(self): ''' List all layers available for building a custom model. Args: None Returns: None ''' self.print_list_layers_custom_model(); ############################################################################################################################################### ## Will be depricated in v2.0 ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Activations(self): ''' List all activations available for appending the base model. Args: None Returns: None ''' self.print_list_activations_transfer_learning(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Activations_Transfer_Learning(self): ''' List all activations available for appending the base model. Args: None Returns: None ''' self.print_list_activations_transfer_learning(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Activations_Custom_Model(self): ''' List all activations available for building a custom model. Args: None Returns: None ''' self.print_list_activations_custom_model(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Losses(self): ''' List all loss functions available. Args: None Returns: None ''' self.print_list_losses(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Optimizers(self): ''' List all optimizers functions available. Args: None Returns: None ''' self.print_list_optimizers(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Schedulers(self): ''' List all learning rate scheduler functions available. Args: None Returns: None ''' self.print_list_schedulers(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Transforms(self): ''' List all data transformation functions available. Args: None Returns: None ''' self.print_list_transforms(); ############################################################################################################################################### ############################################################################################################################################### @accepts("self", post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def List_Blocks(self): ''' List all blocks available for building a custom model. Args: None Returns: None ''' self.print_list_blocks(); ############################################################################################################################################### ############################################################################################################################################### @warning_checks(None, None, None, ["lt", 50], num_epochs=["lte", 10], state=None, post_trace=True) @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], None, ["gt", 0, "lte", 100], num_epochs=["gt", 0], state=["in", ["keep_all", "keep_none"]], post_trace=True) @accepts("self", str, list, [int, float], num_epochs=int, state=str, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Analyse_Learning_Rates(self, analysis_name, lr_list, percent_data, num_epochs=2, state="keep_all"): ''' Hyperparameter Tuner - Analyse learning rate Takes in a list of learning rates and trains on a part of dataset Provides summaries and graphs on every sub-experiment created Args: analysis_name (str): A suitable name for analysis lr_list (list): List of learning rates. percent_data (int): Percentage of complete dataset to run experiments on. num_epochs (int): Number of epochs for each sub-experiment state ("str"): If set as "keep_all", keeps every file in the sub-experiment If set as "keep_none", keeps only comparison files for each experiment Returns: dict: Tabular data on training_accuracy, validation_accuracy, training_loss, validation_loss and training_time for each experiment. ''' from keras_prototype import prototype project = analysis_name; self.custom_print(""); self.custom_print("Running Learning rate analysis"); #Change 1 self.custom_print("Analysis Name : {}".format(project)); self.custom_print(""); for i in range(len(lr_list)): #Change 2 ktf_ = prototype(verbose=0); self.custom_print("Running experiment : {}/{}".format(i+1, len(lr_list))); #Change 3 experiment = "Learning_Rate_" + str(lr_list[i]); #Change 4 self.custom_print("Experiment name : {}".format(experiment)) ktf_.Prototype(project, experiment, pseudo_copy_from=[self.system_dict["project_name"], self.system_dict["experiment_name"]]); ktf_.Dataset_Percent(percent_data); dataset_type = ktf_.system_dict["dataset"]["dataset_type"]; dataset_train_path = ktf_.system_dict["dataset"]["train_path"]; dataset_val_path = ktf_.system_dict["dataset"]["val_path"]; csv_train = ktf_.system_dict["dataset"]["csv_train"]; csv_val = ktf_.system_dict["dataset"]["csv_val"]; if(dataset_type=="train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); elif(dataset_type=="csv_train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="csv_train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); ktf_.update_learning_rate(lr_list[i]) #Change 5 ktf_.Reload(); #Change 6 ktf_.update_num_epochs(num_epochs); ktf_.update_display_progress_realtime(False) ktf_.update_save_intermediate_models(False); ktf_.system_dict = set_transform_estimate(ktf_.system_dict); ktf_.set_dataset_dataloader(estimate=True); total_time_per_epoch = ktf_.get_training_estimate(); total_time = total_time_per_epoch*num_epochs; if(int(total_time//60) == 0): self.custom_print("Estimated time : {} sec".format(total_time)); else: self.custom_print("Estimated time : {} min".format(int(total_time//60)+1)); ktf_.Train(); self.custom_print("Experiment Complete"); self.custom_print("\n"); self.custom_print("Comparing Experiments"); from compare_prototype import compare ctf_ = compare(verbose=0); ctf_.Comparison("Comparison_" + analysis_name); self.custom_print("Comparison ID: {}".format("Comparison_" + analysis_name)); training_accuracies = []; validation_accuracies = []; training_losses = []; validation_losses = []; tabular_data = []; for i in range(len(lr_list)): #Change 7 project = analysis_name; experiment = "Learning_Rate_" + str(lr_list[i]); #Change 8 ctf_.Add_Experiment(project, experiment) tmp = []; tmp.append(experiment); training_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_acc_history.npy"; tmp.append(np.load(training_accuracy_file, allow_pickle=True)[-1]); validation_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_acc_history.npy"; tmp.append(np.load(validation_accuracy_file, allow_pickle=True)[-1]); training_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_loss_history.npy"; tmp.append(np.load(training_loss_file, allow_pickle=True)[-1]); validation_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_loss_history.npy"; tmp.append(np.load(validation_loss_file, allow_pickle=True)[-1]); tabular_data.append(tmp) ctf_.Generate_Statistics(); self.custom_print("Generated statistics post all epochs"); self.custom_print(tabulate(tabular_data, headers=['Experiment Name', 'Train Acc', 'Val Acc', 'Train Loss', 'Val Loss'], tablefmt='orgtbl')); self.custom_print(""); return_dict = {}; for i in range(len(tabular_data)): return_dict[tabular_data[i][0]] = {}; return_dict[tabular_data[i][0]]["training_accuracy"] = tabular_data[i][1]; return_dict[tabular_data[i][0]]["validation_accuracy"] = tabular_data[i][2]; return_dict[tabular_data[i][0]]["training_loss"] = tabular_data[i][3]; return_dict[tabular_data[i][0]]["validation_loss"] = tabular_data[i][4]; fname = self.system_dict["master_systems_dir_relative"] + analysis_name + "/" + tabular_data[i][0] + "/experiment_state.json"; system_dict = read_json(fname); return_dict[tabular_data[i][0]]["training_time"] = system_dict["training"]["outputs"]["training_time"]; if(state=="keep_none"): shutil.rmtree(self.system_dict["master_systems_dir_relative"] + analysis_name); return return_dict ############################################################################################################################################### ############################################################################################################################################### @warning_checks(None, None, None, ["lt", 50], num_epochs=["lte", 10], state=None, post_trace=True) @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], None, ["gt", 0, "lte", 100], num_epochs=["gt", 0], state=["in", ["keep_all", "keep_none"]], post_trace=True) @accepts("self", str, list, [int, float], num_epochs=int, state=str, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Analyse_Input_Sizes(self, analysis_name, inp_size_list, percent_data, num_epochs=2, state="keep_all"): ''' Hyperparameter Tuner - Analyse input sizes Takes in a list of input sizes and trains on a part of dataset Provides summaries and graphs on every sub-experiment created Args: analysis_name (str): A suitable name for analysis inp_size_list (list): List of input_sizes. percent_data (int): Percentage of complete dataset to run experiments on. num_epochs (int): Number of epochs for each sub-experiment state ("str"): If set as "keep_all", keeps every file in the sub-experiment If set as "keep_none", keeps only comparison files for each experiment Returns: dict: Tabular data on training_accuracy, validation_accuracy, training_loss, validation_loss and training_time for each experiment. ''' from keras_prototype import prototype project = analysis_name; self.custom_print(""); self.custom_print("Running Input Size analysis"); #Change 1 self.custom_print("Analysis Name : {}".format(project)); self.custom_print(""); for i in range(len(inp_size_list)): #Change 2 ktf_ = prototype(verbose=0); self.custom_print("Running experiment : {}/{}".format(i+1, len(inp_size_list))); #Change 3 experiment = "Input_Size_" + str(inp_size_list[i]); #Change 4 self.custom_print("Experiment name : {}".format(experiment)) ktf_.Prototype(project, experiment, pseudo_copy_from=[self.system_dict["project_name"], self.system_dict["experiment_name"]]); ktf_.Dataset_Percent(percent_data); dataset_type = ktf_.system_dict["dataset"]["dataset_type"]; dataset_train_path = ktf_.system_dict["dataset"]["train_path"]; dataset_val_path = ktf_.system_dict["dataset"]["val_path"]; csv_train = ktf_.system_dict["dataset"]["csv_train"]; csv_val = ktf_.system_dict["dataset"]["csv_val"]; if(dataset_type=="train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); elif(dataset_type=="csv_train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="csv_train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); ktf_.update_input_size(inp_size_list[i]) #Change 5 ktf_.Reload(); #Change 6 ktf_.update_num_epochs(num_epochs); ktf_.update_display_progress_realtime(False) ktf_.update_save_intermediate_models(False); ktf_.system_dict = set_transform_estimate(ktf_.system_dict); ktf_.set_dataset_dataloader(estimate=True); total_time_per_epoch = ktf_.get_training_estimate(); total_time = total_time_per_epoch*num_epochs; if(int(total_time//60) == 0): self.custom_print("Estimated time : {} sec".format(total_time)); else: self.custom_print("Estimated time : {} min".format(int(total_time//60)+1)); ktf_.Train(); self.custom_print("Experiment Complete"); self.custom_print("\n"); self.custom_print("Comparing Experiments"); from compare_prototype import compare ctf_ = compare(verbose=0); ctf_.Comparison("Comparison_" + analysis_name); self.custom_print("Comparison ID: {}".format("Comparison_" + analysis_name)); training_accuracies = []; validation_accuracies = []; training_losses = []; validation_losses = []; tabular_data = []; for i in range(len(inp_size_list)): #Change 7 project = analysis_name; experiment = "Input_Size_" + str(inp_size_list[i]); #Change 8 ctf_.Add_Experiment(project, experiment) tmp = []; tmp.append(experiment); training_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_acc_history.npy"; tmp.append(np.load(training_accuracy_file, allow_pickle=True)[-1]); validation_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_acc_history.npy"; tmp.append(np.load(validation_accuracy_file, allow_pickle=True)[-1]); training_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_loss_history.npy"; tmp.append(np.load(training_loss_file, allow_pickle=True)[-1]); validation_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_loss_history.npy"; tmp.append(np.load(validation_loss_file, allow_pickle=True)[-1]); tabular_data.append(tmp) ctf_.Generate_Statistics(); self.custom_print("Generated statistics post all epochs"); self.custom_print(tabulate(tabular_data, headers=['Experiment Name', 'Train Acc', 'Val Acc', 'Train Loss', 'Val Loss'], tablefmt='orgtbl')); self.custom_print(""); return_dict = {}; for i in range(len(tabular_data)): return_dict[tabular_data[i][0]] = {}; return_dict[tabular_data[i][0]]["training_accuracy"] = tabular_data[i][1]; return_dict[tabular_data[i][0]]["validation_accuracy"] = tabular_data[i][2]; return_dict[tabular_data[i][0]]["training_loss"] = tabular_data[i][3]; return_dict[tabular_data[i][0]]["validation_loss"] = tabular_data[i][4]; fname = self.system_dict["master_systems_dir_relative"] + analysis_name + "/" + tabular_data[i][0] + "/experiment_state.json"; system_dict = read_json(fname); return_dict[tabular_data[i][0]]["training_time"] = system_dict["training"]["outputs"]["training_time"]; if(state=="keep_none"): shutil.rmtree(self.system_dict["master_systems_dir_relative"] + analysis_name); return return_dict ############################################################################################################################################### ############################################################################################################################################### @warning_checks(None, None, None, ["lt", 50], num_epochs=["lte", 10], state=None, post_trace=True) @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], None, ["gt", 0, "lte", 100], num_epochs=["gt", 0], state=["in", ["keep_all", "keep_none"]], post_trace=True) @accepts("self", str, list, [int, float], num_epochs=int, state=str, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Analyse_Batch_Sizes(self, analysis_name, batch_size_list, percent_data, num_epochs=2, state="keep_all"): ''' Hyperparameter Tuner - Analyse batch sizes Takes in a list of batch sizes and trains on a part of dataset Provides summaries and graphs on every sub-experiment created Args: analysis_name (str): A suitable name for analysis inp_size_list (list): List of batch sizes. percent_data (int): Percentage of complete dataset to run experiments on. num_epochs (int): Number of epochs for each sub-experiment state ("str"): If set as "keep_all", keeps every file in the sub-experiment If set as "keep_none", keeps only comparison files for each experiment Returns: dict: Tabular data on training_accuracy, validation_accuracy, training_loss, validation_loss and training_time for each experiment. ''' from keras_prototype import prototype project = analysis_name; self.custom_print(""); self.custom_print("Running Batch Size analysis"); #Change 1 self.custom_print("Analysis Name : {}".format(project)); self.custom_print(""); for i in range(len(batch_size_list)): #Change 2 ktf_ = prototype(verbose=0); self.custom_print("Running experiment : {}/{}".format(i+1, len(batch_size_list))); #Change 3 experiment = "Batch_Size_" + str(batch_size_list[i]); #Change 4, 5 self.custom_print("Experiment name : {}".format(experiment)) ktf_.Prototype(project, experiment, pseudo_copy_from=[self.system_dict["project_name"], self.system_dict["experiment_name"]]); ktf_.Dataset_Percent(percent_data); dataset_type = ktf_.system_dict["dataset"]["dataset_type"]; dataset_train_path = ktf_.system_dict["dataset"]["train_path"]; dataset_val_path = ktf_.system_dict["dataset"]["val_path"]; csv_train = ktf_.system_dict["dataset"]["csv_train"]; csv_val = ktf_.system_dict["dataset"]["csv_val"]; if(dataset_type=="train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); elif(dataset_type=="csv_train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="csv_train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); ktf_.update_batch_size(batch_size_list[i]) #Change 6 ktf_.Reload(); #Change 7 ktf_.update_num_epochs(num_epochs); ktf_.update_display_progress_realtime(False); ktf_.update_save_intermediate_models(False); ktf_.system_dict = set_transform_estimate(ktf_.system_dict); ktf_.set_dataset_dataloader(estimate=True); total_time_per_epoch = ktf_.get_training_estimate(); total_time = total_time_per_epoch*num_epochs; if(int(total_time//60) == 0): self.custom_print("Estimated time : {} sec".format(total_time)); else: self.custom_print("Estimated time : {} min".format(int(total_time//60)+1)); ktf_.Train(); self.custom_print("Experiment Complete"); self.custom_print("\n"); self.custom_print("Comparing Experiments"); from compare_prototype import compare ctf_ = compare(verbose=0); ctf_.Comparison("Comparison_" + analysis_name); self.custom_print("Comparison ID: {}".format("Comparison_" + analysis_name)); training_accuracies = []; validation_accuracies = []; training_losses = []; validation_losses = []; tabular_data = []; for i in range(len(batch_size_list)): #Change 8 project = analysis_name; experiment = "Batch_Size_" + str(batch_size_list[i]); #Change 9, 10 ctf_.Add_Experiment(project, experiment) tmp = []; tmp.append(experiment); training_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_acc_history.npy"; tmp.append(np.load(training_accuracy_file, allow_pickle=True)[-1]); validation_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_acc_history.npy"; tmp.append(np.load(validation_accuracy_file, allow_pickle=True)[-1]); training_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_loss_history.npy"; tmp.append(np.load(training_loss_file, allow_pickle=True)[-1]); validation_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_loss_history.npy"; tmp.append(np.load(validation_loss_file, allow_pickle=True)[-1]); tabular_data.append(tmp) ctf_.Generate_Statistics(); self.custom_print("Generated statistics post all epochs"); self.custom_print(tabulate(tabular_data, headers=['Experiment Name', 'Train Acc', 'Val Acc', 'Train Loss', 'Val Loss'], tablefmt='orgtbl')); self.custom_print(""); return_dict = {}; for i in range(len(tabular_data)): return_dict[tabular_data[i][0]] = {}; return_dict[tabular_data[i][0]]["training_accuracy"] = tabular_data[i][1]; return_dict[tabular_data[i][0]]["validation_accuracy"] = tabular_data[i][2]; return_dict[tabular_data[i][0]]["training_loss"] = tabular_data[i][3]; return_dict[tabular_data[i][0]]["validation_loss"] = tabular_data[i][4]; fname = self.system_dict["master_systems_dir_relative"] + analysis_name + "/" + tabular_data[i][0] + "/experiment_state.json"; system_dict = read_json(fname); return_dict[tabular_data[i][0]]["training_time"] = system_dict["training"]["outputs"]["training_time"]; if(state=="keep_none"): shutil.rmtree(self.system_dict["master_systems_dir_relative"] + analysis_name); return return_dict ############################################################################################################################################### ############################################################################################################################################### @warning_checks(None, None, None, ["lt", 50], num_epochs=["lte", 10], state=None, post_trace=True) @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], None, ["gt", 0, "lte", 100], num_epochs=["gt", 0], state=["in", ["keep_all", "keep_none"]], post_trace=True) @accepts("self", str, list, [int, float], num_epochs=int, state=str, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Analyse_Models(self, analysis_name, model_list, percent_data, num_epochs=2, state="keep_all"): ''' Hyperparameter Tuner - Analyse base models Takes in a list of base models and trains on a part of dataset Provides summaries and graphs on every sub-experiment created Args: analysis_name (str): A suitable name for analysis inp_size_list (list of list): List of base models. The format is [model_name_string, freeze_base_model_bool, use_pretrained_model_bool] 1) First arg - Model name in string 2) Second arg - Whether to freeze base model or not 3) Thrid arg - Whether to use pretrained model or use randomly initialized weights percent_data (int): Percentage of complete dataset to run experiments on. num_epochs (int): Number of epochs for each sub-experiment state ("str"): If set as "keep_all", keeps every file in the sub-experiment If set as "keep_none", keeps only comparison files for each experiment Returns: dict: Tabular data on training_accuracy, validation_accuracy, training_loss, validation_loss and training_time for each experiment. ''' from keras_prototype import prototype project = analysis_name; self.custom_print(""); self.custom_print("Running Model analysis"); #Change 1 self.custom_print("Analysis Name : {}".format(project)); self.custom_print(""); for i in range(len(model_list)): #Change 2 ktf_ = prototype(verbose=0); self.custom_print("Running experiment : {}/{}".format(i+1, len(model_list))); #Change 3 if(model_list[i][1]): experiment = "Model_" + str(model_list[i][0]) + "_freeze_base"; #Change 4, 5 else: experiment = "Model_" + str(model_list[i][0]) + "_unfreeze_base"; if(model_list[i][2]): experiment += "_pretrained"; else: experiment += "_uninitialized"; self.custom_print("Experiment name : {}".format(experiment)) ktf_.Prototype(project, experiment, pseudo_copy_from=[self.system_dict["project_name"], self.system_dict["experiment_name"]]); ktf_.Dataset_Percent(percent_data); dataset_type = ktf_.system_dict["dataset"]["dataset_type"]; dataset_train_path = ktf_.system_dict["dataset"]["train_path"]; dataset_val_path = ktf_.system_dict["dataset"]["val_path"]; csv_train = ktf_.system_dict["dataset"]["csv_train"]; csv_val = ktf_.system_dict["dataset"]["csv_val"]; if(dataset_type=="train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); elif(dataset_type=="csv_train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="csv_train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); ktf_.update_model_name(model_list[i][0]) #Change 6 ktf_.update_freeze_base_network(model_list[i][1]) ktf_.update_use_pretrained(model_list[i][2]) ktf_.Reload(); #Change 7 ktf_.update_num_epochs(num_epochs); ktf_.update_display_progress_realtime(False) ktf_.update_save_intermediate_models(False); ktf_.system_dict = set_transform_estimate(ktf_.system_dict); ktf_.set_dataset_dataloader(estimate=True); total_time_per_epoch = ktf_.get_training_estimate(); total_time = total_time_per_epoch*num_epochs; if(int(total_time//60) == 0): self.custom_print("Estimated time : {} sec".format(total_time)); else: self.custom_print("Estimated time : {} min".format(int(total_time//60)+1)); ktf_.Train(); self.custom_print("Experiment Complete"); self.custom_print("\n"); self.custom_print("Comparing Experiments"); from compare_prototype import compare ctf_ = compare(verbose=0); ctf_.Comparison("Comparison_" + analysis_name); self.custom_print("Comparison ID: {}".format("Comparison_" + analysis_name)); training_accuracies = []; validation_accuracies = []; training_losses = []; validation_losses = []; tabular_data = []; for i in range(len(model_list)): #Change 8 project = analysis_name; if(model_list[i][1]): experiment = "Model_" + str(model_list[i][0]) + "_freeze_base"; #Change 9, 10 else: experiment = "Model_" + str(model_list[i][0]) + "_unfreeze_base"; if(model_list[i][2]): experiment += "_pretrained"; else: experiment += "_uninitialized"; ctf_.Add_Experiment(project, experiment) tmp = []; tmp.append(experiment); training_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_acc_history.npy"; tmp.append(np.load(training_accuracy_file, allow_pickle=True)[-1]); validation_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_acc_history.npy"; tmp.append(np.load(validation_accuracy_file, allow_pickle=True)[-1]); training_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_loss_history.npy"; tmp.append(np.load(training_loss_file, allow_pickle=True)[-1]); validation_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_loss_history.npy"; tmp.append(np.load(validation_loss_file, allow_pickle=True)[-1]); tabular_data.append(tmp) ctf_.Generate_Statistics(); self.custom_print("Generated statistics post all epochs"); self.custom_print(tabulate(tabular_data, headers=['Experiment Name', 'Train Acc', 'Val Acc', 'Train Loss', 'Val Loss'], tablefmt='orgtbl')); self.custom_print(""); return_dict = {}; for i in range(len(tabular_data)): return_dict[tabular_data[i][0]] = {}; return_dict[tabular_data[i][0]]["training_accuracy"] = tabular_data[i][1]; return_dict[tabular_data[i][0]]["validation_accuracy"] = tabular_data[i][2]; return_dict[tabular_data[i][0]]["training_loss"] = tabular_data[i][3]; return_dict[tabular_data[i][0]]["validation_loss"] = tabular_data[i][4]; fname = self.system_dict["master_systems_dir_relative"] + analysis_name + "/" + tabular_data[i][0] + "/experiment_state.json"; system_dict = read_json(fname); return_dict[tabular_data[i][0]]["training_time"] = system_dict["training"]["outputs"]["training_time"]; if(state=="keep_none"): shutil.rmtree(self.system_dict["master_systems_dir_relative"] + analysis_name); return return_dict ############################################################################################################################################### ############################################################################################################################################### @warning_checks(None, None, None, ["lt", 50], num_epochs=["lte", 10], state=None, post_trace=True) @error_checks(None, ["name", ["A-Z", "a-z", "0-9", "-", "_", "."]], None, ["gt", 0, "lte", 100], num_epochs=["gt", 0], state=["in", ["keep_all", "keep_none"]], post_trace=True) @accepts("self", str, list, [int, float], num_epochs=int, state=str, post_trace=True) @TraceFunction(trace_args=True, trace_rv=True) def Analyse_Optimizers(self, analysis_name, optimizer_list, percent_data, num_epochs=2, state="keep_all"): ''' Hyperparameter Tuner - Analyse optimizers Takes in a list of optimizers and trains on a part of dataset Provides summaries and graphs on every sub-experiment created Args: analysis_name (str): A suitable name for analysis inp_size_list (list): List of optimizers. percent_data (int): Percentage of complete dataset to run experiments on. num_epochs (int): Number of epochs for each sub-experiment state ("str"): If set as "keep_all", keeps every file in the sub-experiment If set as "keep_none", keeps only comparison files for each experiment Returns: dict: Tabular data on training_accuracy, validation_accuracy, training_loss, validation_loss and training_time for each experiment. ''' from keras_prototype import prototype project = analysis_name; self.custom_print(""); self.custom_print("Running Optimizer analysis"); #Change 1 self.custom_print("Analysis Name : {}".format(project)); self.custom_print(""); for i in range(len(optimizer_list)): #Change 2 ktf_ = prototype(verbose=0); self.custom_print("Running experiment : {}/{}".format(i+1, len(optimizer_list))); #Change 3 experiment = "Optimizer_" + str(optimizer_list[i]); #Change 4, 5 self.custom_print("Experiment name : {}".format(experiment)) ktf_.Prototype(project, experiment, pseudo_copy_from=[self.system_dict["project_name"], self.system_dict["experiment_name"]]); ktf_.Dataset_Percent(percent_data); dataset_type = ktf_.system_dict["dataset"]["dataset_type"]; dataset_train_path = ktf_.system_dict["dataset"]["train_path"]; dataset_val_path = ktf_.system_dict["dataset"]["val_path"]; csv_train = ktf_.system_dict["dataset"]["csv_train"]; csv_val = ktf_.system_dict["dataset"]["csv_val"]; if(dataset_type=="train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); elif(dataset_type=="csv_train"): ktf_.update_dataset(dataset_path=dataset_train_path, path_to_csv="sampled_dataset_train.csv"); elif(dataset_type=="csv_train-val"): ktf_.update_dataset(dataset_path=[dataset_train_path, dataset_val_path], path_to_csv=["sampled_dataset_train.csv", "sampled_dataset_val.csv"]); lr = ktf_.system_dict["hyper-parameters"]["learning_rate"] if(optimizer_list[i] == "adagrad"): #Change 6 ktf_.optimizer_adagrad(lr); elif(optimizer_list[i] == "adadelta"): ktf_.optimizer_adadelta(lr); elif(optimizer_list[i] == "adam"): ktf_.optimizer_adam(lr); elif(optimizer_list[i] == "adamax"): ktf_.optimizer_adamax(lr); elif(optimizer_list[i] == "rmsprop"): ktf_.optimizer_rmsprop(lr); elif(optimizer_list[i] == "nesterov_adam"): ktf_.optimizer_nesterov_adam(lr); elif(optimizer_list[i] == "sgd"): ktf_.optimizer_sgd(lr); elif(optimizer_list[i] == "nesterov_sgd"): ktf_.optimizer_nesterov_sgd(lr); ktf_.Reload(); #Change 7 ktf_.update_num_epochs(num_epochs); ktf_.update_display_progress_realtime(False) ktf_.update_save_intermediate_models(False); ktf_.system_dict = set_transform_estimate(ktf_.system_dict); ktf_.set_dataset_dataloader(estimate=True); total_time_per_epoch = ktf_.get_training_estimate(); total_time = total_time_per_epoch*num_epochs; if(int(total_time//60) == 0): self.custom_print("Estimated time : {} sec".format(total_time)); else: self.custom_print("Estimated time : {} min".format(int(total_time//60)+1)); ktf_.Train(); self.custom_print("Experiment Complete"); self.custom_print("\n"); self.custom_print("Comparing Experiments"); from compare_prototype import compare ctf_ = compare(verbose=0); ctf_.Comparison("Comparison_" + analysis_name); self.custom_print("Comparison ID: {}".format("Comparison_" + analysis_name)); training_accuracies = []; validation_accuracies = []; training_losses = []; validation_losses = []; tabular_data = []; for i in range(len(optimizer_list)): #Change 8 project = analysis_name; experiment = "Optimizer_" + str(optimizer_list[i]); #Change 9, 10 ctf_.Add_Experiment(project, experiment) tmp = []; tmp.append(experiment); training_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_acc_history.npy"; tmp.append(np.load(training_accuracy_file, allow_pickle=True)[-1]); validation_accuracy_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_acc_history.npy"; tmp.append(np.load(validation_accuracy_file, allow_pickle=True)[-1]); training_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/train_loss_history.npy"; tmp.append(np.load(training_loss_file, allow_pickle=True)[-1]); validation_loss_file = self.system_dict["master_systems_dir_relative"] + "/" + project + "/" + experiment + "/output/logs/val_loss_history.npy"; tmp.append(np.load(validation_loss_file, allow_pickle=True)[-1]); tabular_data.append(tmp) ctf_.Generate_Statistics(); self.custom_print("Generated statistics post all epochs"); self.custom_print(tabulate(tabular_data, headers=['Experiment Name', 'Train Acc', 'Val Acc', 'Train Loss', 'Val Loss'], tablefmt='orgtbl')); self.custom_print(""); return_dict = {}; for i in range(len(tabular_data)): return_dict[tabular_data[i][0]] = {}; return_dict[tabular_data[i][0]]["training_accuracy"] = tabular_data[i][1]; return_dict[tabular_data[i][0]]["validation_accuracy"] = tabular_data[i][2]; return_dict[tabular_data[i][0]]["training_loss"] = tabular_data[i][3]; return_dict[tabular_data[i][0]]["validation_loss"] = tabular_data[i][4]; fname = self.system_dict["master_systems_dir_relative"] + analysis_name + "/" + tabular_data[i][0] + "/experiment_state.json"; system_dict = read_json(fname); return_dict[tabular_data[i][0]]["training_time"] = system_dict["training"]["outputs"]["training_time"]; if(state=="keep_none"): shutil.rmtree(self.system_dict["master_systems_dir_relative"] + analysis_name); return return_dict ###############################################################################################################################################
""" Does the following: 1. Generates and saves random secret keys for django and database access in env.example ansible/host_vars/{{cookiecutter.production_host_name}} A portion of this code was adopted from Django's standard crypto functions and utilities, specifically: https://github.com/django/django/blob/master/django/utils/crypto.py """ from __future__ import print_function import os import random # import shutil # from cookiecutter.main import cookiecutter # Get the root project directory PROJECT_DIRECTORY = os.path.realpath(os.path.curdir) # Use the system PRNG if possible try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: using_sysrandom = False def get_random_string( length=50, allowed_chars='abcdefghijklmnopqrstuvwxyz0123456789!@%^&*(-_=+)'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if using_sysrandom: return ''.join(random.choice(allowed_chars) for i in range(length)) print( "Couldn't find a secure pseudo-random number generator on your system." "Please change change your SECRET_KEY variables in" "env.example ansible/host_vars" "manually." ) return "CHANGEME!!" def set_secret_key(file_location): # Open locals.py with open(file_location) as f: file_ = f.read() # Generate a SECRET_KEY that matches the Django standard SECRET_KEY = get_random_string() # Replace "CHANGEME!!!" with SECRET_KEY file_ = file_.replace('change_django_secret_key!!!', SECRET_KEY, 1) # Write the results to the locals.py module with open(file_location, 'w') as f: f.write(file_) def set_django_admin_user_password(file_location, secret_key): with open(file_location) as f: file_ = f.read() file_ = file_.replace('change_django_admin_password!!!', secret_key, 1) with open(file_location, 'w') as f: f.write(file_) def set_db_password(file_location, secret_key): with open(file_location) as f: file_ = f.read() file_ = file_.replace('change_db_password!!!', secret_key, 1) with open(file_location, 'w') as f: f.write(file_) def make_secret_key(project_directory): """Generates and saves random secret key""" # Determine the local_setting_file_location env_file = os.path.join( project_directory, 'env.example' ) # env.example file set_secret_key(env_file) def make_db_password(project_directory): """Generates and saves a random password for the db user""" SECRET_KEY = get_random_string(length=12) env_file = os.path.join( project_directory, 'env.example' ) # env.example file set_db_password(env_file, SECRET_KEY) # import pdb; pdb.set_trace() ### BREAK-POINT host_vars_file = os.path.join( project_directory, 'ansible', 'host_vars', '{{ cookiecutter.production_host_name }}' ) # set it in host_vars file set_db_password(host_vars_file, SECRET_KEY) def make_django_admin_user_password(project_directory): # import pdb; pdb.set_trace() ### BREAK-POINT SECRET_KEY = get_random_string(length=12) host_vars_file = os.path.join( project_directory, 'ansible', 'host_vars', '{{ cookiecutter.production_host_name }}' ) set_django_admin_user_password(host_vars_file, SECRET_KEY) def remove_file(file_name): if os.path.exists(file_name): os.remove(file_name) make_secret_key(PROJECT_DIRECTORY) make_db_password(PROJECT_DIRECTORY) make_django_admin_user_password(PROJECT_DIRECTORY)
import logging import os import subprocess import time import json import yaml from jinja2 import Environment, select_autoescape, PackageLoader __author__ = 'Sumit_Nagal@intuit.com' logger = logging.getLogger(__name__) class Helper(object): #################################### # Function definitions # #################################### TEST_RESULT_STATUS = { True: "Success", False: "Failed", "Running": "Awaited" } def run_shell_task(self, cmd_arg_list): """ run_shell_task() runs a shell command and prints the output as it executes. It takes a list of strings that comprises the command itself, as the sole arg. """ run_cmd = subprocess.Popen(cmd_arg_list, stdout=subprocess.PIPE, env=os.environ.copy()) run_cmd.communicate() def chaos_result_tracker(self, exp_name, exp_phase, exp_verdict, ns, jornal_file_name = None): """ chaos_result_tracker() creates/patches the litmus chaosresult custom resource in the provided namespace. Typically invoked before and after chaos, and takes the .spec.phase, .spec.verdict & namespace as as args. """ env_tmpl = Environment(loader=PackageLoader('chaostest', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=select_autoescape(['yaml'])) template = env_tmpl.get_template('chaos-result.j2') events = None # if jornal_file_name: # if os.path.exists(jornal_file_name): # with open(jornal_file_name, "r") as file: # yaml_content = yaml.dump(json.load(file)) # if yaml_content: # events = "\n" + yaml_content # file.close() updated_chaosresult_template = template.render(c_experiment=exp_name, phase=exp_phase, verdict=exp_verdict, events=events) with open('chaosresult.yaml', "w+") as f: f.write(updated_chaosresult_template) chaosresult_update_cmd_args_list = ['kubectl', 'apply', '-f', 'chaosresult.yaml', '-n', ns] self.run_shell_task(chaosresult_update_cmd_args_list) @staticmethod def get_updated_result_name(experiment_name: str): timestamp = str(int(time.time() * 1000)) result_name = experiment_name + "-" + timestamp return result_name
/* * This header is generated by classdump-dyld 1.5 * on Wednesday, October 27, 2021 at 3:23:07 PM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/WatchListKit.framework/WatchListKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <WatchListKit/WLKUTSNetworkRequestOperation.h> @class NSArray; @interface WLKTopShelfRequestOperation : WLKUTSNetworkRequestOperation { NSArray* _items; } @property (nonatomic,readonly) NSArray * items; //@synthesize items=_items - In the implementation block -(id)init; -(NSArray *)items; -(void)processResponse; -(id)initWithQueryParameters:(id)arg1 options:(long long)arg2 ; @end
import pool from "./../../system/pooling.js"; import * as event from "./../../system/event.js"; import { viewport } from "./../../game.js"; import collision from "./../../physics/collision.js"; import Body from "./../../physics/body.js"; import TMXOrthogonalRenderer from "./renderer/TMXOrthogonalRenderer.js"; import TMXIsometricRenderer from "./renderer/TMXIsometricRenderer.js"; import TMXHexagonalRenderer from "./renderer/TMXHexagonalRenderer.js"; import TMXStaggeredRenderer from "./renderer/TMXStaggeredRenderer.js"; import TMXTileset from "./TMXTileset.js"; import TMXTilesetGroup from "./TMXTilesetGroup.js"; import TMXGroup from "./TMXGroup.js"; import TMXLayer from "./TMXLayer.js"; import { applyTMXProperties } from "./TMXUtils.js"; import Renderable from "./../../renderable/renderable.js"; import Container from "./../../renderable/container.js"; import Rect from "./../../shapes/rectangle.js"; // constant to identify the collision object layer var COLLISION_GROUP = "collision"; /** * set a compatible renderer object * for the specified map * @ignore */ function getNewDefaultRenderer(map) { switch (map.orientation) { case "orthogonal": return new TMXOrthogonalRenderer(map); case "isometric": return new TMXIsometricRenderer(map); case "hexagonal": return new TMXHexagonalRenderer(map); case "staggered": return new TMXStaggeredRenderer(map); // if none found, throw an exception default: throw new Error(map.orientation + " type TMX Tile Map not supported!"); } } /** * read the layer Data * @ignore */ function readLayer(map, data, z) { return new TMXLayer(map, data, map.tilewidth, map.tileheight, map.orientation, map.tilesets, z); } /** * read the Image Layer Data * @ignore */ function readImageLayer(map, data, z) { // Normalize properties applyTMXProperties(data.properties, data); // create the layer var imageLayer = pool.pull("ImageLayer", // x/y is deprecated since 0.15 and replace by offsetx/y +data.offsetx || +data.x || 0, +data.offsety || +data.y || 0, Object.assign({ name: data.name, image: data.image, ratio : pool.pull("Vector2d", +data.parallaxx || 1.0, +data.parallaxy || 1.0), // convert to melonJS color format (note: this should be done earlier when parsing data) tint : typeof (data.tintcolor) !== "undefined" ? (pool.pull("Color")).parseHex(data.tintcolor, true) : undefined, z: z }, data.properties) ); // set some additional flags var visible = typeof(data.visible) !== "undefined" ? data.visible : true; imageLayer.setOpacity(visible ? +data.opacity : 0); return imageLayer; } /** * read the tileset Data * @ignore */ function readTileset(data) { return (new TMXTileset(data)); } /** * read the object group Data * @ignore */ function readObjectGroup(map, data, z) { return (new TMXGroup(map, data, z)); } /** * @classdesc * a TMX Tile Map Object * Tiled QT +0.7.x format * @class TMXTileMap * @memberOf me * @constructor * @param {String} levelId name of TMX map * @param {Object} data TMX map in JSON format * @example * // create a new level object based on the TMX JSON object * var level = new me.TMXTileMap(levelId, me.loader.getTMX(levelId)); * // add the level to the game world container * level.addTo(me.game.world, true); */ export default class TMXTileMap { // constructor constructor(levelId, data) { /** * the level data (JSON) * @ignore */ this.data = data; /** * name of the tilemap * @public * @type {String} * @name me.TMXTileMap#name */ this.name = levelId; /** * width of the tilemap in tiles * @public * @type {Number} * @name me.TMXTileMap#cols */ this.cols = +data.width; /** * height of the tilemap in tiles * @public * @type {Number} * @name me.TMXTileMap#rows */ this.rows = +data.height; /** * Tile width * @public * @type {Number} * @name me.TMXTileMap#tilewidth */ this.tilewidth = +data.tilewidth; /** * Tile height * @public * @type {Number} * @name me.TMXTileMap#tileheight */ this.tileheight = +data.tileheight; /** * is the map an infinite map * @public * @type {Number} * @default 0 * @name me.TMXTileMap#infinite */ this.infinite = +data.infinite; /** * the map orientation type. melonJS supports “orthogonal”, “isometric”, “staggered” and “hexagonal”. * @public * @type {String} * @default "orthogonal" * @name me.TMXTileMap#orientation */ this.orientation = data.orientation; /** * the order in which tiles on orthogonal tile layers are rendered. * (valid values are "left-down", "left-up", "right-down", "right-up") * @public * @type {String} * @default "right-down" * @name me.TMXTileMap#renderorder */ this.renderorder = data.renderorder || "right-down"; /** * the TMX format version * @public * @type {String} * @name me.TMXTileMap#version */ this.version = data.version; /** * The Tiled version used to save the file (since Tiled 1.0.1). * @public * @type {String} * @name me.TMXTileMap#tiledversion */ this.tiledversion = data.tiledversion; // tilesets for this map this.tilesets = null; // layers if (typeof this.layers === "undefined") { this.layers = []; } // group objects if (typeof this.objectGroups === "undefined") { this.objectGroups = []; } // Check if map is from melon editor this.isEditor = data.editor === "melon-editor"; // object id this.nextobjectid = +data.nextobjectid || undefined; // hex/iso properties this.hexsidelength = +data.hexsidelength; this.staggeraxis = data.staggeraxis; this.staggerindex = data.staggerindex; // calculate the map bounding rect this.bounds = this.getRenderer().getBounds().clone(); // map "real" size this.width = this.bounds.width; this.height = this.bounds.height; // background color this.backgroundcolor = data.backgroundcolor; // set additional map properties (if any) applyTMXProperties(this, data); // internal flag this.initialized = false; if (this.infinite === 1) { // #956 Support for Infinite map // see as well in me.TMXUtils throw new Error("Tiled Infinite Map not supported!"); } } /** * Return the map default renderer * @name getRenderer * @memberOf me.TMXTileMap * @public * @function * @return {me.TMXRenderer} a TMX renderer */ getRenderer() { if ((typeof(this.renderer) === "undefined") || (!this.renderer.canRender(this))) { this.renderer = getNewDefaultRenderer(this); }; return this.renderer; } /** * return the map bounding rect * @name me.TMXRenderer#getBounds * @public * @function * @return {me.Bounds} */ getBounds() { // calculated in the constructor return this.bounds; } /** * parse the map * @ignore */ readMapObjects(data) { if (this.initialized === true) { return; } // to automatically increment z index var zOrder = 0; // Tileset information if (!this.tilesets) { // make sure we have a TilesetGroup Object this.tilesets = new TMXTilesetGroup(); } // parse all tileset objects if (typeof (data.tilesets) !== "undefined") { var tilesets = data.tilesets; tilesets.forEach((tileset) => { // add the new tileset this.tilesets.add(readTileset(tileset)); }); } // check if a user-defined background color is defined if (this.backgroundcolor) { this.layers.push( pool.pull("ColorLayer", "background_color", this.backgroundcolor, zOrder++ ) ); } // check if a background image is defined if (this.background_image) { // add a new image layer this.layers.push( pool.pull("ImageLayer", 0, 0, { name : "background_image", image : this.background_image, z : zOrder++ } )); } data.layers.forEach((layer) => { switch (layer.type) { case "imagelayer": this.layers.push(readImageLayer(this, layer, zOrder++)); break; case "tilelayer": this.layers.push(readLayer(this, layer, zOrder++)); break; // get the object groups information case "objectgroup": this.objectGroups.push(readObjectGroup(this, layer, zOrder++)); break; // get the object groups information case "group": this.objectGroups.push(readObjectGroup(this, layer, zOrder++)); break; default: break; } }); this.initialized = true; } /** * add all the map layers and objects to the given container. * note : this will not automatically update the camera viewport * @name me.TMXTileMap#addTo * @public * @function * @param {me.Container} target container * @param {boolean} [flatten=true] if true, flatten all objects into the given container, else a `me.Container` object will be created for each corresponding groups * @param {boolean} [setViewportBounds=false] if true, set the viewport bounds to the map size, this should be set to true especially if adding a level to the game world container. * @example * // create a new level object based on the TMX JSON object * var level = new me.TMXTileMap(levelId, me.loader.getTMX(levelId)); * // add the level to the game world container * level.addTo(me.game.world, true, true); */ addTo(container, flatten, setViewportBounds) { var _sort = container.autoSort; var _depth = container.autoDepth; var levelBounds = this.getBounds(); // disable auto-sort and auto-depth container.autoSort = false; container.autoDepth = false; // add all layers instances this.getLayers().forEach(function (layer) { container.addChild(layer); }); // add all Object instances this.getObjects(flatten).forEach(function (object) { container.addChild(object); }); // resize the container accordingly container.resize(this.bounds.width, this.bounds.height); // sort everything (recursively) container.sort(true); // callback funtion for the viewport resize event function _setBounds(width, height) { // adjust the viewport bounds if level is smaller viewport.setBounds( 0, 0, Math.max(levelBounds.width, width), Math.max(levelBounds.height, height) ); // center the map if smaller than the current viewport container.pos.set( Math.max(0, ~~((width - levelBounds.width) / 2)), Math.max(0, ~~((height - levelBounds.height) / 2)), // don't change the container z position if defined container.pos.z ); } if (setViewportBounds === true) { event.off(event.VIEWPORT_ONRESIZE, _setBounds); // force viewport bounds update _setBounds(viewport.width, viewport.height); // Replace the resize handler event.on(event.VIEWPORT_ONRESIZE, _setBounds, this); } // set back auto-sort and auto-depth container.autoSort = _sort; container.autoDepth = _depth; } /** * return an Array of instantiated objects, based on the map object definition * @name me.TMXTileMap#getObjects * @public * @function * @param {boolean} [flatten=true] if true, flatten all objects into the returned array. * when false, a `me.Container` object will be created for each corresponding groups * @return {me.Renderable[]} Array of Objects */ getObjects(flatten) { var objects = []; var isCollisionGroup = false; var targetContainer; // parse the map for objects this.readMapObjects(this.data); for (var g = 0; g < this.objectGroups.length; g++) { var group = this.objectGroups[g]; // check if this is the collision shape group isCollisionGroup = group.name.toLowerCase().includes(COLLISION_GROUP); if (flatten === false) { // create a new container targetContainer = new Container(0, 0, this.width, this.height); // tiled uses 0,0 by default targetContainer.anchorPoint.set(0, 0); // set additional properties targetContainer.name = group.name; targetContainer.pos.z = group.z; targetContainer.setOpacity(group.opacity); // disable auto-sort and auto-depth targetContainer.autoSort = false; targetContainer.autoDepth = false; } // iterate through the group and add all object into their // corresponding target Container for (var o = 0; o < group.objects.length; o++) { // TMX object settings var settings = group.objects[o]; // reference to the instantiated object var obj; // Tiled uses 0,0 by default if (typeof (settings.anchorPoint) === "undefined") { settings.anchorPoint = {x : 0, y : 0}; } // convert to melonJS renderable argument name if (typeof (settings.tintcolor) !== "undefined") { settings.tint = pool.pull("Color"); settings.tint.parseHex(settings.tintcolor, true); } /// XXX Clean/rewrite all this part to remove object /// specific instantiation logic/details from here // groups can contains either text, objects or layers if (settings instanceof TMXLayer) { // layers are already instantiated & initialized obj = settings; // z value set already } else if (typeof settings.text === "object") { // Tiled uses 0,0 by default if (typeof (settings.text.anchorPoint) === "undefined") { settings.text.anchorPoint = settings.anchorPoint; } if (settings.text.bitmap === true) { obj = pool.pull("BitmapText", settings.x, settings.y, settings.text); } else { obj = pool.pull("Text", settings.x, settings.y, settings.text); } // set the obj z order obj.pos.z = settings.z; } else if (typeof settings.tile === "object") { // check if a me.Tile object is embedded obj = settings.tile.getRenderable(settings); obj.body = new Body(obj, settings.shapes || new Rect(0, 0, this.width, this.height)); obj.body.setStatic(true); // set the obj z order obj.pos.setMuted(settings.x, settings.y, settings.z); } else { // pull the corresponding object from the object pool if (typeof settings.name !== "undefined" && settings.name !== "") { obj = pool.pull( settings.name, settings.x, settings.y, settings ); } else { // unnamed shape object obj = pool.pull( "Renderable", settings.x, settings.y, settings.width, settings.height ); obj.anchorPoint.set(0, 0); obj.name = settings.name; obj.type = settings.type; obj.id = settings.id; obj.body = new Body(obj, settings.shapes || new Rect(0, 0, obj.width, obj.height)); obj.body.setStatic(true); obj.resize(obj.body.getBounds().width, obj.body.getBounds().height); } // set the obj z order obj.pos.z = settings.z; } if (isCollisionGroup && !settings.name && obj.body) { // configure the body accordingly obj.body.collisionType = collision.types.WORLD_SHAPE; } //apply group opacity value to the child objects if group are merged if (flatten !== false) { if (obj.isRenderable === true) { obj.setOpacity(obj.getOpacity() * group.opacity); // and to child renderables if any if (obj.renderable instanceof Renderable) { obj.renderable.setOpacity(obj.renderable.getOpacity() * group.opacity); } } // directly add the obj into the objects array objects.push(obj); } else /* false*/ { // add it to the new container targetContainer.addChild(obj); } } // if we created a new container if ((flatten === false) && (targetContainer.children.length > 0)) { // re-enable auto-sort and auto-depth targetContainer.autoSort = true; targetContainer.autoDepth = true; // add our container to the world objects.push(targetContainer); } } return objects; } /** * return all the existing layers * @name me.TMXTileMap#getLayers * @public * @function * @return {me.TMXLayer[]} Array of Layers */ getLayers() { // parse the map for objects this.readMapObjects(this.data); return this.layers; } /** * destroy function, clean all allocated objects * @name me.TMXTileMap#destroy * @public * @function */ destroy() { this.tilesets = undefined; this.layers.length = 0; this.objectGroups.length = 0; this.initialized = false; } };
require('dotenv').config() const fetch = require('node-fetch') const log = require('./logger') const { CARD_CONTRACT, OPENSEA_SLUG } = require('./constants') const OPENSEA_URL = 'https://opensea.io/assets' const OPENSEA_API = 'https://api.opensea.io/api/v1' const API_LIMIT = 15 const { OPENSEA_API_KEY } = process.env const headers = OPENSEA_API_KEY ? {"X-API-KEY": OPENSEA_API_KEY } : {} const getCardUrl = id => `${OPENSEA_URL}/${CARD_CONTRACT}/${id}` const makeRequest = async api => { log.debug(`Requesting ${api}`) const res = await fetch(api, {method: 'GET', headers}) return await res.json() } const getCard = async id => { const api = `${OPENSEA_API}/asset/${CARD_CONTRACT}/${id}` return await makeRequest(api) } const getCardEvents = async after => { let api = `${OPENSEA_API}/events?collection_slug=${OPENSEA_SLUG}&event_type=successful&limit=${API_LIMIT}` if (after) { // Add unix timestamp api += `&occurred_after=${after.unix()}` } return await makeRequest(api) } const getCardDetails = async cardIds => { let api = `${OPENSEA_API}/assets?asset_contract_address=${CARD_CONTRACT}&token_ids=${cardIds.join('&token_ids=')}` return await makeRequest(api) } module.exports = { getCardUrl, getCard, getCardEvents, getCardDetails, }
import { createElement, PureComponent } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { deburrUpper } from 'utils/strings'; import groupBy from 'lodash/groupBy'; import remove from 'lodash/remove'; import Component from './component'; const mapStateToProps = ( { modalMeta }, { value, options, noSelectedValue } ) => { const activeValue = options && (typeof value === 'string' || typeof value === 'number') ? options.find((o) => o.value === value) : value; const activeLabel = (activeValue && activeValue.label) || noSelectedValue; return { modalOpen: modalMeta ? modalMeta.open : false, modalClosing: modalMeta ? modalMeta.closing : false, activeValue, activeLabel, }; }; class DropdownContainer extends PureComponent { constructor(props) { super(props); this.state = { inputValue: '', isOpen: false, showGroup: '', highlightedIndex: 0, }; } filterItems = () => { const { inputValue } = this.state; const { options, groupKey } = this.props; return groupBy( inputValue ? options.filter( (item) => deburrUpper(item.label).indexOf(deburrUpper(inputValue)) > -1 ) : options, groupKey || 'group' ); }; getGroupedItems = () => { const newItems = this.filterItems(); const groups = remove(Object.keys(newItems), (r) => r !== 'undefined'); const list = newItems.undefined || []; const listWithGroups = list.concat( groups.map((g) => ({ label: g, value: g, groupParent: g })) ); let listWithGroupsAndItems = listWithGroups; groups.forEach((g) => { listWithGroupsAndItems = listWithGroupsAndItems.concat(newItems[g]); }); return listWithGroupsAndItems; }; handleStateChange = (changes, downshiftStateAndHelpers) => { if (!downshiftStateAndHelpers.isOpen) { this.setState({ inputValue: '' }); } else if ((changes && changes.inputValue) || changes.inputValue === '') { this.setState({ inputValue: changes.inputValue, highlightedIndex: 0 }); } if (changes && changes.selectedItem) { this.setState({ isOpen: false, inputValue: '' }); } if (Object.keys(changes).indexOf('isOpen') > -1) { this.setState({ inputValue: '' }); } if ( (changes && changes.highlightedIndex) || changes.highlightedIndex === 0 ) { this.setState({ highlightedIndex: changes.highlightedIndex }); } }; checkModalClosing = () => { const { modalOpen, modalClosing } = this.props; if (!modalOpen && !modalClosing) { this.setState({ isOpen: false }); } }; onInputClick = () => { const { searchable } = this.props; const { isOpen } = this.state; if (!searchable && isOpen) { this.setState({ isOpen: false, showGroup: '' }); } else { this.setState({ isOpen: true, inputValue: '' }); } }; onSelectorClick = () => { const { isOpen } = this.state; this.setState({ isOpen: !isOpen, inputValue: '' }); }; handleClearSelection = () => { const { onChange } = this.props; onChange(); this.setState({ isOpen: false, showGroup: '', inputValue: '' }); }; handleSelectGroup = (item) => { const { showGroup } = this.state; this.setState({ showGroup: item.groupParent === showGroup ? '' : item.groupParent, isOpen: true, }); }; handleKeyEnter = (e) => { const { showGroup, highlightedIndex } = this.state; if (e.key === 'Enter') { const groupedItems = this.getGroupedItems(); const selected = groupedItems[highlightedIndex]; if (selected && selected.groupParent) { e.persist(); e.preventDownshiftDefault = true; this.setState({ showGroup: showGroup === selected.groupParent ? '' : selected.groupParent, }); } } }; buildInputProps = (getInputProps) => { const { isOpen } = this.state; const { searchable, placeholder } = this.props; return getInputProps({ placeholder: isOpen && searchable ? placeholder : '', onClick: this.onInputClick, readOnly: !isOpen || !searchable, onKeyDown: (e) => this.handleKeyEnter(e), }); }; render() { const { isOpen, showGroup, inputValue, highlightedIndex } = this.state; return createElement(Component, { ...this.props, isOpen, showGroup, inputValue, highlightedIndex, checkModalClosing: this.checkModalClosing, handleStateChange: this.handleStateChange, onInputClick: this.onInputClick, onSelectorClick: this.onSelectorClick, handleClearSelection: this.handleClearSelection, buildInputProps: this.buildInputProps, handleSelectGroup: this.handleSelectGroup, items: this.getGroupedItems(), }); } } DropdownContainer.propTypes = { modalOpen: PropTypes.bool, modalClosing: PropTypes.bool, searchable: PropTypes.bool, options: PropTypes.array, groupKey: PropTypes.string, placeholder: PropTypes.string, onChange: PropTypes.func, }; export default connect(mapStateToProps, null)(DropdownContainer);
import Config from '../configs/api'; import request from 'request-promise'; import queryString from 'querystring'; function getData(pathElements, parameters) { parameters = parameters || {}; var path = 'https://global.api.pvp.net/api/lol/' + pathElements.join('/'); // jscs:disable parameters.api_key = Config.API_KEY; path += '?' + queryString.stringify(parameters); return request(path).then(function(body) { return JSON.parse(body); }); } function getStaticData(pathElements, parameters) { var base = ['static-data', Config.REGION, 'v1.2']; base = base.concat(pathElements); return getData(base, parameters); } function getApiResource(resource, params) { switch (resource) { case 'champions': return getStaticData(['champion']); case 'champion': return getStaticData(['champion', params.id]); case 'items': return getStaticData(['item']); case 'item': return getStaticData(['item', params.id]); case 'masteries': return getStaticData(['mastery']); case 'mastery': return getStaticData(['mastery', params.id]); case 'runes': return getStaticData(['rune']); case 'rune': return getStaticData(['rune', params.id]); case 'summoner-spells': return getStaticData(['summoner-spell']); case 'summoner-spell': return getStaticData(['summoner-spell', params.id]); } return null; }; function apiRead(req, resource, params, config, callback) { let data = getApiResource(resource, params); if (!data) { callback(new Error('Fetching ' + resource + ' with params ' + params.toString() + ' failed')); } else { callback(data); } } const riotService = { name: 'riot', read: apiRead }; export default riotService;
# Copyright: See the LICENSE file. from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) email = db.Column(db.String(120), unique=True) def __init__(self, username, email): self.username = username self.email = email def __repr__(self): return '<User %r>' % self.username class UserLog(db.Model): id = db.Column(db.Integer, primary_key=True) message = db.Column(db.String(1000)) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('logs', lazy='dynamic')) def __init__(self, message, user): self.message = message self.user = user def __repr__(self): return f'<Log for {self.user!r}: {self.message}>'
from .cart import Cart #instantiate the cart using the request object and make it available to other templates as variable names 'cart' #makes the current car object available to all templates with cart as name #next setting.py to add context:processors #than base.html add django template to html def cart_context(request): return {'cart':Cart(request)}
# Copyright (C) 2017 MongoDB Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License, version 3, # as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # """ IDL compiler driver. Orchestrates the 3 passes (parser, binder, and generator) together. """ from __future__ import absolute_import, print_function, unicode_literals import io import logging import os import platform from typing import Any, List from . import binder from . import errors from . import generator from . import parser from . import syntax class CompilerArgs(object): """Set of compiler arguments.""" # pylint: disable=too-many-instance-attributes def __init__(self): # type: () -> None """Create a container for compiler arguments.""" self.import_directories = None # type: List[unicode] self.input_file = None # type: unicode self.target_arch = None # type: unicode self.output_source = None # type: unicode self.output_header = None # type: unicode self.output_base_dir = None # type: unicode self.output_suffix = None # type: unicode self.write_dependencies = False # type: bool class CompilerImportResolver(parser.ImportResolverBase): """Class for the IDL compiler to resolve imported files.""" def __init__(self, import_directories): # type: (List[unicode]) -> None """Construct a ImportResolver.""" self._import_directories = import_directories super(CompilerImportResolver, self).__init__() def resolve(self, base_file, imported_file_name): # type: (unicode, unicode) -> unicode """Return the complete path to an imported file name.""" logging.debug("Resolving imported file '%s' for file '%s'", imported_file_name, base_file) # Check for fully-qualified paths logging.debug("Checking for imported file '%s' for file '%s' at '%s'", imported_file_name, base_file, imported_file_name) if os.path.isabs(imported_file_name) and os.path.exists(imported_file_name): logging.debug("Found imported file '%s' for file '%s' at '%s'", imported_file_name, base_file, imported_file_name) return imported_file_name for candidate_dir in self._import_directories or []: base_dir = os.path.abspath(candidate_dir) resolved_file_name = os.path.normpath(os.path.join(base_dir, imported_file_name)) logging.debug("Checking for imported file '%s' for file '%s' at '%s'", imported_file_name, base_file, resolved_file_name) if os.path.exists(resolved_file_name): logging.debug("Found imported file '%s' for file '%s' at '%s'", imported_file_name, base_file, resolved_file_name) return resolved_file_name msg = ("Cannot find imported file '%s' for file '%s'" % (imported_file_name, base_file)) logging.error(msg) raise errors.IDLError(msg) def open(self, resolved_file_name): # type: (unicode) -> Any """Return an io.Stream for the requested file.""" return io.open(resolved_file_name, encoding='utf-8') def _write_dependencies(spec): # type: (syntax.IDLSpec) -> None """Write a list of dependencies to standard out.""" if not spec.imports: return dependencies = sorted(spec.imports.dependencies) for resolved_file_name in dependencies: print(resolved_file_name) def _update_import_includes(args, spec, header_file_name): # type: (CompilerArgs, syntax.IDLSpec, unicode) -> None """Update the list of imports with a list of include files for each import with structs.""" # This function is fragile: # In order to try to generate headers with an "include what you use" set of headers, the IDL # compiler needs to generate include statements to headers for imported files with structs. The # problem is that the IDL compiler needs to make the following assumptions: # 1. The layout of build vs source directory. # 2. The file naming suffix rules for all IDL invocations are consistent. if not spec.imports: return if args.output_base_dir: base_include_h_file_name = os.path.relpath( os.path.normpath(header_file_name), os.path.normpath(args.output_base_dir)) else: base_include_h_file_name = os.path.abspath(header_file_name) # Normalize to POSIX style for consistency across Windows and POSIX. base_include_h_file_name = base_include_h_file_name.replace("\\", "/") # Modify the includes list of the root_doc to include all of its direct imports if not spec.globals: spec.globals = syntax.Global(args.input_file, -1, -1) first_dir = base_include_h_file_name.split('/')[0] for resolved_file_name in spec.imports.resolved_imports: # Guess: the file naming rules are consistent across IDL invocations include_h_file_name = os.path.splitext(resolved_file_name)[0] + args.output_suffix + ".h" if args.output_base_dir: include_h_file_name = os.path.relpath( os.path.normpath(include_h_file_name), os.path.normpath(args.output_base_dir)) else: include_h_file_name = os.path.abspath(include_h_file_name) # Normalize to POSIX style for consistency across Windows and POSIX. include_h_file_name = include_h_file_name.replace("\\", "/") if args.output_base_dir: # Guess: The layout of build vs source directory include_h_file_name = include_h_file_name[include_h_file_name.find(first_dir):] spec.globals.cpp_includes.append(include_h_file_name) def compile_idl(args): # type: (CompilerArgs) -> bool """Compile an IDL file into C++ code.""" # Named compile_idl to avoid naming conflict with builtin if not os.path.exists(args.input_file): logging.error("File '%s' not found", args.input_file) if args.output_source is None: if not '.' in args.input_file: logging.error("File name '%s' must be end with a filename extension, such as '%s.idl'", args.input_file, args.input_file) return False file_name_prefix = os.path.splitext(args.input_file)[0] file_name_prefix += args.output_suffix source_file_name = file_name_prefix + ".cpp" header_file_name = file_name_prefix + ".h" else: source_file_name = args.output_source header_file_name = args.output_header if args.target_arch is None: args.target_arch = platform.machine() # Compile the IDL through the 3 passes with io.open(args.input_file, encoding='utf-8') as file_stream: parsed_doc = parser.parse(file_stream, args.input_file, CompilerImportResolver(args.import_directories)) # Stop compiling if we only need to scan import dependencies if args.write_dependencies: _write_dependencies(parsed_doc.spec) return True if not parsed_doc.errors: _update_import_includes(args, parsed_doc.spec, header_file_name) bound_doc = binder.bind(parsed_doc.spec) if not bound_doc.errors: generator.generate_code(bound_doc.spec, args.target_arch, args.output_base_dir, header_file_name, source_file_name) return True else: bound_doc.errors.dump_errors() else: parsed_doc.errors.dump_errors() return False
function spiralTraverse(array) { const spiralSort = []; let startRow = 0, endRow = array.length -1; let startCol = 0, endCol = array[0].length -1; while(startRow <= endRow && startCol <= endCol) { for (let col = startCol; col <= endCol; col++) { spiralSort.push(array[startRow][col]); } for (let row = startRow+1; row <= endRow; row++) { spiralSort.push(array[row][endCol]); } for (let col = endCol-1; col >= startCol; col--) { if(startRow === endRow)break; spiralSort.push(array[endRow][col]); } for (let row = endRow-1; row > startRow; row--) { if(startCol === endCol)break; spiralSort.push(array[row][startCol]); } startRow++; endRow--; startCol++; endCol--; } return spiralSort; } array = [ [1,2,3,4], [12,13,14,5], [11,16,15,6], [10,9,8,7] ] console.log(spiralTraverse(array))
const m = require("mithril"); module.exports = m( ".icon", m.trust( '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-bold"><path d="M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"></path><path d="M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"></path></svg>', ), );
// ymaps.ready(init); // // function init() { // var myMap = new ymaps.Map("map", { // center: [47.222104, 39.720179], // zoom: 10 // }); // // // myMap.balloon.open(myMap.getCenter(), { // // contentHeader: "Однажды", // // contentBody: "В студенную зимнюю пору" // // }); // }
# -*- coding: utf-8 -*- # # skiboot documentation build configuration file, created by # sphinx-quickstart on Mon Jul 25 15:23:23 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'skiboot' copyright = u'2016, Stewart Smith, IBM, others' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '5.3' # The full version, including alpha/beta/rc tags. release = '5.3.0-rc1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'skibootdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'skiboot.tex', u'skiboot Documentation', u'Stewart Smith, IBM, others', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'skiboot', u'skiboot Documentation', [u'Stewart Smith, IBM, others'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'skiboot', u'skiboot Documentation', u'Stewart Smith, IBM, others', 'skiboot', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
//===--- ASTContext.h - AST Context Object ----------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the ASTContext interface. // //===----------------------------------------------------------------------===// #ifndef SWIFT_AST_ASTCONTEXT_H #define SWIFT_AST_ASTCONTEXT_H #include "llvm/Support/DataTypes.h" #include "swift/AST/ClangModuleLoader.h" #include "swift/AST/Identifier.h" #include "swift/AST/SearchPathOptions.h" #include "swift/AST/SubstitutionList.h" #include "swift/AST/Type.h" #include "swift/AST/TypeAlignments.h" #include "swift/Basic/LangOptions.h" #include "swift/Basic/Malloc.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/Allocator.h" #include <functional> #include <memory> #include <utility> #include <vector> namespace clang { class Decl; class MacroInfo; class Module; class ObjCInterfaceDecl; } namespace swift { class ASTContext; enum class Associativity : unsigned char; class BoundGenericType; class ClangNode; class Decl; class DeclContext; class DefaultArgumentInitializer; class ExtensionDecl; class ForeignRepresentationInfo; class FuncDecl; class GenericContext; class InFlightDiagnostic; class IterableDeclContext; class LazyContextData; class LazyGenericContextData; class LazyIterableDeclContextData; class LazyMemberLoader; class LazyResolver; class PatternBindingDecl; class PatternBindingInitializer; class SourceFile; class SourceLoc; class Type; class TypeVariableType; class TupleType; class FunctionType; class GenericSignatureBuilder; class ArchetypeType; class Identifier; class InheritedNameSet; class ModuleDecl; class ModuleLoader; class NominalTypeDecl; class NormalProtocolConformance; class InheritedProtocolConformance; class SpecializedProtocolConformance; enum class ProtocolConformanceState; class Pattern; enum PointerTypeKind : unsigned; class PrecedenceGroupDecl; class TupleTypeElt; class EnumElementDecl; enum OptionalTypeKind : unsigned; class ProtocolDecl; class SubstitutableType; class SourceManager; class ValueDecl; class DiagnosticEngine; class Substitution; class TypeCheckerDebugConsumer; struct RawComment; class DocComment; class SILBoxType; class TypeAliasDecl; class VarDecl; class UnifiedStatsReporter; enum class KnownProtocolKind : uint8_t; /// \brief The arena in which a particular ASTContext allocation will go. enum class AllocationArena { /// \brief The permanent arena, which is tied to the lifetime of /// the ASTContext. /// /// All global declarations and types need to be allocated into this arena. /// At present, everything that is not a type involving a type variable is /// allocated in this arena. Permanent, /// \brief The constraint solver's temporary arena, which is tied to the /// lifetime of a particular instance of the constraint solver. /// /// Any type involving a type variable is allocated in this arena. ConstraintSolver }; /// Lists the set of "known" Foundation entities that are used in the /// compiler. /// /// While the names of Foundation types aren't likely to change in /// Objective-C, their mapping into Swift can. Therefore, when /// referring to names of Foundation entities in Swift, use this enum /// and \c ASTContext::getSwiftName or \c ASTContext::getSwiftId. enum class KnownFoundationEntity { #define FOUNDATION_ENTITY(Name) Name, #include "swift/AST/KnownFoundationEntities.def" }; /// Retrieve the Foundation entity kind for the given Objective-C /// entity name. Optional<KnownFoundationEntity> getKnownFoundationEntity(StringRef name); /// \brief Introduces a new constraint checker arena, whose lifetime is /// tied to the lifetime of this RAII object. class ConstraintCheckerArenaRAII { ASTContext &Self; void *Data; public: /// \brief Introduces a new constraint checker arena, supplanting any /// existing constraint checker arena. /// /// \param self The ASTContext into which this constraint checker arena /// will be installed. /// /// \param allocator The allocator used for allocating any data that /// goes into the constraint checker arena. ConstraintCheckerArenaRAII(ASTContext &self, llvm::BumpPtrAllocator &allocator); ConstraintCheckerArenaRAII(const ConstraintCheckerArenaRAII &) = delete; ConstraintCheckerArenaRAII(ConstraintCheckerArenaRAII &&) = delete; ConstraintCheckerArenaRAII & operator=(const ConstraintCheckerArenaRAII &) = delete; ConstraintCheckerArenaRAII & operator=(ConstraintCheckerArenaRAII &&) = delete; ~ConstraintCheckerArenaRAII(); }; class SILLayout; // From SIL /// \brief Describes either a nominal type declaration or an extension /// declaration. typedef llvm::PointerUnion<NominalTypeDecl *, ExtensionDecl *> TypeOrExtensionDecl; /// ASTContext - This object creates and owns the AST objects. /// However, this class does more than just maintain context within an AST. /// It is the closest thing to thread-local or compile-local storage in this /// code base. Why? SourceKit uses this code with multiple threads per Unix /// process. Each thread processes a different source file. Each thread has its /// own instance of ASTContext, and that instance persists for the duration of /// the thread, throughout all phases of the compilation. (The name "ASTContext" /// is a bit of a misnomer here.) Why not use thread-local storage? This code /// may use DispatchQueues and pthread-style TLS won't work with code that uses /// DispatchQueues. Summary: if you think you need a global or static variable, /// you probably need to put it here instead. class ASTContext { ASTContext(const ASTContext&) = delete; void operator=(const ASTContext&) = delete; public: // Members that should only be used by ASTContext.cpp. struct Implementation; Implementation &Impl; friend ConstraintCheckerArenaRAII; public: ASTContext(LangOptions &langOpts, SearchPathOptions &SearchPathOpts, SourceManager &SourceMgr, DiagnosticEngine &Diags); ~ASTContext(); /// \brief The language options used for translation. LangOptions &LangOpts; /// \brief The search path options used by this AST context. SearchPathOptions &SearchPathOpts; /// \brief The source manager object. SourceManager &SourceMgr; /// Diags - The diagnostics engine. DiagnosticEngine &Diags; /// The set of top-level modules we have loaded. /// This map is used for iteration, therefore it's a MapVector and not a /// DenseMap. llvm::MapVector<Identifier, ModuleDecl*> LoadedModules; /// The builtin module. ModuleDecl * const TheBuiltinModule; /// The standard library module. mutable ModuleDecl *TheStdlibModule = nullptr; /// The name of the standard library module "Swift". Identifier StdlibModuleName; /// The name of the SwiftShims module "SwiftShims". Identifier SwiftShimsModuleName; // Define the set of known identifiers. #define IDENTIFIER_WITH_NAME(Name, IdStr) Identifier Id_##Name; #include "swift/AST/KnownIdentifiers.def" /// \brief The list of external definitions imported by this context. llvm::SetVector<Decl *> ExternalDefinitions; /// FIXME: HACK HACK HACK /// This state should be tracked somewhere else. unsigned LastCheckedExternalDefinition = 0; /// A consumer of type checker debug output. std::unique_ptr<TypeCheckerDebugConsumer> TypeCheckerDebug; /// Cache for names of canonical GenericTypeParamTypes. mutable llvm::DenseMap<unsigned, Identifier> CanonicalGenericTypeParamTypeNames; /// Cache of remapped types (useful for diagnostics). llvm::StringMap<Type> RemappedTypes; /// Optional table of counters to report, nullptr when not collecting. UnifiedStatsReporter *Stats = nullptr; private: /// \brief The current generation number, which reflects the number of /// times that external modules have been loaded. /// /// Various places in the AST, such as the set of extensions associated with /// a nominal type, keep track of the generation number they saw and will /// automatically update when they are out of date. unsigned CurrentGeneration = 0; friend class Pattern; /// Mapping from patterns that store interface types that will be lazily /// resolved to contextual types, to the declaration context in which the /// pattern resides. llvm::DenseMap<const Pattern *, DeclContext *> DelayedPatternContexts; /// Cache of module names that fail the 'canImport' test in this context. llvm::SmallPtrSet<Identifier, 8> FailedModuleImportNames; public: /// \brief Retrieve the allocator for the given arena. llvm::BumpPtrAllocator & getAllocator(AllocationArena arena = AllocationArena::Permanent) const; /// Allocate - Allocate memory from the ASTContext bump pointer. void *Allocate(unsigned long bytes, unsigned alignment, AllocationArena arena = AllocationArena::Permanent) const { if (bytes == 0) return nullptr; if (LangOpts.UseMalloc) return AlignedAlloc(bytes, alignment); return getAllocator(arena).Allocate(bytes, alignment); } template <typename T> T *Allocate(AllocationArena arena = AllocationArena::Permanent) const { T *res = (T *) Allocate(sizeof(T), alignof(T), arena); new (res) T(); return res; } template <typename T> MutableArrayRef<T> AllocateUninitialized(unsigned NumElts, AllocationArena Arena = AllocationArena::Permanent) const { T *Data = (T *) Allocate(sizeof(T) * NumElts, alignof(T), Arena); return { Data, NumElts }; } template <typename T> MutableArrayRef<T> Allocate(unsigned numElts, AllocationArena arena = AllocationArena::Permanent) const { T *res = (T *) Allocate(sizeof(T) * numElts, alignof(T), arena); for (unsigned i = 0; i != numElts; ++i) new (res+i) T(); return {res, numElts}; } /// Allocate a copy of the specified object. template <typename T> typename std::remove_reference<T>::type *AllocateObjectCopy(T &&t, AllocationArena arena = AllocationArena::Permanent) const { // This function cannot be named AllocateCopy because it would always win // overload resolution over the AllocateCopy(ArrayRef<T>). using TNoRef = typename std::remove_reference<T>::type; TNoRef *res = (TNoRef *) Allocate(sizeof(TNoRef), alignof(TNoRef), arena); new (res) TNoRef(std::forward<T>(t)); return res; } template <typename T, typename It> T *AllocateCopy(It start, It end, AllocationArena arena = AllocationArena::Permanent) const { T *res = (T*)Allocate(sizeof(T)*(end-start), alignof(T), arena); for (unsigned i = 0; start != end; ++start, ++i) new (res+i) T(*start); return res; } template<typename T, size_t N> MutableArrayRef<T> AllocateCopy(T (&array)[N], AllocationArena arena = AllocationArena::Permanent) const { return MutableArrayRef<T>(AllocateCopy<T>(array, array+N, arena), N); } template<typename T> MutableArrayRef<T> AllocateCopy(ArrayRef<T> array, AllocationArena arena = AllocationArena::Permanent) const { return MutableArrayRef<T>(AllocateCopy<T>(array.begin(),array.end(), arena), array.size()); } template<typename T> ArrayRef<T> AllocateCopy(const SmallVectorImpl<T> &vec, AllocationArena arena = AllocationArena::Permanent) const { return AllocateCopy(ArrayRef<T>(vec), arena); } template<typename T> MutableArrayRef<T> AllocateCopy(SmallVectorImpl<T> &vec, AllocationArena arena = AllocationArena::Permanent) const { return AllocateCopy(MutableArrayRef<T>(vec), arena); } StringRef AllocateCopy(StringRef Str, AllocationArena arena = AllocationArena::Permanent) const { ArrayRef<char> Result = AllocateCopy(llvm::makeArrayRef(Str.data(), Str.size()), arena); return StringRef(Result.data(), Result.size()); } template<typename T, typename Vector, typename Set> MutableArrayRef<T> AllocateCopy(llvm::SetVector<T, Vector, Set> setVector, AllocationArena arena = AllocationArena::Permanent) const { return MutableArrayRef<T>(AllocateCopy<T>(setVector.begin(), setVector.end(), arena), setVector.size()); } /// Retrieve the lazy resolver for this context. LazyResolver *getLazyResolver() const; /// Set the lazy resolver for this context. void setLazyResolver(LazyResolver *resolver); /// getIdentifier - Return the uniqued and AST-Context-owned version of the /// specified string. Identifier getIdentifier(StringRef Str) const; /// Decide how to interpret two precedence groups. Associativity associateInfixOperators(PrecedenceGroupDecl *left, PrecedenceGroupDecl *right) const; /// Retrieve the declaration of Swift.Error. ProtocolDecl *getErrorDecl() const; CanType getExceptionType() const; #define KNOWN_STDLIB_TYPE_DECL(NAME, DECL_CLASS, NUM_GENERIC_PARAMS) \ /** Retrieve the declaration of Swift.NAME. */ \ DECL_CLASS *get##NAME##Decl() const; #include "swift/AST/KnownStdlibTypes.def" /// Retrieve the declaration of Swift.Optional or ImplicitlyUnwrappedOptional. EnumDecl *getOptionalDecl(OptionalTypeKind kind) const; /// Retrieve the declaration of Swift.Optional<T>.Some. EnumElementDecl *getOptionalSomeDecl() const; /// Retrieve the declaration of Swift.Optional<T>.None. EnumElementDecl *getOptionalNoneDecl() const; /// Retrieve the declaration of Swift.ImplicitlyUnwrappedOptional<T>.Some. EnumElementDecl *getImplicitlyUnwrappedOptionalSomeDecl() const; /// Retrieve the declaration of Swift.ImplicitlyUnwrappedOptional<T>.None. EnumElementDecl *getImplicitlyUnwrappedOptionalNoneDecl() const; EnumElementDecl *getOptionalSomeDecl(OptionalTypeKind kind) const; EnumElementDecl *getOptionalNoneDecl(OptionalTypeKind kind) const; /// Retrieve the declaration of the "pointee" property of a pointer type. VarDecl *getPointerPointeePropertyDecl(PointerTypeKind ptrKind) const; /// Retrieve the type Swift.AnyObject. CanType getAnyObjectType() const; /// Retrieve the type Swift.Never. CanType getNeverType() const; /// Retrieve the declaration of Swift.Void. TypeAliasDecl *getVoidDecl() const; /// Retrieve the declaration of ObjectiveC.ObjCBool. StructDecl *getObjCBoolDecl() const; /// Retrieve the declaration of Foundation.NSError. ClassDecl *getNSErrorDecl() const; /// Retrieve the declaration of Foundation.NSNumber. ClassDecl *getNSNumberDecl() const; /// Retrieve the declaration of Foundation.NSValue. ClassDecl *getNSValueDecl() const; // Declare accessors for the known declarations. #define FUNC_DECL(Name, Id) \ FuncDecl *get##Name(LazyResolver *resolver) const; #include "swift/AST/KnownDecls.def" /// Get the '+' function on two RangeReplaceableCollection. FuncDecl *getPlusFunctionOnRangeReplaceableCollection() const; /// Get the '+' function on two String. FuncDecl *getPlusFunctionOnString() const; /// Check whether the standard library provides all the correct /// intrinsic support for Optional<T>. /// /// If this is true, the four methods above all promise to return /// non-null. bool hasOptionalIntrinsics(LazyResolver *resolver) const; /// Check whether the standard library provides all the correct /// intrinsic support for UnsafeMutablePointer<T> function arguments. /// /// If this is true, the methods getConvert*ToPointerArgument /// all promise to return non-null. bool hasPointerArgumentIntrinsics(LazyResolver *resolver) const; /// Check whether the standard library provides all the correct /// intrinsic support for array literals. /// /// If this is true, the method getAllocateUninitializedArray /// promises to return non-null. bool hasArrayLiteralIntrinsics(LazyResolver *resolver) const; /// Retrieve the declaration of Swift._getBool. FuncDecl *getGetBoolDecl(LazyResolver *resolver) const; /// Retrieve the declaration of Swift.==(Int, Int) -> Bool. FuncDecl *getEqualIntDecl() const; /// Retrieve the declaration of Array.append(element:) FuncDecl *getArrayAppendElementDecl() const; /// Retrieve the declaration of /// Array.reserveCapacityForAppend(newElementsCount: Int) FuncDecl *getArrayReserveCapacityDecl() const; /// Retrieve the declaration of Swift._unimplementedInitializer. FuncDecl *getUnimplementedInitializerDecl(LazyResolver *resolver) const; /// Retrieve the declaration of Swift._undefined. FuncDecl *getUndefinedDecl(LazyResolver *resolver) const; // Retrieve the declaration of Swift._stdlib_isOSVersionAtLeast. FuncDecl *getIsOSVersionAtLeastDecl(LazyResolver *resolver) const; /// Look for the declaration with the given name within the /// Swift module. void lookupInSwiftModule(StringRef name, SmallVectorImpl<ValueDecl *> &results) const; /// Retrieve a specific, known protocol. ProtocolDecl *getProtocol(KnownProtocolKind kind) const; /// Determine whether the given nominal type is one of the standard /// library or Cocoa framework types that is known to be bridged by another /// module's overlay, for layering or implementation detail reasons. bool isTypeBridgedInExternalModule(NominalTypeDecl *nominal) const; /// True if the given type is an Objective-C class that serves as the bridged /// object type for many Swift value types, meaning that the conversion from /// an object to a value is a conditional cast. bool isObjCClassWithMultipleSwiftBridgedTypes(Type t); /// Get the Objective-C type that a Swift type bridges to, if any. /// /// \param dc The context in which bridging is occurring. /// \param type The Swift for which we are querying bridging behavior. /// \param bridgedValueType The specific value type that is bridged, /// which will usually by the same as \c type. Type getBridgedToObjC(const DeclContext *dc, Type type, Type *bridgedValueType = nullptr) const; /// Determine whether the given Swift type is representable in a /// given foreign language. ForeignRepresentationInfo getForeignRepresentationInfo(NominalTypeDecl *nominal, ForeignLanguage language, const DeclContext *dc); /// Add a declaration to a list of declarations that need to be emitted /// as part of the current module or source file, but are otherwise not /// nested within it. void addExternalDecl(Decl *decl); /// Add a cleanup function to be called when the ASTContext is deallocated. void addCleanup(std::function<void(void)> cleanup); /// Add a cleanup to run the given object's destructor when the ASTContext is /// deallocated. template<typename T> void addDestructorCleanup(T &object) { addCleanup([&object]{ object.~T(); }); } //===--------------------------------------------------------------------===// // Diagnostics Helper functions //===--------------------------------------------------------------------===// bool hadError() const; //===--------------------------------------------------------------------===// // Type manipulation routines. //===--------------------------------------------------------------------===// // Builtin type and simple types that are used frequently. const CanType TheErrorType; /// This is the ErrorType singleton. const CanType TheUnresolvedType; /// This is the UnresolvedType singleton. const CanType TheEmptyTupleType; /// This is '()', aka Void const CanType TheAnyType; /// This is 'Any', the empty protocol composition const CanType TheNativeObjectType; /// Builtin.NativeObject const CanType TheBridgeObjectType; /// Builtin.BridgeObject const CanType TheUnknownObjectType; /// Builtin.UnknownObject const CanType TheRawPointerType; /// Builtin.RawPointer const CanType TheUnsafeValueBufferType; /// Builtin.UnsafeValueBuffer const CanType TheIEEE32Type; /// 32-bit IEEE floating point const CanType TheIEEE64Type; /// 64-bit IEEE floating point // Target specific types. const CanType TheIEEE16Type; /// 16-bit IEEE floating point const CanType TheIEEE80Type; /// 80-bit IEEE floating point const CanType TheIEEE128Type; /// 128-bit IEEE floating point const CanType ThePPC128Type; /// 128-bit PowerPC 2xDouble /// Adds a search path to SearchPathOpts, unless it is already present. /// /// Does any proper bookkeeping to keep all module loaders up to date as well. void addSearchPath(StringRef searchPath, bool isFramework, bool isSystem); /// \brief Adds a module loader to this AST context. /// /// \param loader The new module loader, which will be added after any /// existing module loaders. /// \param isClang \c true if this module loader is responsible for loading /// Clang modules, which are special-cased in some parts of the /// compiler. void addModuleLoader(std::unique_ptr<ModuleLoader> loader, bool isClang = false); /// \brief Load extensions to the given nominal type from the external /// module loaders. /// /// \param nominal The nominal type whose extensions should be loaded. /// /// \param previousGeneration The previous generation number. The AST already /// contains extensions loaded from any generation up to and including this /// one. void loadExtensions(NominalTypeDecl *nominal, unsigned previousGeneration); /// \brief Load the methods within the given class that produce /// Objective-C class or instance methods with the given selector. /// /// \param classDecl The class in which we are searching for @objc methods. /// The search only considers this class and its extensions; not any /// superclasses. /// /// \param selector The selector to search for. /// /// \param isInstanceMethod Whether we are looking for an instance method /// (vs. a class method). /// /// \param previousGeneration The previous generation with which this /// callback was invoked. The list of methods will already contain all of /// the results from generations up and including \c previousGeneration. /// /// \param methods The list of @objc methods in this class that have this /// selector and are instance/class methods as requested. This list will be /// extended with any methods found in subsequent generations. void loadObjCMethods(ClassDecl *classDecl, ObjCSelector selector, bool isInstanceMethod, unsigned previousGeneration, llvm::TinyPtrVector<AbstractFunctionDecl *> &methods); /// \brief Retrieve the Clang module loader for this ASTContext. /// /// If there is no Clang module loader, returns a null pointer. /// The loader is owned by the AST context. ClangModuleLoader *getClangModuleLoader() const; /// Asks every module loader to verify the ASTs it has loaded. /// /// Does nothing in non-asserts (NDEBUG) builds. void verifyAllLoadedModules() const; /// \brief Check whether the module with a given name can be imported without /// importing it. /// /// Note that even if this check succeeds, errors may still occur if the /// module is loaded in full. bool canImportModule(std::pair<Identifier, SourceLoc> ModulePath); /// \returns a module with a given name that was already loaded. If the /// module was not loaded, returns nullptr. ModuleDecl *getLoadedModule( ArrayRef<std::pair<Identifier, SourceLoc>> ModulePath) const; ModuleDecl *getLoadedModule(Identifier ModuleName) const; /// \brief Attempts to load a module into this ASTContext. /// /// If a module by this name has already been loaded, the existing module will /// be returned. /// /// \returns The requested module, or NULL if the module cannot be found. ModuleDecl *getModule(ArrayRef<std::pair<Identifier, SourceLoc>> ModulePath); ModuleDecl *getModuleByName(StringRef ModuleName); /// Returns the standard library module, or null if the library isn't present. /// /// If \p loadIfAbsent is true, the ASTContext will attempt to load the module /// if it hasn't been set yet. ModuleDecl *getStdlibModule(bool loadIfAbsent = false); ModuleDecl *getStdlibModule() const { return const_cast<ASTContext *>(this)->getStdlibModule(false); } /// \brief Retrieve the current generation number, which reflects the /// number of times a module import has caused mass invalidation of /// lookup tables. /// /// Various places in the AST keep track of the generation numbers at which /// their own information is valid, such as the list of extensions associated /// with a nominal type. unsigned getCurrentGeneration() const { return CurrentGeneration; } /// \brief Increase the generation number, implying that various lookup /// tables have been significantly altered by the introduction of a new /// module import. /// /// \returns the previous generation number. unsigned bumpGeneration() { return CurrentGeneration++; } /// \brief Produce a "normal" conformance for a nominal type. NormalProtocolConformance * getConformance(Type conformingType, ProtocolDecl *protocol, SourceLoc loc, DeclContext *dc, ProtocolConformanceState state); /// Produce a new normal conformance for a property behavior. NormalProtocolConformance * getBehaviorConformance(Type conformingType, ProtocolDecl *protocol, SourceLoc loc, AbstractStorageDecl *storage, ProtocolConformanceState state); /// A callback used to produce a diagnostic for an ill-formed protocol /// conformance that was type-checked before we're actually walking the /// conformance itself, along with a bit indicating whether this diagnostic /// produces an error. struct DelayedConformanceDiag { ValueDecl *Requirement; std::function<void()> Callback; bool IsError; }; /// Add a delayed diagnostic produced while type-checking a /// particular protocol conformance. void addDelayedConformanceDiag(NormalProtocolConformance *conformance, DelayedConformanceDiag fn); /// Retrieve the delayed-conformance diagnostic callbacks for the /// given normal protocol conformance. std::vector<DelayedConformanceDiag> takeDelayedConformanceDiags(NormalProtocolConformance *conformance); /// Add delayed missing witnesses for the given normal protocol conformance. void addDelayedMissingWitnesses(NormalProtocolConformance *conformance, ArrayRef<ValueDecl*> witnesses); /// Retrieve the delayed missing witnesses for the given normal protocol /// conformance. std::vector<ValueDecl*> takeDelayedMissingWitnesses(NormalProtocolConformance *conformance); /// \brief Produce a specialized conformance, which takes a generic /// conformance and substitutions written in terms of the generic /// conformance's signature. /// /// \param type The type for which we are retrieving the conformance. /// /// \param generic The generic conformance. /// /// \param substitutions The set of substitutions required to produce the /// specialized conformance from the generic conformance. This list is /// copied so passing a temporary is permitted. SpecializedProtocolConformance * getSpecializedConformance(Type type, ProtocolConformance *generic, SubstitutionList substitutions); /// \brief Produce a specialized conformance, which takes a generic /// conformance and substitutions written in terms of the generic /// conformance's signature. /// /// \param type The type for which we are retrieving the conformance. /// /// \param generic The generic conformance. /// /// \param substitutions The set of substitutions required to produce the /// specialized conformance from the generic conformance. The keys must /// be generic parameters, not archetypes, so for example passing in /// TypeBase::getContextSubstitutionMap() is OK. SpecializedProtocolConformance * getSpecializedConformance(Type type, ProtocolConformance *generic, const SubstitutionMap &substitutions); /// \brief Produce an inherited conformance, for subclasses of a type /// that already conforms to a protocol. /// /// \param type The type for which we are retrieving the conformance. /// /// \param inherited The inherited conformance. InheritedProtocolConformance * getInheritedConformance(Type type, ProtocolConformance *inherited); /// Record compiler-known protocol information in the AST. void recordKnownProtocols(ModuleDecl *Stdlib); /// Get the lazy data for the given declaration. /// /// \param lazyLoader If non-null, the lazy loader to use when creating the /// lazy data. The pointer must either be null or be consistent /// across all calls for the same \p func. LazyContextData *getOrCreateLazyContextData(const DeclContext *decl, LazyMemberLoader *lazyLoader); /// Get the lazy function data for the given generic context. /// /// \param lazyLoader If non-null, the lazy loader to use when creating the /// function data. The pointer must either be null or be consistent /// across all calls for the same \p func. LazyGenericContextData *getOrCreateLazyGenericContextData( const GenericContext *dc, LazyMemberLoader *lazyLoader); /// Get the lazy iterable context for the given iterable declaration context. /// /// \param lazyLoader If non-null, the lazy loader to use when creating the /// iterable context data. The pointer must either be null or be consistent /// across all calls for the same \p idc. LazyIterableDeclContextData *getOrCreateLazyIterableContextData( const IterableDeclContext *idc, LazyMemberLoader *lazyLoader); /// \brief Returns memory usage of this ASTContext. size_t getTotalMemory() const; /// \brief Returns memory used exclusively by constraint solver. size_t getSolverMemory() const; /// Complain if @objc or dynamic is used without importing Foundation. void diagnoseAttrsRequiringFoundation(SourceFile &SF); /// Note that the given method produces an Objective-C method. void recordObjCMethod(AbstractFunctionDecl *method); /// Diagnose any Objective-C method overrides that aren't reflected /// as overrides in Swift. bool diagnoseUnintendedObjCMethodOverrides(SourceFile &sf); /// Note that there is a conflict between different definitions that /// produce the same Objective-C method. void recordObjCMethodConflict(ClassDecl *classDecl, ObjCSelector selector, bool isInstance); /// Diagnose all conflicts between members that have the same /// Objective-C selector in the same class. /// /// \param sf The source file for which we are diagnosing conflicts. /// /// \returns true if there were any conflicts diagnosed. bool diagnoseObjCMethodConflicts(SourceFile &sf); /// Note that an optional @objc requirement has gone unsatisfied by /// a conformance to its protocol. /// /// \param dc The declaration context in which the conformance occurs. /// \param req The optional requirement. void recordObjCUnsatisfiedOptReq(DeclContext *dc, AbstractFunctionDecl *req); /// Diagnose any unsatisfied @objc optional requirements of /// protocols that conflict with methods. bool diagnoseObjCUnsatisfiedOptReqConflicts(SourceFile &sf); /// Retrieve the Swift name for the given Foundation entity, where /// "NS" prefix stripping will apply under omit-needless-words. StringRef getSwiftName(KnownFoundationEntity kind); /// Retrieve the Swift identifier for the given Foundation entity, where /// "NS" prefix stripping will apply under omit-needless-words. Identifier getSwiftId(KnownFoundationEntity kind) { return getIdentifier(getSwiftName(kind)); } /// Collect visible clang modules from the ClangModuleLoader. These modules are /// not necessarily loaded. void getVisibleTopLevelClangModules(SmallVectorImpl<clang::Module*> &Modules) const; private: /// Register the given generic signature builder to be used as the canonical /// generic signature builder for the given signature, if we don't already /// have one. void registerGenericSignatureBuilder(GenericSignature *sig, ModuleDecl &module, GenericSignatureBuilder &&builder); friend class GenericSignatureBuilder; public: /// Retrieve or create the stored generic signature builder for the given /// canonical generic signature and module. GenericSignatureBuilder *getOrCreateGenericSignatureBuilder(CanGenericSignature sig, ModuleDecl *mod); /// Retrieve or create the canonical generic environment of a canonical /// generic signature builder. GenericEnvironment *getOrCreateCanonicalGenericEnvironment( GenericSignatureBuilder *builder, GenericSignature *sig, ModuleDecl &module); /// Retrieve the inherited name set for the given class. const InheritedNameSet *getAllPropertyNames(ClassDecl *classDecl, bool forInstance); /// Retrieve the inherited name set for the given Objective-C class. const InheritedNameSet *getAllPropertyNames( clang::ObjCInterfaceDecl *classDecl, bool forInstance); /// Retrieve a generic signature with a single unconstrained type parameter, /// like `<T>`. CanGenericSignature getSingleGenericParameterSignature() const; /// Retrieve a generic signature with a single type parameter conforming /// to the given existential type. CanGenericSignature getExistentialSignature(CanType existential, ModuleDecl *mod); /// Whether our effective Swift version is in the Swift 3 family. bool isSwiftVersion3() const { return LangOpts.isSwiftVersion3(); } /// Whether our effective Swift version is at least 'major'. /// /// This is usually the check you want; for example, when introducing /// a new language feature which is only visible in Swift 5, you would /// check for isSwiftVersionAtLeast(5). bool isSwiftVersionAtLeast(unsigned major) const { return LangOpts.isSwiftVersionAtLeast(major); } private: friend Decl; Optional<RawComment> getRawComment(const Decl *D); void setRawComment(const Decl *D, RawComment RC); Optional<StringRef> getBriefComment(const Decl *D); void setBriefComment(const Decl *D, StringRef Comment); friend TypeBase; friend ArchetypeType; /// Provide context-level uniquing for SIL lowered type layouts and boxes. friend SILLayout; friend SILBoxType; }; /// Retrieve information about the given Objective-C method for /// diagnostic purposes, to be used with OBJC_DIAG_SELECT in /// DiagnosticsSema.def. std::pair<unsigned, DeclName> getObjCMethodDiagInfo( AbstractFunctionDecl *method); /// Attach Fix-Its to the given diagnostic that updates the name of the /// given declaration to the desired target name. /// /// \returns false if the name could not be fixed. bool fixDeclarationName(InFlightDiagnostic &diag, ValueDecl *decl, DeclName targetName); /// Fix the Objective-C name of the given declaration to match the provided /// Objective-C selector. /// /// \param ignoreImpliedName When true, ignore the implied name of the /// given declaration, because it no longer applies. /// /// For properties, the selector should be a zero-parameter selector of the /// given property's name. bool fixDeclarationObjCName(InFlightDiagnostic &diag, ValueDecl *decl, Optional<ObjCSelector> targetNameOpt, bool ignoreImpliedName = false); } // end namespace swift #endif
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var crypto = _interopDefault(require('crypto')); var max = 10000000000000; // biggest 10^n integer that can still fit 2^53 when multiplied by 256 var Int10 = /** @class */ (function () { function Int10(value) { this.buf = [+value || 0]; } Int10.prototype.mulAdd = function (m, c) { // assert(m <= 256) var b = this.buf, l = b.length, i, t; for (i = 0; i < l; ++i) { t = b[i] * m + c; if (t < max) c = 0; else { c = 0 | (t / max); t -= c * max; } b[i] = t; } if (c > 0) b[i] = c; }; Int10.prototype.sub = function (c) { // assert(m <= 256) var b = this.buf, l = b.length, i, t; for (i = 0; i < l; ++i) { t = b[i] - c; if (t < 0) { t += max; c = 1; } else c = 0; b[i] = t; } while (b[b.length - 1] === 0) b.pop(); }; Int10.prototype.toString = function (base) { if ((base || 10) != 10) throw 'only base 10 is supported'; var b = this.buf, s = b[b.length - 1].toString(); for (var i = b.length - 2; i >= 0; --i) s += (max + b[i]).toString().substring(1); return s; }; Int10.prototype.valueOf = function () { var b = this.buf, v = 0; for (var i = b.length - 1; i >= 0; --i) v = v * max + b[i]; return v; }; Int10.prototype.simplify = function () { var b = this.buf; return (b.length == 1) ? b[0] : this; }; return Int10; }()); var UNSUPPORTED_ALGORITHM = 'Unsupported algorithm name specified! Supported algorithms: "HS256", "HS384", "HS512", "RS256", "RS384", "RS512" and "none".'; var ILLEGAL_ARGUMENT = 'Illegal argument specified!'; function num2hex(memo, i) { return memo + ('0' + i.toString(16)).slice(-2); } // clean leading zeros function cleanZeros(b) { return b[0] === 0 ? cleanZeros(b.slice(1)) : b; } function hex2AB(hex) { if (!hex) throw new Error(ILLEGAL_ARGUMENT); var match = hex.match(/[0-9A-F]{2}/ig); if (!match) throw new Error(ILLEGAL_ARGUMENT); return new Uint8Array(match.map(function (i) { return parseInt(i, 16); })); } function AB2hex(buff) { if (buff instanceof ArrayBuffer) buff = new Uint8Array(buff); return buff.reduce(num2hex, ''); } /** * Try running function and replace it's response as Promise.resolve/reject * * @param {function} fn - fn to call in for response * * @returns {Promise<any>} resulting Promise */ function tryPromise(fn) { try { return Promise.resolve(fn()); } catch (e) { return Promise.reject(e); } } /** * Converts string to ArrayBuffer * * @param {string} str - data string to convert * * @returns {ArrayBuffer | Uint8Array} charCode ArrayBuffer */ function s2AB(str) { var buff = new Uint8Array(str.length); for (var i = 0; i < str.length; i++) buff[i] = str.charCodeAt(i); return buff; } /** * Converts ArrayBuffer to string * * @param {ArrayBuffer | Uint8Array} buff - charCode ArrayBuffer to convert * * @returns {string} data string */ function AB2s(buff) { if (buff instanceof ArrayBuffer) buff = new Uint8Array(buff); return String.fromCharCode.apply(String, buff); } /** * Converts string to base64 string * * @param {string} str - data string to convert * * @returns {string} decoded data string */ function b2s(str) { try { if (typeof window === 'object' && typeof window.atob === 'function') { return window.atob(str); } else if (typeof Buffer !== 'undefined') { return Buffer.from(str, 'base64').toString('binary'); } else throw new Error(ILLEGAL_ARGUMENT); } catch (e) { throw new Error(e); } } /** * Converts base64 string to base64url string * * @param {string} str - data string to convert * * @returns {string} base64url string */ function b2bu(str) { if ((typeof str !== 'string') || (str.length % 4 !== 0)) { throw new Error(ILLEGAL_ARGUMENT); } return str .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); } /** * * Converts base64url string to base64 string * * @param {string} str - data string to convert * * @returns {string} base64 string */ function bu2b(str) { if ((typeof str !== 'string') || (str.length % 4 === 1)) { throw new Error(ILLEGAL_ARGUMENT); } for (; (str.length % 4 !== 0);) { str += '='; } return str .replace(/\-/g, '+') .replace(/_/g, '/'); } /** * Converts base64url string to string * * @param {string} str - base64url string to convert * * @returns {string} decoded data string */ function bu2s(str) { return b2s(bu2b(str)); } /** * Converts base64 string to string * * @param {string} str - data string to convert * * @returns {string} base64 string */ function s2b(str) { try { if (typeof window === 'object' && typeof window.atob === 'function') { return window.btoa(str); } else if (typeof Buffer !== 'undefined') { return Buffer.from(str).toString('base64'); } else throw new Error(ILLEGAL_ARGUMENT); } catch (e) { throw new Error(e); } } /** * Converts string to base64url string * * @param {string} str - data string to convert * * @returns {string} base64url string */ function s2bu(str) { return b2bu(s2b(str)); } var ellipsis = "\u2026", reTimeS = /^(\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/, reTimeL = /^(\d\d\d\d)(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])([01]\d|2[0-3])(?:([0-5]\d)(?:([0-5]\d)(?:[.,](\d{1,3}))?)?)?(Z|[-+](?:[0]\d|1[0-2])([0-5]\d)?)?$/; function stringCut(str, len) { if (str.length > len) str = str.substring(0, len) + ellipsis; return str; } var Stream = /** @class */ (function () { function Stream(enc, pos) { if (pos === void 0) { pos = 0; } this.hexDigits = "0123456789ABCDEF"; if (enc instanceof Stream) { this.enc = enc.enc; this.pos = enc.pos; } else { this.enc = enc; this.pos = pos; } } Stream.prototype.get = function (pos) { if (pos === undefined) pos = this.pos++; if (pos >= this.enc.length) throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length; return (typeof this.enc == "string") ? this.enc.charCodeAt(pos) : this.enc[pos]; }; Stream.prototype.hexByte = function (b) { return this.hexDigits.charAt((b >> 4) & 0xF) + this.hexDigits.charAt(b & 0xF); }; Stream.prototype.hexDump = function (start, end, raw) { var s = ""; for (var i = start; i < end; ++i) { s += this.hexByte(this.get(i)); if (raw !== true) switch (i & 0xF) { case 0x7: s += " "; break; case 0xF: s += "\n"; break; default: s += " "; } } return s; }; Stream.prototype.isASCII = function (start, end) { for (var i = start; i < end; ++i) { var c = this.get(i); if (c < 32 || c > 176) return false; } return true; }; Stream.prototype.parseStringISO = function (start, end) { var s = ""; for (var i = start; i < end; ++i) s += String.fromCharCode(this.get(i)); return s; }; Stream.prototype.parseStringUTF = function (start, end) { var s = ""; for (var i = start; i < end;) { var c = this.get(i++); if (c < 128) s += String.fromCharCode(c); else if ((c > 191) && (c < 224)) s += String.fromCharCode(((c & 0x1F) << 6) | (this.get(i++) & 0x3F)); else s += String.fromCharCode(((c & 0x0F) << 12) | ((this.get(i++) & 0x3F) << 6) | (this.get(i++) & 0x3F)); } return s; }; Stream.prototype.parseStringBMP = function (start, end) { var str = "", hi, lo; for (var i = start; i < end;) { hi = this.get(i++); lo = this.get(i++); str += String.fromCharCode((hi << 8) | lo); } return str; }; Stream.prototype.parseTime = function (start, end, shortYear) { var s = this.parseStringISO(start, end), m = (shortYear ? reTimeS : reTimeL).exec(s); if (!m) return "Unrecognized time: " + s; if (shortYear) { var t = +m[1], y = (t < 70) ? 2000 : 1900; m[1] = y + ""; } s = m[1] + "-" + m[2] + "-" + m[3] + " " + m[4]; if (m[5]) { s += ":" + m[5]; if (m[6]) { s += ":" + m[6]; if (m[7]) s += "." + m[7]; } } if (m[8]) { s += " UTC"; if (m[8] != 'Z') { s += m[8]; if (m[9]) s += ":" + m[9]; } } return s; }; Stream.prototype.parseInteger = function (start, end) { var v = this.get(start), neg = (v > 127), pad = neg ? 255 : 0, len, s = ''; while (v == pad && ++start < end) v = this.get(start); len = end - start; if (len === 0) return neg ? -1 : 0; if (len > 4) { var t = +v; len <<= 3; while (((t ^ pad) & 0x80) === 0) { t <<= 1; --len; } s = "(" + len + " bit)\n"; } if (neg) v = v - 256; var n = new Int10(v); for (var i = start + 1; i < end; ++i) n.mulAdd(256, this.get(i)); return s + n.toString(); }; Stream.prototype.parseBitString = function (start, end, maxLength) { var unusedBit = this.get(start), lenBit = ((end - start - 1) << 3) - unusedBit, intro = "(" + lenBit + " bit)\n", s = ""; for (var i = start + 1; i < end; ++i) { var b = this.get(i), skip = (i == end - 1) ? unusedBit : 0; for (var j = 7; j >= skip; --j) s += (b >> j) & 1 ? "1" : "0"; if (s.length > maxLength) return intro + stringCut(s, maxLength); } return intro + s; }; Stream.prototype.parseOctetString = function (start, end, maxLength) { if (this.isASCII(start, end)) return stringCut(this.parseStringISO(start, end), maxLength); var len = end - start, s = "(" + len + " byte)\n"; maxLength /= 2; if (len > maxLength) end = start + maxLength; for (var i = start; i < end; ++i) s += this.hexByte(this.get(i)); if (len > maxLength) s += ellipsis; return s; }; Stream.prototype.parseOID = function (start, end, maxLength) { var s = '', n = new Int10(), bits = 0; for (var i = start; i < end; ++i) { var v = this.get(i); n.mulAdd(128, v & 0x7F); bits += 7; if (!(v & 0x80)) { if (s === '') { n = n.simplify(); if (n instanceof Int10) { n.sub(80); s = "2." + n.toString(); } else { var m = n < 80 ? n < 40 ? 0 : 1 : 2; s = m + "." + (n - m * 40); } } else s += "." + n.toString(); if (s.length > maxLength) return stringCut(s, maxLength); n = new Int10(); bits = 0; } } if (bits > 0) s += ".incomplete"; return s; }; return Stream; }()); var ASN1 = /** @class */ (function () { function ASN1(stream, header, length, tag, sub) { if (!(tag instanceof ASN1Tag)) throw 'Invalid tag value.'; this.stream = stream; this.header = header; this.length = length; this.tag = tag; this.sub = sub; } ASN1.decodeLength = function (stream) { var buf = stream.get(); var len = buf & 0x7F; if (len == buf) return len; if (len > 6) throw "Length over 48 bits not supported at position " + (stream.pos - 1); if (len === 0) return null; buf = 0; for (var i = 0; i < len; ++i) buf = (buf * 256) + stream.get(); return buf; }; ASN1.decode = function (stream) { if (!(stream instanceof Stream)) stream = new Stream(stream, 0); var streamStart = new Stream(stream); var tag = new ASN1Tag(stream); var len = ASN1.decodeLength(stream), sub = null; var start = stream.pos; var header = start - streamStart.pos; var getSub = function () { sub = []; if (len !== null) { var end = start + len; while (stream.pos < end) sub[sub.length] = ASN1.decode(stream); if (stream.pos != end) throw "Content size is not correct for container starting at offset " + start; } else { try { for (;;) { var s = ASN1.decode(stream); if (s.tag.isEOC()) break; sub[sub.length] = s; } len = start - stream.pos; } catch (e) { throw "Exception while decoding undefined length content: " + e; } } }; if (tag.tagConstructed) { getSub(); } else if (tag.isUniversal() && ((tag.tagNumber == 0x03) || (tag.tagNumber == 0x04))) { try { if (tag.tagNumber == 0x03) if (stream.get() != 0) throw "BIT STRINGs with unused bits cannot encapsulate."; getSub(); for (var i = 0; i < sub.length; ++i) if (sub[i].tag.isEOC()) throw 'EOC is not supposed to be actual content.'; } catch (e) { sub = null; } } if (sub === null) { if (len === null) throw "We can't skip over an invalid tag with undefined length at offset " + start; stream.pos = start + Math.abs(len); } return new ASN1(streamStart, header, len, tag, sub); }; ASN1.prototype.typeName = function () { switch (this.tag.tagClass) { case 0: switch (this.tag.tagNumber) { case 0x00: return "EOC"; case 0x01: return "BOOLEAN"; case 0x02: return "INTEGER"; case 0x03: return "BIT_STRING"; case 0x04: return "OCTET_STRING"; case 0x05: return "NULL"; case 0x06: return "OBJECT_IDENTIFIER"; case 0x07: return "ObjectDescriptor"; case 0x08: return "EXTERNAL"; case 0x09: return "REAL"; case 0x0A: return "ENUMERATED"; case 0x0B: return "EMBEDDED_PDV"; case 0x0C: return "UTF8String"; case 0x10: return "SEQUENCE"; case 0x11: return "SET"; case 0x12: return "NumericString"; case 0x13: return "PrintableString"; case 0x14: return "TeletexString"; case 0x15: return "VideotexString"; case 0x16: return "IA5String"; case 0x17: return "UTCTime"; case 0x18: return "GeneralizedTime"; case 0x19: return "GraphicString"; case 0x1A: return "VisibleString"; case 0x1B: return "GeneralString"; case 0x1C: return "UniversalString"; case 0x1E: return "BMPString"; } return "Universal_" + this.tag.tagNumber.toString(); case 1: return "Application_" + this.tag.tagNumber.toString(); case 2: return "[" + this.tag.tagNumber.toString() + "]"; case 3: return "Private_" + this.tag.tagNumber.toString(); } }; ASN1.prototype.content = function (maxLength) { if (this.tag === undefined) return null; if (maxLength === undefined) maxLength = Infinity; var content = this.posContent(), len = Math.abs(this.length); if (!this.tag.isUniversal()) { if (this.sub !== null) return "(" + this.sub.length + " elem)"; return this.stream.parseOctetString(content, content + len, maxLength); } switch (this.tag.tagNumber) { case 0x01: return (this.stream.get(content) === 0) ? "false" : "true"; case 0x02: return this.stream.parseInteger(content, content + len); case 0x03: return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseBitString(content, content + len, maxLength); case 0x04: return this.sub ? "(" + this.sub.length + " elem)" : this.stream.parseOctetString(content, content + len, maxLength); case 0x06: return this.stream.parseOID(content, content + len, maxLength); case 0x10: case 0x11: if (this.sub !== null) return "(" + this.sub.length + " elem)"; else return "(no elem)"; case 0x0C: return stringCut(this.stream.parseStringUTF(content, content + len), maxLength); case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x1A: return stringCut(this.stream.parseStringISO(content, content + len), maxLength); case 0x1E: return stringCut(this.stream.parseStringBMP(content, content + len), maxLength); case 0x17: case 0x18: return this.stream.parseTime(content, content + len, (this.tag.tagNumber == 0x17)); } return null; }; ASN1.prototype.toString = function () { return this.typeName() + "@" + this.stream.pos + "[header:" + this.header + ",length:" + this.length + ",sub:" + ((this.sub === null) ? 'null' : this.sub.length) + "]"; }; ASN1.prototype.posStart = function () { return this.stream.pos; }; ASN1.prototype.posContent = function () { return this.stream.pos + this.header; }; ASN1.prototype.posEnd = function () { return this.stream.pos + this.header + Math.abs(this.length); }; ASN1.prototype.toHexString = function (root) { return this.stream.hexDump(this.posStart(), this.posEnd(), true); }; ASN1.prototype.getHex = function () { return this.stream.hexDump(this.posContent(), this.posEnd(), true); }; ASN1.prototype.getAB = function (clean) { if (clean === void 0) { clean = true; } return clean ? cleanZeros(hex2AB(this.getHex())) : hex2AB(this.getHex()); }; return ASN1; }()); var ASN1Tag = /** @class */ (function () { function ASN1Tag(stream) { var buf = stream.get(); this.tagClass = buf >> 6; this.tagConstructed = ((buf & 0x20) !== 0); this.tagNumber = buf & 0x1F; if (this.tagNumber == 0x1F) { var n = new Int10(); do { buf = stream.get(); n.mulAdd(128, buf & 0x7F); } while (buf & 0x80); this.tagNumber = n.simplify(); } } ASN1Tag.prototype.isUniversal = function () { return this.tagClass === 0x00; }; ASN1Tag.prototype.isEOC = function () { return this.tagClass === 0x00 && this.tagNumber === 0x00; }; return ASN1Tag; }()); var PEM = /** @class */ (function () { function PEM(secret) { var _this = this; if (typeof secret !== 'string') { throw new Error(ILLEGAL_ARGUMENT); } this.type = 'public'; var ignore = function (line) { if (ignoreLinesPriv.some(function (ign) { return line.toUpperCase().indexOf(ign) > -1; })) { _this.type = 'private'; return false; } return !ignoreLinesPub.some(function (ign) { return line.toUpperCase().indexOf(ign) > -1; }); }; var lines = secret.split('\n'), ignoreLinesPriv = [ '-BEGIN PRIVATE KEY-', '-END PRIVATE KEY-', '-BEGIN EC PRIVATE KEY-', '-END EC PRIVATE KEY-', '-BEGIN RSA PRIVATE KEY-', '-END RSA PRIVATE KEY-' ], ignoreLinesPub = [ '-BEGIN RSA PUBLIC KEY-', '-BEGIN EC PUBLIC KEY-', '-BEGIN PUBLIC KEY-', '-END PUBLIC KEY-', '-END EC PUBLIC KEY-', '-END RSA PUBLIC KEY-' ], body = lines.map(function (line) { return line.trim(); }).filter(function (line) { return line.length && ignore(line); }).join(''); if (body.length) { this.body = s2AB(b2s(bu2b(body))); return this; } else { throw new Error(ILLEGAL_ARGUMENT); } } return PEM; }()); var ECCurves = [ { name: "p-256", curve: "1.2.840.10045.3.1.7", coordinateLength: 32 }, { name: "p-384", curve: "1.3.132.0.34", coordinateLength: 48 }, { name: "p-384", curve: "1.3.132.0.35", coordinateLength: 66 } ]; var EC = /** @class */ (function () { function EC() { } EC.ASN1fromPEM = function (body) { if (!body) throw new Error(ILLEGAL_ARGUMENT); if (body instanceof ArrayBuffer) body = new Uint8Array(body); var asn1 = ASN1.decode(body); var res = {}; if (asn1.sub.length === 3) { res['version'] = asn1.sub[0].content(); // int res['keyType'] = asn1.sub[1].sub[0].content(); // string res['namedCurve'] = asn1.sub[1].sub[1].content(); // string res['versionSub'] = asn1.sub[2].sub[0].sub[0].content(); // int res['privateKey'] = asn1.sub[2].sub[0].sub[2].getAB(); // ArrayBuffer res['curveTypeSub'] = asn1.sub[2].sub[0].sub[2].sub[0].content(); // string res['publicKey'] = asn1.sub[2].sub[0].sub[3].sub[0].getAB(); // ArrayBuffer } else if (asn1.sub.length === 2) { res['keyType'] = asn1.sub[0].sub[0].content(); // string res['namedCurve'] = asn1.sub[0].sub[1].content(); // string res['publicKey'] = asn1.sub[1].getAB(); // int } return asn1; }; EC.JWKfromASN1 = function (asn1, type, extra) { var pemTypes = ['public', 'private']; if (!asn1) throw new Error(ILLEGAL_ARGUMENT); type = ((typeof type === 'string') && type.toLowerCase()) || pemTypes[!!asn1.privateKey ? 1 : 0]; if (type === 'private' && !asn1.privateKey) { throw new Error(ILLEGAL_ARGUMENT); } var crv = ECCurves.find(function (c) { return c.curve === asn1.namedCurve; }); if (!crv) { throw new Error(ILLEGAL_ARGUMENT); } var publicKey = asn1.publicKey; if (publicKey.readInt8(0) !== 4) { throw new Error(ILLEGAL_ARGUMENT); } var jwk = Object.assign({ kty: 'EC', crv: crv.name }, extra, { x: s2bu(AB2s(publicKey.slice(1, crv.coordinateLength))), y: s2bu(AB2s(publicKey.slice(crv.coordinateLength + 1, 2 * (crv.coordinateLength + 1)))) }); if (type === 'private') { Object.assign(jwk, { d: s2bu(AB2s(asn1.privateKey)) }); } return jwk; }; EC.JWKfromEC = function (secret, type, extra) { return tryPromise(function () { var pem = new PEM(secret); return EC.JWKfromASN1(EC.ASN1fromPEM(pem.body), type, extra); }); }; return EC; }()); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var webCrypto = typeof window === "object" && (window.crypto || window['msCrypto']); var webCryptoSubtle = webCrypto && (webCrypto.subtle || webCrypto['webkitSubtle'] || webCrypto['Subtle']); var HMAC = /** @class */ (function () { function HMAC() { } HMAC.createSigner = function (name, secret) { return __awaiter(this, void 0, void 0, function () { var keyData; return __generator(this, function (_a) { if (webCryptoSubtle) { keyData = s2AB(secret); return [2 /*return*/, webCryptoSubtle.importKey('raw', keyData, { name: 'HMAC', hash: { name: name } }, true, ['sign']).then(function (key) { return { update: function (thing) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, webCryptoSubtle.sign('HMAC', key, s2AB(thing))]; }); }); } }; })]; } else { return [2 /*return*/, !!crypto && crypto.createHmac ? Promise.resolve(crypto.createHmac(name.replace('SHA-', 'sha'), secret)) : Promise.reject(webCrypto)]; } return [2 /*return*/]; }); }); }; HMAC.sign = function (bits) { return function sign(thing, secret) { return __awaiter(this, void 0, void 0, function () { var hmac, _a, _b, _c, _d, _e, _f; return __generator(this, function (_g) { switch (_g.label) { case 0: return [4 /*yield*/, HMAC.createSigner('SHA-' + bits, secret)]; case 1: hmac = _g.sent(); _b = (_a = Promise).resolve; if (!webCryptoSubtle) return [3 /*break*/, 4]; _d = s2bu; _e = AB2s; _f = hmac; if (!_f) return [3 /*break*/, 3]; return [4 /*yield*/, hmac.update(thing)]; case 2: _f = (_g.sent()); _g.label = 3; case 3: _c = _d.apply(void 0, [_e.apply(void 0, [_f])]); return [3 /*break*/, 5]; case 4: _c = b2bu(hmac && hmac.update(thing).digest('base64')); _g.label = 5; case 5: return [2 /*return*/, _b.apply(_a, [_c])]; } }); }); }; }; HMAC.verify = function (bits) { return function verify(thing, signature, secret) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, HMAC.sign(bits)(thing, secret)]; case 1: return [2 /*return*/, (_a.sent()) === signature]; } }); }); }; }; return HMAC; }()); var webCrypto$1 = typeof window === "object" && (window.crypto || window['msCrypto']); var webCryptoSubtle$1 = webCrypto$1 && (webCrypto$1.subtle || webCrypto$1['webkitSubtle'] || webCrypto$1['Subtle']); var RSA = /** @class */ (function () { function RSA() { } RSA.ASN1fromPEM = function (body) { if (!body) throw new Error(ILLEGAL_ARGUMENT); if (body instanceof ArrayBuffer) body = new Uint8Array(body); var asn1 = ASN1.decode(body), res = {}; if (asn1.sub.length === 3) { asn1 = asn1.sub[2].sub[0]; } if (asn1.sub.length === 9) { // Parse the private key. res['modulus'] = asn1.sub[1].getAB(); // ArrayBuffer res['publicExponent'] = parseInt(asn1.sub[2].getHex(), 16); // int res['privateExponent'] = asn1.sub[3].getAB(); // ArrayBuffer res['prime1'] = asn1.sub[4].getAB(); // ArrayBuffer res['prime2'] = asn1.sub[5].getAB(); // ArrayBuffer res['exponent1'] = asn1.sub[6].getAB(); // ArrayBuffer res['exponent2'] = asn1.sub[7].getAB(); // ArrayBuffer res['coefficient'] = asn1.sub[8].getAB(); // ArrayBuffer } else if (asn1.sub.length === 2) { // Parse the public key. asn1 = asn1.sub[1].sub[0]; res['modulus'] = asn1.sub[0].getAB(); // ArrayBuffer res['publicExponent'] = parseInt(asn1.sub[1].getHex(), 16); // int } res['bits'] = (res['modulus'].length - 1) * 8 + Math.ceil(Math.log(res['modulus'][0] + 1) / Math.log(2)); if (!res['bits']) { throw new Error(ILLEGAL_ARGUMENT); } return res; }; RSA.JWKfromASN1 = function (asn1, type, extra) { var pemTypes = ['public', 'private']; if (!asn1) throw new Error(ILLEGAL_ARGUMENT); type = ((typeof type === 'string') && type.toLowerCase()) || pemTypes[!!asn1.privateExponent ? 1 : 0]; if (type === 'private' && !asn1.privateExponent) { throw new Error(ILLEGAL_ARGUMENT); } var v = asn1.publicExponent; var expSize = Math.ceil(Math.log(v) / Math.log(256)); var exp = new Uint8Array(expSize).map(function (el) { el = v % 256; v = Math.floor(v / 256); return el; }).reverse(); var jwk = Object.assign({ kty: 'RSA' }, extra, { n: s2bu(AB2s(asn1.modulus)), e: s2bu(AB2s(exp)), }); if (type === 'private') { Object.assign(jwk, { d: s2bu(AB2s(asn1.privateExponent)), p: s2bu(AB2s(asn1.prime1)), q: s2bu(AB2s(asn1.prime2)), dp: s2bu(AB2s(asn1.exponent1)), dq: s2bu(AB2s(asn1.exponent2)), qi: s2bu(AB2s(asn1.coefficient)) }); } return jwk; }; RSA.JWKfromRSA = function (secret, type, extra) { return tryPromise(function () { var pem = new PEM(secret); return RSA.JWKfromASN1(RSA.ASN1fromPEM(pem.body), type, extra); }); }; RSA.createSigner = function (name) { if (webCryptoSubtle$1) { return { update: function (thing) { return { sign: function (secret, encoding) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, RSA.JWKfromRSA(secret, 'private', { key_ops: ['sign'], alg: name.replace('SHA-', 'RS') }).then(function (keyData) { return __awaiter(_this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, webCryptoSubtle$1.importKey('jwk', keyData, { name: 'RSASSA-PKCS1-v1_5', hash: { name: name } }, true, ['sign']).then(function (key) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, webCryptoSubtle$1.sign({ name: 'RSASSA-PKCS1-v1_5', hash: { name: name } }, key, s2AB(thing)).then(AB2s).then(s2b)]; }); }); })]; }); }); })]; }); }); } }; } }; } else { if (crypto && crypto.createSign) { return crypto.createSign(name.replace('SHA-', 'RSA-SHA')); } else { throw new Error(ILLEGAL_ARGUMENT); } } }; RSA.sign = function (bits) { return function sign(thing, privateKey) { return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) { return [2 /*return*/, tryPromise(function () { return RSA.createSigner('SHA-' + bits) .then(function (res) { return res .update(thing) .sign(privateKey, 'base64') .then(b2bu); }); })]; }); }); }; }; RSA.createVerifier = function (name) { if (webCryptoSubtle$1) { return { update: function (thing) { return { verify: function (secret, signature, encoding) { return __awaiter(this, void 0, void 0, function () { var _this = this; return __generator(this, function (_a) { return [2 /*return*/, RSA.JWKfromRSA(secret, 'public', { key_ops: ['verify'], alg: name.replace('SHA-', 'RS') }).then(function (_a) { var kty = _a.kty, n = _a.n, e = _a.e; return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_b) { return [2 /*return*/, webCryptoSubtle$1.importKey('jwk', { kty: kty, n: n, e: e }, { name: 'RSASSA-PKCS1-v1_5', hash: { name: name } }, false, ['verify']).then(function (key) { return webCryptoSubtle$1.verify('RSASSA-PKCS1-v1_5', key, s2AB(bu2s(signature)), s2AB(thing)); })]; }); }); })]; }); }); } }; } }; } else { if (crypto && crypto.createVerify) { return crypto.createVerify(name.replace('SHA-', 'RSA-SHA')); } else { throw new Error(ILLEGAL_ARGUMENT); } } }; RSA.verify = function (bits) { return function verify(thing, signature, publicKey) { return __awaiter(this, void 0, void 0, function () { var e_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); return [4 /*yield*/, RSA.createVerifier('SHA-' + bits) .then(function (res) { return res .update(thing) .verify(publicKey, bu2b(signature), 'base64'); })]; case 1: return [2 /*return*/, _a.sent()]; case 2: e_1 = _a.sent(); return [2 /*return*/, Promise.reject(new Error(e_1.message))]; case 3: return [2 /*return*/]; } }); }); }; }; return RSA; }()); var jwkJs = { ASN1: ASN1, EC: EC, PEM: PEM, RSA: RSA, HMAC: HMAC, ILLEGAL_ARGUMENT: ILLEGAL_ARGUMENT, UNSUPPORTED_ALGORITHM: UNSUPPORTED_ALGORITHM, tryPromise: tryPromise, AB2hex: AB2hex, AB2s: AB2s, b2bu: b2bu, b2s: b2s, bu2b: bu2b, bu2s: bu2s, cleanZeros: cleanZeros, hex2AB: hex2AB, num2hex: num2hex, s2AB: s2AB, s2b: s2b, s2bu: s2bu }; exports.default = jwkJs; exports.jwkJs = jwkJs; //# sourceMappingURL=jwk-js.cjs.js.map
import unittest import json from mock import patch from mock import Mock import sys from django.conf.urls import url from django.conf import settings from django.test import RequestFactory from django.test import SimpleTestCase from django.test import override_settings from django.test import modify_settings from django.test import Client from honeybadger import honeybadger from honeybadger.config import Configuration from honeybadger.contrib import DjangoHoneybadgerMiddleware from honeybadger.contrib.django import DjangoPlugin from honeybadger.contrib.django import clear_request from honeybadger.contrib.django import set_request from honeybadger.contrib.django import current_request from .django_test_app.views import plain_view from .django_test_app.views import always_fails from ..utils import mock_urlopen try: settings.configure() except: pass def versions_match(): import django VERSION_MATRIX = { '1.11': sys.version_info >= (3, 5), '2.2': sys.version_info >= (3, 5), '3.0': sys.version_info >= (3, 6), '3.1': sys.version_info >= (3, 6) } for django_version, supported in VERSION_MATRIX.items(): if django.__version__.startswith(django_version) and supported: return True return False class DjangoPluginTestCase(unittest.TestCase): def setUp(self): self.plugin = DjangoPlugin() self.rf = RequestFactory() self.config = Configuration() self.url = url(r'test', plain_view, name='test_view') self.default_payload = {'request':{}} def tearDown(self): clear_request() def test_supports_django_request(self): request = self.rf.get('test') set_request(request) self.assertTrue(self.plugin.supports(self.config, {})) def test_generate_payload_get(self): request = self.rf.get('test', {'a': 1}) request.resolver_match = self.url.resolve('test') set_request(request) payload = self.plugin.generate_payload(self.default_payload, self.config, {'foo': 'bar'}) self.assertEqual(payload['request']['url'], 'http://testserver/test?a=1') self.assertEqual(payload['request']['action'], 'plain_view') self.assertDictEqual(payload['request']['params'], {'a': ['1']}) self.assertDictEqual(payload['request']['session'], {}) self.assertDictEqual(payload['request']['context'], {'foo': 'bar'}) def test_generate_payload_post(self): request = self.rf.post('test', data={'a': 1, 'b': 2, 'password': 'notsafe'}) request.resolver_match = self.url.resolve('test') set_request(request) payload = self.plugin.generate_payload(self.default_payload, self.config, {'foo': 'bar'}) self.assertEqual(payload['request']['url'], 'http://testserver/test') self.assertEqual(payload['request']['action'], 'plain_view') self.assertDictEqual(payload['request']['params'], {'a': ['1'], 'b': ['2'], 'password': '[FILTERED]'}) self.assertDictEqual(payload['request']['session'], {}) self.assertDictEqual(payload['request']['context'], {'foo': 'bar'}) def test_generate_payload_with_session(self): request = self.rf.get('test') request.resolver_match = self.url.resolve('test') request.session = {'lang': 'en'} set_request(request) payload = self.plugin.generate_payload(self.default_payload, self.config, {'foo': 'bar'}) self.assertEqual(payload['request']['url'], 'http://testserver/test') self.assertEqual(payload['request']['action'], 'plain_view') self.assertDictEqual(payload['request']['session'], {'lang': 'en'}) self.assertDictEqual(payload['request']['context'], {'foo': 'bar'}) # TODO: add an integration test case that tests the actual integration with Django class DjangoMiddlewareTestCase(unittest.TestCase): def setUp(self): self.rf = RequestFactory() self.url = url(r'test', plain_view, name='test_view') def tearDown(self): clear_request() def get_response(self, request): return Mock() @patch('honeybadger.contrib.django.honeybadger') def test_process_exception(self, mock_hb): request = self.rf.get('test') request.resolver_match = self.url.resolve('test') exc = ValueError('test exception') middleware = DjangoHoneybadgerMiddleware(self.get_response) middleware.process_exception(request, exc) mock_hb.notify.assert_called_with(exc) self.assertIsNone(current_request(), msg='Current request should be cleared after exception handling') def test___call__(self): request = self.rf.get('test') request.resolver_match = self.url.resolve('test') middleware = DjangoHoneybadgerMiddleware(self.get_response) response = middleware(request) self.assertDictEqual({}, honeybadger._get_context(), msg='Context should be cleared after response handling') self.assertIsNone(current_request(), msg='Current request should be cleared after response handling') @override_settings( ROOT_URLCONF='honeybadger.tests.contrib.django_test_app.urls', MIDDLEWARE=['honeybadger.contrib.django.DjangoHoneybadgerMiddleware'] ) class DjangoMiddlewareIntegrationTestCase(SimpleTestCase): def setUp(self): self.client = Client() @unittest.skipUnless(versions_match(), "Current Python version unsupported by current version of Django") def test_context_cleared_after_response(self): self.assertIsNone(current_request(), msg='Current request should be empty prior to request') response = self.client.get('/plain_view') self.assertIsNone(current_request(), msg='Current request should be cleared after request processed') @unittest.skipUnless(versions_match(), "Current Python version unsupported by current version of Django") @override_settings( HONEYBADGER={ 'API_KEY': 'abc123' } ) def test_exceptions_handled_by_middleware(self): def assert_payload(req): error_payload = json.loads(str(req.data, "utf-8")) self.assertEqual(req.get_header('X-api-key'), 'abc123') self.assertEqual(req.get_full_url(), '{}/v1/notices/'.format(honeybadger.config.endpoint)) self.assertEqual(error_payload['error']['class'], 'ValueError') self.assertEqual(error_payload['error']['message'], 'always fails') with mock_urlopen(assert_payload) as request_mock: try: response = self.client.get('/always_fails/') except: pass self.assertTrue(request_mock.called)
APPCFG = { // // UI // // Enable embed mode: disable header on desktop // Can also be set through url parameter ?embed EMBED: false, // Header Logo HEADER_LOGO_URL: "resources/logo.png", HEADER_LOGO_TARGET: "http://www.gbs.co.nz/", // Header top right link HEADER_LINK_TEXT: "A GBS Story Map", HEADER_LINK_URL: "http://www.gbs.co.nz/", // Control display of Facebook and Twitter links HEADER_SOCIAL: { facebook: true, twitter: true, bitly: { enable: true, login: "esristorymaps", key: "R_14fc9f92e48f7c78c21db32bd01f7014" } }, // Header, Picture Panel and Carousel colors COLORS: ["#444", "#797979", "#c2c2c2"], // Map popup colors POPUP_BACKGROUND_COLOR: "#444444", POPUP_BORDER_COLOR: "#444444", POPUP_ARROW_COLOR: "#444444", MINIMUM_MAP_WIDTH: 450, TIMEOUT_VIEWER_LOAD: 12000, TIMEOUT_VIEWER_REQUEST: 8000, TIMEOUT_BUILDER_REQUEST: 20000, // // DATA // // Case insensitive prioritized list of fields name to be used FIELDS_CANDIDATE: { objectid: ['Number'], name: ['name', 'title', 'name-short', 'name-long'], description: ['description', 'caption', 'snippet', 'comment'], color: ['icon_color', 'color', 'style'], pic_url: ['pic_url', 'url', 'pic', 'picture'], thumb_url: ['thumb_url', 'thumb', 'thumbnail'] }, // Pin has to be numbered from 1 to that value MAX_ALLOWED_POINTS: 150, // Ordered list of pin configuration (has to be lower case) PIN_CFG: { r: { iconPath: 'resources/markers/red/NumberIcon', // A css class that define the color to be used for the Desktop carousel and builder organize popup cssClass: 'number-red' }, b: { iconPath: 'resources/markers/blue/NumberIconb', cssClass: 'number-blue' }, g: { iconPath: 'resources/markers/green/NumberIcong', cssClass: 'number-green' }, p: { iconPath: 'resources/markers/purple/IconPurple', cssClass: 'number-purple' } }, // Default color PIN_DEFAULT_CFG: 'r', // Pin states ICON_CFG: { normal: { width: 22, height: 28, offsetX: 3, offsetY: 8, // Normal state has to define the clip information for mobile components clipRules: "clip: rect(0px, 22px, 22px, 0px); left: 13px; top: 13px; height:40px; width: 32px;" }, hover: { width: 24, height: 30, offsetX: 3, offsetY: 8 }, selected: { width: 32, height: 40, offsetX: 3, offsetY: 11 } }, // // Builder // // Control the authorized data source (for initialization and import screen) AUTHORIZED_IMPORT_SOURCE: { // featureService is set to false in the app when the Map Tour is hosted // on a Portal for ArcGIS instance 10.2 as that feature isn't supported yet featureService: true, flickr: true, facebook: true, picasa: true }, // Online photo sharing services connection parameters FLICKR_API_KEY: "750b36a2ac65a72e03cf9cef06d79f45", // The Facebook ID is only valid on arcgis.com domain // If used on another domain, user will have an error in the Facebook popup after login // To use Facebook import on Portal for ArcGIS, create your own ID at https://developers.facebook.com/ // or set AUTHORIZED_IMPORT_SOURCE.facebook to false FACEBOOK_APP_ID: "471023926309627", COLOR_SCHEMES: [ // COLORS is added as the first item at runtime {name: "Black", headerColor: "#000", middleColor: "#797979", footerColor: "#c2c2c2"}, {name: "Blue", headerColor: "#0e3867", middleColor: "#5d6f89", footerColor: "#9096a9"}, {name: "Green", headerColor: "#1a3606", middleColor: "#737c6c", footerColor: "#a8b09e"} ], // Optional array of server that will leverage CORS (for developement or specific cross domain deployment) CORS_SERVER: ["glazou.esri.com:7777", "monoprice.esri.com", "story.maps.arcgis.com", "active.mapsdevext.arcgis.com"], // Edit those to set a custom sharing or proxy URL // You have to edit those only if your webmap is deployed on Portal for ArcGIS instance and if you are not deploying the template on the Portal webserver // If you are using ArcGIS Online or deploying the template on a Portal instance, you don't have to edit those URL DEFAULT_SHARING_URL: "//www.arcgis.com/sharing/content/items", //DEFAULT_SHARING_URL: "//portal.internal.com/arcgis/sharing/content/items", DEFAULT_PROXY_URL: "//gbsmaps.azurewebsites.net/proxy.ashx" //DEFAULT_PROXY_URL: "//portal.internal.com/arcgis/sharing/proxy" };
import torch from torchvision import transforms from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True from utils.utils import * import json import numpy as np import os from tool.darknet2pytorch import * from infer import infer from tqdm import tqdm from skimage import measure def fgsm_attack(image, epsilon, data_grad): # 收集数据梯度的元素符号 sign_data_grad = data_grad.sign() # 通过调整输入图像的每个像素来创建扰动图像 perturbed_image = image + epsilon*sign_data_grad # 添加剪切以维持[0,1]范围 perturbed_image = torch.clamp(perturbed_image, 0, 1) # 返回被扰动的图像 return perturbed_image def test_fgsm( model, device, x,y, epsilon ): # 精度计数器 correct = 0 adv_examples = [] # 循环遍历测试集中的所有示例 for data, target in x,y: # 把数据和标签发送到设备 data, target = data.to(device), target.to(device) # 设置张量的requires_grad属性,这对于攻击很关键 data.requires_grad = True # 通过模型前向传递数据 output = model(data) init_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability # 如果初始预测是错误的,不打断攻击,继续 if init_pred.item() != target.item(): continue # 计算损失 loss = F.nll_loss(output, target) # 将所有现有的渐变归零 model.zero_grad() # 计算后向传递模型的梯度 loss.backward() # 收集datagrad data_grad = data.grad.data # 唤醒FGSM进行攻击 perturbed_data = fgsm_attack(data, epsilon, data_grad) # 重新分类受扰乱的图像 output = model(perturbed_data) # 检查是否成功 final_pred = output.max(1, keepdim=True)[1] # get the index of the max log-probability if final_pred.item() == target.item(): correct += 1 # 保存0 epsilon示例的特例 if (epsilon == 0) and (len(adv_examples) < 5): adv_ex = perturbed_data.squeeze().detach().cpu().numpy() adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) ) else: # 稍后保存一些用于可视化的示例 if len(adv_examples) < 5: adv_ex = perturbed_data.squeeze().detach().cpu().numpy() adv_examples.append( (init_pred.item(), final_pred.item(), adv_ex) ) # 计算这个epsilon的最终准确度 final_acc = correct/float(len(test_loader)) print("Epsilon: {}\tTest Accuracy = {} / {} = {}".format(epsilon, correct, len(test_loader), final_acc)) # 返回准确性和对抗性示例 return final_acc, adv_examples os.environ["CUDA_VISIBLE_DEVICES"] = "1" def count_detection_score_fasterrcnn(img_file_dir, bb_json_name, output_dir): config = './mmdetection/configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py' checkpoint = './models/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' infer(config=config, checkpoint=checkpoint, img_file_dir=img_file_dir + '/', output_dir=output_dir, json_name=bb_json_name) return def count_detection_score_yolov4(selected_path, json_name, output_dir): cfgfile = "models/yolov4.cfg" weightfile = "models/yolov4.weights" darknet_model = Darknet(cfgfile) darknet_model.load_weights(weightfile) darknet_model = darknet_model.eval().cuda() files = os.listdir(selected_path) files.sort() bb_score_dict = {} for img_name_index in tqdm(range(len(files))): img_name = files[img_name_index] img_file_dir2 = selected_path.replace('_p', '') # clean img_path0 = os.path.join(img_file_dir2, img_name) img0 = Image.open(img_path0).convert('RGB') img_path1 = os.path.join(selected_path, img_name) img1 = Image.open(img_path1).convert('RGB') resize_small = transforms.Compose([ transforms.Resize((608, 608)), ]) img0 = resize_small(img0) img1 = resize_small(img1) # --------------------BOX score boxes0 = do_detect(darknet_model, img0, 0.5, 0.4, True) boxes1 = do_detect(darknet_model, img1, 0.5, 0.4, True) assert len(boxes0) != 0 bb_score = 1 - min(len(boxes0), len(boxes1))/len(boxes0) bb_score_dict[img_name] = bb_score with open(os.path.join(output_dir, json_name), 'w') as f_obj: json.dump(bb_score_dict, f_obj) def count_connected_domin_score(max_total_area_rate, selected_path, max_patch_number, json_name, output_dir): files = os.listdir(selected_path) resize2 = transforms.Compose([ transforms.ToTensor()]) files.sort() connected_domin_score_dict = {} zero_patch=0 zero_area=0 for img_name_index in tqdm(range(len(files))): img_name = files[img_name_index] img_path0 = os.path.join(selected_path.replace('_p', ''), img_name) img0 = Image.open(img_path0).convert('RGB') img_path1 = os.path.join(selected_path, img_name) img1 = Image.open(img_path1).convert('RGB') img0_t = resize2(img0).cuda() img1_t = resize2(img1).cuda() img_minus_t = img0_t - img1_t connected_domin_score, total_area_rate, patch_number = \ connected_domin_detect_and_score(img_minus_t, max_total_area_rate, max_patch_number) if patch_number > max_patch_number: connected_domin_score_dict[img_name] = 0.0 print(img_name,':patch number is too many') zero_patch+=1 continue if patch_number == 0: connected_domin_score_dict[img_name] = 0.0 print(img_name,': **********patch number=0**********') continue if total_area_rate > max_total_area_rate: print(img_name,': patch area is too large') zero_area+=1 connected_domin_score_dict[img_name] = 0.0 continue connected_domin_score_dict[img_name] = connected_domin_score print('zero_patch:',zero_patch, ' zero_area:',zero_area) with open(os.path.join(output_dir, json_name), 'w') as f_obj: json.dump(connected_domin_score_dict, f_obj) def connected_domin_detect_and_score(input_img, max_total_area_rate, max_patch_number): # detection input_img_new = (input_img[0]+input_img[1]+input_img[2]) ones = torch.cuda.FloatTensor(input_img_new.size()).fill_(1) zeros = torch.cuda.FloatTensor(input_img_new.size()).fill_(0) whole_size = input_img_new.shape[0]*input_img_new.shape[1] input_map_new = torch.where((input_img_new != 0), ones, zeros) labels = measure.label(input_map_new.cpu().numpy()[:, :], background=0, connectivity=2) label_max_number = np.max(labels) if max_patch_number > 0: if label_max_number > max_patch_number: return 0, 0, float(label_max_number) if label_max_number == 0: return 0, 0, 0 total_area = torch.sum(input_map_new).item() total_area_rate = total_area / whole_size area_score = 2 - float(total_area_rate/max_total_area_rate) return float(area_score), float(total_area_rate), float(label_max_number) def compute_overall_score(json1, json2, output_dir, output_json): with open(os.path.join(output_dir, json1)) as f_obj: connected_domin_score_dict = json.load(f_obj) with open(os.path.join(output_dir, json2)) as f_obj: bbox_score_dict = json.load(f_obj) assert len(bbox_score_dict) == len(connected_domin_score_dict) score_sum = 0 overall_score = {} for (k, _) in bbox_score_dict.items(): overall_score[k] = connected_domin_score_dict[k] * bbox_score_dict[k] score_sum += connected_domin_score_dict[k] * bbox_score_dict[k] print('Overall score: ', score_sum) print('Saving into {}...'.format(output_json)) with open(os.path.join(output_dir, output_json), 'w') as f_obj: json.dump(overall_score, f_obj) if __name__ == '__main__': MAX_TOTAL_AREA_RATE = 0.02 # 5000/(500*500) = 0.02 selected_path = './select1000_new_p' max_patch_number = 10 output_dir = './output_data' # compute_connected_domin_score cd_json_name = 'connected_domin_score.json' count_connected_domin_score(MAX_TOTAL_AREA_RATE, selected_path, max_patch_number, cd_json_name, output_dir) # compute_boundingbox_score bb_json_name = 'whitebox_yolo_boundingbox_score.json' whitebox_yolo_result = 'whitebox_yolo_overall_score.json' count_detection_score_yolov4(selected_path, bb_json_name, output_dir) compute_overall_score(cd_json_name, bb_json_name, output_dir, whitebox_yolo_result) bb_json_name = 'whitebox_fasterrcnn_boundingbox_score.json' whitebox_fasterrcnn_result = 'whitebox_fasterrcnn_overall_score.json' count_detection_score_fasterrcnn(selected_path, bb_json_name, output_dir) compute_overall_score(cd_json_name, bb_json_name, output_dir, whitebox_fasterrcnn_result)
# Karolina Szafran-Belzowska, 2019-03-16 # collatz.py # Adapted from https://stackoverflow.com/questions/33508034/making-a-collatz-program-automate-the-boring-stuff?answertab=active#tab-top def collatzSequence(number): if (number % 2 == 0): # if it's even number = number // 2 else: # if it's odd number = number * 3 + 1 print (number) return (number) n = int(input('Enter a number: ')) while (n != 1): n = collatzSequence(n)
this["polylang-pro"] = /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 506: /***/ ((module) => { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } module.exports = _assertThisInitialized; /***/ }), /***/ 575: /***/ ((module) => { function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } module.exports = _classCallCheck; /***/ }), /***/ 913: /***/ ((module) => { function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } module.exports = _createClass; /***/ }), /***/ 713: /***/ ((module) => { function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } module.exports = _defineProperty; /***/ }), /***/ 754: /***/ ((module) => { function _getPrototypeOf(o) { module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } module.exports = _getPrototypeOf; /***/ }), /***/ 205: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var setPrototypeOf = __webpack_require__(489); function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) setPrototypeOf(subClass, superClass); } module.exports = _inherits; /***/ }), /***/ 585: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { var _typeof = __webpack_require__(8); var assertThisInitialized = __webpack_require__(506); function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return assertThisInitialized(self); } module.exports = _possibleConstructorReturn; /***/ }), /***/ 489: /***/ ((module) => { function _setPrototypeOf(o, p) { module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } module.exports = _setPrototypeOf; /***/ }), /***/ 8: /***/ ((module) => { function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { module.exports = _typeof = function _typeof(obj) { return typeof obj; }; } else { module.exports = _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = _typeof; /***/ }), /***/ 757: /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(666); /***/ }), /***/ 392: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external {"this":["wp","element"]} var external_this_wp_element_ = __webpack_require__(2); // EXTERNAL MODULE: external {"this":["wp","plugins"]} var external_this_wp_plugins_ = __webpack_require__(601); // EXTERNAL MODULE: external {"this":["wp","editPost"]} var external_this_wp_editPost_ = __webpack_require__(219); // EXTERNAL MODULE: external {"this":["wp","i18n"]} var external_this_wp_i18n_ = __webpack_require__(57); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/classCallCheck.js var classCallCheck = __webpack_require__(575); var classCallCheck_default = /*#__PURE__*/__webpack_require__.n(classCallCheck); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/createClass.js var createClass = __webpack_require__(913); var createClass_default = /*#__PURE__*/__webpack_require__.n(createClass); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/inherits.js var inherits = __webpack_require__(205); var inherits_default = /*#__PURE__*/__webpack_require__.n(inherits); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/possibleConstructorReturn.js var possibleConstructorReturn = __webpack_require__(585); var possibleConstructorReturn_default = /*#__PURE__*/__webpack_require__.n(possibleConstructorReturn); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/getPrototypeOf.js var getPrototypeOf = __webpack_require__(754); var getPrototypeOf_default = /*#__PURE__*/__webpack_require__.n(getPrototypeOf); // EXTERNAL MODULE: external {"this":["wp","data"]} var external_this_wp_data_ = __webpack_require__(197); // EXTERNAL MODULE: external "lodash" var external_lodash_ = __webpack_require__(804); // EXTERNAL MODULE: external {"this":["wp","apiFetch"]} var external_this_wp_apiFetch_ = __webpack_require__(839); var external_this_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_this_wp_apiFetch_); // EXTERNAL MODULE: external {"this":["wp","url"]} var external_this_wp_url_ = __webpack_require__(696); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/defineProperty.js var defineProperty = __webpack_require__(713); var defineProperty_default = /*#__PURE__*/__webpack_require__.n(defineProperty); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/assertThisInitialized.js var assertThisInitialized = __webpack_require__(506); var assertThisInitialized_default = /*#__PURE__*/__webpack_require__.n(assertThisInitialized); // EXTERNAL MODULE: external {"this":["wp","components"]} var external_this_wp_components_ = __webpack_require__(587); // EXTERNAL MODULE: external {"this":["wp","compose"]} var external_this_wp_compose_ = __webpack_require__(390); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/confirmation-modal/index.js function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * Wordpress dependencies * * @package Polylang-Pro */ var ConfirmationModal = /*#__PURE__*/function (_Component) { inherits_default()(ConfirmationModal, _Component); var _super = _createSuper(ConfirmationModal); function ConfirmationModal() { var _this; classCallCheck_default()(this, ConfirmationModal); _this = _super.apply(this, arguments); _this.confirmButton = (0,external_this_wp_element_.createRef)(); return _this; } createClass_default()(ConfirmationModal, [{ key: "componentDidMount", value: function componentDidMount() { this.confirmButton.current.focus(); } }, { key: "render", value: function render() { var _this$props = this.props, idPrefix = _this$props.idPrefix, title = _this$props.title, updateState = _this$props.updateState, handleChange = _this$props.handleChange, children = _this$props.children; // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_components_.Modal, { title: title, className: "confirmBox", onRequestClose: updateState, shouldCloseOnEsc: false, shouldCloseOnClickOutside: false, focusOnMount: false }, children, (0,external_this_wp_element_.createElement)(external_this_wp_components_.ButtonGroup, { className: "buttons" }, (0,external_this_wp_element_.createElement)(external_this_wp_components_.Button, { id: "".concat(idPrefix, "_confirm"), ref: this.confirmButton, isPrimary: true, onClick: function onClick(event) { handleChange(event); updateState(); } }, (0,external_this_wp_i18n_.__)('OK', 'polylang-pro')), (0,external_this_wp_element_.createElement)(external_this_wp_components_.Button, { id: "".concat(idPrefix, "_cancel"), isSecondary: true, onClick: function onClick() { return updateState(); } }, (0,external_this_wp_i18n_.__)('Cancel', 'polylang-pro')))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }]); return ConfirmationModal; }(external_this_wp_element_.Component); /** * Control the execution of a component's function with a confirmation modal. * * @param {string} idPrefix Used to identify the modal's buttons. {@see ConfirmationModal.render()} * @param {React.Component} ModalContent Component which contains the content displayed in the confirmation modal. * @param {handleChangeCallback} handleChangeCallback Action triggered when we valid the confirmation modal by clicking the confirmation button. * * @return {Function} Higher-order component. */ var withConfirmation = function withConfirmation(idPrefix, ModalContent, handleChangeCallback) { return (0,external_this_wp_compose_.createHigherOrderComponent)( /** * @function Higher-Order Component * * @param {React.Component} WrappedComponent The component which needs a confirmation to change to its new value. * @param {string} WrappedComponent.labelConfirmationModal Used for both WrappedComponent and ConfirmationModal titles. * @param {WrappedComponent.getChangeValueCallback} WrappedComponent.getChangeValue * @param {WrappedComponent.bypassConfirmationCallback} WrappedComponent.bypassConfirmation * @return {WPComponent} */ function (WrappedComponent) { var enhanceComponent = /*#__PURE__*/function (_Component2) { inherits_default()(enhanceComponent, _Component2); var _super2 = _createSuper(enhanceComponent); // phpcs:ignore PEAR.Functions.FunctionCallSignature.Indent function enhanceComponent() { var _this2; classCallCheck_default()(this, enhanceComponent); _this2 = _super2.apply(this, arguments); _this2.state = { isOpen: false, changeValue: null }; _this2.handleChange = _this2.handleChange.bind(assertThisInitialized_default()(_this2)); return _this2; } createClass_default()(enhanceComponent, [{ key: "handleChange", value: function handleChange(event) { var changeValue = WrappedComponent.getChangeValue(event); if (!(0,external_lodash_.isUndefined)(WrappedComponent.bypassConfirmation) && WrappedComponent.bypassConfirmation(this.props.translationData)) { handleChangeCallback(changeValue); } else { this.setState({ isOpen: true, changeValue: changeValue }); } } }, { key: "render", value: function render() { var _this3 = this; var passThroughProps = this.props; var wrappedComponentProps = Object.assign({}, _objectSpread({}, passThroughProps), { handleChange: this.handleChange }); // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_element_.Fragment, null, (0,external_this_wp_element_.createElement)(WrappedComponent, wrappedComponentProps), this.state.isOpen && (0,external_this_wp_element_.createElement)(ConfirmationModal, { title: WrappedComponent.labelConfirmationModal, idPrefix: idPrefix, handleChange: function handleChange() { return handleChangeCallback(_this3.state.changeValue); }, updateState: function updateState() { return _this3.setState({ isOpen: false, changeValue: null }); } }, (0,external_this_wp_element_.createElement)(ModalContent, null))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }]); return enhanceComponent; }(external_this_wp_element_.Component); ; // phpcs:disable PEAR.Functions.FunctionCallSignature.Indent enhanceComponent.bypassConfirmation = WrappedComponent.bypassConfirmation; enhanceComponent.getChangeValue = WrappedComponent.getChangeValue; return enhanceComponent; // phpcs:enable PEAR.Functions.FunctionCallSignature.Indent }, 'withConfirmation'); }; /** * Callback to trigger the action to change the value in the Component wrapped by the withConfirmation HOC. * * @callback handleChangeCallback * @param {string} changeValue The value computed by {@see WrappedComponent.getChangeValueCallback} */ /** * Callback to retrieve the value to change from the Component wrapped by the withConfirmation HOC. * * @callback WrappedComponent.getChangeValueCallback * @param {Event} event A DOM triggered by the wrapped component. */ /** * Optional callback to check whether the Component wrapped by the withConfirmation HOC need to open the confirmation modal or not. * * @callback WrappedComponent.bypassConfirmationCallback * @param {Object} [translationData] A entry which represents the translation of the current post in a language {@see PLL_REST_Post::get_translations_table()}. */ /* harmony default export */ const confirmation_modal = (withConfirmation); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/settings.js /** * Module Constants * * @package Polylang-Pro */ var MODULE_KEY = 'pll/metabox'; var MODULE_CORE_EDITOR_KEY = 'core/editor'; var MODULE_CORE_KEY = 'core'; var DEFAULT_STATE = { languages: [], selectedLanguage: {}, translatedPosts: {}, fromPost: null }; ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/utils.js /** * WordPress Dependencies * * @package Polylang-Pro */ /** * Convert array of object to a map * * @param {type} array to convert * @param {type} key in the object used as key to build map * @returns {Map} */ function convertArrayToMap(array, key) { var map = new Map(); array.reduce(function (accumulator, currentValue) { accumulator.set(currentValue[key], currentValue); return accumulator; }, map); return map; } /** * Convert map to an associative array * * @param {Map} map to convert * @returns {Object} */ function convertMapToObject(map) { var object = {}; map.forEach(function (value, key, map) { var obj = this; this[key] = (0,external_lodash_.isBoolean)(value) ? value.toString() : value; }, object); return object; } /** * Return the post type URL for REST API calls * * @param {string} post type name * @returns {string} */ function getPostsUrl(name) { var postTypes = select('core').getEntitiesByKind('postType'); var postType = find(postTypes, { name: name }); return postType.baseURL; } /** * Get all query string parameters and convert them in a URLSearchParams object * * @returns {object} */ function getSearchParams() { // Variable window.location.search is just read for creating and returning a URLSearchParams object to be able to manipulate it more easily if (!(0,external_lodash_.isEmpty)(window.location.search)) { // phpcs:ignore WordPressVIPMinimum.JS.Window.location return new URLSearchParams(window.location.search); // phpcs:ignore WordPressVIPMinimum.JS.Window.location } else { return null; } } /** * Get selected language * * @param string Post language code * @returns {Object} Selected Language */ function getSelectedLanguage(lang) { var languages = (0,external_this_wp_data_.select)(MODULE_KEY).getLanguages(); // Pick up this language as selected in languages list return languages.get(lang); } /** * Get translated posts * * @param array ids of translated posts * @returns {Map} */ function getTranslatedPosts(translations, translations_table, lang) { var translationsTable = getTranslationsTable(translations_table, lang); var fromPost = (0,external_this_wp_data_.select)(MODULE_KEY).getFromPost(); var translatedPosts = new Map(Object.entries([])); if (!(0,external_lodash_.isUndefined)(translations)) { translatedPosts = new Map(Object.entries(translations)); } // phpcs:disable PEAR.Functions.FunctionCallSignature.Indent // If we come from another post for creating a new one, we have to update translated posts from the original post // to be able to update translations attribute of the post if (!(0,external_lodash_.isNil)(fromPost) && !(0,external_lodash_.isNil)(fromPost.id)) { translationsTable.forEach(function (translationData, lang) { if (!(0,external_lodash_.isNil)(translationData.translated_post) && !(0,external_lodash_.isNil)(translationData.translated_post.id)) { translatedPosts.set(lang, translationData.translated_post.id); } }); } // phpcs:enable PEAR.Functions.FunctionCallSignature.Indent return translatedPosts; } /** * Get synchronized posts * * @param array ids of synchronized posts * @returns {Map} */ function getSynchronizedPosts(pll_sync_post) { var synchronizedPosts = new Map(Object.entries([])); if (!(0,external_lodash_.isUndefined)(pll_sync_post)) { synchronizedPosts = new Map(Object.entries(pll_sync_post)); } return synchronizedPosts; } /** * Get translations table * * @param object translations table datas * @param string language code * @returns {Map} */ function getTranslationsTable(translationsTableDatas, lang) { var translationsTable = new Map(Object.entries([])); // get translations table datas from post if (!(0,external_lodash_.isUndefined)(translationsTableDatas)) { // Build translations table map with language slug as key translationsTable = new Map(Object.entries(translationsTableDatas)); } return translationsTable; } ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/switcher/index.js function switcher_createSuper(Derived) { var hasNativeReflectConstruct = switcher_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function switcher_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var Switcher = /*#__PURE__*/function (_Component) { inherits_default()(Switcher, _Component); var _super = switcher_createSuper(Switcher); function Switcher() { classCallCheck_default()(this, Switcher); return _super.apply(this, arguments); } createClass_default()(Switcher, [{ key: "render", value: function render() { var _this = this; var languages = (0,external_this_wp_data_.select)(MODULE_KEY).getLanguages(); var lang = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('lang'); var selectedLanguage = getSelectedLanguage(lang); // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter, PEAR.Functions.FunctionCallSignature.Indent return (0,external_this_wp_element_.createElement)(external_this_wp_element_.Fragment, null, (0,external_this_wp_element_.createElement)("p", null, (0,external_this_wp_element_.createElement)("strong", null, (0,external_this_wp_i18n_.__)("Language", "polylang-pro"))), (0,external_this_wp_element_.createElement)("label", { className: "screen-reader-text", htmlFor: "pll_post_lang_choice" }, (0,external_this_wp_i18n_.__)("Language", "polylang-pro")), (0,external_this_wp_element_.createElement)("div", { id: "select-post-language" }, (0,external_this_wp_element_.createElement)("span", { className: "pll-select-flag" }, !(0,external_lodash_.isEmpty)(selectedLanguage.flag_url) ? (0,external_this_wp_element_.createElement)("span", { className: "pll-select-flag" }, (0,external_this_wp_element_.createElement)("img", { src: selectedLanguage.flag_url, alt: selectedLanguage.name, title: selectedLanguage.name, className: "flag" })) : (0,external_this_wp_element_.createElement)("abbr", null, selectedLanguage.slug, (0,external_this_wp_element_.createElement)("span", { className: "screen-reader-text" }, selectedLanguage.name))), (0,external_this_wp_element_.createElement)("select", { value: selectedLanguage.slug, onChange: function onChange(event) { return _this.props.handleChange(event); }, id: "pll_post_lang_choice", name: "pll_post_lang_choice", className: "post_lang_choice" }, Array.from(languages.values()).map(function (_ref) { var slug = _ref.slug, name = _ref.name, w3c = _ref.w3c; return (0,external_this_wp_element_.createElement)("option", { value: slug, lang: w3c, key: slug }, name); })))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter, PEAR.Functions.FunctionCallSignature.Indent } }], [{ key: "bypassConfirmation", value: function bypassConfirmation() { var editor = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY); return !editor.getEditedPostAttribute('title') && !editor.getEditedPostContent() && !editor.getEditedPostAttribute('excerpt'); } }, { key: "getChangeValue", value: function getChangeValue(event) { return event.target.value; } /** * Manage language choice in the dropdown list * * @param language New language slug. */ }, { key: "handleLanguageChange", value: function handleLanguageChange(language) { var oldLanguageSlug = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('lang'); var postId = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getCurrentPostId(); var languages = (0,external_this_wp_data_.select)(MODULE_KEY).getLanguages(); var newLanguage = languages.get(language); var oldSelectedLanguage = getSelectedLanguage(oldLanguageSlug); var pll_sync_post = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('pll_sync_post'); var synchronizedPosts = getSynchronizedPosts(pll_sync_post); var translations_table = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations_table'); var translations = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations'); var translatedPosts = getTranslatedPosts(translations, translations_table, oldSelectedLanguage.slug); var translationsTable = getTranslationsTable(translations_table, oldSelectedLanguage.slug); // The translated post of the previous selected language must be deleted translatedPosts.delete(oldSelectedLanguage.slug); // Replace translated post for the new language translatedPosts.set(newLanguage.slug, postId); // The current post is synchronized itself and synchronization must be deleted for the previous language // to ensure it will be not synchronized with the new language synchronizedPosts.delete(oldSelectedLanguage.slug); // Update translations table // Add old selected language datas - only datas needed just to update visually the metabox var oldTranslationData = translationsTable.get(oldSelectedLanguage.slug); translationsTable.set(oldSelectedLanguage.slug, { can_synchronize: oldTranslationData.can_synchronize, lang: oldTranslationData.lang, links: { add_link: oldTranslationData.links.add_link } }); // Update some new language datas from the old selected language datas var newTranslationData = translationsTable.get(newLanguage.slug); translationsTable.set(newLanguage.slug, { can_synchronize: newTranslationData.can_synchronize, lang: newTranslationData.lang, links: oldTranslationData.links, translated_post: oldTranslationData.translated_post }); // Update the global javascript variable for maintaining it updated outside block editor context pll_block_editor_plugin_settings = newLanguage; // And save changes in store (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ lang: newLanguage.slug }); (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ pll_sync_post: convertMapToObject(synchronizedPosts) }); (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ translations: convertMapToObject(translatedPosts) }); (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ translations_table: convertMapToObject(translationsTable) }); // Need to save post for recalculating permalink (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).savePost(); Switcher.forceLanguageSave(oldSelectedLanguage.slug); Switcher.invalidateParentPagesStoredInCore(); } /** * Even if no content has been written, Polylang back-end code needs the correct language to send back the correct metadatas. (e.g.: Attachable Medias). * * @since 3.0 * * @param {string} lang A language slug. */ }, { key: "forceLanguageSave", value: function forceLanguageSave(lang) { var editor = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY); if (!editor.getEditedPostAttribute('title') && !editor.getEditedPostContent() && !editor.getEditedPostAttribute('excerpt')) { external_this_wp_apiFetch_default()({ path: (0,external_this_wp_url_.addQueryArgs)("wp/v2/posts/".concat(editor.getCurrentPostId()), // phpcs:ignore WordPress.WhiteSpace.OperatorSpacing { lang: lang }), method: 'POST' }); } } /** * Invalidate resolution of parent page attribute request to redo it * and refresh the list of pages filtered with the right language */ }, { key: "invalidateParentPagesStoredInCore", value: function invalidateParentPagesStoredInCore() { // invalidate cache on parent pages attribute // arguments must be exactly the same as the getEntityRecords done in the parent pages component of the editor var postId = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getCurrentPostId(); var postTypeSlug = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('type'); var query = { per_page: -1, exclude: postId, parent_exclude: postId, orderby: 'menu_order', order: 'asc' }; (0,external_this_wp_data_.dispatch)('core/data').invalidateResolution('core', 'getEntityRecords', ['postType', postTypeSlug, query]); } }]); return Switcher; }(external_this_wp_element_.Component); Switcher.labelConfirmationModal = (0,external_this_wp_i18n_.__)('Change language', 'polylang-pro'); var ModalContent = function ModalContent() { // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)("p", null, (0,external_this_wp_i18n_.__)('Are you sure you want to change the language of the current content?', 'polylang-pro')); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter }; var SwitcherWithConfirmation = confirmation_modal('pll_change_lang', ModalContent, Switcher.handleLanguageChange)(Switcher); /* harmony default export */ const switcher = (SwitcherWithConfirmation); // EXTERNAL MODULE: ./node_modules/@babel/runtime/helpers/typeof.js var helpers_typeof = __webpack_require__(8); var typeof_default = /*#__PURE__*/__webpack_require__.n(helpers_typeof); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/duplicate-button/index.js function duplicate_button_createSuper(Derived) { var hasNativeReflectConstruct = duplicate_button_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function duplicate_button_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * WordPress dependencies * * @package Polylang-Pro */ var DuplicateButton = /*#__PURE__*/function (_Component) { inherits_default()(DuplicateButton, _Component); var _super = duplicate_button_createSuper(DuplicateButton); function DuplicateButton() { var _this; classCallCheck_default()(this, DuplicateButton); _this = _super.apply(this, arguments); var currentUser = (0,external_this_wp_data_.select)(MODULE_KEY).getCurrentUser(); _this.postType = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getCurrentPostType(); _this.state = { isDuplicateActive: _this.isDuplicateActive(currentUser), currentUser: currentUser }; _this.handleDuplicateContentChange = _this.handleDuplicateContentChange.bind(assertThisInitialized_default()(_this)); _this.setState = _this.setState.bind(assertThisInitialized_default()(_this)); return _this; } /** * Read if content duplicate tool is active or not * * @param {type} user * @returns {Boolean} */ createClass_default()(DuplicateButton, [{ key: "isDuplicateActive", value: function isDuplicateActive(user) { if (undefined === typeof_default()(user.pll_duplicate_content) || undefined === typeof_default()(user.pll_duplicate_content[this.postType])) { return false; } return user.pll_duplicate_content[this.postType]; } /** * Manage Duplicate content change by clicking on the icon * * @param {type} event */ }, { key: "handleDuplicateContentChange", value: function handleDuplicateContentChange(event) { var currentUser = this.state.currentUser; // If pll_duplicate_content user meta is a string, it have never been created // So we initialize it as an object if ((0,external_lodash_.isString)(currentUser.pll_duplicate_content)) { currentUser.pll_duplicate_content = {}; } currentUser.pll_duplicate_content[this.postType] = !this.state.isDuplicateActive; // update component state this.setState({ currentUser: currentUser, isDuplicateActive: !this.state.isDuplicateActive }); // and update currentUser in store (0,external_this_wp_data_.dispatch)(MODULE_KEY).setCurrentUser({ pll_duplicate_content: currentUser.pll_duplicate_content }, true); } }, { key: "render", value: function render() { var isDuplicateActive = this.state.isDuplicateActive; /* translators: accessibility text */ var duplicateButtonText = this.state.isDuplicateActive ? (0,external_this_wp_i18n_.__)('Deactivate the content duplication', 'polylang-pro') : (0,external_this_wp_i18n_.__)('Activate the content duplication', 'polylang-pro'); // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_components_.IconButton, { id: "pll-duplicate", className: "pll-button ".concat(isDuplicateActive && "wp-ui-text-highlight"), onClick: this.handleDuplicateContentChange, icon: "admin-page", label: duplicateButtonText }, (0,external_this_wp_element_.createElement)("span", { className: "screen-reader-text" }, duplicateButtonText)); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }]); return DuplicateButton; }(external_this_wp_element_.Component); /* harmony default export */ const duplicate_button = (DuplicateButton); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/synchronization-button/index.js function synchronization_button_createSuper(Derived) { var hasNativeReflectConstruct = synchronization_button_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function synchronization_button_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var SynchronizationButton = /*#__PURE__*/function (_Component) { inherits_default()(SynchronizationButton, _Component); var _super = synchronization_button_createSuper(SynchronizationButton); function SynchronizationButton() { classCallCheck_default()(this, SynchronizationButton); return _super.apply(this, arguments); } /** * Manage synchronziation with translated posts * * @param {type} event */ createClass_default()(SynchronizationButton, [{ key: "render", value: function render() { var _this = this; var pll_sync_post = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('pll_sync_post'); var synchronizedPosts = getSynchronizedPosts(pll_sync_post); var translationData = this.props.translationData; var isSynchronized = !(0,external_lodash_.isEmpty)(synchronizedPosts) && synchronizedPosts.has(translationData.lang.slug); var highlightButtonClass = isSynchronized && 'wp-ui-text-highlight'; var synchronizeButtonText = isSynchronized ? (0,external_this_wp_i18n_.__)("Don't synchronize this post", 'polylang-pro') : (0,external_this_wp_i18n_.__)('Synchronize this post', 'polylang-pro'); // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_components_.IconButton, { icon: "controls-repeat", label: synchronizeButtonText, id: "pll_sync_post[".concat(translationData.lang.slug, "]"), className: "pll-button ".concat(highlightButtonClass), onClick: function onClick(event) { _this.props.handleChange(event); } }, (0,external_this_wp_element_.createElement)("span", { className: "screen-reader-text" }, synchronizeButtonText)); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }], [{ key: "handleSynchronizationChange", value: function handleSynchronizationChange(language) { var pll_sync_post = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('pll_sync_post'); var synchronizedPosts = getSynchronizedPosts(pll_sync_post); if (synchronizedPosts.has(language)) { synchronizedPosts.delete(language); } else { synchronizedPosts.set(language, true); } // and store the new value (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ pll_sync_post: convertMapToObject(synchronizedPosts) }); // simulate a post modification to change status of the publish/update button (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ title: (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('title') }); } }, { key: "bypassConfirmation", value: function bypassConfirmation(translationData) { var pll_sync_post = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('pll_sync_post'); var synchronizedPosts = getSynchronizedPosts(pll_sync_post); var isSynchronized = !(0,external_lodash_.isEmpty)(synchronizedPosts) && synchronizedPosts.has(translationData.lang.slug); var isTranslated = !(0,external_lodash_.isUndefined)(translationData.translated_post) && !(0,external_lodash_.isNil)(translationData.translated_post.id); return isSynchronized || !isTranslated; } }, { key: "getChangeValue", value: function getChangeValue(event) { return event.currentTarget.id.match(/\[(.[^[]+)\]/i)[1]; } }]); return SynchronizationButton; }(external_this_wp_element_.Component); SynchronizationButton.labelConfirmationModal = (0,external_this_wp_i18n_.__)('Synchronize this post', 'polylang-pro'); var synchronization_button_ModalContent = function ModalContent() { // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)("p", null, (0,external_this_wp_i18n_.__)('You are about to overwrite an existing translation. Are you sure you want to proceed?', 'polylang-pro')); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter }; var SynchronizationButtonWithConfirmation = confirmation_modal('pll_sync_post', synchronization_button_ModalContent, SynchronizationButton.handleSynchronizationChange)(SynchronizationButton); // phpcs:enable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine /* harmony default export */ const synchronization_button = (SynchronizationButtonWithConfirmation); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/add-edit-link/index.js /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var AddEditLink = function AddEditLink(_ref) { var translationData = _ref.translationData; var isTranslated = !(0,external_lodash_.isUndefined)(translationData.translated_post) && !(0,external_lodash_.isNil)(translationData.translated_post.id); var currentUserCanEdit = !(0,external_lodash_.isUndefined)(translationData.links) && !(0,external_lodash_.isNil)(translationData.links.edit_link); var translationIcon = 'plus'; /* translators: accessibility text, %s is a native language name. For example Deutsch for German or Français for french. */ var translationScreenReaderText = (0,external_this_wp_i18n_.sprintf)((0,external_this_wp_i18n_.__)('Add a translation in %s', 'polylang-pro'), translationData.lang.name); var translationUrl = decodeURI(translationData.links.add_link); if (isTranslated) { translationIcon = 'edit'; /* translators: accessibility text, %s is a native language name. For example Deutsch for German or Français for french. */ translationScreenReaderText = (0,external_this_wp_i18n_.sprintf)((0,external_this_wp_i18n_.__)('Edit the translation in %s', 'polylang-pro'), translationData.lang.name); translationUrl = decodeURI(translationData.links.edit_link); } // if the current user can't edit return nothing if (!currentUserCanEdit && isTranslated) { return null; } // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_components_.IconButton, { href: translationUrl, icon: translationIcon, label: translationScreenReaderText }, (0,external_this_wp_element_.createElement)("span", { className: "screen-reader-text" }, translationScreenReaderText)); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter }; /* harmony default export */ const add_edit_link = (AddEditLink); // EXTERNAL MODULE: ./node_modules/classnames/index.js var classnames = __webpack_require__(184); var classnames_default = /*#__PURE__*/__webpack_require__.n(classnames); ;// CONCATENATED MODULE: ./node_modules/dom-scroll-into-view/dist-web/index.js function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function dist_web_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { dist_web_ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { dist_web_ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var RE_NUM = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source; function getClientPosition(elem) { var box; var x; var y; var doc = elem.ownerDocument; var body = doc.body; var docElem = doc && doc.documentElement; // 根据 GBS 最新数据,A-Grade Browsers 都已支持 getBoundingClientRect 方法,不用再考虑传统的实现方式 box = elem.getBoundingClientRect(); // 注:jQuery 还考虑减去 docElem.clientLeft/clientTop // 但测试发现,这样反而会导致当 html 和 body 有边距/边框样式时,获取的值不正确 // 此外,ie6 会忽略 html 的 margin 值,幸运地是没有谁会去设置 html 的 margin x = box.left; y = box.top; // In IE, most of the time, 2 extra pixels are added to the top and left // due to the implicit 2-pixel inset border. In IE6/7 quirks mode and // IE6 standards mode, this border can be overridden by setting the // document element's border to zero -- thus, we cannot rely on the // offset always being 2 pixels. // In quirks mode, the offset can be determined by querying the body's // clientLeft/clientTop, but in standards mode, it is found by querying // the document element's clientLeft/clientTop. Since we already called // getClientBoundingRect we have already forced a reflow, so it is not // too expensive just to query them all. // ie 下应该减去窗口的边框吧,毕竟默认 absolute 都是相对窗口定位的 // 窗口边框标准是设 documentElement ,quirks 时设置 body // 最好禁止在 body 和 html 上边框 ,但 ie < 9 html 默认有 2px ,减去 // 但是非 ie 不可能设置窗口边框,body html 也不是窗口 ,ie 可以通过 html,body 设置 // 标准 ie 下 docElem.clientTop 就是 border-top // ie7 html 即窗口边框改变不了。永远为 2 // 但标准 firefox/chrome/ie9 下 docElem.clientTop 是窗口边框,即使设了 border-top 也为 0 x -= docElem.clientLeft || body.clientLeft || 0; y -= docElem.clientTop || body.clientTop || 0; return { left: x, top: y }; } function getScroll(w, top) { var ret = w["page".concat(top ? 'Y' : 'X', "Offset")]; var method = "scroll".concat(top ? 'Top' : 'Left'); if (typeof ret !== 'number') { var d = w.document; // ie6,7,8 standard mode ret = d.documentElement[method]; if (typeof ret !== 'number') { // quirks mode ret = d.body[method]; } } return ret; } function getScrollLeft(w) { return getScroll(w); } function getScrollTop(w) { return getScroll(w, true); } function getOffset(el) { var pos = getClientPosition(el); var doc = el.ownerDocument; var w = doc.defaultView || doc.parentWindow; pos.left += getScrollLeft(w); pos.top += getScrollTop(w); return pos; } function _getComputedStyle(elem, name, computedStyle_) { var val = ''; var d = elem.ownerDocument; var computedStyle = computedStyle_ || d.defaultView.getComputedStyle(elem, null); // https://github.com/kissyteam/kissy/issues/61 if (computedStyle) { val = computedStyle.getPropertyValue(name) || computedStyle[name]; } return val; } var _RE_NUM_NO_PX = new RegExp("^(".concat(RE_NUM, ")(?!px)[a-z%]+$"), 'i'); var RE_POS = /^(top|right|bottom|left)$/; var CURRENT_STYLE = 'currentStyle'; var RUNTIME_STYLE = 'runtimeStyle'; var LEFT = 'left'; var PX = 'px'; function _getComputedStyleIE(elem, name) { // currentStyle maybe null // http://msdn.microsoft.com/en-us/library/ms535231.aspx var ret = elem[CURRENT_STYLE] && elem[CURRENT_STYLE][name]; // 当 width/height 设置为百分比时,通过 pixelLeft 方式转换的 width/height 值 // 一开始就处理了! CUSTOM_STYLE.height,CUSTOM_STYLE.width ,cssHook 解决@2011-08-19 // 在 ie 下不对,需要直接用 offset 方式 // borderWidth 等值也有问题,但考虑到 borderWidth 设为百分比的概率很小,这里就不考虑了 // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // exclude left right for relativity if (_RE_NUM_NO_PX.test(ret) && !RE_POS.test(name)) { // Remember the original values var style = elem.style; var left = style[LEFT]; var rsLeft = elem[RUNTIME_STYLE][LEFT]; // prevent flashing of content elem[RUNTIME_STYLE][LEFT] = elem[CURRENT_STYLE][LEFT]; // Put in the new values to get a computed value out style[LEFT] = name === 'fontSize' ? '1em' : ret || 0; ret = style.pixelLeft + PX; // Revert the changed values style[LEFT] = left; elem[RUNTIME_STYLE][LEFT] = rsLeft; } return ret === '' ? 'auto' : ret; } var getComputedStyleX; if (typeof window !== 'undefined') { getComputedStyleX = window.getComputedStyle ? _getComputedStyle : _getComputedStyleIE; } function each(arr, fn) { for (var i = 0; i < arr.length; i++) { fn(arr[i]); } } function isBorderBoxFn(elem) { return getComputedStyleX(elem, 'boxSizing') === 'border-box'; } var BOX_MODELS = ['margin', 'border', 'padding']; var CONTENT_INDEX = -1; var PADDING_INDEX = 2; var BORDER_INDEX = 1; var MARGIN_INDEX = 0; function swap(elem, options, callback) { var old = {}; var style = elem.style; var name; // Remember the old values, and insert the new ones for (name in options) { if (options.hasOwnProperty(name)) { old[name] = style[name]; style[name] = options[name]; } } callback.call(elem); // Revert the old values for (name in options) { if (options.hasOwnProperty(name)) { style[name] = old[name]; } } } function getPBMWidth(elem, props, which) { var value = 0; var prop; var j; var i; for (j = 0; j < props.length; j++) { prop = props[j]; if (prop) { for (i = 0; i < which.length; i++) { var cssProp = void 0; if (prop === 'border') { cssProp = "".concat(prop + which[i], "Width"); } else { cssProp = prop + which[i]; } value += parseFloat(getComputedStyleX(elem, cssProp)) || 0; } } } return value; } /** * A crude way of determining if an object is a window * @member util */ function isWindow(obj) { // must use == for ie8 /* eslint eqeqeq:0 */ return obj != null && obj == obj.window; } var domUtils = {}; each(['Width', 'Height'], function (name) { domUtils["doc".concat(name)] = function (refWin) { var d = refWin.document; return Math.max( // firefox chrome documentElement.scrollHeight< body.scrollHeight // ie standard mode : documentElement.scrollHeight> body.scrollHeight d.documentElement["scroll".concat(name)], // quirks : documentElement.scrollHeight 最大等于可视窗口多一点? d.body["scroll".concat(name)], domUtils["viewport".concat(name)](d)); }; domUtils["viewport".concat(name)] = function (win) { // pc browser includes scrollbar in window.innerWidth var prop = "client".concat(name); var doc = win.document; var body = doc.body; var documentElement = doc.documentElement; var documentElementProp = documentElement[prop]; // 标准模式取 documentElement // backcompat 取 body return doc.compatMode === 'CSS1Compat' && documentElementProp || body && body[prop] || documentElementProp; }; }); /* 得到元素的大小信息 @param elem @param name @param {String} [extra] 'padding' : (css width) + padding 'border' : (css width) + padding + border 'margin' : (css width) + padding + border + margin */ function getWH(elem, name, extra) { if (isWindow(elem)) { return name === 'width' ? domUtils.viewportWidth(elem) : domUtils.viewportHeight(elem); } else if (elem.nodeType === 9) { return name === 'width' ? domUtils.docWidth(elem) : domUtils.docHeight(elem); } var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom']; var borderBoxValue = name === 'width' ? elem.offsetWidth : elem.offsetHeight; var computedStyle = getComputedStyleX(elem); var isBorderBox = isBorderBoxFn(elem); var cssBoxValue = 0; if (borderBoxValue == null || borderBoxValue <= 0) { borderBoxValue = undefined; // Fall back to computed then un computed css if necessary cssBoxValue = getComputedStyleX(elem, name); if (cssBoxValue == null || Number(cssBoxValue) < 0) { cssBoxValue = elem.style[name] || 0; } // Normalize '', auto, and prepare for extra cssBoxValue = parseFloat(cssBoxValue) || 0; } if (extra === undefined) { extra = isBorderBox ? BORDER_INDEX : CONTENT_INDEX; } var borderBoxValueOrIsBorderBox = borderBoxValue !== undefined || isBorderBox; var val = borderBoxValue || cssBoxValue; if (extra === CONTENT_INDEX) { if (borderBoxValueOrIsBorderBox) { return val - getPBMWidth(elem, ['border', 'padding'], which); } return cssBoxValue; } if (borderBoxValueOrIsBorderBox) { var padding = extra === PADDING_INDEX ? -getPBMWidth(elem, ['border'], which) : getPBMWidth(elem, ['margin'], which); return val + (extra === BORDER_INDEX ? 0 : padding); } return cssBoxValue + getPBMWidth(elem, BOX_MODELS.slice(extra), which); } var cssShow = { position: 'absolute', visibility: 'hidden', display: 'block' }; // fix #119 : https://github.com/kissyteam/kissy/issues/119 function getWHIgnoreDisplay(elem) { var val; var args = arguments; // in case elem is window // elem.offsetWidth === undefined if (elem.offsetWidth !== 0) { val = getWH.apply(undefined, args); } else { swap(elem, cssShow, function () { val = getWH.apply(undefined, args); }); } return val; } function css(el, name, v) { var value = v; if (_typeof(name) === 'object') { for (var i in name) { if (name.hasOwnProperty(i)) { css(el, i, name[i]); } } return undefined; } if (typeof value !== 'undefined') { if (typeof value === 'number') { value += 'px'; } el.style[name] = value; return undefined; } return getComputedStyleX(el, name); } each(['width', 'height'], function (name) { var first = name.charAt(0).toUpperCase() + name.slice(1); domUtils["outer".concat(first)] = function (el, includeMargin) { return el && getWHIgnoreDisplay(el, name, includeMargin ? MARGIN_INDEX : BORDER_INDEX); }; var which = name === 'width' ? ['Left', 'Right'] : ['Top', 'Bottom']; domUtils[name] = function (elem, val) { if (val !== undefined) { if (elem) { var computedStyle = getComputedStyleX(elem); var isBorderBox = isBorderBoxFn(elem); if (isBorderBox) { val += getPBMWidth(elem, ['padding', 'border'], which); } return css(elem, name, val); } return undefined; } return elem && getWHIgnoreDisplay(elem, name, CONTENT_INDEX); }; }); // 设置 elem 相对 elem.ownerDocument 的坐标 function setOffset(elem, offset) { // set position first, in-case top/left are set even on static elem if (css(elem, 'position') === 'static') { elem.style.position = 'relative'; } var old = getOffset(elem); var ret = {}; var current; var key; for (key in offset) { if (offset.hasOwnProperty(key)) { current = parseFloat(css(elem, key)) || 0; ret[key] = current + offset[key] - old[key]; } } css(elem, ret); } var util = _objectSpread2({ getWindow: function getWindow(node) { var doc = node.ownerDocument || node; return doc.defaultView || doc.parentWindow; }, offset: function offset(el, value) { if (typeof value !== 'undefined') { setOffset(el, value); } else { return getOffset(el); } }, isWindow: isWindow, each: each, css: css, clone: function clone(obj) { var ret = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { ret[i] = obj[i]; } } var overflow = obj.overflow; if (overflow) { for (var _i in obj) { if (obj.hasOwnProperty(_i)) { ret.overflow[_i] = obj.overflow[_i]; } } } return ret; }, scrollLeft: function scrollLeft(w, v) { if (isWindow(w)) { if (v === undefined) { return getScrollLeft(w); } window.scrollTo(v, getScrollTop(w)); } else { if (v === undefined) { return w.scrollLeft; } w.scrollLeft = v; } }, scrollTop: function scrollTop(w, v) { if (isWindow(w)) { if (v === undefined) { return getScrollTop(w); } window.scrollTo(getScrollLeft(w), v); } else { if (v === undefined) { return w.scrollTop; } w.scrollTop = v; } }, viewportWidth: 0, viewportHeight: 0 }, domUtils); function scrollIntoView(elem, container, config) { config = config || {}; // document 归一化到 window if (container.nodeType === 9) { container = util.getWindow(container); } var allowHorizontalScroll = config.allowHorizontalScroll; var onlyScrollIfNeeded = config.onlyScrollIfNeeded; var alignWithTop = config.alignWithTop; var alignWithLeft = config.alignWithLeft; var offsetTop = config.offsetTop || 0; var offsetLeft = config.offsetLeft || 0; var offsetBottom = config.offsetBottom || 0; var offsetRight = config.offsetRight || 0; allowHorizontalScroll = allowHorizontalScroll === undefined ? true : allowHorizontalScroll; var isWin = util.isWindow(container); var elemOffset = util.offset(elem); var eh = util.outerHeight(elem); var ew = util.outerWidth(elem); var containerOffset; var ch; var cw; var containerScroll; var diffTop; var diffBottom; var win; var winScroll; var ww; var wh; if (isWin) { win = container; wh = util.height(win); ww = util.width(win); winScroll = { left: util.scrollLeft(win), top: util.scrollTop(win) }; // elem 相对 container 可视视窗的距离 diffTop = { left: elemOffset.left - winScroll.left - offsetLeft, top: elemOffset.top - winScroll.top - offsetTop }; diffBottom = { left: elemOffset.left + ew - (winScroll.left + ww) + offsetRight, top: elemOffset.top + eh - (winScroll.top + wh) + offsetBottom }; containerScroll = winScroll; } else { containerOffset = util.offset(container); ch = container.clientHeight; cw = container.clientWidth; containerScroll = { left: container.scrollLeft, top: container.scrollTop }; // elem 相对 container 可视视窗的距离 // 注意边框, offset 是边框到根节点 diffTop = { left: elemOffset.left - (containerOffset.left + (parseFloat(util.css(container, 'borderLeftWidth')) || 0)) - offsetLeft, top: elemOffset.top - (containerOffset.top + (parseFloat(util.css(container, 'borderTopWidth')) || 0)) - offsetTop }; diffBottom = { left: elemOffset.left + ew - (containerOffset.left + cw + (parseFloat(util.css(container, 'borderRightWidth')) || 0)) + offsetRight, top: elemOffset.top + eh - (containerOffset.top + ch + (parseFloat(util.css(container, 'borderBottomWidth')) || 0)) + offsetBottom }; } if (diffTop.top < 0 || diffBottom.top > 0) { // 强制向上 if (alignWithTop === true) { util.scrollTop(container, containerScroll.top + diffTop.top); } else if (alignWithTop === false) { util.scrollTop(container, containerScroll.top + diffBottom.top); } else { // 自动调整 if (diffTop.top < 0) { util.scrollTop(container, containerScroll.top + diffTop.top); } else { util.scrollTop(container, containerScroll.top + diffBottom.top); } } } else { if (!onlyScrollIfNeeded) { alignWithTop = alignWithTop === undefined ? true : !!alignWithTop; if (alignWithTop) { util.scrollTop(container, containerScroll.top + diffTop.top); } else { util.scrollTop(container, containerScroll.top + diffBottom.top); } } } if (allowHorizontalScroll) { if (diffTop.left < 0 || diffBottom.left > 0) { // 强制向上 if (alignWithLeft === true) { util.scrollLeft(container, containerScroll.left + diffTop.left); } else if (alignWithLeft === false) { util.scrollLeft(container, containerScroll.left + diffBottom.left); } else { // 自动调整 if (diffTop.left < 0) { util.scrollLeft(container, containerScroll.left + diffTop.left); } else { util.scrollLeft(container, containerScroll.left + diffBottom.left); } } } else { if (!onlyScrollIfNeeded) { alignWithLeft = alignWithLeft === undefined ? true : !!alignWithLeft; if (alignWithLeft) { util.scrollLeft(container, containerScroll.left + diffTop.left); } else { util.scrollLeft(container, containerScroll.left + diffBottom.left); } } } } } /* harmony default export */ const dist_web = (scrollIntoView); //# sourceMappingURL=index.js.map // EXTERNAL MODULE: external {"this":["wp","htmlEntities"]} var external_this_wp_htmlEntities_ = __webpack_require__(664); // EXTERNAL MODULE: external {"this":["wp","keycodes"]} var external_this_wp_keycodes_ = __webpack_require__(750); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/translation-input/index.js function translation_input_createSuper(Derived) { var hasNativeReflectConstruct = translation_input_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function translation_input_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * External dependencies * * @package Polylang-Pro */ /** * WordPress dependencies */ /** * Internal dependencies */ // Since TranslationInput is rendered in the context of other inputs, but should be // considered a separate modal node, prevent keyboard events from propagating // as being considered from the input. var stopEventPropagation = function stopEventPropagation(event) { return event.stopPropagation(); }; var TranslationInput = /*#__PURE__*/function (_Component) { inherits_default()(TranslationInput, _Component); var _super = translation_input_createSuper(TranslationInput); function TranslationInput() { var _this; classCallCheck_default()(this, TranslationInput); _this = _super.apply(this, arguments); _this.onChange = _this.onChange.bind(assertThisInitialized_default()(_this)); _this.onKeyDown = _this.onKeyDown.bind(assertThisInitialized_default()(_this)); _this.bindListNode = _this.bindListNode.bind(assertThisInitialized_default()(_this)); _this.updateSuggestions = (0,external_lodash_.throttle)(_this.updateSuggestions.bind(assertThisInitialized_default()(_this)), 200); _this.suggestionNodes = []; _this.state = { posts: [], showSuggestions: false, selectedSuggestion: null }; return _this; } createClass_default()(TranslationInput, [{ key: "componentDidUpdate", value: function componentDidUpdate() { var _this2 = this; var _this$state = this.state, showSuggestions = _this$state.showSuggestions, selectedSuggestion = _this$state.selectedSuggestion; // only have to worry about scrolling selected suggestion into view // when already expanded if (showSuggestions && selectedSuggestion !== null && !this.scrollingIntoView) { this.scrollingIntoView = true; dist_web(this.suggestionNodes[selectedSuggestion], this.listNode, { onlyScrollIfNeeded: true }); setTimeout(function () { _this2.scrollingIntoView = false; // phpcs:ignore PEAR.Functions.FunctionCallSignature.Indent }, 100); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { delete this.suggestionsRequest; } }, { key: "bindListNode", value: function bindListNode(ref) { this.listNode = ref; } }, { key: "bindSuggestionNode", value: function bindSuggestionNode(index) { var _this3 = this; return function (ref) { _this3.suggestionNodes[index] = ref; }; } }, { key: "updateSuggestions", value: function updateSuggestions(value) { var _this4 = this; var noControl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; // Show the suggestions after typing at least 2 characters // and also for URLs if (value.length < 2 && !noControl) { this.setState({ showSuggestions: false, selectedSuggestion: null, loading: false }); return; } this.setState({ selectedSuggestion: null, loading: true }); var postId = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getCurrentPostId(); var postType = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getCurrentPostType(); var postLanguageSlug = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('lang'); var translationLanguageSlug = this.props.translationData.lang.slug; // language for the suggestion var request = external_this_wp_apiFetch_default()({ path: (0,external_this_wp_url_.addQueryArgs)('/pll/v1/untranslated-posts', { search: value, include: postId, untranslated_in: postLanguageSlug, lang: translationLanguageSlug, type: postType, is_block_editor: true }), filterLang: false // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact }); // phpcs:disable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine request.then(function (posts) { // A fetch Promise doesn't have an abort option. It's mimicked by // comparing the request reference in on the instance, which is // reset or deleted on subsequent requests or unmounting. if (_this4.suggestionsRequest !== request) { return; } _this4.setState({ posts: posts, showSuggestions: true, loading: false }); if (!!posts.length) { // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact, WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter _this4.props.debouncedSpeak((0,external_this_wp_i18n_.sprintf)( /* translators: accessibility text. %d is a number of posts. */ (0,external_this_wp_i18n_._n)('%d result found, use up and down arrow keys to navigate.', '%d results found, use up and down arrow keys to navigate.', posts.length, 'polylang-pro'), posts.length), 'assertive'); } else { // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact /* translators: accessibility text */ _this4.props.debouncedSpeak((0,external_this_wp_i18n_.__)('No results.', 'polylang-pro'), 'assertive'); } // phpcs:ignore Generic.WhiteSpace.ScopeIndent.IncorrectExact }).catch(function () { if (_this4.suggestionsRequest === request) { _this4.setState({ loading: false }); } }); // phpcs:enable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine this.suggestionsRequest = request; } }, { key: "onChange", value: function onChange(event) { var inputValue = event.target.value; var translatedPosts = this.props.translatedPosts; var translationsTable = this.props.translationsTable; var language = this.props.translationData.lang; this.props.onChange({ value: inputValue, translatedPosts: translatedPosts, translationsTable: translationsTable, language: language }); this.updateSuggestions(inputValue); } }, { key: "onKeyDown", value: function onKeyDown(event) { var _this$state2 = this.state, showSuggestions = _this$state2.showSuggestions, selectedSuggestion = _this$state2.selectedSuggestion, posts = _this$state2.posts, loading = _this$state2.loading; var inputValue = event.target.value; var doUpdateSuggestions = false; // If the suggestions are not shown or loading, we shouldn't handle the arrow keys // We shouldn't preventDefault to allow block arrow keys navigation if (!showSuggestions || !posts.length || loading) { switch (event.keyCode) { case external_this_wp_keycodes_.SPACE: var ctrlKey = event.ctrlKey, shiftKey = event.shiftKey, altKey = event.altKey, metaKey = event.metaKey; if (ctrlKey && !(shiftKey || altKey || metaKey)) { inputValue = ''; doUpdateSuggestions = true; } break; case external_this_wp_keycodes_.BACKSPACE: if ((0,external_lodash_.isEmpty)(inputValue)) { doUpdateSuggestions = true; } break; } if (doUpdateSuggestions) { this.updateSuggestions(inputValue, true); } return; } switch (event.keyCode) { case external_this_wp_keycodes_.UP: { event.stopPropagation(); event.preventDefault(); var previousIndex = !selectedSuggestion ? posts.length - 1 : selectedSuggestion - 1; this.setState({ selectedSuggestion: previousIndex }); break; } case external_this_wp_keycodes_.DOWN: { event.stopPropagation(); event.preventDefault(); var nextIndex = selectedSuggestion === null || selectedSuggestion === posts.length - 1 ? 0 : selectedSuggestion + 1; this.setState({ selectedSuggestion: nextIndex }); break; } case external_this_wp_keycodes_.ENTER: { if (this.state.selectedSuggestion !== null) { event.stopPropagation(); var post = this.state.posts[this.state.selectedSuggestion]; this.selectLink(post); } break; } case external_this_wp_keycodes_.ESCAPE: { event.stopPropagation(); this.setState({ selectedSuggestion: null, showSuggestions: false }); break; } } } }, { key: "selectLink", value: function selectLink(post) { var translationsTable = this.props.translationsTable; var translatedPosts = this.props.translatedPosts; var language = this.props.translationData.lang; this.props.onChange({ value: post.title.rendered, post: post, translatedPosts: translatedPosts, translationsTable: translationsTable, language: language }); this.setState({ selectedSuggestion: null, showSuggestions: false }); } }, { key: "render", value: function render() { var _this5 = this; var _this$props = this.props, _this$props$value = _this$props.value, value = _this$props$value === void 0 ? '' : _this$props$value, _this$props$autoFocus = _this$props.autoFocus, autoFocus = _this$props$autoFocus === void 0 ? true : _this$props$autoFocus, instanceId = _this$props.instanceId, translationData = _this$props.translationData; var language = translationData.lang; var _this$state3 = this.state, showSuggestions = _this$state3.showSuggestions, posts = _this$state3.posts, selectedSuggestion = _this$state3.selectedSuggestion, loading = _this$state3.loading; var currentUserCanEdit = !(0,external_lodash_.isUndefined)(translationData.links) && ((0,external_lodash_.isUndefined)(translationData.links.edit_link) || !(0,external_lodash_.isUndefined)(translationData.links.edit_link) && !(0,external_lodash_.isNull)(translationData.links.edit_link)); // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_element_.Fragment, null, (0,external_this_wp_element_.createElement)("div", { className: "translation-input" }, (0,external_this_wp_element_.createElement)("input", { lang: language.w3c, dir: language.is_rtl ? 'rtl' : 'ltr', style: { direction: language.is_rtl ? 'rtl' : 'ltr' }, autoFocus: autoFocus, disabled: !currentUserCanEdit, type: "text", "aria-label": /* translators: accessibility text */ (0,external_this_wp_i18n_.__)('URL', 'polylang-pro'), required: true, value: value, onChange: this.onChange, onInput: stopEventPropagation, placeholder: (0,external_this_wp_i18n_.__)('Start typing the post title', 'polylang-pro'), onKeyDown: this.onKeyDown, role: "combobox", "aria-expanded": showSuggestions, "aria-autocomplete": "list", "aria-owns": "translation-input-suggestions-".concat(instanceId), "aria-activedescendant": selectedSuggestion !== null ? "translation-input-suggestion-".concat(instanceId, "-").concat(selectedSuggestion) : undefined }), loading && (0,external_this_wp_element_.createElement)(external_this_wp_components_.Spinner, null)), showSuggestions && !!posts.length && (0,external_this_wp_element_.createElement)(external_this_wp_components_.Popover, { position: "bottom", noArrow: true, focusOnMount: false }, (0,external_this_wp_element_.createElement)("div", { className: "translation-input__suggestions", id: "translation-input-suggestions-".concat(instanceId), ref: this.bindListNode, role: "listbox" }, posts.map(function (post, index) { return (0,external_this_wp_element_.createElement)("button", { key: post.id, role: "option", tabIndex: "-1", id: "translation-input-suggestion-".concat(instanceId, "-").concat(index), ref: _this5.bindSuggestionNode(index), className: classnames_default()('translation-input__suggestion', { 'is-selected': index === selectedSuggestion }), onClick: function onClick() { return _this5.selectLink(post); }, "aria-selected": index === selectedSuggestion }, (0,external_this_wp_htmlEntities_.decodeEntities)(post.title.rendered) || (0,external_this_wp_i18n_.__)('(no title)', 'polylang-pro')); })))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }]); return TranslationInput; }(external_this_wp_element_.Component); /* harmony default export */ const translation_input = ((0,external_this_wp_components_.withSpokenMessages)((0,external_this_wp_compose_.withInstanceId)(TranslationInput))); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/translations-table/index.js /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var onChange = function onChange(_ref) { var value = _ref.value, _ref$post = _ref.post, post = _ref$post === void 0 ? null : _ref$post, translatedPosts = _ref.translatedPosts, translationsTable = _ref.translationsTable, language = _ref.language; var translationData = translationsTable.get(language.slug); if ((0,external_lodash_.isEmpty)(post)) { translationData.translated_post = { id: null, title: value }; translationData.links = { add_link: translationData.links.add_link }; // unlink translation translatedPosts.delete(language.slug); } else { translatedPosts.set(language.slug, post.id); translationData.translated_post = { id: post.id, title: post.title.rendered }; translationData.links.edit_link = post.edit_link; } // update translations table in store translationsTable.set(language.slug, translationData); (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ translations: convertMapToObject(translatedPosts) }); // simulate a post modification to change status of the publish/update button (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ title: (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('title') }); }; var TranslationsTable = function TranslationsTable(_ref2) { var selectedLanguage = _ref2.selectedLanguage, translationsTable = _ref2.translationsTable, translatedPosts = _ref2.translatedPosts, synchronizedPosts = _ref2.synchronizedPosts, handleSynchronizationChange = _ref2.handleSynchronizationChange; // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter, Generic.Formatting.MultipleStatementAlignment.IncorrectWarning return (0,external_this_wp_element_.createElement)("div", { id: "post-translations", className: "translations" }, (0,external_this_wp_element_.createElement)("p", null, (0,external_this_wp_element_.createElement)("strong", null, (0,external_this_wp_i18n_.__)("Translations", "polylang-pro"))), (0,external_this_wp_element_.createElement)("table", null, (0,external_this_wp_element_.createElement)("tbody", null, Array.from(translationsTable.values()).map( // phpcs:disable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine function (translationData) { var isSynchronized = !(0,external_lodash_.isEmpty)(synchronizedPosts) && synchronizedPosts.has(translationData.lang.slug); var isTranslated = !(0,external_lodash_.isUndefined)(translationData.translated_post) && !(0,external_lodash_.isNil)(translationData.translated_post.id); var synchronizeButtonText = isSynchronized ? (0,external_this_wp_i18n_.__)("Don't synchronize this post", 'polylang-pro') : (0,external_this_wp_i18n_.__)('Synchronize this post', 'polylang-pro'); return selectedLanguage.slug !== translationData.lang.slug && (0,external_this_wp_element_.createElement)("tr", { key: translationData.lang.slug }, (0,external_this_wp_element_.createElement)("th", { className: "pll-language-column" }, !(0,external_lodash_.isEmpty)(translationData.lang.flag) ? (0,external_this_wp_element_.createElement)("span", { className: "pll-select-flag flag" }, (0,external_this_wp_element_.createElement)("img", { src: translationData.lang.flag_url, alt: translationData.lang.name, title: translationData.lang.name })) : (0,external_this_wp_element_.createElement)("abbr", null, translationData.lang.slug, (0,external_this_wp_element_.createElement)("span", { className: "screen-reader-text" }, translationData.lang.name))), (0,external_this_wp_element_.createElement)("td", { className: "pll-edit-column pll-column-icon" }, (0,external_this_wp_element_.createElement)(add_edit_link, { translationData: translationData })), (0,external_this_wp_element_.createElement)("td", { className: "pll-sync-column pll-column-icon" }, translationData.can_synchronize && (0,external_this_wp_element_.createElement)(synchronization_button, { translationData: translationData })), (0,external_this_wp_element_.createElement)("td", { className: "pll-translation-column" }, (0,external_this_wp_element_.createElement)("label", { className: "screen-reader-text", htmlFor: "tr_lang_".concat(translationData.lang.slug) }, /* translators: accessibility text */ (0,external_this_wp_i18n_.__)('Translation', 'polylang-pro')), (0,external_this_wp_element_.createElement)(translation_input, { id: "htr_lang_".concat(translationData.lang.slug), autoFocus: false, translationsTable: translationsTable, translatedPosts: translatedPosts, translationData: translationData, value: !(0,external_lodash_.isUndefined)(translationData.translated_post) ? translationData.translated_post.title : '', onChange: onChange }))); // phpcs:enable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine })))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter, Generic.Formatting.MultipleStatementAlignment.IncorrectWarning }; /* harmony default export */ const translations_table = (TranslationsTable); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/metabox/index.js function metabox_createSuper(Derived) { var hasNativeReflectConstruct = metabox_isNativeReflectConstruct(); return function _createSuperInternal() { var Super = getPrototypeOf_default()(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = getPrototypeOf_default()(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return possibleConstructorReturn_default()(this, result); }; } function metabox_isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var MetaBox = /*#__PURE__*/function (_Component) { inherits_default()(MetaBox, _Component); var _super = metabox_createSuper(MetaBox); function MetaBox() { classCallCheck_default()(this, MetaBox); return _super.apply(this, arguments); } createClass_default()(MetaBox, [{ key: "componentDidMount", value: function componentDidMount() { var fromPost = (0,external_this_wp_data_.select)(MODULE_KEY).getFromPost(); var lang = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('lang'); var translations = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations'); var translations_table = (0,external_this_wp_data_.select)(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations_table'); var translatedPosts = getTranslatedPosts(translations, translations_table, lang); // if we come from another post for creating a new one, we have to update translations from the original post if (!(0,external_lodash_.isNil)(fromPost) && !(0,external_lodash_.isNil)(fromPost.id)) { (0,external_this_wp_data_.dispatch)(MODULE_CORE_EDITOR_KEY).editPost({ translations: convertMapToObject(translatedPosts) }); } } /** * Render the language metabox */ }, { key: "render", value: function render() { // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)("div", { className: "components-panel__body is-opened" }, (0,external_this_wp_element_.createElement)("form", { className: "pll-metabox-location" }, (0,external_this_wp_element_.createElement)(switcher, null), (0,external_this_wp_element_.createElement)(duplicate_button, null), (0,external_this_wp_element_.createElement)(translations_table, { selectedLanguage: this.props.selectedLanguage, translationsTable: this.props.translationsTable, synchronizedPosts: this.props.synchronizedPosts, translatedPosts: this.props.translatedPosts }))); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter } }]); return MetaBox; }(external_this_wp_element_.Component); // phpcs:disable PEAR.Functions.FunctionCallSignature.Indent, PEAR.Functions.FunctionCallSignature.EmptyLine /** * High Order Component to wrap polylang sidebar component */ var wrapLanguagesPanel = function wrapLanguagesPanel(select) { var lang = select(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('lang'); var translations_table = select(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations_table'); var translations = select(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('translations'); var pll_sync_post = select(MODULE_CORE_EDITOR_KEY).getEditedPostAttribute('pll_sync_post'); var selectedLanguage = getSelectedLanguage(lang); var translationsTable = getTranslationsTable(translations_table, lang); var translatedPosts = getTranslatedPosts(translations, translations_table, lang); var synchronizedPosts = getSynchronizedPosts(pll_sync_post); return { selectedLanguage: selectedLanguage, translationsTable: translationsTable, translatedPosts: translatedPosts, synchronizedPosts: synchronizedPosts }; }; var MetaBoxWatch = (0,external_this_wp_data_.withSelect)(wrapLanguagesPanel)(MetaBox); /* harmony default export */ const metabox = (MetaBoxWatch); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/sidebar/index.js /** * WordPress dependencies * * @package Polylang-Pro */ /** * Internal Dependencies */ // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter var Sidebar = function Sidebar() { return (0,external_this_wp_element_.createElement)(external_this_wp_editPost_.PluginSidebar, { name: "polylang-sidebar", title: (0,external_this_wp_i18n_.__)('Languages', 'polylang-pro') }, (0,external_this_wp_element_.createElement)(metabox, null)); }; // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter /* harmony default export */ const sidebar = (Sidebar); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/components/menu-item/index.js /** * @package Polylang-Pro */ // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter var MenuItem = function MenuItem() { return (0,external_this_wp_element_.createElement)(external_this_wp_editPost_.PluginSidebarMoreMenuItem, { target: "polylang-sidebar" }, (0,external_this_wp_i18n_.__)("Languages", "polylang-pro")); }; // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter /* harmony default export */ const menu_item = (MenuItem); // EXTERNAL MODULE: ./node_modules/@babel/runtime/regenerator/index.js var regenerator = __webpack_require__(757); var regenerator_default = /*#__PURE__*/__webpack_require__.n(regenerator); ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/store/index.js function store_ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function store_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { store_ownKeys(Object(source), true).forEach(function (key) { defineProperty_default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { store_ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } /** * WordPress Dependencies * * @package Polylang-Pro */ /** * Internal dependencies */ var actions = { setLanguages: function setLanguages(languages) { return { type: 'SET_LANGUAGES', languages: languages }; }, setCurrentUser: function setCurrentUser(currentUser) { var save = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return { type: 'SET_CURRENT_USER', currentUser: currentUser, save: save }; }, setFromPost: function setFromPost(fromPost) { return { type: 'SET_FROM_POST', fromPost: fromPost }; }, fetchFromAPI: function fetchFromAPI(options) { return { type: 'FETCH_FROM_API', options: options }; } }; var store = (0,external_this_wp_data_.registerStore)(MODULE_KEY, { reducer: function reducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_STATE; var action = arguments.length > 1 ? arguments[1] : undefined; // phpcs:disable Generic.WhiteSpace.ScopeIndent.IncorrectExact switch (action.type) { case 'SET_LANGUAGES': return store_objectSpread(store_objectSpread({}, state), {}, { languages: action.languages }); case 'SET_CURRENT_USER': if (action.save) { updateCurrentUser(action.currentUser); } return store_objectSpread(store_objectSpread({}, state), {}, { currentUser: action.currentUser }); case 'SET_FROM_POST': return store_objectSpread(store_objectSpread({}, state), {}, { fromPost: action.fromPost }); default: return state; } // phpcs:enable Generic.WhiteSpace.ScopeIndent.IncorrectExact }, selectors: { getLanguages: function getLanguages(state) { return state.languages; }, getCurrentUser: function getCurrentUser(state) { return state.currentUser; }, getFromPost: function getFromPost(state) { return state.fromPost; } }, actions: actions, controls: { FETCH_FROM_API: function FETCH_FROM_API(action) { return external_this_wp_apiFetch_default()(store_objectSpread({}, action.options)); } }, resolvers: { getLanguages: /*#__PURE__*/regenerator_default().mark(function getLanguages() { var path, languages; return regenerator_default().wrap(function getLanguages$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: path = '/pll/v1/languages'; _context.next = 3; return actions.fetchFromAPI({ path: path, filterLang: false }); case 3: languages = _context.sent; return _context.abrupt("return", actions.setLanguages(convertArrayToMap(languages, 'slug'))); case 5: case "end": return _context.stop(); } } }, getLanguages); }), getCurrentUser: /*#__PURE__*/regenerator_default().mark(function getCurrentUser() { var path, currentUser; return regenerator_default().wrap(function getCurrentUser$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: path = '/wp/v2/users/me'; _context2.next = 3; return actions.fetchFromAPI({ path: path, filterLang: true }); case 3: currentUser = _context2.sent; return _context2.abrupt("return", actions.setCurrentUser(currentUser)); case 5: case "end": return _context2.stop(); } } }, getCurrentUser); }) } }); /** * Initialize some store data to ensure data is ready before displaying metabox */ function initializeStore() { // call to getLanguages to force call to resolvers and initialize state var languages = (0,external_this_wp_data_.select)(MODULE_KEY).getLanguages(); // call to getCurrentUser to force call to resolvers and initialize state var currentUser = (0,external_this_wp_data_.select)(MODULE_KEY).getCurrentUser(); // save url params espacially when a new translation is creating saveURLParams(); } /** * Save query string parameters from URL. They could be needed after * They could be null if they does not exist */ function saveURLParams() { // Variable window.location.search isn't use directly // Function getSearchParams return an URLSearchParams object for manipulating each parameter // Each of them are sanitized below var searchParams = getSearchParams(window.location.search); // phpcs:ignore WordPressVIPMinimum.JS.Window.location if (null !== searchParams) { (0,external_this_wp_data_.dispatch)(MODULE_KEY).setFromPost({ id: wp.sanitize.stripTagsAndEncodeText(searchParams.get('from_post')), postType: wp.sanitize.stripTagsAndEncodeText(searchParams.get('post_type')), newLanguage: wp.sanitize.stripTagsAndEncodeText(searchParams.get('new_lang')) }); } } /** * Save current user when it is wondered * * @param {object} currentUser */ function updateCurrentUser(currentUser) { external_this_wp_apiFetch_default()({ path: '/wp/v2/users/me', data: currentUser, method: 'POST' }); } /* harmony default export */ const sidebar_store = ((/* unused pure expression or super */ null && (store))); // EXTERNAL MODULE: external {"this":["wp","primitives"]} var external_this_wp_primitives_ = __webpack_require__(684); ;// CONCATENATED MODULE: ./modules/block-editor/js/icons/library/translation.js /** * Translation icon * * @package Polylang-Pro */ /** * WordPress dependencies */ var isPrimitivesComponents = !(0,external_lodash_.isUndefined)(wp.primitives); var translation = isPrimitivesComponents ? (0,external_this_wp_element_.createElement)(external_this_wp_primitives_.SVG, { width: "20", height: "20", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20" }, (0,external_this_wp_element_.createElement)(external_this_wp_primitives_.Path, { d: "M11 7H9.49c-.63 0-1.25.3-1.59.7L7 5H4.13l-2.39 7h1.69l.74-2H7v4H2c-1.1 0-2-.9-2-2V5c0-1.1.9-2 2-2h7c1.1 0 2 .9 2 2v2zM6.51 9H4.49l1-2.93zM10 8h7c1.1 0 2 .9 2 2v7c0 1.1-.9 2-2 2h-7c-1.1 0-2-.9-2-2v-7c0-1.1.9-2 2-2zm7.25 5v-1.08h-3.17V9.75h-1.16v2.17H9.75V13h1.28c.11.85.56 1.85 1.28 2.62-.87.36-1.89.62-2.31.62-.01.02.22.97.2 1.46.84 0 2.21-.5 3.28-1.15 1.09.65 2.48 1.15 3.34 1.15-.02-.49.2-1.44.2-1.46-.43 0-1.49-.27-2.38-.63.7-.77 1.14-1.77 1.25-2.61h1.36zm-3.81 1.93c-.5-.46-.85-1.13-1.01-1.93h2.09c-.17.8-.51 1.47-1 1.93l-.04.03s-.03-.02-.04-.03z" })) : 'translation'; /* harmony default export */ const library_translation = (translation); ;// CONCATENATED MODULE: ./modules/block-editor/js/icons/index.js /** * Icons library * * @package Polylang-Pro */ ;// CONCATENATED MODULE: ./modules/block-editor/js/sidebar/index.js /** * Import styles * * @package Polylang-Pro */ /** * WordPress Dependencies */ /** * Internal dependencies */ /** * Call initialization of pll/metabox store for getting ready some datas */ initializeStore(); var PolylangSidebar = function PolylangSidebar() { // phpcs:disable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter return (0,external_this_wp_element_.createElement)(external_this_wp_element_.Fragment, null, (0,external_this_wp_element_.createElement)(sidebar, null), (0,external_this_wp_element_.createElement)(menu_item, null)); // phpcs:enable WordPress.WhiteSpace.OperatorSpacing.NoSpaceBefore, WordPress.WhiteSpace.OperatorSpacing.NoSpaceAfter }; /** * Register plugin polylang-sidebar */ (0,external_this_wp_plugins_.registerPlugin)("polylang-sidebar", { icon: library_translation, render: PolylangSidebar }); /***/ }), /***/ 184: /***/ ((module, exports) => { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2017 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg) && arg.length) { var inner = classNames.apply(null, arg); if (inner) { classes.push(inner); } } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if ( true && module.exports) { classNames.default = classNames; module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = (function () { return classNames; }).apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else {} }()); /***/ }), /***/ 666: /***/ ((module) => { /** * Copyright (c) 2014-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var runtime = (function (exports) { "use strict"; var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined; // More compressible than void 0. var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { // IE 8 has a broken Object.defineProperty that only works on DOM objects. define({}, ""); } catch (err) { define = function(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, // .throw, and .return methods. generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion // record like context.tryEntries[i].completion. This interface could // have been (and was previously) designed to take a closure to be // invoked without arguments, but in all the cases we care about we // already have an existing method we want to call, so there's no need // to create a new function object. We can even get away with assuming // the method takes exactly one argument, since that happens to be true // in every case, so we don't have to touch the arguments object. The // only additional allocation required is the completion record, which // has a stable shape and so hopefully should be cheap to allocate. function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as // breaking out of the dispatch switch statement. var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and // .constructor.prototype properties for functions that return Generator // objects. For full spec compliance, you may wish to configure your // minifier not to mangle the names of these two functions. function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that // don't natively support it. var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { // This environment has a native %IteratorPrototype%; use it instead // of the polyfill. IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = define( GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction" ); // Helper for defining the .next, .throw, and .return methods of the // Iterator interface in terms of a single ._invoke method. function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function(method) { define(prototype, method, function(arg) { return this._invoke(method, arg); }); }); } exports.isGeneratorFunction = function(genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can // do is to check its .name property. (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function(genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; // Within the body of any async function, `await x` is transformed to // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test // `hasOwn.call(value, "__await")` to determine if the yielded value is // meant to be awaited. exports.awrap = function(arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && typeof value === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function(value) { invoke("next", value, resolve, reject); }, function(err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function(unwrapped) { // When a yielded Promise is resolved, its final value becomes // the .value of the Promise<{value,done}> result for the // current iteration. result.value = unwrapped; resolve(result); }, function(error) { // If a rejected Promise was yielded, throw the rejection back // into the async generator function so it can be handled there. return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function(resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = // If enqueue has been called before, then we want to wait until // all previous Promises have been resolved before calling invoke, // so that results are always delivered in the correct order. If // enqueue has not been called before, then it is important to // call invoke immediately, without waiting on a callback to fire, // so that the async generator function has the opportunity to do // any necessary setup in a predictable way. This predictability // is why the Promise constructor synchronously invokes its // executor callback, and why async functions synchronously // execute code before the first await. Since we implement simple // async functions in terms of async generators, it is especially // important to get this right, even though it requires care. previousPromise ? previousPromise.then( callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later // invocations of the iterator. callInvokeWithMethodAndArg ) : callInvokeWithMethodAndArg(); } // Define the unified helper method that is used to implement .next, // .throw, and .return (see defineIteratorMethods). this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of // AsyncIterator objects; they just return a Promise for the value of // the final result produced by the iterator. exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator( wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl ); return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. : iter.next().then(function(result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } // Be forgiving, per 25.3.3.3.3 of the spec: // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { // Setting context._sent for legacy support of Babel's // function.sent implementation. context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { // If an exception is thrown from innerFn, we leave state === // GenStateExecuting and loop back for another invocation. state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; // Dispatch the exception by looping back around to the // context.dispatchException(context.arg) call above. context.method = "throw"; context.arg = record.arg; } } }; } // Call delegate.iterator[context.method](context.arg) and handle the // result, either by returning a { value, done } result from the // delegate iterator, or by modifying context.method and context.arg, // setting context.delegate to null, and returning the ContinueSentinel. function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined) { // A .throw or .return when the delegate iterator has no .throw // method always terminates the yield* loop. context.delegate = null; if (context.method === "throw") { // Note: ["return"] must be used for ES3 parsing compatibility. if (delegate.iterator["return"]) { // If the delegate iterator has a return method, give it a // chance to clean up. context.method = "return"; context.arg = undefined; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { // If maybeInvokeDelegate(context) changed context.method from // "return" to "throw", let that override the TypeError below. return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError( "The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (! info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { // Assign the result of the finished delegate to the temporary // variable specified by delegate.resultName (see delegateYield). context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the // exception, let the outer generator proceed normally. If // context.method was "next", forget context.arg since it has been // "consumed" by the delegate iterator. If context.method was // "return", allow the original .return call to continue in the // outer generator. if (context.method !== "return") { context.method = "next"; context.arg = undefined; } } else { // Re-yield the result returned by the delegate method. return info; } // The delegate iterator is finished, so forget it and continue with // the outer generator. context.delegate = null; return ContinueSentinel; } // Define Generator.prototype.{next,throw,return} in terms of the // unified ._invoke helper method. defineIteratorMethods(Gp); define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the // @@iterator function is called on it. Some browsers' implementations of the // iterator prototype chain incorrectly implement this, causing the Generator // object to not be returned from this call. This ensures that doesn't happen. // See https://github.com/facebook/regenerator/issues/274 for more details. Gp[iteratorSymbol] = function() { return this; }; Gp.toString = function() { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { // The root entry object (effectively a try statement without a catch // or a finally block) gives us a place to store values thrown from // locations where there is no enclosing try statement. this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function(object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); // Rather than returning an object with a next method, we keep // things simple and return the next function itself. return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } // To avoid creating an additional object, we just hang the .value // and .done properties off the next function object itself. This // also ensures that the minifier will not anonymize the function. next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined; next.done = true; return next; }; return next.next = next; } } // Return an iterator with no values. return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined, done: true }; } Context.prototype = { constructor: Context, reset: function(skipTempReset) { this.prev = 0; this.next = 0; // Resetting context._sent for legacy support of Babel's // function.sent implementation. this.sent = this._sent = undefined; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { // Not sure about the optimal order of these conditions: if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined; } } } }, stop: function() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { // If the dispatched exception was caught by a catch block, // then let that catch block handle the exception normally. context.method = "next"; context.arg = undefined; } return !! caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { // Exception thrown outside of any try block that could handle // it, so set the completion value of the entire function to // throw the exception. return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { // Ignore the finally entry if control is not jumping to a // location outside the try/catch block. finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } // The context.catch method must only be called with a location // argument that corresponds to a known catch block. throw new Error("illegal catch attempt"); }, delegateYield: function(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { // Deliberately forget the last sent value so that we don't // accidentally pass it on to the delegate. this.arg = undefined; } return ContinueSentinel; } }; // Regardless of whether this script is executing as a CommonJS module // or not, return the runtime object so that we can declare the variable // regeneratorRuntime in the outer scope, which allows this module to be // injected easily by `bin/regenerator --include-runtime script.js`. return exports; }( // If this script is executing as a CommonJS module, use module.exports // as the regeneratorRuntime namespace. Otherwise create a new empty // object. Either way, the resulting object will be used to initialize // the regeneratorRuntime variable at the top of this file. true ? module.exports : 0 )); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { // This module should not be running in strict mode, so the above // assignment should always work unless something is misconfigured. Just // in case runtime.js accidentally runs in strict mode, we can escape // strict mode using a global Function call. This could conceivably fail // if a Content Security Policy forbids using Function, but in that case // the proper solution is to fix the accidental strict mode problem. If // you've misconfigured your bundler to force strict mode and applied a // CSP to forbid Function, and you're not willing to fix either of those // problems, please detail your unique predicament in a GitHub issue. Function("r", "regeneratorRuntime = r")(runtime); } /***/ }), /***/ 804: /***/ ((module) => { module.exports = (function() { return this["lodash"]; }()); /***/ }), /***/ 839: /***/ ((module) => { module.exports = (function() { return this["wp"]["apiFetch"]; }()); /***/ }), /***/ 587: /***/ ((module) => { module.exports = (function() { return this["wp"]["components"]; }()); /***/ }), /***/ 390: /***/ ((module) => { module.exports = (function() { return this["wp"]["compose"]; }()); /***/ }), /***/ 197: /***/ ((module) => { module.exports = (function() { return this["wp"]["data"]; }()); /***/ }), /***/ 219: /***/ ((module) => { module.exports = (function() { return this["wp"]["editPost"]; }()); /***/ }), /***/ 2: /***/ ((module) => { module.exports = (function() { return this["wp"]["element"]; }()); /***/ }), /***/ 664: /***/ ((module) => { module.exports = (function() { return this["wp"]["htmlEntities"]; }()); /***/ }), /***/ 57: /***/ ((module) => { module.exports = (function() { return this["wp"]["i18n"]; }()); /***/ }), /***/ 750: /***/ ((module) => { module.exports = (function() { return this["wp"]["keycodes"]; }()); /***/ }), /***/ 601: /***/ ((module) => { module.exports = (function() { return this["wp"]["plugins"]; }()); /***/ }), /***/ 684: /***/ ((module) => { module.exports = (function() { return this["wp"]["primitives"]; }()); /***/ }), /***/ 696: /***/ ((module) => { module.exports = (function() { return this["wp"]["url"]; }()); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(__webpack_module_cache__[moduleId]) { /******/ return __webpack_module_cache__[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ var getter = module && module.__esModule ? /******/ () => module['default'] : /******/ () => module; /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* 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/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 }); /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ return __webpack_require__(392); /******/ })() ;
describe("chorus.views.SchemaListSidebar", function() { beforeEach(function() { this.view = new chorus.views.SchemaListSidebar(); }); it("does not show an info section", function () { expect(this.view.$('.info')).not.toExist(); }); });
from ajenti.api import * from ajenti.plugins import * info = PluginInfo( title='Database Commons', icon='table', dependencies=[ PluginDependency('main'), PluginDependency('services'), ], ) def init(): import api
import ActivityExecution from './ActivityExecution'; import BpmnIO from '../io/BpmnIO'; import {brokerSafeId, getUniqueId} from '../shared'; import {ActivityApi} from '../Api'; import {ActivityBroker} from '../EventBroker'; import {Formatter} from '../MessageFormatter'; import {cloneContent, cloneParent, cloneMessage} from '../messageHelper'; import {makeErrorFromMessage, ActivityError} from '../error/Errors'; export default function Activity(Behaviour, activityDef, context) { const {id, type = 'activity', name, parent: originalParent = {}, behaviour = {}, isParallelGateway, isSubProcess, triggeredByEvent, isThrowing, isTransaction} = activityDef; const isForCompensation = behaviour.isForCompensation; const parent = cloneParent(originalParent); const {environment, getInboundSequenceFlows, getOutboundSequenceFlows, getInboundAssociations} = context; const logger = environment.Logger(type.toLowerCase()); const {step} = environment.settings; const {attachedTo: attachedToRef, eventDefinitions} = behaviour; let attachedToActivity, attachedTo; if (attachedToRef) { attachedTo = attachedToRef.id; attachedToActivity = context.getActivityById(attachedToRef.id); } const inboundSequenceFlows = getInboundSequenceFlows(id) || []; const outboundSequenceFlows = getOutboundSequenceFlows(id) || []; const inboundAssociations = getInboundAssociations(id) || []; const isStart = inboundSequenceFlows.length === 0 && !attachedTo && !triggeredByEvent && !isForCompensation; const isEnd = outboundSequenceFlows.length === 0; const isParallelJoin = inboundSequenceFlows.length > 1 && isParallelGateway; const isMultiInstance = !!behaviour.loopCharacteristics; let execution, initExecutionId, executionId, stateMessage, status, stopped = false, executeMessage, consumingRunQ; const inboundTriggers = attachedToActivity ? [attachedToActivity] : inboundSequenceFlows.slice(); const inboundJoinFlows = []; let counters = { taken: 0, discarded: 0, }; const activityApi = { id, type, name, isEnd, isStart, isSubProcess, isThrowing, isForCompensation, triggeredByEvent, parent: cloneParent(parent), behaviour: {...behaviour, eventDefinitions}, attachedTo: attachedToActivity, environment, inbound: inboundSequenceFlows, outbound: outboundSequenceFlows, get counters() { return {...counters}; }, get executionId() { return executionId; }, get status() { return status; }, get stopped() { return stopped; }, get isRunning() { if (!consumingRunQ) return false; return !!status; }, Behaviour, activate, deactivate, evaluateOutbound, logger, discard, getApi, getActivityById, getState, init, recover, resume, run, shake, stop, next: step && next, }; const {broker, on, once, waitFor, emitFatal} = ActivityBroker(activityApi); activityApi.on = on; activityApi.once = once; activityApi.waitFor = waitFor; activityApi.emitFatal = emitFatal; const runQ = broker.getQueue('run-q'); const executionQ = broker.getQueue('execution-q'); const inboundQ = broker.assertQueue('inbound-q', {durable: true, autoDelete: false}); const formatRunQ = broker.getQueue('format-run-q'); const formatter = Formatter({id, broker, logger}, formatRunQ); if (isForCompensation) { inboundAssociations.forEach((trigger) => { trigger.broker.subscribeTmp('event', '#', onInboundEvent, {noAck: true, consumerTag: `_inbound-${id}`}); }); } else { inboundTriggers.forEach((trigger) => { if (trigger.isSequenceFlow) trigger.broker.subscribeTmp('event', 'flow.#', onInboundEvent, {noAck: true, consumerTag: `_inbound-${id}`}); else trigger.broker.subscribeTmp('event', 'activity.#', onInboundEvent, {noAck: true, consumerTag: `_inbound-${id}`}); }); } Object.defineProperty(activityApi, 'broker', { enumerable: true, get: () => broker, }); Object.defineProperty(activityApi, 'execution', { enumerable: true, get: () => execution, }); const bpmnIo = BpmnIO(activityApi, context); const loaedEventDefinitions = eventDefinitions && eventDefinitions.map((ed) => ed.Behaviour(activityApi, ed, context)); Object.defineProperty(activityApi, 'eventDefinitions', { enumerable: true, get: () => loaedEventDefinitions, }); const extensions = context.loadExtensions(activityApi); Object.defineProperty(activityApi, 'extensions', { enumerable: true, get: () => extensions, }); return activityApi; function init(initContent) { initExecutionId = initExecutionId || getUniqueId(id); logger.debug(`<${id}> initialized with executionId <${initExecutionId}>`); publishEvent('init', createMessage({...initContent, executionId: initExecutionId})); } function run(runContent) { if (activityApi.isRunning) throw new Error(`activity <${id}> is already running`); executionId = initExecutionId || getUniqueId(id); initExecutionId = undefined; consumeApi(); const content = createMessage({...runContent, executionId}); broker.publish('run', 'run.enter', content); broker.publish('run', 'run.start', cloneContent(content)); consumeRunQ(); } function createMessage(override = {}) { const result = { ...override, id, type, ...(name ? {name} : undefined), ...(status ? {status} : undefined), parent: cloneParent({...override.parent, ...parent}), }; const flags = {isEnd, isStart, isSubProcess, isMultiInstance, isForCompensation, attachedTo, isTransaction}; for (const flag in flags) { if (flags[flag]) result[flag] = flags[flag]; } return result; } function recover(state) { if (activityApi.isRunning) throw new Error(`cannot recover running activity <${id}>`); if (!state) return; stopped = state.stopped; status = state.status; executionId = state.executionId; counters = {...counters, ...state.counters}; if (state.execution) { execution = ActivityExecution(activityApi, context).recover(state.execution); } broker.recover(state.broker); return activityApi; } function resume() { if (consumingRunQ) { throw new Error(`cannot resume running activity <${id}>`); } if (!status) return activate(); stopped = false; consumeApi(); const content = createMessage({executionId}); broker.publish('run', 'run.resume', content, {persistent: false}); consumeRunQ(); } function discard(discardContent) { if (!status) return runDiscard(discardContent); if (execution && !execution.completed) return execution.discard(); deactivateRunConsumers(); runQ.purge(); broker.publish('run', 'run.discard', cloneContent(stateMessage.content)); consumeRunQ(); } function discardRun() { if (!status) return; if (execution && !execution.completed) return; switch (status) { case 'executing': case 'error': case 'discarded': return; } deactivateRunConsumers(); if (extensions) extensions.deactivate(); runQ.purge(); broker.publish('run', 'run.discard', cloneContent(stateMessage.content)); consumeRunQ(); } function runDiscard(discardContent = {}) { executionId = initExecutionId || getUniqueId(id); consumeApi(); initExecutionId = undefined; const content = createMessage({...discardContent, executionId}); broker.publish('run', 'run.discard', content); consumeRunQ(); } function stop() { if (!consumingRunQ) return; return getApi().stop(); } function onStop(message) { const running = consumingRunQ; stopped = true; consumingRunQ = false; broker.cancel('_activity-run'); broker.cancel('_activity-api'); broker.cancel('_activity-execution'); broker.cancel('_run-on-inbound'); broker.cancel('_format-consumer'); if (running) { if (extensions) extensions.deactivate(message || createMessage()); publishEvent('stop'); } } function activate() { if (isForCompensation) return; return consumeInbound(); } function deactivate() { broker.cancel('_run-on-inbound'); broker.cancel('_format-consumer'); } function consumeRunQ() { if (consumingRunQ) return; consumingRunQ = true; runQ.assertConsumer(onRunMessage, {exclusive: true, consumerTag: '_activity-run'}); } function consumeApi() { if (!executionId) return; broker.cancel('_activity-api'); broker.subscribeTmp('api', `activity.*.${executionId}`, onApiMessage, {noAck: true, consumerTag: '_activity-api', priority: 100}); } function consumeInbound() { if (status) return; if (isParallelJoin) { return inboundQ.consume(onJoinInbound, {consumerTag: '_run-on-inbound', prefetch: 1000}); } return inboundQ.consume(onInbound, {consumerTag: '_run-on-inbound'}); } function deactivateRunConsumers() { broker.cancel('_activity-api'); broker.cancel('_activity-run'); broker.cancel('_activity-execution'); consumingRunQ = false; } function onInboundEvent(routingKey, message) { const {fields, content, properties} = message; switch (routingKey) { case 'activity.enter': case 'activity.discard': { if (content.id === attachedToActivity.id) { inboundQ.queueMessage(fields, cloneContent(content), properties); } break; } case 'flow.shake': { shakeOutbound(message); break; } case 'association.take': case 'flow.take': case 'flow.discard': inboundQ.queueMessage(fields, cloneContent(content), properties); break; case 'association.discard': { logger.debug(`<${id}> compensation discarded`); inboundQ.purge(); break; } case 'association.complete': { if (!isForCompensation) break; inboundQ.queueMessage(fields, cloneContent(content), properties); const compensationId = `${brokerSafeId(id)}_${brokerSafeId(content.sequenceId)}`; publishEvent('compensation.start', createMessage({ executionId: compensationId, placeholder: true, })); logger.debug(`<${id}> start compensation with id <${compensationId}>`); consumeInbound(); break; } } } function onInbound(routingKey, message) { message.ack(); broker.cancel('_run-on-inbound'); const content = message.content; const inbound = [cloneContent(content)]; switch (routingKey) { case 'association.take': case 'flow.take': case 'activity.enter': run({ message: content.message, inbound, }); break; case 'flow.discard': case 'activity.discard': { let discardSequence; if (content.discardSequence) discardSequence = content.discardSequence.slice(); runDiscard({inbound, discardSequence}); break; } case 'association.complete': { broker.cancel('_run-on-inbound'); const compensationId = `${brokerSafeId(id)}_${brokerSafeId(content.sequenceId)}`; logger.debug(`<${id}> completed compensation with id <${compensationId}>`); publishEvent('compensation.end', createMessage({ executionId: compensationId, })); break; } } } function onJoinInbound(routingKey, message) { const {content} = message; const idx = inboundJoinFlows.findIndex((msg) => msg.content.id === content.id); inboundJoinFlows.push(message); if (idx > -1) return; const allTouched = inboundJoinFlows.length >= inboundTriggers.length; if (!allTouched) { const remaining = inboundSequenceFlows.filter((inb, i, list) => list.indexOf(inb) === i).length - inboundJoinFlows.length; return logger.debug(`<${id}> inbound ${message.content.action} from <${message.content.id}>, ${remaining} remaining`); } const evaluatedInbound = inboundJoinFlows.splice(0); let taken; const inbound = evaluatedInbound.map((im) => { if (im.fields.routingKey === 'flow.take') taken = true; im.ack(); return cloneContent(im.content); }); const discardSequence = !taken && evaluatedInbound.reduce((result, im) => { if (!im.content.discardSequence) return result; im.content.discardSequence.forEach((sourceId) => { if (result.indexOf(sourceId) === -1) result.push(sourceId); }); return result; }, []); broker.cancel('_run-on-inbound'); if (!taken) return runDiscard({inbound, discardSequence}); return run({inbound}); } function onRunMessage(routingKey, message, messageProperties) { switch (routingKey) { case 'run.outbound.discard': case 'run.outbound.take': case 'run.next': return continueRunMessage(routingKey, message, messageProperties); case 'run.resume': { return onResumeMessage(); } } const preStatus = status; status = 'formatting'; return formatter(message, (err, formattedContent, formatted) => { if (err) return emitFatal(err, message.content); if (formatted) message.content = formattedContent; status = preStatus; continueRunMessage(routingKey, message, messageProperties); }); function onResumeMessage() { message.ack(); const {fields} = stateMessage; switch (fields.routingKey) { case 'run.enter': case 'run.start': case 'run.discarded': case 'run.end': case 'run.leave': break; default: return; } if (!fields.redelivered) return; logger.debug(`<${id}> resume from ${message.content.status}`); return broker.publish('run', fields.routingKey, cloneContent(stateMessage.content), stateMessage.properties); } } function continueRunMessage(routingKey, message) { const {fields, content: originalContent, ack} = message; const isRedelivered = fields.redelivered; const content = cloneContent(originalContent); const {correlationId} = message.properties; stateMessage = message; switch (routingKey) { case 'run.enter': { logger.debug(`<${id}> enter`, isRedelivered ? 'redelivered' : ''); status = 'entered'; if (!isRedelivered) { execution = undefined; } if (extensions) extensions.activate(cloneMessage(message), activityApi); if (bpmnIo) bpmnIo.activate(message); if (!isRedelivered) publishEvent('enter', content, {correlationId}); break; } case 'run.discard': { logger.debug(`<${id}> discard`, isRedelivered ? 'redelivered' : ''); status = 'discard'; execution = undefined; if (extensions) extensions.activate(cloneMessage(message), activityApi); if (bpmnIo) bpmnIo.activate(message); if (!isRedelivered) { broker.publish('run', 'run.discarded', content, {correlationId}); publishEvent('discard', content); } break; } case 'run.start': { logger.debug(`<${id}> start`, isRedelivered ? 'redelivered' : ''); status = 'started'; if (!isRedelivered) { broker.publish('run', 'run.execute', content, {correlationId}); publishEvent('start', content, {correlationId}); } break; } case 'run.execute.passthrough': { if (!isRedelivered && execution) { executeMessage = message; return execution.passthrough(message); } } case 'run.execute': { status = 'executing'; executeMessage = message; executionQ.assertConsumer(onExecutionMessage, {exclusive: true, consumerTag: '_activity-execution'}); execution = execution || ActivityExecution(activityApi, context); if (isRedelivered) { return resumeExtensions(message, (err, formattedContent) => { if (err) return emitFatal(err, message.content); if (formattedContent) message.content = formattedContent; status = 'executing'; return execution.execute(message); }); } return execution.execute(message); } case 'run.end': { if (status === 'end') break; counters.taken++; status = 'end'; if (isRedelivered) break; return doRunLeave(false, () => { publishEvent('end', content, {correlationId}); if (!step) ack(); }); } case 'run.error': { publishEvent('error', cloneContent(content, { error: fields.redelivered ? makeErrorFromMessage(message) : content.error, }), {correlationId}); break; } case 'run.discarded': { logger.debug(`<${executionId} (${id})> discarded`); counters.discarded++; status = 'discarded'; content.outbound = undefined; if (!isRedelivered) { return doRunLeave(true, () => { if (!step) ack(); }); } break; } case 'run.outbound.take': { const flow = getOutboundSequenceFlowById(content.flow.id); ack(); return flow.take(content.flow); } case 'run.outbound.discard': { const flow = getOutboundSequenceFlowById(content.flow.id); ack(); return flow.discard(content.flow); } case 'run.leave': { status = undefined; if (bpmnIo) bpmnIo.deactivate(message); if (extensions) extensions.deactivate(message); if (!isRedelivered) { broker.publish('run', 'run.next', cloneContent(content), {persistent: false}); publishEvent('leave', content, {correlationId}); } break; } case 'run.next': consumeInbound(); break; } if (!step) ack(); function doRunLeave(isDiscarded, onOutbound) { if (content.ignoreOutbound) { broker.publish('run', 'run.leave', cloneContent(content), {correlationId}); if (onOutbound) onOutbound(); return; } return doOutbound(cloneMessage(message), isDiscarded, (err, outbound) => { if (err) { return publishEvent('error', cloneContent(content, {error: err}), {correlationId}); } broker.publish('run', 'run.leave', cloneContent(content, { ...(outbound.length ? {outbound} : undefined), }), {correlationId}); if (onOutbound) onOutbound(); }); } } function resumeExtensions(message, callback) { if (!extensions && !bpmnIo) return callback(); if (extensions) extensions.activate(cloneMessage(message), activityApi); if (bpmnIo) bpmnIo.activate(cloneMessage(message)); status = 'formatting'; return formatter(message, (err, formattedContent, formatted) => { if (err) return callback(err); return callback(null, formatted && formattedContent); }); } function getOutboundSequenceFlowById(flowId) { return outboundSequenceFlows.find((flow) => flow.id === flowId); } function onExecutionMessage(routingKey, message) { const content = cloneContent({ ...executeMessage.content, ...message.content, executionId: executeMessage.content.executionId, parent: {...parent}, }); const {correlationId} = message.properties; publishEvent(routingKey, content, message.properties); switch (routingKey) { case 'execution.outbound.take': { return doOutbound(cloneMessage(message), false, (err, outbound) => { message.ack(); if (err) return emitFatal(err, content); broker.publish('run', 'run.execute.passthrough', cloneContent(content, {outbound})); return ackRunExecuteMessage(); }); } case 'execution.error': { status = 'error'; broker.publish('run', 'run.error', content, {correlationId}); broker.publish('run', 'run.discarded', content, {correlationId}); break; } case 'execution.discard': status = 'discarded'; broker.publish('run', 'run.discarded', content, {correlationId}); break; default: { status = 'executed'; broker.publish('run', 'run.end', content, {correlationId}); } } message.ack(); ackRunExecuteMessage(); function ackRunExecuteMessage() { if (step) return; if (!executeMessage) return; const ackMessage = executeMessage; executeMessage = null; ackMessage.ack(); } } function onApiMessage(routingKey, message) { const messageType = message.properties.type; switch (messageType) { case 'discard': { discardRun(message); break; } case 'stop': { onStop(message); break; } case 'shake': { shakeOutbound(message); break; } } } function shake() { shakeOutbound({content: createMessage()}); } function shakeOutbound(sourceMessage) { const message = cloneMessage(sourceMessage); message.content.sequence = message.content.sequence || []; message.content.sequence.push({id, type}); broker.publish('api', 'activity.shake.start', message.content, {persistent: false, type: 'shake'}); if (isEnd) { return broker.publish('event', 'activity.shake.end', message.content, {persistent: false, type: 'shake'}); } outboundSequenceFlows.forEach((f) => f.shake(message)); } function publishEvent(state, content, messageProperties = {}) { if (!state) return; if (!content) content = createMessage(); broker.publish('event', `activity.${state}`, {...content, state}, { ...messageProperties, type: state, mandatory: state === 'error', persistent: 'persistent' in messageProperties ? messageProperties.persistent : state !== 'stop', }); } function doOutbound(fromMessage, isDiscarded, callback) { if (!outboundSequenceFlows.length) return callback(null, []); const fromContent = fromMessage.content; let discardSequence = fromContent.discardSequence; if (isDiscarded && !discardSequence && attachedTo && fromContent.inbound && fromContent.inbound[0]) { discardSequence = [fromContent.inbound[0].id]; } let outboundFlows; if (isDiscarded) { outboundFlows = outboundSequenceFlows.map((flow) => formatFlowAction(flow, {action: 'discard'})); } else if (fromContent.outbound && fromContent.outbound.length) { outboundFlows = outboundSequenceFlows.map((flow) => formatFlowAction(flow, fromContent.outbound.filter((f) => f.id === flow.id).pop())); } if (outboundFlows) { doRunOutbound(outboundFlows); return callback(null, outboundFlows); } return evaluateOutbound(fromMessage, fromContent.outboundTakeOne, (err, evaluatedOutbound) => { if (err) return callback(new ActivityError(err.message, fromMessage, err)); const outbound = doRunOutbound(evaluatedOutbound); return callback(null, outbound); }); function doRunOutbound(outboundList) { return outboundList.map((outboundFlow) => { const {id: flowId, action} = outboundFlow; broker.publish('run', 'run.outbound.' + action, cloneContent(fromContent, { flow: { ...outboundFlow, sequenceId: getUniqueId(`${flowId}_${action}`), ...(discardSequence ? {discardSequence: discardSequence.slice()} : undefined), }, })); return outboundFlow; }); } } function formatFlowAction(flow, options) { if (!options) options = {action: 'discard'}; const action = options.action; const message = options.message; return { ...options, id: flow.id, action, ...(flow.isDefault ? {isDefault: true} : undefined), ...(message !== undefined ? {message} : undefined), }; } function evaluateOutbound(fromMessage, discardRestAtTake, callback) { let conditionMet; const outbound = {}; if (!outboundSequenceFlows.length) return completed(); const content = fromMessage.content; const message = content.message; const evaluateFlows = outboundSequenceFlows.slice(); const defaultFlowIdx = outboundSequenceFlows.findIndex(({isDefault}) => isDefault); if (defaultFlowIdx > -1) { evaluateFlows.splice(defaultFlowIdx, 1); evaluateFlows.push(outboundSequenceFlows[defaultFlowIdx]); } let takenCount = 0; broker.subscribeTmp('execution', 'evaluate.flow.#', (routingKey, {content: evalContent, ack}) => { const {id: flowId, action} = evalContent; if (action === 'take') { takenCount++; conditionMet = true; } outbound[flowId] = evalContent; if ('result' in evalContent) { logger.debug(`<${content.executionId} (${id})> flow <${flowId}> evaluated to: ${evalContent.result}`); } let nextFlow = evaluateFlows.shift(); if (!nextFlow) return completed(); if (discardRestAtTake && conditionMet) { do { outbound[nextFlow.id] = formatFlowAction(nextFlow, {action: 'discard'}); } while ((nextFlow = evaluateFlows.shift())); return completed(); } if (conditionMet && nextFlow.isDefault) { outbound[nextFlow.id] = formatFlowAction(nextFlow, {action: 'discard'}); return completed(); } ack(); evaluateSequenceFlows(nextFlow); }, {consumerTag: `_flow-evaluation-${executionId}`}); return evaluateSequenceFlows(evaluateFlows.shift()); function completed(err) { broker.cancel(`_flow-evaluation-${executionId}`); if (err) return callback(err); if (!takenCount) { const nonTakenError = new ActivityError(`<${id}> no conditional flow taken`, fromMessage); logger.error(`<${id}>`, nonTakenError); return callback(nonTakenError); } const outboundList = Object.keys(outbound).reduce((result, flowId) => { const flow = outbound[flowId]; result.push({ ...flow, ...(message !== undefined ? {message} : undefined), }); return result; }, []); return callback(null, outboundList); } function evaluateSequenceFlows(flow) { if (!flow) return completed(); if (flow.isDefault) { return broker.publish('execution', 'evaluate.flow.take', formatFlowAction(flow, {action: 'take'}), {persistent: false}); } const flowCondition = flow.getCondition(); if (!flowCondition) { return broker.publish('execution', 'evaluate.flow.take', formatFlowAction(flow, {action: 'take'}), {persistent: false}); } flowCondition.execute(cloneMessage(fromMessage), (err, result) => { if (err) return completed(err); const action = result ? 'take' : 'discard'; return broker.publish('execution', 'evaluate.flow.' + action, formatFlowAction(flow, { action, result, }), {persistent: false}); }); } } function getActivityById(elementId) { return context.getActivityById(elementId); } function getState() { const msg = createMessage(); return { ...msg, status, executionId, stopped, behaviour: {...behaviour}, counters: {...counters}, broker: broker.getState(true), execution: execution && execution.getState(), }; } function next() { if (!step) return; if (!stateMessage) return; if (status === 'executing') return false; if (status === 'formatting') return false; const current = stateMessage; stateMessage.ack(); return current; } function getApi(message) { if (execution && !execution.completed) return execution.getApi(message); return ActivityApi(broker, message || stateMessage); } }
"""Add movie table and movie_genre Revision ID: d11d5359e4ca Revises: Create Date: 2020-09-27 23:20:58.300881 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd11d5359e4ca' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('movie', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('ninety_nine_popularity', sa.Float(), nullable=False), sa.Column('name', sa.String(length=100), nullable=False), sa.Column('director', sa.String(length=100), nullable=False), sa.Column('imdb_score', sa.Float(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), sa.Column('is_deleted', sa.Boolean(), nullable=False), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('name', 'director', name='move_name_director_name') ) op.create_index(op.f('ix_movie_director'), 'movie', ['director'], unique=False) op.create_index(op.f('ix_movie_imdb_score'), 'movie', ['imdb_score'], unique=False) op.create_index(op.f('ix_movie_name'), 'movie', ['name'], unique=False) op.create_index(op.f('ix_movie_ninety_nine_popularity'), 'movie', ['ninety_nine_popularity'], unique=False) op.create_table('movie_genre', sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), sa.Column('name', sa.String(length=100), nullable=False), sa.Column('movie_id', sa.Integer(), nullable=True), sa.Column('is_deleted', sa.Boolean(), nullable=False), sa.ForeignKeyConstraint(['movie_id'], ['movie.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_movie_genre_name'), 'movie_genre', ['name'], unique=False) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_movie_genre_name'), table_name='movie_genre') op.drop_table('movie_genre') op.drop_index(op.f('ix_movie_ninety_nine_popularity'), table_name='movie') op.drop_index(op.f('ix_movie_name'), table_name='movie') op.drop_index(op.f('ix_movie_imdb_score'), table_name='movie') op.drop_index(op.f('ix_movie_director'), table_name='movie') op.drop_table('movie') # ### end Alembic commands ###
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var App = require('app'); App.WizardStep0View = Em.View.extend({ tagName: "form", //todo: why form? attributeBindings: ['autocomplete'], autocomplete: 'off', templateName: require('templates/wizard/step0'), //todo: create property for placeholder(go to template) didInsertElement: function () { $("[rel=popover]").popover({'placement': 'right', 'trigger': 'hover'}); this.get('controller').loadStep(); }, //todo: rename it to class or write comments onError: function () { return this.get('controller.clusterNameError') !== ''; }.property('controller.clusterNameError') }); App.WizardStep0ViewClusterNameInput = Em.TextField.extend({ keyPress: function(event) { if (event.keyCode == 13) { this.get('parentView.controller').submit(); return false; } } });