丶视觉

文章 评论 浏览 31

丶视觉 2025-02-21 01:02:24

答案,感谢 @zx485:

cat input.xml | xmlstarlet edit --subnode "//a/b/c" -t elem -n 'd e="data3"'

The answer, thanks to @zx485:

cat input.xml | xmlstarlet edit --subnode "//a/b/c" -t elem -n 'd e="data3"'

与XMLSTARLET添加一个新子节点几乎正确

丶视觉 2025-02-21 00:06:34

Not a perfect solution, but use multi-caret selection:

First double click on您需要的第一个标识符,然后双击持有时的每个以下标识符 alt + shift down。您应该选择所需的所有标识符。使用 cmd/ctrl + c 将它们复制到剪贴板。在formview.add()的括号之间放置套件。不要按住任何钥匙,所以您只剩下一个镜头。粘贴 cmd/ctrl + v 。所有标识符都将粘贴在单独的行上。握住 alt ,然后单击并将鼠标拖动到所选行的末端(最后一条除外)。这应该在每条线的末端添加一个镜头。键入a 在粘贴标识符之间添加逗号,并选择加入行 ctrl + shift ++ j 放置一条线上的呼叫。

这应该比输入所有内容要少得多。

Not a perfect solution, but use multi-caret selection:

First double click on the first identifier you need, then double click on each following identifier while holding Alt+Shift down. You should have all the identifiers you need selected. Copy them to the clipboard using Cmd/Ctrl+C. Put the caret between the parentheses of formview.add(). Don't hold any keys down, so you have only a single caret left. Paste Cmd/Ctrl+V. All identifiers will be pasted on separate lines. Hold Alt and click and drag the mouse past the end of the selected lines (except the last one). This should add a caret at the end of every line. Type a , to add a comma between the pasted identifiers and optionally join lines Ctrl+Shift+J to put the call on a single line.

This should be quite a bit less work than typing everything out.

Intellij复制类字段名称并将其粘贴到方法中?

丶视觉 2025-02-20 23:29:04

当找不到元素时,document.queryselector将返回null。因此,您可以检查变量是否等于NULL。

var open_menu = document.querySelector("#open-menu")
…
if (open_menu != null) {
  open_menu.addEventListener("click", …)
} else {
  // the open_menu element doesn't exist
}

然后重复需要使用的每个元素。

或者,如果您使用的是javaScript的较新版本,则可以使用可选的链接。

open_menu?.addEventListener("click", …)

缺点是,如果Open_Menu是 无效的。

When the element can't be found, document.querySelector will return null. So, you can check to see if the variable is equal to null.

var open_menu = document.querySelector("#open-menu")
…
if (open_menu != null) {
  open_menu.addEventListener("click", …)
} else {
  // the open_menu element doesn't exist
}

Then repeat that for each element you need to use.

Or, if you are using a newer version of JavaScript, you can use optional chaining.

open_menu?.addEventListener("click", …)

The downside of that is that you can't do anything if open_menu is null.

如何使用JavaScript检查页面上元素的存在?

丶视觉 2025-02-20 22:31:46

由于Matching_ingr_zing.py已经在src目录中,因此您不需要在File Emport Expiction的开头就添加src

简单地做:

from services.ingredient_extractor_for_search.py import ... as ... 

Since matching_ingr_zing.py is already inside the src directory, you don't need to add src at the beginning of file import anymore.

Simply do:

from services.ingredient_extractor_for_search.py import ... as ... 

VSCODE PYTHON -MODULENOTFOUNDERROR:NO模块名为' src'

丶视觉 2025-02-20 17:38:58

这是每个VC ++程序员一次又一次看到的最令人困惑的错误消息之一。让我们首先使事情变得清晰。

a。什么是符号?
简而言之,符号是一个名称。它可以是一个变量名称,函数名称,类名称,typedef名称或除了属于C ++语言的那些名称和标志之外的任何内容。它是由依赖项库(另一个用户定义)定义或介绍的用户。

b。什么是外部?
在VC ++中,每个源文件(.cpp,.c等)被视为翻​​译单元,编译器一次编译一个单元,并为当前翻译单元生成一个对象文件(.OBJ)。 (请注意,包含此源文件的每个标头文件都将进行预处理,并将被视为该翻译单元的一部分)翻译单元中的所有内容都被视为内部,其他所有内容都被视为外部。在C ++中,您可以使用extern__ extspec(dllimport)等关键字来引用外部符号。

c。什么是“解决”?
解析是一个链接时间。在链接时间时,链接器试图找到对象文件中无法在内部找到其定义的每个符号的外部定义。此搜索过程的范围包括:

  • 在编译时间中生成的所有对象文件,
  • 所有库(.lib)是明确或隐式的
    指定为该建筑物应用程序的其他依赖关系。

此搜索过程称为Resolve。

d。最后,为什么未解决的外部符号?
如果链接器无法找到没有内部定义的符号的外部定义,则报告未解决的外部符号错误。

e。 LNK2019的可能原因:未解决的外部符号错误。
我们已经知道,此错误是由于链接器未能找到外部符号的定义,因此可能的原因可以按以下方式排序:

  1. 将其排序。

例如,如果我们具有在A.CPP中定义的称为FOO的函数,则

int foo()
{
    return 0;
}

可以 我们要调用function foo,因此我们添加

void foo();

到声明函数foo(),然后在另一个功能主体中调用它,例如bar()

void bar()
{
    foo();
}

现在,当您构建此代码时,您将获得LNK2019错误那Foo是一个未解决的符号。在这种情况下,我们知道FOO()在A.CPP中具有其定义,但与我们所调用的定义不同(不同的返回值)。存在定义的情况。

  1. 则不存在定义

如果我们要在库中调用某些函数, ,但是未将导入库添加到附加依赖项列表中(设置为:project | properties |配置属性|链接|链接|输入|附加依赖关系)您的项目设置。现在,链接器将报告LNK2019,因为该定义在当前搜索范围中不存在。

This is one of most confusing error messages that every VC++ programmers have seen time and time again. Let’s make things clarity first.

A. What is symbol?
In short, a symbol is a name. It can be a variable name, a function name, a class name, a typedef name, or anything except those names and signs that belong to C++ language. It is user defined or introduced by a dependency library (another user-defined).

B. What is external?
In VC++, every source file (.cpp,.c,etc.) is considered as a translation unit, the compiler compiles one unit at a time, and generate one object file(.obj) for the current translation unit. (Note that every header file that this source file included will be preprocessed and will be considered as part of this translation unit)Everything within a translation unit is considered as internal, everything else is considered as external. In C++, you may reference an external symbol by using keywords like extern, __declspec (dllimport) and so on.

C. What is “resolve”?
Resolve is a linking-time term. In linking-time, linker attempts to find the external definition for every symbol in object files that cannot find its definition internally. The scope of this searching process including:

  • All object files that generated in compiling time
  • All libraries (.lib) that are either explicitly or implicitly
    specified as additional dependencies of this building application.

This searching process is called resolve.

D. Finally, why Unresolved External Symbol?
If the linker cannot find the external definition for a symbol that has no definition internally, it reports an Unresolved External Symbol error.

E. Possible causes of LNK2019: Unresolved External Symbol error.
We already know that this error is due to the linker failed to find the definition of external symbols, the possible causes can be sorted as:

  1. Definition exists

For example, if we have a function called foo defined in a.cpp:

int foo()
{
    return 0;
}

In b.cpp we want to call function foo, so we add

void foo();

to declare function foo(), and call it in another function body, say bar():

void bar()
{
    foo();
}

Now when you build this code you will get a LNK2019 error complaining that foo is an unresolved symbol. In this case, we know that foo() has its definition in a.cpp, but different from the one we are calling(different return value). This is the case that definition exists.

  1. Definition does not exist

If we want to call some functions in a library, but the import library is not added into the additional dependency list (set from: Project | Properties | Configuration Properties | Linker | Input | Additional Dependency) of your project setting. Now the linker will report a LNK2019 since the definition does not exist in current searching scope.

什么是未定义的参考/未解决的外部符号错误,我该如何修复?

丶视觉 2025-02-20 15:21:37

如果您检查服务器日志,您可能会看到专门抱怨不渗透的参数。您需要一次允许所有必需的键。

devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :phone, :schoolNumber, :surname, :email, :password, :password_confirmation])

If you check the server logs, you might see devise complaining about unpermitted params. You'll need to permit all the required keys at once.

devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :phone, :schoolNumber, :surname, :email, :password, :password_confirmation])

设计注册不在铁轨上的红宝石上工作

丶视觉 2025-02-20 00:47:33

您可以使用:

df.melt(['Period:', 'symbol']).groupby(['symbol','variable', 'Period:'])['value'].agg(lambda x: x).unstack('Period:').reset_index().rename_axis(index=None, columns=None).rename(columns={'variable':'Period'})

输出:

symbol  Period  Value1  Value2  Value3
0   a   2011    10  21  20
1   a   2012    12  45  19
2   a   2013    12  45  19
3   b   2011    10  39  15
4   b   2012    10  39  15
5   b   2013    10  39  16

You can use:

df.melt(['Period:', 'symbol']).groupby(['symbol','variable', 'Period:'])['value'].agg(lambda x: x).unstack('Period:').reset_index().rename_axis(index=None, columns=None).rename(columns={'variable':'Period'})

Output:

symbol  Period  Value1  Value2  Value3
0   a   2011    10  21  20
1   a   2012    12  45  19
2   a   2013    12  45  19
3   b   2011    10  39  15
4   b   2012    10  39  15
5   b   2013    10  39  16

熊猫枢轴表排列没有sympbol的聚合

丶视觉 2025-02-19 22:19:43

excel表单元格的返回标头(字符串)

”在此处输入图像描述

  • 您可以使用StrtableCellheader函数。假设您对为什么失败的原因不感兴趣,即返回一个空字符串,它被简化了('Dirty')。
Option Explicit

Function StrTableCellHeader(ByVal Cell As Range) As String
    On Error Resume Next ' defer error trapping
    StrTableCellHeader = CStr(Cell.EntireColumn _
        .Rows(Cell.ListObject.HeaderRowRange.Row).Value)
    On Error GoTo 0 ' disable error trapping
End Function

Sub StrTableCellHeaderTEST()
    Dim Cell As Range: Set Cell = Range("B5")
    Debug.Print StrTableCellHeader(Cell)
    ' or just e.g.:
    Debug.Print StrTableCellHeader(Range("G3"))
    ' Results:
    ' Col2
    ' Col7
End Sub

Sub StrTableCellHeaderTESTErrors()
    ' The following 'Debug.Print' lines return an empty string,
    ' the default value of 'StrTableCellHeader' since an error occurred
    ' in the function.
    
    Dim Cell As Range
    
    ' The cell is 'Nothing' (e.g. forgotten to create a reference)
    ' ('.EntireRow' failed).
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '91': Object variable or With block variable not set
    
    ' The cell is not in an Excel table ('.ListObject' failed).
    Set Cell = Range("L10")
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '91': Object variable or With block variable not set
    
    ' 'Cell' is not a single cell
    ' ('CStr' failed because '.Value' is an array, not a simple data type).
    Set Cell = Range("A1:B2")
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '13': Type mismatch

End Sub

Return Header (String) of an Excel Table Cell

enter image description here

  • You could use the StrTableCellHeader function. It is simplified ('dirty') under the assumption that you're not interested in why it may have failed i.e. returned an empty string.
Option Explicit

Function StrTableCellHeader(ByVal Cell As Range) As String
    On Error Resume Next ' defer error trapping
    StrTableCellHeader = CStr(Cell.EntireColumn _
        .Rows(Cell.ListObject.HeaderRowRange.Row).Value)
    On Error GoTo 0 ' disable error trapping
End Function

Sub StrTableCellHeaderTEST()
    Dim Cell As Range: Set Cell = Range("B5")
    Debug.Print StrTableCellHeader(Cell)
    ' or just e.g.:
    Debug.Print StrTableCellHeader(Range("G3"))
    ' Results:
    ' Col2
    ' Col7
End Sub

Sub StrTableCellHeaderTESTErrors()
    ' The following 'Debug.Print' lines return an empty string,
    ' the default value of 'StrTableCellHeader' since an error occurred
    ' in the function.
    
    Dim Cell As Range
    
    ' The cell is 'Nothing' (e.g. forgotten to create a reference)
    ' ('.EntireRow' failed).
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '91': Object variable or With block variable not set
    
    ' The cell is not in an Excel table ('.ListObject' failed).
    Set Cell = Range("L10")
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '91': Object variable or With block variable not set
    
    ' 'Cell' is not a single cell
    ' ('CStr' failed because '.Value' is an array, not a simple data type).
    Set Cell = Range("A1:B2")
    Debug.Print StrTableCellHeader(Cell)
    ' Run-time error '13': Type mismatch

End Sub

从单元格中检索ListObject列

丶视觉 2025-02-19 18:00:43

只需将您传递给V-For循环的值添加并观察魔术即可。这实际上可能不是您想要的,但是应该可以更好地了解您要做的事情。这已经足够了。

var app = new Vue({
  el: '#app',
  data: {
    pageStructure: ['Welcome', 'to', 'vue', 'world']
  },
  methods: {
    printElementDiv(el) {
      console.log(el)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="column in pageStructure">
    <h1>Div: {{column}}</h1>
    <button @click="printElementDiv(column)">Print</button>
  </div>
</div>

Simply add the value you passed to v-for loop and see the magic. This might not actually be what you want, but it should give a better understanding of what you're going to do. This is just enough.

var app = new Vue({
  el: '#app',
  data: {
    pageStructure: ['Welcome', 'to', 'vue', 'world']
  },
  methods: {
    printElementDiv(el) {
      console.log(el)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="column in pageStructure">
    <h1>Div: {{column}}</h1>
    <button @click="printElementDiv(column)">Print</button>
  </div>
</div>

在纸上打印在循环中的元素

丶视觉 2025-02-19 06:33:54

要添加到 colm.anseo 答案,这种映射也被称为线性一致生成器

x n+1 =(ax n +c)mod m

当c≠0时,正确选择的参数允许所有种子值等于m的周期。这种情况才会发生,并且仅在以下情况下:

  • M和C相对较好时,
  • A-1由M的所有主要因素排除,
  • 如果M可以通过4分组4

。 –Dobell定理。

对于64位LCG a = 6364136223846793005和C = 1442695040888963407,来自Knuth看起来不错。

请注意,LCG映射为1-1,它将整个[0 ... 2 64 -1]区域映射到本身。如果需要,可以倒置。作为RNG,它具有独特的跳跃能力。

To add to colm.anseo answer, this kind of mapping is also known as Linear congruential generator.

Xn+1 = (aXn+c) mod m

When c ≠ 0, correctly chosen parameters allow a period equal to m, for all seed values. This will occur if and only if:

  • m and c are relatively prime,
  • a-1 is divisible by all prime factors of m,
  • a-1 is divisible by 4 if m is divisible by 4.

These three requirements are referred to as the Hull–Dobell Theorem.

For 64bit LCG a=6364136223846793005 and c=1442695040888963407 from Knuth looks good.

Note, that LCG mapping is 1-to-1, it maps whole [0...264-1] region to itself. You could invert it if you want. And as RNG it has distinctive ability for jump-ahead.

从没有重复的另一个人中产生确定性的INT

丶视觉 2025-02-19 06:31:30

您可以将随机生成的数字传递给Drawplayer函数,这是一个示例

const randomNum = () => {
    return Math.floor(Math.random() * 6) + 1;
};

diceBtn.addEventListener( "click", () => {
  const diceNum = document.getElementById( "dice-num" );
  const rndNum = randomNum();
  diceNum.innerText = rndNum;
  drawPlayer( rndNum );
});

function drawPlayer( rndNum ) {
  document.querySelectorAll( ".playerBody" ).forEach( element => {
    element.innerText = rndNum;
  });
}
<button id="diceBtn">Roll</button>
<div id="dice-num">#</div>

<div class="playerBody">0</div>
<div class="playerBody">1</div>
<div class="playerBody">2</div>
<div class="playerBody">3</div>
<div class="playerBody">4</div>
<div class="playerBody">5</div>
<div class="playerBody">6</div>

You can pass the random generated number to the drawPlayer function, here's a sample

const randomNum = () => {
    return Math.floor(Math.random() * 6) + 1;
};

diceBtn.addEventListener( "click", () => {
  const diceNum = document.getElementById( "dice-num" );
  const rndNum = randomNum();
  diceNum.innerText = rndNum;
  drawPlayer( rndNum );
});

function drawPlayer( rndNum ) {
  document.querySelectorAll( ".playerBody" ).forEach( element => {
    element.innerText = rndNum;
  });
}
<button id="diceBtn">Roll</button>
<div id="dice-num">#</div>

<div class="playerBody">0</div>
<div class="playerBody">1</div>
<div class="playerBody">2</div>
<div class="playerBody">3</div>
<div class="playerBody">4</div>
<div class="playerBody">5</div>
<div class="playerBody">6</div>

如何使用Math.random在不同地方获得相同的随机数?

丶视觉 2025-02-19 03:27:27

我们已经多次使用颜色来完成此操作,但是可以扩展形状 colors 版式 都相同。

val Shapes = Shapes(
        small = RoundedCornerShape(4.dp),
        medium = RoundedCornerShape(10.dp),
        large = RoundedCornerShape(12.dp)
).apply {
    test = RoundedCornerShape(16.dp)
}

var Shapes.test: CornerBasedShape

这是非常简单的,并且可能没有任何注释。

第一步是为课程创建一个扩展字段。
之后,您可以使用应用方法以自己的价值扩展构造函数调用。

新形状可以像这样的任何其他形状都称为

MaterialTheme.shapes.test

We have done this with our colors multiple times, but it's possible to extend the Shapes, Colors or Typography all the same way.

val Shapes = Shapes(
        small = RoundedCornerShape(4.dp),
        medium = RoundedCornerShape(10.dp),
        large = RoundedCornerShape(12.dp)
).apply {
    test = RoundedCornerShape(16.dp)
}

var Shapes.test: CornerBasedShape

It's very easy and possible without any annotation.

The first step is to create an extension field for the class.
After that you can use the apply method to extend the constructor call with your own value.

The new shape can be called simply like any other shape like this

MaterialTheme.shapes.test

JetPack中的自定义形状大小组成

丶视觉 2025-02-18 16:54:35

通常的事情是从express> express软件包中导入 type express :

import { Express } from "express";

请注意,这只是导入类型而不是函数。然后,您的其余代码是正常的(包括app上的类型)。

如果您没有该类型,请安装Express之类的类型:

npm install --save-dev @types/express

...但是您可能已经完成了。

The usual thing is to import the type Express from the express package:

import { Express } from "express";

Note that that's just importing the type, not the function. The rest of your code is then fine as-is (including the type on app).

If you don't have that type, install the types for express like this:

npm install --save-dev @types/express

...but you've probably already done that.

如何在不导入Express的情况下声明TypeScript中类型的express变量?

丶视觉 2025-02-18 14:28:32

拜托,请尝试下一步。它使用“ adodb.stream”

Sub QuoteCommaExport_()
   Dim DestFile As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long, strLine As String, strTxt As String
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   
   arr = Selection.Value2

   For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            strLine = strLine & ",""" & arr(i, j) & """"
        Next j
        If i = 1 Then
            strTxt = Mid(strLine, 2) & vbCrLf
        Else
            strTxt = strTxt & Mid(strLine, 2) & vbCrLf
        End If
        strLine = ""
   Next i
   strTxt = left(strTxt, Len(strTxt) - 1)

  WriteUTF8NoBOM strTxt, DestFile
End Sub
Sub WriteUTF8NoBOM(strTxt As String, fileName As String)
 Dim UTFStream As Object, BinaryStream As Object
 With CreateObject("ADODB.stream")
    .Type = 2
    .Mode = 3
    .Charset = "UTF-8"
    .LineSeparator = -1
    .Open
    .WriteText strTxt, 1
    .Position = 3 'skip BOM
    Set BinaryStream = CreateObject("adodb.stream")
    BinaryStream.Type = 1
    BinaryStream.Mode = 3
    BinaryStream.Open
    'Strips BOM (first 3 bytes)
    .CopyTo BinaryStream
    .flush
    .Close
 End With
 BinaryStream.SaveToFile fileName, 2
 BinaryStream.flush
 BinaryStream.Close
End Sub

上面的代码将CSV文件保存在文件夹中保留代码的工作簿,并使用“ testfile.csv”的名称使用您想要的任何名称,以您尝试的方式定义或以其他方式定义...

我发布了一种(更复杂的)方法以保存为CSV UTF-8没有BOM。如果带有BOM的UTF-8足够好,请使用下一个(简单)编写sub

Sub writeUTF8BOM(strTxt As String, fileName As String)
   Dim objStream As Object
    With CreateObject("ADODB.Stream")
        .Type = 2
        .Charset = "UTF-8"
        .Open
        .WriteText strTxt, 1
        .SaveToFile fileName, 2
        .Close
    End With
End Sub

您可以测试哪种类型的UTF编码所得文件用途,在Notepad ++中打开它,然后单击'编码''菜单。您会看到编码类型...

再次编辑
下一个版本将直接保存选择为CSV(UTF-8):

Sub QuoteCommaExport()
   Dim DestFile As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   
   arr = Selection.Value2

   For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            arr(i, j) = """" & arr(i, j) & """"
        Next j
   Next i

   ActiveSheet.Copy 'this linw creates a new workbook with the content of the active sheet
   Dim ws As Worksheet, wb As Workbook
   Set wb = ActiveWorkbook: Set ws = wb.Sheets(1)
   ws.cells.Clear
   ws.Range("A1").Resize(UBound(arr), UBound(arr, 2)).Value2 = arr 'drop the processed array content
   wb.saveas fileName:=DestFile, FileFormat:=xlCSVUTF8, Local:=False
   wb.Close False
End Sub

有线的内容,如果您不处理范围(添加双引号),则可以正确保存它,并随心所欲地保存任何非ASCII字符。但是,如果您添加双引号(在wb.cloe false line之前放置一个断点),您将看到正确的(数量)双引号。如果您在记事本+++中打开CSV文件,则字符串在三倍引号之间...

如果尝试在Excel中打开它(作为文本,过滤TXT,RTF,CSV),而“文本限制符”是

>将其 阅读非ASCII字符,因此在保存或删除Exces之后无法放置双引号,因为我认为可能有可能(在我的评论中)...

现在,一个丑陋的解决方案(但工作)是打开保存的CSV在记事本中的文件,按ctrl + H带来查找并替换窗口,写“”“”在左上方的框中和>“在下面的一个中,然后按替换所有,然后保存文件

,我什至不知道是否存在Macos Notepad(很可能,不存在)...也许是一个 程序具有质量替换的选项。

类似的应用 代码>编辑菜单(使用API​​)并启动适当的窗口。如果您确认了记事本应用程序的存在,我将仅出于查看该方案而尝试此方案。我敢肯定,在此步骤之前,我可以没有更多并发症。查找替换窗口的句柄,自动写入要使用的字符串,然后按编程方式按必要的按钮,可能会更复杂...

最终编辑(我希望.. 。):

请测试下一个版本,该版本(理论上)也应该在MacOS中使用。它使用函数将字节数组(要保存的字符串)转换为一个字节数组,该字节数组可以写入以创建UTF8编码文件。然后,另一个功能将转换的字节数组写入文件:

Sub ExportSelectionAsUTF8CSV()
   Dim DestFile As String, strLine As String, strTxt As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   If Selection.cells.count < 2 Then Exit Sub 'It does not treat the case of a single cell...
   
   arr = Selection.Value2
   
    For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            strLine = strLine & ",""" & arr(i, j) & """"
        Next j
        If i = 1 Then
            strTxt = Mid(strLine, 2) & vbCrLf
        Else
            strTxt = strTxt & Mid(strLine, 2) & vbCrLf
        End If
        strLine = ""
   Next i
   strTxt = left(strTxt, Len(strTxt) - 1)
   
   Dim b() As Byte
   b = strTxt 'place the string in a bytes array
   
   WriteByteArrToFile DestFile, UTF8Encode(b) 'encode UTF-8 and write to the file...
 End Sub

Private Function UTF8Encode(b() As Byte) As Byte()
    Dim b1, b2, b3 As Byte         ' UTF8 encoded bytes
    Dim u1, u2 As Byte             ' Unicode input bytes
    Dim out As New Collection      ' Collection to build output array
    Dim i, j As Integer, unicode As Long

    If UBound(b) <= 0 Then
        Exit Function
    End If

    For i = 0 To UBound(b) Step 2
        u1 = b(i)
        u2 = b(i + 1)
        unicode = u2 * 256 + u1

        If unicode < &H80 Then
            ' Boils down to ASCII, one byte UTF-8
            out.Add (u1)
        ElseIf unicode < &H800 Then
            ' Two byte UTF-8
            ' Code path not tested
            b1 = &H80 Or (&H3F And u1)
            b2 = &HC0 Or (Int(u1 / 64)) Or ((&H7 And u2) * 4)
            out.Add (b2) ' Add most significant byte first
            out.Add (b1)
        ElseIf unicode < &H10000 Then
            ' Three byte UTF-8
            ' Thai chars are in this range
            b1 = &H80 Or (&H3F And u1)
            b2 = &H80 Or (Int(u1 / 64)) Or ((&HF And u2) * 4)
            b3 = &HE0 Or (Int(u2 / 16))
            out.Add (b3) ' Add most significant byte first
            out.Add (b2)
            out.Add (b1)
        Else
            Stop ' This case wont arise as VBA strings are 2 byte. If stopped here, something really strange happened...
        End If
    Next

    Dim outBytes() As Byte
    ReDim outBytes(1 To out.count)
    For j = 1 To out.count
        outBytes(j) = CByte(out.Item(j))
    Next
    UTF8Encode = outBytes
End Function

Function WriteByteArrToFile(filePath As String, fileB() As Byte)
    Dim fileNo As Integer: fileNo = FreeFile
     
    If Dir(filePath) <> "" Then Kill filePath   
    Open filePath For Binary Access Write As #fileNo
        Put #fileNo, 1, fileB
    Close #fileNo
End Function

我不是编码函数的“创建者”。我已经形成了几年,我不知道从哪里下载。我不需要它,但是它看起来很有趣,只有在那个时间进行了测试...

请发送一些反馈以确认它在MacOS中也可以正常工作。

Please, try the next way. It places selection in an array (for faster iteration) bo build the necessary string and write is (as UTF-8) using "ADODB.stream":

Sub QuoteCommaExport_()
   Dim DestFile As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long, strLine As String, strTxt As String
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   
   arr = Selection.Value2

   For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            strLine = strLine & ",""" & arr(i, j) & """"
        Next j
        If i = 1 Then
            strTxt = Mid(strLine, 2) & vbCrLf
        Else
            strTxt = strTxt & Mid(strLine, 2) & vbCrLf
        End If
        strLine = ""
   Next i
   strTxt = left(strTxt, Len(strTxt) - 1)

  WriteUTF8NoBOM strTxt, DestFile
End Sub
Sub WriteUTF8NoBOM(strTxt As String, fileName As String)
 Dim UTFStream As Object, BinaryStream As Object
 With CreateObject("ADODB.stream")
    .Type = 2
    .Mode = 3
    .Charset = "UTF-8"
    .LineSeparator = -1
    .Open
    .WriteText strTxt, 1
    .Position = 3 'skip BOM
    Set BinaryStream = CreateObject("adodb.stream")
    BinaryStream.Type = 1
    BinaryStream.Mode = 3
    BinaryStream.Open
    'Strips BOM (first 3 bytes)
    .CopyTo BinaryStream
    .flush
    .Close
 End With
 BinaryStream.SaveToFile fileName, 2
 BinaryStream.flush
 BinaryStream.Close
End Sub

The above code saves the csv file in the folder where the workbook keeping the code exists, with the name "testFile.csv" You may use whatever name you want, defined in the way you try, or in any other way...

I posted a (more complicated) method to save as CSV UTF-8 without BOM. If UTF-8 with BOM is good enough, please use the next (simpler) writing Sub:

Sub writeUTF8BOM(strTxt As String, fileName As String)
   Dim objStream As Object
    With CreateObject("ADODB.Stream")
        .Type = 2
        .Charset = "UTF-8"
        .Open
        .WriteText strTxt, 1
        .SaveToFile fileName, 2
        .Close
    End With
End Sub

You can test what type of UTF encoding the resulted file uses, opening it in Notepad++ and click 'Encoding' menu. You will see there the encoding type...

Edited again:
The next version will save selection as CSV (UTF-8) directly:

Sub QuoteCommaExport()
   Dim DestFile As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   
   arr = Selection.Value2

   For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            arr(i, j) = """" & arr(i, j) & """"
        Next j
   Next i

   ActiveSheet.Copy 'this linw creates a new workbook with the content of the active sheet
   Dim ws As Worksheet, wb As Workbook
   Set wb = ActiveWorkbook: Set ws = wb.Sheets(1)
   ws.cells.Clear
   ws.Range("A1").Resize(UBound(arr), UBound(arr, 2)).Value2 = arr 'drop the processed array content
   wb.saveas fileName:=DestFile, FileFormat:=xlCSVUTF8, Local:=False
   wb.Close False
End Sub

What is wired, if you do not process the range (adding double quotes), it is correctly saved, any non ASCII character being saved as it should. But if you add the double quotes (placing a break point before wb.Cloe False line) you will see the correct (number of) double quotes. If you open the csv file in Notepad+++ the strings are between triple double quotes...

If you try opening it in Excel (as text, filtering txt, rtf, csv) and the 'Text qualifier' is " then it is open as it should... If choose there 'none' the file will be open with each string surrounded by triple double quotes.

Trying to open it using Open x For Input does not correctly read the non ASCII characters, so the double quotes cannot be placed after saving or deleting the exces, as I was supposing to be possible (in my comment)...

Now, an ugly solution (but working) is to open the saved csv file in Notepad, press Ctrl + H to bring Find and Replace window, write """ in the top left box and " in the one below it, then press Replace All followed by saving the file.

Now, I do not even know if in MacOS Notepad exists (most probably, not)... Maybe a similar application having the option to mass replace.

If by chance it exists, I can squeeze my brain and I think I can update the code to automatically open the file in Notepad, find the Replace option in the Edit menu (using API) and launch the appropriate window. I will try this scenario only for the sake of seeing it working, if you confirm the Notepad application existence. I am sure that until this step I can do it without more complications. Finding the handles of the Replace window, automatically write the strings to be used and programmatically press the necessary button, may be more complicated...

Final Edit(I hope...):

Please test the next version, which (theoretically) should work in MacOS, too. It uses a function to convert a Byte array (of the string to be saved) into a byte array that can be written to create a UTF8 Encoded file. Then, another function writes the converted byte array into a file:

Sub ExportSelectionAsUTF8CSV()
   Dim DestFile As String, strLine As String, strTxt As String
   ' Prompt user for destination file name.
   'DestFile = InputBox("Enter the destination filename" _
       & Chr(10) & "(with complete path):", "Quote-Comma Exporter")
   
   DestFile = ThisWorkbook.path & "\testFile.csv"
   If Dir(left(DestFile, InStrRev(DestFile, "\")), vbDirectory) = "" Then _
         MsgBox "The folder where to save the csv file does not exist...": Exit Sub
   Dim arr, i As Long, j As Long
   
   If Not TypeOf Selection Is Range Then Exit Sub 'if something else than a Range is selected...
   If Selection.cells.count < 2 Then Exit Sub 'It does not treat the case of a single cell...
   
   arr = Selection.Value2
   
    For i = 1 To UBound(arr)
        For j = 1 To UBound(arr, 2)
            strLine = strLine & ",""" & arr(i, j) & """"
        Next j
        If i = 1 Then
            strTxt = Mid(strLine, 2) & vbCrLf
        Else
            strTxt = strTxt & Mid(strLine, 2) & vbCrLf
        End If
        strLine = ""
   Next i
   strTxt = left(strTxt, Len(strTxt) - 1)
   
   Dim b() As Byte
   b = strTxt 'place the string in a bytes array
   
   WriteByteArrToFile DestFile, UTF8Encode(b) 'encode UTF-8 and write to the file...
 End Sub

Private Function UTF8Encode(b() As Byte) As Byte()
    Dim b1, b2, b3 As Byte         ' UTF8 encoded bytes
    Dim u1, u2 As Byte             ' Unicode input bytes
    Dim out As New Collection      ' Collection to build output array
    Dim i, j As Integer, unicode As Long

    If UBound(b) <= 0 Then
        Exit Function
    End If

    For i = 0 To UBound(b) Step 2
        u1 = b(i)
        u2 = b(i + 1)
        unicode = u2 * 256 + u1

        If unicode < &H80 Then
            ' Boils down to ASCII, one byte UTF-8
            out.Add (u1)
        ElseIf unicode < &H800 Then
            ' Two byte UTF-8
            ' Code path not tested
            b1 = &H80 Or (&H3F And u1)
            b2 = &HC0 Or (Int(u1 / 64)) Or ((&H7 And u2) * 4)
            out.Add (b2) ' Add most significant byte first
            out.Add (b1)
        ElseIf unicode < &H10000 Then
            ' Three byte UTF-8
            ' Thai chars are in this range
            b1 = &H80 Or (&H3F And u1)
            b2 = &H80 Or (Int(u1 / 64)) Or ((&HF And u2) * 4)
            b3 = &HE0 Or (Int(u2 / 16))
            out.Add (b3) ' Add most significant byte first
            out.Add (b2)
            out.Add (b1)
        Else
            Stop ' This case wont arise as VBA strings are 2 byte. If stopped here, something really strange happened...
        End If
    Next

    Dim outBytes() As Byte
    ReDim outBytes(1 To out.count)
    For j = 1 To out.count
        outBytes(j) = CByte(out.Item(j))
    Next
    UTF8Encode = outBytes
End Function

Function WriteByteArrToFile(filePath As String, fileB() As Byte)
    Dim fileNo As Integer: fileNo = FreeFile
     
    If Dir(filePath) <> "" Then Kill filePath   
    Open filePath For Binary Access Write As #fileNo
        Put #fileNo, 1, fileB
    Close #fileNo
End Function

I am not the 'creator' of the encoding function. I have it form some years and I do not know where from I downloaded. I did not need it, but it looked interesting and only tested that time...

Please, send some feedback to confirm that it works in MacOS as it should, too.

用Excel的双引号导出UTF-8 CSV

丶视觉 2025-02-18 14:27:21

您使用的是旧版本的trix.js(R83)。在该版本中,将深度选项挤出在中被称为nose,如果不存在,则默认为100。如果您将深度更改为金额 intrudeSettings 对象,或(最好是)更改cdn链接以导入更新的three.js的最新版本,您的代码应按预期工作。

You're using an old version of Three.js (r83). In that version, what became the depth option in ExtrudeGeometry was called amount, and it defaults to 100 if it's not present. If you change depth to amount in your extrudeSettings object, or (preferably) change your CDN link to import a more recent version of Three.js, your code should work as expected.

用三J的挤出尺寸错误

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文