Best Python code snippet using localstack_python
metadata.py
Source:metadata.py
...41 self.exif = exift.get_metadata(filename)42 def get_all(self):43 ''' Get all extracted metadata items '''44 return self.exif45 def get_item(self, item, index=None):46 ''' Get metadata item by Namespace:Parameter'''47 val = None48 try:49 val = self.exif[item]50 if index is not None:51 try:52 if isinstance(val, unicode):53 val = val.encode('ascii','ignore')54 except NameError:55 #throws on python 3 where unicode is undefined56 pass57 if isinstance(val,str) and len(val.split(',')) > 1:58 val = val.split(',')59 val = val[index]60 except KeyError:61 #print ("Item "+item+" not found")62 pass63 except IndexError:64 print("Item {0} is length {1}, index {2} is outside this range.".format(65 item,66 len(self.exif[item]),67 index))68 return val69 def size(self, item):70 '''get the size (length) of a metadata item'''71 val = self.get_item(item)72 try:73 if isinstance(val, unicode):74 val = val.encode('ascii','ignore')75 except NameError:76 #throws on python 3 where unicode is undefined77 pass78 if isinstance(val,str) and len(val.split(',')) > 1:79 val = val.split(',')80 if val is not None:81 return len(val)82 else:83 return 084 def print_all(self):85 for item in self.get_all():86 print("{}: {}".format(item, self.get_item(item)))87 def dls_present(self):88 return self.get_item("XMP:Irradiance") is not None89 def supports_radiometric_calibration(self):90 if(self.get_item('XMP:RadiometricCalibration')) is None:91 return False92 return True93 def position(self):94 '''get the WGS-84 latitude, longitude tuple as signed decimal degrees'''95 lat = self.get_item('EXIF:GPSLatitude')96 latref = self.get_item('EXIF:GPSLatitudeRef')97 if latref=='S':98 lat *= -1.099 lon = self.get_item('EXIF:GPSLongitude')100 lonref = self.get_item('EXIF:GPSLongitudeRef')101 if lonref=='W':102 lon *= -1.0103 alt = self.get_item('EXIF:GPSAltitude')104 return lat, lon, alt105 def utc_time(self):106 ''' Get the timezone-aware datetime of the image capture '''107 str_time = self.get_item('EXIF:DateTimeOriginal')108 utc_time = datetime.strptime(str_time, "%Y:%m:%d %H:%M:%S")109 subsec = int(self.get_item('EXIF:SubSecTime'))110 negative = 1.0111 if subsec < 0:112 negative = -1.0113 subsec *= -1.0114 subsec = float('0.{}'.format(int(subsec)))115 subsec *= negative116 ms = subsec * 1e3117 utc_time += timedelta(milliseconds = ms)118 timezone = pytz.timezone('UTC')119 utc_time = timezone.localize(utc_time)120 return utc_time121 def dls_pose(self):122 ''' get DLS pose as local earth-fixed yaw, pitch, roll in radians '''123 if self.get_item('XMP:Yaw') is not None:124 yaw = float(self.get_item('XMP:Yaw')) # should be XMP.DLS.Yaw, but exiftool doesn't expose it that way125 pitch = float(self.get_item('XMP:Pitch'))126 roll = float(self.get_item('XMP:Roll'))127 else:128 yaw = pitch = roll = 0.0129 return yaw, pitch, roll130 def dls_irradiance(self):131 if self.get_item('XMP:SpectralIrradiance') is not None:132 irr = float(self.get_item('XMP:SpectralIrradiance'))133 else:134 irr = 0.0135 return irr136 def rig_relatives(self):137 if self.get_item('XMP:RigRelatives') is not None:138 nelem = self.size('XMP:RigRelatives')139 return [float(self.get_item('XMP:RigRelatives', i)) for i in range(nelem)]140 else:141 return None142 def capture_id(self):143 return self.get_item('XMP:CaptureId')144 def flight_id(self):145 return self.get_item('XMP:FlightId')146 def camera_make(self):147 return self.get_item('EXIF:Make')148 def camera_model(self):149 return self.get_item('EXIF:Model')150 def firmware_version(self):151 return self.get_item('EXIF:Software')152 def band_name(self):153 return self.get_item('XMP:BandName')154 def band_index(self):155 return self.get_item('XMP:RigCameraIndex')156 def exposure(self):157 exp = self.get_item('EXIF:ExposureTime')158 if math.fabs(exp-(1.0/6329.0)) < 0.0001:159 exp = 0.000274160 return exp161 def gain(self):162 return self.get_item('EXIF:ISOSpeed')/100.0163 def image_size(self):164 return self.get_item('EXIF:ImageWidth'), self.get_item('EXIF:ImageHeight')165 def center_wavelength(self):166 return self.get_item('XMP:CentralWavelength')167 def bandwidth(self):168 return self.get_item('XMP:WavelengthFWHM')169 def radiometric_cal(self):170 nelem = self.size('XMP:RadiometricCalibration')171 return [float(self.get_item('XMP:RadiometricCalibration', i)) for i in range(nelem)]172 def black_level(self):173 if self.get_item('EXIF:BlackLevel') is None:174 return 0175 black_lvl = self.get_item('EXIF:BlackLevel').split(' ')176 total = 0.0177 num = len(black_lvl)178 for pixel in black_lvl:179 total += float(pixel)180 return total/float(num)181 def dark_pixels(self):182 ''' get the average of the optically covered pixel values183 Note: these pixels are raw, and have not been radiometrically184 corrected. Use the black_level() method for all185 radiomentric calibrations '''186 dark_pixels = self.get_item('XMP:DarkRowValue')187 total = 0.0188 num = len(dark_pixels)189 for pixel in dark_pixels:190 total += float(pixel)191 return total/float(num)192 def bits_per_pixel(self):193 ''' get the number of bits per pixel, which defines the maximum digital number value in the image '''194 return self.get_item('EXIF:BitsPerSample')195 def vignette_center(self):196 ''' get the vignette center in X and Y image coordinates'''197 nelem = self.size('XMP:VignettingCenter')198 return [float(self.get_item('XMP:VignettingCenter', i)) for i in range(nelem)]199 def vignette_polynomial(self):200 ''' get the radial vignette polynomial in the order it's defined in the metadata'''201 nelem = self.size('XMP:VignettingPolynomial')202 return [float(self.get_item('XMP:VignettingPolynomial', i)) for i in range(nelem)]203 def distortion_parameters(self):204 nelem = self.size('XMP:PerspectiveDistortion')205 return [float(self.get_item('XMP:PerspectiveDistortion', i)) for i in range(nelem)]206 def principal_point(self):207 return [float(item) for item in self.get_item('XMP:PrincipalPoint').split(',')]208 def focal_plane_resolution_px_per_mm(self):209 fp_x_resolution = float(self.get_item('EXIF:FocalPlaneXResolution'))210 fp_y_resolution = float(self.get_item('EXIF:FocalPlaneYResolution'))211 return fp_x_resolution, fp_y_resolution212 def focal_length_mm(self):213 units = self.get_item('XMP:PerspectiveFocalLengthUnits')214 focal_length_mm = 0.0215 if units == 'mm':216 focal_length_mm = float(self.get_item('XMP:PerspectiveFocalLength'))217 else:218 focal_length_px = float(self.get_item('XMP:PerspectiveFocalLength'))219 focal_length_mm = focal_length_px / self.focal_plane_resolution_px_per_mm()[0]220 return focal_length_mm221 def __float_or_zero(self, str):222 if str is not None:223 return float(str)224 else:225 return 0.0226 def spectral_irradiance(self):227 return self.__float_or_zero(self.get_item('XMP:SpectralIrradiance'))228 def horizontal_irradiance(self):229 return self.__float_or_zero(self.get_item('XMP:HorizontalIrradiance'))/100.0230 def scattered_irradiance(self):231 return self.__float_or_zero(self.get_item('XMP:ScatteredIrradiance'))232 def direct_irradiance(self):233 return self.__float_or_zero(self.get_item('XMP:DirectIrradiance'))234 def solar_azimuth(self):235 return self.__float_or_zero(self.get_item('XMP:SolarAzimuth'))236 def solar_elevation(self):237 return self.__float_or_zero(self.get_item('XMP:SolarElevation'))238 def estimated_direct_vector(self):239 if self.get_item('XMP:EstimatedDirectLightVector') is not None:240 return [self.__float_or_zero(item) for item in self.get_item('XMP:EstimatedDirectLightVector')]241 else:242 return None243 def auto_calibration_image(self):244 cal_tag = self.get_item('XMP:CalibrationPicture')245 return cal_tag is not None and \246 cal_tag == 2 and \247 self.panel_albedo() is not None and \248 self.panel_region() is not None and \249 self.panel_serial() is not None250 def panel_albedo(self):251 albedo = self.get_item('XMP:Albedo')252 if albedo is not None:253 return self.__float_or_zero(albedo)254 return albedo255 def panel_region(self):256 if self.get_item('XMP:ReflectArea') is not None:257 coords = [int(item) for item in self.get_item('XMP:ReflectArea').split(',')]258 return list(zip(coords[0::2], coords[1::2]))259 else:260 return None261 def panel_serial(self):...
binary_tree.py
Source:binary_tree.py
...14 node = Node(item)15 # If this is first item in the tree , set it as root16 if self.root is None:17 self.root = node18 print('Root is empty. Setting root to : %s' % node.get_item())19 self.size += 120 else: # Otherwise, we need to insert the item into the tree using the binary tree insert algorithm21 print('Root %s is not empty. Need to add %s as a child' % (self.root.get_item(), node.get_item()))22 self.insert(self.root, node)2324 def insert(self, parent, child):2526 # If child is less than parent, it goes here27 if child.get_item() < parent.get_item():28 print('Child %s is less than parent %s' % (child.get_item(), parent.get_item()))29 if parent.get_left() is None: # If left node is None (null) we have found our spot!30 print('Left node is %s. So we found our spot. Adding child %s here.' % (parent.get_left(), child.get_item()))31 parent.set_left(child)32 child.set_parent(parent)33 print("%s is the new left of parent %s " % (parent.get_left().get_item(), parent.get_item()))34 print("%s is the new parent of child %s " % (child.get_parent().get_item(), child.get_item()))35 self.size += 136 # Otherwise we need to call insert again and test for left or right (recursion)37 else:38 print('Left node is %s. So we haven not found our spot yet. Calling recursion to add child %s in the level below here.' % (parent.get_left().get_item(), child.get_item()))39 self.insert(parent.get_left(), child)4041 # If child is greater than parent, it goes to the right42 elif child.get_item() > parent.get_item():43 print('Child %s is greater than parent %s' % (child.get_item(), parent.get_item()))44 # If right node is null, we have found our spot!45 if parent.get_right() is None:46 print('Right node is %s. So we found our spot. Adding child %s here.' % (parent.get_right(), child.get_item()))47 parent.set_right(child)48 child.set_parent(parent)49 self.size += 150 else:51 # Otherwise we need to call insert again and test for left and right using recursion52 print('Right node is %s. So we haven not found our spot yet. Calling recursion to add child %s in the level below here.' % (parent.get_right().get_item(), child.get_item()))53 self.insert(parent.get_right(), child)54 # If the parent and child happen to be equal, we don't do anything assuming that the data in the binary tree is unique5556 def does_tree_contains(self, item):57 current_node = self.get_node(item)58 if current_node is None:59 return False60 else:61 return True6263 def get_node(self, item):64 current_node = self.root65 while current_node is not None:66 if item == current_node.get_item():67 return current_node68 elif item < current_node.get_item():69 current_node = current_node.get_left()70 else:71 current_node = current_node.get_right()7273 return None7475 def delete_item(self, item):76 deleted = False7778 # Make sure the root isn't null meaning the tree is empty79 if self.root is None:80 return False8182 if self.get_node(item) is None:83 return False8485 # Find the node to delete86 node_to_be_deleted = self.get_node(item)87 print("Deleting node %s" % node_to_be_deleted.get_item())8889 if node_to_be_deleted is not None:90 # If the node to delete doesn't have any children, just delete it91 if node_to_be_deleted.get_left() is None and node_to_be_deleted.get_right() is None:92 self.unlink_item(node_to_be_deleted, None)93 deleted = True94 # If the node to delete only has a right child, remove it in the h hierarchy95 elif node_to_be_deleted.get_left() is None and node_to_be_deleted.get_right() is not None:96 self.unlink_item(node_to_be_deleted, node_to_be_deleted.get_right())97 deleted = True98 # If the node to delete only has a left child, remove it in the h hierarchy99 elif node_to_be_deleted.get_left() is not None and node_to_be_deleted.get_right() is None:100 self.unlink_item(node_to_be_deleted, node_to_be_deleted.get_left())101 deleted = True102 # The node has both children, do a node swap to delete103 else:104 print("Node to be deleted is %s and current root is %s" % (node_to_be_deleted.get_item(), self.root.get_item()))105 print("Left child of %s is %s and Right child of %s is %s" % (node_to_be_deleted.get_item(), node_to_be_deleted.get_left().get_item(), node_to_be_deleted.get_item(), node_to_be_deleted.get_right().get_item()))106 print("Right child of %s is %s and its right child is %s" % (107 node_to_be_deleted.get_item(), node_to_be_deleted.get_right().get_item(), node_to_be_deleted.get_right().get_right().get_item()))108109 child = node_to_be_deleted.get_left()110 print("Candidate child node is %s" % child.get_item())111 print("child.get_right() is %s" % child.get_right().get_item())112 print("child.get_left() is %s" % child.get_left().get_item())113 while child.get_right() is not None and child.get_left() is not None:114 child = child.get_right()115 print("We found the most leaf node %s. We can replace the node to be deleted %s with this node" % (child.get_item(), node_to_be_deleted.get_item()))116 # We have the right most leaf node. We can replace the current node with this node117 child.get_parent().set_right(None) # Remove the leaf node from it's current position118119 child.set_left(node_to_be_deleted.get_left())120 print("Right node of Node t be deleted at this stage is %s" % node_to_be_deleted.get_right().get_item())121 child.set_right(node_to_be_deleted.get_right().get_right())122123 self.unlink_item(node_to_be_deleted, child)124 deleted = True125 if deleted:126 self.size -= 1127128 return deleted129130 def unlink_item(self, node_to_be_deleted, new_node):131 print("node_to_be_deleted is %s" % node_to_be_deleted.get_item())132 print("Unlinking Node: %s" % node_to_be_deleted.get_item())133 if new_node is not None:134 print("New Node is %s" % new_node.get_item())135136 if node_to_be_deleted.get_item() == self.root.get_item():137 print("Current Node is Root: %s" % node_to_be_deleted.get_item())138 new_node.set_left(node_to_be_deleted.get_left())139 new_node.set_right(node_to_be_deleted.get_right())140 self.root = new_node141 print("New root is %s. New root left node is %s. New root right node is %s" % (self.root.get_item(), self.root.get_left().get_item(), self.root.get_right().get_item()))142 elif node_to_be_deleted.get_parent().get_right().get_item() == node_to_be_deleted.get_item():143 node_to_be_deleted.get_parent().set_right(new_node)144 else:145 node_to_be_deleted.get_parent().set_left(new_node)146147 def display_tree_data(self):148149 print("Tree Root is: %s" % self.root.get_item())150 child_node = self.root.get_left()151152 print("................... Left side Nodes from tree Root ...................")153 while child_node:154 print("Left child_node is %s" % child_node.get_item())155 if child_node.get_right() is not None:156 print("Right child_node is %s" % child_node.get_right().get_item())157 child_node = child_node.get_left()158159 print("................... Right side Nodes from tree Root ...................")160 child_node = self.root.get_right()161 while child_node:162 print("Right child_node is %s" % child_node.get_item())163 if child_node.get_left() is not None:164 print("Left child_node is %s" % child_node.get_left().get_item())
...
certutils.py
Source:certutils.py
...30 def cert_date_to_gmt_date(self, d):31 return datetime.datetime.strptime(d.decode('ascii'), '%Y%m%d%H%M%SZ')32 def cert_date_to_gmt_date_string(self, d):33 return self.cert_date_to_gmt_date(d).strftime("%Y-%m-%d %H:%M:%S GMT")34 def get_item(self, item, extension=None, return_as=None, algo=None):35 try:36 if item == 'subject':37 return self.decode_x509name_obj(self.cert.get_subject())3839 elif item == 'subject_o':40 return self.cert.get_subject().O.strip()4142 elif item == 'subject_cn':43 return self.cert.get_subject().CN.strip()4445 elif item == 'extensions':46 ext_count = self.cert.get_extension_count()47 if extension is None:48 ext_infos = []49 for i in range (0, ext_count):50 ext = self.cert.get_extension(i)51 ext_infos.append(ext.get_short_name().decode('utf-8'))52 return ext_infos5354 for i in range (0, ext_count):55 ext = self.cert.get_extension(i)56 if extension in str(ext.get_short_name()):57 return ext.__str__().strip()58 return None5960 elif item == 'version':61 return self.cert.get_version()6263 elif item == 'pubkey_type':64 pk_type = self.cert.get_pubkey().type()65 if pk_type == crypto.TYPE_RSA:66 return 'RSA'67 elif pk_type == crypto.TYPE_DSA:68 return 'DSA'69 return 'Unknown'7071 elif item == 'pubkey_pem':72 return crypto.dump_publickey(crypto.FILETYPE_PEM, self.cert.get_pubkey()).decode('utf-8')7374 elif item == 'serial_number':75 return self.cert.get_serial_number()7677 elif item == 'not_before':78 not_before = self.cert.get_notBefore()79 if return_as == 'string':80 return self.cert_date_to_gmt_date_string(not_before)81 return self.cert_date_to_gmt_date(not_before)8283 elif item == 'not_after':84 not_after = self.cert.get_notAfter()85 if return_as == 'string':86 return self.cert_date_to_gmt_date_string(not_after)87 return self.cert_date_to_gmt_date(not_after)8889 elif item == 'has_expired':90 return self.cert.has_expired()9192 elif item == 'issuer':93 return self.decode_x509name_obj(self.cert.get_issuer())9495 elif item == 'issuer_o':96 return self.cert.get_issuer().O.strip()9798 elif item == 'issuer_cn':99 return self.cert.get_issuer().CN.strip()100101 elif item == 'signature_algorithm':102 return self.cert.get_signature_algorithm().decode('utf-8')103104 elif item == 'digest':105 # ['md5', 'sha1', 'sha256', 'sha512']106 return self.cert.digest(algo)107108 elif item == 'pem':109 return crypto.dump_certificate(crypto.FILETYPE_PEM, self.cert).decode('utf-8')110111 else:112 return None113114 except Exception as e:115 # logger.error('item = {}, exception, e = {}'.format(item, e))116 return None117 @property118 def subject(self):119 return self.get_item('subject')120 @property121 def subject_o(self):122 return self.get_item('subject_o')123 @property124 def subject_cn(self):125 return self.get_item('subject_cn')126 @property127 def subject_name_hash(self):128 return self.get_item('subject_name_hash')129 @property130 def extension_count(self):131 return self.get_item('extension_count')132 @property133 def extensions(self):134 return self.get_item('extensions')135 @property136 def extension_basic_constraints(self):137 return self.get_item('extensions', extension='basicConstraints')138 @property139 def extension_subject_key_identifier(self):140 return self.get_item('extensions', extension='subjectKeyIdentifier')141 @property142 def extension_authority_key_identifier(self):143 return self.get_item('extensions', extension='authorityKeyIdentifier')144 @property145 def extension_subject_alt_name(self):146 return self.get_item('extensions', extension='subjectAltName')147 @property148 def version(self):149 return self.get_item('version')150 @property151 def pubkey_type(self):152 return self.get_item('pubkey_type')153 @property154 def pubkey_pem(self):155 return self.get_item('pubkey_pem')156 @property157 def serial_number(self):158 return self.get_item('serial_number')159 @property160 def not_before(self):161 return self.get_item('not_before')162 @property163 def not_before_s(self):164 return self.get_item('not_before', return_as='string')165 @property166 def not_after(self):167 return self.get_item('not_after')168 @property169 def not_after_s(self):170 return self.get_item('not_after', return_as='string')171 @property172 def has_expired(self):173 return self.get_item('has_expired')174 @property175 def issuer(self):176 return self.get_item('issuer')177 @property178 def issuer_o(self):179 return self.get_item('issuer_o')180 @property181 def issuer_cn(self):182 return self.get_item('issuer_cn')183 @property184 def signature_algorithm(self):185 return self.get_item('signature_algorithm')186 @property187 def digest_sha256(self):188 return self.get_item('digest', algo='sha256')189 @property190 def pem(self):191 return self.get_item('pem')192193194def verify_certificate_chain(cert_pem, trusted_certs):195 certificate = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)196 # parse ceritificate information197 clientcert = CertInfo(certificate)198 # get subject common name199 subject = clientcert.subject_cn200 issuer = clientcert.issuer_cn201 # Check if subject is admin user202 if subject != "admin":203 raise Exception("Not trusted user")204 # validate issuer 205 if issuer != "ca":
...
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!!