body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
a682ce6fb14335ce79cb06f303e7980caf9ec1a8ce71b71daafa3dda947313c4
def p_factor_ID(p): 'factor : ID' p[0] = s.Id('<factor>', [], p[1])
factor : ID
parser.py
p_factor_ID
FaruNL/compiler-2
0
python
def p_factor_ID(p): p[0] = s.Id('<factor>', [], p[1])
def p_factor_ID(p): p[0] = s.Id('<factor>', [], p[1])<|docstring|>factor : ID<|endoftext|>
adbd15f95cddbb91b9f7ac88dd75dbb9f2eb02522dde8cbd8f99c70058bace0e
def p_factor_NUMBER(p): 'factor : NUMBER' p[0] = s.Number('<factor>', [], p[1])
factor : NUMBER
parser.py
p_factor_NUMBER
FaruNL/compiler-2
0
python
def p_factor_NUMBER(p): p[0] = s.Number('<factor>', [], p[1])
def p_factor_NUMBER(p): p[0] = s.Number('<factor>', [], p[1])<|docstring|>factor : NUMBER<|endoftext|>
e296b2b09c65b6cbe2bef8249658ba88223d40a48cf4feb51b0ba88fde8644d2
def p_factor_GROUP(p): 'factor : LPAREN expression RPAREN' p[0] = s.Group('group_expression', [p[2]])
factor : LPAREN expression RPAREN
parser.py
p_factor_GROUP
FaruNL/compiler-2
0
python
def p_factor_GROUP(p): p[0] = s.Group('group_expression', [p[2]])
def p_factor_GROUP(p): p[0] = s.Group('group_expression', [p[2]])<|docstring|>factor : LPAREN expression RPAREN<|endoftext|>
b46e3188d2d042b3d99b8b28c7cdbda261c2a0867533ed9b829a5211d1045a2c
def p_empty(p): 'empty :' pass
empty :
parser.py
p_empty
FaruNL/compiler-2
0
python
def p_empty(p): pass
def p_empty(p): pass<|docstring|>empty :<|endoftext|>
1814a0c699d4a715ad9803463e8b1a393c9d2eebc064bd3fb9ee8d53ec114a0d
def create_empty_iod(self): 'Creates and empty IOD with the required DICOM tags but no values\n Parameters\n ----------\n ' super().create_empty_iod() self.copy_required_dicom_attributes(Dataset(), include_optional=True)
Creates and empty IOD with the required DICOM tags but no values Parameters ----------
pydicomutils/IODs/CSPS.py
create_empty_iod
sectra-medical/pydicomutils
8
python
def create_empty_iod(self): 'Creates and empty IOD with the required DICOM tags but no values\n Parameters\n ----------\n ' super().create_empty_iod() self.copy_required_dicom_attributes(Dataset(), include_optional=True)
def create_empty_iod(self): 'Creates and empty IOD with the required DICOM tags but no values\n Parameters\n ----------\n ' super().create_empty_iod() self.copy_required_dicom_attributes(Dataset(), include_optional=True)<|docstring|>Creates and empty IOD with the required DICOM tags but no values Parameters ----------<|endoftext|>
ccc84ecd472f24cd2a789fd84398879096b306c3001c2f2c95bf32df02c3606f
def copy_required_dicom_attributes(self, dataset_to_copy_from, include_iod_specific=True, include_optional=False): 'Copies required DICOM attributes from provided dataset\n Parameters\n ----------\n dataset_to_copy_from : Dataset to copy DICOM attributes from\n include_iod_specific : Include IOD specific DICOM attributes in copy (True)\n include_optional : Include optional DICOM attributes in copy (False)\n ' super().copy_required_dicom_attributes(dataset_to_copy_from, include_optional) if include_iod_specific: pr_specific_modules = [PresentationModule(), PresentationStateIdentificationModule(), PresentationStateRelationshipModule(), DisplayedAreaModule()] for module in pr_specific_modules: module.copy_required_dicom_attributes(dataset_to_copy_from, self.dataset) if include_optional: module.copy_optional_dicom_attributes(dataset_to_copy_from, self.dataset)
Copies required DICOM attributes from provided dataset Parameters ---------- dataset_to_copy_from : Dataset to copy DICOM attributes from include_iod_specific : Include IOD specific DICOM attributes in copy (True) include_optional : Include optional DICOM attributes in copy (False)
pydicomutils/IODs/CSPS.py
copy_required_dicom_attributes
sectra-medical/pydicomutils
8
python
def copy_required_dicom_attributes(self, dataset_to_copy_from, include_iod_specific=True, include_optional=False): 'Copies required DICOM attributes from provided dataset\n Parameters\n ----------\n dataset_to_copy_from : Dataset to copy DICOM attributes from\n include_iod_specific : Include IOD specific DICOM attributes in copy (True)\n include_optional : Include optional DICOM attributes in copy (False)\n ' super().copy_required_dicom_attributes(dataset_to_copy_from, include_optional) if include_iod_specific: pr_specific_modules = [PresentationModule(), PresentationStateIdentificationModule(), PresentationStateRelationshipModule(), DisplayedAreaModule()] for module in pr_specific_modules: module.copy_required_dicom_attributes(dataset_to_copy_from, self.dataset) if include_optional: module.copy_optional_dicom_attributes(dataset_to_copy_from, self.dataset)
def copy_required_dicom_attributes(self, dataset_to_copy_from, include_iod_specific=True, include_optional=False): 'Copies required DICOM attributes from provided dataset\n Parameters\n ----------\n dataset_to_copy_from : Dataset to copy DICOM attributes from\n include_iod_specific : Include IOD specific DICOM attributes in copy (True)\n include_optional : Include optional DICOM attributes in copy (False)\n ' super().copy_required_dicom_attributes(dataset_to_copy_from, include_optional) if include_iod_specific: pr_specific_modules = [PresentationModule(), PresentationStateIdentificationModule(), PresentationStateRelationshipModule(), DisplayedAreaModule()] for module in pr_specific_modules: module.copy_required_dicom_attributes(dataset_to_copy_from, self.dataset) if include_optional: module.copy_optional_dicom_attributes(dataset_to_copy_from, self.dataset)<|docstring|>Copies required DICOM attributes from provided dataset Parameters ---------- dataset_to_copy_from : Dataset to copy DICOM attributes from include_iod_specific : Include IOD specific DICOM attributes in copy (True) include_optional : Include optional DICOM attributes in copy (False)<|endoftext|>
566ae396fa640cb3d9b1b4ca6398e8214bc432beb4b73ef3cf14581e3d7c7aaf
def initiate(self, referenced_dcm_files=None): 'Initiate the IOD by setting some dummy values for required attributes\n \n Keyword Arguments:\n referenced_dcm_files {[dcm_file1, dcm_file2, ...]} -- List of file paths (default: {None})\n ' super().initiate() if referenced_dcm_files: ds = read_file(referenced_dcm_files[0]) self.dataset.PatientID = ds.PatientID self.dataset.PatientName = ds.PatientName self.dataset.PatientSex = ds.PatientSex self.dataset.PatientBirthDate = ds.PatientBirthDate self.dataset.StudyInstanceUID = ds.StudyInstanceUID self.dataset.StudyID = ds.StudyID self.dataset.AccessionNumber = ds.AccessionNumber if ('StudyDescription' in ds): self.dataset.StudyDescription = ds.StudyDescription self.dataset.StudyDate = ds.StudyDate self.dataset.StudyTime = ds.StudyTime self.dataset.Modality = SOP_CLASS_UID_MODALITY_DICT[self.iod_type] self.dataset.PresentationCreationDate = datetime.now().strftime('%Y%m%d') self.dataset.PresentationCreationTime = datetime.now().strftime('%H%M%S') self.dataset.InstanceNumber = str(1) self.dataset.ContentLabel = 'PRESENTATION_STATE' if referenced_dcm_files: self.dataset.ReferencedSeriesSequence = generate_RS_sequence(referenced_dcm_files) if referenced_dcm_files: self.dataset.DisplayedAreaSelectionSequence = generate_DAS_sequence(referenced_dcm_files) self.dataset.PresentationLUTShape = 'IDENTITY'
Initiate the IOD by setting some dummy values for required attributes Keyword Arguments: referenced_dcm_files {[dcm_file1, dcm_file2, ...]} -- List of file paths (default: {None})
pydicomutils/IODs/CSPS.py
initiate
sectra-medical/pydicomutils
8
python
def initiate(self, referenced_dcm_files=None): 'Initiate the IOD by setting some dummy values for required attributes\n \n Keyword Arguments:\n referenced_dcm_files {[dcm_file1, dcm_file2, ...]} -- List of file paths (default: {None})\n ' super().initiate() if referenced_dcm_files: ds = read_file(referenced_dcm_files[0]) self.dataset.PatientID = ds.PatientID self.dataset.PatientName = ds.PatientName self.dataset.PatientSex = ds.PatientSex self.dataset.PatientBirthDate = ds.PatientBirthDate self.dataset.StudyInstanceUID = ds.StudyInstanceUID self.dataset.StudyID = ds.StudyID self.dataset.AccessionNumber = ds.AccessionNumber if ('StudyDescription' in ds): self.dataset.StudyDescription = ds.StudyDescription self.dataset.StudyDate = ds.StudyDate self.dataset.StudyTime = ds.StudyTime self.dataset.Modality = SOP_CLASS_UID_MODALITY_DICT[self.iod_type] self.dataset.PresentationCreationDate = datetime.now().strftime('%Y%m%d') self.dataset.PresentationCreationTime = datetime.now().strftime('%H%M%S') self.dataset.InstanceNumber = str(1) self.dataset.ContentLabel = 'PRESENTATION_STATE' if referenced_dcm_files: self.dataset.ReferencedSeriesSequence = generate_RS_sequence(referenced_dcm_files) if referenced_dcm_files: self.dataset.DisplayedAreaSelectionSequence = generate_DAS_sequence(referenced_dcm_files) self.dataset.PresentationLUTShape = 'IDENTITY'
def initiate(self, referenced_dcm_files=None): 'Initiate the IOD by setting some dummy values for required attributes\n \n Keyword Arguments:\n referenced_dcm_files {[dcm_file1, dcm_file2, ...]} -- List of file paths (default: {None})\n ' super().initiate() if referenced_dcm_files: ds = read_file(referenced_dcm_files[0]) self.dataset.PatientID = ds.PatientID self.dataset.PatientName = ds.PatientName self.dataset.PatientSex = ds.PatientSex self.dataset.PatientBirthDate = ds.PatientBirthDate self.dataset.StudyInstanceUID = ds.StudyInstanceUID self.dataset.StudyID = ds.StudyID self.dataset.AccessionNumber = ds.AccessionNumber if ('StudyDescription' in ds): self.dataset.StudyDescription = ds.StudyDescription self.dataset.StudyDate = ds.StudyDate self.dataset.StudyTime = ds.StudyTime self.dataset.Modality = SOP_CLASS_UID_MODALITY_DICT[self.iod_type] self.dataset.PresentationCreationDate = datetime.now().strftime('%Y%m%d') self.dataset.PresentationCreationTime = datetime.now().strftime('%H%M%S') self.dataset.InstanceNumber = str(1) self.dataset.ContentLabel = 'PRESENTATION_STATE' if referenced_dcm_files: self.dataset.ReferencedSeriesSequence = generate_RS_sequence(referenced_dcm_files) if referenced_dcm_files: self.dataset.DisplayedAreaSelectionSequence = generate_DAS_sequence(referenced_dcm_files) self.dataset.PresentationLUTShape = 'IDENTITY'<|docstring|>Initiate the IOD by setting some dummy values for required attributes Keyword Arguments: referenced_dcm_files {[dcm_file1, dcm_file2, ...]} -- List of file paths (default: {None})<|endoftext|>
416732ae403dc8e0dc82c66b8fc5f9471a76ab9a6fad2270b4a2acd48281f5f1
def add_graphical_layer(self, layer_name, layer_order, recommended_grayscale_value=None, recommended_cielab_value=None, layer_description=None): 'Add graphical layer\n \n Arguments:\n layer_name {str} -- Name of layer\n layer_order {int} -- Order of layer\n \n Keyword Arguments:\n recommended_grayscale_value {[type]} -- [description] (default: {None})\n recommended_cielab_value {[type]} -- [description] (default: {None})\n layer_description {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds.GraphicLayer = layer_name ds.GraphicLayerOrder = layer_order if (recommended_grayscale_value is not None): ds.GraphicLayerRecommendedDisplayGrayscaleValue = recommended_grayscale_value if (recommended_cielab_value is not None): ds.GraphicLayerRecommendedDisplayCIELabValue = recommended_cielab_value if (layer_description is not None): ds.GraphicLayerDescription = layer_description if ('GraphicLayerSequence' not in self.dataset): self.dataset.GraphicLayerSequence = generate_sequence('GraphicLayerSequence', [{}]) self.dataset.GraphicLayerSequence.append(ds)
Add graphical layer Arguments: layer_name {str} -- Name of layer layer_order {int} -- Order of layer Keyword Arguments: recommended_grayscale_value {[type]} -- [description] (default: {None}) recommended_cielab_value {[type]} -- [description] (default: {None}) layer_description {[type]} -- [description] (default: {None})
pydicomutils/IODs/CSPS.py
add_graphical_layer
sectra-medical/pydicomutils
8
python
def add_graphical_layer(self, layer_name, layer_order, recommended_grayscale_value=None, recommended_cielab_value=None, layer_description=None): 'Add graphical layer\n \n Arguments:\n layer_name {str} -- Name of layer\n layer_order {int} -- Order of layer\n \n Keyword Arguments:\n recommended_grayscale_value {[type]} -- [description] (default: {None})\n recommended_cielab_value {[type]} -- [description] (default: {None})\n layer_description {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds.GraphicLayer = layer_name ds.GraphicLayerOrder = layer_order if (recommended_grayscale_value is not None): ds.GraphicLayerRecommendedDisplayGrayscaleValue = recommended_grayscale_value if (recommended_cielab_value is not None): ds.GraphicLayerRecommendedDisplayCIELabValue = recommended_cielab_value if (layer_description is not None): ds.GraphicLayerDescription = layer_description if ('GraphicLayerSequence' not in self.dataset): self.dataset.GraphicLayerSequence = generate_sequence('GraphicLayerSequence', [{}]) self.dataset.GraphicLayerSequence.append(ds)
def add_graphical_layer(self, layer_name, layer_order, recommended_grayscale_value=None, recommended_cielab_value=None, layer_description=None): 'Add graphical layer\n \n Arguments:\n layer_name {str} -- Name of layer\n layer_order {int} -- Order of layer\n \n Keyword Arguments:\n recommended_grayscale_value {[type]} -- [description] (default: {None})\n recommended_cielab_value {[type]} -- [description] (default: {None})\n layer_description {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds.GraphicLayer = layer_name ds.GraphicLayerOrder = layer_order if (recommended_grayscale_value is not None): ds.GraphicLayerRecommendedDisplayGrayscaleValue = recommended_grayscale_value if (recommended_cielab_value is not None): ds.GraphicLayerRecommendedDisplayCIELabValue = recommended_cielab_value if (layer_description is not None): ds.GraphicLayerDescription = layer_description if ('GraphicLayerSequence' not in self.dataset): self.dataset.GraphicLayerSequence = generate_sequence('GraphicLayerSequence', [{}]) self.dataset.GraphicLayerSequence.append(ds)<|docstring|>Add graphical layer Arguments: layer_name {str} -- Name of layer layer_order {int} -- Order of layer Keyword Arguments: recommended_grayscale_value {[type]} -- [description] (default: {None}) recommended_cielab_value {[type]} -- [description] (default: {None}) layer_description {[type]} -- [description] (default: {None})<|endoftext|>
0ed395b6ae61621e5f77ada4270631fd31e1405964e67bd1ab68a22464930118
def add_graphic_object(self, referenced_dcm_file, layer_name, graphic_data, graphic_type, graphic_filled=None, cielab_value=None, shadow_style=None, line_thickness=None): 'Add graphical object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n graphic_data {[type]} -- [description]\n graphic_type {[type]} -- [description]\n \n Keyword Arguments:\n graphic_filled {[type]} -- [description] (default: {None})\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n line_thickness {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.GraphicObjectSequence = generate_sequence('GraphicObjectSequence', [{'GraphicAnnotationUnits': 'PIXEL', 'GraphicDimensions': 2, 'NumberOfGraphicPoints': int((len(graphic_data) / 2)), 'GraphicData': graphic_data, 'GraphicType': graphic_type}]) if graphic_filled: ds.GraphicObjectSequence[0].GraphicFilled = graphic_filled if (cielab_value or shadow_style or line_thickness): ds.GraphicObjectSequence[0].LineStyleSequence = generate_sequence('LineStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].LineStyleSequence[0].PatternOnColorCIELabValue = cielab_value if shadow_style: ds.GraphicObjectSequence[0].LineStyleSequence[0].ShadowStyle = shadow_style if line_thickness: ds.GraphicObjectSequence[0].LineStyleSequence[0].LineThickness = line_thickness if (graphic_filled and cielab_value): ds.GraphicObjectSequence[0].FillStyleSequence = generate_sequence('FillStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].FillStyleSequence[0].PatternOnColorCIELabValue = cielab_value if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)
Add graphical object Arguments: referenced_dcm_file {[type]} -- [description] layer_name {[type]} -- [description] graphic_data {[type]} -- [description] graphic_type {[type]} -- [description] Keyword Arguments: graphic_filled {[type]} -- [description] (default: {None}) cielab_value {[type]} -- [description] (default: {None}) shadow_style {[type]} -- [description] (default: {None}) line_thickness {[type]} -- [description] (default: {None})
pydicomutils/IODs/CSPS.py
add_graphic_object
sectra-medical/pydicomutils
8
python
def add_graphic_object(self, referenced_dcm_file, layer_name, graphic_data, graphic_type, graphic_filled=None, cielab_value=None, shadow_style=None, line_thickness=None): 'Add graphical object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n graphic_data {[type]} -- [description]\n graphic_type {[type]} -- [description]\n \n Keyword Arguments:\n graphic_filled {[type]} -- [description] (default: {None})\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n line_thickness {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.GraphicObjectSequence = generate_sequence('GraphicObjectSequence', [{'GraphicAnnotationUnits': 'PIXEL', 'GraphicDimensions': 2, 'NumberOfGraphicPoints': int((len(graphic_data) / 2)), 'GraphicData': graphic_data, 'GraphicType': graphic_type}]) if graphic_filled: ds.GraphicObjectSequence[0].GraphicFilled = graphic_filled if (cielab_value or shadow_style or line_thickness): ds.GraphicObjectSequence[0].LineStyleSequence = generate_sequence('LineStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].LineStyleSequence[0].PatternOnColorCIELabValue = cielab_value if shadow_style: ds.GraphicObjectSequence[0].LineStyleSequence[0].ShadowStyle = shadow_style if line_thickness: ds.GraphicObjectSequence[0].LineStyleSequence[0].LineThickness = line_thickness if (graphic_filled and cielab_value): ds.GraphicObjectSequence[0].FillStyleSequence = generate_sequence('FillStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].FillStyleSequence[0].PatternOnColorCIELabValue = cielab_value if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)
def add_graphic_object(self, referenced_dcm_file, layer_name, graphic_data, graphic_type, graphic_filled=None, cielab_value=None, shadow_style=None, line_thickness=None): 'Add graphical object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n graphic_data {[type]} -- [description]\n graphic_type {[type]} -- [description]\n \n Keyword Arguments:\n graphic_filled {[type]} -- [description] (default: {None})\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n line_thickness {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.GraphicObjectSequence = generate_sequence('GraphicObjectSequence', [{'GraphicAnnotationUnits': 'PIXEL', 'GraphicDimensions': 2, 'NumberOfGraphicPoints': int((len(graphic_data) / 2)), 'GraphicData': graphic_data, 'GraphicType': graphic_type}]) if graphic_filled: ds.GraphicObjectSequence[0].GraphicFilled = graphic_filled if (cielab_value or shadow_style or line_thickness): ds.GraphicObjectSequence[0].LineStyleSequence = generate_sequence('LineStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].LineStyleSequence[0].PatternOnColorCIELabValue = cielab_value if shadow_style: ds.GraphicObjectSequence[0].LineStyleSequence[0].ShadowStyle = shadow_style if line_thickness: ds.GraphicObjectSequence[0].LineStyleSequence[0].LineThickness = line_thickness if (graphic_filled and cielab_value): ds.GraphicObjectSequence[0].FillStyleSequence = generate_sequence('FillStyleSequence', [{}]) if cielab_value: ds.GraphicObjectSequence[0].FillStyleSequence[0].PatternOnColorCIELabValue = cielab_value if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)<|docstring|>Add graphical object Arguments: referenced_dcm_file {[type]} -- [description] layer_name {[type]} -- [description] graphic_data {[type]} -- [description] graphic_type {[type]} -- [description] Keyword Arguments: graphic_filled {[type]} -- [description] (default: {None}) cielab_value {[type]} -- [description] (default: {None}) shadow_style {[type]} -- [description] (default: {None}) line_thickness {[type]} -- [description] (default: {None})<|endoftext|>
a23cc90b0bcd4574e2457cf35dbaa155b1af893885d0d3e54c03223262427fd0
def add_text_object(self, referenced_dcm_file, layer_name, text_value, anchor_point, cielab_value=None, shadow_style=None): 'Add text object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n text_value {[type]} -- [description]\n anchor_point {[type]} -- [description]\n \n Keyword Arguments:\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.TextObjectSequence = generate_sequence('TextObjectSequence', [{'AnchorPointAnnotationUnits': 'PIXEL', 'UnformattedTextValue': text_value, 'AnchorPoint': anchor_point, 'AnchorPointVisibility': 'N'}]) if (cielab_value or shadow_style): ds.TextObjectSequence[0].TextStyleSequence = generate_sequence('TextStyleSequence', [{}]) if cielab_value: ds.TextObjectSequence[0].TextStyleSequence[0].TextColorCIELabValue = cielab_value if shadow_style: ds.TextObjectSequence[0].TextStyleSequence[0].ShadowStyle = shadow_style if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)
Add text object Arguments: referenced_dcm_file {[type]} -- [description] layer_name {[type]} -- [description] text_value {[type]} -- [description] anchor_point {[type]} -- [description] Keyword Arguments: cielab_value {[type]} -- [description] (default: {None}) shadow_style {[type]} -- [description] (default: {None})
pydicomutils/IODs/CSPS.py
add_text_object
sectra-medical/pydicomutils
8
python
def add_text_object(self, referenced_dcm_file, layer_name, text_value, anchor_point, cielab_value=None, shadow_style=None): 'Add text object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n text_value {[type]} -- [description]\n anchor_point {[type]} -- [description]\n \n Keyword Arguments:\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.TextObjectSequence = generate_sequence('TextObjectSequence', [{'AnchorPointAnnotationUnits': 'PIXEL', 'UnformattedTextValue': text_value, 'AnchorPoint': anchor_point, 'AnchorPointVisibility': 'N'}]) if (cielab_value or shadow_style): ds.TextObjectSequence[0].TextStyleSequence = generate_sequence('TextStyleSequence', [{}]) if cielab_value: ds.TextObjectSequence[0].TextStyleSequence[0].TextColorCIELabValue = cielab_value if shadow_style: ds.TextObjectSequence[0].TextStyleSequence[0].ShadowStyle = shadow_style if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)
def add_text_object(self, referenced_dcm_file, layer_name, text_value, anchor_point, cielab_value=None, shadow_style=None): 'Add text object\n \n Arguments:\n referenced_dcm_file {[type]} -- [description]\n layer_name {[type]} -- [description]\n text_value {[type]} -- [description]\n anchor_point {[type]} -- [description]\n \n Keyword Arguments:\n cielab_value {[type]} -- [description] (default: {None})\n shadow_style {[type]} -- [description] (default: {None})\n ' ds = Dataset() ds_ref = read_file(referenced_dcm_file) ds.ReferencedImageSequence = generate_sequence('ReferencedImageSequence', [{'ReferencedSOPClassUID': ds_ref.SOPClassUID, 'ReferencedSOPInstanceUID': ds_ref.SOPInstanceUID}]) ds.GraphicLayer = layer_name ds.TextObjectSequence = generate_sequence('TextObjectSequence', [{'AnchorPointAnnotationUnits': 'PIXEL', 'UnformattedTextValue': text_value, 'AnchorPoint': anchor_point, 'AnchorPointVisibility': 'N'}]) if (cielab_value or shadow_style): ds.TextObjectSequence[0].TextStyleSequence = generate_sequence('TextStyleSequence', [{}]) if cielab_value: ds.TextObjectSequence[0].TextStyleSequence[0].TextColorCIELabValue = cielab_value if shadow_style: ds.TextObjectSequence[0].TextStyleSequence[0].ShadowStyle = shadow_style if ('GraphicAnnotationSequence' not in self.dataset): self.dataset.GraphicAnnotationSequence = generate_sequence('GraphicAnnotationSequence', [{}]) self.dataset.GraphicAnnotationSequence.append(ds)<|docstring|>Add text object Arguments: referenced_dcm_file {[type]} -- [description] layer_name {[type]} -- [description] text_value {[type]} -- [description] anchor_point {[type]} -- [description] Keyword Arguments: cielab_value {[type]} -- [description] (default: {None}) shadow_style {[type]} -- [description] (default: {None})<|endoftext|>
1a6d03dd0e70bf0d81b87a0ed9c3290eee3f38566fa927121fa11f7826130e3c
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: 'Stylize a plot by adding the curve metadata.\n\n Args:\n fig: Plot figure.\n ax: Plot axes.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.x_dim is not None): ax.set_xlabel(self.x_dim) if (self.y_dim is not None): ax.set_ylabel(self.y_dim) return (fig, ax)
Stylize a plot by adding the curve metadata. Args: fig: Plot figure. ax: Plot axes. Returns: The updated figure and axes of the plot.
performance_curves/curve.py
draw_to
erp12/performance-curves
0
python
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: 'Stylize a plot by adding the curve metadata.\n\n Args:\n fig: Plot figure.\n ax: Plot axes.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.x_dim is not None): ax.set_xlabel(self.x_dim) if (self.y_dim is not None): ax.set_ylabel(self.y_dim) return (fig, ax)
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: 'Stylize a plot by adding the curve metadata.\n\n Args:\n fig: Plot figure.\n ax: Plot axes.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.x_dim is not None): ax.set_xlabel(self.x_dim) if (self.y_dim is not None): ax.set_ylabel(self.y_dim) return (fig, ax)<|docstring|>Stylize a plot by adding the curve metadata. Args: fig: Plot figure. ax: Plot axes. Returns: The updated figure and axes of the plot.<|endoftext|>
35a5bc93d2375098cecc4a74f66162439bd0beaf14edf1f192c541525c21b354
def __init__(self, x: np.ndarray, y: np.ndarray, meta: Optional[CurveMeta]=None): 'Instantiate a `Curve`.\n\n Args:\n x: Array of values for the x-dimension.\n y: Array of values for the y-dimension. Should correspond to `x` position-wise.\n meta: Optional curve metadata.\n ' self.x = x self.y = y self.meta = meta
Instantiate a `Curve`. Args: x: Array of values for the x-dimension. y: Array of values for the y-dimension. Should correspond to `x` position-wise. meta: Optional curve metadata.
performance_curves/curve.py
__init__
erp12/performance-curves
0
python
def __init__(self, x: np.ndarray, y: np.ndarray, meta: Optional[CurveMeta]=None): 'Instantiate a `Curve`.\n\n Args:\n x: Array of values for the x-dimension.\n y: Array of values for the y-dimension. Should correspond to `x` position-wise.\n meta: Optional curve metadata.\n ' self.x = x self.y = y self.meta = meta
def __init__(self, x: np.ndarray, y: np.ndarray, meta: Optional[CurveMeta]=None): 'Instantiate a `Curve`.\n\n Args:\n x: Array of values for the x-dimension.\n y: Array of values for the y-dimension. Should correspond to `x` position-wise.\n meta: Optional curve metadata.\n ' self.x = x self.y = y self.meta = meta<|docstring|>Instantiate a `Curve`. Args: x: Array of values for the x-dimension. y: Array of values for the y-dimension. Should correspond to `x` position-wise. meta: Optional curve metadata.<|endoftext|>
89b4b69a00745c222d1529b9dd056043da947dd1aad599719c675adea01ad358
@property def arrays(self) -> SynchronizedArrays: 'The underlying arrays that make up the points of the curve.' return SynchronizedArrays(arrays={'x': self.x, 'y': self.y})
The underlying arrays that make up the points of the curve.
performance_curves/curve.py
arrays
erp12/performance-curves
0
python
@property def arrays(self) -> SynchronizedArrays: return SynchronizedArrays(arrays={'x': self.x, 'y': self.y})
@property def arrays(self) -> SynchronizedArrays: return SynchronizedArrays(arrays={'x': self.x, 'y': self.y})<|docstring|>The underlying arrays that make up the points of the curve.<|endoftext|>
feb76ecf06e2dc99ea297d3a4ca7fd054de3268e6fd0e8cb71a30f0a8a49389f
def draw_line(self, fig: plt.Figure, ax: plt.Axes, **kwargs) -> Tuple[(plt.Figure, plt.Axes)]: 'Draw the curve as a line on the given plot.\n\n @todo Add links to matplotlib documentation for the style overrides.\n @todo Should this method be public or private?\n\n Args:\n fig: The figure of the plot.\n ax: The axes of the plot.\n **kwargs: Additional plotting options to pass to `.plot` of matplotlib.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.meta is None): ax.plot(self.x, self.y, **kwargs) else: ax.plot(self.x, self.y, label=self.meta.name, **kwargs) return (fig, ax)
Draw the curve as a line on the given plot. @todo Add links to matplotlib documentation for the style overrides. @todo Should this method be public or private? Args: fig: The figure of the plot. ax: The axes of the plot. **kwargs: Additional plotting options to pass to `.plot` of matplotlib. Returns: The updated figure and axes of the plot.
performance_curves/curve.py
draw_line
erp12/performance-curves
0
python
def draw_line(self, fig: plt.Figure, ax: plt.Axes, **kwargs) -> Tuple[(plt.Figure, plt.Axes)]: 'Draw the curve as a line on the given plot.\n\n @todo Add links to matplotlib documentation for the style overrides.\n @todo Should this method be public or private?\n\n Args:\n fig: The figure of the plot.\n ax: The axes of the plot.\n **kwargs: Additional plotting options to pass to `.plot` of matplotlib.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.meta is None): ax.plot(self.x, self.y, **kwargs) else: ax.plot(self.x, self.y, label=self.meta.name, **kwargs) return (fig, ax)
def draw_line(self, fig: plt.Figure, ax: plt.Axes, **kwargs) -> Tuple[(plt.Figure, plt.Axes)]: 'Draw the curve as a line on the given plot.\n\n @todo Add links to matplotlib documentation for the style overrides.\n @todo Should this method be public or private?\n\n Args:\n fig: The figure of the plot.\n ax: The axes of the plot.\n **kwargs: Additional plotting options to pass to `.plot` of matplotlib.\n\n Returns:\n The updated figure and axes of the plot.\n ' if (self.meta is None): ax.plot(self.x, self.y, **kwargs) else: ax.plot(self.x, self.y, label=self.meta.name, **kwargs) return (fig, ax)<|docstring|>Draw the curve as a line on the given plot. @todo Add links to matplotlib documentation for the style overrides. @todo Should this method be public or private? Args: fig: The figure of the plot. ax: The axes of the plot. **kwargs: Additional plotting options to pass to `.plot` of matplotlib. Returns: The updated figure and axes of the plot.<|endoftext|>
d6533bd18202b6858defa6f411c31bea13089dc12061b365a2bda4c4d2ebdfdb
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: 'Draws the curve on the given plot.' return self.draw_line(fig, ax)
Draws the curve on the given plot.
performance_curves/curve.py
draw_to
erp12/performance-curves
0
python
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: return self.draw_line(fig, ax)
def draw_to(self, fig: plt.Figure, ax: plt.Axes) -> Tuple[(plt.Figure, plt.Axes)]: return self.draw_line(fig, ax)<|docstring|>Draws the curve on the given plot.<|endoftext|>
75f69afdabb0624a3f86f33d2db39186a3ae15e50a63f9cfc3724cd05f4d05a6
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: 'Create a new plot with the curve on it.' (fig, ax) = plt.subplots() if (self.meta is not None): (fig, ax) = self.meta.draw_to(fig, ax) return self.draw_to(fig, ax)
Create a new plot with the curve on it.
performance_curves/curve.py
plot
erp12/performance-curves
0
python
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: (fig, ax) = plt.subplots() if (self.meta is not None): (fig, ax) = self.meta.draw_to(fig, ax) return self.draw_to(fig, ax)
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: (fig, ax) = plt.subplots() if (self.meta is not None): (fig, ax) = self.meta.draw_to(fig, ax) return self.draw_to(fig, ax)<|docstring|>Create a new plot with the curve on it.<|endoftext|>
5f9a16ee9f2ff274fe5d4b661c3fcff62b6923064f0f9a5f0031ab5442eabdfe
def with_meta(self, meta: CurveMeta) -> 'Curve': 'A new `Curve` with the same data and new metadata.' return Curve(self.x, self.y, meta)
A new `Curve` with the same data and new metadata.
performance_curves/curve.py
with_meta
erp12/performance-curves
0
python
def with_meta(self, meta: CurveMeta) -> 'Curve': return Curve(self.x, self.y, meta)
def with_meta(self, meta: CurveMeta) -> 'Curve': return Curve(self.x, self.y, meta)<|docstring|>A new `Curve` with the same data and new metadata.<|endoftext|>
4d741e7c2e3150123adbff7e3b3431209d14dd3426888296880ec231b1f7de2f
def without_meta(self) -> 'Curve': 'A new `Curve` with the same data and no metadata.' return Curve(self.x, self.y)
A new `Curve` with the same data and no metadata.
performance_curves/curve.py
without_meta
erp12/performance-curves
0
python
def without_meta(self) -> 'Curve': return Curve(self.x, self.y)
def without_meta(self) -> 'Curve': return Curve(self.x, self.y)<|docstring|>A new `Curve` with the same data and no metadata.<|endoftext|>
146e61f04aeb921c79dba8c8360643659859b62af7d72ae1789b01d0f6943ff1
def x_cutoff(self, y_limit: float, is_upper_limit: bool=False, find_min_x: bool=False) -> float: 'Finds the x-dimension value of the closest data point to the given y-limit.' pred = (le if is_upper_limit else ge) selector = (np.min if find_min_x else np.max) return selector(self.arrays.filter('y', (lambda a: pred(a, y_limit)))['x'])
Finds the x-dimension value of the closest data point to the given y-limit.
performance_curves/curve.py
x_cutoff
erp12/performance-curves
0
python
def x_cutoff(self, y_limit: float, is_upper_limit: bool=False, find_min_x: bool=False) -> float: pred = (le if is_upper_limit else ge) selector = (np.min if find_min_x else np.max) return selector(self.arrays.filter('y', (lambda a: pred(a, y_limit)))['x'])
def x_cutoff(self, y_limit: float, is_upper_limit: bool=False, find_min_x: bool=False) -> float: pred = (le if is_upper_limit else ge) selector = (np.min if find_min_x else np.max) return selector(self.arrays.filter('y', (lambda a: pred(a, y_limit)))['x'])<|docstring|>Finds the x-dimension value of the closest data point to the given y-limit.<|endoftext|>
0a4a4e3a7b51c022a0f45376e99e6eb71566a13a8566e1da84ce4ed2097d4e37
def __init__(self, curves: Iterable[Curve], *, kind_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None, curve_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None): 'Instantiate a `Curves` object from a collection of `Curve` objects and some optional style overrides.\n\n @todo Add links to matplotlib documentation for the style overrides.\n\n Args:\n curves: The `Curve` objects.\n kind_overrides: Plot style overrides to apply to curves based their `kind`.\n curve_overrides: Plot style overrides to apply to curves based their `name`.\n Takes priority over `kind_overrides`.\n ' self.curves = curves self.kind_overrides = ({} if (kind_overrides is None) else kind_overrides) self.curve_overrides = ({} if (curve_overrides is None) else curve_overrides)
Instantiate a `Curves` object from a collection of `Curve` objects and some optional style overrides. @todo Add links to matplotlib documentation for the style overrides. Args: curves: The `Curve` objects. kind_overrides: Plot style overrides to apply to curves based their `kind`. curve_overrides: Plot style overrides to apply to curves based their `name`. Takes priority over `kind_overrides`.
performance_curves/curve.py
__init__
erp12/performance-curves
0
python
def __init__(self, curves: Iterable[Curve], *, kind_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None, curve_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None): 'Instantiate a `Curves` object from a collection of `Curve` objects and some optional style overrides.\n\n @todo Add links to matplotlib documentation for the style overrides.\n\n Args:\n curves: The `Curve` objects.\n kind_overrides: Plot style overrides to apply to curves based their `kind`.\n curve_overrides: Plot style overrides to apply to curves based their `name`.\n Takes priority over `kind_overrides`.\n ' self.curves = curves self.kind_overrides = ({} if (kind_overrides is None) else kind_overrides) self.curve_overrides = ({} if (curve_overrides is None) else curve_overrides)
def __init__(self, curves: Iterable[Curve], *, kind_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None, curve_overrides: Optional[Mapping[(Any, Mapping[(str, Any)])]]=None): 'Instantiate a `Curves` object from a collection of `Curve` objects and some optional style overrides.\n\n @todo Add links to matplotlib documentation for the style overrides.\n\n Args:\n curves: The `Curve` objects.\n kind_overrides: Plot style overrides to apply to curves based their `kind`.\n curve_overrides: Plot style overrides to apply to curves based their `name`.\n Takes priority over `kind_overrides`.\n ' self.curves = curves self.kind_overrides = ({} if (kind_overrides is None) else kind_overrides) self.curve_overrides = ({} if (curve_overrides is None) else curve_overrides)<|docstring|>Instantiate a `Curves` object from a collection of `Curve` objects and some optional style overrides. @todo Add links to matplotlib documentation for the style overrides. Args: curves: The `Curve` objects. kind_overrides: Plot style overrides to apply to curves based their `kind`. curve_overrides: Plot style overrides to apply to curves based their `name`. Takes priority over `kind_overrides`.<|endoftext|>
91f0c3cf8c236900974c525d4c4a91a1dbc631fca2e99d586f48260edc1e216d
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: 'Create a new plot that shows all curves.' x_labs: Set[str] = set() y_labs: Set[str] = set() (fig, ax) = plt.subplots() for curve in self.curves: overrides: Dict[(str, Any)] = {} meta = curve.meta if (meta is not None): overrides.update(self.kind_overrides.get(meta.kind, {})) overrides.update(self.curve_overrides.get(meta.name, {})) if (meta.x_dim is not None): x_labs.add(meta.x_dim) if (meta.y_dim is not None): y_labs.add(meta.y_dim) (fig, ax) = curve.without_meta().draw_line(fig, ax, **overrides) ax.set_xlabel(', '.join(x_labs)) ax.set_ylabel(', '.join(y_labs)) return (fig, ax)
Create a new plot that shows all curves.
performance_curves/curve.py
plot
erp12/performance-curves
0
python
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: x_labs: Set[str] = set() y_labs: Set[str] = set() (fig, ax) = plt.subplots() for curve in self.curves: overrides: Dict[(str, Any)] = {} meta = curve.meta if (meta is not None): overrides.update(self.kind_overrides.get(meta.kind, {})) overrides.update(self.curve_overrides.get(meta.name, {})) if (meta.x_dim is not None): x_labs.add(meta.x_dim) if (meta.y_dim is not None): y_labs.add(meta.y_dim) (fig, ax) = curve.without_meta().draw_line(fig, ax, **overrides) ax.set_xlabel(', '.join(x_labs)) ax.set_ylabel(', '.join(y_labs)) return (fig, ax)
def plot(self) -> Tuple[(plt.Figure, plt.Axes)]: x_labs: Set[str] = set() y_labs: Set[str] = set() (fig, ax) = plt.subplots() for curve in self.curves: overrides: Dict[(str, Any)] = {} meta = curve.meta if (meta is not None): overrides.update(self.kind_overrides.get(meta.kind, {})) overrides.update(self.curve_overrides.get(meta.name, {})) if (meta.x_dim is not None): x_labs.add(meta.x_dim) if (meta.y_dim is not None): y_labs.add(meta.y_dim) (fig, ax) = curve.without_meta().draw_line(fig, ax, **overrides) ax.set_xlabel(', '.join(x_labs)) ax.set_ylabel(', '.join(y_labs)) return (fig, ax)<|docstring|>Create a new plot that shows all curves.<|endoftext|>
07a1a30b0847949393d8ae32fa8fe1f2a67b183309b812d28b52a6d8e5be18a1
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_onboarding_doc(self): '\n This test starts the beat and checks that the onboarding doc has been published to ES\n ' self.wait_until((lambda : self.es.indices.exists(self.index_name))) self.es.indices.refresh(index=self.index_name) self.wait_until((lambda : (self.es.count(index=self.index_name)['count'] == 1))) self.assert_no_logged_warnings()
This test starts the beat and checks that the onboarding doc has been published to ES
tests/system/test_integration.py
test_onboarding_doc
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_onboarding_doc(self): '\n \n ' self.wait_until((lambda : self.es.indices.exists(self.index_name))) self.es.indices.refresh(index=self.index_name) self.wait_until((lambda : (self.es.count(index=self.index_name)['count'] == 1))) self.assert_no_logged_warnings()
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_onboarding_doc(self): '\n \n ' self.wait_until((lambda : self.es.indices.exists(self.index_name))) self.es.indices.refresh(index=self.index_name) self.wait_until((lambda : (self.es.count(index=self.index_name)['count'] == 1))) self.assert_no_logged_warnings()<|docstring|>This test starts the beat and checks that the onboarding doc has been published to ES<|endoftext|>
0505bf6d5e9d2e4b052ef8b04aee6d75701c547081cc863472b5aa2fe58310bb
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_transaction(self): '\n This test starts the beat with a loaded template and sends transaction data to elasticsearch.\n It verifies that all data make it into ES, means data is compatible with the template\n and data are in expected format.\n ' self.load_docs_with_template(self.get_transaction_payload_path(), self.transactions_url, 'transaction', 9) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'transaction'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'transaction.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'transaction') rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'span'}}}) assert (rs['hits']['total'] == 5), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'spans.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'span') self.check_backend_transaction_sourcemap(count=5)
This test starts the beat with a loaded template and sends transaction data to elasticsearch. It verifies that all data make it into ES, means data is compatible with the template and data are in expected format.
tests/system/test_integration.py
test_load_docs_with_template_and_add_transaction
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_transaction(self): '\n This test starts the beat with a loaded template and sends transaction data to elasticsearch.\n It verifies that all data make it into ES, means data is compatible with the template\n and data are in expected format.\n ' self.load_docs_with_template(self.get_transaction_payload_path(), self.transactions_url, 'transaction', 9) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'transaction'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'transaction.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'transaction') rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'span'}}}) assert (rs['hits']['total'] == 5), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'spans.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'span') self.check_backend_transaction_sourcemap(count=5)
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_transaction(self): '\n This test starts the beat with a loaded template and sends transaction data to elasticsearch.\n It verifies that all data make it into ES, means data is compatible with the template\n and data are in expected format.\n ' self.load_docs_with_template(self.get_transaction_payload_path(), self.transactions_url, 'transaction', 9) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'transaction'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'transaction.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'transaction') rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'span'}}}) assert (rs['hits']['total'] == 5), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'spans.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'span') self.check_backend_transaction_sourcemap(count=5)<|docstring|>This test starts the beat with a loaded template and sends transaction data to elasticsearch. It verifies that all data make it into ES, means data is compatible with the template and data are in expected format.<|endoftext|>
f7fde6d29cdc362912259f40fcd91f8b82863b2d444687f9712873f07a64a9d3
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_error(self): '\n This test starts the beat with a loaded template and sends error data to elasticsearch.\n It verifies that all data make it into ES means data is compatible with the template.\n ' self.load_docs_with_template(self.get_error_payload_path(), self.errors_url, 'error', 4) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'error'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'error.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'error') self.check_backend_error_sourcemap(count=4)
This test starts the beat with a loaded template and sends error data to elasticsearch. It verifies that all data make it into ES means data is compatible with the template.
tests/system/test_integration.py
test_load_docs_with_template_and_add_error
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_error(self): '\n This test starts the beat with a loaded template and sends error data to elasticsearch.\n It verifies that all data make it into ES means data is compatible with the template.\n ' self.load_docs_with_template(self.get_error_payload_path(), self.errors_url, 'error', 4) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'error'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'error.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'error') self.check_backend_error_sourcemap(count=4)
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_load_docs_with_template_and_add_error(self): '\n This test starts the beat with a loaded template and sends error data to elasticsearch.\n It verifies that all data make it into ES means data is compatible with the template.\n ' self.load_docs_with_template(self.get_error_payload_path(), self.errors_url, 'error', 4) self.assert_no_logged_warnings() rs = self.es.search(index=self.index_name, body={'query': {'term': {'processor.event': 'error'}}}) assert (rs['hits']['total'] == 4), 'found {} documents'.format(rs['count']) with open(self._beat_path_join(os.path.dirname(__file__), 'error.approved.json')) as f: approved = json.load(f) self.check_docs(approved, rs['hits']['hits'], 'error') self.check_backend_error_sourcemap(count=4)<|docstring|>This test starts the beat with a loaded template and sends error data to elasticsearch. It verifies that all data make it into ES means data is compatible with the template.<|endoftext|>
5e4e3de5033af842dbef90efd3804f4c99dd2b74159113e9b0bad822ab051078
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): 'expvar disabled, should 404' r = self.get_debug_vars() assert (r.status_code == 404), r.status_code
expvar disabled, should 404
tests/system/test_integration.py
test_expvar_exists
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 404), r.status_code
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 404), r.status_code<|docstring|>expvar disabled, should 404<|endoftext|>
3e92a3b63ac5442aa03509c28f2ddf0d7531045b0cbdeb36e49c5c9bf849658b
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): 'expvar enabled, should 200' r = self.get_debug_vars() assert (r.status_code == 200), r.status_code
expvar enabled, should 200
tests/system/test_integration.py
test_expvar_exists
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 200), r.status_code
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 200), r.status_code<|docstring|>expvar enabled, should 200<|endoftext|>
3e92a3b63ac5442aa03509c28f2ddf0d7531045b0cbdeb36e49c5c9bf849658b
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): 'expvar enabled, should 200' r = self.get_debug_vars() assert (r.status_code == 200), r.status_code
expvar enabled, should 200
tests/system/test_integration.py
test_expvar_exists
KOTungseth/apm-server
2
python
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 200), r.status_code
@unittest.skipUnless(INTEGRATION_TESTS, 'integration test') def test_expvar_exists(self): r = self.get_debug_vars() assert (r.status_code == 200), r.status_code<|docstring|>expvar enabled, should 200<|endoftext|>
539d1f7d5241bb96e2f9158271b7b8fb10a75e94c17ad4a610e584a8dae6fb42
def ParseArgs(): '\n 参数解析\n :return: option args\n ' parser = optparse.OptionParser() parser.add_option('-f', '--file', type='string', dest='filename', help='Specify the Config file', default='setting.ini') parser.add_option('-n', '--node', type='string', dest='node', help='Specify the the name of Server/Node') parser.add_option('-s', '--section', type='string', dest='section', help='Specify the Section to Run', default='clear-test') parser.add_option('-l', '--log', type='string', dest='log', help='Specify the log path') parser.add_option('-d', action='store_true', default='True', dest='debug', help='Indicate whether to log debug info') (options, args) = parser.parse_args() if (not options.filename): options.error('Error : Config file Missing. Use -f or --file to specify the config file') print(('*' * 50)) print(options) print(('*' * 50)) return (options, args)
参数解析 :return: option args
korok.py
ParseArgs
spiolynn/log-processing
3
python
def ParseArgs(): '\n 参数解析\n :return: option args\n ' parser = optparse.OptionParser() parser.add_option('-f', '--file', type='string', dest='filename', help='Specify the Config file', default='setting.ini') parser.add_option('-n', '--node', type='string', dest='node', help='Specify the the name of Server/Node') parser.add_option('-s', '--section', type='string', dest='section', help='Specify the Section to Run', default='clear-test') parser.add_option('-l', '--log', type='string', dest='log', help='Specify the log path') parser.add_option('-d', action='store_true', default='True', dest='debug', help='Indicate whether to log debug info') (options, args) = parser.parse_args() if (not options.filename): options.error('Error : Config file Missing. Use -f or --file to specify the config file') print(('*' * 50)) print(options) print(('*' * 50)) return (options, args)
def ParseArgs(): '\n 参数解析\n :return: option args\n ' parser = optparse.OptionParser() parser.add_option('-f', '--file', type='string', dest='filename', help='Specify the Config file', default='setting.ini') parser.add_option('-n', '--node', type='string', dest='node', help='Specify the the name of Server/Node') parser.add_option('-s', '--section', type='string', dest='section', help='Specify the Section to Run', default='clear-test') parser.add_option('-l', '--log', type='string', dest='log', help='Specify the log path') parser.add_option('-d', action='store_true', default='True', dest='debug', help='Indicate whether to log debug info') (options, args) = parser.parse_args() if (not options.filename): options.error('Error : Config file Missing. Use -f or --file to specify the config file') print(('*' * 50)) print(options) print(('*' * 50)) return (options, args)<|docstring|>参数解析 :return: option args<|endoftext|>
a2dddf0cdddf419d78b5a144f738b974d024464865dacf7dbdc2c89037972df6
def Run(self): '\n 启动\n :return:\n ' success = 0 failure = 0 ret = 0 sections = self.ConParser.sections() section = self.Options.section args = self.Args if (section in sections): try: action = self.ConParser.get(section, 'action') except Exception as ex: ret = 2 logging.error(('Error: No Action definition ' + section)) logging.exception(ex) if (action == 'copy'): if (not self.Copy(section, args)): ret = 11 elif (action == 'execute'): if (not self.Execute(section)): ret = 12 elif (action == 'clear'): if (not self.Clear(section, args)): ret = 13 elif (action == 'processmon'): if (not self.ProcessMon(section)): ret = 14 elif (action == 'service'): if (not self.Service(section, args)): ret = 15 elif (action == 'archive'): if (not self.Zip(section)): ret = 16 elif (action == 'archive_month'): if (not self.Zip_Month(section)): ret = 16 else: logging.error(('Error: No such Action ' + section)) ret = 3 logging.debug((section + ' ends')) else: logging.info(' {}.{}'.format(section, 'is not setting')) return ret
启动 :return:
korok.py
Run
spiolynn/log-processing
3
python
def Run(self): '\n 启动\n :return:\n ' success = 0 failure = 0 ret = 0 sections = self.ConParser.sections() section = self.Options.section args = self.Args if (section in sections): try: action = self.ConParser.get(section, 'action') except Exception as ex: ret = 2 logging.error(('Error: No Action definition ' + section)) logging.exception(ex) if (action == 'copy'): if (not self.Copy(section, args)): ret = 11 elif (action == 'execute'): if (not self.Execute(section)): ret = 12 elif (action == 'clear'): if (not self.Clear(section, args)): ret = 13 elif (action == 'processmon'): if (not self.ProcessMon(section)): ret = 14 elif (action == 'service'): if (not self.Service(section, args)): ret = 15 elif (action == 'archive'): if (not self.Zip(section)): ret = 16 elif (action == 'archive_month'): if (not self.Zip_Month(section)): ret = 16 else: logging.error(('Error: No such Action ' + section)) ret = 3 logging.debug((section + ' ends')) else: logging.info(' {}.{}'.format(section, 'is not setting')) return ret
def Run(self): '\n 启动\n :return:\n ' success = 0 failure = 0 ret = 0 sections = self.ConParser.sections() section = self.Options.section args = self.Args if (section in sections): try: action = self.ConParser.get(section, 'action') except Exception as ex: ret = 2 logging.error(('Error: No Action definition ' + section)) logging.exception(ex) if (action == 'copy'): if (not self.Copy(section, args)): ret = 11 elif (action == 'execute'): if (not self.Execute(section)): ret = 12 elif (action == 'clear'): if (not self.Clear(section, args)): ret = 13 elif (action == 'processmon'): if (not self.ProcessMon(section)): ret = 14 elif (action == 'service'): if (not self.Service(section, args)): ret = 15 elif (action == 'archive'): if (not self.Zip(section)): ret = 16 elif (action == 'archive_month'): if (not self.Zip_Month(section)): ret = 16 else: logging.error(('Error: No such Action ' + section)) ret = 3 logging.debug((section + ' ends')) else: logging.info(' {}.{}'.format(section, 'is not setting')) return ret<|docstring|>启动 :return:<|endoftext|>
29543be9b8ca8b2dbc5472633fec74645de2afc283dcd66bd8aa23168c8eee53
def Zip_Month(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip_by_month') _month = self.nowMonth() try: srclist = self.ConParser.get(section, 'src').split() _srclist = [] for src in srclist: _srclist.append(os.path.join(src, _month)) srclist = _srclist logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') dest = os.path.join(dest, _month) logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') _patternlist = [] for i in patternlist: _dirpath = os.path.dirname(i) _pattern = os.path.basename(i) _patternlist.append(os.path.join(_dirpath, _month, _pattern)) patternlist = _patternlist logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = os.path.join(dest, (((self.ExecTime + '-') + self.HostNm) + '.tar.gz')) else: dest = os.path.join(dest, (self.HostNm + '.tar.gz')) logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: if (not os.path.exists(os.path.dirname(dest))): os.makedirs(os.path.dirname(dest)) destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() return 1 for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: cur_path = os.getcwd() os.chdir(os.path.dirname(srcfile)) mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: srcfile = os.path.basename(srcfile) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: os.chdir(cur_path) self.PrintStack() destgzfile.close()
:param section: # section need parameter # src 源目录 # dst 目标目录 # pattern 正则匹配 # mtime 修改时间 # timestamp bool 加时间标签 # reserve 是否递归
korok.py
Zip_Month
spiolynn/log-processing
3
python
def Zip_Month(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip_by_month') _month = self.nowMonth() try: srclist = self.ConParser.get(section, 'src').split() _srclist = [] for src in srclist: _srclist.append(os.path.join(src, _month)) srclist = _srclist logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') dest = os.path.join(dest, _month) logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') _patternlist = [] for i in patternlist: _dirpath = os.path.dirname(i) _pattern = os.path.basename(i) _patternlist.append(os.path.join(_dirpath, _month, _pattern)) patternlist = _patternlist logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = os.path.join(dest, (((self.ExecTime + '-') + self.HostNm) + '.tar.gz')) else: dest = os.path.join(dest, (self.HostNm + '.tar.gz')) logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: if (not os.path.exists(os.path.dirname(dest))): os.makedirs(os.path.dirname(dest)) destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() return 1 for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: cur_path = os.getcwd() os.chdir(os.path.dirname(srcfile)) mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: srcfile = os.path.basename(srcfile) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: os.chdir(cur_path) self.PrintStack() destgzfile.close()
def Zip_Month(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip_by_month') _month = self.nowMonth() try: srclist = self.ConParser.get(section, 'src').split() _srclist = [] for src in srclist: _srclist.append(os.path.join(src, _month)) srclist = _srclist logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') dest = os.path.join(dest, _month) logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') _patternlist = [] for i in patternlist: _dirpath = os.path.dirname(i) _pattern = os.path.basename(i) _patternlist.append(os.path.join(_dirpath, _month, _pattern)) patternlist = _patternlist logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = os.path.join(dest, (((self.ExecTime + '-') + self.HostNm) + '.tar.gz')) else: dest = os.path.join(dest, (self.HostNm + '.tar.gz')) logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: if (not os.path.exists(os.path.dirname(dest))): os.makedirs(os.path.dirname(dest)) destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() return 1 for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: cur_path = os.getcwd() os.chdir(os.path.dirname(srcfile)) mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: srcfile = os.path.basename(srcfile) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: os.chdir(cur_path) self.PrintStack() destgzfile.close()<|docstring|>:param section: # section need parameter # src 源目录 # dst 目标目录 # pattern 正则匹配 # mtime 修改时间 # timestamp bool 加时间标签 # reserve 是否递归<|endoftext|>
0cf0095334c650eb5ea6811465bbf6709e7c6deb2a533f50e9d65ca5d4901538
def Zip(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip') try: srclist = self.ConParser.get(section, 'src').split('|') logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = ((((dest + self.ExecTime) + '-') + self.HostNm) + '.tar.gz') else: dest = (((dest + '-') + self.HostNm) + '.tar.gz') logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: print(os.getcwd()) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: self.PrintStack()
:param section: # section need parameter # src 源目录 # dst 目标目录 # pattern 正则匹配 # mtime 修改时间 # timestamp bool 加时间标签 # reserve 是否递归
korok.py
Zip
spiolynn/log-processing
3
python
def Zip(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip') try: srclist = self.ConParser.get(section, 'src').split('|') logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = ((((dest + self.ExecTime) + '-') + self.HostNm) + '.tar.gz') else: dest = (((dest + '-') + self.HostNm) + '.tar.gz') logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: print(os.getcwd()) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: self.PrintStack()
def Zip(self, section): '\n :param section:\n # section need parameter\n # src 源目录\n # dst 目标目录\n # pattern 正则匹配\n # mtime 修改时间\n # timestamp bool 加时间标签\n # reserve 是否递归\n ' print('zip') try: srclist = self.ConParser.get(section, 'src').split('|') logging.debug('{:15}{:10}'.format('srcpath lst:', str(srclist))) except BaseException: print('No Source defined for Copy', section) self.PrintStack() return 0 try: dest = self.ConParser.get(section, 'dst') logging.debug('{:15}{:10}'.format('dstpath str:', str(dest))) except BaseException: print('No destination defined for Copy', section) self.PrintStack() return 0 try: patternlist = self.ConParser.get(section, 'pattern').split('@@') logging.debug('{:15}{:10}'.format('pattern lst:', str(patternlist))) except BaseException: print('No pattern defined for Copy', section) self.PrintStack() return 0 try: duration = str(self.ConParser.get(section, 'mtime')) logging.debug('{:15}{:10}'.format('duration:', str(duration))) except BaseException: duration = None print('No mtime defined for Copy', section) try: timestamp = str(self.ConParser.get(section, 'timestamp')) if ((timestamp == 'yes') or (timestamp == 'YES') or (timestamp == 'y') or (timestamp == 'Y')): dest = ((((dest + self.ExecTime) + '-') + self.HostNm) + '.tar.gz') else: dest = (((dest + '-') + self.HostNm) + '.tar.gz') logging.debug('{:15}{:10}'.format('dest will:', str(dest))) except BaseException: print('Unmark time stamp for Zip', section) try: reserve = str(self.ConParser.get(section, 'reserve')) if ((reserve == 'no') or (reserve == 'NO') or (reserve == 'n') or (reserve == 'N')): reserve = False else: reserve = True logging.debug('{:15}{:10}'.format('reserve:', str(reserve))) except BaseException: reserve = True print('Un mark time stamp for Copy', section) if duration: delta = self.convert_to_time(duration) if (not delta): logging.error('Can not get time delta') print('Can not get time delta') return 0 try: destgzfile = tarfile.open(dest, 'w:gz') except BaseException: print('Zip File creation failed for', dest) self.PrintStack() for pattern in patternlist: srcfiles = glob.glob(pattern) logging.debug('{:15}{:10}'.format('pattern file:', str(srcfiles))) for srcfile in srcfiles: mtime = os.stat(srcfile).st_mtime if (not ((self.NowTime - mtime) > delta)): continue print('Zip from', srcfile, 'to', dest) logging.debug('Zip from {:15} srcfile {:10}'.format(srcfile, dest)) try: print(os.getcwd()) if os.path.isfile(srcfile): destgzfile.add(srcfile) if (not reserve): os.remove(srcfile) elif os.path.isdir(srcfile): destgzfile.add(srcfile) if (not reserve): shutil.rmtree(srcfile) except BaseException: self.PrintStack()<|docstring|>:param section: # section need parameter # src 源目录 # dst 目标目录 # pattern 正则匹配 # mtime 修改时间 # timestamp bool 加时间标签 # reserve 是否递归<|endoftext|>
4ba858edd5aa29ba0d9debaae724c491aba76697287f04c8652a30a52d3921d4
def get_pool(name='default', thread_count=1): 'Get (and initialize) a Thread pool.\n\n If thread_count is 0, then None is returned.\n\n If the thread pool had already been initialized, thread_count will\n be ignored.\n ' if (not thread_count): return None with _init_lock: pool = _pools.get(name, None) if (pool is None): pool = ThreadPool(thread_count) _pools[name] = pool return pool
Get (and initialize) a Thread pool. If thread_count is 0, then None is returned. If the thread pool had already been initialized, thread_count will be ignored.
webapp/graphite/worker_pool/pool.py
get_pool
cthiel42/graphite-web
4,281
python
def get_pool(name='default', thread_count=1): 'Get (and initialize) a Thread pool.\n\n If thread_count is 0, then None is returned.\n\n If the thread pool had already been initialized, thread_count will\n be ignored.\n ' if (not thread_count): return None with _init_lock: pool = _pools.get(name, None) if (pool is None): pool = ThreadPool(thread_count) _pools[name] = pool return pool
def get_pool(name='default', thread_count=1): 'Get (and initialize) a Thread pool.\n\n If thread_count is 0, then None is returned.\n\n If the thread pool had already been initialized, thread_count will\n be ignored.\n ' if (not thread_count): return None with _init_lock: pool = _pools.get(name, None) if (pool is None): pool = ThreadPool(thread_count) _pools[name] = pool return pool<|docstring|>Get (and initialize) a Thread pool. If thread_count is 0, then None is returned. If the thread pool had already been initialized, thread_count will be ignored.<|endoftext|>
57e5688e407c13ced5fc0658e63bbdc14a1fc040c88006ef84850d8df0f7edd6
def pool_exec(pool, jobs, timeout): 'Execute a list of jobs, yielding each one as it completes.\n\n If a pool is specified then the jobs will be executed asynchronously,\n otherwise they are executed in order.\n\n If not all jobs have been executed after the specified timeout a\n PoolTimeoutError will be raised. When operating synchronously the\n timeout is checked before each job is run.\n ' start = time.time() deadline = (start + timeout) if pool: queue = six.moves.queue.Queue() def pool_executor(job): job.run() queue.put(job) for job in jobs: pool.apply_async(func=pool_executor, args=[job]) done = 0 total = len(jobs) while (done < total): wait_time = max(0, (deadline - time.time())) try: job = queue.get(True, wait_time) except six.moves.queue.Empty: raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) done += 1 (yield job) else: for job in jobs: if (time.time() > deadline): raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) job.run() (yield job)
Execute a list of jobs, yielding each one as it completes. If a pool is specified then the jobs will be executed asynchronously, otherwise they are executed in order. If not all jobs have been executed after the specified timeout a PoolTimeoutError will be raised. When operating synchronously the timeout is checked before each job is run.
webapp/graphite/worker_pool/pool.py
pool_exec
cthiel42/graphite-web
4,281
python
def pool_exec(pool, jobs, timeout): 'Execute a list of jobs, yielding each one as it completes.\n\n If a pool is specified then the jobs will be executed asynchronously,\n otherwise they are executed in order.\n\n If not all jobs have been executed after the specified timeout a\n PoolTimeoutError will be raised. When operating synchronously the\n timeout is checked before each job is run.\n ' start = time.time() deadline = (start + timeout) if pool: queue = six.moves.queue.Queue() def pool_executor(job): job.run() queue.put(job) for job in jobs: pool.apply_async(func=pool_executor, args=[job]) done = 0 total = len(jobs) while (done < total): wait_time = max(0, (deadline - time.time())) try: job = queue.get(True, wait_time) except six.moves.queue.Empty: raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) done += 1 (yield job) else: for job in jobs: if (time.time() > deadline): raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) job.run() (yield job)
def pool_exec(pool, jobs, timeout): 'Execute a list of jobs, yielding each one as it completes.\n\n If a pool is specified then the jobs will be executed asynchronously,\n otherwise they are executed in order.\n\n If not all jobs have been executed after the specified timeout a\n PoolTimeoutError will be raised. When operating synchronously the\n timeout is checked before each job is run.\n ' start = time.time() deadline = (start + timeout) if pool: queue = six.moves.queue.Queue() def pool_executor(job): job.run() queue.put(job) for job in jobs: pool.apply_async(func=pool_executor, args=[job]) done = 0 total = len(jobs) while (done < total): wait_time = max(0, (deadline - time.time())) try: job = queue.get(True, wait_time) except six.moves.queue.Empty: raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) done += 1 (yield job) else: for job in jobs: if (time.time() > deadline): raise PoolTimeoutError(('Timed out after %fs' % (time.time() - start))) job.run() (yield job)<|docstring|>Execute a list of jobs, yielding each one as it completes. If a pool is specified then the jobs will be executed asynchronously, otherwise they are executed in order. If not all jobs have been executed after the specified timeout a PoolTimeoutError will be raised. When operating synchronously the timeout is checked before each job is run.<|endoftext|>
fe4f00650030abbd6329c61c2083976e412669b1ed2b3531167e88a5e6489e44
def learn(images, algo, code_length=8, num_encoder_layers='auto', num_decoder_layers='auto', epochs=10, batch_size=16, optimizer='adam', learning_rate=0.001, loss_function='mse', metrics=['mse'], samples_for_code_statistics=64): " This function train model based on passed data and argumenents to generate realastic looking images\n\n **Parameters**\n\n images : list\n Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size\n algo : str\n Algorithm to be used to learn image representation, Eg Autoencode_dense,\n code_length: int\n Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed.\n num_encoder_layer: int\n Default 'auto', number of layers to be used in encoder, applicable for autoenocder\n num_decoder_layers: int\n Default 'auto', number of layers to be used in decoder, applicable for autoenocder\n epochs: int\n Default 10, number of epoch to be used while training model\n batch_size: int\n Default 16, batch size of each training/eval/generation step\n optimizer: string\n Default 'adam', optimizer used to train the model\n learning_rate: int\n Default 0.001, learning rate for training model\n loss_function: string\n Default 'mse', loss function for training model\n metrics: list of string\n Default ['mse'], list of metrics to be printed while training\n samples_for_code_statistics: int\n Default 64, samples to be used to generate code statistics\n\n\n **Returns**\n\n object\n model object trained on given dataset\n\n " print('Number sample:', images.shape[0], 'Image shape:', images[0].shape) model = mapping.algo_mapping.get(algo, None) if (not model): raise Exception(('Algo not implement/present possible values for also are %s' % mapping.algo_mapping.keys())) optimizer_keys = optimizer optimizer = mapping.optimizer_mapping.get(optimizer, None) if (not optimizer): raise Exception(('Optimizer not implement/present possible values for also are %s' % mapping.optimizer_mapping.keys())) loss_function_keys = loss_function loss_function = mapping.loss_function_mapping.get(loss_function, None) if (not optimizer): raise Exception(('loss_function not implement/present possible values for also are %s' % mapping.loss_function_mapping.keys())) metrics_keys = metrics metrics = [mapping.metrics_mapping.get(x, None) for x in metrics] if list(filter((lambda x: (x == None)), metrics)): raise Exception(('One or more of the metrics passed is not a valid metrics, possible values are %s' % mapping.metrics_mapping.keys())) if ((code_length % 4) != 0): raise Exception('code_length must be a multiple of 4') print('===================================================================') print('Algo:\t\t', model) print('optimizer:\t', optimizer) print('loss_function:\t', loss_function) print('metrics:\t', metrics) print('Epochs:\t\t', epochs) print('batch_size:\t', batch_size) print('learning_rate:\t', learning_rate) print('===================================================================') images = image_functions.convert_2dto3d(images) if algo.startswith('gan'): model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_generator_layers=num_encoder_layers, num_discriminator_layers=num_decoder_layers) else: model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_encoder_layers=num_encoder_layers, num_decoder_layers=num_decoder_layers) model.build_model_graph(images[0].shape) (images_train, images_test) = train_test_split(images, test_size=0.3, shuffle=True) print('Train:', len(images_train.shape)) print('Test:', len(images_test.shape)) model.train(images_train, images_test, epochs=epochs, batch_size=batch_size, validation_split=0.2) if (not algo.startswith('gan')): model.prepare_code_statistics(images_train, batch_size=batch_size, sample_size=samples_for_code_statistics) return model
This function train model based on passed data and argumenents to generate realastic looking images **Parameters** images : list Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size algo : str Algorithm to be used to learn image representation, Eg Autoencode_dense, code_length: int Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed. num_encoder_layer: int Default 'auto', number of layers to be used in encoder, applicable for autoenocder num_decoder_layers: int Default 'auto', number of layers to be used in decoder, applicable for autoenocder epochs: int Default 10, number of epoch to be used while training model batch_size: int Default 16, batch size of each training/eval/generation step optimizer: string Default 'adam', optimizer used to train the model learning_rate: int Default 0.001, learning rate for training model loss_function: string Default 'mse', loss function for training model metrics: list of string Default ['mse'], list of metrics to be printed while training samples_for_code_statistics: int Default 64, samples to be used to generate code statistics **Returns** object model object trained on given dataset
gimmick/distributer.py
learn
pankajr141/gimmick
0
python
def learn(images, algo, code_length=8, num_encoder_layers='auto', num_decoder_layers='auto', epochs=10, batch_size=16, optimizer='adam', learning_rate=0.001, loss_function='mse', metrics=['mse'], samples_for_code_statistics=64): " This function train model based on passed data and argumenents to generate realastic looking images\n\n **Parameters**\n\n images : list\n Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size\n algo : str\n Algorithm to be used to learn image representation, Eg Autoencode_dense,\n code_length: int\n Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed.\n num_encoder_layer: int\n Default 'auto', number of layers to be used in encoder, applicable for autoenocder\n num_decoder_layers: int\n Default 'auto', number of layers to be used in decoder, applicable for autoenocder\n epochs: int\n Default 10, number of epoch to be used while training model\n batch_size: int\n Default 16, batch size of each training/eval/generation step\n optimizer: string\n Default 'adam', optimizer used to train the model\n learning_rate: int\n Default 0.001, learning rate for training model\n loss_function: string\n Default 'mse', loss function for training model\n metrics: list of string\n Default ['mse'], list of metrics to be printed while training\n samples_for_code_statistics: int\n Default 64, samples to be used to generate code statistics\n\n\n **Returns**\n\n object\n model object trained on given dataset\n\n " print('Number sample:', images.shape[0], 'Image shape:', images[0].shape) model = mapping.algo_mapping.get(algo, None) if (not model): raise Exception(('Algo not implement/present possible values for also are %s' % mapping.algo_mapping.keys())) optimizer_keys = optimizer optimizer = mapping.optimizer_mapping.get(optimizer, None) if (not optimizer): raise Exception(('Optimizer not implement/present possible values for also are %s' % mapping.optimizer_mapping.keys())) loss_function_keys = loss_function loss_function = mapping.loss_function_mapping.get(loss_function, None) if (not optimizer): raise Exception(('loss_function not implement/present possible values for also are %s' % mapping.loss_function_mapping.keys())) metrics_keys = metrics metrics = [mapping.metrics_mapping.get(x, None) for x in metrics] if list(filter((lambda x: (x == None)), metrics)): raise Exception(('One or more of the metrics passed is not a valid metrics, possible values are %s' % mapping.metrics_mapping.keys())) if ((code_length % 4) != 0): raise Exception('code_length must be a multiple of 4') print('===================================================================') print('Algo:\t\t', model) print('optimizer:\t', optimizer) print('loss_function:\t', loss_function) print('metrics:\t', metrics) print('Epochs:\t\t', epochs) print('batch_size:\t', batch_size) print('learning_rate:\t', learning_rate) print('===================================================================') images = image_functions.convert_2dto3d(images) if algo.startswith('gan'): model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_generator_layers=num_encoder_layers, num_discriminator_layers=num_decoder_layers) else: model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_encoder_layers=num_encoder_layers, num_decoder_layers=num_decoder_layers) model.build_model_graph(images[0].shape) (images_train, images_test) = train_test_split(images, test_size=0.3, shuffle=True) print('Train:', len(images_train.shape)) print('Test:', len(images_test.shape)) model.train(images_train, images_test, epochs=epochs, batch_size=batch_size, validation_split=0.2) if (not algo.startswith('gan')): model.prepare_code_statistics(images_train, batch_size=batch_size, sample_size=samples_for_code_statistics) return model
def learn(images, algo, code_length=8, num_encoder_layers='auto', num_decoder_layers='auto', epochs=10, batch_size=16, optimizer='adam', learning_rate=0.001, loss_function='mse', metrics=['mse'], samples_for_code_statistics=64): " This function train model based on passed data and argumenents to generate realastic looking images\n\n **Parameters**\n\n images : list\n Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size\n algo : str\n Algorithm to be used to learn image representation, Eg Autoencode_dense,\n code_length: int\n Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed.\n num_encoder_layer: int\n Default 'auto', number of layers to be used in encoder, applicable for autoenocder\n num_decoder_layers: int\n Default 'auto', number of layers to be used in decoder, applicable for autoenocder\n epochs: int\n Default 10, number of epoch to be used while training model\n batch_size: int\n Default 16, batch size of each training/eval/generation step\n optimizer: string\n Default 'adam', optimizer used to train the model\n learning_rate: int\n Default 0.001, learning rate for training model\n loss_function: string\n Default 'mse', loss function for training model\n metrics: list of string\n Default ['mse'], list of metrics to be printed while training\n samples_for_code_statistics: int\n Default 64, samples to be used to generate code statistics\n\n\n **Returns**\n\n object\n model object trained on given dataset\n\n " print('Number sample:', images.shape[0], 'Image shape:', images[0].shape) model = mapping.algo_mapping.get(algo, None) if (not model): raise Exception(('Algo not implement/present possible values for also are %s' % mapping.algo_mapping.keys())) optimizer_keys = optimizer optimizer = mapping.optimizer_mapping.get(optimizer, None) if (not optimizer): raise Exception(('Optimizer not implement/present possible values for also are %s' % mapping.optimizer_mapping.keys())) loss_function_keys = loss_function loss_function = mapping.loss_function_mapping.get(loss_function, None) if (not optimizer): raise Exception(('loss_function not implement/present possible values for also are %s' % mapping.loss_function_mapping.keys())) metrics_keys = metrics metrics = [mapping.metrics_mapping.get(x, None) for x in metrics] if list(filter((lambda x: (x == None)), metrics)): raise Exception(('One or more of the metrics passed is not a valid metrics, possible values are %s' % mapping.metrics_mapping.keys())) if ((code_length % 4) != 0): raise Exception('code_length must be a multiple of 4') print('===================================================================') print('Algo:\t\t', model) print('optimizer:\t', optimizer) print('loss_function:\t', loss_function) print('metrics:\t', metrics) print('Epochs:\t\t', epochs) print('batch_size:\t', batch_size) print('learning_rate:\t', learning_rate) print('===================================================================') images = image_functions.convert_2dto3d(images) if algo.startswith('gan'): model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_generator_layers=num_encoder_layers, num_discriminator_layers=num_decoder_layers) else: model.__init__(learning_rate=learning_rate, optimizer=optimizer, optimizer_keys=optimizer_keys, loss_function=loss_function, loss_function_keys=loss_function_keys, metrics=metrics, metrics_keys=metrics_keys, code_length=code_length, num_encoder_layers=num_encoder_layers, num_decoder_layers=num_decoder_layers) model.build_model_graph(images[0].shape) (images_train, images_test) = train_test_split(images, test_size=0.3, shuffle=True) print('Train:', len(images_train.shape)) print('Test:', len(images_test.shape)) model.train(images_train, images_test, epochs=epochs, batch_size=batch_size, validation_split=0.2) if (not algo.startswith('gan')): model.prepare_code_statistics(images_train, batch_size=batch_size, sample_size=samples_for_code_statistics) return model<|docstring|>This function train model based on passed data and argumenents to generate realastic looking images **Parameters** images : list Images to be passed to learning functions, has shape [N, (2D or 3D)], where N is number of samples and 2D and 3D denotes image size algo : str Algorithm to be used to learn image representation, Eg Autoencode_dense, code_length: int Default 8, Length of intermediate representation or condense space generated by model. In order to generate a random image sample having dimention equal to code_length must be passed. num_encoder_layer: int Default 'auto', number of layers to be used in encoder, applicable for autoenocder num_decoder_layers: int Default 'auto', number of layers to be used in decoder, applicable for autoenocder epochs: int Default 10, number of epoch to be used while training model batch_size: int Default 16, batch size of each training/eval/generation step optimizer: string Default 'adam', optimizer used to train the model learning_rate: int Default 0.001, learning rate for training model loss_function: string Default 'mse', loss function for training model metrics: list of string Default ['mse'], list of metrics to be printed while training samples_for_code_statistics: int Default 64, samples to be used to generate code statistics **Returns** object model object trained on given dataset<|endoftext|>
1f098c8eaf3b810df0306f0f06dcdcb85c63186ec8526d22a2b020b2db858cea
@pytest.mark.parametrize('precision', [np.float32, np.float64]) @pytest.mark.parametrize('input_type', ['numpy']) def test_stationarity(precision, input_type): 'Test the kpss stationarity check.\n Note: this test is intended to test the Python wrapper.\n Another more exhaustive test is part of the C++ unit tests.\n ' inc_rates = [(- 0.7), 0.0, 0.5] offsets = [(- 0.3), 0.5, 0.0] d_ref = [1, 0, 1] num_samples = 200 xs = np.linspace(0, 1, num_samples) np.random.seed(13) noise = np.random.normal(scale=0.1, size=num_samples) np_df = np.zeros((num_samples, len(d_ref)), order='F', dtype=precision) for i in range(len(d_ref)): np_df[(:, i)] = (((xs[:] * inc_rates[i]) + offsets[i]) + noise[:]) if (input_type == 'numpy'): df = np_df d_actual = stationarity(df) (success, message) = array_eq(d_ref, d_actual) assert success, message
Test the kpss stationarity check. Note: this test is intended to test the Python wrapper. Another more exhaustive test is part of the C++ unit tests.
python/cuml/test/test_stationarity.py
test_stationarity
asony03/cuml
1
python
@pytest.mark.parametrize('precision', [np.float32, np.float64]) @pytest.mark.parametrize('input_type', ['numpy']) def test_stationarity(precision, input_type): 'Test the kpss stationarity check.\n Note: this test is intended to test the Python wrapper.\n Another more exhaustive test is part of the C++ unit tests.\n ' inc_rates = [(- 0.7), 0.0, 0.5] offsets = [(- 0.3), 0.5, 0.0] d_ref = [1, 0, 1] num_samples = 200 xs = np.linspace(0, 1, num_samples) np.random.seed(13) noise = np.random.normal(scale=0.1, size=num_samples) np_df = np.zeros((num_samples, len(d_ref)), order='F', dtype=precision) for i in range(len(d_ref)): np_df[(:, i)] = (((xs[:] * inc_rates[i]) + offsets[i]) + noise[:]) if (input_type == 'numpy'): df = np_df d_actual = stationarity(df) (success, message) = array_eq(d_ref, d_actual) assert success, message
@pytest.mark.parametrize('precision', [np.float32, np.float64]) @pytest.mark.parametrize('input_type', ['numpy']) def test_stationarity(precision, input_type): 'Test the kpss stationarity check.\n Note: this test is intended to test the Python wrapper.\n Another more exhaustive test is part of the C++ unit tests.\n ' inc_rates = [(- 0.7), 0.0, 0.5] offsets = [(- 0.3), 0.5, 0.0] d_ref = [1, 0, 1] num_samples = 200 xs = np.linspace(0, 1, num_samples) np.random.seed(13) noise = np.random.normal(scale=0.1, size=num_samples) np_df = np.zeros((num_samples, len(d_ref)), order='F', dtype=precision) for i in range(len(d_ref)): np_df[(:, i)] = (((xs[:] * inc_rates[i]) + offsets[i]) + noise[:]) if (input_type == 'numpy'): df = np_df d_actual = stationarity(df) (success, message) = array_eq(d_ref, d_actual) assert success, message<|docstring|>Test the kpss stationarity check. Note: this test is intended to test the Python wrapper. Another more exhaustive test is part of the C++ unit tests.<|endoftext|>
1e507ea32dd6824a196c354d371884917a4678c9edeb0f9b7b0b2dd3cf49e8ae
def get() -> flask.Response: '\n Get the default seed.\n\n Returns:\n The default seed or a server error.\n\n ' try: return flask.Response(seed.get_seed().get(name=config.get_env().default_seed_name), status=200, mimetype='text/plain') except seed.exceptions.SeedNotFoundError as exc: return flask.Response(str(exc), status=500, mimetype='text/plain')
Get the default seed. Returns: The default seed or a server error.
api/library/seed.py
get
open-alchemy/Editor
0
python
def get() -> flask.Response: '\n Get the default seed.\n\n Returns:\n The default seed or a server error.\n\n ' try: return flask.Response(seed.get_seed().get(name=config.get_env().default_seed_name), status=200, mimetype='text/plain') except seed.exceptions.SeedNotFoundError as exc: return flask.Response(str(exc), status=500, mimetype='text/plain')
def get() -> flask.Response: '\n Get the default seed.\n\n Returns:\n The default seed or a server error.\n\n ' try: return flask.Response(seed.get_seed().get(name=config.get_env().default_seed_name), status=200, mimetype='text/plain') except seed.exceptions.SeedNotFoundError as exc: return flask.Response(str(exc), status=500, mimetype='text/plain')<|docstring|>Get the default seed. Returns: The default seed or a server error.<|endoftext|>
05afe3c7e6e8ce0e7055ae9125941cbfeb71fde0c1b2db185b4b3a068c42b365
def get_root(ast) -> int: 'get root node index' for (idx, node) in ast.items(): if (node['parent'] is None): return idx
get root node index
dataset/py150/utils/ast/child_value.py
get_root
CGCL-codes/naturalcc
71
python
def get_root(ast) -> int: for (idx, node) in ast.items(): if (node['parent'] is None): return idx
def get_root(ast) -> int: for (idx, node) in ast.items(): if (node['parent'] is None): return idx<|docstring|>get root node index<|endoftext|>
d32098a317f7215ba8762ed811bca83b543e20f0e4ffae73c3f5074328033fa1
def reset_indices(ast): "rename ast tree's node indices with consecutive indices" if (sorted(list(ast.keys())) == list(range(len(ast)))): return ast _idx = 0 def _dfs(idx, _parent_idx): nonlocal _idx (_new_idx, _idx) = (f'_{_idx}', (_idx + 1)) node = ast.pop(idx) ast[_new_idx] = node if (node['parent'] is None): pass else: parent_node = ast[_parent_idx] parent_node['children'][parent_node['children'].index(idx)] = _new_idx node['parent'] = _parent_idx if ('children' in node): for child_idx in node['children']: _dfs(child_idx, _parent_idx=_new_idx) else: return root_idx = get_root(ast) _dfs(root_idx, _parent_idx=None) node_ids = deepcopy(list(ast.keys())) for idx in node_ids: node = ast.pop(idx) if ('children' in node): node['children'] = [int(child_idx[1:]) for child_idx in node['children']] if (node['parent'] == None): pass else: node['parent'] = int(node['parent'][1:]) ast[int(idx[1:])] = node return ast
rename ast tree's node indices with consecutive indices
dataset/py150/utils/ast/child_value.py
reset_indices
CGCL-codes/naturalcc
71
python
def reset_indices(ast): if (sorted(list(ast.keys())) == list(range(len(ast)))): return ast _idx = 0 def _dfs(idx, _parent_idx): nonlocal _idx (_new_idx, _idx) = (f'_{_idx}', (_idx + 1)) node = ast.pop(idx) ast[_new_idx] = node if (node['parent'] is None): pass else: parent_node = ast[_parent_idx] parent_node['children'][parent_node['children'].index(idx)] = _new_idx node['parent'] = _parent_idx if ('children' in node): for child_idx in node['children']: _dfs(child_idx, _parent_idx=_new_idx) else: return root_idx = get_root(ast) _dfs(root_idx, _parent_idx=None) node_ids = deepcopy(list(ast.keys())) for idx in node_ids: node = ast.pop(idx) if ('children' in node): node['children'] = [int(child_idx[1:]) for child_idx in node['children']] if (node['parent'] == None): pass else: node['parent'] = int(node['parent'][1:]) ast[int(idx[1:])] = node return ast
def reset_indices(ast): if (sorted(list(ast.keys())) == list(range(len(ast)))): return ast _idx = 0 def _dfs(idx, _parent_idx): nonlocal _idx (_new_idx, _idx) = (f'_{_idx}', (_idx + 1)) node = ast.pop(idx) ast[_new_idx] = node if (node['parent'] is None): pass else: parent_node = ast[_parent_idx] parent_node['children'][parent_node['children'].index(idx)] = _new_idx node['parent'] = _parent_idx if ('children' in node): for child_idx in node['children']: _dfs(child_idx, _parent_idx=_new_idx) else: return root_idx = get_root(ast) _dfs(root_idx, _parent_idx=None) node_ids = deepcopy(list(ast.keys())) for idx in node_ids: node = ast.pop(idx) if ('children' in node): node['children'] = [int(child_idx[1:]) for child_idx in node['children']] if (node['parent'] == None): pass else: node['parent'] = int(node['parent'][1:]) ast[int(idx[1:])] = node return ast<|docstring|>rename ast tree's node indices with consecutive indices<|endoftext|>
df951b01144b43c7c025956c00f81c40048865dc33c65edac396e2e160e1702f
def ast2sbt(ast, idx): '\n build structure-based traversal SBT tree\n ref: Deep Code Comment Generation\n ' idx = str(idx) if ('value' in ast[idx]): token = [ast[idx]['type'], ast[idx]['value']] seq = [SBT_LEFT_PARENTHESE, token, SBT_RIGHT_PARENTHESE, token] else: token = ast[idx]['type'] seq = [SBT_LEFT_PARENTHESE, token] for child_idx in ast[idx]['children']: seq += ast2sbt(ast, child_idx) seq += [SBT_RIGHT_PARENTHESE, token] return seq
build structure-based traversal SBT tree ref: Deep Code Comment Generation
dataset/py150/utils/ast/child_value.py
ast2sbt
CGCL-codes/naturalcc
71
python
def ast2sbt(ast, idx): '\n build structure-based traversal SBT tree\n ref: Deep Code Comment Generation\n ' idx = str(idx) if ('value' in ast[idx]): token = [ast[idx]['type'], ast[idx]['value']] seq = [SBT_LEFT_PARENTHESE, token, SBT_RIGHT_PARENTHESE, token] else: token = ast[idx]['type'] seq = [SBT_LEFT_PARENTHESE, token] for child_idx in ast[idx]['children']: seq += ast2sbt(ast, child_idx) seq += [SBT_RIGHT_PARENTHESE, token] return seq
def ast2sbt(ast, idx): '\n build structure-based traversal SBT tree\n ref: Deep Code Comment Generation\n ' idx = str(idx) if ('value' in ast[idx]): token = [ast[idx]['type'], ast[idx]['value']] seq = [SBT_LEFT_PARENTHESE, token, SBT_RIGHT_PARENTHESE, token] else: token = ast[idx]['type'] seq = [SBT_LEFT_PARENTHESE, token] for child_idx in ast[idx]['children']: seq += ast2sbt(ast, child_idx) seq += [SBT_RIGHT_PARENTHESE, token] return seq<|docstring|>build structure-based traversal SBT tree ref: Deep Code Comment Generation<|endoftext|>
82c92a613d9cecd47d9760f009b3242bdefa48d5da324aa92b433aea3830cfb0
@property def parent_snapshot_name(self): "\n The name of the snapshot in\n 'parent-volume-name' serving\n as the parent of this clone.\n " return self._parent_snapshot_name
The name of the snapshot in 'parent-volume-name' serving as the parent of this clone.
generated-libraries/python/netapp/volume/clone_parent_info.py
parent_snapshot_name
radekg/netapp-ontap-lib-get
2
python
@property def parent_snapshot_name(self): "\n The name of the snapshot in\n 'parent-volume-name' serving\n as the parent of this clone.\n " return self._parent_snapshot_name
@property def parent_snapshot_name(self): "\n The name of the snapshot in\n 'parent-volume-name' serving\n as the parent of this clone.\n " return self._parent_snapshot_name<|docstring|>The name of the snapshot in 'parent-volume-name' serving as the parent of this clone.<|endoftext|>
072c963a786a7c9ac9f1dcc1d4f2b6623f3e34e6fed026076d95ba0384dcf3b5
@property def parent_volume_name(self): '\n The name of the flexible\n volume serving as the\n parent of this clone.\n ' return self._parent_volume_name
The name of the flexible volume serving as the parent of this clone.
generated-libraries/python/netapp/volume/clone_parent_info.py
parent_volume_name
radekg/netapp-ontap-lib-get
2
python
@property def parent_volume_name(self): '\n The name of the flexible\n volume serving as the\n parent of this clone.\n ' return self._parent_volume_name
@property def parent_volume_name(self): '\n The name of the flexible\n volume serving as the\n parent of this clone.\n ' return self._parent_volume_name<|docstring|>The name of the flexible volume serving as the parent of this clone.<|endoftext|>
aa06b5b23efaeb95dd1534c85fc6edf88a5a839055b8a89b1ad3f15d776f3d5d
def _get_item_by_idx(self, iterator, idx): 'Get the idx-th item of the iterator' size = len(self) idx = operator.index(idx) if (not ((- size) <= idx < size)): raise IndexError('index {} is out of range'.format(idx)) idx %= size return next(islice(iterator, idx, None))
Get the idx-th item of the iterator
python/oneflow/nn/utils/container.py
_get_item_by_idx
felixhao28/oneflow
3,285
python
def _get_item_by_idx(self, iterator, idx): size = len(self) idx = operator.index(idx) if (not ((- size) <= idx < size)): raise IndexError('index {} is out of range'.format(idx)) idx %= size return next(islice(iterator, idx, None))
def _get_item_by_idx(self, iterator, idx): size = len(self) idx = operator.index(idx) if (not ((- size) <= idx < size)): raise IndexError('index {} is out of range'.format(idx)) idx %= size return next(islice(iterator, idx, None))<|docstring|>Get the idx-th item of the iterator<|endoftext|>
d1d611624f2e35f98c910dc5e33d5a8429213f291e0abbe7b195ab4b86a19bca
def _get_abs_string_index(self, idx): 'Get the absolute index for the list of modules' idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)
Get the absolute index for the list of modules
python/oneflow/nn/utils/container.py
_get_abs_string_index
felixhao28/oneflow
3,285
python
def _get_abs_string_index(self, idx): idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)
def _get_abs_string_index(self, idx): idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)<|docstring|>Get the absolute index for the list of modules<|endoftext|>
9a94d63355557420b5ba1fe4b40df3b8f35c24b6d36af49f6d7169645de57e47
def insert(self, index: int, module: T) -> None: 'Insert a given module before a given index in the list.\n \n Arguments:\n index (int): index to insert.\n module (nn.Module): module to insert\n ' for i in range(len(self._modules), index, (- 1)): self._modules[str(i)] = self._modules[str((i - 1))] self._modules[str(index)] = module
Insert a given module before a given index in the list. Arguments: index (int): index to insert. module (nn.Module): module to insert
python/oneflow/nn/utils/container.py
insert
felixhao28/oneflow
3,285
python
def insert(self, index: int, module: T) -> None: 'Insert a given module before a given index in the list.\n \n Arguments:\n index (int): index to insert.\n module (nn.Module): module to insert\n ' for i in range(len(self._modules), index, (- 1)): self._modules[str(i)] = self._modules[str((i - 1))] self._modules[str(index)] = module
def insert(self, index: int, module: T) -> None: 'Insert a given module before a given index in the list.\n \n Arguments:\n index (int): index to insert.\n module (nn.Module): module to insert\n ' for i in range(len(self._modules), index, (- 1)): self._modules[str(i)] = self._modules[str((i - 1))] self._modules[str(index)] = module<|docstring|>Insert a given module before a given index in the list. Arguments: index (int): index to insert. module (nn.Module): module to insert<|endoftext|>
9e8cac899471c19ab80b0fcce3875fc80bb0be3c1901da31261479310bc4a174
def append(self: T, module: T) -> T: 'Appends a given module to the end of the list.\n \n Arguments:\n module (nn.Module): module to append\n ' self.add_module(str(len(self)), module) return self
Appends a given module to the end of the list. Arguments: module (nn.Module): module to append
python/oneflow/nn/utils/container.py
append
felixhao28/oneflow
3,285
python
def append(self: T, module: T) -> T: 'Appends a given module to the end of the list.\n \n Arguments:\n module (nn.Module): module to append\n ' self.add_module(str(len(self)), module) return self
def append(self: T, module: T) -> T: 'Appends a given module to the end of the list.\n \n Arguments:\n module (nn.Module): module to append\n ' self.add_module(str(len(self)), module) return self<|docstring|>Appends a given module to the end of the list. Arguments: module (nn.Module): module to append<|endoftext|>
abe83d1ee8979c341fdfe880fcaa917a9370b70d4487a05aa09098bc54a9f817
def extend(self: T, modules: Iterable[Module]) -> T: 'Appends modules from a Python iterable to the end of the list.\n \n Arguments:\n modules (iterable): iterable of modules to append\n ' if (not isinstance(modules, collections.abc.Iterable)): raise TypeError(('ModuleList.extend should be called with an iterable, but got ' + type(modules).__name__)) offset = len(self) for (i, module) in enumerate(modules): self.add_module(str((offset + i)), module) return self
Appends modules from a Python iterable to the end of the list. Arguments: modules (iterable): iterable of modules to append
python/oneflow/nn/utils/container.py
extend
felixhao28/oneflow
3,285
python
def extend(self: T, modules: Iterable[Module]) -> T: 'Appends modules from a Python iterable to the end of the list.\n \n Arguments:\n modules (iterable): iterable of modules to append\n ' if (not isinstance(modules, collections.abc.Iterable)): raise TypeError(('ModuleList.extend should be called with an iterable, but got ' + type(modules).__name__)) offset = len(self) for (i, module) in enumerate(modules): self.add_module(str((offset + i)), module) return self
def extend(self: T, modules: Iterable[Module]) -> T: 'Appends modules from a Python iterable to the end of the list.\n \n Arguments:\n modules (iterable): iterable of modules to append\n ' if (not isinstance(modules, collections.abc.Iterable)): raise TypeError(('ModuleList.extend should be called with an iterable, but got ' + type(modules).__name__)) offset = len(self) for (i, module) in enumerate(modules): self.add_module(str((offset + i)), module) return self<|docstring|>Appends modules from a Python iterable to the end of the list. Arguments: modules (iterable): iterable of modules to append<|endoftext|>
2167ef2582afc5809068d1e05035f28db7ffb54255457826e27361a6c736028a
def clear(self) -> None: 'Remove all items from the ModuleDict.\n ' self._modules.clear()
Remove all items from the ModuleDict.
python/oneflow/nn/utils/container.py
clear
felixhao28/oneflow
3,285
python
def clear(self) -> None: '\n ' self._modules.clear()
def clear(self) -> None: '\n ' self._modules.clear()<|docstring|>Remove all items from the ModuleDict.<|endoftext|>
94c7e5da6079ad5a2cd7d9e774be30857758006b1279cf6277b4792ee0e327c1
def pop(self, key: str) -> T: 'Remove key from the ModuleDict and return its module.\n \n Arguments:\n key (string): key to pop from the ModuleDict\n ' v = self[key] del self[key] return v
Remove key from the ModuleDict and return its module. Arguments: key (string): key to pop from the ModuleDict
python/oneflow/nn/utils/container.py
pop
felixhao28/oneflow
3,285
python
def pop(self, key: str) -> T: 'Remove key from the ModuleDict and return its module.\n \n Arguments:\n key (string): key to pop from the ModuleDict\n ' v = self[key] del self[key] return v
def pop(self, key: str) -> T: 'Remove key from the ModuleDict and return its module.\n \n Arguments:\n key (string): key to pop from the ModuleDict\n ' v = self[key] del self[key] return v<|docstring|>Remove key from the ModuleDict and return its module. Arguments: key (string): key to pop from the ModuleDict<|endoftext|>
1c18bf231b1b539720b6920fc4df63dd9c4b2add72c03115ddd498e195dc6b55
def keys(self) -> Iterable[str]: 'Return an iterable of the ModuleDict keys.\n ' return self._modules.keys()
Return an iterable of the ModuleDict keys.
python/oneflow/nn/utils/container.py
keys
felixhao28/oneflow
3,285
python
def keys(self) -> Iterable[str]: '\n ' return self._modules.keys()
def keys(self) -> Iterable[str]: '\n ' return self._modules.keys()<|docstring|>Return an iterable of the ModuleDict keys.<|endoftext|>
ef01aee898ca24fcb794a420e3821684fb7ee28d36bdf27a7b6314b3d8723267
def items(self) -> Iterable[Tuple[(str, T)]]: 'Return an iterable of the ModuleDict key/value pairs.\n ' return self._modules.items()
Return an iterable of the ModuleDict key/value pairs.
python/oneflow/nn/utils/container.py
items
felixhao28/oneflow
3,285
python
def items(self) -> Iterable[Tuple[(str, T)]]: '\n ' return self._modules.items()
def items(self) -> Iterable[Tuple[(str, T)]]: '\n ' return self._modules.items()<|docstring|>Return an iterable of the ModuleDict key/value pairs.<|endoftext|>
906a4ba222119f9f510e333a4b48c6036e4f4d24457b018b1854c2243cf3f327
def values(self) -> Iterable[T]: 'Return an iterable of the ModuleDict values.\n ' return self._modules.values()
Return an iterable of the ModuleDict values.
python/oneflow/nn/utils/container.py
values
felixhao28/oneflow
3,285
python
def values(self) -> Iterable[T]: '\n ' return self._modules.values()
def values(self) -> Iterable[T]: '\n ' return self._modules.values()<|docstring|>Return an iterable of the ModuleDict values.<|endoftext|>
d1d611624f2e35f98c910dc5e33d5a8429213f291e0abbe7b195ab4b86a19bca
def _get_abs_string_index(self, idx): 'Get the absolute index for the list of modules' idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)
Get the absolute index for the list of modules
python/oneflow/nn/utils/container.py
_get_abs_string_index
felixhao28/oneflow
3,285
python
def _get_abs_string_index(self, idx): idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)
def _get_abs_string_index(self, idx): idx = operator.index(idx) if (not ((- len(self)) <= idx < len(self))): raise IndexError('index {} is out of range'.format(idx)) if (idx < 0): idx += len(self) return str(idx)<|docstring|>Get the absolute index for the list of modules<|endoftext|>
e4983d1593a3e84bb74bd2734143f9a4bae2d9c809ce84e36a412a24525cc6c7
def append(self: T, parameter) -> T: 'Appends a given parameter at the end of the list.\n \n Arguments:\n \n parameter (nn.Parameter): parameter to append\n ' self.register_parameter(str(len(self)), parameter) return self
Appends a given parameter at the end of the list. Arguments: parameter (nn.Parameter): parameter to append
python/oneflow/nn/utils/container.py
append
felixhao28/oneflow
3,285
python
def append(self: T, parameter) -> T: 'Appends a given parameter at the end of the list.\n \n Arguments:\n \n parameter (nn.Parameter): parameter to append\n ' self.register_parameter(str(len(self)), parameter) return self
def append(self: T, parameter) -> T: 'Appends a given parameter at the end of the list.\n \n Arguments:\n \n parameter (nn.Parameter): parameter to append\n ' self.register_parameter(str(len(self)), parameter) return self<|docstring|>Appends a given parameter at the end of the list. Arguments: parameter (nn.Parameter): parameter to append<|endoftext|>
d4eaeee48b4855b598cc736dbe484ffd9dda9bcffd47a96eea907dbf883df686
def extend(self: T, parameters) -> T: 'Appends parameters from a Python iterable to the end of the list.\n \n Arguments:\n \n parameters (iterable): iterable of parameters to append\n ' if (not isinstance(parameters, collections.abc.Iterable)): raise TypeError(('ParameterList.extend should be called with an iterable, but got ' + type(parameters).__name__)) offset = len(self) for (i, param) in enumerate(parameters): self.register_parameter(str((offset + i)), param) return self
Appends parameters from a Python iterable to the end of the list. Arguments: parameters (iterable): iterable of parameters to append
python/oneflow/nn/utils/container.py
extend
felixhao28/oneflow
3,285
python
def extend(self: T, parameters) -> T: 'Appends parameters from a Python iterable to the end of the list.\n \n Arguments:\n \n parameters (iterable): iterable of parameters to append\n ' if (not isinstance(parameters, collections.abc.Iterable)): raise TypeError(('ParameterList.extend should be called with an iterable, but got ' + type(parameters).__name__)) offset = len(self) for (i, param) in enumerate(parameters): self.register_parameter(str((offset + i)), param) return self
def extend(self: T, parameters) -> T: 'Appends parameters from a Python iterable to the end of the list.\n \n Arguments:\n \n parameters (iterable): iterable of parameters to append\n ' if (not isinstance(parameters, collections.abc.Iterable)): raise TypeError(('ParameterList.extend should be called with an iterable, but got ' + type(parameters).__name__)) offset = len(self) for (i, param) in enumerate(parameters): self.register_parameter(str((offset + i)), param) return self<|docstring|>Appends parameters from a Python iterable to the end of the list. Arguments: parameters (iterable): iterable of parameters to append<|endoftext|>
b23163e575b2c6e46e4b19cbd3343bd0642d11b8181febba10fb6cb1a7e4dc3c
def clear(self) -> None: 'Remove all items from the ParameterDict.\n ' self._parameters.clear()
Remove all items from the ParameterDict.
python/oneflow/nn/utils/container.py
clear
felixhao28/oneflow
3,285
python
def clear(self) -> None: '\n ' self._parameters.clear()
def clear(self) -> None: '\n ' self._parameters.clear()<|docstring|>Remove all items from the ParameterDict.<|endoftext|>
a819f764d4475fc8be63307a7faa3cb673e71683bbeeedf61b60880d4ae8fba9
def pop(self, key: str): 'Remove key from the ParameterDict and return its parameter.\n \n Args:\n \n key (string): key to pop from the ParameterDict\n ' v = self[key] del self[key] return v
Remove key from the ParameterDict and return its parameter. Args: key (string): key to pop from the ParameterDict
python/oneflow/nn/utils/container.py
pop
felixhao28/oneflow
3,285
python
def pop(self, key: str): 'Remove key from the ParameterDict and return its parameter.\n \n Args:\n \n key (string): key to pop from the ParameterDict\n ' v = self[key] del self[key] return v
def pop(self, key: str): 'Remove key from the ParameterDict and return its parameter.\n \n Args:\n \n key (string): key to pop from the ParameterDict\n ' v = self[key] del self[key] return v<|docstring|>Remove key from the ParameterDict and return its parameter. Args: key (string): key to pop from the ParameterDict<|endoftext|>
5a392282944d29b143b450276d0c942349844ce474e0cafed489c3f3e9b00a69
def keys(self) -> Iterable[str]: 'Return an iterable of the ParameterDict keys.\n ' return self._parameters.keys()
Return an iterable of the ParameterDict keys.
python/oneflow/nn/utils/container.py
keys
felixhao28/oneflow
3,285
python
def keys(self) -> Iterable[str]: '\n ' return self._parameters.keys()
def keys(self) -> Iterable[str]: '\n ' return self._parameters.keys()<|docstring|>Return an iterable of the ParameterDict keys.<|endoftext|>
f5bea9c8698c06af8a47e203fd1680a64c49168c48c674a32a5e6ffe68d0fc54
def items(self): 'Return an iterable of the ParameterDict key/value pairs.\n ' return self._parameters.items()
Return an iterable of the ParameterDict key/value pairs.
python/oneflow/nn/utils/container.py
items
felixhao28/oneflow
3,285
python
def items(self): '\n ' return self._parameters.items()
def items(self): '\n ' return self._parameters.items()<|docstring|>Return an iterable of the ParameterDict key/value pairs.<|endoftext|>
177bb480abda333432809e2b23427d026f7c373c26a082428307e3b18e09599d
def values(self): 'Return an iterable of the ParameterDict values.\n ' return self._parameters.values()
Return an iterable of the ParameterDict values.
python/oneflow/nn/utils/container.py
values
felixhao28/oneflow
3,285
python
def values(self): '\n ' return self._parameters.values()
def values(self): '\n ' return self._parameters.values()<|docstring|>Return an iterable of the ParameterDict values.<|endoftext|>
1e34e349f453c12edf100c834599b9121312ad310fb5b17543cd23008f667e4d
def update(self, parameters) -> None: 'Update the :class:`~flow.nn.ParameterDict` with the key-value pairs from a\n mapping or an iterable, overwriting existing keys.\n \n .. note::\n If :attr:`parameters` is an ``OrderedDict``, a :class:`~flow.nn.ParameterDict`, or\n an iterable of key-value pairs, the order of new elements in it is preserved.\n \n Args:\n parameters (iterable): a mapping (dictionary) from string to\n :class:`~flow.nn.Parameter`, or an iterable of\n key-value pairs of type (string, :class:`~flow.nn.Parameter`)\n \n ' if (not isinstance(parameters, container_abcs.Iterable)): raise TypeError(('ParametersDict.update should be called with an iterable of key/value pairs, but got ' + type(parameters).__name__)) if isinstance(parameters, (OrderedDict, ParameterDictContainer)): for (key, parameter) in parameters.items(): self[key] = parameter elif isinstance(parameters, container_abcs.Mapping): for (key, parameter) in sorted(parameters.items()): self[key] = parameter else: for (j, p) in enumerate(parameters): if (not isinstance(p, container_abcs.Iterable)): raise TypeError(((('ParameterDict update sequence element #' + str(j)) + ' should be Iterable; is') + type(p).__name__)) if (not (len(p) == 2)): raise ValueError((((('ParameterDict update sequence element #' + str(j)) + ' has length ') + str(len(p))) + '; 2 is required')) self[p[0]] = p[1]
Update the :class:`~flow.nn.ParameterDict` with the key-value pairs from a mapping or an iterable, overwriting existing keys. .. note:: If :attr:`parameters` is an ``OrderedDict``, a :class:`~flow.nn.ParameterDict`, or an iterable of key-value pairs, the order of new elements in it is preserved. Args: parameters (iterable): a mapping (dictionary) from string to :class:`~flow.nn.Parameter`, or an iterable of key-value pairs of type (string, :class:`~flow.nn.Parameter`)
python/oneflow/nn/utils/container.py
update
felixhao28/oneflow
3,285
python
def update(self, parameters) -> None: 'Update the :class:`~flow.nn.ParameterDict` with the key-value pairs from a\n mapping or an iterable, overwriting existing keys.\n \n .. note::\n If :attr:`parameters` is an ``OrderedDict``, a :class:`~flow.nn.ParameterDict`, or\n an iterable of key-value pairs, the order of new elements in it is preserved.\n \n Args:\n parameters (iterable): a mapping (dictionary) from string to\n :class:`~flow.nn.Parameter`, or an iterable of\n key-value pairs of type (string, :class:`~flow.nn.Parameter`)\n \n ' if (not isinstance(parameters, container_abcs.Iterable)): raise TypeError(('ParametersDict.update should be called with an iterable of key/value pairs, but got ' + type(parameters).__name__)) if isinstance(parameters, (OrderedDict, ParameterDictContainer)): for (key, parameter) in parameters.items(): self[key] = parameter elif isinstance(parameters, container_abcs.Mapping): for (key, parameter) in sorted(parameters.items()): self[key] = parameter else: for (j, p) in enumerate(parameters): if (not isinstance(p, container_abcs.Iterable)): raise TypeError(((('ParameterDict update sequence element #' + str(j)) + ' should be Iterable; is') + type(p).__name__)) if (not (len(p) == 2)): raise ValueError((((('ParameterDict update sequence element #' + str(j)) + ' has length ') + str(len(p))) + '; 2 is required')) self[p[0]] = p[1]
def update(self, parameters) -> None: 'Update the :class:`~flow.nn.ParameterDict` with the key-value pairs from a\n mapping or an iterable, overwriting existing keys.\n \n .. note::\n If :attr:`parameters` is an ``OrderedDict``, a :class:`~flow.nn.ParameterDict`, or\n an iterable of key-value pairs, the order of new elements in it is preserved.\n \n Args:\n parameters (iterable): a mapping (dictionary) from string to\n :class:`~flow.nn.Parameter`, or an iterable of\n key-value pairs of type (string, :class:`~flow.nn.Parameter`)\n \n ' if (not isinstance(parameters, container_abcs.Iterable)): raise TypeError(('ParametersDict.update should be called with an iterable of key/value pairs, but got ' + type(parameters).__name__)) if isinstance(parameters, (OrderedDict, ParameterDictContainer)): for (key, parameter) in parameters.items(): self[key] = parameter elif isinstance(parameters, container_abcs.Mapping): for (key, parameter) in sorted(parameters.items()): self[key] = parameter else: for (j, p) in enumerate(parameters): if (not isinstance(p, container_abcs.Iterable)): raise TypeError(((('ParameterDict update sequence element #' + str(j)) + ' should be Iterable; is') + type(p).__name__)) if (not (len(p) == 2)): raise ValueError((((('ParameterDict update sequence element #' + str(j)) + ' has length ') + str(len(p))) + '; 2 is required')) self[p[0]] = p[1]<|docstring|>Update the :class:`~flow.nn.ParameterDict` with the key-value pairs from a mapping or an iterable, overwriting existing keys. .. note:: If :attr:`parameters` is an ``OrderedDict``, a :class:`~flow.nn.ParameterDict`, or an iterable of key-value pairs, the order of new elements in it is preserved. Args: parameters (iterable): a mapping (dictionary) from string to :class:`~flow.nn.Parameter`, or an iterable of key-value pairs of type (string, :class:`~flow.nn.Parameter`)<|endoftext|>
9d39422ccd18c5be04bf57eb195ead89621a27aeac5cf420a873f5c7a2e46176
def setUp(self): '\n Initializes a unit test\n ' locs = locals() globs = globals() globs['__builtins__']['quit'] = self.doquit globs['__builtins__']['print'] = self.doprint self._test = __import__('introcs.testcase', globs, locs) self.clear()
Initializes a unit test
tests/test_testcase.py
setUp
WalkerWhite/introcs-python
1
python
def setUp(self): '\n \n ' locs = locals() globs = globals() globs['__builtins__']['quit'] = self.doquit globs['__builtins__']['print'] = self.doprint self._test = __import__('introcs.testcase', globs, locs) self.clear()
def setUp(self): '\n \n ' locs = locals() globs = globals() globs['__builtins__']['quit'] = self.doquit globs['__builtins__']['print'] = self.doprint self._test = __import__('introcs.testcase', globs, locs) self.clear()<|docstring|>Initializes a unit test<|endoftext|>
917a3003a270c1a5794ad616e94d4cadf39890dfcc3e787372765b7c69a45c25
def tearDown(self): '\n Completes a unit test\n ' globs = globals() globs['__builtins__']['quit'] = display globs['__builtins__']['print'] = thequit self._test = None
Completes a unit test
tests/test_testcase.py
tearDown
WalkerWhite/introcs-python
1
python
def tearDown(self): '\n \n ' globs = globals() globs['__builtins__']['quit'] = display globs['__builtins__']['print'] = thequit self._test = None
def tearDown(self): '\n \n ' globs = globals() globs['__builtins__']['quit'] = display globs['__builtins__']['print'] = thequit self._test = None<|docstring|>Completes a unit test<|endoftext|>
f5f6404401056a96a4a269cf6307c0fa253411dcc3a6bd033456da96e1bb64b7
def doquit(self): '\n Performs a faux application quit\n ' self._quit = True
Performs a faux application quit
tests/test_testcase.py
doquit
WalkerWhite/introcs-python
1
python
def doquit(self): '\n \n ' self._quit = True
def doquit(self): '\n \n ' self._quit = True<|docstring|>Performs a faux application quit<|endoftext|>
5ee1c346707822a68fb91fd12aa0889d2816ed5f357bed49407582e8abd9c5f3
def isquit(self): '\n Returns true if the assert quit the program.\n ' return self._quit
Returns true if the assert quit the program.
tests/test_testcase.py
isquit
WalkerWhite/introcs-python
1
python
def isquit(self): '\n \n ' return self._quit
def isquit(self): '\n \n ' return self._quit<|docstring|>Returns true if the assert quit the program.<|endoftext|>
246fb5071ea805e45ad8346f4dbf3d2410873dd505aeaf7df83ab6f961889114
def doprint(self, *objects, sep=' ', end='\n', file=None, flush=False): '\n Captures a print statement to an internal attribute for recording.\n ' from io import StringIO outs = StringIO() display(*objects, sep=sep, end=end, file=outs, flush=flush) self._outp.append(outs.getvalue()) outs.close()
Captures a print statement to an internal attribute for recording.
tests/test_testcase.py
doprint
WalkerWhite/introcs-python
1
python
def doprint(self, *objects, sep=' ', end='\n', file=None, flush=False): '\n \n ' from io import StringIO outs = StringIO() display(*objects, sep=sep, end=end, file=outs, flush=flush) self._outp.append(outs.getvalue()) outs.close()
def doprint(self, *objects, sep=' ', end='\n', file=None, flush=False): '\n \n ' from io import StringIO outs = StringIO() display(*objects, sep=sep, end=end, file=outs, flush=flush) self._outp.append(outs.getvalue()) outs.close()<|docstring|>Captures a print statement to an internal attribute for recording.<|endoftext|>
f180d29f54cebf608ac858a144ab796fdcd7865aad82a45e83f764a08678de76
def getprint(self): '\n Returns the attributes recorded form print statements.\n ' return self._outp
Returns the attributes recorded form print statements.
tests/test_testcase.py
getprint
WalkerWhite/introcs-python
1
python
def getprint(self): '\n \n ' return self._outp
def getprint(self): '\n \n ' return self._outp<|docstring|>Returns the attributes recorded form print statements.<|endoftext|>
a1cb250ea6f25871b19cec95ea8d50560c38a60a13c4c243aab55110bc403e1c
def clear(self): '\n Resets the recording of any assert messages.\n ' self._quit = False self._outp = []
Resets the recording of any assert messages.
tests/test_testcase.py
clear
WalkerWhite/introcs-python
1
python
def clear(self): '\n \n ' self._quit = False self._outp = []
def clear(self): '\n \n ' self._quit = False self._outp = []<|docstring|>Resets the recording of any assert messages.<|endoftext|>
8aa94cbf7ddab5366c1b75bc8b622a4fa7c85052d6154dbb204ce9d99dfa3235
def test03_quit(self): '\n Tests the quit command and interception.\n ' def invoke(): self._test.quit_with_error('Hello world!') invoke() self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'Hello world!') self.assertEqual(self._outp[1][:7], 'Line 85') self.clear()
Tests the quit command and interception.
tests/test_testcase.py
test03_quit
WalkerWhite/introcs-python
1
python
def test03_quit(self): '\n \n ' def invoke(): self._test.quit_with_error('Hello world!') invoke() self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'Hello world!') self.assertEqual(self._outp[1][:7], 'Line 85') self.clear()
def test03_quit(self): '\n \n ' def invoke(): self._test.quit_with_error('Hello world!') invoke() self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'Hello world!') self.assertEqual(self._outp[1][:7], 'Line 85') self.clear()<|docstring|>Tests the quit command and interception.<|endoftext|>
c72dfca9fcf3518956eac5d0365e2f7a4bf2b01de0711a9280775cac101f5668
def test04_asserts_basic(self): '\n Tests the basic unit test asserts.\n ' self._test.assert_equals(1, 1) self.assertFalse(self.isquit()) self.clear() self._test.assert_equals(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_equals: expected 1 but instead got 2') self.assertEqual(self._outp[1][:7], 'Line 99') self.clear() self._test.assert_not_equals(1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_not_equals(1, 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_not_equals: expected something different from 1') self.assertEqual(self._outp[1][:8], 'Line 109') self.clear() self._test.assert_true((1 == 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_true(0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_true: 0 evaluates to False') self.assertEqual(self._outp[1][:8], 'Line 119') self.clear() self._test.assert_false((1 == 2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_false(1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_false: 1 evaluates to True') self.assertEqual(self._outp[1][:8], 'Line 129') self.clear()
Tests the basic unit test asserts.
tests/test_testcase.py
test04_asserts_basic
WalkerWhite/introcs-python
1
python
def test04_asserts_basic(self): '\n \n ' self._test.assert_equals(1, 1) self.assertFalse(self.isquit()) self.clear() self._test.assert_equals(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_equals: expected 1 but instead got 2') self.assertEqual(self._outp[1][:7], 'Line 99') self.clear() self._test.assert_not_equals(1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_not_equals(1, 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_not_equals: expected something different from 1') self.assertEqual(self._outp[1][:8], 'Line 109') self.clear() self._test.assert_true((1 == 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_true(0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_true: 0 evaluates to False') self.assertEqual(self._outp[1][:8], 'Line 119') self.clear() self._test.assert_false((1 == 2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_false(1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_false: 1 evaluates to True') self.assertEqual(self._outp[1][:8], 'Line 129') self.clear()
def test04_asserts_basic(self): '\n \n ' self._test.assert_equals(1, 1) self.assertFalse(self.isquit()) self.clear() self._test.assert_equals(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_equals: expected 1 but instead got 2') self.assertEqual(self._outp[1][:7], 'Line 99') self.clear() self._test.assert_not_equals(1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_not_equals(1, 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_not_equals: expected something different from 1') self.assertEqual(self._outp[1][:8], 'Line 109') self.clear() self._test.assert_true((1 == 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_true(0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_true: 0 evaluates to False') self.assertEqual(self._outp[1][:8], 'Line 119') self.clear() self._test.assert_false((1 == 2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_false(1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_false: 1 evaluates to True') self.assertEqual(self._outp[1][:8], 'Line 129') self.clear()<|docstring|>Tests the basic unit test asserts.<|endoftext|>
89abbf8be7ac5de4a27365494a271cc14ce6ea4a44948290a4c6916ef3c8dcba
def test05_asserts_floats(self): '\n Tests the float unit test asserts.\n ' self._test.assert_floats_equal(1.0000001, 1.0000002) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 143') self.clear() self._test.assert_floats_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 149') self.clear() self._test.assert_floats_equal(1.1, 1.2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_equal: expected 1.1 but instead got 1.2') self.assertEqual(self._outp[1][:8], 'Line 155') self.clear() self._test.assert_floats_not_equal(1.1, 1.2) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_not_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 165') self.clear() self._test.assert_floats_not_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 171') self.clear() self._test.assert_floats_not_equal(1.0000001, 1.0000002) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_not_equal: expected something different from 1.0000001') self.assertEqual(self._outp[1][:8], 'Line 177') self.clear() self._test.assert_float_lists_equal([2, 1.0000001], (2, 1.0000002)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 187') self.clear() self._test.assert_float_lists_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 193') self.clear() self._test.assert_float_lists_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 199') self.clear() self._test.assert_float_lists_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 205') self.clear() self._test.assert_float_lists_equal([2], (2, 1)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [2] and (2, 1) have different sizes') self.assertEqual(self._outp[1][:8], 'Line 211') self.clear() self._test.assert_float_lists_equal((2, 1), [2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences (2, 1) and [2] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 217') self.clear() self._test.assert_float_lists_equal([1.1, 2.1], [1.1, 2.2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [1.1, 2.1] but instead got [1.1, 2.2]') self.assertEqual(self._outp[1][:8], 'Line 223') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [[1, 2], [3, 4]] but instead got [[1, 2], [3, 5]]') self.assertEqual(self._outp[1][:8], 'Line 233') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [[1, 2], [3, 4]] and [[1, 2]] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 239') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 245') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 251') self.clear() self._test.assert_float_lists_not_equal([1.1, 2.1], (1.1, 2.2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 261') self.clear() self._test.assert_float_lists_not_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 267') self.clear() self._test.assert_float_lists_not_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 273') self.clear() self._test.assert_float_lists_not_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 279') self.clear() self._test.assert_float_lists_not_equal([2], (2, 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal((2, 1), [2]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([2, 1.0000001], (2, 1.0000002)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [2, 1.0000001]') self.assertEqual(self._outp[1][:8], 'Line 293') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [[1, 2], [3, 4]]') self.assertEqual(self._outp[1][:8], 'Line 303') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 309') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 315') self.clear()
Tests the float unit test asserts.
tests/test_testcase.py
test05_asserts_floats
WalkerWhite/introcs-python
1
python
def test05_asserts_floats(self): '\n \n ' self._test.assert_floats_equal(1.0000001, 1.0000002) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 143') self.clear() self._test.assert_floats_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 149') self.clear() self._test.assert_floats_equal(1.1, 1.2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_equal: expected 1.1 but instead got 1.2') self.assertEqual(self._outp[1][:8], 'Line 155') self.clear() self._test.assert_floats_not_equal(1.1, 1.2) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_not_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 165') self.clear() self._test.assert_floats_not_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 171') self.clear() self._test.assert_floats_not_equal(1.0000001, 1.0000002) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_not_equal: expected something different from 1.0000001') self.assertEqual(self._outp[1][:8], 'Line 177') self.clear() self._test.assert_float_lists_equal([2, 1.0000001], (2, 1.0000002)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 187') self.clear() self._test.assert_float_lists_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 193') self.clear() self._test.assert_float_lists_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 199') self.clear() self._test.assert_float_lists_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 205') self.clear() self._test.assert_float_lists_equal([2], (2, 1)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [2] and (2, 1) have different sizes') self.assertEqual(self._outp[1][:8], 'Line 211') self.clear() self._test.assert_float_lists_equal((2, 1), [2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences (2, 1) and [2] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 217') self.clear() self._test.assert_float_lists_equal([1.1, 2.1], [1.1, 2.2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [1.1, 2.1] but instead got [1.1, 2.2]') self.assertEqual(self._outp[1][:8], 'Line 223') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [[1, 2], [3, 4]] but instead got [[1, 2], [3, 5]]') self.assertEqual(self._outp[1][:8], 'Line 233') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [[1, 2], [3, 4]] and [[1, 2]] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 239') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 245') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 251') self.clear() self._test.assert_float_lists_not_equal([1.1, 2.1], (1.1, 2.2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 261') self.clear() self._test.assert_float_lists_not_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 267') self.clear() self._test.assert_float_lists_not_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 273') self.clear() self._test.assert_float_lists_not_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 279') self.clear() self._test.assert_float_lists_not_equal([2], (2, 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal((2, 1), [2]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([2, 1.0000001], (2, 1.0000002)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [2, 1.0000001]') self.assertEqual(self._outp[1][:8], 'Line 293') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [[1, 2], [3, 4]]') self.assertEqual(self._outp[1][:8], 'Line 303') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 309') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 315') self.clear()
def test05_asserts_floats(self): '\n \n ' self._test.assert_floats_equal(1.0000001, 1.0000002) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 143') self.clear() self._test.assert_floats_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 149') self.clear() self._test.assert_floats_equal(1.1, 1.2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_equal: expected 1.1 but instead got 1.2') self.assertEqual(self._outp[1][:8], 'Line 155') self.clear() self._test.assert_floats_not_equal(1.1, 1.2) self.assertFalse(self.isquit()) self.clear() self._test.assert_floats_not_equal('a', 1) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: first argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 165') self.clear() self._test.assert_floats_not_equal(1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_floats_not_equal: second argument 'a' is not a number") self.assertEqual(self._outp[1][:8], 'Line 171') self.clear() self._test.assert_floats_not_equal(1.0000001, 1.0000002) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_floats_not_equal: expected something different from 1.0000001') self.assertEqual(self._outp[1][:8], 'Line 177') self.clear() self._test.assert_float_lists_equal([2, 1.0000001], (2, 1.0000002)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 187') self.clear() self._test.assert_float_lists_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 193') self.clear() self._test.assert_float_lists_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 199') self.clear() self._test.assert_float_lists_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 205') self.clear() self._test.assert_float_lists_equal([2], (2, 1)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [2] and (2, 1) have different sizes') self.assertEqual(self._outp[1][:8], 'Line 211') self.clear() self._test.assert_float_lists_equal((2, 1), [2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences (2, 1) and [2] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 217') self.clear() self._test.assert_float_lists_equal([1.1, 2.1], [1.1, 2.2]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [1.1, 2.1] but instead got [1.1, 2.2]') self.assertEqual(self._outp[1][:8], 'Line 223') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: expected [[1, 2], [3, 4]] but instead got [[1, 2], [3, 5]]') self.assertEqual(self._outp[1][:8], 'Line 233') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_equal: sequences [[1, 2], [3, 4]] and [[1, 2]] have different sizes') self.assertEqual(self._outp[1][:8], 'Line 239') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 245') self.clear() self._test.assert_float_lists_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 251') self.clear() self._test.assert_float_lists_not_equal([1.1, 2.1], (1.1, 2.2)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal('a', [1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 261') self.clear() self._test.assert_float_lists_not_equal((1,), 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument 'a' is not a sequence") self.assertEqual(self._outp[1][:8], 'Line 267') self.clear() self._test.assert_float_lists_not_equal((1, 'a'), [2, 1]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 273') self.clear() self._test.assert_float_lists_not_equal([2, 1], (1, 'a')) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument (1, 'a') has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 279') self.clear() self._test.assert_float_lists_not_equal([2], (2, 1)) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal((2, 1), [2]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([2, 1.0000001], (2, 1.0000002)) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [2, 1.0000001]') self.assertEqual(self._outp[1][:8], 'Line 293') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 5]]) self.assertFalse(self.isquit()) self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_float_lists_not_equal: expected something different from [[1, 2], [3, 4]]') self.assertEqual(self._outp[1][:8], 'Line 303') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 4]], [[1, 2], [3, 'a']]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: second argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 309') self.clear() self._test.assert_float_lists_not_equal([[1, 2], [3, 'a']], [[1, 2], [3, 4]]) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_float_lists_not_equal: first argument [[1, 2], [3, 'a']] has non-numeric values") self.assertEqual(self._outp[1][:8], 'Line 315') self.clear()<|docstring|>Tests the float unit test asserts.<|endoftext|>
c28d0c0d1e5a1b8c7cb6bb0254400aeed6712c2f1b27036be18fc61b54747f4a
def test06_asserts_error(self): '\n Tests the enforcement assertion\n ' def func1(s): assert (type(s) == str) assert (s != '') return s[0] def func2(s): if (type(s) != str): raise TypeError() if (s == ''): raise ValueError(1, 3) return s[0] def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) self._test.assert_error(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: argument 1 is not callable') self.assertEqual(self._outp[1][:8], 'Line 347') self.clear() self._test.assert_error(func1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func1('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 353') self.clear() self._test.assert_error(func1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func1, '') self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 367') self.clear() self._test.assert_error(func2, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func2(2) crashed with TypeError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 373') self.clear() self._test.assert_error(func2, 2, error=TypeError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, '', error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2('') crashed with ValueError, not TypeError") self.assertEqual(self._outp[1][:8], 'Line 383') self.clear() self._test.assert_error(func2, '', error=ValueError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 2) did not crash but instead returned 1.5') self.assertEqual(self._outp[1][:8], 'Line 393') self.clear() self._test.assert_error(func3, 3.0, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3.0, 2, error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3.0, 2) crashed with AssertionError, not TypeError') self.assertEqual(self._outp[1][:8], 'Line 403') self.clear() self._test.assert_error(func3, 3, 2.0) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 0) crashed with ZeroDivisionError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 413') self.clear() self._test.assert_error(func3, 3, 0, error=ZeroDivisionError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 2, error=TypeError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: TypeError has no reason, but expected 'a'") self.assertEqual(self._outp[1][:8], 'Line 423') self.clear() self._test.assert_error(func2, 2, error=TypeError, reason=()) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, '', error=ValueError, reason=(1, 3)) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, '', error=ValueError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: ValueError has reason (1, 3), not 'a'") self.assertEqual(self._outp[1][:8], 'Line 437') self.clear() self._test.assert_error(func3, 'a', 2, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: AssertionError has reason "\'a\' is bad", not \'a\'') self.assertEqual(self._outp[1][:8], 'Line 443') self.clear() self._test.assert_error(func3, True, 2, reason='True is bad') self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 2, True, reason=()) self.assertFalse(self.isquit()) self.clear()
Tests the enforcement assertion
tests/test_testcase.py
test06_asserts_error
WalkerWhite/introcs-python
1
python
def test06_asserts_error(self): '\n \n ' def func1(s): assert (type(s) == str) assert (s != ) return s[0] def func2(s): if (type(s) != str): raise TypeError() if (s == ): raise ValueError(1, 3) return s[0] def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) self._test.assert_error(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: argument 1 is not callable') self.assertEqual(self._outp[1][:8], 'Line 347') self.clear() self._test.assert_error(func1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func1('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 353') self.clear() self._test.assert_error(func1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func1, ) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 367') self.clear() self._test.assert_error(func2, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func2(2) crashed with TypeError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 373') self.clear() self._test.assert_error(func2, 2, error=TypeError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2() crashed with ValueError, not TypeError") self.assertEqual(self._outp[1][:8], 'Line 383') self.clear() self._test.assert_error(func2, , error=ValueError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 2) did not crash but instead returned 1.5') self.assertEqual(self._outp[1][:8], 'Line 393') self.clear() self._test.assert_error(func3, 3.0, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3.0, 2, error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3.0, 2) crashed with AssertionError, not TypeError') self.assertEqual(self._outp[1][:8], 'Line 403') self.clear() self._test.assert_error(func3, 3, 2.0) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 0) crashed with ZeroDivisionError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 413') self.clear() self._test.assert_error(func3, 3, 0, error=ZeroDivisionError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 2, error=TypeError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: TypeError has no reason, but expected 'a'") self.assertEqual(self._outp[1][:8], 'Line 423') self.clear() self._test.assert_error(func2, 2, error=TypeError, reason=()) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=ValueError, reason=(1, 3)) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=ValueError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: ValueError has reason (1, 3), not 'a'") self.assertEqual(self._outp[1][:8], 'Line 437') self.clear() self._test.assert_error(func3, 'a', 2, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: AssertionError has reason "\'a\' is bad", not \'a\) self.assertEqual(self._outp[1][:8], 'Line 443') self.clear() self._test.assert_error(func3, True, 2, reason='True is bad') self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 2, True, reason=()) self.assertFalse(self.isquit()) self.clear()
def test06_asserts_error(self): '\n \n ' def func1(s): assert (type(s) == str) assert (s != ) return s[0] def func2(s): if (type(s) != str): raise TypeError() if (s == ): raise ValueError(1, 3) return s[0] def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) self._test.assert_error(1, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: argument 1 is not callable') self.assertEqual(self._outp[1][:8], 'Line 347') self.clear() self._test.assert_error(func1, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func1('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 353') self.clear() self._test.assert_error(func1, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func1, ) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 'a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2('a') did not crash but instead returned 'a'") self.assertEqual(self._outp[1][:8], 'Line 367') self.clear() self._test.assert_error(func2, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func2(2) crashed with TypeError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 373') self.clear() self._test.assert_error(func2, 2, error=TypeError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: call func2() crashed with ValueError, not TypeError") self.assertEqual(self._outp[1][:8], 'Line 383') self.clear() self._test.assert_error(func2, , error=ValueError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 2) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 2) did not crash but instead returned 1.5') self.assertEqual(self._outp[1][:8], 'Line 393') self.clear() self._test.assert_error(func3, 3.0, 2) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3.0, 2, error=TypeError) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3.0, 2) crashed with AssertionError, not TypeError') self.assertEqual(self._outp[1][:8], 'Line 403') self.clear() self._test.assert_error(func3, 3, 2.0) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 3, 0) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: call func3(3, 0) crashed with ZeroDivisionError, not AssertionError') self.assertEqual(self._outp[1][:8], 'Line 413') self.clear() self._test.assert_error(func3, 3, 0, error=ZeroDivisionError) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, 2, error=TypeError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: TypeError has no reason, but expected 'a'") self.assertEqual(self._outp[1][:8], 'Line 423') self.clear() self._test.assert_error(func2, 2, error=TypeError, reason=()) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=ValueError, reason=(1, 3)) self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func2, , error=ValueError, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), "assert_error: ValueError has reason (1, 3), not 'a'") self.assertEqual(self._outp[1][:8], 'Line 437') self.clear() self._test.assert_error(func3, 'a', 2, reason='a') self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), 'assert_error: AssertionError has reason "\'a\' is bad", not \'a\) self.assertEqual(self._outp[1][:8], 'Line 443') self.clear() self._test.assert_error(func3, True, 2, reason='True is bad') self.assertFalse(self.isquit()) self.clear() self._test.assert_error(func3, 2, True, reason=()) self.assertFalse(self.isquit()) self.clear()<|docstring|>Tests the enforcement assertion<|endoftext|>
35ca173a296083b44fc0769d7855581715779dbf9d302ba5c82b783ed03efbd4
def test07_messages(self): '\n Tests the custom assert messages\n ' message = 'Test1' self._test.assert_equals(1, 2, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test2' self._test.assert_not_equals(1, 1, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test3' self._test.assert_true(False, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test4' self._test.assert_false(True, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test5' self._test.assert_floats_equal(1, 1.001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test6' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test7' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test8' self._test.assert_float_lists_equal([1, 2], [1.001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test9' self._test.assert_float_lists_not_equal([1, 2], [1.000001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) message = 'Test9' self._test.assert_error(1, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test10' self._test.assert_error(func3, 3, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test11' self._test.assert_error(func3, 3, 0, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test12' self._test.assert_error(func3, True, 0, error=TypeError, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test13' self._test.assert_error(func3, True, 0, reason=(), message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test14' self._test.assert_error(func3, True, 0, reason='a', message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear()
Tests the custom assert messages
tests/test_testcase.py
test07_messages
WalkerWhite/introcs-python
1
python
def test07_messages(self): '\n \n ' message = 'Test1' self._test.assert_equals(1, 2, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test2' self._test.assert_not_equals(1, 1, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test3' self._test.assert_true(False, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test4' self._test.assert_false(True, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test5' self._test.assert_floats_equal(1, 1.001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test6' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test7' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test8' self._test.assert_float_lists_equal([1, 2], [1.001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test9' self._test.assert_float_lists_not_equal([1, 2], [1.000001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) message = 'Test9' self._test.assert_error(1, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test10' self._test.assert_error(func3, 3, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test11' self._test.assert_error(func3, 3, 0, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test12' self._test.assert_error(func3, True, 0, error=TypeError, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test13' self._test.assert_error(func3, True, 0, reason=(), message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test14' self._test.assert_error(func3, True, 0, reason='a', message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear()
def test07_messages(self): '\n \n ' message = 'Test1' self._test.assert_equals(1, 2, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test2' self._test.assert_not_equals(1, 1, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test3' self._test.assert_true(False, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test4' self._test.assert_false(True, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test5' self._test.assert_floats_equal(1, 1.001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test6' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test7' self._test.assert_floats_not_equal(1, 1.000001, message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test8' self._test.assert_float_lists_equal([1, 2], [1.001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test9' self._test.assert_float_lists_not_equal([1, 2], [1.000001, 2], message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() def func3(x, y): assert (type(x) == int), (repr(x) + ' is bad') assert (type(y) == int) return (x / y) message = 'Test9' self._test.assert_error(1, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test10' self._test.assert_error(func3, 3, 2, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test11' self._test.assert_error(func3, 3, 0, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test12' self._test.assert_error(func3, True, 0, error=TypeError, message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test13' self._test.assert_error(func3, True, 0, reason=(), message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear() message = 'Test14' self._test.assert_error(func3, True, 0, reason='a', message=message) self.assertTrue(self.isquit()) self.assertEqual(self._outp[0].strip(), message) self.clear()<|docstring|>Tests the custom assert messages<|endoftext|>
f1115d1f905e2359379b20cde9daea6fe2576b8e2bc06b2689990796692b1b12
def test01_checks(self): '\n Tests the type checks.\n ' self.assertTrue(self._test.isint(1.0)) self.assertTrue(self._test.isint(1)) self.assertTrue(self._test.isint('1')) self.assertFalse(self._test.isint('1.0')) self.assertFalse(self._test.isint('1e1')) self.assertFalse(self._test.isint('e1')) self.assertTrue(self._test.isfloat(1.0)) self.assertTrue(self._test.isfloat(1)) self.assertTrue(self._test.isfloat('1.0')) self.assertTrue(self._test.isfloat('1e1')) self.assertFalse(self._test.isfloat('e1')) self.assertTrue(self._test.isbool(True)) self.assertTrue(self._test.isbool(1.0)) self.assertTrue(self._test.isbool(1)) self.assertTrue(self._test.isbool('True')) self.assertTrue(self._test.isbool('False')) self.assertFalse(self._test.isbool('true')) self.assertFalse(self._test.isbool('1')) self.assertFalse(self._test.isbool('1.0')) self.assertFalse(self._test.isbool('1e1')) self.assertFalse(self._test.isbool('e1'))
Tests the type checks.
tests/test_testcase.py
test01_checks
WalkerWhite/introcs-python
1
python
def test01_checks(self): '\n \n ' self.assertTrue(self._test.isint(1.0)) self.assertTrue(self._test.isint(1)) self.assertTrue(self._test.isint('1')) self.assertFalse(self._test.isint('1.0')) self.assertFalse(self._test.isint('1e1')) self.assertFalse(self._test.isint('e1')) self.assertTrue(self._test.isfloat(1.0)) self.assertTrue(self._test.isfloat(1)) self.assertTrue(self._test.isfloat('1.0')) self.assertTrue(self._test.isfloat('1e1')) self.assertFalse(self._test.isfloat('e1')) self.assertTrue(self._test.isbool(True)) self.assertTrue(self._test.isbool(1.0)) self.assertTrue(self._test.isbool(1)) self.assertTrue(self._test.isbool('True')) self.assertTrue(self._test.isbool('False')) self.assertFalse(self._test.isbool('true')) self.assertFalse(self._test.isbool('1')) self.assertFalse(self._test.isbool('1.0')) self.assertFalse(self._test.isbool('1e1')) self.assertFalse(self._test.isbool('e1'))
def test01_checks(self): '\n \n ' self.assertTrue(self._test.isint(1.0)) self.assertTrue(self._test.isint(1)) self.assertTrue(self._test.isint('1')) self.assertFalse(self._test.isint('1.0')) self.assertFalse(self._test.isint('1e1')) self.assertFalse(self._test.isint('e1')) self.assertTrue(self._test.isfloat(1.0)) self.assertTrue(self._test.isfloat(1)) self.assertTrue(self._test.isfloat('1.0')) self.assertTrue(self._test.isfloat('1e1')) self.assertFalse(self._test.isfloat('e1')) self.assertTrue(self._test.isbool(True)) self.assertTrue(self._test.isbool(1.0)) self.assertTrue(self._test.isbool(1)) self.assertTrue(self._test.isbool('True')) self.assertTrue(self._test.isbool('False')) self.assertFalse(self._test.isbool('true')) self.assertFalse(self._test.isbool('1')) self.assertFalse(self._test.isbool('1.0')) self.assertFalse(self._test.isbool('1e1')) self.assertFalse(self._test.isbool('e1'))<|docstring|>Tests the type checks.<|endoftext|>
2f0697e4eca206073ff761e01f4c923859b3f1faa1dea577d27dc1ec60f654d8
def test02_compares(self): '\n Tests the float comparisons.\n ' self.assertTrue(self._test.isclose(1, 1.000001)) self.assertFalse(self._test.isclose(1, 1.001)) self.assertEqual(self._test.isclose((1, 2), (1.000001, 2.001)), [True, False]) self.assertEqual(self._test.isclose((1, 2), (1.001, 2.000001)), [False, True]) self.assertEqual(self._test.isclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), [[True, True], [False, True]]) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.001)), False) self.assertEqual(self._test.allclose((1, 2), (1.001, 2.000001)), False) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.000001)), True) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), False) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (3, 4))), True)
Tests the float comparisons.
tests/test_testcase.py
test02_compares
WalkerWhite/introcs-python
1
python
def test02_compares(self): '\n \n ' self.assertTrue(self._test.isclose(1, 1.000001)) self.assertFalse(self._test.isclose(1, 1.001)) self.assertEqual(self._test.isclose((1, 2), (1.000001, 2.001)), [True, False]) self.assertEqual(self._test.isclose((1, 2), (1.001, 2.000001)), [False, True]) self.assertEqual(self._test.isclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), [[True, True], [False, True]]) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.001)), False) self.assertEqual(self._test.allclose((1, 2), (1.001, 2.000001)), False) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.000001)), True) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), False) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (3, 4))), True)
def test02_compares(self): '\n \n ' self.assertTrue(self._test.isclose(1, 1.000001)) self.assertFalse(self._test.isclose(1, 1.001)) self.assertEqual(self._test.isclose((1, 2), (1.000001, 2.001)), [True, False]) self.assertEqual(self._test.isclose((1, 2), (1.001, 2.000001)), [False, True]) self.assertEqual(self._test.isclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), [[True, True], [False, True]]) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.001)), False) self.assertEqual(self._test.allclose((1, 2), (1.001, 2.000001)), False) self.assertEqual(self._test.allclose((1, 2), (1.000001, 2.000001)), True) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (5, 4))), False) self.assertEqual(self._test.allclose(((1, 2), (3, 4)), ((1, 2.0000001), (3, 4))), True)<|docstring|>Tests the float comparisons.<|endoftext|>
23bea7478276143e0ff01863595a27779cccb9a314c69f37951ccd560196a51b
def step(self, action): ' Run environment for one timestep.\n\n Parameters:\n action(np.ndarray): Numpy array of shape (num_agents,3) containing the\n commands for each car. Each command is of the shape (steer, gas, brake).\n ' if hasattr(self, 'state'): self.prev_state = self.state else: self.prev_state = None if (action is not None): self.reward -= 0.1 cont_action = np.reshape(action, (self.num_agents, (- 1))) for (car_id, car) in enumerate(self.cars): car.steer((- cont_action[car_id][0])) car.gas(cont_action[car_id][1]) car.brake(cont_action[car_id][2]) for car in self.cars: car.step((1.0 / FPS)) self.world.Step((1.0 / FPS), (6 * 30), (2 * 30)) self.t += (1.0 / FPS) self.state = self.render('state_pixels') if (action is not None): for (car_id, car) in enumerate(self.cars): features = self._collect_features(car_id) done = (True in self.all_feats[(:, 48)]) self.track_reward = (copy.copy(self.reward) - copy.copy(self.prev_reward)) self.prev_reward = copy.copy(self.reward) step_reward = self.get_reward(action) observations = (self.all_feats if (self.observation_type == 'features') else self.state) return (observations, step_reward, done, {'total_score': self.reward})
Run environment for one timestep. Parameters: action(np.ndarray): Numpy array of shape (num_agents,3) containing the commands for each car. Each command is of the shape (steer, gas, brake).
gym_multi_car_racing/multi_car_racing.py
step
ParsaVahidi/Deep-Reinforcent-Learning-for-openAI-car-racing-game
0
python
def step(self, action): ' Run environment for one timestep.\n\n Parameters:\n action(np.ndarray): Numpy array of shape (num_agents,3) containing the\n commands for each car. Each command is of the shape (steer, gas, brake).\n ' if hasattr(self, 'state'): self.prev_state = self.state else: self.prev_state = None if (action is not None): self.reward -= 0.1 cont_action = np.reshape(action, (self.num_agents, (- 1))) for (car_id, car) in enumerate(self.cars): car.steer((- cont_action[car_id][0])) car.gas(cont_action[car_id][1]) car.brake(cont_action[car_id][2]) for car in self.cars: car.step((1.0 / FPS)) self.world.Step((1.0 / FPS), (6 * 30), (2 * 30)) self.t += (1.0 / FPS) self.state = self.render('state_pixels') if (action is not None): for (car_id, car) in enumerate(self.cars): features = self._collect_features(car_id) done = (True in self.all_feats[(:, 48)]) self.track_reward = (copy.copy(self.reward) - copy.copy(self.prev_reward)) self.prev_reward = copy.copy(self.reward) step_reward = self.get_reward(action) observations = (self.all_feats if (self.observation_type == 'features') else self.state) return (observations, step_reward, done, {'total_score': self.reward})
def step(self, action): ' Run environment for one timestep.\n\n Parameters:\n action(np.ndarray): Numpy array of shape (num_agents,3) containing the\n commands for each car. Each command is of the shape (steer, gas, brake).\n ' if hasattr(self, 'state'): self.prev_state = self.state else: self.prev_state = None if (action is not None): self.reward -= 0.1 cont_action = np.reshape(action, (self.num_agents, (- 1))) for (car_id, car) in enumerate(self.cars): car.steer((- cont_action[car_id][0])) car.gas(cont_action[car_id][1]) car.brake(cont_action[car_id][2]) for car in self.cars: car.step((1.0 / FPS)) self.world.Step((1.0 / FPS), (6 * 30), (2 * 30)) self.t += (1.0 / FPS) self.state = self.render('state_pixels') if (action is not None): for (car_id, car) in enumerate(self.cars): features = self._collect_features(car_id) done = (True in self.all_feats[(:, 48)]) self.track_reward = (copy.copy(self.reward) - copy.copy(self.prev_reward)) self.prev_reward = copy.copy(self.reward) step_reward = self.get_reward(action) observations = (self.all_feats if (self.observation_type == 'features') else self.state) return (observations, step_reward, done, {'total_score': self.reward})<|docstring|>Run environment for one timestep. Parameters: action(np.ndarray): Numpy array of shape (num_agents,3) containing the commands for each car. Each command is of the shape (steer, gas, brake).<|endoftext|>
37d5c39b6c9d927ffc2c864c48c69fce799efd013da0827465d477ada4010fb4
def get_feat(self, car_id): '\n Given a car ID, this function will return the corresponding\n 32 features as follows:\n pos: position of the car (2x1)\n car_angle: angle of the var (1x1)\n angle_diff: angle diff between next tile and the angle of the car (1x1)\n driving_on_grass: whether we are on grass or track (1x1)\n driving_backward: whether we are going forward or backward (1x1)\n distance_to_tiles: distances to next 10 tiles (10x2)\n distance_to_others: distances to closest 3 cars (3x2)\n ' return self.all_feats[(car_id, 0:self.num_obsv)]
Given a car ID, this function will return the corresponding 32 features as follows: pos: position of the car (2x1) car_angle: angle of the var (1x1) angle_diff: angle diff between next tile and the angle of the car (1x1) driving_on_grass: whether we are on grass or track (1x1) driving_backward: whether we are going forward or backward (1x1) distance_to_tiles: distances to next 10 tiles (10x2) distance_to_others: distances to closest 3 cars (3x2)
gym_multi_car_racing/multi_car_racing.py
get_feat
ParsaVahidi/Deep-Reinforcent-Learning-for-openAI-car-racing-game
0
python
def get_feat(self, car_id): '\n Given a car ID, this function will return the corresponding\n 32 features as follows:\n pos: position of the car (2x1)\n car_angle: angle of the var (1x1)\n angle_diff: angle diff between next tile and the angle of the car (1x1)\n driving_on_grass: whether we are on grass or track (1x1)\n driving_backward: whether we are going forward or backward (1x1)\n distance_to_tiles: distances to next 10 tiles (10x2)\n distance_to_others: distances to closest 3 cars (3x2)\n ' return self.all_feats[(car_id, 0:self.num_obsv)]
def get_feat(self, car_id): '\n Given a car ID, this function will return the corresponding\n 32 features as follows:\n pos: position of the car (2x1)\n car_angle: angle of the var (1x1)\n angle_diff: angle diff between next tile and the angle of the car (1x1)\n driving_on_grass: whether we are on grass or track (1x1)\n driving_backward: whether we are going forward or backward (1x1)\n distance_to_tiles: distances to next 10 tiles (10x2)\n distance_to_others: distances to closest 3 cars (3x2)\n ' return self.all_feats[(car_id, 0:self.num_obsv)]<|docstring|>Given a car ID, this function will return the corresponding 32 features as follows: pos: position of the car (2x1) car_angle: angle of the var (1x1) angle_diff: angle diff between next tile and the angle of the car (1x1) driving_on_grass: whether we are on grass or track (1x1) driving_backward: whether we are going forward or backward (1x1) distance_to_tiles: distances to next 10 tiles (10x2) distance_to_others: distances to closest 3 cars (3x2)<|endoftext|>
468c949f943f0d8e4c44d4d0fc3f967bc1654331d58734bc283368f743d2a558
def _render_window(self, car_id, mode): ' Performs the actual rendering for each car individually.\n\n Parameters:\n car_id(int): Numerical id of car for which the corresponding window\n will be rendered.\n mode(str): Rendering mode.\n ' if (self.viewer[car_id] is None): from gym.envs.classic_control import rendering self.viewer[car_id] = rendering.Viewer(WINDOW_W, WINDOW_H) self.viewer[car_id].window.set_caption(f'Car {car_id}') self.score_label = pyglet.text.Label('0000', font_size=36, x=20, y=((WINDOW_H * 2.5) / 40.0), anchor_x='left', anchor_y='center', color=(255, 255, 255, 255)) self.transform = rendering.Transform() if ('t' not in self.__dict__): return zoom = (((0.1 * SCALE) * max((1 - self.t), 0)) + ((ZOOM * SCALE) * min(self.t, 1))) scroll_x = self.cars[car_id].hull.position[0] scroll_y = self.cars[car_id].hull.position[1] angle = (- self.cars[car_id].hull.angle) vel = self.cars[car_id].hull.linearVelocity if (np.linalg.norm(vel) > 0.5): angle = math.atan2(vel[0], vel[1]) self.transform.set_scale(zoom, zoom) self.transform.set_translation(((WINDOW_W / 2) - (((scroll_x * zoom) * math.cos(angle)) - ((scroll_y * zoom) * math.sin(angle)))), ((WINDOW_H * self.h_ratio) - (((scroll_x * zoom) * math.sin(angle)) + ((scroll_y * zoom) * math.cos(angle))))) self.transform.set_rotation(angle) for (id, car) in enumerate(self.cars): if self.use_ego_color: car.hull.color = (0.0, 0.0, 0.8) if (id == car_id): car.hull.color = (0.8, 0.0, 0.0) car.draw(self.viewer[car_id], (mode != 'state_pixels')) arr = None win = self.viewer[car_id].window win.switch_to() win.dispatch_events() win.clear() t = self.transform if (mode == 'rgb_array'): VP_W = VIDEO_W VP_H = VIDEO_H elif (mode == 'state_pixels'): VP_W = STATE_W VP_H = STATE_H else: pixel_scale = 1 if hasattr(win.context, '_nscontext'): pixel_scale = win.context._nscontext.view().backingScaleFactor() VP_W = int((pixel_scale * WINDOW_W)) VP_H = int((pixel_scale * WINDOW_H)) gl.glViewport(0, 0, VP_W, VP_H) t.enable() self.render_road() for geom in self.viewer[car_id].onetime_geoms: geom.render() self.viewer[car_id].onetime_geoms = [] t.disable() self.render_indicators(car_id, WINDOW_W, WINDOW_H) if (mode == 'human'): win.flip() return self.viewer[car_id].isopen image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data() arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep='') arr = arr.reshape(VP_H, VP_W, 4) arr = arr[(::(- 1), :, 0:3)] return arr
Performs the actual rendering for each car individually. Parameters: car_id(int): Numerical id of car for which the corresponding window will be rendered. mode(str): Rendering mode.
gym_multi_car_racing/multi_car_racing.py
_render_window
ParsaVahidi/Deep-Reinforcent-Learning-for-openAI-car-racing-game
0
python
def _render_window(self, car_id, mode): ' Performs the actual rendering for each car individually.\n\n Parameters:\n car_id(int): Numerical id of car for which the corresponding window\n will be rendered.\n mode(str): Rendering mode.\n ' if (self.viewer[car_id] is None): from gym.envs.classic_control import rendering self.viewer[car_id] = rendering.Viewer(WINDOW_W, WINDOW_H) self.viewer[car_id].window.set_caption(f'Car {car_id}') self.score_label = pyglet.text.Label('0000', font_size=36, x=20, y=((WINDOW_H * 2.5) / 40.0), anchor_x='left', anchor_y='center', color=(255, 255, 255, 255)) self.transform = rendering.Transform() if ('t' not in self.__dict__): return zoom = (((0.1 * SCALE) * max((1 - self.t), 0)) + ((ZOOM * SCALE) * min(self.t, 1))) scroll_x = self.cars[car_id].hull.position[0] scroll_y = self.cars[car_id].hull.position[1] angle = (- self.cars[car_id].hull.angle) vel = self.cars[car_id].hull.linearVelocity if (np.linalg.norm(vel) > 0.5): angle = math.atan2(vel[0], vel[1]) self.transform.set_scale(zoom, zoom) self.transform.set_translation(((WINDOW_W / 2) - (((scroll_x * zoom) * math.cos(angle)) - ((scroll_y * zoom) * math.sin(angle)))), ((WINDOW_H * self.h_ratio) - (((scroll_x * zoom) * math.sin(angle)) + ((scroll_y * zoom) * math.cos(angle))))) self.transform.set_rotation(angle) for (id, car) in enumerate(self.cars): if self.use_ego_color: car.hull.color = (0.0, 0.0, 0.8) if (id == car_id): car.hull.color = (0.8, 0.0, 0.0) car.draw(self.viewer[car_id], (mode != 'state_pixels')) arr = None win = self.viewer[car_id].window win.switch_to() win.dispatch_events() win.clear() t = self.transform if (mode == 'rgb_array'): VP_W = VIDEO_W VP_H = VIDEO_H elif (mode == 'state_pixels'): VP_W = STATE_W VP_H = STATE_H else: pixel_scale = 1 if hasattr(win.context, '_nscontext'): pixel_scale = win.context._nscontext.view().backingScaleFactor() VP_W = int((pixel_scale * WINDOW_W)) VP_H = int((pixel_scale * WINDOW_H)) gl.glViewport(0, 0, VP_W, VP_H) t.enable() self.render_road() for geom in self.viewer[car_id].onetime_geoms: geom.render() self.viewer[car_id].onetime_geoms = [] t.disable() self.render_indicators(car_id, WINDOW_W, WINDOW_H) if (mode == 'human'): win.flip() return self.viewer[car_id].isopen image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data() arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep=) arr = arr.reshape(VP_H, VP_W, 4) arr = arr[(::(- 1), :, 0:3)] return arr
def _render_window(self, car_id, mode): ' Performs the actual rendering for each car individually.\n\n Parameters:\n car_id(int): Numerical id of car for which the corresponding window\n will be rendered.\n mode(str): Rendering mode.\n ' if (self.viewer[car_id] is None): from gym.envs.classic_control import rendering self.viewer[car_id] = rendering.Viewer(WINDOW_W, WINDOW_H) self.viewer[car_id].window.set_caption(f'Car {car_id}') self.score_label = pyglet.text.Label('0000', font_size=36, x=20, y=((WINDOW_H * 2.5) / 40.0), anchor_x='left', anchor_y='center', color=(255, 255, 255, 255)) self.transform = rendering.Transform() if ('t' not in self.__dict__): return zoom = (((0.1 * SCALE) * max((1 - self.t), 0)) + ((ZOOM * SCALE) * min(self.t, 1))) scroll_x = self.cars[car_id].hull.position[0] scroll_y = self.cars[car_id].hull.position[1] angle = (- self.cars[car_id].hull.angle) vel = self.cars[car_id].hull.linearVelocity if (np.linalg.norm(vel) > 0.5): angle = math.atan2(vel[0], vel[1]) self.transform.set_scale(zoom, zoom) self.transform.set_translation(((WINDOW_W / 2) - (((scroll_x * zoom) * math.cos(angle)) - ((scroll_y * zoom) * math.sin(angle)))), ((WINDOW_H * self.h_ratio) - (((scroll_x * zoom) * math.sin(angle)) + ((scroll_y * zoom) * math.cos(angle))))) self.transform.set_rotation(angle) for (id, car) in enumerate(self.cars): if self.use_ego_color: car.hull.color = (0.0, 0.0, 0.8) if (id == car_id): car.hull.color = (0.8, 0.0, 0.0) car.draw(self.viewer[car_id], (mode != 'state_pixels')) arr = None win = self.viewer[car_id].window win.switch_to() win.dispatch_events() win.clear() t = self.transform if (mode == 'rgb_array'): VP_W = VIDEO_W VP_H = VIDEO_H elif (mode == 'state_pixels'): VP_W = STATE_W VP_H = STATE_H else: pixel_scale = 1 if hasattr(win.context, '_nscontext'): pixel_scale = win.context._nscontext.view().backingScaleFactor() VP_W = int((pixel_scale * WINDOW_W)) VP_H = int((pixel_scale * WINDOW_H)) gl.glViewport(0, 0, VP_W, VP_H) t.enable() self.render_road() for geom in self.viewer[car_id].onetime_geoms: geom.render() self.viewer[car_id].onetime_geoms = [] t.disable() self.render_indicators(car_id, WINDOW_W, WINDOW_H) if (mode == 'human'): win.flip() return self.viewer[car_id].isopen image_data = pyglet.image.get_buffer_manager().get_color_buffer().get_image_data() arr = np.fromstring(image_data.get_data(), dtype=np.uint8, sep=) arr = arr.reshape(VP_H, VP_W, 4) arr = arr[(::(- 1), :, 0:3)] return arr<|docstring|>Performs the actual rendering for each car individually. Parameters: car_id(int): Numerical id of car for which the corresponding window will be rendered. mode(str): Rendering mode.<|endoftext|>
a975f629de68616d327bfe9bd585fabb2b38ee1ce4d96cb3aa3b27fddbb9af75
def __init__(self, csv_filename: str, country_curr_codes, euro_rates, input_dir=_default_input_dir): '\n Create instance of AirportAtlas comprising dictionary of Airport objects.\n \n Default is empty dictionary.\n Dictionary values must be Airport objects.\n Set csv_filename parameter to construct dictionary from the csv\n ' self.load_data(csv_filename, input_dir) self._country_curr_codes = country_curr_codes self._euro_rates = euro_rates
Create instance of AirportAtlas comprising dictionary of Airport objects. Default is empty dictionary. Dictionary values must be Airport objects. Set csv_filename parameter to construct dictionary from the csv
flight_plan/airports.py
__init__
crotty-d/flight-plan
0
python
def __init__(self, csv_filename: str, country_curr_codes, euro_rates, input_dir=_default_input_dir): '\n Create instance of AirportAtlas comprising dictionary of Airport objects.\n \n Default is empty dictionary.\n Dictionary values must be Airport objects.\n Set csv_filename parameter to construct dictionary from the csv\n ' self.load_data(csv_filename, input_dir) self._country_curr_codes = country_curr_codes self._euro_rates = euro_rates
def __init__(self, csv_filename: str, country_curr_codes, euro_rates, input_dir=_default_input_dir): '\n Create instance of AirportAtlas comprising dictionary of Airport objects.\n \n Default is empty dictionary.\n Dictionary values must be Airport objects.\n Set csv_filename parameter to construct dictionary from the csv\n ' self.load_data(csv_filename, input_dir) self._country_curr_codes = country_curr_codes self._euro_rates = euro_rates<|docstring|>Create instance of AirportAtlas comprising dictionary of Airport objects. Default is empty dictionary. Dictionary values must be Airport objects. Set csv_filename parameter to construct dictionary from the csv<|endoftext|>
9f1fb838b142ed933f1e7fd1c2c6eb2628be652ecac1316312d035c528513c7b
def load_data(self, csv_filename: str, input_dir): 'Load data from CSV file' try: with open(os.path.join(input_dir, csv_filename), 'rt', encoding='utf8') as f: reader = csv.reader(f) for line in reader: self._airports_dict[line[4]] = Airport(line[4], line[2], line[3], line[6], line[7]) except IOError as e: print(e)
Load data from CSV file
flight_plan/airports.py
load_data
crotty-d/flight-plan
0
python
def load_data(self, csv_filename: str, input_dir): try: with open(os.path.join(input_dir, csv_filename), 'rt', encoding='utf8') as f: reader = csv.reader(f) for line in reader: self._airports_dict[line[4]] = Airport(line[4], line[2], line[3], line[6], line[7]) except IOError as e: print(e)
def load_data(self, csv_filename: str, input_dir): try: with open(os.path.join(input_dir, csv_filename), 'rt', encoding='utf8') as f: reader = csv.reader(f) for line in reader: self._airports_dict[line[4]] = Airport(line[4], line[2], line[3], line[6], line[7]) except IOError as e: print(e)<|docstring|>Load data from CSV file<|endoftext|>
97d6df669a79679bebbf382e11c7a4991323e35226eb1cef18bd6f7b4fcc0208
def get_dict(self): 'Return dictionary of Airport objects for all airports in atlas' return self._airports_dict
Return dictionary of Airport objects for all airports in atlas
flight_plan/airports.py
get_dict
crotty-d/flight-plan
0
python
def get_dict(self): return self._airports_dict
def get_dict(self): return self._airports_dict<|docstring|>Return dictionary of Airport objects for all airports in atlas<|endoftext|>
f54c1c6831b2e18e15fdecd7a2ed2fc2f41ce73c291d22f5d944fff71bdc913e
def get_airport(self, airport_code: str): 'Return Airport instance specified in airport code parameter' return self._airports_dict[airport_code]
Return Airport instance specified in airport code parameter
flight_plan/airports.py
get_airport
crotty-d/flight-plan
0
python
def get_airport(self, airport_code: str): return self._airports_dict[airport_code]
def get_airport(self, airport_code: str): return self._airports_dict[airport_code]<|docstring|>Return Airport instance specified in airport code parameter<|endoftext|>
53ac21f038c1c81be0907ab178188db094403c81e697ebb06adb70bf74d82a08
def great_circle_distance(self, latitude1, longitude1, latitude2, longitude2): '\n Return the distance between two sets of geographical coordinates as a float.\n \n All parameters are floats.\n ' R_EARTH = 6371 theta1 = ((longitude1 * (2 * pi)) / 360) theta2 = ((longitude2 * (2 * pi)) / 360) phi1 = (((90 - latitude1) * (2 * pi)) / 360) phi2 = (((90 - latitude2) * (2 * pi)) / 360) distance = (acos((((sin(phi1) * sin(phi2)) * cos((theta1 - theta2))) + (cos(phi1) * cos(phi2)))) * R_EARTH) return distance
Return the distance between two sets of geographical coordinates as a float. All parameters are floats.
flight_plan/airports.py
great_circle_distance
crotty-d/flight-plan
0
python
def great_circle_distance(self, latitude1, longitude1, latitude2, longitude2): '\n Return the distance between two sets of geographical coordinates as a float.\n \n All parameters are floats.\n ' R_EARTH = 6371 theta1 = ((longitude1 * (2 * pi)) / 360) theta2 = ((longitude2 * (2 * pi)) / 360) phi1 = (((90 - latitude1) * (2 * pi)) / 360) phi2 = (((90 - latitude2) * (2 * pi)) / 360) distance = (acos((((sin(phi1) * sin(phi2)) * cos((theta1 - theta2))) + (cos(phi1) * cos(phi2)))) * R_EARTH) return distance
def great_circle_distance(self, latitude1, longitude1, latitude2, longitude2): '\n Return the distance between two sets of geographical coordinates as a float.\n \n All parameters are floats.\n ' R_EARTH = 6371 theta1 = ((longitude1 * (2 * pi)) / 360) theta2 = ((longitude2 * (2 * pi)) / 360) phi1 = (((90 - latitude1) * (2 * pi)) / 360) phi2 = (((90 - latitude2) * (2 * pi)) / 360) distance = (acos((((sin(phi1) * sin(phi2)) * cos((theta1 - theta2))) + (cos(phi1) * cos(phi2)))) * R_EARTH) return distance<|docstring|>Return the distance between two sets of geographical coordinates as a float. All parameters are floats.<|endoftext|>
e2b96dbff30ef1a2effdd0b2008c598743b2f43244c62bb86582dbcc69bc6ece
def distance_between_airports(self, airport_code1, airport_code2): '\n Return the distance between two airports as a float.\n ' airport1 = self._airports_dict[airport_code1] airport2 = self._airports_dict[airport_code2] coordinates = (airport1.get_latitude(), airport1.get_longitude(), airport2.get_latitude(), airport2.get_longitude()) distance = self.great_circle_distance(*coordinates) return distance
Return the distance between two airports as a float.
flight_plan/airports.py
distance_between_airports
crotty-d/flight-plan
0
python
def distance_between_airports(self, airport_code1, airport_code2): '\n \n ' airport1 = self._airports_dict[airport_code1] airport2 = self._airports_dict[airport_code2] coordinates = (airport1.get_latitude(), airport1.get_longitude(), airport2.get_latitude(), airport2.get_longitude()) distance = self.great_circle_distance(*coordinates) return distance
def distance_between_airports(self, airport_code1, airport_code2): '\n \n ' airport1 = self._airports_dict[airport_code1] airport2 = self._airports_dict[airport_code2] coordinates = (airport1.get_latitude(), airport1.get_longitude(), airport2.get_latitude(), airport2.get_longitude()) distance = self.great_circle_distance(*coordinates) return distance<|docstring|>Return the distance between two airports as a float.<|endoftext|>
7e9ece490f277f1cad9fa00b812a9f713befb7e2a71ca903243aa76a38998657
def airport_euro_rate(self, airport_code): '\n Return the euro exchange rate at the given airport\n ' airport = self._airports_dict[airport_code] country = airport.get_country() currency_code = self._country_curr_codes.get_code(country) exch_rate = self._euro_rates.get_rate(currency_code) return exch_rate
Return the euro exchange rate at the given airport
flight_plan/airports.py
airport_euro_rate
crotty-d/flight-plan
0
python
def airport_euro_rate(self, airport_code): '\n \n ' airport = self._airports_dict[airport_code] country = airport.get_country() currency_code = self._country_curr_codes.get_code(country) exch_rate = self._euro_rates.get_rate(currency_code) return exch_rate
def airport_euro_rate(self, airport_code): '\n \n ' airport = self._airports_dict[airport_code] country = airport.get_country() currency_code = self._country_curr_codes.get_code(country) exch_rate = self._euro_rates.get_rate(currency_code) return exch_rate<|docstring|>Return the euro exchange rate at the given airport<|endoftext|>
e36690b2b91330ad0ad7dc871705667180bc711592f6f720793ecb84cc07074c
def cost_between_airports(self, distance, exch_rate): '\n Return the distance between two airports as a float.\n ' return (distance * exch_rate)
Return the distance between two airports as a float.
flight_plan/airports.py
cost_between_airports
crotty-d/flight-plan
0
python
def cost_between_airports(self, distance, exch_rate): '\n \n ' return (distance * exch_rate)
def cost_between_airports(self, distance, exch_rate): '\n \n ' return (distance * exch_rate)<|docstring|>Return the distance between two airports as a float.<|endoftext|>
ebada3e7d3587a558178477b625d8f8a4dd09e664d159ccb09b42aebef1c8b13
def _rescale(val: Sequence[float], low: float, high: float) -> List[float]: '\n Rescales a list of confidence value between 0 and 1 to an interval [low,\n high].\n\n Args:\n val (float): List of values in interval (0,1)\n low (float): Lower bound of rescaling interval\n high (float): Upper bound of rescaling interval\n\n Returns:\n Rescaled value (float).\n ' return [(((high - low) * x) + low) for x in val]
Rescales a list of confidence value between 0 and 1 to an interval [low, high]. Args: val (float): List of values in interval (0,1) low (float): Lower bound of rescaling interval high (float): Upper bound of rescaling interval Returns: Rescaled value (float).
kraken/serialization.py
_rescale
tbaptista/kraken
1
python
def _rescale(val: Sequence[float], low: float, high: float) -> List[float]: '\n Rescales a list of confidence value between 0 and 1 to an interval [low,\n high].\n\n Args:\n val (float): List of values in interval (0,1)\n low (float): Lower bound of rescaling interval\n high (float): Upper bound of rescaling interval\n\n Returns:\n Rescaled value (float).\n ' return [(((high - low) * x) + low) for x in val]
def _rescale(val: Sequence[float], low: float, high: float) -> List[float]: '\n Rescales a list of confidence value between 0 and 1 to an interval [low,\n high].\n\n Args:\n val (float): List of values in interval (0,1)\n low (float): Lower bound of rescaling interval\n high (float): Upper bound of rescaling interval\n\n Returns:\n Rescaled value (float).\n ' return [(((high - low) * x) + low) for x in val]<|docstring|>Rescales a list of confidence value between 0 and 1 to an interval [low, high]. Args: val (float): List of values in interval (0,1) low (float): Lower bound of rescaling interval high (float): Upper bound of rescaling interval Returns: Rescaled value (float).<|endoftext|>
28241b0af64e9858265e332be3821bac73ef931a93d992291a62362f0887a8b1
def max_bbox(boxes: Iterable[Tuple[(int, int, int, int)]]) -> Tuple[(int, int, int, int)]: '\n Calculates the minimal bounding box containing all boxes contained in an\n iterator.\n\n Args:\n boxes (iterator): An iterator returning tuples of the format (x0, y0,\n x1, y1)\n Returns:\n A box covering all bounding boxes in the input argument\n ' sbox = list(map(sorted, list(zip(*boxes)))) return (sbox[0][0], sbox[1][0], sbox[2][(- 1)], sbox[3][(- 1)])
Calculates the minimal bounding box containing all boxes contained in an iterator. Args: boxes (iterator): An iterator returning tuples of the format (x0, y0, x1, y1) Returns: A box covering all bounding boxes in the input argument
kraken/serialization.py
max_bbox
tbaptista/kraken
1
python
def max_bbox(boxes: Iterable[Tuple[(int, int, int, int)]]) -> Tuple[(int, int, int, int)]: '\n Calculates the minimal bounding box containing all boxes contained in an\n iterator.\n\n Args:\n boxes (iterator): An iterator returning tuples of the format (x0, y0,\n x1, y1)\n Returns:\n A box covering all bounding boxes in the input argument\n ' sbox = list(map(sorted, list(zip(*boxes)))) return (sbox[0][0], sbox[1][0], sbox[2][(- 1)], sbox[3][(- 1)])
def max_bbox(boxes: Iterable[Tuple[(int, int, int, int)]]) -> Tuple[(int, int, int, int)]: '\n Calculates the minimal bounding box containing all boxes contained in an\n iterator.\n\n Args:\n boxes (iterator): An iterator returning tuples of the format (x0, y0,\n x1, y1)\n Returns:\n A box covering all bounding boxes in the input argument\n ' sbox = list(map(sorted, list(zip(*boxes)))) return (sbox[0][0], sbox[1][0], sbox[2][(- 1)], sbox[3][(- 1)])<|docstring|>Calculates the minimal bounding box containing all boxes contained in an iterator. Args: boxes (iterator): An iterator returning tuples of the format (x0, y0, x1, y1) Returns: A box covering all bounding boxes in the input argument<|endoftext|>
36715a80951c5a16fdfd11b1ae3642ce06723d914054ecd0bcc1f646d936ca92
def serialize(records: Sequence[ocr_record], image_name: str=None, image_size: Tuple[(int, int)]=(0, 0), writing_mode: str='horizontal-tb', scripts: Optional[Iterable[str]]=None, template: str='hocr') -> str: "\n Serializes a list of ocr_records into an output document.\n\n Serializes a list of predictions and their corresponding positions by doing\n some hOCR-specific preprocessing and then renders them through one of\n several jinja2 templates.\n\n Note: Empty records are ignored for serialization purposes.\n\n Args:\n records (iterable): List of kraken.rpred.ocr_record\n image_name (str): Name of the source image\n image_size (tuple): Dimensions of the source image\n writing_mode (str): Sets the principal layout of lines and the\n direction in which blocks progress. Valid values\n are horizontal-tb, vertical-rl, and\n vertical-lr.\n scripts (list): List of scripts contained in the OCR records\n template (str): Selector for the serialization format. May be\n 'hocr' or 'alto'.\n\n Returns:\n (str) rendered template.\n " logger.info('Serialize {} records from {} with template {}.'.format(len(records), image_name, template)) page = {'lines': [], 'size': image_size, 'name': image_name, 'writing_mode': writing_mode, 'scripts': scripts} seg_idx = 0 char_idx = 0 for (idx, record) in enumerate(records): if (not record.prediction): logger.debug('Empty record. Skipping') continue line = {'index': idx, 'bbox': max_bbox(record.cuts), 'cuts': record.cuts, 'confidences': record.confidences, 'recognition': []} splits = regex.split('(\\s+)', record.prediction) line_offset = 0 logger.debug('Record contains {} segments'.format(len(splits))) for segment in splits: if (len(segment) == 0): continue seg_bbox = max_bbox(record.cuts[line_offset:(line_offset + len(segment))]) line['recognition'].extend([{'bbox': seg_bbox, 'confidences': record.confidences[line_offset:(line_offset + len(segment))], 'cuts': record.cuts[line_offset:(line_offset + len(segment))], 'text': segment, 'recognition': [{'bbox': cut, 'confidence': conf, 'text': char, 'index': cid} for (conf, cut, char, cid) in zip(record.confidences[line_offset:(line_offset + len(segment))], record.cuts[line_offset:(line_offset + len(segment))], segment, range(char_idx, (char_idx + len(segment))))], 'index': seg_idx}]) char_idx += len(segment) seg_idx += 1 line_offset += len(segment) page['lines'].append(line) logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) env.tests['whitespace'] = str.isspace env.filters['rescale'] = _rescale logger.debug('Retrieving template.') tmpl = env.get_template(template) logger.debug('Rendering data.') return tmpl.render(page=page)
Serializes a list of ocr_records into an output document. Serializes a list of predictions and their corresponding positions by doing some hOCR-specific preprocessing and then renders them through one of several jinja2 templates. Note: Empty records are ignored for serialization purposes. Args: records (iterable): List of kraken.rpred.ocr_record image_name (str): Name of the source image image_size (tuple): Dimensions of the source image writing_mode (str): Sets the principal layout of lines and the direction in which blocks progress. Valid values are horizontal-tb, vertical-rl, and vertical-lr. scripts (list): List of scripts contained in the OCR records template (str): Selector for the serialization format. May be 'hocr' or 'alto'. Returns: (str) rendered template.
kraken/serialization.py
serialize
tbaptista/kraken
1
python
def serialize(records: Sequence[ocr_record], image_name: str=None, image_size: Tuple[(int, int)]=(0, 0), writing_mode: str='horizontal-tb', scripts: Optional[Iterable[str]]=None, template: str='hocr') -> str: "\n Serializes a list of ocr_records into an output document.\n\n Serializes a list of predictions and their corresponding positions by doing\n some hOCR-specific preprocessing and then renders them through one of\n several jinja2 templates.\n\n Note: Empty records are ignored for serialization purposes.\n\n Args:\n records (iterable): List of kraken.rpred.ocr_record\n image_name (str): Name of the source image\n image_size (tuple): Dimensions of the source image\n writing_mode (str): Sets the principal layout of lines and the\n direction in which blocks progress. Valid values\n are horizontal-tb, vertical-rl, and\n vertical-lr.\n scripts (list): List of scripts contained in the OCR records\n template (str): Selector for the serialization format. May be\n 'hocr' or 'alto'.\n\n Returns:\n (str) rendered template.\n " logger.info('Serialize {} records from {} with template {}.'.format(len(records), image_name, template)) page = {'lines': [], 'size': image_size, 'name': image_name, 'writing_mode': writing_mode, 'scripts': scripts} seg_idx = 0 char_idx = 0 for (idx, record) in enumerate(records): if (not record.prediction): logger.debug('Empty record. Skipping') continue line = {'index': idx, 'bbox': max_bbox(record.cuts), 'cuts': record.cuts, 'confidences': record.confidences, 'recognition': []} splits = regex.split('(\\s+)', record.prediction) line_offset = 0 logger.debug('Record contains {} segments'.format(len(splits))) for segment in splits: if (len(segment) == 0): continue seg_bbox = max_bbox(record.cuts[line_offset:(line_offset + len(segment))]) line['recognition'].extend([{'bbox': seg_bbox, 'confidences': record.confidences[line_offset:(line_offset + len(segment))], 'cuts': record.cuts[line_offset:(line_offset + len(segment))], 'text': segment, 'recognition': [{'bbox': cut, 'confidence': conf, 'text': char, 'index': cid} for (conf, cut, char, cid) in zip(record.confidences[line_offset:(line_offset + len(segment))], record.cuts[line_offset:(line_offset + len(segment))], segment, range(char_idx, (char_idx + len(segment))))], 'index': seg_idx}]) char_idx += len(segment) seg_idx += 1 line_offset += len(segment) page['lines'].append(line) logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) env.tests['whitespace'] = str.isspace env.filters['rescale'] = _rescale logger.debug('Retrieving template.') tmpl = env.get_template(template) logger.debug('Rendering data.') return tmpl.render(page=page)
def serialize(records: Sequence[ocr_record], image_name: str=None, image_size: Tuple[(int, int)]=(0, 0), writing_mode: str='horizontal-tb', scripts: Optional[Iterable[str]]=None, template: str='hocr') -> str: "\n Serializes a list of ocr_records into an output document.\n\n Serializes a list of predictions and their corresponding positions by doing\n some hOCR-specific preprocessing and then renders them through one of\n several jinja2 templates.\n\n Note: Empty records are ignored for serialization purposes.\n\n Args:\n records (iterable): List of kraken.rpred.ocr_record\n image_name (str): Name of the source image\n image_size (tuple): Dimensions of the source image\n writing_mode (str): Sets the principal layout of lines and the\n direction in which blocks progress. Valid values\n are horizontal-tb, vertical-rl, and\n vertical-lr.\n scripts (list): List of scripts contained in the OCR records\n template (str): Selector for the serialization format. May be\n 'hocr' or 'alto'.\n\n Returns:\n (str) rendered template.\n " logger.info('Serialize {} records from {} with template {}.'.format(len(records), image_name, template)) page = {'lines': [], 'size': image_size, 'name': image_name, 'writing_mode': writing_mode, 'scripts': scripts} seg_idx = 0 char_idx = 0 for (idx, record) in enumerate(records): if (not record.prediction): logger.debug('Empty record. Skipping') continue line = {'index': idx, 'bbox': max_bbox(record.cuts), 'cuts': record.cuts, 'confidences': record.confidences, 'recognition': []} splits = regex.split('(\\s+)', record.prediction) line_offset = 0 logger.debug('Record contains {} segments'.format(len(splits))) for segment in splits: if (len(segment) == 0): continue seg_bbox = max_bbox(record.cuts[line_offset:(line_offset + len(segment))]) line['recognition'].extend([{'bbox': seg_bbox, 'confidences': record.confidences[line_offset:(line_offset + len(segment))], 'cuts': record.cuts[line_offset:(line_offset + len(segment))], 'text': segment, 'recognition': [{'bbox': cut, 'confidence': conf, 'text': char, 'index': cid} for (conf, cut, char, cid) in zip(record.confidences[line_offset:(line_offset + len(segment))], record.cuts[line_offset:(line_offset + len(segment))], segment, range(char_idx, (char_idx + len(segment))))], 'index': seg_idx}]) char_idx += len(segment) seg_idx += 1 line_offset += len(segment) page['lines'].append(line) logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) env.tests['whitespace'] = str.isspace env.filters['rescale'] = _rescale logger.debug('Retrieving template.') tmpl = env.get_template(template) logger.debug('Rendering data.') return tmpl.render(page=page)<|docstring|>Serializes a list of ocr_records into an output document. Serializes a list of predictions and their corresponding positions by doing some hOCR-specific preprocessing and then renders them through one of several jinja2 templates. Note: Empty records are ignored for serialization purposes. Args: records (iterable): List of kraken.rpred.ocr_record image_name (str): Name of the source image image_size (tuple): Dimensions of the source image writing_mode (str): Sets the principal layout of lines and the direction in which blocks progress. Valid values are horizontal-tb, vertical-rl, and vertical-lr. scripts (list): List of scripts contained in the OCR records template (str): Selector for the serialization format. May be 'hocr' or 'alto'. Returns: (str) rendered template.<|endoftext|>
5ac9d149738567e08e1244a634ffead320cca8e585f20c1aa2be64382b8e34cf
def render_report(model: str, chars: int, errors: int, char_confusions: Counter, scripts: Counter, insertions: Counter, deletions: int, substitutions: Counter) -> str: '\n Renders an accuracy report.\n\n Args:\n model (str): Model name.\n errors (int): Number of errors on test set.\n char_confusions (dict): Dictionary mapping a tuple (gt, pred) to a\n number of occurrences.\n scripts (dict): Dictionary counting character per script.\n insertions (dict): Dictionary counting insertion operations per Unicode\n script\n deletions (int): Number of deletions\n substitutions (dict): Dictionary counting substitution operations per\n Unicode script.\n\n Returns:\n A string containing the rendered report.\n ' logger.info('Serializing report for {}'.format(model)) report = {'model': model, 'chars': chars, 'errors': errors, 'accuracy': (((chars - errors) / chars) * 100), 'insertions': sum(insertions.values()), 'deletions': deletions, 'substitutions': sum(substitutions.values()), 'scripts': sorted([{'script': k, 'count': v, 'errors': (insertions[k] + substitutions[k]), 'accuracy': ((100 * (v - (insertions[k] + substitutions[k]))) / v)} for (k, v) in scripts.items()], key=(lambda x: x['accuracy']), reverse=True), 'counts': sorted([{'correct': make_printable(k[0]), 'generated': make_printable(k[1]), 'errors': v} for (k, v) in char_confusions.items() if (k[0] != k[1])], key=(lambda x: x['errors']), reverse=True)} logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) logger.debug('Retrieving template.') tmpl = env.get_template('report') logger.debug('Rendering data.') return tmpl.render(report=report)
Renders an accuracy report. Args: model (str): Model name. errors (int): Number of errors on test set. char_confusions (dict): Dictionary mapping a tuple (gt, pred) to a number of occurrences. scripts (dict): Dictionary counting character per script. insertions (dict): Dictionary counting insertion operations per Unicode script deletions (int): Number of deletions substitutions (dict): Dictionary counting substitution operations per Unicode script. Returns: A string containing the rendered report.
kraken/serialization.py
render_report
tbaptista/kraken
1
python
def render_report(model: str, chars: int, errors: int, char_confusions: Counter, scripts: Counter, insertions: Counter, deletions: int, substitutions: Counter) -> str: '\n Renders an accuracy report.\n\n Args:\n model (str): Model name.\n errors (int): Number of errors on test set.\n char_confusions (dict): Dictionary mapping a tuple (gt, pred) to a\n number of occurrences.\n scripts (dict): Dictionary counting character per script.\n insertions (dict): Dictionary counting insertion operations per Unicode\n script\n deletions (int): Number of deletions\n substitutions (dict): Dictionary counting substitution operations per\n Unicode script.\n\n Returns:\n A string containing the rendered report.\n ' logger.info('Serializing report for {}'.format(model)) report = {'model': model, 'chars': chars, 'errors': errors, 'accuracy': (((chars - errors) / chars) * 100), 'insertions': sum(insertions.values()), 'deletions': deletions, 'substitutions': sum(substitutions.values()), 'scripts': sorted([{'script': k, 'count': v, 'errors': (insertions[k] + substitutions[k]), 'accuracy': ((100 * (v - (insertions[k] + substitutions[k]))) / v)} for (k, v) in scripts.items()], key=(lambda x: x['accuracy']), reverse=True), 'counts': sorted([{'correct': make_printable(k[0]), 'generated': make_printable(k[1]), 'errors': v} for (k, v) in char_confusions.items() if (k[0] != k[1])], key=(lambda x: x['errors']), reverse=True)} logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) logger.debug('Retrieving template.') tmpl = env.get_template('report') logger.debug('Rendering data.') return tmpl.render(report=report)
def render_report(model: str, chars: int, errors: int, char_confusions: Counter, scripts: Counter, insertions: Counter, deletions: int, substitutions: Counter) -> str: '\n Renders an accuracy report.\n\n Args:\n model (str): Model name.\n errors (int): Number of errors on test set.\n char_confusions (dict): Dictionary mapping a tuple (gt, pred) to a\n number of occurrences.\n scripts (dict): Dictionary counting character per script.\n insertions (dict): Dictionary counting insertion operations per Unicode\n script\n deletions (int): Number of deletions\n substitutions (dict): Dictionary counting substitution operations per\n Unicode script.\n\n Returns:\n A string containing the rendered report.\n ' logger.info('Serializing report for {}'.format(model)) report = {'model': model, 'chars': chars, 'errors': errors, 'accuracy': (((chars - errors) / chars) * 100), 'insertions': sum(insertions.values()), 'deletions': deletions, 'substitutions': sum(substitutions.values()), 'scripts': sorted([{'script': k, 'count': v, 'errors': (insertions[k] + substitutions[k]), 'accuracy': ((100 * (v - (insertions[k] + substitutions[k]))) / v)} for (k, v) in scripts.items()], key=(lambda x: x['accuracy']), reverse=True), 'counts': sorted([{'correct': make_printable(k[0]), 'generated': make_printable(k[1]), 'errors': v} for (k, v) in char_confusions.items() if (k[0] != k[1])], key=(lambda x: x['errors']), reverse=True)} logger.debug('Initializing jinja environment.') env = Environment(loader=PackageLoader('kraken', 'templates'), trim_blocks=True, lstrip_blocks=True, autoescape=True) logger.debug('Retrieving template.') tmpl = env.get_template('report') logger.debug('Rendering data.') return tmpl.render(report=report)<|docstring|>Renders an accuracy report. Args: model (str): Model name. errors (int): Number of errors on test set. char_confusions (dict): Dictionary mapping a tuple (gt, pred) to a number of occurrences. scripts (dict): Dictionary counting character per script. insertions (dict): Dictionary counting insertion operations per Unicode script deletions (int): Number of deletions substitutions (dict): Dictionary counting substitution operations per Unicode script. Returns: A string containing the rendered report.<|endoftext|>
b7248e8a2d02f93c9e1525f9d6202c248239addc6fffb26a80d0beb5c2f6ccfd
@property def sid(self): 'An alphanumeric string identifying this resource.\n :rtype: str\n ' return self._sid
An alphanumeric string identifying this resource. :rtype: str
zang/domain/bna_lookup.py
sid
engasm89/zangasm
1
python
@property def sid(self): 'An alphanumeric string identifying this resource.\n :rtype: str\n ' return self._sid
@property def sid(self): 'An alphanumeric string identifying this resource.\n :rtype: str\n ' return self._sid<|docstring|>An alphanumeric string identifying this resource. :rtype: str<|endoftext|>
8d7d6961e9c3fbe18c3f2f7ba056721ba9b3bba0d933d1e414939a91b4cdd485
@property def accountSid(self): 'An alphanumeric string identifying the account this lookup\n occurred through.\n :rtype: str\n ' return self._account_sid
An alphanumeric string identifying the account this lookup occurred through. :rtype: str
zang/domain/bna_lookup.py
accountSid
engasm89/zangasm
1
python
@property def accountSid(self): 'An alphanumeric string identifying the account this lookup\n occurred through.\n :rtype: str\n ' return self._account_sid
@property def accountSid(self): 'An alphanumeric string identifying the account this lookup\n occurred through.\n :rtype: str\n ' return self._account_sid<|docstring|>An alphanumeric string identifying the account this lookup occurred through. :rtype: str<|endoftext|>
0aeade4b58d802f0d9360c21c95bc6ffb4093aebd015885fe2a118bc008fb120
@property def dateCreated(self): 'The date the lookup resource was created.\n :rtype: date\n ' return self._date_created
The date the lookup resource was created. :rtype: date
zang/domain/bna_lookup.py
dateCreated
engasm89/zangasm
1
python
@property def dateCreated(self): 'The date the lookup resource was created.\n :rtype: date\n ' return self._date_created
@property def dateCreated(self): 'The date the lookup resource was created.\n :rtype: date\n ' return self._date_created<|docstring|>The date the lookup resource was created. :rtype: date<|endoftext|>
440bc1920e6c32fed8f1289951555055d28dffbf7575881e40ca89df4ee4e0e3
@property def dateUpdated(self): 'The date the lookup resource was last updated.\n :rtype: date\n ' return self._date_updated
The date the lookup resource was last updated. :rtype: date
zang/domain/bna_lookup.py
dateUpdated
engasm89/zangasm
1
python
@property def dateUpdated(self): 'The date the lookup resource was last updated.\n :rtype: date\n ' return self._date_updated
@property def dateUpdated(self): 'The date the lookup resource was last updated.\n :rtype: date\n ' return self._date_updated<|docstring|>The date the lookup resource was last updated. :rtype: date<|endoftext|>
37733449c5ee20ab1b994ac2303353039b0e627db1336b95c642744aac1176a5
@property def phoneNumber(self): 'The phone number the lookup was performed on.\n :rtype: str\n ' return self._phone_number
The phone number the lookup was performed on. :rtype: str
zang/domain/bna_lookup.py
phoneNumber
engasm89/zangasm
1
python
@property def phoneNumber(self): 'The phone number the lookup was performed on.\n :rtype: str\n ' return self._phone_number
@property def phoneNumber(self): 'The phone number the lookup was performed on.\n :rtype: str\n ' return self._phone_number<|docstring|>The phone number the lookup was performed on. :rtype: str<|endoftext|>
5d23371e4c50152baa5a1f29bf0da56b7133e8cfc337bc03adf7d4aa9f4ef86c
@property def firstName(self): 'The first name of the individual associated with this phone number.\n :rtype: str\n ' return self._first_name
The first name of the individual associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
firstName
engasm89/zangasm
1
python
@property def firstName(self): 'The first name of the individual associated with this phone number.\n :rtype: str\n ' return self._first_name
@property def firstName(self): 'The first name of the individual associated with this phone number.\n :rtype: str\n ' return self._first_name<|docstring|>The first name of the individual associated with this phone number. :rtype: str<|endoftext|>
a649bb63f2f33179afce6c01d4b6014253961434d932e366dabf0754891942af
@property def lastName(self): 'The last name of the individual associated with this phone number.\n :rtype: str\n ' return self._last_name
The last name of the individual associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
lastName
engasm89/zangasm
1
python
@property def lastName(self): 'The last name of the individual associated with this phone number.\n :rtype: str\n ' return self._last_name
@property def lastName(self): 'The last name of the individual associated with this phone number.\n :rtype: str\n ' return self._last_name<|docstring|>The last name of the individual associated with this phone number. :rtype: str<|endoftext|>
546f12b9e4c30e1310c99ea0217128117738b6d7ce2c159a1c9a0bcc6cd86ab5
@property def address(self): 'The address associated with this phone number.\n :rtype: str\n ' return self._address
The address associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
address
engasm89/zangasm
1
python
@property def address(self): 'The address associated with this phone number.\n :rtype: str\n ' return self._address
@property def address(self): 'The address associated with this phone number.\n :rtype: str\n ' return self._address<|docstring|>The address associated with this phone number. :rtype: str<|endoftext|>
ca8f7eeb00edf9433f6c47808fa40cc359262715cc26cfaeb884afb354e0a58d
@property def city(self): 'The city associated with this phone number.\n :rtype: str\n ' return self._city
The city associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
city
engasm89/zangasm
1
python
@property def city(self): 'The city associated with this phone number.\n :rtype: str\n ' return self._city
@property def city(self): 'The city associated with this phone number.\n :rtype: str\n ' return self._city<|docstring|>The city associated with this phone number. :rtype: str<|endoftext|>
d500372c9c44f3439e4f79545af11c478177a86e87a6bccdeb8a8438a3f78036
@property def state(self): 'The US state associated with this phone number.\n :rtype: str\n ' return self._state
The US state associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
state
engasm89/zangasm
1
python
@property def state(self): 'The US state associated with this phone number.\n :rtype: str\n ' return self._state
@property def state(self): 'The US state associated with this phone number.\n :rtype: str\n ' return self._state<|docstring|>The US state associated with this phone number. :rtype: str<|endoftext|>
3f7036456bc0b723e43798b9dd1998007a0c648dfaaa5a52ee10ff7ed9f94746
@property def zipCode(self): 'The zip code associated with this phone number.\n :rtype: str\n ' return self._zip_code
The zip code associated with this phone number. :rtype: str
zang/domain/bna_lookup.py
zipCode
engasm89/zangasm
1
python
@property def zipCode(self): 'The zip code associated with this phone number.\n :rtype: str\n ' return self._zip_code
@property def zipCode(self): 'The zip code associated with this phone number.\n :rtype: str\n ' return self._zip_code<|docstring|>The zip code associated with this phone number. :rtype: str<|endoftext|>