Microsoft Translator Text not raising error when wrong params passed with custom engine - microsoft-translator

I've noticed 2 cases in which Microsoft Translator Text should raise errors when using custom engines, but instead has an unexpected behavior.
Normal Case
I send a request with the method POST.
URL = https://api.cognitive.microsofttranslator.com/translate
parameters :
- api-version=3.0
- textType=plain
- category=my_engine_id
- from=de
- to=en
Headers={"Ocp-Apim-Subscription-Key": my_key,'Content-type': 'application/json'}
Body (JSON format) :
[{"Text": "Klicken Sie in jedem Bildschirm auf das Textbeispiel, das am besten lesbar ist."},
{"Text": "Verschiedene Themen aus den Bereichen Wortschatz, Satzbau, Kohärenz, Textwiedergabe,
Kommasetzung und Orthographie werden anhand von Textbeispielen und Übungen vorgestellt."},
{"Text": "„Auch wenn zwei Staaten in Deutschland existieren, sind sie doch füreinander nicht Ausland; ihre Beziehungen zueinander können nur von besonderer Art sein.“"},
{"Text": "Mit dieser Formel bricht der neue Kanzler ein jahrzehntelanges Tabu."},
{"Text": "Bislang wird der östliche Teil Deutschlands von den bundesdeutschen Politikern als SBZ, Zone oder „sogenannte DDR“ bezeichnet."}]
The response is as expected:
[{"translations":
[{"text": "On each screen, click on the text sample that is most readable.",
"to": "en"}]},
{"translations":
[{"text": "Various topics from the fields of vocabulary, typesetting, coherence, text reproduction, comma setting and orthography are presented using text examples and exercises.",
"to": "en"}]},
etc.
Case 1
I change the parameter to=fr in the URL (instead of "en").
The response shows that the text has been translated into french, although the custom engine is only trained from DE>EN (therefore I think a generic engine was used instead, but there is no info in the HTTP response) !
[{"translations":[{"text":"Sur chaque écran, cliquez sur l’échantillon de texte le plus lisible.","to":"fr"}]},{"translations":[{"text":"Divers sujets des domaines du vocabulaire, du typage, de la cohérence, de la reproduction du texte, du décor de virgule et de l’orthographe sont présentés à l’aide d’exemples de textes et d’exercices.","to":"fr"}]},{"translations":[{"text":"\"Même si deux États existent en Allemagne, ils ne sont pas étrangers l’un à l’autre; Leurs relations les uns avec les autres ne peuvent être que d’un genre particulier.","to":"fr"}]},{"translations":[{"text":"Avec cette formule, le nouveau chancelier brise un tabou de dix ans.","to":"fr"}]},{"translations":[{"text":"Jusqu’à présent, la partie orientale de l’Allemagne est appelée par les politiciens fédéraux allemands SBZ, zone ou « soi-disant DDR ».","to":"fr"}]}]
Instead of this behaviour, I would have expected an error in the HTTP response :
400075 The language pair and category combination is not valid.
Case 2
I change the parameter from=da in the URL (instead of "de").
The response shows that the translation is simply a copy of the source text, although it indicates that it was translated into "en" !
[{"translations":[{"text":"Klicken Sie in jedem Bildschirm auf das Textbeispiel, das am besten lesbar ist.","to":"en"}]},{"translations":[{"text":"Verschiedene Themen aus den Bereichen Wortschatz, Satzbau, Kohärenz, Textwiedergabe, Kommasetzung und Orthographie werden anhand von Textbeispielen und Übungen vorgestellt.","to":"en"}]},{"translations":[{"text":"\"Auch wenn zwei Staaten in Deutschland existieren, sind sie doch füreinander nicht Ausland; ihre Beziehungen zueinander können nur von besonderer Art sein.\"","to":"en"}]},{"translations":[{"text":"Mit dieser Formula bricht der neue Kanzler ein jahrzehntelanges Tabu.","to":"en"}]},{"translations":[{"text":"Bislang wird der östliche Teil Deutschlands von den bundesdeutschen Politikern als SBZ, Zone oder \"sogenannte DDR\" bezeichnet.","to":"en"}]}]
Same as for Case 1, instead of this behaviour, I would have expected an error in the HTTP response :
400075 The language pair and category combination is not valid.
Is it normal that I don't get an error for these 2 cases ? Has anybody else encountered this behavior before ?
Actually I would like to either use these error codes, or else check before sending the translation request that the language pair corresponds to the custom engine, do you know of some way to do it ?

For case1, translation is done in two hops - de>en, en>fr. The custom engine is used for the first hop, and our general model is used for the second. If you want the translation to fail in this case instead, you can set the parameter allowFallback to false
allowFallback Optional parameter.
Specifies that the service is allowed to fallback to a general system when a custom system does not exist. Possible values are: true (default) or false.
docs
In the second case, the request contains German text but is labeled as Danish. There is nothing we can do here except return the input. If you want the api to detect the from language, omit it from the parameters and the api will run auto-detect on the text.
If the from parameter is not specified, automatic language detection is applied to determine the source language.

Related

How to solve json loading issue?

I just started learning web scraping with Python 3, and I am trying to apply it in a small project which consists of extracting data from job listings. I did look for answers and found some questions which touched a somewhat similar subject, but none of them seemed to have the exact same use case - at least that is my understanding. 
I extracted company URLs from the search results of a website and appended the company URLs in a list named sitelis. Then, I looped through sitelis to extract the json data from each of the company URLs. However, I have a problem to retrieve the json data from some of the company URLs (see traceback: json.decoder.JSONDecodeError: Invalid \escape) - while the large majority URLs work just fine. Any idea what could cause this? I am a bit lost since 90% of the URLs work fine, and for those few which do not parse correctly I cannot find any differences which would explain it.
Thanks a lot for your help!
Here is an example of such an error:
This is the traceback:
Traceback (most recent call last):
File "glassdoor_json.py", line 117, in <module>
company_js = json.loads(company_jdata.text, strict=False) # to get a Python list
File "/Users/spw/anaconda3/lib/python3.7/json/__init__.py", line 361, in loads
return cls(**kw).decode(s)
File "/Users/spw/anaconda3/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/spw/anaconda3/lib/python3.7/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid \escape: line 54 column 92 (char 2146)
This is the code for the for-loop:
for site in sitelis:
count_site = count_site + 1
try:
companyrstarturl = Request(site, headers={'User-Agent': 'Mozilla/5.0'})
fhand_company = urllib.request.urlopen(companyrstarturl, context=ctx)
companydata = fhand_company.read()
company_soup = BeautifulSoup(companydata, 'lxml')
company_jdata = company_soup.select("[type='application/ld+json']")[0]
company_js = json.loads(company_jdata.text, strict=False) # to get a Python list
print('')
print('>>>>>>>>>>>>>>> (json) Company', count_site, '<<<<<<<<<<<<<<<' )
print('')
print(json.dumps(company_js, indent=4))
print('')
except KeyboardInterrupt:
print('')
print('(2) Program interrupted by user...')
break
This is the associated json data from a company website (the one with traceback):
{
"#context": "http://schema.org",
"#type": "JobPosting",
"title": "Back-End Developer (m/w/d)",
"url": "https://www.glassdoor.de/job-listing/back-end-developer-mwd-storming-creative-studios-JV_IC2561561_KO0,22_KE23,48.htm?jl=3655406413",
"datePosted": "2020-08-25",
"employmentType": "FULL_TIME",
"salaryCurrency": "EUR",
"validThrough": "2020-09-26",
"hiringOrganization": {
"#type": "Organization",
"name": "STORMING GmbH Creative Studios"
},
"jobLocation": {
"#type": "Place",
"address": {
"#type": "PostalAddress",
"addressLocality": "Leonberg",
"addressRegion": "01",
"addressCountry": {
"#type" : "Country",
"name" : "DE"
}
}
,
"geo": {
"#type": "GeoCoordinates",
"latitude": "48.8005",
"longitude": "9.0168"
}
}
,"description": "In den STORMING Creative Studios wird Kommunikation neu gedacht: In f&uuml;nf einzigartigen Studios b&uuml;ndeln wir unsere Kompetenzen und erschaffen innovative Kommunikationsdienstleistungen. Wir blicken auf beeindruckendes Wachstum zur&uuml;ck und schauen in eine ambitionierte Zukunft. Werde jetzt Teil des Teams.
<br/><br/>
In unserem Development Studio entstehen innovative Webseiten, durchdachte Apps und hilfreiche Software. Dabei bieten wir unseren Kunden immer die neuesten Technologien und zielf&uuml;hrendsten L&ouml;sungen. F&uuml;r unser Team suchen wir daher Back-End Developer f&uuml;r folgende Aufgaben:
<ul>
<li>Arbeit an Unternehmenssoftware zur Digitalisierung von Prozessen</li>
<li>Anpassungen an CMS-Backends</li>
<li>Erstellung von Konfiguratoren</li>
<li>Enge Zusammenarbeit mit Front-End Developern und Projektleitungen</li>
</ul>
Uns ist wichtig, dass wir uns aufeinander verlassen und uns vertrauen k&ouml;nnen. Jede\*r bei STORMING ist ein wichtiger Teil des Unternehmens, tr&auml;gt Verantwortung und unterst&uuml;tzt aktiv unser Wachstum. Aus diesem Grund suchen wir nach loyalen Mitarbeitern\*innen mit hoher Motivation. Dar&uuml;ber hinaus ist uns folgendes wichtig:
<ul>
<li>Hervorragende Kenntnisse in PHP, Javascript &amp; SQL</li>
<li>Kenntnisse in Pythan, Objective-C/Swift &amp; Java von Vorteil</li>
<li>Berufserfahrung</li>
<li>Zuverl&auml;ssigkeit</li>
</ul>
F&uuml;r uns sind faire Bezahlung und geldwerte Vorteile eine Selbstverst&auml;ndlichkeit. Doch auch dar&uuml;ber hinaus ist unser Ziel, einen Ort zu schaffen, an dem Menschen sich gern aufhalten und sie selbst sein k&ouml;nnen.Zusammengefasst bieten wir dir:
<ul>
<li>gute Work-Life-Balance</li>
<li>faire Bezahlung &amp; geldwerte Vorteile</li>
<li>moderne Ausstattung &amp; firmeneigene Parkpl&auml;tze</li>
<li>flache Hierarchien &amp; kurze Entscheidungswege</li>
</ul>
Interesse? Dann bewirb dich jetzt per Mail mit deinem Lebenslauf und Portfolio. Wir freuen uns auf dich!
<br/><br/>
Art der Stelle: Vollzeit"
}
And here is an example of a json (from a company website) which worked fine:
{
"#context": "http://schema.org",
"#type": "JobPosting",
"title": "Back-End Node Developer",
"url": "https://www.glassdoor.de/job-listing/back-end-node-developer-ust-global-JV_IC2622109_KO0,23_KE24,34.htm?jl=3615685703",
"datePosted": "2020-08-28",
"employmentType": "FULL_TIME",
"salaryCurrency": "EUR",
"validThrough": "2020-09-27",
"industry": "Information Technology",
"hiringOrganization": {
"#type": "Organization",
"name": "UST Global",
"logo": "https://media.glassdoor.com/sqll/155577/ust-global-squarelogo-1579115891630.png",
"sameAs": "www.ust-global.com"
},
"jobLocation": {
"#type": "Place",
"address": {
"#type": "PostalAddress",
"addressLocality": "Berlin",
"addressRegion": "16",
"addressCountry": {
"#type" : "Country",
"name" : "DE"
}
}
,
"geo": {
"#type": "GeoCoordinates",
"latitude": "52.5177",
"longitude": "13.4055"
}
}
,"occupationalCategory" : ["15-1132.00", "Software Developers, Applications"]
,"description": "<p>UST Global is increasing its International Digital &amp; Innovation Hub in Berlin in partnership model with one of our Fortune 500 clients, to deliver new digital solutions in more than 60 countries as part of their business transformation model.</p>
<p>The Hub team leads the end-to-end process of creating new capabilities, products and platforms, applying best practices, top technology trends and agile techniques.</p>
<p>As part of our Digital Hub based in Berlin, you will have the opportunity to work in a multicultural and highly dynamic environment. You will have the chance to live the first steps of this international, highly skilled, success-oriented team.</p>
<p><strong>Key responsibilities</strong></p>
<p>As part of our digital squads you will work on state-of-the-art technologies to design and create products for creating new business models, that will transform the way of interacting between people and enterprises:</p>
<ul>
<li>E2E responsibility for building digital products and solutions.</li>
<li>Build AI solutions.</li>
<li>Apply architecture principles and development standards.</li>
<li>Work closely with other technical teams undertaking product development coordination and delivery.</li>
</ul>
<p><strong>Basic qualifications:</strong></p>
<ul>
<li>You are experienced in JavaScript/TypeScript</li>
<li>You are familiar with building scalable applications and services with Node.js</li>
<li>You have knowledge in relational databases like Postgres</li>
<li>Monitoring with ELK (Elastic Search, LogStash, Kibana)</li>
<li>Use of best practices in clean code, testing and code review.</li>
<li>Understanding on quality documentation and diagrams.</li>
<li>Experience working with Agile principles and best practices.</li>
<li>Good time management skills.</li>
<li>Real passion of coding and technology</li>
<li>A degree in computer science, or similar professional certifications.</li>
<li>Fluent English and excellent communication skills.</li>
<li>Used to work in multinational projects.</li>
</ul>
<p><strong>Desirable qualifications:</strong></p>
<ul>
<li>Experience implementing and managing CI/CD solutions.</li>
<li>Experience under some of the following frameworks: Angular or React.</li>
<li>Knowledge of Kafka is a plus</li>
</ul>
<p><strong>Suitable candidates:</strong></p>
<ul>
<li>German passport holders</li>
<li>German valid working visa</li>
<li>European Union passport holders</li>
</ul>
<p><strong> </strong><strong>Who we are:</strong></p>
<p>We are a multinational digital company with over 20.000 employees all over the world and presence in more than 25 countries.</p>
<p>We transform lives with our human centered innovative solutions, touching 3 billion &ldquo;personas&rdquo; through digital solutions and technologies.</p>
<p>UST Global is a Great Place to Work&reg; and Top Employer&reg; certified company.</p>
<p>For further details please go to www.ust-global.com</p>
<p><strong>What we offer:</strong></p>
<ul>
<li>Competitive compensation package and benefits.</li>
<li>Flexible Payment Plan so you can adapt your salary according to your preferences (child care checks, transport card, online German and English lessons with native teachers, health insurance&hellip;).</li>
<li>25 working days of holidays.</li>
<li>Free breakfast, food and drinks.</li>
<li>Team activities like barbecues, game nights, team events and much more.</li>
<li>Professional career in our Center of Excellence where you could participate on several projects inside the company.</li>
<li>International environment and close contact with colleagues specialized in the core technologies of the company, with whom you will share your knowledge.</li>
<li>We have an (internal) program to compensate referrals from which you can benefit when you refer professionals that get on the company.</li>
</ul>
<p>If you want to know more, don&rsquo;t hesitate to apply and we&rsquo;ll get in touch with you to give more details about the offer. If you are a digital native, this is an amazing opportunity to join one of the leading initiatives in Central Europe, Berlin.</p>"
}
I have figured out how to solve the issue.
The issue was caused by escaped backslashes, \, on some of the json data. An escape sequence contains two/more characters starting with a backlash, such as '\n' that represents a newline, where '\' does not represent itself. Examples of escaped backlashes on some of the data:
<li>Enge Abstimmung mit Designer\*innen &amp; Projektleitung</li>
and
Aus diesem Grund suchen wir nach loyalen Mitarbeitern\*innen mit hoher Motivation.
Here is the solution:
company_js = json.loads(company_jdata.text.replace('\\', '/'), strict=False)
In order to solve the problem, '/' is used in the second argument as a replacement for the escaped backslash. In the first argument, '\\' is used: an additional backlash is used together with the '\' to escape the escape backlash (i.e. '\\' is actually representing '\').
Uns ist wichtig, dass wir uns aufeinander verlassen und uns vertrauen können. Jede*r bei STORMING ist ein wichtiger Teil des Unternehmens, trägt Verantwortung und unterstützt aktiv unser Wachstum. Aus diesem Grund suchen wir nach loyalen Mitarbeitern*innen mit hoher Motivation. Darüber hinaus ist uns folgendes wichtig:
That is line 53 in the non functional example you have. I see a non escaped colon at the end of the line, which the JSON parser might treat as a key:pair delimiter. If this is the case, would possibly explain the error and you would need some type of sanitizer to capture and properly escape these.
Not sure if that is something built in, or if you would need to make your own. Maybe someone else can offer a solution to how to handle that.
I also see the same thing on line 63
Für uns sind faire Bezahlung und geldwerte Vorteile eine Selbstverständlichkeit. Doch auch darüber hinaus ist unser Ziel, einen Ort zu schaffen, an dem Menschen sich gern aufhalten und sie selbst sein können.Zusammengefasst bieten wir dir:

SQL Server 2016: Import of JSON Information

I operate a SQL Server 2016 to store different information that I receive via REST/JSON. This works properly good and i actually add additional sources (4 Import types). On one json import i got an error like that:
Msg 13609, Level 16, Status 4, line 2
The JSON text is not properly formatted. At position 0, the unexpected character "൛ " was found.
I checked the file and Syntax and they are similar like other files / Formats that I Import (without an error):
Json example:
[
{
"cid": 6498,
"hotel_description": "Hotelmerkmale: All Inclusive, Family, Paare, Single\n<br /> \n<br /> Die ideale Wahl für den unternehmungslustigen Gast. Genießen Sie tagsüber vom Pool den entspannenden Blick auf das Meer und die Side-Halbinsel und leben Sie abends Ihr Shopping- oder Tanzfieber in der nahe gelegenen Altstadt von Side aus.\n<br /> \n<br /> \n<strong>Lage:</strong> In erhöhter Lage mit Panoramablick auf das Meer und die historische Altstadt von Side. Ca. 200 m vom kilometerlangen, flach abfallenden, feinen Sandstrand und ca. 1,5 km vom Zentrum mit zahlreichen Einkaufs- und Unterhaltungsmöglichkeiten, Restaurants, Bars und Cafés entfernt (regelmäßige Minibusverbindungen vorhanden).\n<br /> \n<br /> \n<strong>Ausstattung:</strong> Bekanntes Hotel der gehobenen Mittelklasse mit 2 Swimmingpools (einer davon mit 2 Wasserrutschen), Sonnenterrasse. Liegen, Auflagen, Sonnenschirme (Badetücher gegen Kaution). Pool-/Snackbar, Strandbar. Elegante Empfangshalle, Rezeption, WLAN in der Lobby, Sitzgruppen, Lobbybar, Spieleraum, Fernsehecke mit Großbildschirm, klimatisiertes Hauptrestaurant, 4 À-la-carte-Restaurants, Minimarkt, Diskothek, Friseur, Hallenbad. Landeskategorie: 5 Sterne, 341 Zimmer, 6 Etagen, Lifte.\n<br /> \n<br /> \n<strong>Wohnen:</strong> Doppelzimmer (ca. 18-22 qm), Klimaanlage (indiv.), Minibar, Telefon, TV, Mietsafe, Kaffee-/Teeset. Dusche/WC mit Föhn. Balkon. Max. 2E. Wahlweise seitl. Meerblick/Meerblick. Max. 3E, auch zur Alleinnutzung buchbar\n<br /> Juniorsuite (ca. 35 qm), zus. Couch, Klimaanlage (indiv.), Minibar, Telefon, TV, Mietsafe, Kaffee-/Teeset. Dusche/WC mit Föhn. Balkon. Landseite/seitl. Meerblick. Max. 3E+1K\n<br /> Familienzimmer (ca. 40 qm), zus. separates Schlafzimmer, Klimaanlage (indiv.), Minibar, Telefon, TV, Mietsafe, Kaffee-/Teeset. Dusche/WC mit Föhn. Balkon. Meerseite/seitl. Meerblick. Max. 4E\n<br /> \n<br /> \n<strong>Essen und Trinken:</strong> all inclusive: Frühstücksbuffet, mittags und abends kaltes/warmes Buffet, Themenabende, täglich Showkochen\n<br /> Snacks (stdw.), nachm. Kaffee, Tee, Gebäck\n<br /> Alkoholfr., nat. alkohol. (ab 18 J.) Getränke von 10:00-24:00 Uhr (an der Strandbar von 10:00-17:00 Uhr)Tägliche Auffüllung der Minibar mit Wasser\n<br /> \n<br /> \n<strong>Wellness und Fitness:</strong> Wellnesscenter (ca. 370 qm)\n<br /> Türkisches Bad, Dampfbad, Sauna\n<br /> Jacuzzi, Wellnessmassagen (geg. Geb.)\n<br /> Fitnessraum (ca. 70 qm)\n<br /> \n<br /> \n<strong>Sport und Fitness:</strong> Tischtennis\n<br /> Wassersport am Strand (örtlicher Anbieter, gegen Gebühr)\n<br /> \n<br /> \n<strong>Einzelzimmer ohne Aufpreis:</strong> Zu bestimmten Terminen kein Zuschlag\n<br /> \n<strong>Single mit Kind:</strong> Kinderfestpreis bei einem Vollzahler\n<br /> \n<strong>Kinderfestpreis:</strong>2 Kinder 2-12 Jahre\n<br />\n<br /> \n<br /> \n<strong>Minis & Maxis (4-12 Jahre):</strong> Miniclub (stdw.)\n<br /> Spielplatz, Kinderbuffet\n<br /> \n<br />"
}
]
My SQL statement looks like this:
MERGE dbo.hotel_description t
USING ((SELECT
cid, hotel_description
FROM
OPENROWSET(BULK 'C:\Import\weg.de\hotel_info_import.json', SINGLE_NCLOB)j
CROSS APPLY
OPENJSON(BulkColumn)
WITH
(cid INT,
hotel_description NVARCHAR(MAX)))) s ON t.cid = s.cid
WHEN NOT MATCHED THEN
INSERT (cid, hotel_description)
VALUES (s.cid, s.hotel_description);
I checked Google and stackoverflow but found no reason for that error message.
Any hints?
Thanks
Regards
Timo
In SQL Server 2016 CU7 still needed that the JSON file must be be encoded as Little Endian (UCS-2) or UTF8 with BOM. UTF8 without BOM runs into that error.

Extracting Text between sub strings in MySQL

I have a text like the below
[:de]Die BB2 ist eine erlesene türkische Gulet in klassischer Holzbauweise, die alle Annehmlichkeiten und die Eleganz einer exklusiven Yacht, die durch die hohe Qualität der vorzüglichen Holzverarbeitung und das anspruchsvolle Design untermalt wird. Auf 37 m Länge bietet Sie Ihnen 15 moderne, klimatisierte, große Kabinen mit Duschkabine / WC. Salon und Deck sind ausgesprochen großzügig angelegt und mit edlem Mobiliar ausgestattet. Die professionelle und erfahrene Crew ist auf das Beste damit vertraut für die Sicherheit und Zufriedenheit der Gäste zu sorgen und Ihnen einen Rundumservice zu bieten.
[:en]At 37 x 10 m the BB2 is designed to portray elegant style with a relaxing atmosphere. She is one of the most perfect examples of the Turkish wooden gulets with all amenities of an exclusive yacht. 15 modern, air-conditioned cabins with shower and toilet are on offer for the guests on board. The salon and deck are spaciously designed and equipped for your comfort. The professional and experienced crew is more than familiar in making sure the guests feel safe and comfortable and offer a great service all around.
[:]
[:en] represents English text and [:de] represents German text
want output for a language in MySQL. What will be the query to extract text in German only?
Assuming this is your data with the german always before the english, then:
select substring_index(substring_index(col, '[:de]', -1), '[:en]', 1)
If this is not the case, you can test for different possibilities:
select (case when col like '%[:de]%[%:en]%'
then substring_index(substring_index(col, '[:de]', -1), '[:en]', 1)
when col like '%[:de]%[%:]%'
then substring_index(substring_index(col, '[:de]', -1), '[:]', 1)
else substring_index(col, '[:de]', -1)
end)

How to HTML encode en dash in vb.net?

My string :
Feste begründen die Identität einer Gemeinschaft und ihr
Selbstverständnis nach innen. Eng damit verbunden sind Emotionen, die
zunächst im Zusammenhang mit einer gefühlten Zugehörigkeit zu einer
Fest-Gemeinschaft zu verstehen sind. Mit jedem Fest verbindet sich
aber auch eine emotionale Überschreitung des Alltags: Der bestimmende
festliche Eindruck – die feierliche Gestimmtheit – ist der einer
erhöhten Bedeutungshaftigkeit des Lebens, durch die sich das Festliche
aus dem Lauf des Alltagslebens hervorhebt und dessen Wirkmächtigkeit
zuvörderst anhand der Analyse des bürgerlichen Geburtstages sinnfällig
demonstriert werden soll.
I want to encode as HTML the above string
I tried:
System.Web.HttpUtility.HtmlEncode(strings)
I am getting output as :
Feste begründen die Identität einer Gemeinschaft und ihr
Selbstverständnis nach innen. Eng damit verbunden sind Emotionen,
die zunächst im Zusammenhang mit einer gefühlten
Zugehörigkeit zu einer Fest-Gemeinschaft zu verstehen sind. Mit
jedem Fest verbindet sich aber auch eine emotionale
Überschreitung des Alltags: Der bestimmende festliche Eindruck –
die feierliche Gestimmtheit – ist der einer erhöhten
Bedeutungshaftigkeit des Lebens, durch die sich das Festliche aus dem
Lauf des Alltagslebens hervorhebt und dessen Wirkmächtigkeit
zuvörderst anhand der Analyse des bürgerlichen Geburtstages
sinnfällig demonstriert werden soll.
You can see the above output that the en-dash is not encoded, kindly suggest any solution for this.
Also I want to encode 100% without missing any characters like this.
"I want to encode 100 % without missing any characters like this."
No need to do this if you are using the correct format. In fact, you also don't need to encode en dash or any other non-ascii characters. But if for some reason you really ought to use this feature, you can write:
Dim enDash = "–"
myString.Replace(HttpUtility.HtmlDecode(enDash), enDash)

Set width of HTML UIWebView

Can I programmatically set the width of the HTML file that I throw into the UIWebView? My problem is that the UIWebView frame is set in a UITableViewCell, so I had to set CGRectMake to fit it in the cell. But now the size of the content is bigger than the frame. Can I set the width in the UIWebView for the HTML?
My HTML Code:
<div id="attachment_16505" class="wp-caption alignnone" style="width: 460px"><img src="http://www.floorballmagazin.de/wp-content/uploads/2013/03/20130303_schweiz.jpg" alt="Maßgeblich beteiligt - Mathias Hofbauer sprang von der Strafbank und netzte zum 3:1 ein. / Foto: Hans Ulrich Muelchi, Swiss Unihockey" width="460" height="318" class="size-full wp-image-16505 colorbox-16504" /> <p class="wp-caption-text">Maßgeblich beteiligt – Mathias Hofbauer sprang von der Strafbank und netzte zum 3:1 ein. / Foto: Hans Ulrich Muelchi, Swiss Unihockey</p> </div> <p><em>In der Schweiz kann Wiler sein historisches Ausscheiden aus den Playoffs mit einem versöhnlichen Cupsieg kurieren. Vor über 3.000 Zuschauern besiegen die Berner Grünenmatt mit 3:1. Bei den Damen kann Sandra Dirksen ihren Titelreigen nicht fortsetzen, die Red Ants brachten eine versprechende Führung nicht über die Runden.</em></p> <p>Als Wilers Kapitän Mathias Hofbauer in 56. Spielminute auf die Strafbank wanderte, wurde es nochmal eng für den noch aktuellen Meister. Sein Unterzahlspiel überstand man aber mit Bravour und als Hofbauer wieder zurück aufs Feld durfte, dauerte es gerade mal sechs Sekunden und der WM-Rekordscorer machte mit einem scharfen Schlenzer alles klar.</p> <p>Bei den Damen waren Deutschlands Ex-Nationalspielerin Sandra Dirksen und ihre Red Ants auf dem Weg zum vierten Cupsieg in Folge. Rychenberg führte zu Beginn des Schlussdrittels mit 2:0, brach aber ein und unterlag Chur mit 2:5. “Wer den Pokal mit nach Hause nehmen will, muss drei Drittel gut spielen und nicht nur zwei”, bedauert Dirksen.</p> <p>“Wir hatten zwar den besseren Start, aber am Ende doch nur Silber. Fünfzehn Sekunden vor der 2. Drittelspause haben wir ein abgelenktes, unglückliches Tor kassiert, das war der Knackpunkt leider.” Dafür sei man umso motivierter für die bevorstehenden Play-Offs. “Die Atmosphäre bei einem Cup-Finale ist und bleibt einzigartig. Unsere Fans waren toll”, schätzt Dirksen.</p>
This is what happens in the cell:
One solution is to intercept your HTML and prepend:
<html>
<head>
<style>div {max-width: 460px;}</style>
</head>
<body>
<div>
And append:
</div>
</body>
Take a look at this question/answer (HTML Content fit in UIWebview without zooming out) from a while back. I posted some code there.
You could either try to set the height of the HTML contents within your HTML code equals to UIWebView. Otherwise try this command to set the size of UIWebView fitting to the page
webView.scalesPageToFit = YES;
One solution can be :
Load the URL Request
NSString *urlAddress = #"your URL";
NSURLRequest *requestObj = [NSURLRequest requestWithURL:[NSURL URLWithString:urlAddress]];
[self.webView loadRequest:requestObj];
self.webView.delegate = self;
Then implement WebViewDidFinishDownload delegate to correctly set the scale factor/zoom level
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGSize contentSize = webView.scrollView.contentSize;
CGSize viewSize = self.view.bounds.size;
float sfactor = viewSize.width / contentSize.width;
webView.scrollView.minimumZoomScale = sfactor;
webView.scrollView.maximumZoomScale = sfactor;
webView.scrollView.zoomScale = sfactor;
}
Hope this Helps !!!