Best JavaScript code snippet using wpt
DoSuperpixel.py
Source:DoSuperpixel.py
1from point import Point2from EnforceConnectivity import EnforceConnectivity3from preEnforceConnetivity import preEnforceConnectivity4import numpy as np5import sys6import time7from scipy.io import loadmat8from test_utils import compare_matrix9import math10from math import pow11import pickle12DBL_MAX = sys.float_info[0] # max float value13TEST_INITIALIZATION = False14TEST_KMEANS_LABEL = False15FAKE_KMEANS_LABEL = False16TEST_PEC_LABEL = False17FAKE_EC_LABEL = False18# Perform weighted kmeans iteratively in the ten dimensional feature space.19def DoSuperpixel(L1: np.ndarray, L2: np.ndarray, a1: np.ndarray, a2: np.ndarray, b1: np.ndarray, b2: np.ndarray,20 x1: np.ndarray, x2: np.ndarray, y1: np.ndarray, y2: np.ndarray,21 W: np.ndarray, label: np.ndarray, seedArray: list, seedNum: int, nRows: int, nCols: int, StepX: int,22 StepY: int, iterationNum: int, thresholdCoef: int, new_label: np.ndarray):23 if FAKE_KMEANS_LABEL:24 iterationNum = -125 print("\t[{}] [DoSuperpixel.py]: Pre-treatment".format(time.ctime()[11:19]))26 dist = np.empty([nRows, nCols], dtype=np.float64)27 centerL1 = np.empty([seedNum], dtype=np.float64)28 centerL2 = np.empty([seedNum], dtype=np.float64)29 centera1 = np.empty([seedNum], dtype=np.float64)30 centera2 = np.empty([seedNum], dtype=np.float64)31 centerb1 = np.empty([seedNum], dtype=np.float64)32 centerb2 = np.empty([seedNum], dtype=np.float64)33 centerx1 = np.empty([seedNum], dtype=np.float64)34 centerx2 = np.empty([seedNum], dtype=np.float64)35 centery1 = np.empty([seedNum], dtype=np.float64)36 centery2 = np.empty([seedNum], dtype=np.float64)37 WSum = np.empty([seedNum], dtype=np.float64)38 clusterSize = np.empty([seedNum], dtype=np.int32)39 print("\t[{}] [DoSuperpixel.py]: Initialization".format(time.ctime()[11:19]))40 for i in range(seedNum):41 centerL1[i] = 042 centerL2[i] = 043 centera1[i] = 044 centera2[i] = 045 centerb1[i] = 046 centerb2[i] = 047 centerx1[i] = 048 centerx2[i] = 049 centery1[i] = 050 centery2[i] = 051 x = seedArray[i].x52 y = seedArray[i].y53 minX = int(0 if x - StepX // 4 <= 0 else x - StepX // 4)54 minY = int(0 if y - StepY // 4 <= 0 else y - StepY // 4)55 maxX = int(nRows - 1 if x + StepX // 4 >= nRows - 1 else x + StepX // 4)56 maxY = int(nCols - 1 if y + StepY // 4 >= nCols - 1 else y + StepY // 4)57 Count = 058 for j in range(minX, maxX + 1):59 for k in range(minY, maxY + 1):60 Count += 161 centerL1[i] += L1[j][k]62 centerL2[i] += L2[j][k]63 centera1[i] += a1[j][k]64 centera2[i] += a2[j][k]65 centerb1[i] += b1[j][k]66 centerb2[i] += b2[j][k]67 centerx1[i] += x1[j][k]68 centerx2[i] += x2[j][k]69 centery1[i] += y1[j][k]70 centery2[i] += y2[j][k]71 centerL1[i] /= Count72 centerL2[i] /= Count73 centera1[i] /= Count74 centera2[i] /= Count75 centerb1[i] /= Count76 centerb2[i] /= Count77 centerx1[i] /= Count78 centerx2[i] /= Count79 centery1[i] /= Count80 centery2[i] /= Count81 if TEST_INITIALIZATION:82 data = loadmat("test_27_DOS_Initialization_centers.mat")83 print(compare_matrix.compare_1D_array(centerL1, data["tCenterL1"].reshape([200]), 10, 1e-8), end="", flush=True)84 print(compare_matrix.compare_1D_array(centerL2, data["tCenterL2"].reshape([200]), 10, 1e-8), end="", flush=True)85 print(compare_matrix.compare_1D_array(centera1, data["tCentera1"].reshape([200]), 10, 1e-8), end="", flush=True)86 print(compare_matrix.compare_1D_array(centera2, data["tCentera2"].reshape([200]), 10, 1e-8), end="", flush=True)87 print(compare_matrix.compare_1D_array(centerb1, data["tCenterb1"].reshape([200]), 10, 1e-8), end="", flush=True)88 print(compare_matrix.compare_1D_array(centerb2, data["tCenterb2"].reshape([200]), 10, 1e-8), end="", flush=True)89 print(compare_matrix.compare_1D_array(centerx1, data["tCenterx1"].reshape([200]), 10, 1e-8), end="", flush=True)90 print(compare_matrix.compare_1D_array(centerx2, data["tCenterx2"].reshape([200]), 10, 1e-8), end="", flush=True)91 print(compare_matrix.compare_1D_array(centery1, data["tCentery1"].reshape([200]), 10, 1e-8), end="", flush=True)92 print(compare_matrix.compare_1D_array(centery2, data["tCentery2"].reshape([200]), 10, 1e-8), end="", flush=True)93 # exit()94 print("\t[{}] [DoSuperpixel.py]: K-means".format(time.ctime()[11:19]))95 for iteration in range(iterationNum + 1):96 print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_step_1".format(time.ctime()[11:19], iteration))97 for i in range(nRows):98 for j in range(nCols):99 dist[i][j] = DBL_MAX100 for i in range(seedNum):101 # print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_seed{}".format(time.ctime()[11:19], iteration, i))102 x = seedArray[i].x103 y = seedArray[i].y104 minX = int(0 if x - StepX <= 0 else x - StepX)105 minY = int(0 if y - StepY <= 0 else y - StepY)106 maxX = int(nRows - 1 if x + StepX >= nRows - 1 else x + StepX)107 maxY = int(nCols - 1 if y + StepY >= nCols - 1 else y + StepY)108 # my implementation start109 step1_min_x = minX110 step1_max_x = maxX + 1111 step1_min_y = minY112 step1_max_y = maxY + 1113 step1_vpow = np.vectorize(lambda _: _ * _)114 step1_L1_pow = step1_vpow(L1[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerL1[i])115 step1_L2_pow = step1_vpow(L2[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerL2[i])116 step1_a1_pow = step1_vpow(a1[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centera1[i])117 step1_a2_pow = step1_vpow(a2[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centera2[i])118 step1_b1_pow = step1_vpow(b1[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerb1[i])119 step1_b2_pow = step1_vpow(b2[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerb2[i])120 step1_x1_pow = step1_vpow(x1[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerx1[i])121 step1_x2_pow = step1_vpow(x2[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centerx2[i])122 step1_y1_pow = step1_vpow(y1[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centery1[i])123 step1_y2_pow = step1_vpow(y2[step1_min_x:step1_max_x, step1_min_y: step1_max_y] - centery2[i])124 step1_D = step1_L1_pow + step1_L2_pow + step1_a1_pow + step1_a2_pow + step1_b1_pow + step1_b2_pow + \125 step1_x1_pow + step1_x2_pow + step1_y1_pow + step1_y2_pow126 step1_if = (step1_D - dist[step1_min_x: step1_max_x, step1_min_y: step1_max_y] < 0).astype(np.uint16)127 step1_neg_if = 1 - step1_if128 new_label[step1_min_x: step1_max_x, step1_min_y: step1_max_y] *= step1_neg_if129 new_label[step1_min_x: step1_max_x, step1_min_y: step1_max_y] += (step1_if * i)130 dist[step1_min_x: step1_max_x, step1_min_y: step1_max_y] *= step1_neg_if131 step1_D_to_plus = step1_D * step1_if132 dist[step1_min_x: step1_max_x, step1_min_y: step1_max_y] += step1_D_to_plus133 # my implementation end134 # previous implementation start135 # for m in range(minX, maxX + 1):136 # for n in range(minY, maxY + 1):137 # D = (L1[m][n] - centerL1[i]) * (L1[m][n] - centerL1[i]) + \138 # (L2[m][n] - centerL2[i]) * (L2[m][n] - centerL2[i]) + \139 # (a1[m][n] - centera1[i]) * (a1[m][n] - centera1[i]) + \140 # (a2[m][n] - centera2[i]) * (a2[m][n] - centera2[i]) + \141 # (b1[m][n] - centerb1[i]) * (b1[m][n] - centerb1[i]) + \142 # (b2[m][n] - centerb2[i]) * (b2[m][n] - centerb2[i]) + \143 # (x1[m][n] - centerx1[i]) * (x1[m][n] - centerx1[i]) + \144 # (x2[m][n] - centerx2[i]) * (x2[m][n] - centerx2[i]) + \145 # (y1[m][n] - centery1[i]) * (y1[m][n] - centery1[i]) + \146 # (y2[m][n] - centery2[i]) * (y2[m][n] - centery2[i])147 # if D < dist[m][n]:148 # label[m * nCols + n] = i149 # dist[m][n] = D150 # previous implementation end151 print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_step_2".format(time.ctime()[11:19], iteration))152 for i in range(seedNum):153 centerL1[i] = 0154 centerL2[i] = 0155 centera1[i] = 0156 centera2[i] = 0157 centerb1[i] = 0158 centerb2[i] = 0159 centerx1[i] = 0160 centerx2[i] = 0161 centery1[i] = 0162 centery2[i] = 0163 WSum[i] = 0164 clusterSize[i] = 0165 seedArray[i].x = 0166 seedArray[i].y = 0167 print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_step_3".format(time.ctime()[11:19], iteration))168 label = new_label.copy().reshape([nRows * nCols])169 # my implementation start : tested but slow (~= 17s)170 # step3_WL1 = W * L1171 # step3_WL2 = W * L2172 # step3_Wa1 = W * a1173 # step3_Wa2 = W * a2174 # step3_Wb1 = W * b1175 # step3_Wb2 = W * b2176 # step3_Wx1 = W * x1177 # step3_Wx2 = W * x2178 # step3_Wy1 = W * y1179 # step3_Wy2 = W * y2180 # for L in range(seedNum):181 # if L % 50 == 0:182 # print("\t\t\t\t[{}] [DEBUG]: seedNum{}".format(time.ctime()[11:19], L))183 # add_range_matrix = (new_label == L)184 # centerL1[L] += (step3_WL1 * add_range_matrix).sum()185 # centerL2[L] += (step3_WL2 * add_range_matrix).sum()186 # centera1[L] += (step3_Wa1 * add_range_matrix).sum()187 # centera2[L] += (step3_Wa2 * add_range_matrix).sum()188 # centerb1[L] += (step3_Wb1 * add_range_matrix).sum()189 # centerb2[L] += (step3_Wb2 * add_range_matrix).sum()190 # centerx1[L] += (step3_Wx1 * add_range_matrix).sum()191 # centerx2[L] += (step3_Wx2 * add_range_matrix).sum()192 # centery1[L] += (step3_Wy1 * add_range_matrix).sum()193 # centery2[L] += (step3_Wy2 * add_range_matrix).sum()194 # clusterSize[L] += add_range_matrix.sum()195 # WSum[L] += (W * add_range_matrix).sum()196 # seedArray[L].x, seedArray[L].y = np.sum(a=np.argwhere(add_range_matrix), axis=0)197 # my implementation end198 # previous implementation start (~= 10s)199 for i in range(nRows):200 for j in range(nCols):201 L = label[i * nCols + j] # int202 Weight = W[i][j] # double203 centerL1[L] += Weight * L1[i][j]204 centerL2[L] += Weight * L2[i][j]205 centera1[L] += Weight * a1[i][j]206 centera2[L] += Weight * a2[i][j]207 centerb1[L] += Weight * b1[i][j]208 centerb2[L] += Weight * b2[i][j]209 centerx1[L] += Weight * x1[i][j]210 centerx2[L] += Weight * x2[i][j]211 centery1[L] += Weight * y1[i][j]212 centery2[L] += Weight * y2[i][j]213 clusterSize[L] += 1214 WSum[L] += Weight215 seedArray[L].x += i216 seedArray[L].y += j217 # previous implementation end218 print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_step_4".format(time.ctime()[11:19], iteration))219 for i in range(seedNum):220 WSum[i] = 1 if WSum[i] == 0 else WSum[i]221 clusterSize[i] = 1 if clusterSize[i] == 0 else clusterSize[i]222 print("\t\t[{}] [DoSuperpixel.py]: K-means_iter_{}_step_5".format(time.ctime()[11:19], iteration))223 for i in range(seedNum):224 centerL1[i] /= WSum[i]225 centerL2[i] /= WSum[i]226 centera1[i] /= WSum[i]227 centera2[i] /= WSum[i]228 centerb1[i] /= WSum[i]229 centerb2[i] /= WSum[i]230 centerx1[i] /= WSum[i]231 centerx2[i] /= WSum[i]232 centery1[i] /= WSum[i]233 centery2[i] /= WSum[i]234 seedArray[i].x /= clusterSize[i]235 seedArray[i].y /= clusterSize[i]236 if FAKE_KMEANS_LABEL:237 label = pickle.load(open("test_dump_data\\test_27_DOS_label_iter20.pydump", 'rb'))238 if TEST_KMEANS_LABEL:239 data = loadmat("test_matlab_data\\test_27_DOS_label_after_KMEANS.mat")240 print(compare_matrix.compare_2D_matrix(label.reshape([nRows, nCols]).transpose([1, 0]), data["tLabel"]))241 exit()242 threshold = int((nRows * nCols) / (seedNum * thresholdCoef))243 preEnforceConnectivity(label, nRows, nCols)244 if TEST_PEC_LABEL:245 data = loadmat("test_matlab_data\\test_27_DOS_label_after_PEC.mat")246 print(compare_matrix.compare_2D_matrix(label.reshape([nRows, nCols]).transpose([1, 0]), data["tLabel"]))247 exit()248 if FAKE_EC_LABEL:249 label = loadmat("test_matlab_data\\FINAL.mat")["label"].transpose([1, 0]).reshape([nRows * nCols])250 else:251 label = EnforceConnectivity(L1, L2, a1, a2, b1, b2, x1, x2, y1, y2, W, label, threshold, nRows, nCols)...
forms.py
Source:forms.py
1from __future__ import unicode_literals2from django import forms, http3from django.conf import settings4from django.db import models5from django.test import TestCase6from django.template.response import TemplateResponse7from django.utils.importlib import import_module8from django.contrib.auth.models import User9from django.contrib.formtools.wizard.views import (WizardView,10 SessionWizardView,11 CookieWizardView)12class DummyRequest(http.HttpRequest):13 def __init__(self, POST=None):14 super(DummyRequest, self).__init__()15 self.method = POST and "POST" or "GET"16 if POST is not None:17 self.POST.update(POST)18 self.session = {}19 self._dont_enforce_csrf_checks = True20def get_request(*args, **kwargs):21 request = DummyRequest(*args, **kwargs)22 engine = import_module(settings.SESSION_ENGINE)23 request.session = engine.SessionStore(None)24 return request25class Step1(forms.Form):26 name = forms.CharField()27class Step2(forms.Form):28 name = forms.CharField()29class Step3(forms.Form):30 data = forms.CharField()31class CustomKwargsStep1(Step1):32 def __init__(self, test=None, *args, **kwargs):33 self.test = test34 return super(CustomKwargsStep1, self).__init__(*args, **kwargs)35class TestModel(models.Model):36 name = models.CharField(max_length=100)37 class Meta:38 app_label = 'formtools'39class TestModelForm(forms.ModelForm):40 class Meta:41 model = TestModel42TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2)43class TestWizard(WizardView):44 storage_name = 'django.contrib.formtools.wizard.storage.session.SessionStorage'45 def dispatch(self, request, *args, **kwargs):46 response = super(TestWizard, self).dispatch(request, *args, **kwargs)47 return response, self48 def get_form_kwargs(self, step, *args, **kwargs):49 kwargs = super(TestWizard, self).get_form_kwargs(step, *args, **kwargs)50 if step == 'kwargs_test':51 kwargs['test'] = True52 return kwargs53class FormTests(TestCase):54 def test_form_init(self):55 testform = TestWizard.get_initkwargs([Step1, Step2])56 self.assertEqual(testform['form_list'], {'0': Step1, '1': Step2})57 testform = TestWizard.get_initkwargs([('start', Step1), ('step2', Step2)])58 self.assertEqual(59 testform['form_list'], {'start': Step1, 'step2': Step2})60 testform = TestWizard.get_initkwargs([Step1, Step2, ('finish', Step3)])61 self.assertEqual(62 testform['form_list'], {'0': Step1, '1': Step2, 'finish': Step3})63 def test_first_step(self):64 request = get_request()65 testform = TestWizard.as_view([Step1, Step2])66 response, instance = testform(request)67 self.assertEqual(instance.steps.current, '0')68 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])69 response, instance = testform(request)70 self.assertEqual(instance.steps.current, 'start')71 def test_persistence(self):72 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])73 request = get_request({'test_wizard-current_step': 'start',74 'name': 'data1'})75 response, instance = testform(request)76 self.assertEqual(instance.steps.current, 'start')77 instance.storage.current_step = 'step2'78 testform2 = TestWizard.as_view([('start', Step1), ('step2', Step2)])79 request.POST = {'test_wizard-current_step': 'step2'}80 response, instance = testform2(request)81 self.assertEqual(instance.steps.current, 'step2')82 def test_form_condition(self):83 request = get_request()84 testform = TestWizard.as_view(85 [('start', Step1), ('step2', Step2), ('step3', Step3)],86 condition_dict={'step2': True})87 response, instance = testform(request)88 self.assertEqual(instance.get_next_step(), 'step2')89 testform = TestWizard.as_view(90 [('start', Step1), ('step2', Step2), ('step3', Step3)],91 condition_dict={'step2': False})92 response, instance = testform(request)93 self.assertEqual(instance.get_next_step(), 'step3')94 def test_form_kwargs(self):95 request = get_request()96 testform = TestWizard.as_view([('start', Step1),97 ('kwargs_test', CustomKwargsStep1)])98 response, instance = testform(request)99 self.assertEqual(instance.get_form_kwargs('start'), {})100 self.assertEqual(instance.get_form_kwargs('kwargs_test'), {'test': True})101 self.assertEqual(instance.get_form('kwargs_test').test, True)102 def test_form_prefix(self):103 request = get_request()104 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])105 response, instance = testform(request)106 self.assertEqual(instance.get_form_prefix(), 'start')107 self.assertEqual(instance.get_form_prefix('another'), 'another')108 def test_form_initial(self):109 request = get_request()110 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)],111 initial_dict={'start': {'name': 'value1'}})112 response, instance = testform(request)113 self.assertEqual(instance.get_form_initial('start'), {'name': 'value1'})114 self.assertEqual(instance.get_form_initial('step2'), {})115 def test_form_instance(self):116 request = get_request()117 the_instance = TestModel()118 testform = TestWizard.as_view([('start', TestModelForm), ('step2', Step2)],119 instance_dict={'start': the_instance})120 response, instance = testform(request)121 self.assertEqual(122 instance.get_form_instance('start'),123 the_instance)124 self.assertEqual(125 instance.get_form_instance('non_exist_instance'),126 None)127 def test_formset_instance(self):128 request = get_request()129 the_instance1, created = TestModel.objects.get_or_create(130 name='test object 1')131 the_instance2, created = TestModel.objects.get_or_create(132 name='test object 2')133 testform = TestWizard.as_view([('start', TestModelFormSet), ('step2', Step2)],134 instance_dict={'start': TestModel.objects.filter(name='test object 1')})135 response, instance = testform(request)136 self.assertEqual(list(instance.get_form_instance('start')), [the_instance1])137 self.assertEqual(instance.get_form_instance('non_exist_instance'), None)138 self.assertEqual(instance.get_form().initial_form_count(), 1)139 def test_done(self):140 request = get_request()141 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])142 response, instance = testform(request)143 self.assertRaises(NotImplementedError, instance.done, None)144 def test_revalidation(self):145 request = get_request()146 testform = TestWizard.as_view([('start', Step1), ('step2', Step2)])147 response, instance = testform(request)148 instance.render_done(None)149 self.assertEqual(instance.storage.current_step, 'start')150class SessionFormTests(TestCase):151 def test_init(self):152 request = get_request()153 testform = SessionWizardView.as_view([('start', Step1)])154 self.assertTrue(isinstance(testform(request), TemplateResponse))155class CookieFormTests(TestCase):156 def test_init(self):157 request = get_request()158 testform = CookieWizardView.as_view([('start', Step1)])...
index.js
Source:index.js
1import Vue from 'vue'2import Router from 'vue-router'3import Layout from '@comp/layout/index'4import HomeIndex from '@page/home/index'5import LoginIndex from '@page/login/index'6import ActivityIndex from '@page/activity/index'7import MessageIndex from '@page/message/MessageIndex'8import MessageDetail from '@page/message/MessageDetail'9import RecruitmentIndex from '@page/message/RecruitmentIndex'10import RecruitmentDetail from '@page/message/RecruitmentDetail'11import PolicyIndex from '@page/policy/index'12import ActivityView from '@page/activity/view'13import TenementRepairsStep1 from '@page/serve/TenementRepairs/step1'14import TenementRepairsStep2 from '@page/serve/TenementRepairs/step2'15import TenementAppealStep1 from '@page/serve/TenementAppeal/step1'16import TenementAppealStep2 from '@page/serve/TenementAppeal/step2'17import DemandSubmissionStep1 from '@page/serve/DemandSubmission/step1'18import DemandSubmissionStep2 from '@page/serve/DemandSubmission/step2'19import ParkingApplyStep1 from '@page/serve/ParkingApply/step1'20import ParkingApplyStep2 from '@page/serve/ParkingApply/step2'21import ItRepairsStep1 from '@page/serve/ItRepairs/step1'22import ItRepairsStep2 from '@page/serve/ItRepairs/step2'23import AdvertisingApplyStep1 from '@page/serve/AdvertisingApply/step1'24import AdvertisingApplyStep2 from '@page/serve/AdvertisingApply/step2'25import PublicFacilitiesStep1 from '@page/serve/PublicFacilities/step1'26import PublicFacilitiesStep2 from '@page/serve/PublicFacilities/step2'27import EnterprisesRecordStep1 from '@page/serve/EnterprisesRecord/step1'28import EnterprisesRecordStep2 from '@page/serve/EnterprisesRecord/step2'29import RubbishDispositionStep1 from '@page/serve/RubbishDisposition/step1'30import RubbishDispositionStep2 from '@page/serve/RubbishDisposition/step2'31import UrbanRoadStep1 from '@page/serve/UrbanRoad/step1'32import UrbanRoadStep2 from '@page/serve/UrbanRoad/step2'33import NewLandProjectStep1 from '@page/serve/NewLandProject/step1'34import NewLandProjectStep2 from '@page/serve/NewLandProject/step2'35import NewRentalProjectStep1 from '@page/serve/NewRentalProject/step1'36import NewRentalProjectStep2 from '@page/serve/NewRentalProject/step2'37import NewTechProjectStep1 from '@page/serve/NewTechProject/step1'38import NewTechProjectStep2 from '@page/serve/NewTechProject/step2'39import ConferenceReservation from '@page/serve/ConferenceReservation/List'40import AdvertisingReservation from '@page/serve/AdvertisingReservation/List'41Vue.use(Router)42export default new Router({43 mode: 'history',44 routes: [45 {46 path: '/',47 component: Layout,48 children: [49 { path: 'home/index', name: 'HomeIndex', component: HomeIndex },50 { path: 'login/index', name: 'LoginIndex', component: LoginIndex },51 { path: 'activity/index', name: 'ActivityIndex', component: ActivityIndex },52 { path: 'message/index/:id', name: 'MessageIndex', component: MessageIndex },53 { path: 'message/detail/:id', name: 'MessageDetail', component: MessageDetail },54 { path: 'message/RecruitmentIndex', name: 'RecruitmentIndex', component: RecruitmentIndex },55 { path: 'message/RecruitmentDetail/:id', name: 'RecruitmentDetail', component: RecruitmentDetail },56 { path: 'policy/index', name: 'PolicyIndex', component: PolicyIndex },57 { path: 'activity/view/:id', name: 'ActivityView', component: ActivityView },58 { path: 'serve/TenementRepairs/step1', name: 'TenementRepairsStep1', component: TenementRepairsStep1 },59 { path: 'serve/TenementRepairs/step2', name: 'TenementRepairsStep2', component: TenementRepairsStep2 },60 { path: 'serve/TenementAppeal/step1', name: 'TenementAppealStep1', component: TenementAppealStep1 },61 { path: 'serve/TenementAppeal/step2', name: 'TenementAppealStep2', component: TenementAppealStep2 },62 { path: 'serve/DemandSubmission/step1', name: 'DemandSubmissionStep1', component: DemandSubmissionStep1 },63 { path: 'serve/DemandSubmission/step2', name: 'DemandSubmissionStep2', component: DemandSubmissionStep2 },64 { path: 'serve/ParkingApply/step1', name: 'ParkingApplyStep1', component: ParkingApplyStep1 },65 { path: 'serve/ParkingApply/step2', name: 'ParkingApplyStep2', component: ParkingApplyStep2 },66 { path: 'serve/ItRepairs/step1', name: 'ItRepairsStep1', component: ItRepairsStep1 },67 { path: 'serve/ItRepairs/step2', name: 'ItRepairsStep2', component: ItRepairsStep2 },68 { path: 'serve/AdvertisingApply/step1/:id', name: 'AdvertisingApplyStep1', component: AdvertisingApplyStep1 },69 { path: 'serve/AdvertisingApply/step2', name: 'AdvertisingApplyStep2', component: AdvertisingApplyStep2 },70 { path: 'serve/PublicFacilities/step1', name: 'PublicFacilitiesStep1', component: PublicFacilitiesStep1 },71 { path: 'serve/PublicFacilities/step2', name: 'PublicFacilitiesStep2', component: PublicFacilitiesStep2 },72 { path: 'serve/EnterprisesRecord/step1', name: 'EnterprisesRecordStep1', component: EnterprisesRecordStep1 },73 { path: 'serve/EnterprisesRecord/step2', name: 'EnterprisesRecordStep2', component: EnterprisesRecordStep2 },74 { path: 'serve/RubbishDisposition/step1', name: 'RubbishDispositionStep1', component: RubbishDispositionStep1 },75 { path: 'serve/RubbishDisposition/step2', name: 'RubbishDispositionStep2', component: RubbishDispositionStep2 },76 { path: 'serve/UrbanRoad/step1', name: 'UrbanRoadStep1', component: UrbanRoadStep1 },77 { path: 'serve/UrbanRoad/step2', name: 'UrbanRoadStep2', component: UrbanRoadStep2 },78 { path: 'serve/NewLandProject/step1', name: 'NewLandProjectStep1', component: NewLandProjectStep1 },79 { path: 'serve/NewLandProject/step2', name: 'NewLandProjectStep2', component: NewLandProjectStep2 },80 { path: 'serve/NewRentalProject/step1', name: 'NewRentalProjectStep1', component: NewRentalProjectStep1 },81 { path: 'serve/NewRentalProject/step2', name: 'NewRentalProjectStep2', component: NewRentalProjectStep2 },82 { path: 'serve/NewTechProject/step1', name: 'NewTechProjectStep1', component: NewTechProjectStep1 },83 { path: 'serve/NewTechProject/step2', name: 'NewTechProjectStep2', component: NewTechProjectStep2 },84 { path: 'serve/ConferenceReservation', name: 'ConferenceReservation', component: ConferenceReservation },85 { path: 'serve/AdvertisingReservation', name: 'AdvertisingReservation', component: AdvertisingReservation },86 ]87 }88 ]...
wizardStep1.js
Source:wizardStep1.js
1import {2 STEP1_UPDATE_GENDER_ACTION, STEP1_UPDATE_AGE_ACTION, STEP1_VALIDATION_ERRORS_ACTION, STEP1_CLEAR_VALIDATION_ERRORS_ACTION3} from '../actions/types';4import { isEmpty } from '../../helpers/validationHelper';5const validationFunction = function (currentState) {6 if (currentState.step1_ageInterval === false) {7 return !isEmpty(currentState.step1_age);8 } else if ( isEmpty(currentState.step1_ageIntervalFrom) || 9 isEmpty(currentState.step1_ageIntervalTo) ) {10 return false;11 }12 return (currentState.step1_ageIntervalFrom < currentState.step1_ageIntervalTo);13}14const step1InitialState = {15 step1_gender : '1',16 step1_age : null,17 step1_ageClass : '',18 step1_ageInterval : false,19 step1_ageIntervalFrom : null,20 step1_ageIntervalFromClass : '',21 step1_ageIntervalTo : null,22 step1_ageIntervalToClass : '',23 step1_validationError : false,24 step1_validationFunction : validationFunction25}26const wizardStep1 = (state = step1InitialState, action) => {27 switch (action.type) {28 case STEP1_UPDATE_GENDER_ACTION:29 return handleUpdateGenderAction(state, action);30 case STEP1_UPDATE_AGE_ACTION:31 return handleUpdateAgeAction(state, action);32 case STEP1_VALIDATION_ERRORS_ACTION:33 return handleValidationErrorsAction(state);34 case STEP1_CLEAR_VALIDATION_ERRORS_ACTION:35 return handleClearValidationErrorsAction(state);36 default:37 return state;38 }39}40const handleUpdateGenderAction = (state, action) => {41 return {42 ...state,43 step1_gender : action.data44 };45}46const handleUpdateAgeAction = (state, action) => {47 return {48 ...state,49 step1_age : action.data.age,50 step1_ageInterval : action.data.ageInterval,51 step1_ageIntervalFrom : action.data.ageFrom,52 step1_ageIntervalTo : action.data.ageTo53 };54}55const handleValidationErrorsAction = (state) => {56 let ageClass = '';57 let ageIntervalFromClass = '';58 let ageIntervalToClass = '';59 if (state.step1_ageInterval === false) {60 ageClass = 'inputError';61 } else if ( (isEmpty(state.step1_ageIntervalFrom) && isEmpty(state.step1_ageIntervalTo)) || 62 (!isEmpty(state.step1_ageIntervalFrom) && !isEmpty(state.step1_ageIntervalTo)) ) {63 ageIntervalFromClass = 'inputError';64 ageIntervalToClass = 'inputError';65 } else if (isEmpty(state.step1_ageIntervalFrom)) {66 ageIntervalFromClass = 'inputError';67 } else {68 ageIntervalToClass = 'inputError';69 }70 return {71 ...state,72 step1_validationError : true,73 step1_ageClass : ageClass,74 step1_ageIntervalFromClass : ageIntervalFromClass,75 step1_ageIntervalToClass : ageIntervalToClass 76 };77}78const handleClearValidationErrorsAction = (state) => {79 return {80 ...state,81 step1_validationError : false,82 step1_ageClass : '',83 step1_ageIntervalFromClass : '',84 step1_ageIntervalToClass : '' 85 };86}...
taskStep.test.ts
Source:taskStep.test.ts
1process.env.NODE_ENV = 'test';2import {expect} from 'chai';3import 'mocha';4import {TaskStep1} from './task/task1';5describe('task step', () => {6 it('should run one step', async () => {7 const taskStep1 = new TaskStep1({value: 'demo', roll: 0});8 const taskStepPromise = taskStep1.wait();9 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'init', value: 'demo', roll: 0});10 taskStep1.status('pending'); // we can only run pending task step11 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'pending', value: 'demo', roll: 0});12 const data = await taskStep1.action();13 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'success', value: 'demo', roll: 1});14 expect(data).to.be.eql({data: 'demo world!'});15 await taskStep1.cancel();16 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'init', value: 'demo', roll: 0});17 expect(await taskStepPromise).to.be.eql({data: 'demo world!'});18 });19 it('should run one step and wait after done', async () => {20 const taskStep1 = new TaskStep1({value: 'demo', roll: 0});21 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'init', value: 'demo', roll: 0});22 taskStep1.status('pending'); // we can only run pending task step23 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'pending', value: 'demo', roll: 0});24 const data = await taskStep1.action();25 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'success', value: 'demo', roll: 1});26 expect(data).to.be.eql({data: 'demo world!'});27 await taskStep1.cancel();28 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'init', value: 'demo', roll: 0});29 const taskStepPromise = taskStep1.wait();30 expect(await taskStepPromise).to.be.eql({data: 'demo world!'});31 });32 it('should fail run action', async () => {33 const taskStep1 = new TaskStep1({value: 'error', roll: 0});34 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'init', value: 'error', roll: 0});35 taskStep1.status('pending'); // we can only run pending task step36 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'pending', value: 'error', roll: 0});37 try {38 await taskStep1.action();39 throw new Error('should not be here');40 } catch (err: any) {41 expect(err.message).to.be.eql('action error');42 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'failure', value: 'error', roll: 0});43 }44 try {45 await taskStep1.cancel();46 throw new Error('should not be here');47 } catch (err: any) {48 expect(err.message).to.be.eql('TaskStep not in success state');49 expect(taskStep1.toJSON()).to.be.eql({key: 'step1', status: 'failure', value: 'error', roll: 0});50 }51 });...
Using AI Code Generation
1wpt.step1();2wpt.step2();3wpt.step3();4wpt.step4();5wpt.step5();6wpt.step6();7wpt.step7();8wpt.step8();9wpt.step9();10wpt.step10();11wpt.step11();12wpt.step12();13wpt.step13();14wpt.step14();15wpt.step15();16wpt.step16();17wpt.step17();18wpt.step18();19wpt.step19();20wpt.step20();21wpt.step21();22wpt.step22();23wpt.step23();
Using AI Code Generation
1var wpt = require('./wpt.js');2wpt.step1(url, function(err, data) {3 if (err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var request = require('request');10exports.step1 = function(url, callback) {11 request(url + url, function(err, resp, body) {12 if (err) {13 callback(err);14 } else {15 callback(null, body);16 }17 });18}19var request = require('request');20exports.step1 = function(url, callback) {21 request(url + url, function(err, resp, body) {22 if (err) {23 callback(err);24 } else {25 callback(null, body);26 }27 });28};29exports.step2 = function(testId, callback) {30 if (err) {31 callback(err);32 } else {33 callback(null, body);34 }35 });36};37var request = require('request');38exports.step1 = function(url, callback) {39 request(url + url, function(err, resp, body) {40 if (err) {41 callback(err);42 } else {43 callback(null, body);44 }45 });46};
Using AI Code Generation
1var wpt = require('./wpt.js');2 console.log('step1 callback');3 if (err) {4 console.log(err);5 }6 else {7 console.log(data);8 }9});10var request = require('request');11var wpt = {};12wpt.step1 = function(url, callback) {13 console.log('step1');14 var options = {15 qs: {16 }17 };18 request(options, function(err, response, body) {19 console.log('step1 request');20 if (err) {21 console.log('step1 error');22 callback(err, null);23 }24 else {25 console.log('step1 success');26 callback(null, body);27 }28 });29};30module.exports = wpt;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!