Best JavaScript code snippet using wpt
ism.py
Source:ism.py
1from __future__ import unicode_literals2import time3import binascii4import io5from .fragment import FragmentFD6from ..compat import (7 compat_Struct,8 compat_urllib_error,9)10u8 = compat_Struct('>B')11u88 = compat_Struct('>Bx')12u16 = compat_Struct('>H')13u1616 = compat_Struct('>Hxx')14u32 = compat_Struct('>I')15u64 = compat_Struct('>Q')16s88 = compat_Struct('>bx')17s16 = compat_Struct('>h')18s1616 = compat_Struct('>hxx')19s32 = compat_Struct('>i')20unity_matrix = (s32.pack(0x10000) + s32.pack(0) * 3) * 2 + s32.pack(0x40000000)21TRACK_ENABLED = 0x122TRACK_IN_MOVIE = 0x223TRACK_IN_PREVIEW = 0x424SELF_CONTAINED = 0x125def box(box_type, payload):26 return u32.pack(8 + len(payload)) + box_type + payload27def full_box(box_type, version, flags, payload):28 return box(box_type, u8.pack(version) + u32.pack(flags)[1:] + payload)29def write_piff_header(stream, params):30 track_id = params['track_id']31 fourcc = params['fourcc']32 duration = params['duration']33 timescale = params.get('timescale', 10000000)34 language = params.get('language', 'und')35 height = params.get('height', 0)36 width = params.get('width', 0)37 is_audio = width == 0 and height == 038 creation_time = modification_time = int(time.time())39 ftyp_payload = b'isml' # major brand40 ftyp_payload += u32.pack(1) # minor version41 ftyp_payload += b'piff' + b'iso2' # compatible brands42 stream.write(box(b'ftyp', ftyp_payload)) # File Type Box43 mvhd_payload = u64.pack(creation_time)44 mvhd_payload += u64.pack(modification_time)45 mvhd_payload += u32.pack(timescale)46 mvhd_payload += u64.pack(duration)47 mvhd_payload += s1616.pack(1) # rate48 mvhd_payload += s88.pack(1) # volume49 mvhd_payload += u16.pack(0) # reserved50 mvhd_payload += u32.pack(0) * 2 # reserved51 mvhd_payload += unity_matrix52 mvhd_payload += u32.pack(0) * 6 # pre defined53 mvhd_payload += u32.pack(0xffffffff) # next track id54 moov_payload = full_box(b'mvhd', 1, 0, mvhd_payload) # Movie Header Box55 tkhd_payload = u64.pack(creation_time)56 tkhd_payload += u64.pack(modification_time)57 tkhd_payload += u32.pack(track_id) # track id58 tkhd_payload += u32.pack(0) # reserved59 tkhd_payload += u64.pack(duration)60 tkhd_payload += u32.pack(0) * 2 # reserved61 tkhd_payload += s16.pack(0) # layer62 tkhd_payload += s16.pack(0) # alternate group63 tkhd_payload += s88.pack(1 if is_audio else 0) # volume64 tkhd_payload += u16.pack(0) # reserved65 tkhd_payload += unity_matrix66 tkhd_payload += u1616.pack(width)67 tkhd_payload += u1616.pack(height)68 trak_payload = full_box(b'tkhd', 1, TRACK_ENABLED | TRACK_IN_MOVIE | TRACK_IN_PREVIEW, tkhd_payload) # Track Header Box69 mdhd_payload = u64.pack(creation_time)70 mdhd_payload += u64.pack(modification_time)71 mdhd_payload += u32.pack(timescale)72 mdhd_payload += u64.pack(duration)73 mdhd_payload += u16.pack(((ord(language[0]) - 0x60) << 10) | ((ord(language[1]) - 0x60) << 5) | (ord(language[2]) - 0x60))74 mdhd_payload += u16.pack(0) # pre defined75 mdia_payload = full_box(b'mdhd', 1, 0, mdhd_payload) # Media Header Box76 hdlr_payload = u32.pack(0) # pre defined77 hdlr_payload += b'soun' if is_audio else b'vide' # handler type78 hdlr_payload += u32.pack(0) * 3 # reserved79 hdlr_payload += (b'Sound' if is_audio else b'Video') + b'Handler\0' # name80 mdia_payload += full_box(b'hdlr', 0, 0, hdlr_payload) # Handler Reference Box81 if is_audio:82 smhd_payload = s88.pack(0) # balance83 smhd_payload += u16.pack(0) # reserved84 media_header_box = full_box(b'smhd', 0, 0, smhd_payload) # Sound Media Header85 else:86 vmhd_payload = u16.pack(0) # graphics mode87 vmhd_payload += u16.pack(0) * 3 # opcolor88 media_header_box = full_box(b'vmhd', 0, 1, vmhd_payload) # Video Media Header89 minf_payload = media_header_box90 dref_payload = u32.pack(1) # entry count91 dref_payload += full_box(b'url ', 0, SELF_CONTAINED, b'') # Data Entry URL Box92 dinf_payload = full_box(b'dref', 0, 0, dref_payload) # Data Reference Box93 minf_payload += box(b'dinf', dinf_payload) # Data Information Box94 stsd_payload = u32.pack(1) # entry count95 sample_entry_payload = u8.pack(0) * 6 # reserved96 sample_entry_payload += u16.pack(1) # data reference index97 if is_audio:98 sample_entry_payload += u32.pack(0) * 2 # reserved99 sample_entry_payload += u16.pack(params.get('channels', 2))100 sample_entry_payload += u16.pack(params.get('bits_per_sample', 16))101 sample_entry_payload += u16.pack(0) # pre defined102 sample_entry_payload += u16.pack(0) # reserved103 sample_entry_payload += u1616.pack(params['sampling_rate'])104 if fourcc == 'AACL':105 sample_entry_box = box(b'mp4a', sample_entry_payload)106 else:107 sample_entry_payload += u16.pack(0) # pre defined108 sample_entry_payload += u16.pack(0) # reserved109 sample_entry_payload += u32.pack(0) * 3 # pre defined110 sample_entry_payload += u16.pack(width)111 sample_entry_payload += u16.pack(height)112 sample_entry_payload += u1616.pack(0x48) # horiz resolution 72 dpi113 sample_entry_payload += u1616.pack(0x48) # vert resolution 72 dpi114 sample_entry_payload += u32.pack(0) # reserved115 sample_entry_payload += u16.pack(1) # frame count116 sample_entry_payload += u8.pack(0) * 32 # compressor name117 sample_entry_payload += u16.pack(0x18) # depth118 sample_entry_payload += s16.pack(-1) # pre defined119 codec_private_data = binascii.unhexlify(params['codec_private_data'].encode('utf-8'))120 if fourcc in ('H264', 'AVC1'):121 sps, pps = codec_private_data.split(u32.pack(1))[1:]122 avcc_payload = u8.pack(1) # configuration version123 avcc_payload += sps[1:4] # avc profile indication + profile compatibility + avc level indication124 avcc_payload += u8.pack(0xfc | (params.get('nal_unit_length_field', 4) - 1)) # complete representation (1) + reserved (11111) + length size minus one125 avcc_payload += u8.pack(1) # reserved (0) + number of sps (0000001)126 avcc_payload += u16.pack(len(sps))127 avcc_payload += sps128 avcc_payload += u8.pack(1) # number of pps129 avcc_payload += u16.pack(len(pps))130 avcc_payload += pps131 sample_entry_payload += box(b'avcC', avcc_payload) # AVC Decoder Configuration Record132 sample_entry_box = box(b'avc1', sample_entry_payload) # AVC Simple Entry133 stsd_payload += sample_entry_box134 stbl_payload = full_box(b'stsd', 0, 0, stsd_payload) # Sample Description Box135 stts_payload = u32.pack(0) # entry count136 stbl_payload += full_box(b'stts', 0, 0, stts_payload) # Decoding Time to Sample Box137 stsc_payload = u32.pack(0) # entry count138 stbl_payload += full_box(b'stsc', 0, 0, stsc_payload) # Sample To Chunk Box139 stco_payload = u32.pack(0) # entry count140 stbl_payload += full_box(b'stco', 0, 0, stco_payload) # Chunk Offset Box141 minf_payload += box(b'stbl', stbl_payload) # Sample Table Box142 mdia_payload += box(b'minf', minf_payload) # Media Information Box143 trak_payload += box(b'mdia', mdia_payload) # Media Box144 moov_payload += box(b'trak', trak_payload) # Track Box145 mehd_payload = u64.pack(duration)146 mvex_payload = full_box(b'mehd', 1, 0, mehd_payload) # Movie Extends Header Box147 trex_payload = u32.pack(track_id) # track id148 trex_payload += u32.pack(1) # default sample description index149 trex_payload += u32.pack(0) # default sample duration150 trex_payload += u32.pack(0) # default sample size151 trex_payload += u32.pack(0) # default sample flags152 mvex_payload += full_box(b'trex', 0, 0, trex_payload) # Track Extends Box153 moov_payload += box(b'mvex', mvex_payload) # Movie Extends Box154 stream.write(box(b'moov', moov_payload)) # Movie Box155def extract_box_data(data, box_sequence):156 data_reader = io.BytesIO(data)157 while True:158 box_size = u32.unpack(data_reader.read(4))[0]159 box_type = data_reader.read(4)160 if box_type == box_sequence[0]:161 box_data = data_reader.read(box_size - 8)162 if len(box_sequence) == 1:163 return box_data164 return extract_box_data(box_data, box_sequence[1:])165 data_reader.seek(box_size - 8, 1)166class IsmFD(FragmentFD):167 """168 Download segments in a ISM manifest169 """170 FD_NAME = 'ism'171 def real_download(self, filename, info_dict):172 segments = info_dict['fragments'][:1] if self.params.get(173 'test', False) else info_dict['fragments']174 ctx = {175 'filename': filename,176 'total_frags': len(segments),177 }178 self._prepare_and_start_frag_download(ctx)179 fragment_retries = self.params.get('fragment_retries', 0)180 skip_unavailable_fragments = self.params.get('skip_unavailable_fragments', True)181 track_written = False182 frag_index = 0183 for i, segment in enumerate(segments):184 frag_index += 1185 if frag_index <= ctx['fragment_index']:186 continue187 count = 0188 while count <= fragment_retries:189 try:190 success, frag_content = self._download_fragment(ctx, segment['url'], info_dict)191 if not success:192 return False193 if not track_written:194 tfhd_data = extract_box_data(frag_content, [b'moof', b'traf', b'tfhd'])195 info_dict['_download_params']['track_id'] = u32.unpack(tfhd_data[4:8])[0]196 write_piff_header(ctx['dest_stream'], info_dict['_download_params'])197 track_written = True198 self._append_fragment(ctx, frag_content)199 break200 except compat_urllib_error.HTTPError as err:201 count += 1202 if count <= fragment_retries:203 self.report_retry_fragment(err, frag_index, count, fragment_retries)204 if count > fragment_retries:205 if skip_unavailable_fragments:206 self.report_skip_fragment(frag_index)207 continue208 self.report_error('giving up after %s fragment retries' % fragment_retries)209 return False210 self._finish_frag_download(ctx)...
posts.js
Source:posts.js
1import Vue from 'vue';2import throttle from 'lodash.throttle';3export const state = () => ({4 mainPosts: [],5 hasMorePost: true,6 imagePaths: [],7 modifyImagePaths: [],8});9const limit = 10;10export const mutations = {11 addMainPost(state, payload) {12 state.mainPosts.unshift(payload); //ìê¸ì´ ììì¤ëë¡13 state.imagePaths = [];14 },15 modifyMainPost(state, payload) {16 const index = state.mainPosts.findIndex(v => v.id === payload.postId);17 state.mainPosts[index] = payload.data; //ìê¸ì´ ììì¤ëë¡18 state.mainPosts = state.mainPosts.concat();19 state.modifyImagePaths = [];20 },21 removeMainPost(state, payload) {22 const index = state.mainPosts.findIndex(v => v.id === payload.postId);23 state.mainPosts.splice(index, 1);24 },25 addComment(state, payload) {26 const index = state.mainPosts.findIndex(v => v.id === payload.PostId);27 state.mainPosts[index].Comments.push(payload);28 },29 loadPost(state, payload) {30 state.mainPosts = [payload];31 },32 loadPosts(state, payload) {33 if (payload.refresh) {34 state.mainPosts = payload.data;35 state.hasMorePost = payload.data.length === limit; //10ê°ì© ë¶ë¬ì¬ëë ë¤ì ëììììì¼ë true 10ê° ì´íë©´ ëëê±°ë false36 } else {37 state.mainPosts = state.mainPosts.concat(payload.data);38 state.hasMorePost = payload.data.length === limit; //10ê°ì© ë¶ë¬ì¬ëë ë¤ì ëììììì¼ë true 10ê° ì´íë©´ ëëê±°ë false39 }40 },41 loadComments(state, payload) {42 const index = state.mainPosts.findIndex(v => v.id === payload.PostId);43 Vue.set(state.mainPosts[index], 'Comments', payload);44 },45 concatImagePaths(state, payload) {46 state.imagePaths = state.imagePaths.concat(payload);47 },48 concatModifyImagePaths(state, payload) {49 state.modifyImagePaths = state.modifyImagePaths.concat(payload);50 },51 removeImagePath(state, payload) {52 state.imagePaths.splice(payload, 1);53 },54 removeModifyImagePath(state, payload) {55 state.modifyImagePaths.splice(payload, 1);56 },57 deleteModifyImagePaths(state, payload) {58 state.modifyImagePaths = [];59 },60 likePost(state, payload) {61 const index = state.mainPosts.findIndex(v => v.id === payload.postId);62 state.mainPosts[index].Likers.push({63 id: payload.userId,64 });65 },66 unLikePost(state, payload) {67 const index = state.mainPosts.findIndex(v => v.id === payload.postId);68 const userIndex = state.mainPosts[index].Likers.findIndex(v => v.id === payload.userId);69 state.mainPosts[index].Likers.splice(userIndex, 1);70 },71};72export const actions = {73 add: throttle(async function({ commit, state }, payload) {74 //ìë²ì ê²ìê¸ ë±ë¡75 try {76 const res = await this.$axios.post('/post', {77 content: payload.content,78 image: state.imagePaths79 }, {80 withCredentials: true81 });82 commit('addMainPost', res.data);83 } catch (err) {84 console.error(err);85 alert(err.response.data);86 }87 }, 4000),88 update: throttle(async function({ commit, state }, payload) {89 //ìë²ì ê²ìê¸ ë±ë¡90 try {91 console.log(payload.content);92 const res = await this.$axios.patch('/post', {93 postId: payload.postId,94 content: payload.content,95 image: state.modifyImagePaths96 }, {97 withCredentials: true98 });99 commit('modifyMainPost', {100 data: res.data,101 postId: payload.postId,102 });103 } catch (err) {104 console.error(err);105 alert(err.response.data);106 }107 }, 4000),108 async edit({ commit }, payload) {109 try {110 await this.$axios.patch(`/post/${payload.postId}`, {111 content: payload.content,112 image: state.imagePaths113 }, {114 withCredentials: true,115 });116 commit('editMainPost', payload);117 } catch (err) {118 console.error(err);119 alert(err.response.data);120 }121 },122 async remove({ commit }, payload) {123 try {124 await this.$axios.delete(`/post/${payload.postId}`, {125 withCredentials: true,126 });127 commit('removeMainPost', payload);128 } catch (err) {129 console.error(err);130 alert(err.response.data);131 }132 },133 async addComment({ commit }, payload) {134 try {135 const res = await this.$axios.post(`/post/${payload.postId}/comment`, {136 content: payload.content,137 }, {138 withCredentials: true,139 });140 commit('addComment', res.data);141 } catch (err) {142 console.error(err);143 alert(err.response.data);144 }145 },146 async loadPost({ commit, state }, payload) {147 try {148 const res = await this.$axios.get(`/post/${payload.postId}`);149 commit('loadPost', res.data);150 } catch (err) {151 console.error(err);152 // alert(err.response.data);153 }154 },155 loadPosts: throttle(async function({ commit, state }, payload) {156 if (state.hasMorePost || (payload && payload.refresh)) {157 try {158 let lastPost;159 let res;160 if (payload && payload.refresh) {161 lastPost = undefined;162 } else {163 lastPost = state.mainPosts[state.mainPosts.length - 1];164 }165 res = await this.$axios.get(`/posts?lastId=${lastPost && lastPost.id}&limit=10`)166 commit('loadPosts', {167 data: res.data,168 refresh: payload && payload.refresh169 });170 } catch (err) {171 console.error(err);172 // alert(err.response.data);173 }174 }175 }, 4000),176 loadUserPosts: throttle(async function({ commit, state }, payload) {177 if (state.hasMorePost || (payload && payload.refresh)) {178 try {179 let lastPost;180 let res;181 if (payload && payload.refresh) {182 lastPost = undefined;183 } else {184 lastPost = state.mainPosts[state.mainPosts.length - 1];185 }186 res = await this.$axios.get(`/user/${payload.userId}/posts?lastId=${lastPost && lastPost.id}&limit=10`)187 commit('loadPosts', {188 data: res.data,189 refresh: payload && payload.refresh190 });191 } catch (err) {192 console.error(err);193 // alert(err.response.data);194 }195 }196 }, 1000),197 loadHashtagPosts: throttle(async function({ commit, state }, payload) {198 if (state.hasMorePost || (payload && payload.refresh)) {199 try {200 let lastPost;201 let res;202 if (payload && payload.refresh) {203 lastPost = undefined;204 } else {205 lastPost = state.mainPosts[state.mainPosts.length - 1];206 }207 res = await this.$axios.get(`/hashtag/${payload.hashtag}?lastId=${lastPost && lastPost.id}&limit=10`)208 commit('loadPosts', {209 data: res.data,210 refresh: payload && payload.refresh211 });212 } catch (err) {213 console.error(err);214 // alert(err.response.data);215 }216 }217 }, 1000),218 async loadComments({ commit }, payload) {219 try {220 const res = await this.$axios.get(`/post/${payload.postId}/comments`);221 res.data.PostId = payload.postId;222 commit('loadComments', res.data);223 } catch (err) {224 console.error(err);225 alert(err.response);226 }227 },228 async uploadImages({ commit }, payload) {229 try {230 const res = await this.$axios.post('/post/images', payload, {231 withCredentials: true,232 });233 console.log(res.data);234 commit('concatImagePaths', res.data);235 } catch (err) {236 console.error(err);237 alert(err.response.data);238 }239 },240 async modifyUploadImages({ commit }, payload) {241 try {242 const res = await this.$axios.post('/post/images', payload, {243 withCredentials: true,244 });245 console.log(res.data);246 commit('concatModifyImagePaths', res.data);247 } catch (err) {248 console.error(err);249 alert(err.response.data);250 }251 },252 async onRetweet({ commit }, payload) {253 try {254 const res = await this.$axios.post(`/post/${payload.postId}/retweet`, {}, {255 withCredentials: true,256 });257 commit('addMainPost', res.data);258 } catch (err) {259 console.error(err);260 alert(err.response.data);261 }262 },263 async unlikePost({ commit }, payload) {264 try {265 const res = await this.$axios.delete(`/post/${payload.postId}/like`, {266 withCredentials: true,267 });268 commit('unLikePost', {269 userId: res.data.userId,270 postId: payload.postId,271 });272 } catch (err) {273 console.error(err);274 alert(err.response.data);275 }276 },277 async likePost({ commit }, payload) {278 try {279 const res = await this.$axios.post(`/post/${payload.postId}/like`, {}, {280 withCredentials: true,281 });282 commit('likePost', {283 userId: res.data.userId,284 postId: payload.postId,285 });286 } catch (err) {287 console.error(err);288 alert(err.response.data);289 }290 }...
dashboard.js
Source:dashboard.js
1const Order = require("../models/Order")2const XMLWriter = require('xml-writer')3const axios = require('axios')4module.exports.getOrders = async (req, res) => {5 const orders = await Order.find({}).populate('customer')6 const data = orders.map(o => { return { 7 id: o._id.toString(),8 paymentId: o.paymentId,9 receiptUrl: o.receiptUrl,10 orderId: o.orderId,11 dateCreated: o.dateCreated,12 amount: o.amount,13 items: o.items,14 status: o.status,15 customer: `${o.customer.firstName} ${o.customer.lastName}`16 }})17 res.json(data)18}19module.exports.completeOrder = async (req, res) => {20 const order = await Order.findOne({ _id: req.body.order.id })21 if (order.items) {22 order.items.map(item => {23 if(item._id.toString() === req.body.item._id) {24 item.status = 'completed'25 }26 if(!order.items.filter(i => i.status === 'open').length) {27 order.status = 'completed'28 }29 })30 }31 await order.save()32 const payload = await Order.find({})33 res.json({ message: 'success', payload })34}35module.exports.undoOrder = async (req, res) => {36 const order = await Order.findOne({ _id: req.body.order.id })37 if (order.items) {38 order.items.map(item => {39 if(item._id.toString() === req.body.item._id) {40 item.status = 'open'41 }42 if(order.items.filter(i => i.status === 'open').length > 0) {43 order.status = 'open'44 }45 })46 }47 await order.save()48 const payload = await Order.find({})49 res.json({ message: 'success', payload })50}51module.exports.deleteOrder = async (req, res) => {52 await Order.findOneAndDelete({ _id: req.body.order.id })53 const payload = await Order.find({})54 res.json({ message: 'success', payload })55}56module.exports.printTag = async(req, res) => {57 console.log(req.body.item)58 const payload = new XMLWriter59 payload.startDocument()60 payload.startElement('eVSRequest')61 payload.writeAttribute('USERID', '995MPPRO5353')62 payload.startElement('ImageParameters')63 payload.startElement('LabelSequence')64 payload.startElement('PackageNumber')65 payload.text('1')66 payload.endElement('PackageNumber')67 payload.startElement('TotalPackages')68 payload.text('1')69 payload.endElement('TotalPackages')70 payload.endElement('LabelSequence')71 payload.endElement('ImageParameters')72 payload.startElement('FromName')73 payload.text('Lina Smith')74 payload.endElement('FromName')75 payload.startElement('FromFirm')76 payload.text('Horizon')77 payload.endElement('FromFirm')78 payload.startElement('FromAddress1')79 payload.text('Apt 303')80 payload.endElement('FromAddress1')81 payload.startElement('FromAddress2')82 payload.text('1309 S Agnew Avenue')83 payload.endElement('FromAddress2')84 payload.startElement('FromCity')85 payload.text('Oklahoma City')86 payload.endElement('FromCity')87 payload.startElement('FromState')88 payload.text('OK')89 payload.endElement('FromState')90 payload.startElement('FromZip5')91 payload.text('73108')92 payload.endElement('FromZip5')93 payload.startElement('FromZip4')94 payload.text('2427')95 payload.endElement('FromZip4')96 payload.startElement('FromPhone')97 payload.text('1234567890')98 payload.endElement('FromPhone')99 payload.startElement('AllowNonCleansedOriginAddr')100 payload.text('false')101 payload.endElement('AllowNonCleansedOriginAddr')102 payload.startElement('ToName')103 payload.text('Tall Tom')104 payload.endElement('ToName')105 payload.startElement('ToFirm')106 payload.text('ABC Corp')107 payload.endElement('ToFirm')108 payload.startElement('ToAddress2')109 payload.text('1098 N Fraser Street')110 payload.endElement('ToAddress2')111 payload.startElement('ToCity')112 payload.text('Georgetown')113 payload.endElement('ToCity')114 payload.startElement('ToState')115 payload.text('SC')116 payload.endElement('ToState')117 payload.startElement('ToZip5')118 payload.text('29440')119 payload.endElement('ToZip5')120 payload.startElement('ToZip4')121 payload.text('2849')122 payload.endElement('ToZip4')123 payload.startElement('ToPhone')124 payload.text('8005554526')125 payload.endElement('ToPhone')126 payload.startElement('ToContactPreference')127 payload.text('email')128 payload.endElement('ToContactPreference')129 payload.startElement('ToContactEMail')130 payload.text('talltom@aol.com')131 payload.endElement('ToContactEMail')132 payload.startElement('AllowNonCleansedDestAddr')133 payload.text('false')134 payload.endElement('AllowNonCleansedDestAddr')135 payload.startElement('WeightInOunces')136 payload.text('32')137 payload.endElement('WeightInOunces')138 payload.startElement('ServiceType')139 payload.text('PRIORITY')140 payload.endElement('ServiceType')141 payload.startElement('Container')142 payload.text('VARIABLE')143 payload.endElement('Container')144 payload.startElement('Width')145 payload.text('5.5')146 payload.endElement('Width')147 payload.startElement('Length')148 payload.text('11')149 payload.endElement('Length')150 payload.startElement('Height')151 payload.text('11')152 payload.endElement('Height')153 payload.startElement('Machinable')154 payload.text('TRUE')155 payload.endElement('Machinable')156 payload.startElement('InsuredAmount')157 payload.text('100.00')158 payload.endElement('InsuredAmount')159 payload.startElement('AddressServiceREquested')160 payload.text('true')161 payload.endElement('AddressServiceREquested')162 payload.startElement('CustomerRefNo')163 payload.text('EF789UJK')164 payload.endElement('CustomerRefNo')165 payload.startElement('CustomerRefNo2')166 payload.text('EE66GG87')167 payload.endElement('CustomerRefNo2')168 payload.startElement('ExtraServices')169 payload.startElement('ExtraService')170 payload.text('120')171 payload.endElement('ExtraService')172 payload.endElement('ExtraServices')173 payload.startElement('CRID')174 payload.text('4569873')175 payload.endElement('CRID')176 payload.startElement('MID')177 payload.text('456789354')178 payload.endElement('MID')179 payload.startElement('VendorCode')180 payload.text('1234')181 payload.endElement('VendorCode')182 payload.startElement('VendorProductVersionNumber')183 payload.text('5.02.1B')184 payload.endElement('VendorProductVersionNumber')185 payload.startElement('SenderName')186 payload.text('Adam Johnson')187 payload.endElement('SenderName')188 payload.startElement('SenderEMail')189 payload.text('Adam1234d@aol.com')190 payload.endElement('SenderEMail')191 payload.startElement('RecipientName')192 payload.text('Robert Jones')193 payload.endElement('RecipientName')194 payload.startElement('RecipientEMail')195 payload.text('bobjones@aol.com')196 payload.endElement('RecipientEMail')197 payload.startElement('RecipientOption')198 payload.text('SAME PAGE')199 payload.endElement('RecipientOption')200 payload.startElement('ImageType')201 payload.text('PDF')202 payload.endElement('ImageType')203 payload.startElement('HoldForManifest')204 payload.text('N')205 payload.endElement('HoldForManifest')206 payload.startElement('NineDigitRoutingZip')207 payload.text('false')208 payload.endElement('NineDigitRoutingZip')209 payload.startElement('ShipInfo')210 payload.text('True')211 payload.endElement('ShipInfo')212 payload.startElement('CarrierRelease')213 payload.text('False')214 payload.endElement('CarrierRelease')215 payload.startElement('ReturnCommitments')216 payload.text('True')217 payload.endElement('ReturnCommitments')218 payload.startElement('PrintCustomerRefNo')219 payload.text('False')220 payload.endElement('PrintCustomerRefNo')221 payload.startElement('PrintCustomerRefNo2')222 payload.text('True')223 payload.endElement('PrintCustomerRefNo2')224 payload.startElement('Content')225 payload.startElement('ContentType')226 payload.text('Perishable')227 payload.endElement('ContentType')228 payload.startElement('ContentDescription')229 payload.text('Other')230 payload.endElement('ContentDescription')231 payload.endElement('Content')232 payload.startElement('ActionCode')233 payload.text('M0')234 payload.endElement('ActionCode')235 payload.startElement('OptOutOfSPE')236 payload.text('false')237 payload.endElement('OptOutOfSPE')238 payload.endElement('eVSRequest')239 payload.endDocument()240 await axios({241 method: 'GET',242 url: 'https://secure.shippingapis.com/ShippingAPI.dll?API=eVS&XML=' + payload.toString()243 }).then( res => console.log(res))...
dataTypes.py
Source:dataTypes.py
...160 resultState: The state of the request161 '''162 return self._state163 @property164 def payload(self) -> responsePayload:165 '''The payload166 Returns:167 responsePayload: The payload object168 '''169 return self._payload170 @property171 def error(self) -> str:172 '''An error string describing the fault173 Returns:174 str: An error string describing the fault175 '''176 return self._error177class loginResult(Enum):178 '''Enum with possible login results...
adminStateSlice.ts
Source:adminStateSlice.ts
1import { createSlice, PayloadAction } from "@reduxjs/toolkit";2import { ShortPreviewSchema } from "../../schema/DatabaseSchema";3import { AdminState } from "../../types/State";4const adminStateSlice = createSlice({5 name: "adminStateSlice",6 initialState: {7 feature: "featured",8 currentSelectionFeatured: [],9 currentSelectionForYou: [],10 currentSelectionInternational: [],11 currentSelectionAssociate: [],12 } as AdminState,13 reducers: {14 updateCurrentFeature: (15 state: AdminState,16 payload: PayloadAction<string>17 ) => {18 state.feature = payload.payload;19 },20 addCurrentSelection: (21 state: AdminState,22 payload: PayloadAction<{23 payload: ShortPreviewSchema;24 type: string;25 }>26 ) => {27 if (payload.payload.type === "featured") {28 const alreadyExist = state.currentSelectionFeatured.find(29 (selection: ShortPreviewSchema) =>30 payload.payload.payload.id === selection.id31 );32 if (alreadyExist === undefined) {33 state.currentSelectionFeatured.push(34 payload.payload.payload35 );36 }37 }38 if (payload.payload.type === "for-you") {39 const alreadyExist = state.currentSelectionForYou.find(40 (selection: ShortPreviewSchema) =>41 payload.payload.payload.id === selection.id42 );43 if (alreadyExist === undefined) {44 state.currentSelectionForYou.push(payload.payload.payload);45 }46 }47 if (payload.payload.type === "international") {48 const alreadyExist = state.currentSelectionInternational.find(49 (selection: ShortPreviewSchema) =>50 payload.payload.payload.id === selection.id51 );52 if (alreadyExist === undefined) {53 state.currentSelectionInternational.push(54 payload.payload.payload55 );56 }57 }58 if (payload.payload.type === "associate") {59 const alreadyExist = state.currentSelectionAssociate.find(60 (selection: ShortPreviewSchema) =>61 payload.payload.payload.id === selection.id62 );63 if (alreadyExist === undefined) {64 state.currentSelectionAssociate.push(65 payload.payload.payload66 );67 }68 }69 },70 removeCurrentSelection: (71 state: AdminState,72 payload: PayloadAction<{73 payload: ShortPreviewSchema;74 type: string;75 }>76 ) => {77 if (payload.payload.type === "featured") {78 state.currentSelectionFeatured =79 state.currentSelectionFeatured.filter(80 (item: ShortPreviewSchema) =>81 item.id !== payload.payload.payload.id82 );83 }84 if (payload.payload.type === "for-you") {85 state.currentSelectionForYou =86 state.currentSelectionForYou.filter(87 (item: ShortPreviewSchema) =>88 item.id !== payload.payload.payload.id89 );90 }91 if (payload.payload.type === "international") {92 state.currentSelectionInternational =93 state.currentSelectionInternational.filter(94 (item: ShortPreviewSchema) =>95 item.id !== payload.payload.payload.id96 );97 }98 if (payload.payload.type === "associate") {99 state.currentSelectionAssociate =100 state.currentSelectionAssociate.filter(101 (item: ShortPreviewSchema) =>102 item.id !== payload.payload.payload.id103 );104 }105 },106 resetCurrentSelection: (107 state: AdminState,108 payload: PayloadAction<{109 type: string;110 }>111 ) => {112 if (payload.payload.type === "featured") {113 state.currentSelectionFeatured = [];114 }115 if (payload.payload.type === "for-you") {116 state.currentSelectionForYou = [];117 }118 if (payload.payload.type === "international") {119 state.currentSelectionInternational = [];120 }121 if (payload.payload.type === "associate") {122 state.currentSelectionAssociate = [];123 }124 },125 setCurrentSelection: (126 state: AdminState,127 payload: PayloadAction<{128 type: string;129 payload: ShortPreviewSchema[];130 }>131 ) => {132 if (payload.payload.type === "featured") {133 state.currentSelectionFeatured = payload.payload.payload;134 }135 if (payload.payload.type === "for-you") {136 state.currentSelectionForYou = payload.payload.payload;137 }138 if (payload.payload.type === "international") {139 state.currentSelectionInternational = payload.payload.payload;140 }141 if (payload.payload.type === "associate") {142 state.currentSelectionAssociate = payload.payload.payload;143 }144 },145 },146});147export const {148 updateCurrentFeature,149 addCurrentSelection,150 removeCurrentSelection,151 resetCurrentSelection,152 setCurrentSelection,153} = adminStateSlice.actions;...
apiMap.js
Source:apiMap.js
1/* eslint-disable camelcase */2/* eslint-disable radix */3const api = (config) => ({4 loginApi: ({ username, password }) => config('post', '/auth/v1/login/', {5 username,6 password,7 }),8 getProfile: (tokenUser) => config('get', '/account/v1/profile/', '', {9 Authorization: `JWT ${tokenUser} `,10 }),11 logout: (token) => config('post', '/auth/v1/logout/', '', {12 Authorization: `JWT ${token} `,13 }),14 saveAnswerToServer: ({ tokenUser, answer, idListSurvey }) => config('post', '/answer/v1/', {15 answer,16 survey: idListSurvey,17 }, {18 Authorization: `JWT ${tokenUser} `,19 }),20 // account21 getAccount: (keyword) => config('get', `/account/v1/list-account/?search=${keyword}`),22 addAccount: (payload) => config('post', '/auth/v1/register/', payload),23 updateAccount: (payload) => config('patch', `/account/v1/${payload.id}/`, payload.data),24 deleteAccount: (payload) => config('post', '/account/v1/delete_account/', payload),25 changePassword: (payload) => config('post', '/auth/v1/change-password/', payload),26 // tenant27 getTenant: (keyword) => config('get', `/tenant/v1/list-tenant/?search=${keyword}`, ''),28 deleteTenant: (payload) => config('post', '/tenant/v1/delete-tenant/', payload),29 addTenant: (payload) => config('post', '/tenant/v1/', payload),30 updateTenant: (payload) => config('patch', `/tenant/v1/${payload.id}/`, payload.data),31 // chu nha32 getChuNha: (keyword) => config('get', `/chu-nha/v1/list-chu-nha/?search=${keyword}`, ''),33 deleteHost: (payload) => config('post', '/chu-nha/v1/delete_chunha/', payload),34 addHost: (payload) => config('post', '/chu-nha/v1/', payload),35 updateHost: (payload) => config('patch', `/chu-nha/v1/${payload.id}/`, payload.data),36 // khach thue37 getKhachThue: (keyword) => config('get', `/khach-thue/v1/list-khach_thue/?search=${keyword}`, ''),38 deleteGuest: (payload) => config('post', '/khach-thue/v1/delete_khachthue/', payload),39 addGuest: (payload) => config('post', '/khach-thue/v1/', payload),40 updateGuest: (payload) => config('patch', `/khach-thue/v1/${payload.id}/`, payload.data),41 // can ho42 getCanHo: (keyword) => config('get', `/can-ho/v1/list-can-ho/?search=${keyword}`, ''),43 deleteCanHo: (payload) => config('post', '/can-ho/v1/delete_canho/', payload),44 addCanHo: (payload) => config('post', '/can-ho/v1/', payload),45 updateCanHo: (payload) => config('patch', `/can-ho/v1/${payload.id}/`, payload.data),46 // toa nha47 getToaNha: (keyword) => config('get', `/toa-nha/v1/list-toa-nha/?search=${keyword}`, ''),48 deleteToaNha: (payload) => config('post', '/toa-nha/v1/delete_toanha/', payload),49 addBuilding: (payload) => config('post', '/toa-nha/v1/', payload),50 updateBuilding: (payload) => config('patch', `/toa-nha/v1/${payload.id}/`, payload.data),51 // dich vu52 getService: (keyword) => config('get', `/dich-vu/v1/list-dich-vu/?search=${keyword}`, ''),53 deleteService: (payload) => config('post', '/dich-vu/v1/delete_dichvu/', payload),54 // contract55 createContract: (payload) => config('post', '/hd-groups/v1/', payload.data),56 updateContract: (payload) => config('patch', `/hd-groups/v1/${payload.id}/`, payload.data),57 addService: (payload) => config('post', '/dich-vu/v1/', payload),58 updateService: (payload) => config('patch', `/dich-vu/v1/${payload.id}/`, payload.data),59 // payment60 getPayment: (payload) => config('get', `/payment/v1/list-payment/?can_ho=${payload.can_ho}&start_date=${payload.start_date}&end_date=${payload.end_date}`),61 sendEmailPayment: (payload) => config('post', '/payment/v1/send-mail-payment/', payload),62 payment: (payload) => config('post', '/payment/v1/payment/', payload),63 // unpayment64 getUnPayment: (payload) => config('get', `/payment/v1/list-unpaid-payment/?can_ho=${payload.can_ho}`),65 getUnPaymentService: (payload) => config('get', `/payment/v1/service-payment/list-unpaid-service-payment/?can_ho=${payload.can_ho}&dich_vu=${payload.service}`),66 // service payment67 getServicePayment: (payload) => config('get', `/payment/v1/service-payment/list-service-payment/?can_ho=${payload.can_ho}&dich_vu=${payload.service}&start_date=${payload.start_date}&end_date=${payload.end_date}`),68 paymentService: (payload) => config('post', '/payment/v1/service-payment/service-payment/', payload),69 // contract70 getContract: (keyword) => config('get', `/hd-groups/v1/list-hd-group/?search=${keyword}`, ''),71 deleteContract: (payload) => config('post', '/hd-groups/v1/delete_hdgroup/', payload),72 // overview73 overview: () => config('get', '/account/v1/overview/'),74 // district75 listDistrict: () => config('get', '/account/v1/list-district/'),76});...
sample-paths.test.resources.js
Source:sample-paths.test.resources.js
1// Copyright (c) 2019 Uber Technologies, Inc.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14export const simplePayloadElemMaker = (label) => ({15 operation: `${label}Operation`,16 service: `${label}Service`,17});18export const focalPayloadElem = simplePayloadElemMaker('focal');19const sameFocalServicePayloadElem = {20 operation: 'someOtherOperation',21 service: focalPayloadElem.service,22};23const pathLengthener = (path) => {24 const prequels = [];25 const sequels = [];26 path.forEach(({ operation, service }) => {27 if (operation !== focalPayloadElem.operation && service !== focalPayloadElem.service) {28 prequels.push({29 operation: `prequel-${operation}`,30 service,31 });32 sequels.push({33 operation,34 service: `sequel-${service}`,35 });36 }37 });38 return [...prequels, ...path, ...sequels];39};40export const firstPayloadElem = simplePayloadElemMaker('first');41export const beforePayloadElem = simplePayloadElemMaker('before');42export const midPayloadElem = simplePayloadElemMaker('mid');43export const afterPayloadElem = simplePayloadElemMaker('after');44export const lastPayloadElem = simplePayloadElemMaker('last');45export const shortPath = [beforePayloadElem, focalPayloadElem];46export const simplePath = [firstPayloadElem, beforePayloadElem, focalPayloadElem, afterPayloadElem, lastPayloadElem];47export const longSimplePath = pathLengthener(simplePath);48export const noFocalPath = [firstPayloadElem, beforePayloadElem, midPayloadElem, afterPayloadElem, lastPayloadElem];49export const doubleFocalPath = [50 firstPayloadElem,51 beforePayloadElem,52 focalPayloadElem,53 midPayloadElem,54 focalPayloadElem,55 afterPayloadElem,56 lastPayloadElem,57];58export const almostDoubleFocalPath = [59 firstPayloadElem,60 beforePayloadElem,61 sameFocalServicePayloadElem,62 midPayloadElem,63 focalPayloadElem,64 afterPayloadElem,65 lastPayloadElem,66];67const divergentPayloadElem = simplePayloadElemMaker('divergentPayloadElem');68export const convergentPaths = [69 [firstPayloadElem, focalPayloadElem, divergentPayloadElem, afterPayloadElem, lastPayloadElem],70 [firstPayloadElem, focalPayloadElem, midPayloadElem, afterPayloadElem, lastPayloadElem],71];72const generationPayloadElems = {73 afterFocalMid: simplePayloadElemMaker('afterFocalMid'),74 afterTarget0: simplePayloadElemMaker('afterTarget0'),75 afterTarget1: simplePayloadElemMaker('afterTarget1'),76 beforeFocalMid: simplePayloadElemMaker('beforeFocalMid'),77 beforeTarget0: simplePayloadElemMaker('beforeTarget0'),78 beforeTarget1: simplePayloadElemMaker('beforeTarget1'),79 target: simplePayloadElemMaker('target'),80};81export const generationPaths = [82 [83 generationPayloadElems.beforeTarget0,84 generationPayloadElems.target,85 generationPayloadElems.beforeFocalMid,86 focalPayloadElem,87 ],88 [89 generationPayloadElems.beforeTarget1,90 generationPayloadElems.target,91 generationPayloadElems.beforeFocalMid,92 focalPayloadElem,93 ],94 [focalPayloadElem, generationPayloadElems.afterFocalMid, generationPayloadElems.target],95 [96 focalPayloadElem,97 generationPayloadElems.afterFocalMid,98 generationPayloadElems.target,99 generationPayloadElems.afterTarget0,100 ],101 [102 focalPayloadElem,103 generationPayloadElems.afterFocalMid,104 generationPayloadElems.target,105 generationPayloadElems.afterTarget1,106 ],107 [generationPayloadElems.target, generationPayloadElems.beforeFocalMid, focalPayloadElem],108];109export const wrap = (paths) => ({110 dependencies: paths.map((path) => ({ path, attributes: [] })),...
actions.js
Source:actions.js
1import {2 SET_PRODUCTS,3 SET_CATEGORY_PRODUCTS,4 SET_DISPLAY_OVERLAY,5 SET_LOADING,6 SET_ITEM_PROP_OVERLAY,7 SET_CART,8 SET_INFO_TOAST_MESSAGE,9 SET_VALUE_SEARCH,10 SET_POST_TYPE,11 SET_RESULTS_SEARCH,12 SET_FILTER_WITH_CATEGORIES,13 SET_FILTER_WITH_PRICE_ASC,14 SET_FILTER_WITH_PRICE_DESC,15 SET_SHIPPING_DATA,16 SET_ORDER,17 SET_FUNCTION_CAPTURE_CHECKOUT,18 SET_ERROR_MESSAGE,19}from './constants'20export const setProducts = payload => ({21 type: SET_PRODUCTS,22 payload: payload23});24export const setCategoryProducts = payload => ({25 type: SET_CATEGORY_PRODUCTS,26 payload: payload27});28export const setDisplayOverlay = payload => ({29 type: SET_DISPLAY_OVERLAY,30 payload: payload31});32export const setItemPropOverlay = payload => ({33 type: SET_ITEM_PROP_OVERLAY,34 payload: payload35});36export const setLoading = payload => ({37 type: SET_LOADING,38 payload: payload39});40export const setCart = payload => ({41 type: SET_CART,42 payload: payload43});44export const setInfoToastMess = payload => ({45 type: SET_INFO_TOAST_MESSAGE,46 payload: payload47});48export const setValueSearch = payload => ({49 type: SET_VALUE_SEARCH,50 payload: payload51});52export const setPostType = payload => ({53 type: SET_POST_TYPE,54 payload: payload55});56export const setResulesSearch = payload => ({57 type: SET_RESULTS_SEARCH,58 payload: payload59});60export const setFilterWithCategories = payload => ({61 type: SET_FILTER_WITH_CATEGORIES,62 payload: payload63});64export const setFilterWithPriceAsc = payload => ({65 type: SET_FILTER_WITH_PRICE_ASC,66 payload: payload67});68export const setFilterWithPriceDesc = payload => ({69 type: SET_FILTER_WITH_PRICE_DESC,70 payload: payload71});72export const setShippingData = payload => ({73 type: SET_SHIPPING_DATA,74 payload: payload75});76export const setOrder = payload => ({77 type: SET_ORDER,78 payload: payload79});80export const setFunctionCaptureCheckout = payload => ({81 type: SET_FUNCTION_CAPTURE_CHECKOUT,82 payload: payload83});84export const setErrorMessage = payload => ({85 type: SET_ERROR_MESSAGE,86 payload: payload...
Using AI Code Generation
1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3client.runTest(url, function(err, data) {4 if (err) return console.error(err);5 console.log('Test status:', data.statusText);6 client.getTestResults(data.data.testId, function(err, data) {7 if (err) return console.error(err);8 console.log('Test results:', data);9 });10});
Using AI Code Generation
1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var payload = {4 "script": "document.getElementById('hplogo').style.display='none';"5};6wpt.runTest(payload, function(err, data) {7 if (err) return console.error(err);8 console.log('Test %s from %s', data.data.testId, data.data.from);9});
Using AI Code Generation
1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.5e8c8e3b3d3e3b3e3b3e3b3e3b3e3b3e');3wpt.runTest(url, {4}, function(err, data) {5 if (err) return console.error(err);6 console.log(data);7});
Using AI Code Generation
1var request = require('request');2var fs = require('fs');3var url = process.argv[2];4var wpt_server = process.argv[3];5var api_key = process.argv[4];6var payload = {7};8var options = {9};10request(options, function(err, res, body) {11 if (!err && res.statusCode == 200) {12 var test_id = JSON.parse(body).data.testId;13 console.log("Test ID: " + test_id);14 var test_results_url = wpt_server + "/jsonResult.php?test=" + test_id;15 console.log("Test Results URL: " + test_results_url);16 }17});
Using AI Code Generation
1var wpt = require('webpagetest');2var api = new wpt('A.8e2c0e2e2b4b4d4d9f7c1f0a4b0e4f6d');3var location = 'Dulles:Chrome';4var timeout = 10;5var runs = 1;6var firstViewOnly = true;7var pollResults = 5;8var video = true;9var pollResults = 5;10var connectivity = 'Cable';11var connectivityProfile = 'native';12api.runTest(url, {13}, function(err, data) {14 if (err) return console.error(err);15 console.log(data);16});
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!!