本文整理汇总了Python中safe.utilities.unicode.get_string函数的典型用法代码示例。如果您正苦于以下问题:Python get_string函数的具体用法?Python get_string怎么用?Python get_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了get_string函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_generate_report_dictionary_from_dom
def test_generate_report_dictionary_from_dom(self):
"""Test generate_report_dictionary_from_dom function."""
self.mock_the_dialog(test_entire_mode=False)
self.impact_merge_dialog.prepare_input()
self.impact_merge_dialog.validate_all_layers()
# Create the DOM
first_postprocessing_report = \
self.impact_merge_dialog.first_impact['postprocessing_report']
second_postprocessing_report = \
self.impact_merge_dialog.second_impact['postprocessing_report']
first_report = (
'<body>' +
first_postprocessing_report +
'</body>')
second_report = (
'<body>' +
second_postprocessing_report +
'</body>')
# Now create a dom document for each
first_document = minidom.parseString(get_string(first_report))
second_document = minidom.parseString(get_string(second_report))
tables = first_document.getElementsByTagName('table')
tables += second_document.getElementsByTagName('table')
report_dict = \
self.impact_merge_dialog.generate_report_dictionary_from_dom(
tables)
# There should be 4 keys in that dict
# (3 for each aggregation unit and 1 for total in aggregation unit)
expected_number_of_keys = 4
self.assertEqual(len(report_dict), expected_number_of_keys)
示例2: create_keyword_file
def create_keyword_file(self, algorithm):
"""Create keyword file for the raster file created.
Basically copy a template from keyword file in converter data
and add extra keyword (usually a title)
:param algorithm: Which re-sampling algorithm to use.
valid options are 'nearest' (for nearest neighbour), 'invdist'
(for inverse distance), 'average' (for moving average). Defaults
to 'nearest' if not specified. Note that passing re-sampling alg
parameters is currently not supported. If None is passed it will
be replaced with 'nearest'.
:type algorithm: str
"""
if self.algorithm_name:
keyword_path = os.path.join(self.output_dir, "%s-%s.keywords" % (self.output_basename, algorithm))
else:
keyword_path = os.path.join(self.output_dir, "%s.keywords" % self.output_basename)
mmi_keywords = os.path.join(data_dir(), "mmi.keywords")
shutil.copyfile(mmi_keywords, keyword_path)
# append title and source to the keywords file
if len(self.title.strip()) == 0:
keyword_title = self.output_basename
else:
keyword_title = self.title
with open(keyword_path, "a") as keyword_file:
keyword_file.write(get_string("title: %s \n" % keyword_title))
keyword_file.write(get_string("source: %s " % self.source))
示例3: test_get_string
def test_get_string(self):
"""Test get_string function."""
text = 'Test \xe1, \xe9, \xed, \xf3, \xfa, \xfc, \xf1, \xbf'
string_repr = b'Test \xc3\xa1, \xc3\xa9, \xc3\xad, \xc3\xb3, \xc3\xba, \xc3\xbc, \xc3\xb1, \xc2\xbf'
message = 'It should return %s, but it returned %s' % (
string_repr, get_string(text))
self.assertEqual(get_string(text), string_repr, message)
self.assertEqual(get_string(string_repr), string_repr)
示例4: test_generate_reports
def test_generate_reports(self):
"""Test generate_reports function."""
self.mock_the_dialog(test_entire_mode=False)
self.impact_merge_dialog.prepare_input()
self.impact_merge_dialog.validate_all_layers()
# Create the DOM
first_postprocessing_report = \
self.impact_merge_dialog.first_impact['postprocessing_report']
second_postprocessing_report = \
self.impact_merge_dialog.second_impact['postprocessing_report']
first_report = (
'<body>' +
first_postprocessing_report +
'</body>')
second_report = (
'<body>' +
second_postprocessing_report +
'</body>')
# Now create a dom document for each
first_document = minidom.parseString(get_string(first_report))
second_document = minidom.parseString(get_string(second_report))
first_impact_tables = first_document.getElementsByTagName('table')
second_impact_tables = second_document.getElementsByTagName('table')
first_report_dict = \
self.impact_merge_dialog.generate_report_dictionary_from_dom(
first_impact_tables)
second_report_dict = \
self.impact_merge_dialog.generate_report_dictionary_from_dom(
second_impact_tables)
self.impact_merge_dialog.generate_report_summary(
first_report_dict, second_report_dict)
self.impact_merge_dialog.generate_html_reports(
first_report_dict, second_report_dict)
# Generate PDF Reports
self.impact_merge_dialog.generate_reports()
# There should be 3 pdf files in self.impact_merge_dialog.out_dir
report_list = glob(
os.path.join(
self.impact_merge_dialog.out_dir,
'*.pdf'))
expected_reports_number = 3
self.assertEqual(len(report_list), expected_reports_number)
示例5: test_str_unicode_str
def test_str_unicode_str(self):
"""Test if str(unicode(str)) works correctly."""
text = 'Test á, é, í, ó, ú, ü, ñ, ¿'.encode('utf-8')
unicode_repr = get_unicode(text)
str_repr = get_string(unicode_repr)
message = 'It should return %s, but it returned %s' % (text, str_repr)
self.assertEqual(text, str_repr, message)
示例6: __init__
def __init__(self, message=None):
""""General constructor.
:param message: The optional error message.
:type message: str, unicode, MessageElement
"""""
if isinstance(message, unicode):
super(InaSAFEError, self).__init__(get_string(message))
self.message = message
elif isinstance(message, str):
super(InaSAFEError, self).__init__(message)
self.message = get_unicode(message)
elif isinstance(message, MessageElement):
super(InaSAFEError, self).__init__(message.to_text())
self.message = get_unicode(message.to_text())
elif message is None:
pass
elif isinstance(message, BaseException):
super(InaSAFEError, self).__init__(unicode(message))
self.message = unicode(message)
# This shouldn't happen...
else:
raise TypeError
示例7: accept
def accept(self):
"""Method invoked when OK button is clicked."""
try:
self.save_metadata()
except InvalidValidationException as e:
display_warning_message_box(
self, tr('Invalid Field Mapping'), get_string(e.message))
return
super(FieldMappingDialog, self).accept()
示例8: __str__
def __str__(self):
"""return the HTML code for the table cell as a string
.. note:: Since we are using the bootstrap framework we set
alignment using inlined css as bootstrap will override the
alignment given by align and valign html attributes.
"""
attribs_str = ''
if self.bgcolor:
self.attribs['bgcolor'] = self.bgcolor
if self.width:
self.attribs['width'] = self.width
if self.align:
self.attribs['align'] = self.align
self.style += 'text-align: ' + self.align + ';'
if self.char:
self.attribs['char'] = self.char
if self.charoff:
self.attribs['charoff'] = self.charoff
if self.valign:
self.attribs['valign'] = self.valign
self.style += 'text-align: ' + self.valign + ';'
if self.style:
self.attribs['style'] = self.style
if self.cell_class:
self.attribs['class'] = self.cell_class
if self.row_span:
self.attribs['rowspan'] = self.row_span
if self.col_span:
self.attribs['colspan'] = self.col_span
for attr in self.attribs:
attribs_str += ' %s="%s"' % (attr, self.attribs[attr])
if self.text:
text = self.text
else:
# An empty cell should at least contain a non-breaking space
text = ' '
attribs_str = get_string(attribs_str)
text = get_string(text)
if self.header:
return ' <th%s>%s</th>\n' % (attribs_str, text)
else:
return ' <td%s>%s</td>\n' % (attribs_str, text)
示例9: on_pbnNext_released
def on_pbnNext_released(self):
"""Handle the Next button release.
.. note:: This is an automatic Qt slot
executed when the Next button is released.
"""
current_step = self.get_current_step()
if current_step == self.step_kw_fields_mapping:
try:
self.step_kw_fields_mapping.get_field_mapping()
except InvalidValidationException as e:
display_warning_message_box(
self, tr('Invalid Field Mapping'), get_string(e.message))
return
if current_step.step_type == STEP_FC:
self.impact_function_steps.append(current_step)
elif current_step.step_type == STEP_KW:
self.keyword_steps.append(current_step)
else:
LOGGER.debug(current_step.step_type)
raise InvalidWizardStep
# Save keywords if it's the end of the keyword creation mode
if current_step == self.step_kw_summary:
self.save_current_keywords()
# After any step involving Browser, add selected layer to map canvas
if current_step in [self.step_fc_hazlayer_from_browser,
self.step_fc_explayer_from_browser,
self.step_fc_agglayer_from_browser]:
if not QgsMapLayerRegistry.instance().mapLayersByName(
self.layer.name()):
QgsMapLayerRegistry.instance().addMapLayers([self.layer])
# Make the layer visible. Might be hidden by default. See #2925
legend = self.iface.legendInterface()
legend.setLayerVisible(self.layer, True)
# After the extent selection, save the extent and disconnect signals
if current_step == self.step_fc_extent:
self.step_fc_extent.write_extent()
# Determine the new step to be switched
new_step = current_step.get_next_step()
if new_step is not None:
# Prepare the next tab
new_step.set_widgets()
else:
# Wizard complete
self.accept()
return
self.go_to_step(new_step)
示例10: test_generate_html_reports
def test_generate_html_reports(self):
"""Test generate_html_reports function."""
self.mock_the_dialog(test_entire_mode=False)
self.impact_merge_dialog.prepare_input()
self.impact_merge_dialog.validate_all_layers()
first_postprocessing_report = \
self.impact_merge_dialog.first_impact['postprocessing_report']
second_postprocessing_report = \
self.impact_merge_dialog.second_impact['postprocessing_report']
first_report = (
'<body>' +
first_postprocessing_report +
'</body>')
second_report = (
'<body>' +
second_postprocessing_report +
'</body>')
# Now create a dom document for each
first_document = minidom.parseString(get_string(first_report))
second_document = minidom.parseString(get_string(second_report))
first_impact_tables = first_document.getElementsByTagName('table')
second_impact_tables = second_document.getElementsByTagName('table')
first_report_dict = \
self.impact_merge_dialog.generate_report_dictionary_from_dom(
first_impact_tables)
second_report_dict = \
self.impact_merge_dialog.generate_report_dictionary_from_dom(
second_impact_tables)
self.impact_merge_dialog.generate_html_reports(
first_report_dict, second_report_dict)
# There should be 4 HTML files generated
html_list = glob(
os.path.join(
temp_dir(self.impact_merge_dialog.__class__.__name__),
'*.html'))
expected_html_number = 4
self.assertEqual(len(html_list), expected_html_number)
示例11: merge
def merge(self):
"""Merge the postprocessing_report from each impact."""
# Ensure there is always only a single root element or minidom moans
first_postprocessing_report = \
self.first_impact['postprocessing_report']
second_postprocessing_report = \
self.second_impact['postprocessing_report']
# noinspection PyTypeChecker
first_report = '<body>' + first_postprocessing_report + '</body>'
# noinspection PyTypeChecker
second_report = '<body>' + second_postprocessing_report + '</body>'
# Now create a dom document for each
first_document = minidom.parseString(get_string(first_report))
second_document = minidom.parseString(get_string(second_report))
first_impact_tables = first_document.getElementsByTagName('table')
second_impact_tables = second_document.getElementsByTagName('table')
# Now create dictionary report from DOM
first_report_dict = self.generate_report_dictionary_from_dom(
first_impact_tables)
second_report_dict = self.generate_report_dictionary_from_dom(
second_impact_tables)
# Generate report summary for all aggregation unit
self.generate_report_summary(first_report_dict, second_report_dict)
# Generate html reports file from merged dictionary
self.generate_html_reports(first_report_dict, second_report_dict)
# Generate PDF Reports using composer and/or atlas generation:
self.generate_reports()
# Delete html report files:
for area in self.html_reports:
report_path = self.html_reports[area]
if os.path.exists(report_path):
os.remove(report_path)
示例12: prettify_xml
def prettify_xml(xml_str):
"""
returns prettified XML without blank lines
based on http://stackoverflow.com/questions/14479656/
:param xml_str: the XML to be prettified
:type xml_str: str
:return: the prettified XML
:rtype: str
"""
parsed_xml = parseString(get_string(xml_str))
pretty_xml = b'\n'.join(
[line for line in parsed_xml.toprettyxml(
indent=' ' * 2, encoding='UTF-8').split(b'\n') if line.strip()])
if not pretty_xml.endswith(b'\n'):
pretty_xml += b'\n'
return pretty_xml.decode('utf-8')
示例13: merge
def merge(self):
"""Merge the postprocessing_report from each impact."""
# Ensure there is always only a single root element or minidom moans
first_postprocessing_report = \
self.first_impact['postprocessing_report']
second_postprocessing_report = \
self.second_impact['postprocessing_report']
# noinspection PyTypeChecker
first_report = '<body>' + first_postprocessing_report + '</body>'
# noinspection PyTypeChecker
second_report = '<body>' + second_postprocessing_report + '</body>'
# Now create a dom document for each
first_document = minidom.parseString(get_string(first_report))
second_document = minidom.parseString(get_string(second_report))
first_impact_tables = first_document.getElementsByTagName('table')
second_impact_tables = second_document.getElementsByTagName('table')
# Now create dictionary report from DOM
first_report_dict = self.generate_report_dictionary_from_dom(
first_impact_tables)
second_report_dict = self.generate_report_dictionary_from_dom(
second_impact_tables)
# Rizky: Consistency checks with aggregation
# Make sure the aggregation layer both presents in both layers
# We shouldn't have problems with Entire Area mode. It just means
# the impact layer and summary is merged into single report.
# We can have 3 cases:
# 1. If both of them were not aggregated, we can just merge the map
# only
# 2. If both of them were aggregated, we can just merge the map, and
# merge postprocessor report using 'Total aggregation in areas' key
# 3. If only one of them were aggregated, we can just merge the map,
# and uses postprocessor report from the one who has.
if self.entire_area_mode:
# We won't be bothered with the map, it will be merged anyway in
# all 3 cases. We should bother with the postprocessor report.
# If one of them has the report, it means it will contain more
# than one report keys. We can just swap the first report if they
# have one key, and the second have more than one
if (len(first_report_dict.keys()) == 1 and
len(second_report_dict.keys()) > 1):
swap_var = first_report_dict
first_report_dict = second_report_dict
second_report_dict = swap_var
# This condition will covers aggregated mode
# For this case, we should make sure both layers are aggregated with
# the same aggregation layer of the chosen aggregation layer
else:
# check that both layers must have aggregated postprocessor.
# aggregated postprocessor means the report_dict must have minimum
# 2 keys
if not (len(first_report_dict.keys()) > 1 and
len(second_report_dict.keys()) > 1):
raise InvalidLayerError(self.tr(
'Please choose impact layers with aggregated '
'postprocessor if you want to use aggregation layer.'))
# collect all report keys (will contain aggregation areas in the
# report)
report_keys = first_report_dict.keys()
# Discard the last keys. It will always contains total area, not
# aggregated area
if len(report_keys) > 0:
del report_keys[-1]
sec_report = second_report_dict.keys()
if len(sec_report) > 0:
del sec_report[-1]
for k in sec_report:
if k not in report_keys:
report_keys.append(k)
# collect all aggregation areas in aggregation layer
layer = self.aggregation['layer']
aggregation_attr = self.aggregation['aggregation_attribute']
aggregation_attr_index = layer.fieldNameIndex(aggregation_attr)
aggregation_keys = []
for f in layer.getFeatures():
area = f[aggregation_attr_index]
if area not in aggregation_keys:
aggregation_keys.append(area)
is_subset = True
for k in report_keys:
if k not in aggregation_keys:
is_subset = False
if not is_subset:
# This means report keys contains area keys that is not in
# aggregation layer. Which means possibly it is using the
# wrong aggregation layer.
raise InvalidLayerError(
self.tr('First and Second layer does not use chosen '
'Aggregation layer'))
# Generate report summary for all aggregation unit
#.........这里部分代码省略.........
示例14: _keyword_to_row
def _keyword_to_row(self, keyword, value):
"""Helper to make a message row from a keyword.
.. versionadded:: 3.2
Use this when constructing a table from keywords to display as
part of a message object.
:param keyword: The keyword to be rendered.
:type keyword: str
:param value: Value of the keyword to be rendered.
:type value: basestring
:returns: A row to be added to a messaging table.
:rtype: safe.messaging.items.row.Row
"""
row = m.Row()
# Translate titles explicitly if possible
if keyword == 'title':
value = self.tr(value)
# we want to show the user the concept name rather than its key
# if possible. TS
definition = self.definition(keyword)
if definition is None:
definition = self.tr(keyword.capitalize().replace('_', ' '))
else:
definition = definition['name']
# We deal with some special cases first:
# In this case the value contains a DICT that we want to present nicely
if keyword == 'value_map':
value = self._dict_to_row(value)
# In these KEYWORD cases we show the DESCRIPTION for
# the VALUE definition
elif keyword in [
'vector_hazard_classification',
'raster_hazard_classification']:
# get the definition for this class from definitions.py
value = self.definition(value)
value = value['description']
# In these VALUE cases we show the DESCRIPTION for
# the VALUE definition
elif value in []:
# get the definition for this class from definitions.py
value = self.definition(value)
value = value['description']
# In these VALUE cases we show the NAME for the VALUE definition
elif value in [
'multiple_event',
'single_event',
'point',
'line',
'polygon'
'field']:
# get the name for this class from definitions.py
value = self.definition(value)
value = value['name']
# otherwise just treat the keyword as literal text
else:
# Otherwise just directly read the value
value = get_string(value)
key = m.ImportantText(definition)
row.add(m.Cell(key))
row.add(m.Cell(value))
return row
示例15: tr
if not os.path.isfile(keyword_file_path):
message = tr('No keywords file found for %s' % keyword_file_path)
raise NoKeywordsFoundError(message)
# now get the requested keyword using the inasafe library
try:
dictionary = read_keywords(keyword_file_path)
except Exception, e:
message = tr(
'Keyword retrieval failed for %s (%s) \n %s' % (
keyword_file_path, keyword, str(e)))
raise KeywordNotFoundError(message)
# if no keyword was supplied, just return the dict
if keyword is None:
if 'keyword_version' in dictionary.keys():
dictionary['keyword_version'] = get_string(
dictionary['keyword_version'])
return dictionary
if keyword not in dictionary:
message = tr('No value was found in file %s for keyword %s' % (
keyword_file_path, keyword))
raise KeywordNotFoundError(message)
try:
value = dictionary[keyword]
except:
raise
if 'keyword_version' == keyword:
value = get_string(value)
return value