我想用 Gekko 创建一个回归 ANN 模型。我使用 tf_Keras 制作了这个模型,效果非常好。不幸的是,无法将 Keras 模型转换为 Gekko amp 模型。那...
在 JavaScript(服务器端 NodeJS)中,我正在编写一个生成 XML 作为输出的程序。 我通过连接字符串来构建 XML: str += '<' + key + '>'; str += 值; str += ' 在 JavaScript(服务器端 NodeJS)中,我正在编写一个生成 XML 作为输出的程序。 我通过连接字符串来构建 XML: str += '<' + key + '>'; str += value; str += '</' + key + '>'; 问题是:如果value包含'&'、'>'或'<'等字符怎么办? 逃离这些角色的最佳方法是什么? 或者是否有任何 JavaScript 库可以转义 XML 实体? 对于相同的结果,这可能会更有效一些: function escapeXml(unsafe) { return unsafe.replace(/[<>&'"]/g, function (c) { switch (c) { case '<': return '<'; case '>': return '>'; case '&': return '&'; case '\'': return '''; case '"': return '"'; } }); } HTML 编码只是将 &、"、'、< 和 > 字符替换为其实体等效项。顺序很重要,如果您不首先替换 & 字符,您将对某些实体进行双重编码: if (!String.prototype.encodeHTML) { String.prototype.encodeHTML = function () { return this.replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); }; } 如@Johan B.W. de Vries 指出,这会对标签名称产生问题,我想澄清一下,我假设这是用于 value only 相反,如果您想解码 HTML 实体1,请确保在完成其他操作之后将 & 解码为 &,这样就不会双重解码任何实体: if (!String.prototype.decodeHTML) { String.prototype.decodeHTML = function () { return this.replace(/'/g, "'") .replace(/"/g, '"') .replace(/>/g, '>') .replace(/</g, '<') .replace(/&/g, '&'); }; } 1只是基础知识,不包括©到©或其他类似的东西 就图书馆而言。 Underscore.js(或 Lodash,如果您愿意)提供了一个 _.escape 方法来执行此功能。 如果您有 jQuery,这里有一个简单的解决方案: String.prototype.htmlEscape = function() { return $('<div/>').text(this.toString()).html(); }; 像这样使用它: "<foo&bar>".htmlEscape(); -> "<foo&bar>" 您可以使用以下方法。我已将其添加到原型中以便于访问。 我还使用了负前瞻,因此如果您调用该方法两次或更多次,它不会弄乱事情。 用途: var original = "Hi&there"; var escaped = original.EncodeXMLEscapeChars(); //Hi&there 解码由 XML 解析器自动处理。 方法: //String Extenstion to format string for xml content. //Replces xml escape chracters to their equivalent html notation. String.prototype.EncodeXMLEscapeChars = function () { var OutPut = this; if ($.trim(OutPut) != "") { OutPut = OutPut.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'"); OutPut = OutPut.replace(/&(?!(amp;)|(lt;)|(gt;)|(quot;)|(#39;)|(apos;))/g, "&"); OutPut = OutPut.replace(/([^\\])((\\\\)*)\\(?![\\/{])/g, "$1\\\\$2"); //replaces odd backslash(\\) with even. } else { OutPut = ""; } return OutPut; }; 注意,如果 XML 中有 XML,那么所有的正则表达式都不好。 相反,循环字符串一次,并替换所有转义字符。 这样,您就不能两次碰到同一个角色。 function _xmlAttributeEscape(inputString) { var output = []; for (var i = 0; i < inputString.length; ++i) { switch (inputString[i]) { case '&': output.push("&"); break; case '"': output.push("""); break; case "<": output.push("<"); break; case ">": output.push(">"); break; default: output.push(inputString[i]); } } return output.join(""); } 我最初在生产代码中使用了已接受的答案,发现大量使用时它实际上非常慢。这是一个更快的解决方案(以两倍以上的速度运行): var escapeXml = (function() { var doc = document.implementation.createDocument("", "", null) var el = doc.createElement("temp"); el.textContent = "temp"; el = el.firstChild; var ser = new XMLSerializer(); return function(text) { el.nodeValue = text; return ser.serializeToString(el); }; })(); console.log(escapeXml("<>&")); //<>& 也许你可以试试这个, function encodeXML(s) { const dom = document.createElement('div') dom.textContent = s return dom.innerHTML } 参考 添加 ZZZZBov 的答案,我发现这更干净,更容易阅读: const encodeXML = (str) => str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); 此外,所有五个字符都可以在这里找到,例如:https://www.sitemaps.org/protocol.html 请注意,这仅对值进行编码(如其他人所述)。 现在我们有了字符串插值和其他一些现代化改进,现在是时候进行更新了。并使用对象查找,因为它确实应该这样做。 const escapeXml = (unsafe) => unsafe.replace(/[<>&'"]/g, (c) => `&${({ '<': 'lt', '>': 'gt', '&': 'amp', '\'': 'apos', '"': 'quot' })[c]};`); 从技术上讲,&、 不是有效的 XML 实体名称字符。如果您不能信任关键变量,则应该将其过滤掉。 < and >如果您希望它们作为 HTML 实体转义,您可以使用类似 http://www.strictly-software.com/htmlencode . 如果之前有东西被逃脱,你可以尝试这个,因为这不会像许多其他人那样双重逃脱 function escape(text) { return String(text).replace(/(['"<>&'])(\w+;)?/g, (match, char, escaped) => { if(escaped) { return match; } switch(char) { case '\'': return '''; case '"': return '"'; case '<': return '<'; case '>': return '>'; case '&': return '&'; } }); } 这很简单: sText = ("" + sText).split("<").join("<").split(">").join(">").split('"').join(""").split("'").join("'");
我有这个组件来检查设备大小 从“$lib/stores”导入{deviceSize}; 让内部宽度; $:如果(内部宽度> = 1652){ ...</desc> <question vote="0"> <p>我有这个组件来检查设备尺寸</p> <pre><code><script lang="ts"> import { deviceSize } from "$lib/stores"; let innerWidth; $: if (innerWidth >= 1652) { $deviceSize = { xl: true, lg: false, md: false, dsm: false, sm: false, }; } else if (innerWidth >= 1240 && innerWidth < 1652) { $deviceSize = { xl: false, lg: true, md: false, dsm: false, sm: false, }; } else if (innerWidth >= 794 && innerWidth < 1240) { $deviceSize = { xl: false, lg: false, md: true, dsm: false, sm: false, }; } else if (innerWidth >= 640 && innerWidth < 794) { $deviceSize = { xl: false, lg: false, md: false, dsm: true, sm: false, }; } else { $deviceSize = { xl: false, lg: false, md: false, dsm: false, sm: true, }; } $: console.log(innerWidth); </script> <svelte:window bind:innerWidth /> </code></pre> <p>和像这样的应用程序组件</p> <p><App.svelte></p> <pre><code><script> const { lg, xl } = $deviceSize; $: isDesktop = xl || lg; </script> {#if isDesktop} <DesktopComponent/> {/if} {#if !isDesktop} <MobileComponent/> {/if} </code></pre> <p><a href="https://i.stack.imgur.com/6iNXn.png" target="_blank"><img src="https://cdn.txt58.com/i/AWkuc3RhY2suaW1ndXIuY29tLzZpTlhuLnBuZw==" alt="enter image description here"/></a></p> <p>我的问题是innerWidth在初始加载中总是未定义。所以 isDesktop = false,那么即使我使用桌面,也始终渲染 MobileComponent。请帮我解决这个问题。</p> <p>我尝试为 <pre><code>deviceSize</code></pre> 商店设置默认值,但无法按我想要的方式工作,它始终呈现为我使用的任何设备(PC、移动设备)的默认条件。</p> </question> <answer tick="false" vote="0"> <p>根据<a href="https://svelte.dev/docs/svelte-components#:%7E:text=Reactive%20statements%20run%20after%20other%20script%20code%20and%20before%20the%20component%20markup%20is%20rendered%2C" rel="nofollow noreferrer">svelte 文档</a>:</p> <blockquote> <p>反应式语句在其他脚本代码之后、渲染组件标记之前运行</p> </blockquote> <p>意味着 if-else 块在创建 <pre><code>svelte:window</code></pre> 绑定之前运行一次,此时 <pre><code>innerWidth</code></pre> 未定义。</p> <p>为了避免这种情况,您可以将 <pre><code>innerWidth</code></pre> 初始化为正确的值,例如更换</p> <pre><code>let innerWidth; </code></pre> <p>与</p> <pre><code>let innerWidth = window.innerWidth; </code></pre> <p>也就是说,通过使用 <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries" rel="nofollow noreferrer">CSS 媒体查询</a>(而不是 JavaScript)来显示和隐藏标记,您可能会让您的生活变得更轻松。</p> </answer> </body></html>
encodeURIComponent 的结果在服务器端未正确解码
我正在努力正确编码/解码 JSON 字符串,以便通过 GET 请求中的查询字符串发送。 ...</desc> <question vote="0"> <p>我正在努力正确编码/解码 JSON 字符串,以便通过 GET 请求中的查询字符串发送。</p> <pre><code><html> <head> <script type="text/javascript"> function executeRequest(applyUriEncode) { var json = '{"foo":"💀🍕⚡💎&🎁❤很久很久以前"}'; var xmlhttp = new XMLHttpRequest(); xmlhttp.open('GET', 'https://example.com/test.php?json='+(applyUriEncode ? encodeURIComponent(json) : json), false); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { console.log("applyUriEncode: "+(applyUriEncode ? "true\n" : "false\n")); console.log(xmlhttp.responseText+"\n"); } }; xmlhttp.send(); } </script> </head> <body> <button onClick="executeRequest(true);">Submit encoded</button> <button onClick="executeRequest(false);">Submit unencoded</button> </body> </html> </code></pre> <pre><code><?php // test.php echo $_GET['json']; </code></pre> <p>点击<pre><code>Submit encoded</code></pre>和<pre><code>Submit unencoded</code></pre>时的输出:</p> <pre><code>applyUriEncode: true {"foo":"💀ðŸ•âš¡ðŸ’Ž&ðŸŽâ¤å¾ˆä¹…很久以å‰"} applyUriEncode: false {"foo":"💀🍕⚡💎 </code></pre> <p>期望的输出是</p> <pre><code>{"foo":"💀🍕⚡💎&🎁❤很久很久以前"} </code></pre> <p>我需要对 JSON 进行编码,否则,特殊字符(例如 <pre><code>&</code></pre>)会破坏字符串。然而,PHP 似乎没有正确解码 <pre><code>encodeURIComponent</code></pre> 的结果。我在服务器端尝试了 <pre><code>urldecode</code></pre>,但这并没有改变任何事情(输出保持不变)。</p> <p>我觉得这是一个基本问题,在 StackOverflow 上应该有答案,但我找不到。我发现了大量具有类似问题的问题,但没有一个问题能让我找到针对这个特定问题的解决方案。</p> </question> <answer tick="false" vote="0"> <p>您遇到的问题与字符编码有关。当您在 JavaScript 中使用 <pre><code>encodeURIComponent</code></pre> 时,它会正确对 JSON 字符串(包括 Unicode 字符)进行百分比编码。但是,当 PHP 接收查询字符串时,它不会自动将百分比编码的 Unicode 字符解码回其原始形式。</p> <p>要解决此问题,您需要确保 PHP 将传入数据解释为 UTF-8,然后使用 <pre><code>urldecode</code></pre> 解码百分比编码的字符串。以下是如何修改 PHP 代码以获得所需的输出:</p> <pre><code><?php // test.php // Get the raw, percent-encoded JSON string from the query parameter $encodedJson = $_GET['json']; // Manually decode the percent-encoded string $decodedJson = urldecode($encodedJson); // Ensure that the string is treated as UTF-8 $decodedJson = mb_convert_encoding($decodedJson, 'UTF-8', 'UTF-8'); // Output the decoded JSON string echo $decodedJson; </code></pre> <p>此代码片段假设您的 PHP 环境配置为使用 UTF-8 作为默认字符编码。如果不是,您可能需要在脚本开头使用 <pre><code>mb_internal_encoding('UTF-8')</code></pre> 将字符编码显式设置为 UTF-8。</p> <p>此外,需要注意的是,当您在查询字符串中发送 JSON 数据时,应始终使用 <pre><code>encodeURIComponent</code></pre> 对 JSON 字符串进行编码。这是因为查询字符串具有某些保留字符(如 <pre><code>&</code></pre>、<pre><code>=</code></pre>、<pre><code>+</code></pre>、<pre><code>?</code></pre> 等),如果不进行编码,可能会破坏 URL 的结构。 <pre><code>encodeURIComponent</code></pre> 函数确保这些字符被安全编码,这样它们就不会干扰 URL 的格式。</p> <p>在客户端,当将 <pre><code>encodeURIComponent</code></pre> 标志设置为 <pre><code>applyUriEncode</code></pre> 时,您的 JavaScript 代码使用 <pre><code>true</code></pre> 是正确的。始终使用编码版本在查询字符串中发送数据,以避免特殊字符出现问题。</p> </answer> </body></html>
Javascript 函数 openFullscreen() ,如何让它在页面上的多个 iframe 上工作
在页面上我有一个 iframe,src 中有 *.pdf 文件。 <p>在页面上我有一个 iframe,src 中有 *.pdf 文件。</p> <pre><code><div class="node--view-mode-full"> <p><iframe allow="fullscreen" allowfullscreen="" frameborder="0" height="980" scrolling="no" src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" width="660"></iframe></p> <p><iframe allow="fullscreen" allowfullscreen="" frameborder="0" height="980" scrolling="no" src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" width="660"></iframe></p> </div> </code></pre> <p>浏览器中内置的 pdf 查看器现在不支持 iframe 中的全屏模式。</p> <p>我找到了解决方案<a href="https://www.w3schools.com/howto/howto_js_fullscreen.asp" rel="nofollow noreferrer">https://www.w3schools.com/howto/howto_js_fullscreen.asp</a>,解决了问题 - 以全屏模式打开 iframe。在 w3schools 的示例中,打开 iframe 的按钮已存在于 HTML <a href="https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen" rel="nofollow noreferrer">https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen</a>.</p> <p>在我的解决方案中,我通过 javascript 添加按钮,因为带有 iframe 的页面已经存在,但没有此类按钮:</p> <pre><code>jQuery(document).ready(function($){ $(".node--view-mode-full iframe[src*='.pdf']").each(function (index) { $(this).addClass('fullscreenframe'); $(this).attr('id', 'fullscreen-'+index); $('<button onclick="openFullscreen()">Open in Fullscreen Mode</button>&nbsp;<strong>Tip:</strong> Press the "Esc" key to exit full screen.<br>').insertBefore(this); }); }); </code></pre> <p>然后添加一个全屏打开 iframe 的功能(与 w3schools 相同):</p> <pre><code>function openFullscreen() { var elem = document.getElementsByClassName("fullscreenframe")[0]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } }; </code></pre> <p>当页面上只有一个带有 *.pdf 的 iframe 时,Everysing 工作正常。但是,当我在页面上有两个或多个 iframe,并且单击任何 iframe 附近的“以全屏模式打开”任何按钮时,我总是在全屏模式下只看到第一个 *.pdf...</p> <p>我知道,这是因为我只得到 elem = document.getElementsByClassName("fullscreenframe")[0]; 中的第一个 iframe;</p> <p>我知道我需要使用类似的每个或类似的东西,但我无法解决它。在搜索关于页面上一个全屏元素的所有解决方案时,没有关于页面上多个元素的解决方案...谢谢。</p> </question> <answer tick="true" vote="0"> <p>也许是这样的:</p> <pre><code>jQuery(document).ready(function($){ $(".node--view-mode-full iframe[src*='.pdf']").each(function (index) { $(this).addClass('fullscreenframe'); $(this).attr('id', 'fullscreen-'+index); $('<button onclick="openFullscreen(' + index + ')">Open in Fullscreen Mode</button>&nbsp;<strong>Tip:</strong> Press the "Esc" key to exit full screen.<br>').insertBefore(this); }); }); function openFullscreen(index) { var elem = document.getElementsByClassName("fullscreenframe")[index]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } } </code></pre> </answer> <answer tick="false" vote="0"> <p>为什么不整合 jQuery?</p> <pre><code>const fullScreen = element => element.requestFullScreen(); // all modern browsers $(function(){ $(".node--view-mode-full iframe[src*='.pdf']").each(function (index) { $(this).addClass('fullscreenframe'); $(this).attr('id', 'fullscreen-'+index); $('<button class="fullScreen">Open in Fullscreen Mode</button>&nbsp;<strong>Tip:</strong> Press the "Esc" key to exit full screen.<br>').insertBefore(this); }); $(".fullScreen").on("click", function() { const $iFrame = $(this).closest('p').find('iframe.fullscreenframe'); if ($iFrame) fullScreen($iFrame.get(0)); // pass the DOM element }); }); </code></pre> </answer> </body></html>
Svelte slot 的功能是否像 vanilla-js/dom 一样(我似乎无法让它工作)。 在 html/js 中我可以这样做: 身体{颜色:红色;} /* 从外部设置暴露部分的样式 */ ...</desc> <question vote="0"> <p>Svelte <pre><code>slot</code></pre>的功能是否像 vanilla-js/dom 一样(我似乎无法让它工作)。</p> <p>在 html/js 中我可以做:</p> <p></p><div data-babel="false" data-lang="js" data-hide="false" data-console="true"> <div> <pre><code><style> body {color: red;} /* style exposed part from outside */ my-element::part(header) {color: green;} </style> <h1>Hello World</h1> <my-element> <div slot="header"><strong>Header</strong></div> <div slot="body">Body</div> </my-element> <script> customElements.define('my-element', class extends HTMLElement { constructor() { super(); const shadowRoot = this.attachShadow({mode: 'open'}); shadowRoot.innerHTML = ` <style> .container { border: solid 1px blue; padding: 5px; position: relative; &:after { content: "my-element"; display: block; position: absolute; bottom: -.5em; right: 5px; border: inherit; background-color: white; padding: inherit; } } /* style inserted/slotted part from inside */ [part="body"] ::slotted(div) { background-color: lightyellow; } </style> <div class="container"> <header part="header"><slot name="header"></slot></header> <hr> <div part="body"><slot name="body"></slot></div> </div> `; } }); </script></code></pre> </div> </div> <p></p> <p>其中 <pre><code>h1</code></pre> 的全局样式为红色,标有 <pre><code>part="header"</code></pre> 的元素从外部设置为绿色,插入 <pre><code>slot="body"</code></pre> 的内容从内部(shadow dom)设置为绿色有浅黄色背景。</p> <p>我不知道如何在 svelte 中执行任何这种(受控)跨界样式? (例如,当使用 <pre><code>AppShell::part(content)</code></pre> 时,我收到错误:</p> <pre><code>[plugin:vite-plugin-svelte] C:/srv/svelte/yoda5/src/routes/+layout.svelte:23:18 Expected a valid CSS identifier C:/srv/svelte/yoda5/src/routes/+layout.svelte:23:18 21 | 22 | <style> 23 | AppShell::part(content) { | ^ </code></pre> </question> <answer tick="false" vote="0"> <p>这里有关于<a href="https://learn.svelte.dev/tutorial/slots" rel="nofollow noreferrer">老虎机的课程</a>。最好参考该工具的文档。 Svelte 的学习网站非常棒。</p> <pre><code>// Slotted component, say Test.svelte. <div class="private-parent"> <slot /> </div> <style> div.private-parent { color: blue; } </style> </code></pre> <p>然后,您使用该组件:</p> <pre><code><script> import Test from './Test.svelte'; </script> <Test> <!-- This is the slot's content --> <p class="outside-style">Hello!</p> </Test> <style> p.outside-style { color: darkred; } </style> </code></pre> </answer> </body></html>