How to use start_chunk method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

knock48.py

Source: knock48.py Github

copy
1'''
2Ans. for knock48
348. 名詞から根へのパスの抽出
4文中のすべての名詞を含む文節に対し,その文節から構文木の根に至るパスを抽出せよ. ただし,構文木上のパスは以下の仕様を満たすものとする.
5
6各文節は(表層形の)形態素列で表現する
7パスの開始文節から終了文節に至るまで,各文節の表現を"->"で連結する
8「吾輩はここで始めて人間というものを見た」という文(neko.txt.cabochaの8文目)から,次のような出力が得られるはずである.
9
10吾輩は -> 見た
11ここで -> 始めて -> 人間という -> ものを -> 見た
12人間という -> ものを -> 見た
13ものを -> 見た
14'''
15
16from get_chunks_list import get_chunks_list
17
18DIVIDER = ' -> '
19
20def get_root(chunklist, start_chunk, result_lst):
21    res = result_lst
22    if start_chunk.link == -1:# or not start_chunk.has_noun:
23        return
24    if start_chunk.has_noun and len(result_lst) == 0:
25        res = [start_chunk.allbody]
26    elif start_chunk.has_noun and len(result_lst) > 0:
27        res = result_lst
28    else:
29        pass
30    for c in chunklist:
31        if start_chunk.cid < c.cid and start_chunk.link == c.cid:
32            # print('sid:{} ; link:{} : cid:{}'.format(c.sentence_id, start_chunk.cid, c.cid))
33            res.append(c.allbody)
34            # print('-----------',res)
35            if c.link == -1:
36                print(DIVIDER.join(res))
37            else:
38                get_root(chunklist, c, res)
39
40sents_list = get_chunks_list()
41for sent in sents_list: # sentはchunkリスト(文)のリスト
42    target_sent = sent.copy()
43    for c in sent:
44        if c.has_noun:
45            get_root(target_sent, c, [])
46    # for debug
47    if c.sentence_id > 5:
48        break
49
Full Screen

organizer_copy.py

Source: organizer_copy.py Github

copy
1import numpy as np 
2from datetime import datetime as dt
3from backports.datetime_fromisoformat import MonkeyPatch
4MonkeyPatch.patch_fromisoformat()
5
6MAX_PACKET_SIZE = 4096
7BYTES_IN_PACKET = 1456
8
9np.set_printoptions(threshold=np.inf,linewidth=325)
10
11class Organizer:
12
13	def __init__(self, all_data, num_chirp_loops, num_rx, num_tx, num_samples):
14		self.data = all_data[0]
15		self.packet_num = all_data[1]
16		self.byte_count = all_data[2]
17
18		self.num_packets = len(self.byte_count)
19		self.num_chirps = num_chirp_loops*num_tx
20		self.num_rx = num_rx
21		self.num_samples = num_samples
22
23		self.BYTES_IN_FRAME = self.num_chirps * self.num_rx * self.num_samples * 2 * 2
24		self.BYTES_IN_FRAME_CLIPPED = (self.BYTES_IN_FRAME // BYTES_IN_PACKET) * BYTES_IN_PACKET
25		self.UINT16_IN_FRAME = self.BYTES_IN_FRAME // 2
26		self.NUM_PACKETS_PER_FRAME = self.BYTES_IN_FRAME // BYTES_IN_PACKET
27
28		self.start_time = all_data[3]
29		self.end_time = all_data[4]
30
31	def iq(self, raw_frame):
32		"""Reorganizes raw ADC data into a full frame
33
34		Args:
35			raw_frame (ndarray): Data to format
36			num_chirps: Number of chirps included in the frame
37			num_rx: Number of receivers used in the frame
38			num_samples: Number of ADC samples included in each chirp
39
40		Returns:
41			ndarray: Reformatted frame of raw data of shape (num_chirps, num_rx, num_samples)
42
43		"""
44		ret = np.zeros(len(raw_frame) // 2, dtype=np.csingle)
45
46		# Separate IQ data
47		ret[0::2] = raw_frame[0::4] + 1j * raw_frame[2::4]
48		ret[1::2] = raw_frame[1::4] + 1j * raw_frame[3::4]
49		return ret.reshape((self.num_chirps, self.num_rx, self.num_samples))
50
51	def get_frames(self, start_chunk, end_chunk, bc):
52
53		# if first packet received is not the first byte transmitted
54		if bc[start_chunk] == 0:
55			bytes_left_in_curr_frame = 0
56			start = start_chunk*(BYTES_IN_PACKET // 2)
57		else:
58			frames_so_far = bc[start_chunk] // self.BYTES_IN_FRAME
59			bytes_so_far = frames_so_far * self.BYTES_IN_FRAME
60			# bytes_left_in_curr_frame = bc[start_chunk] - bytes_so_far
61			bytes_left_in_curr_frame = (frames_so_far+1)*self.BYTES_IN_FRAME - bc[start_chunk]
62			start = (bytes_left_in_curr_frame // 2) + start_chunk*(BYTES_IN_PACKET // 2)
63
64		# print(start_chunk, start)
65
66		# find num of frames
67		total_bytes = bc[end_chunk] - (bc[start_chunk] + bytes_left_in_curr_frame)
68		num_frames = total_bytes // (self.BYTES_IN_FRAME)
69
70		# print(bc[end_chunk])
71		# print(num_frames, start_chunk, end_chunk, self.BYTES_IN_FRAME)
72		frames = np.zeros((num_frames, self.UINT16_IN_FRAME), dtype=np.int16)
73		ret_frames = np.zeros((num_frames, self.num_chirps, self.num_rx, self.num_samples), dtype=complex)		
74
75		# compress all received data into one byte stream
76		all_uint16 = np.array(self.data).reshape(-1)
77
78		# only choose uint16 starting from a new frame
79		all_uint16 = all_uint16[start:]
80
81		# organizing into frames
82		for i in range(num_frames):
83			frame_start_idx = i*self.UINT16_IN_FRAME
84			frame_end_idx = (i+1)*self.UINT16_IN_FRAME
85			frame = all_uint16[frame_start_idx:frame_end_idx]
86			frames[i][:len(frame)] = frame.astype(np.int16)
87			ret_frames[i] = self.iq(frames[i])	
88
89		return ret_frames
90
91
92	def organize(self):
93
94		radar_unix_start_time = dt.timestamp(dt.fromisoformat(self.start_time[:-1]))*1e6
95		radar_unix_end_time = dt.timestamp(dt.fromisoformat(self.end_time[:-1]))*1e6
96
97		print('Start time: ', self.start_time)
98		print('End time: ', self.end_time)
99
100		self.byte_count = np.array(self.byte_count)
101		self.data = np.array(self.data)
102		self.packet_num = np.array(self.packet_num)
103
104		# Reordering packets
105		# sorted_idx = np.argsort(self.packet_num)
106		# print(sorted_idx.dtype)
107		# print(len(self.packet_num), len(self.byte_count), len(self.data), sorted_idx.shape)
108		# self.packet_num = self.packet_num[sorted_idx]
109		# self.data = self.data[sorted_idx]
110		# self.byte_count = self.byte_count[sorted_idx]
111
112		# self.packet_num = self.packet_num.tolist()
113		# self.byte_count = self.byte_count.tolist()
114		# self.data = self.data.tolist()
115
116
117
118		bc = np.array(self.byte_count)
119
120		packets_ooo = np.where(np.array(self.packet_num[1:])-np.array(self.packet_num[0:-1]) != 1)[0]
121		is_not_monotonic = np.where(np.array(self.packet_num[1:])-np.array(self.packet_num[0:-1]) < 0)[0]
122
123		print('Non monotonic packets: ', is_not_monotonic)
124
125		if len(packets_ooo) == 0:
126			print('packets in order')
127			start_chunk = 0
128			ret_frames = self.get_frames(start_chunk, -1, bc)
129
130		elif len(packets_ooo) == 1:
131			print('1 packet not in order')
132			start_chunk = packets_ooo[0]+1
133			ret_frames = self.get_frames(start_chunk, -1, bc)
134			# start_chunk = 0
135
136		else:
137			print('Packet num not in order')
138			packets_ooo = np.append(packets_ooo, len(self.packet_num)-1)
139
140			# print('Packets ooo', packets_ooo)
141
142			# print(self.NUM_PACKETS_PER_FRAME)
143			# diff = [44]
144			# for i in range(len(packets_ooo)-1):
145			# 	# print(i, len(packets_ooo))
146			# 	diff.append(self.packet_num[packets_ooo[i+1]]-self.packet_num[packets_ooo[i]+1])
147			
148			# print('Packets received before atleast 1 loss ', diff)
149			# print('Total packets received ', np.sum(np.array(diff)))
150
151			diff = []
152			for i in range(len(packets_ooo)-1):
153				diff.append(self.packet_num[packets_ooo[i]+1]-self.packet_num[packets_ooo[i]])
154			
155			# print('Packets lost before atleast 1 reception ', diff)
156			packets_lost = np.sum(np.array(diff))
157
158			packets_expected = self.packet_num[-1]-self.packet_num[0]+1
159			print('Total packets lost ', packets_lost)
160			print('Total packets expected ', packets_expected)
161			print('Fraction lost ', packets_lost/packets_expected)
162
163			new_packets_ooo = []
164			start_new_packets_ooo = []
165			end_new_packets_ooo = []
166			for i in range(1, len(packets_ooo)):
167				if (packets_ooo[i] - packets_ooo[i-1]) > self.NUM_PACKETS_PER_FRAME*2:
168					new_packets_ooo.append(packets_ooo[i-1])
169					start_new_packets_ooo.append(packets_ooo[i-1])
170					end_new_packets_ooo.append(packets_ooo[i])
171
172			new_packets_ooo = np.append(new_packets_ooo, -1)
173
174			# print('New packets ooo', new_packets_ooo)
175			# print('Start new packets ooo', start_new_packets_ooo)
176			# print('End new packets ooo', end_new_packets_ooo)
177			# exit()
178
179			for i in range(len(start_new_packets_ooo)):
180			# for i in range(len(new_packets_ooo)-1):
181			# for i in [len(new_packets_ooo)-2]:
182				# start_chunk = new_packets_ooo[i]+1
183				# end_chunk = new_packets_ooo[i+1]
184
185				start_chunk = start_new_packets_ooo[i]+1
186				end_chunk = end_new_packets_ooo[i]
187
188				# print(self.packet_num[start_chunk],self.packet_num[start_chunk-1])
189				# print(self.byte_count[start_chunk],self.byte_count[start_chunk-1])
190
191				curr_frames = self.get_frames(start_chunk, end_chunk, bc)
192
193				if i == 0:
194					ret_frames = curr_frames
195				else:
196					ret_frames = np.concatenate((ret_frames, curr_frames), axis=0)
197
198
199		return ret_frames
200
201		# Old approach
202
203
204		# frame_start_idx = np.where((bc % self.BYTES_IN_FRAME_CLIPPED == 0) & (bc != 0))[0]
205		# num_frames = len(frame_start_idx)-1
206
207		# frames = np.zeros((num_frames, self.UINT16_IN_FRAME), dtype=np.int16)
208		# ret_frames = np.zeros((num_frames, self.num_chirps, self.num_rx, self.num_samples), dtype=complex)
209
210		# for i in range(num_frames):
211		# 	d = np.array(self.data[frame_start_idx[i]:frame_start_idx[i+1]])
212		# 	frame = d.reshape(-1)
213		# 	frames[i][:len(frame)] = frame.astype(np.int16)
214		# 	ret_frames[i] = self.iq(frames[i])
215
216		# return ret_frames
Full Screen

salsa.py

Source: salsa.py Github

copy
1from samson.utilities.manipulation import left_rotate, get_blocks
2from samson.utilities.bytes import Bytes
3from samson.core.primitives import StreamCipher, Primitive
4from samson.core.metadata import SizeType, SizeSpec, EphemeralSpec, EphemeralType, ConstructionType, FrequencyType
5from samson.ace.decorators import register_primitive
6from copy import deepcopy
7import math
8
9
10def QUARTER_ROUND(a: int, b: int, c: int, d: int) -> (int, int, int, int):
11    """
12    Performs a quarter round of Salsa.
13
14    Parameters:
15        a (int): Salsa state variable.
16        b (int): Salsa state variable.
17        c (int): Salsa state variable.
18        d (int): Salsa state variable.
19    
20    Returns:
21        (int, int, int, int): New values for (a, b, c, d).
22    """
23    b = (b ^ left_rotate((a + d) & 0xFFFFFFFF,  7))
24    c = (c ^ left_rotate((b + a) & 0xFFFFFFFF,  9))
25    d = (d ^ left_rotate((c + b) & 0xFFFFFFFF, 13))
26    a = (a ^ left_rotate((d + c) & 0xFFFFFFFF, 18))
27    return a, b, c, d
28
29
30@register_primitive()
31class Salsa(StreamCipher):
32    """
33    Salsa stream cipher
34
35    Add-rotate-xor (ARX) structure.
36
37    https://en.wikipedia.org/wiki/Salsa20
38    """
39
40    CONSTRUCTION_TYPES = [ConstructionType.ADD_ROTATE_XOR]
41    EPHEMERAL          = EphemeralSpec(ephemeral_type=EphemeralType.NONCE, size=SizeSpec(size_type=SizeType.SINGLE, sizes=96))
42    USAGE_FREQUENCY    = FrequencyType.UNUSUAL
43
44    def __init__(self, key: bytes, nonce: bytes, rounds: int=20, constant: bytes=b"expand 32-byte k"):
45        """
46        Parameters:
47            key      (bytes): Key (128 or 256 bits).
48            nonce    (bytes): Nonce (8 bytes).
49            rounds     (int): Number of rounds to perform.
50            constant (bytes): Constant used in generating the keystream (16 bytes).
51        """
52        Primitive.__init__(self)
53
54        # If key is 80 bits, zero pad it (https://cr.yp.to/snuffle/salsafamily-20071225.pdf, 4.1)
55        if len(key) == 10:
56            key = Bytes.wrap(key).zfill(16)
57
58        # If key is 128 bits, just repeat it
59        if len(key) == 16:
60            key += key
61
62        self.key = key
63        self.nonce = nonce
64        self.rounds = rounds
65        self.constant = constant
66        self.counter = 0
67
68
69
70
71    def full_round(self, block_num: int, state: list=None) -> Bytes:
72        """
73        Performs a full round of Salsa.
74
75        Parameters:
76            block_num (int): Current block number.
77        
78        Returns:
79            Bytes: Keystream block.
80        """
81        ctr_bytes = int.to_bytes(block_num, 8, 'little')
82
83        cons_blocks  = [int.from_bytes(block, 'little') for block in get_blocks(self.constant, 4)]
84        key_blocks   = [int.from_bytes(block, 'little') for block in get_blocks(self.key, 4)]
85        ctr_blocks   = [int.from_bytes(block, 'little') for block in get_blocks(ctr_bytes, 4)]
86        nonce_blocks = [int.from_bytes(block, 'little') for block in get_blocks(self.nonce, 4)]
87
88        x = state or [
89            cons_blocks[0],  *key_blocks[:4],
90            cons_blocks[1],  *nonce_blocks,
91            *ctr_blocks,     cons_blocks[2],
92            *key_blocks[4:], cons_blocks[3]
93        ]
94
95        x = deepcopy(x)
96        tmp = deepcopy(x)
97
98        for _ in range(self.rounds // 2):
99            # Odd round
100            x[ 0], x[ 4], x[ 8], x[12] = QUARTER_ROUND(x[ 0], x[ 4], x[ 8], x[12])
101            x[ 5], x[ 9], x[13], x[ 1] = QUARTER_ROUND(x[ 5], x[ 9], x[13], x[ 1])
102            x[10], x[14], x[ 2], x[ 6] = QUARTER_ROUND(x[10], x[14], x[ 2], x[ 6])
103            x[15], x[ 3], x[ 7], x[11] = QUARTER_ROUND(x[15], x[ 3], x[ 7], x[11])
104
105            # Even round
106            x[ 0], x[ 1], x[ 2], x[ 3] = QUARTER_ROUND(x[ 0], x[ 1], x[ 2], x[ 3])
107            x[ 5], x[ 6], x[ 7], x[ 4] = QUARTER_ROUND(x[ 5], x[ 6], x[ 7], x[ 4])
108            x[10], x[11], x[ 8], x[ 9] = QUARTER_ROUND(x[10], x[11], x[ 8], x[ 9])
109            x[15], x[12], x[13], x[14] = QUARTER_ROUND(x[15], x[12], x[13], x[14])
110
111        for i in range(16):
112            x[i] += tmp[i]
113
114        return Bytes(b''.join([int.to_bytes(state_int & 0xFFFFFFFF, 4, 'little') for state_int in x]), byteorder='little')
115
116
117
118
119    def yield_state(self, start_chunk: int=0, num_chunks: int=1, state: list=None):
120        """
121        Generates `num_chunks` chunks of keystream starting from `start_chunk`.
122
123        Parameters:
124            num_chunks  (int): Desired number of 64-byte keystream chunks.
125            start_chunk (int): Chunk number to start at.
126            state      (list): Custom state to be directly injected.
127        
128        Returns:
129            generator: Keystream chunks.
130        """
131        for iteration in range(start_chunk, start_chunk + num_chunks):
132            yield self.full_round(iteration, state=state)
133
134
135
136    def generate(self, length: int) -> Bytes:
137        """
138        Generates `length` of keystream.
139
140        Parameters:
141            length (int): Desired length of keystream in bytes.
142        
143        Returns:
144            Bytes: Keystream.
145        """
146        num_chunks  = math.ceil(length / 64)
147        start_chunk = self.counter // 64
148
149        counter_mod = self.counter % 64
150
151        if counter_mod:
152            num_chunks += 1
153
154        keystream = sum(list(self.yield_state(start_chunk=start_chunk, num_chunks=num_chunks)))[counter_mod:counter_mod+length]
155        self.counter += length
156
157        return keystream
158
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)