问:
Android Studio build error - unable to preview UI in preview window
Frankly speaking, I don't have the knowledge to understand and debug this error. So please inform me if I miss something.

How am I getting to this error:

I wanted to work with compose and see the preview in preview window

I created a new android studio project with empty compose activity

The build was successful but the preview isn't loading. It is just showing "build and refresh" button there.

When I click on the "build and refresh" button android studio starts the build process again and fails with the following message:

```<code>FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
</code>```

on seeing the logs, it still doesn't give me any concrete idea of the problem:

```<code>Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
    /Users/user1/.gradle/caches/transforms-3/ece73d8c62f06068285ab9f622839930/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar (version 1.5)
    /Users/user1/.gradle/caches/transforms-3/eb2652034b57731d1f9e2d78d329ace4/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar (version 1.5)
    /Users/user1/.gradle/caches/transforms-3/201581d8ae804b86784bd93bdadbd711/transformed/jetified-kotlin-stdlib-1.6.10.jar (version 1.6)
    /Users/user1/.gradle/caches/transforms-3/b9df9c1454100a3c8c23b28a1d48a919/transformed/jetified-kotlin-stdlib-common-1.6.10.jar (version 1.6)
</code>```

My app level build.gradle file:

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.composebasics"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

</code>```

and my project level build.gradle file is:

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.1.0'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I don't know how much and how relevant is the information above, but I can add more if required.

答:
In project level gradle change kotlin version for compatibility with compose 1.1.0

classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"

Check this version compatibility

Body:
Frankly speaking, I don't have the knowledge to understand and debug this error. So please inform me if I miss something.

How am I getting to this error:

I wanted to work with compose and see the preview in preview window

I created a new android studio project with empty compose activity

The build was successful but the preview isn't loading. It is just showing "build and refresh" button there.

When I click on the "build and refresh" button android studio starts the build process again and fails with the following message:

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

on seeing the logs, it still doesn't give me any concrete idea of the problem:

Runtime JAR files in the classpath should have the same version. These files were found in the classpath:
    /Users/user1/.gradle/caches/transforms-3/ece73d8c62f06068285ab9f622839930/transformed/jetified-kotlin-stdlib-jdk8-1.5.30.jar (version 1.5)
    /Users/user1/.gradle/caches/transforms-3/eb2652034b57731d1f9e2d78d329ace4/transformed/jetified-kotlin-stdlib-jdk7-1.5.30.jar (version 1.5)
    /Users/user1/.gradle/caches/transforms-3/201581d8ae804b86784bd93bdadbd711/transformed/jetified-kotlin-stdlib-1.6.10.jar (version 1.6)
    /Users/user1/.gradle/caches/transforms-3/b9df9c1454100a3c8c23b28a1d48a919/transformed/jetified-kotlin-stdlib-common-1.6.10.jar (version 1.6)

My app level build.gradle file:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.example.composebasics"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion compose_version
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.1'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

and my project level build.gradle file is:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext {
        compose_version = '1.1.0'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.0.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I don't know how much and how relevant is the information above, but I can add more if required.


来源: stackexchange

问:
How to insert bold quote symbols in HTML
I wanted to insert this bold ❝❞ as you can see on https://fonts.google.com/specimen/Work+Sans?preview.text=%E2%9D%9D%E2%9D%9E%20:

To do that, I quickly came up with this:

* {font-family: 'Work Sans', sans-serif;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">
<h1>❝ Something ❞</h1></code>```

The problem is that when I run that code, it is this that is shown:

What am I missing? Oh, and when I go to this website, more symbols appear like the one below appear!

答:
```<code><html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>HTML</title>

  <!-- HTML -->

  <!-- Custom Styles -->
  <style type="text/css" media="all">
   b::before{
  content: "\201C";
  color: black;
  font-size: 25px;
  font-family: 'Playfair Display', serif;
}

b::after{
  content: "\201D";
  color: black;
  font-size: 25px;
  font-family: 'Playfair Display', serif;
}

  </style>
</head>

<body>
 <p> there is <b>Something</b></p>
  <!-- Project -->
  <script src="main.js"></script>
</body>
</html>```
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wanted to insert this bold ❝❞ as you can see on https://fonts.google.com/specimen/Work+Sans?preview.text=%E2%9D%9D%E2%9D%9E%20:

To do that, I quickly came up with this:

* {font-family: 'Work Sans', sans-serif;}

<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Work+Sans&display=swap" rel="stylesheet">

❝ Something ❞

The problem is that when I run that code, it is this that is shown:

What am I missing? Oh, and when I go to this website, more symbols appear like the one below appear!


问:
How to get StackTrace of called Assert?
I can get StackTrace for Exception. But I don't know how to get StackTrace for Assert. How to find out in which method Assert was called?

My code:

```<code>namespace ConsoleApp1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Diagnostics;
    using System.Runtime.ExceptionServices;

    class MyProgram
    {
        static void Main(string[] agrs)
        {
            AppDomain.CurrentDomain.FirstChanceException += FirstChanceException!;

            var foo = new Foo();

            try
            {
                foo.FuncException();
            }
            catch { }

            try
            {
                foo.FuncAssert();
            }
            catch { }

            AppDomain.CurrentDomain.FirstChanceException -= FirstChanceException!;
        }

        static private void FirstChanceException(object source, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
        {
            var ex = firstChanceExceptionEventArgs.Exception;
            if (ex != null)
                Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
        }

        static private string GetStackTrace(Exception ex)
        {
            var list = new List<string>();

            var trace = new StackTrace(ex, true);
            foreach (var frame in trace.GetFrames())
            {
                list.Add($"{frame.GetMethod()?.ReflectedType?.Name}.{frame.GetMethod()?.Name}");
            }

            return string.Join(" -> ", list);
        }

        public class Foo
        {
            public void FuncException()
            {
                throw new Exception("Exception - FuncException");
            }

            public void FuncAssert()
            {
                Assert.Fail("Assert - FuncAssert");
            }
        }
    }
}
</code>```

答:
You register an event handler for AppDomain.CurrentDomain.FirstChanceException:

```<code>AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;
</code>```

You call Assert.Fail():

```<code>public class Foo
{
    public void FuncAssert()
    {
        Assert.Fail("Assert - FuncAssert");
    }
}
</code>```

I assume that you expect to see the whole call stack in the exception. But call stack is only gathered when exception is bubbling through the stack.

And AppDomain.FirstChanceException catches the exception right in the place where it's thrown.

Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.firstchanceexception

So, I would say that you are trying to do something wrong.

What is the problem that you are actually trying to solve?

This code will work well because I let exception to bubble along the call stack and be caught:

```<code>try
{
    foo.FuncAssert();
}
catch (Exception ex)
{
    Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
}
</code>```

Output:

Message: Assert - FuncAssert

StackTrace: Assert.ReportFailure -> Assert.Fail -> Assert.Fail -> Foo.FuncAssert -> MyProgram.Main

Title: How to get StackTrace of called Assert?

Body:
I can get StackTrace for Exception. But I don't know how to get StackTrace for Assert. How to find out in which method Assert was called?

My code:

namespace ConsoleApp1
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System.Diagnostics;
    using System.Runtime.ExceptionServices;

    class MyProgram
    {
        static void Main(string[] agrs)
        {
            AppDomain.CurrentDomain.FirstChanceException += FirstChanceException!;

            var foo = new Foo();

            try
            {
                foo.FuncException();
            }
            catch { }

            try
            {
                foo.FuncAssert();
            }
            catch { }

            AppDomain.CurrentDomain.FirstChanceException -= FirstChanceException!;
        }

        static private void FirstChanceException(object source, FirstChanceExceptionEventArgs firstChanceExceptionEventArgs)
        {
            var ex = firstChanceExceptionEventArgs.Exception;
            if (ex != null)
                Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
        }

        static private string GetStackTrace(Exception ex)
        {
            var list = new List<string>();

            var trace = new StackTrace(ex, true);
            foreach (var frame in trace.GetFrames())
            {
                list.Add($"{frame.GetMethod()?.ReflectedType?.Name}.{frame.GetMethod()?.Name}");
            }

            return string.Join(" -> ", list);
        }

        public class Foo
        {
            public void FuncException()
            {
                throw new Exception("Exception - FuncException");
            }

            public void FuncAssert()
            {
                Assert.Fail("Assert - FuncAssert");
            }
        }
    }
}

Body:
You register an event handler for AppDomain.CurrentDomain.FirstChanceException:

AppDomain.CurrentDomain.FirstChanceException += FirstChanceException;

You call Assert.Fail():

public class Foo
{
    public void FuncAssert()
    {
        Assert.Fail("Assert - FuncAssert");
    }
}

I assume that you expect to see the whole call stack in the exception. But call stack is only gathered when exception is bubbling through the stack.

And AppDomain.FirstChanceException catches the exception right in the place where it's thrown.

Occurs when an exception is thrown in managed code, before the runtime searches the call stack for an exception handler in the application domain.

https://learn.microsoft.com/en-us/dotnet/api/system.appdomain.firstchanceexception

So, I would say that you are trying to do something wrong.

What is the problem that you are actually trying to solve?

This code will work well because I let exception to bubble along the call stack and be caught:

try
{
    foo.FuncAssert();
}
catch (Exception ex)
{
    Console.WriteLine($" * * * \n Message: {ex.Message} \n StackTrace: {GetStackTrace(ex)} \n");
}

Output:

Message: Assert - FuncAssert

StackTrace: Assert.ReportFailure -> Assert.Fail -> Assert.Fail -> Foo.FuncAssert -> MyProgram.Main


问:
What the heck is this: background-image: url("/images/sprites.png?v=3");

Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

```<code>/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }
</code>```

I've seen this used on link tags also on http://html5boilerplate.com/:

```<code>   <link rel="stylesheet" href="css/style.css?v=2">
</code>```

答: Found this URL on the HTML5 boilerplate site you linked.  http://html5boilerplate.com/docs/Version-Control-with-Cachebusting/</p>

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  What's a queryString doing in this stylesheet's href?

Can someone explain the significance and function of the 1) query string and 2) specific name/value pair (e.g. ?v=3) in the css snippet please?

/*Here is the snippet:*/
    .css-class {
       background-image: url("/images/sprites.png?v=3");
    }

I've seen this used on link tags also on http://html5boilerplate.com/:

   <link rel="stylesheet" href="css/style.css?v=2">


问:
Failing to use CXX to link Rust-written library in C++ project
I am testing CXX with a very simple project to link a Rust library into a C++ executable.

I write a foo() -> () Rust function and try to access it from C++ but the linker does not find it.

Here's what I have:

// lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        pub fn foo() -> ();
    }
}

pub fn foo() -> () {
    println!("foo")
}
```
<pre class="lang-toml prettyprint-override"><code># Cargo.toml
[package]
name = "cpprust"
version = "0.1.0"
edition = "2021"

[lib]
name = "cpprust"
path = "src/lib.rs"
crate-type = ["staticlib", "rlib", "dylib"] # EDIT: this is incorrect, see note at the end of question

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
cxx = "1.0"
</code>```

// main.cpp

void foo(); // I tried including lib.rs.h but it was not generated!

int main() {
    foo();
}
```
<p>Running <code>cargo build</code> generates <code>target\debug\libcpprust.so</code>.
I then try to make the project with (EDIT: <code>g++</code> command is incorrect, see note at the end of question):</p>
<pre class="lang-plain prettyprint-override"><code>g++ -L../target/debug/ -lcpprust -o cpprust main.cpp
/tmp/ccOA8kJy.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:2: cpprust] Error 1
</code>```

What is wrong here?

EDIT: prog-fh's great answer correctly points out that I need to include build.rs with C++ compilation, even without having C++ to compile and access within the crate. However, even after implementing their answer, I was still getting the same error message. It turns out that I had two other problems: 1) the order of my arguments to g++ were incorrect, and I needed pthread -l dl as well. It should have been:
g++ -o cpprust main.cpp -I ../target/cxxbridge -L../target/debug -lcpprust -pthread -l dl
2) My Cargo.toml file was also generating "rlib", "dylib" library types, but that somehow also causes the error above; it works when only staticlib is generated.

答:
Considering this documentation, the build.rs script should generate the lib.rs.h which was missing in your attempt.

Note that the example in the documentation considers that the main program comes from Rust, and that the C++ code is an extension.
In your question, it is the opposite situation: your main program comes from C++ but is extended by some Rust code.

This answer is made of two parts:

a minimal example very similar to yours (no C++ code to be called from Rust),

a more complete example with a bidirectional interaction between C++ and Rust (but the main program still is on the C++ side).

edit to answer subsequent questions in the comments

As said in the comment of the second build.rs below, the name chosen in .compile("cpp_from_rust") will be used to name a library containing the compiled C++ code (libcpp_from_rust.a for example).
This library will then be used by Rust to extend the Rust code: the libcpprust.a main target produced by Rust contains libcpp_from_rust.a.

If no C++ file is provided before .compile() (as in the first, minimal example below), this C++ library only contains the symbols enabling extern "Rust" access from C++.

```<code>$ nm ./target/debug/build/cpprust-28371278e6cda5e2/out/libcpp_from_rust.a

lib.rs.o:
                 U _GLOBAL_OFFSET_TABLE_
0000000000000000 T _Z13rust_from_cppv
                 U cxxbridge1$rust_from_cpp
</code>```

On the other hand, you already found in the documentation that multiple invocations of .file() are allowed in order to provide the C++ library with much more code from various source files.

Another question was about the kind of library we want Rust to produce.
This documentation enumerates the various binary targets Rust can produce, especially various kinds of libraries.
Since in your original question you wanted the main executable to be on the C++ side, this means that Rust should produce a library which can be considered as a system library, not a Rust specific one, because Rust won't be involved anymore when generating the executable.
In the aforementioned documentation, we can see that only staticlib and cdylib are suitable for this usage.

In my examples, I chose staticlib for the sake of simplicity, but cdylib can be used too.
However, it is a bit more complicated because, as the main library (libcpprust.so) is generated as a dynamic one, Rust does not insert the C++ library (libcpp_from_rust.a) into it; thus, we have to link against this C++ library, which is not very convenient.

```<code>g++ -std=c++17 -o cpp_program src/main.cpp \
    -I .. -I target/cxxbridge \
    -L target/debug -l cpprust \
    -L target/debug/build/cpprust-28371278e6cda5e2/out -l cpp_from_rust \
    -pthread -l dl
</code>```

And of course, because we are now dealing with a shared library, we have to find it at runtime.

```<code>$ LD_LIBRARY_PATH=target/debug ./cpp_program
</code>```

I don't know whether some other kinds of libraries (crate-type) could work (by chance) with this C++ main program or not, but the documentation states that only staticlib and cdylib are intended for this usage.

Finally, note that if you use crate-type = ["staticlib", "rlib", "dylib"]  in Cargo.toml (as stated in your comment), you will produce three libraries:

target/debug/libcpprust.a from staticlib,

target/debug/libcpprust.rlib from rlib,

target/debug/libcpprust.so from dylib.

Unfortunately, when linking with the command g++ ... -l cpprust ..., the linker will prefer the .so to the .a; you will be in the same situation as cdylib above.

The layout of the directory for the minimal example

```<code>cpprust
├── Cargo.toml
├── build.rs
└── src
    ├── lib.rs
    └── main.cpp
</code>```

Cargo.toml

```<code>[package]
name = "cpprust"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["staticlib"]

[dependencies]
cxx = "1.0"

[build-dependencies]
cxx-build = "1.0"
</code>```

build.rs

```<code>fn main() {
    // This will consider the ffi part in lib.rs in order to
    // generate lib.rs.h and lib.rs.cc
    // minimal example: no C++ code to be called from Rust
    cxx_build::bridge("src/lib.rs")
        .compile("cpp_from_rust");
}
</code>```

src/lib.rs

```<code>#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn rust_from_cpp() -> ();
    }
}

pub fn rust_from_cpp() -> () {
    println!("called rust_from_cpp()");
}
</code>```

src/main.cpp

```<code>/*
  Building this program happens outside of the cargo process.
  We simply need to link against the Rust library and the
  system libraries it depends upon

  g++ -std=c++17 -o cpp_program src/main.cpp \
      -I .. -I target/cxxbridge \
      -L target/debug -l cpprust \
      -pthread -l dl
*/

// consider the ffi part of Rust code
#include "cpprust/src/lib.rs.h"

#include <iostream>

int
main()
{
  std::cout << "starting from C++\n";
  rust_from_cpp();
  std::cout << "finishing with C++\n";
  return 0;
}
</code>```

The cargo build command will generate the libcpprust.a static library in target/debug.
Building the main program simply relies on usual commands, provided that we find the relevant headers and libraries (see the comments in the code).

Note that the C++ source code for the main program is in the src directory here, but it could have been put anywhere else.

The layout of the directory for the bidirectional example

```<code>cpprust
├── Cargo.toml
├── build.rs
└── src
    ├── cpp_from_rust.cpp
    ├── cpp_from_rust.hpp
    ├── lib.rs
    └── main.cpp
</code>```

We just added a pair of .hpp/.cpp files.

build.rs

```<code>fn main() {
    // This will consider the ffi part in lib.rs in order to
    // generate lib.rs.h and lib.rs.cc
    // The generated library (libcpp_from_rust.a) contains the code
    // from cpp_from_rust.cpp and will be inserted into the generated
    // Rust library (libcpprust.a).
    cxx_build::bridge("src/lib.rs")
        .file("src/cpp_from_rust.cpp")
        .flag_if_supported("-std=c++17")
        .compile("cpp_from_rust");
}
</code>```

Note that this time the build process actually handles some C++ code (see below) to be called from Rust.

src/lib.rs

```<code>g++ -std=c++17 -o cpp_program src/main.cpp \
    -I .. -I target/cxxbridge \
    -L target/debug -l cpprust \
    -L target/debug/build/cpprust-28371278e6cda5e2/out -l cpp_from_rust \
    -pthread -l dl
</code>```0

src/cpp_from_rust.hpp

```<code>g++ -std=c++17 -o cpp_program src/main.cpp \
    -I .. -I target/cxxbridge \
    -L target/debug -l cpprust \
    -L target/debug/build/cpprust-28371278e6cda5e2/out -l cpp_from_rust \
    -pthread -l dl
</code>```1

src/cpp_from_rust.cpp

```<code>g++ -std=c++17 -o cpp_program src/main.cpp \
    -I .. -I target/cxxbridge \
    -L target/debug -l cpprust \
    -L target/debug/build/cpprust-28371278e6cda5e2/out -l cpp_from_rust \
    -pthread -l dl
</code>```2

Cargo.toml, src/main.cpp and the build process (cargo build, g++ ...) still are the same as in the previous example.

Body:
I am testing CXX with a very simple project to link a Rust library into a C++ executable.

I write a foo() -> () Rust function and try to access it from C++ but the linker does not find it.

Here's what I have:

// lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        pub fn foo() -> ();
    }
}

pub fn foo() -> () {
    println!("foo")
}

# Cargo.toml
[package]
name = "cpprust"
version = "0.1.0"
edition = "2021"

[lib]
name = "cpprust"
path = "src/lib.rs"
crate-type = ["staticlib", "rlib", "dylib"] # EDIT: this is incorrect, see note at the end of question

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
cxx = "1.0"

// main.cpp

void foo(); // I tried including lib.rs.h but it was not generated!

int main() {
    foo();
}

Running cargo build generates target\debug\libcpprust.so.
I then try to make the project with (EDIT: g++ command is incorrect, see note at the end of question):

g++ -L../target/debug/ -lcpprust -o cpprust main.cpp
/tmp/ccOA8kJy.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:2: cpprust] Error 1

What is wrong here?

EDIT: prog-fh's great answer correctly points out that I need to include build.rs with C++ compilation, even without having C++ to compile and access within the crate. However, even after implementing their answer, I was still getting the same error message. It turns out that I had two other problems: 1) the order of my arguments to g++ were incorrect, and I needed pthread -l dl as well. It should have been:
g++ -o cpprust main.cpp -I ../target/cxxbridge -L../target/debug -lcpprust -pthread -l dl
2) My Cargo.toml file was also generating "rlib", "dylib" library types, but that somehow also causes the error above; it works when only staticlib is generated.

Body:
Considering this documentation, the build.rs script should generate the lib.rs.h which was missing in your attempt.

Note that the example in the documentation considers that the main program comes from Rust, and that the C++ code is an extension.
In your question, it is the opposite situation: your main program comes from C++ but is extended by some Rust code.

This answer is made of two parts:

a minimal example very similar to yours (no C++ code to be called from Rust),

a more complete example with a bidirectional interaction between C++ and Rust (but the main program still is on the C++ side).

edit to answer subsequent questions in the comments

As said in the comment of the second build.rs below, the name chosen in .compile("cpp_from_rust") will be used to name a library containing the compiled C++ code (libcpp_from_rust.a for example).
This library will then be used by Rust to extend the Rust code: the libcpprust.a main target produced by Rust contains libcpp_from_rust.a.

If no C++ file is provided before .compile() (as in the first, minimal example below), this C++ library only contains the symbols enabling extern "Rust" access from C++.

$ nm ./target/debug/build/cpprust-28371278e6cda5e2/out/libcpp_from_rust.a

lib.rs.o:
                 U _GLOBAL_OFFSET_TABLE_
0000000000000000 T _Z13rust_from_cppv
                 U cxxbridge1$rust_from_cpp

On the other hand, you already found in the documentation that multiple invocations of .file() are allowed in order to provide the C++ library with much more code from various source files.

Another question was about the kind of library we want Rust to produce.
This documentation enumerates the various binary targets Rust can produce, especially various kinds of libraries.
Since in your original question you wanted the main executable to be on the C++ side, this means that Rust should produce a library which can be considered as a system library, not a Rust specific one, because Rust won't be involved anymore when generating the executable.
In the aforementioned documentation, we can see that only staticlib and cdylib are suitable for this usage.

In my examples, I chose staticlib for the sake of simplicity, but cdylib can be used too.
However, it is a bit more complicated because, as the main library (libcpprust.so) is generated as a dynamic one, Rust does not insert the C++ library (libcpp_from_rust.a) into it; thus, we have to link against this C++ library, which is not very convenient.

g++ -std=c++17 -o cpp_program src/main.cpp \
    -I .. -I target/cxxbridge \
    -L target/debug -l cpprust \
    -L target/debug/build/cpprust-28371278e6cda5e2/out -l cpp_from_rust \
    -pthread -l dl

And of course, because we are now dealing with a shared library, we have to find it at runtime.

$ LD_LIBRARY_PATH=target/debug ./cpp_program

I don't know whether some other kinds of libraries (crate-type) could work (by chance) with this C++ main program or not, but the documentation states that only staticlib and cdylib are intended for this usage.

Finally, note that if you use crate-type = ["staticlib", "rlib", "dylib"]  in Cargo.toml (as stated in your comment), you will produce three libraries:

target/debug/libcpprust.a from staticlib,

target/debug/libcpprust.rlib from rlib,

target/debug/libcpprust.so from dylib.

Unfortunately, when linking with the command g++ ... -l cpprust ..., the linker will prefer the .so to the .a; you will be in the same situation as cdylib above.

The layout of the directory for the minimal example

cpprust
├── Cargo.toml
├── build.rs
└── src
    ├── lib.rs
    └── main.cpp

Cargo.toml

[package]
name = "cpprust"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["staticlib"]

[dependencies]
cxx = "1.0"

[build-dependencies]
cxx-build = "1.0"

build.rs

fn main() {
    // This will consider the ffi part in lib.rs in order to
    // generate lib.rs.h and lib.rs.cc
    // minimal example: no C++ code to be called from Rust
    cxx_build::bridge("src/lib.rs")
        .compile("cpp_from_rust");
}

src/lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn rust_from_cpp() -> ();
    }
}

pub fn rust_from_cpp() -> () {
    println!("called rust_from_cpp()");
}

src/main.cpp

/*
  Building this program happens outside of the cargo process.
  We simply need to link against the Rust library and the
  system libraries it depends upon

  g++ -std=c++17 -o cpp_program src/main.cpp \
      -I .. -I target/cxxbridge \
      -L target/debug -l cpprust \
      -pthread -l dl
*/

// consider the ffi part of Rust code
#include "cpprust/src/lib.rs.h"

#include <iostream>

int
main()
{
  std::cout << "starting from C++\n";
  rust_from_cpp();
  std::cout << "finishing with C++\n";
  return 0;
}

The cargo build command will generate the libcpprust.a static library in target/debug.
Building the main program simply relies on usual commands, provided that we find the relevant headers and libraries (see the comments in the code).

Note that the C++ source code for the main program is in the src directory here, but it could have been put anywhere else.

The layout of the directory for the bidirectional example

cpprust
├── Cargo.toml
├── build.rs
└── src
    ├── cpp_from_rust.cpp
    ├── cpp_from_rust.hpp
    ├── lib.rs
    └── main.cpp

We just added a pair of .hpp/.cpp files.

build.rs

fn main() {
    // This will consider the ffi part in lib.rs in order to
    // generate lib.rs.h and lib.rs.cc
    // The generated library (libcpp_from_rust.a) contains the code
    // from cpp_from_rust.cpp and will be inserted into the generated
    // Rust library (libcpprust.a).
    cxx_build::bridge("src/lib.rs")
        .file("src/cpp_from_rust.cpp")
        .flag_if_supported("-std=c++17")
        .compile("cpp_from_rust");
}

Note that this time the build process actually handles some C++ code (see below) to be called from Rust.

src/lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        fn rust_from_cpp() -> ();
    }
    unsafe extern "C++" {
        include!("cpprust/src/cpp_from_rust.hpp");
        fn cpp_from_rust() -> ();
    }
}

pub fn rust_from_cpp() -> () {
    println!("entering rust_from_cpp()");
    ffi::cpp_from_rust();
    println!("leaving rust_from_cpp()");
}

src/cpp_from_rust.hpp

#ifndef CPP_FROM_RUST_HPP
#define CPP_FROM_RUST_HPP

// declare a usual C++ function (no Rust involved here)
void
cpp_from_rust();

#endif // CPP_FROM_RUST_HPP

src/cpp_from_rust.cpp

#include "cpp_from_rust.hpp"

#include <iostream>

// define a usual C++ function (no Rust involved here)
void
cpp_from_rust()
{
  std::cout << "called " << __func__ << "()\n";
}

Cargo.toml, src/main.cpp and the build process (cargo build, g++ ...) still are the same as in the previous example.


问:
Using MariaDB temporal tables with spring data jpa native query is not giving me the correct result
```<code>public interface PeseeRepository extends JpaRepository<Pesee, Integer> {
...
    @Query(value = "SELECT * FROM pesee FOR SYSTEM_TIME all WHERE id_pesage = ?1", nativeQuery = true)
    List<Pesee> findAllPeseeHystoryById(Integer id);
...
}
</code>```

Log:

```<code>Hibernate:
SELECT
    *
FROM
    pesee FOR SYSTEM_TIME all
WHERE
    id_pesage = ?
</code>```

result of the native query in my program :

raw sql exemple:

```<code>    SELECT
    *
FROM
    pesee FOR SYSTEM_TIME all
WHERE
    id_pesage = 1879;
</code>```

result in raw sql:

apparently the native jpa query does not return the same result as the standard sql query.

But detects the number of rows correctly.

Here is my question: How to make mariadb table versioning work in my spring boot application?
The goal is simply to return me history of a table.

答:
I found how to solve my problem by going through a lower level query

https://javabydeveloper.com/spring-jdbctemplate-query-examples/#preparedstatementcreator

```<code>public class PeseeMapper implements RowMapper<Pesee> {

    private final OffsetDateTime odt = OffsetDateTime.now(ZoneId.systemDefault());
    private final ZoneOffset zoneOffSet = ZoneOffset.of(String.valueOf(odt.getOffset()));

    @Override
    public Pesee mapRow(ResultSet rs, int rowNum) throws SQLException {

        return new Pesee(

                rs.getTimestamp("date_poids_1").toInstant().atOffset(zoneOffSet),
                rs.getInt("poids_1"),
                rs.getTimestamp("date_poids_2").toInstant().atOffset(zoneOffSet),
                rs.getInt("poids_2"),
                rs.getString("destination"),

                rs.getTimestamp("date_creation").toInstant().atOffset(zoneOffSet),
                rs.getTimestamp("date_modification").toInstant().atOffset(zoneOffSet),
                );
    }
}
</code>```
```<code>public class PeseePreparedStatementCreator implements PreparedStatementCreator, SqlProvider {

    private String sql;
    private Integer param;

    public PeseePreparedStatementCreator(String sql, Integer param) {
        this.sql = sql;
        this.param = param;
    }

    @Override
    public String getSql() {
        return sql;
    }

    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement ps = con.prepareStatement(getSql(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ps.setInt(1, param);
        return ps;
    }

}
</code>```
```<code>@Repository
public class PeseeJDBC {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<Pesee> findAllPeseeHystoryById(Integer id) {

        String sql = "SELECT * FROM pesee FOR SYSTEM_TIME all WHERE id_pesage = ? ORDER BY date_modification DESC";

        return jdbcTemplate.query(new PeseePreparedStatementCreator(sql, id), new PeseeMapper());
    }
}

</code>```

this now returns me the correct result of a temporal table

For the Objects to recover I called on my service in PeseeJDBC and I transmitted it to PeseeMapper
Then in the PeseeMapper class I called findById from my transmitted service. (I did not add this in the example codes so as not to complicate the initial problem)
It's a bit wobbly at the architectural level but it's functional

Body:
public interface PeseeRepository extends JpaRepository<Pesee, Integer> {
...
    @Query(value = "SELECT * FROM pesee FOR SYSTEM_TIME all WHERE id_pesage = ?1", nativeQuery = true)
    List<Pesee> findAllPeseeHystoryById(Integer id);
...
}

Log:

Hibernate:
SELECT
    *
FROM
    pesee FOR SYSTEM_TIME all
WHERE
    id_pesage = ?

result of the native query in my program :

raw sql exemple:

    SELECT
    *
FROM
    pesee FOR SYSTEM_TIME all
WHERE
    id_pesage = 1879;

result in raw sql:

apparently the native jpa query does not return the same result as the standard sql query.

But detects the number of rows correctly.

Here is my question: How to make mariadb table versioning work in my spring boot application?
The goal is simply to return me history of a table.

Body:
I found how to solve my problem by going through a lower level query

https://javabydeveloper.com/spring-jdbctemplate-query-examples/#preparedstatementcreator

public class PeseeMapper implements RowMapper<Pesee> {

    private final OffsetDateTime odt = OffsetDateTime.now(ZoneId.systemDefault());
    private final ZoneOffset zoneOffSet = ZoneOffset.of(String.valueOf(odt.getOffset()));

    @Override
    public Pesee mapRow(ResultSet rs, int rowNum) throws SQLException {

        return new Pesee(

                rs.getTimestamp("date_poids_1").toInstant().atOffset(zoneOffSet),
                rs.getInt("poids_1"),
                rs.getTimestamp("date_poids_2").toInstant().atOffset(zoneOffSet),
                rs.getInt("poids_2"),
                rs.getString("destination"),

                rs.getTimestamp("date_creation").toInstant().atOffset(zoneOffSet),
                rs.getTimestamp("date_modification").toInstant().atOffset(zoneOffSet),
                );
    }
}

public class PeseePreparedStatementCreator implements PreparedStatementCreator, SqlProvider {

    private String sql;
    private Integer param;

    public PeseePreparedStatementCreator(String sql, Integer param) {
        this.sql = sql;
        this.param = param;
    }

    @Override
    public String getSql() {
        return sql;
    }

    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement ps = con.prepareStatement(getSql(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        ps.setInt(1, param);
        return ps;
    }

}

@Repository
public class PeseeJDBC {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<Pesee> findAllPeseeHystoryById(Integer id) {

        String sql = "SELECT * FROM pesee FOR SYSTEM_TIME all WHERE id_pesage = ? ORDER BY date_modification DESC";

        return jdbcTemplate.query(new PeseePreparedStatementCreator(sql, id), new PeseeMapper());
    }
}

this now returns me the correct result of a temporal table

For the Objects to recover I called on my service in PeseeJDBC and I transmitted it to PeseeMapper
Then in the PeseeMapper class I called findById from my transmitted service. (I did not add this in the example codes so as not to complicate the initial problem)
It's a bit wobbly at the architectural level but it's functional


问:
How to find a name with the fourth highest score?
pardon this silly question but I need your help.

I have a list of name, let's say

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']

and their scores are

score = [75,60,80,79,90,30]

How to write the code in Python so if I want to know the fourth highest score the result is

The fourth highest score is Alpha.

Thanks in advance for your help.

答:
You could try the nlargest function from the heapq module:

```<code>from heapq import nlargest

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']
score = [75,60,80,79,90,30]

*_,(_,fourth) = nlargest(4,zip(score,name)) # name of last of top 4

print(fourth) # Alpha
</code>```

Body:
You could try the nlargest function from the heapq module:

from heapq import nlargest

name = ['Alpha','Betta','Chroma','Delta','Echo', 'Froyo']
score = [75,60,80,79,90,30]

*_,(_,fourth) = nlargest(4,zip(score,name)) # name of last of top 4

print(fourth) # Alpha


问:
Double jump issue pygame with get key presses
I have created double jump in a few games now, but always in key events in game loop. This is not working for me here now I have put it into 'get key presses' in player class. I have created the boolean to show '1' when in air, and then reset it back to 0 when jumped while its on '1'. but then when I jump it instantly goes back to 0 so I can infinitely jump.</p>
```<code>#player movement
    self.movement = pygame.math.Vector2()
    self.speed = speed
    self.gravity = 1
    self.collision_sprites = collision_sprites
    self.grounded = False
    self.jump_counter = 0

def input(self):
    keys = pygame.key.get_pressed()

    if keys[pygame.K_d]:
        self.movement.x = 1
    elif keys[pygame.K_a]:
        self.movement.x = -1
    else:
        self.movement.x = 0

    if keys[pygame.K_w] and self.grounded == True:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 1

    if keys[pygame.K_w] and self.jump_counter == 1:
        self.movement.y = -JUMP_SPEED

        self.jump_counter = 0

    print(self.jump_counter)

def x_collisions(self):
    for sprite in self.collision_sprites.sprites():
        if sprite.rect.colliderect(self.rect):
            if self.movement.x < 0:
                self.rect.left = sprite.rect.right
            if self.movement.x > 0:
                self.rect.right = sprite.rect.left

def y_collisions(self):
    for sprite in self.collision_sprites.sprites():
        if sprite.rect.colliderect(self.rect):
            if self.movement.y > 0:
                self.rect.bottom = sprite.rect.top
                self.grounded = True
                self.jump_counter = 0
                self.movement.y = 0
            if self.movement.y < 0:
                self.rect.top = sprite.rect.bottom
                self.movement.y = 0

    if self.grounded == True and self.movement.y != 0:
        self.grounded = False

def apply_gravity(self):
    self.movement.y += self.gravity
    self.rect.y += self.movement.y
    if self.movement.y > TERMINAL_VELOCITY:
        self.movement.y = TERMINAL_VELOCITY

def update(self):
    self.input()
    self.rect.x += self.movement.x * self.speed
    self.x_collisions()
    self.apply_gravity()
    self.y_collisions()
</code>```

答:
You need to set self.jump_counter = 2 instead of self.jump_counter = 0. The player can therefore only jump again when it is self.grounded.

Also, you should use the keyboard events instead of pygame.key.get_pressed() for jumping. pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement. The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action like jumping:

def input(self, event_list):

    [...]

    start_jump = False
    for event in event_list:
        start_jump = event.type == pygame.KEYDOWN and event.key == pygame.K_w:

    if start_jump  and self.grounded == True:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 1

    if start_jump  and self.jump_counter == 1:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 2

    # [...]
```
<pre class="lang-py prettyprint-override"><code>run = True
while run:

    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False

    player.input(event_list)

    # [...]
</code>```

See also How to make a character jump in Pygame? and How can I do a double jump in pygame?.

Body:
I have created double jump in a few games now, but always in key events in game loop. This is not working for me here now I have put it into 'get key presses' in player class. I have created the boolean to show '1' when in air, and then reset it back to 0 when jumped while its on '1'. but then when I jump it instantly goes back to 0 so I can infinitely jump.

#player movement
    self.movement = pygame.math.Vector2()
    self.speed = speed
    self.gravity = 1
    self.collision_sprites = collision_sprites
    self.grounded = False
    self.jump_counter = 0

def input(self):
    keys = pygame.key.get_pressed()

    if keys[pygame.K_d]:
        self.movement.x = 1
    elif keys[pygame.K_a]:
        self.movement.x = -1
    else:
        self.movement.x = 0

    if keys[pygame.K_w] and self.grounded == True:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 1

    if keys[pygame.K_w] and self.jump_counter == 1:
        self.movement.y = -JUMP_SPEED

        self.jump_counter = 0

    print(self.jump_counter)

def x_collisions(self):
    for sprite in self.collision_sprites.sprites():
        if sprite.rect.colliderect(self.rect):
            if self.movement.x < 0:
                self.rect.left = sprite.rect.right
            if self.movement.x > 0:
                self.rect.right = sprite.rect.left

def y_collisions(self):
    for sprite in self.collision_sprites.sprites():
        if sprite.rect.colliderect(self.rect):
            if self.movement.y > 0:
                self.rect.bottom = sprite.rect.top
                self.grounded = True
                self.jump_counter = 0
                self.movement.y = 0
            if self.movement.y < 0:
                self.rect.top = sprite.rect.bottom
                self.movement.y = 0

    if self.grounded == True and self.movement.y != 0:
        self.grounded = False

def apply_gravity(self):
    self.movement.y += self.gravity
    self.rect.y += self.movement.y
    if self.movement.y > TERMINAL_VELOCITY:
        self.movement.y = TERMINAL_VELOCITY

def update(self):
    self.input()
    self.rect.x += self.movement.x * self.speed
    self.x_collisions()
    self.apply_gravity()
    self.y_collisions()

Body:
You need to set self.jump_counter = 2 instead of self.jump_counter = 0. The player can therefore only jump again when it is self.grounded.

Also, you should use the keyboard events instead of pygame.key.get_pressed() for jumping. pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement. The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action like jumping:

def input(self, event_list):

    [...]

    start_jump = False
    for event in event_list:
        start_jump = event.type == pygame.KEYDOWN and event.key == pygame.K_w:

    if start_jump  and self.grounded == True:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 1

    if start_jump  and self.jump_counter == 1:
        self.movement.y = -JUMP_SPEED
        self.jump_counter = 2

    # [...]

run = True
while run:

    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False

    player.input(event_list)

    # [...]

See also How to make a character jump in Pygame? and How can I do a double jump in pygame?.


问:
how to extract jwt in envoy
how to extract jwt in envoy on put the extracted values to header

I need to add some extra properties below the http_filters but I have no idea about it and I've researched about jwtProvider and jwtHeader that both come in envoy docs

this is my envoy.yaml file
what's wrong with this configuration:

```<code>admin:
  access_log_path: "/dev/null"
  address:
    socket_address:
      address: 0.0.0.0
      port_value: 8001
static_resources:
  listeners:
  - name: main
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 1337
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: ingress_http
          codec_type: AUTO
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                route:
                  host_rewrite_literal: 0.0.0.0
                  cluster: web_service
          http_filters:
          - name: config.filter.http.jwt_authn.v2alpha.JwtHeader
            from_params:
            - jwt_token
          - name: envoy.filters.http.lua
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
              inline_code: |
                function envoy_on_request(request_handle)
                  local meta = request_handle:streamInfo():dynamicMetadata()
                  for key, value in pairs(meta) do
                    request_handle:logInfo("extract dynamicMetadata key: "..key)
                    request_handle:logInfo("extract dynamicMetadata value: "..value.jwt_payload.usr)
                  end
                end
          - name: envoy.filters.http.router
  clusters:
  - name: web_service
    connect_timeout: 5s
    type: STRICT_DNS  # static
    load_assignment:
      cluster_name: web_service
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 0.0.0.0
                port_value: 3000`enter code here`
</code>```

答:
If I understand correctly, you want that :

envoy extracts and verifies the JWT from Authorization header (Authorization: Bearer ...)

if the JWT is verified, envoy forwards the request to your cluster

in that forwarding request, envoy adds one or more headers corresponding to the decoded JWT payload items

You can do so by changing the http_filters part of your configuration. I am using envoy v1.21.0. For convenience, I am using here a local JWKS config (HS256 algorithm, with secret helloworld = aGVsbG93b3JsZA== in base64). But note that you can also define a remote JWKS config.

          http_filters:
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication"
              providers:
                jwt_auth:
                  local_jwks:
                    inline_string: '{"keys":[{"typ": "JWT", "kty":"oct","alg":"HS256","kid":"df","k":"aGVsbG93b3JsZA=="}]}'
                  from_headers:
                  - name: Authorization
                    value_prefix: "Bearer "
                  payload_in_metadata: jwt_payload
              rules:
              - match:
                  prefix: "/"
                requires:
                  provider_name: jwt_auth
          - name: envoy.filters.http.lua
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
              inline_code: |
                function envoy_on_request(request_handle)
                  local meta = request_handle:streamInfo():dynamicMetadata()
                  for key, value in pairs(meta) do
                    request_handle:headers():add("jwt-extracted-user", value.jwt_payload.usr)
                  end
                end
          - name: envoy.filters.http.router
```
<h3>First filter (<code>envoy.filters.http.jwt_authn</code>)</h3>
<p>The first filter (<code>envoy.filters.http.jwt_authn</code>) is configured to :</p>
<ul>
<li>use some local JWKS configuration : see <code>local_jwks.inline_string</code></li>
<li>get the JWT from <code>Authorization</code> header (after the <code>Bearer </code> part) : see <code>from_headers</code> attribute</li>
<li>write verified JWT payloads to <code>StreamInfo</code> <code>DynamicMetadata</code> with value <code>jwt_payload</code> : see <code>payload_in_metadata</code></li>
<li>define some rules to link a match with the provider defined above (<code>jwt_auth</code>) : see <code>rules</code></li>
</ul>
<h3>Second filter (<code>envoy.filters.http.lua</code>)</h3>
<p>Once this first filter is configured, you can now process <code>StreamInfo</code> <code>DynamicMetadata</code> to add new headers. This is done by the second filter (<code>envoy.filters.http.lua</code>). The inline code :</p>
<pre class="lang-lua prettyprint-override"><code>function envoy_on_request(request_handle)
  local meta = request_handle:streamInfo():dynamicMetadata()
  for key, value in pairs(meta) do
    request_handle:headers():add("jwt-extracted-user", value.jwt_payload.usr)
  end
end
</code>```

iterates on StreamInfo DynamicMetadata

extract the usr field from the JWT payload (named jwt_payload, as configured in the first filter's payload_in_metadata attribute)

add that info (value.jwt_payload.usr) in a new header called jwt-extracted-user

Test

With my answer's http_filters replacing yours in your configuration, you can spin up an envoy that does what you want and test it with a valid JWT containing the following payload :

{
  "usr": "John Doe"
}
```
<p>Just run :</p>
<pre class="lang-sh prettyprint-override"><code>curl \
  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c3IiOiJKb2huIERvZSJ9.-9p297JIIXkHomuuvAFD7pghEtDhdKKAe8V0SqeDqU4' \
  http://localhost:1337
</code>```

The JWT is validated by envoy, forwarded to your web_service with a new header called jwt-extracted-user. To demonstrate that, I have used a simple Flask Python application for your web_service, just printing the headers :

import sys
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route("/")
def hello_world():
    print(request.headers, file=sys.stderr)
    return "Hello, world!"

if __name__ == '__main__':
    app.run(host='0.0.0.0')
```
<p>In the logs of the Python app, you should see something like :</p>
```Host: localhost:1337
User-Agent: curl/7.81.0
Accept: */*
X-Forwarded-Proto: http
X-Request-Id: 3a45f721-ccdd-4225-91ab-8ff4307c97de
Jwt-Extracted-User: John Doe
X-Envoy-Expected-Rq-Timeout-Ms: 15000
```

Note the presence of Jwt-Extracted-User, containing the usr field of the JWT payload.

Credits

https://github.com/envoyproxy/envoy/issues/9716#issuecomment-577261856

Title: how to extract jwt in envoy

Body:
how to extract jwt in envoy on put the extracted values to header

I need to add some extra properties below the http_filters but I have no idea about it and I've researched about jwtProvider and jwtHeader that both come in envoy docs

this is my envoy.yaml file
what's wrong with this configuration:

admin:
  access_log_path: "/dev/null"
  address:
    socket_address:
      address: 0.0.0.0
      port_value: 8001
static_resources:
  listeners:
  - name: main
    address:
      socket_address:
        address: 0.0.0.0
        port_value: 1337
    filter_chains:
    - filters:
      - name: envoy.filters.network.http_connection_manager
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
          stat_prefix: ingress_http
          codec_type: AUTO
          route_config:
            name: local_route
            virtual_hosts:
            - name: local_service
              domains:
              - "*"
              routes:
              - match:
                  prefix: "/"
                route:
                  host_rewrite_literal: 0.0.0.0
                  cluster: web_service
          http_filters:
          - name: config.filter.http.jwt_authn.v2alpha.JwtHeader
            from_params:
            - jwt_token
          - name: envoy.filters.http.lua
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
              inline_code: |
                function envoy_on_request(request_handle)
                  local meta = request_handle:streamInfo():dynamicMetadata()
                  for key, value in pairs(meta) do
                    request_handle:logInfo("extract dynamicMetadata key: "..key)
                    request_handle:logInfo("extract dynamicMetadata value: "..value.jwt_payload.usr)
                  end
                end
          - name: envoy.filters.http.router
  clusters:
  - name: web_service
    connect_timeout: 5s
    type: STRICT_DNS  # static
    load_assignment:
      cluster_name: web_service
      endpoints:
      - lb_endpoints:
        - endpoint:
            address:
              socket_address:
                address: 0.0.0.0
                port_value: 3000`enter code here`

Body:
If I understand correctly, you want that :

envoy extracts and verifies the JWT from Authorization header (Authorization: Bearer ...)

if the JWT is verified, envoy forwards the request to your cluster

in that forwarding request, envoy adds one or more headers corresponding to the decoded JWT payload items

You can do so by changing the http_filters part of your configuration. I am using envoy v1.21.0. For convenience, I am using here a local JWKS config (HS256 algorithm, with secret helloworld = aGVsbG93b3JsZA== in base64). But note that you can also define a remote JWKS config.

          http_filters:
          - name: envoy.filters.http.jwt_authn
            typed_config:
              "@type": "type.googleapis.com/envoy.extensions.filters.http.jwt_authn.v3.JwtAuthentication"
              providers:
                jwt_auth:
                  local_jwks:
                    inline_string: '{"keys":[{"typ": "JWT", "kty":"oct","alg":"HS256","kid":"df","k":"aGVsbG93b3JsZA=="}]}'
                  from_headers:
                  - name: Authorization
                    value_prefix: "Bearer "
                  payload_in_metadata: jwt_payload
              rules:
              - match:
                  prefix: "/"
                requires:
                  provider_name: jwt_auth
          - name: envoy.filters.http.lua
            typed_config:
              "@type": type.googleapis.com/envoy.extensions.filters.http.lua.v3.Lua
              inline_code: |
                function envoy_on_request(request_handle)
                  local meta = request_handle:streamInfo():dynamicMetadata()
                  for key, value in pairs(meta) do
                    request_handle:headers():add("jwt-extracted-user", value.jwt_payload.usr)
                  end
                end
          - name: envoy.filters.http.router

First filter (envoy.filters.http.jwt_authn)

The first filter (envoy.filters.http.jwt_authn) is configured to :

use some local JWKS configuration : see local_jwks.inline_string

get the JWT from Authorization header (after the Bearer  part) : see from_headers attribute

write verified JWT payloads to StreamInfo DynamicMetadata with value jwt_payload : see payload_in_metadata

define some rules to link a match with the provider defined above (jwt_auth) : see rules

Second filter (envoy.filters.http.lua)

Once this first filter is configured, you can now process StreamInfo DynamicMetadata to add new headers. This is done by the second filter (envoy.filters.http.lua). The inline code :

function envoy_on_request(request_handle)
  local meta = request_handle:streamInfo():dynamicMetadata()
  for key, value in pairs(meta) do
    request_handle:headers():add("jwt-extracted-user", value.jwt_payload.usr)
  end
end

iterates on StreamInfo DynamicMetadata

extract the usr field from the JWT payload (named jwt_payload, as configured in the first filter's payload_in_metadata attribute)

add that info (value.jwt_payload.usr) in a new header called jwt-extracted-user

Test

With my answer's http_filters replacing yours in your configuration, you can spin up an envoy that does what you want and test it with a valid JWT containing the following payload :

{
  "usr": "John Doe"
}

Just run :

curl \
  -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c3IiOiJKb2huIERvZSJ9.-9p297JIIXkHomuuvAFD7pghEtDhdKKAe8V0SqeDqU4' \
  http://localhost:1337

The JWT is validated by envoy, forwarded to your web_service with a new header called jwt-extracted-user. To demonstrate that, I have used a simple Flask Python application for your web_service, just printing the headers :

import sys
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route("/")
def hello_world():
    print(request.headers, file=sys.stderr)
    return "Hello, world!"

if __name__ == '__main__':
    app.run(host='0.0.0.0')

In the logs of the Python app, you should see something like :

Host: localhost:1337
User-Agent: curl/7.81.0
Accept: */*
X-Forwarded-Proto: http
X-Request-Id: 3a45f721-ccdd-4225-91ab-8ff4307c97de
Jwt-Extracted-User: John Doe
X-Envoy-Expected-Rq-Timeout-Ms: 15000

Note the presence of Jwt-Extracted-User, containing the usr field of the JWT payload.

Credits

https://github.com/envoyproxy/envoy/issues/9716#issuecomment-577261856


问:
How to negate my player getting stuck if there is something above his head while crouching ( unity 3d )?
ive made this simple code to regulate the height of the player once Lcontrol is pressed

```<code>//crouching
if (Input.GetKey(KeyCode.LeftControl))
    controller.height = 1.0f;
else
    controller.height = 2.0f;
</code>```

but my charachter gets stuck if there is a roof over his head while crouchin

how do i make a function that detects if there is something above my head so even if i unpress the Lcontroll button my caracter stays crouched

how do i lower the camera/body automatically because the camera rn gets stuck in the roof ( with the stuck player )

and you know generally be a smooth crouch ^^" , thanks in advance !

答: To lower my camera I just attach it to my player so when my player gets smaller the camera goes down with it.</p>

Body:
ive made this simple code to regulate the height of the player once Lcontrol is pressed

//crouching
if (Input.GetKey(KeyCode.LeftControl))
    controller.height = 1.0f;
else
    controller.height = 2.0f;

but my charachter gets stuck if there is a roof over his head while crouchin

how do i make a function that detects if there is something above my head so even if i unpress the Lcontroll button my caracter stays crouched

how do i lower the camera/body automatically because the camera rn gets stuck in the roof ( with the stuck player )

and you know generally be a smooth crouch ^^" , thanks in advance !


问:
How to get Unity3D 2018 (or higher) to work with MongoDB C# driver?
I am trying to get Unity3D work with MongoDB, but I am running into too many version compatibility issues.

My Unity is with Framework version 4.6.1. With C# driver 2.8.0 downloaded from NuGet package manager.
MongoDB.Driver package has two netstandard1.5 and net452 folders. MongoDBDriver has net452 and netstandard1.5. Likewise, there are MongoDB.driver.Core.2.8.0,  Dnsclient and MongoDB.Driver.GridFS with multiple version of framework specific .dlls.
My Unity is set to .Net 4.x (Scripting run time version) and .Net standard 2.0 API compatiblity.

With these, the MongoDB name itself is not recognized while scripting.

I downloaded C# driver code from GitHub (2.8.0) and built it fresh. Copied net 1.5 version of .dlls, but it did not work either.

I have taken .DLLs from https://drive.google.com/file/d/16cLVJi0VZpplSS8MDnRcUeVnYuvxypBm/view. It builds fine (with run time version .Net 3.5 and API compatibiltiy standard 2.0). But it fails with "unknown host" probably due to some compatibility issue with Dnsclient - used by MongoDB.Driver.core.

Please let me know if someone knows the correct version combination or the process to build, specific code to modify in MongoDB C# driver code - to make it work with Unity3D.

I have seen answer on typeload exception in link below. I also faced it. But it did not solve my problem.
C# mod dependency throws 'TypeLoadException' when instantiated?

答:
Don't know why all send their githubs. Maybe to advertise themselfs. But there are all dlls for working with MongoDB could be found in the NuGet. It is the right place to get fresh version, because Mongo developers manage them by themselfs. I absolutely not sure these guys, who send their githubs, keep all dlls versions fresh.

https://www.nuget.org/profiles/MongoDB


问:
What is the default value for the --user-data-dir argument for VSCode on macOS (or other OS's)?
I have an issue with VSCode that seems to get fixed if I specify a custom --user-data-dir argument. So I'd like to figure out what file in the user-data-dir is causing my issue. Or at least just delete my entire user-data-dir. Where can I find the default user-data-dir?

答:
The path you're looking for is:

```<code>~/Library/Application Support/Code
</code>```

or

```<code>/Users/YourName/Library/Application Support/Code
</code>```

If you delete this folder it will be as if you provide a completely new --user-data-dir argument.

Body:
The path you're looking for is:

~/Library/Application Support/Code

or

/Users/YourName/Library/Application Support/Code

If you delete this folder it will be as if you provide a completely new --user-data-dir argument.


问:
How to change the textTheme in the ThemeData class?
I cannot change the color of the TextTheme property in the ThemeData class even though the code doesn't give any error.
Here is what I have done so far:

```<code>import 'package:flutter/material.dart';

void main() => runApp(BMICalculator());

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        appBarTheme: AppBarTheme(
          backgroundColor: Color(0xff0a0e21),
        ),
        scaffoldBackgroundColor: Color(0xff0a0e21),
        textTheme: TextTheme(bodyText1: TextStyle(color: Colors.blue)),//the text remains white in the app.
      ),
      home: InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
      ),
      body: Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => print('object'),
      ),
    );
  }
}
</code>```

What am I doing wrong?

答:
You have declared the themes successfully, but are not using it. Here is the replacement code snippet:

```<code>body: Center(
        child: Text('Body Text', style: Theme.of(context).textTheme.bodyText1),
      )
</code>```

You need to specify the theme in style attribute for the necessary changes to take place.

Body:
I cannot change the color of the TextTheme property in the ThemeData class even though the code doesn't give any error.
Here is what I have done so far:

import 'package:flutter/material.dart';

void main() => runApp(BMICalculator());

class BMICalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        appBarTheme: AppBarTheme(
          backgroundColor: Color(0xff0a0e21),
        ),
        scaffoldBackgroundColor: Color(0xff0a0e21),
        textTheme: TextTheme(bodyText1: TextStyle(color: Colors.blue)),//the text remains white in the app.
      ),
      home: InputPage(),
    );
  }
}

class InputPage extends StatefulWidget {
  @override
  _InputPageState createState() => _InputPageState();
}

class _InputPageState extends State<InputPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('BMI CALCULATOR'),
      ),
      body: Center(
        child: Text('Body Text'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => print('object'),
      ),
    );
  }
}

What am I doing wrong?

Body:
You have declared the themes successfully, but are not using it. Here is the replacement code snippet:

body: Center(
        child: Text('Body Text', style: Theme.of(context).textTheme.bodyText1),
      )

You need to specify the theme in style attribute for the necessary changes to take place.


问:
Extracting filesnames in bash with regex
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}
```
<p>Here is an excerpt of the DTX file</p>
<pre class="lang-latex prettyprint-override"><code>\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}
</code>```

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

```
<p>I wasn't able, to modify my <code>regex</code> expression, to split the content of the last <code>\TestFiles{foo-bar, bar+baz,foo_bar_baz}</code> example into three matching results.</p>
<p>I tried a regular expression like this <code>regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'</code>.  I thought the <code>[:alnum:]+-_]*</code> would match the filenames.  As far as I understand regular expressions, the <code>(...)</code> should form a group, that should be listed afterwards in the bash array <code>BASH_REMATCH[$i]</code>.</p>
<p>The part <code>[,]+</code> should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like <code>[[:space:]]*</code> or at least <code>[ ]*</code> should represent this.  The quantifier <code>*</code> means any repetition, ranging from 0 to ..., while <code>+</code> should at least appear one or more times.</p>
<p>But that regular expression did not work at all, if had no matching results.</p>
<p>How must <code>regex</code> be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:</p>
<pre class="lang-sh prettyprint-override"><code>get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

</code>```

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

答:
EDIT (without external programs, though it's rather impractical, and tied to exactly three matches)

```<code>function get_filenames () {
    p='([^, }]*) *,? *'
    regex="\\TestFiles\{$p$p$p"

    while read -r line ; do
        if [[ $line =~ $regex ]] ; then
            i=1
            while [ $i -le 3 ]; do
                echo "Match $i: \"${BASH_REMATCH[$i]}\""
                i=$(( i + 1 ))
            done
            echo
        fi
    done < mystyle.dtx
}
</code>```

If you really need to output exactly three file names (even empty) for each '\TestFiles' row then here's the code.

```<code>function get_filenames () {
    MAX_FILES_CNT=3
    IFS=$'\n'
    for line in $(grep -oP '\\TestFiles\{\K[^}]*' < mystyle.dtx); do
        filenames=()
        for filename in $(grep -m $MAX_FILES_CNT -oP "[^, ]+" <<< "$line"); do
            filenames+=("$filename")
        done
        i=0
        while [ $i -lt $MAX_FILES_CNT ]; do
            echo "Match $(($i+1)): \"${filenames[i]}\""
            i=$(( i + 1 ))
        done
        echo ""
    done
    unset IFS
}
</code>```

Match 1: "foo-bar"

Match 2: ""

Match 3: ""

Match 1: "foo-bar"

Match 2: "bar+baz"

Match 3: "foo_bar_baz"

By the way, BASH_REMATCH is no good for this task, cause it captures only last rematch. Look

```<code>[[ "asdf" =~ (.)* ]]
echo "${BASH_REMATCH[@]}"
</code>```

asdf f

Also I would recommend to read this question https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice

Body:
Can please someone help me to set up a regular expression.

I have a large LaTeX3 TeXDoc file.  LaTeX3 TeXDoc defines the macro \TestFiles{}, which should be used, to list the names of files, which itself should be used as an unit tests.  You can name more than one file between the braces.  So \TestFiles{foo-bar} and \TestFiles{foo-bar, bar+baz,foo_bar_baz} are syntactical correct use cases for this macro.

I would like to write a bash script, to extract all the uni test files, named in the \TestFiles{} macros, to compile them with pdflatex and check, if pdflatex will be able to produce an output file successfully.

I have something like this in my script:

function get_filenames () {
  ## This regex works but is not sensible enough
  # regex='\\TestFiles{(.*)}'
  ## This works also, but is again not precise enough
  regex='\\TestFiles{([0-9a-zA-Z+-_, ]*)}'
  ## This should give more than one matching group
  ## (separated by ", " or ","), but this regex doesn't
  ## work.  I have no idea why or how to modify, to get
  ## it working

  while read -r line ; do
    if [[ $line =~ $regex ]] ; then
      i=1
        while [ $i -le 3 ]; do
          echo "Match $i: \"${BASH_REMATCH[$i]}\""
          i=$(( i + 1 ))
        done
      echo
    fi
  done < mystyle.dtx
}

Here is an excerpt of the DTX file

\TestFiles{foo-bar}

\TestFiles{foo-bar, bar+baz,foo_bar_baz}

(You can store this as mystyle.dtx, in order to reproduce the next example.)

Using the above noted examples, my script gives me the following results:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar, bar+baz,foo_bar_baz"
Match 2: ""
Match 3: ""

I wasn't able, to modify my regex expression, to split the content of the last \TestFiles{foo-bar, bar+baz,foo_bar_baz} example into three matching results.

I tried a regular expression like this regex='\\TestFiles{([[:alnum:]+-_]*)[,]+[ ]*}'.  I thought the [:alnum:]+-_]* would match the filenames.  As far as I understand regular expressions, the (...) should form a group, that should be listed afterwards in the bash array BASH_REMATCH[$i].

The part [,]+ should reflect that every file name must be separated by at least one comma.  Between the filenames there might be some white space, so something like [[:space:]]* or at least [ ]* should represent this.  The quantifier * means any repetition, ranging from 0 to ..., while + should at least appear one or more times.

But that regular expression did not work at all, if had no matching results.

How must regex be defined, to store each filenames as a matching group?  I am searching for the correct regular expression, to get this result:

get_filenames
Match 1: "foo-bar"
Match 2: ""
Match 3: ""

Match 1: "foo-bar"
Match 2: "bar+baz"
Match 3: "foo_bar_baz"

EDIT: in my real world files, there may be (and are) more than tree test files.

Thanks in advance.

Body:
EDIT (without external programs, though it's rather impractical, and tied to exactly three matches)

function get_filenames () {
    p='([^, }]*) *,? *'
    regex="\\TestFiles\{$p$p$p"

    while read -r line ; do
        if [[ $line =~ $regex ]] ; then
            i=1
            while [ $i -le 3 ]; do
                echo "Match $i: \"${BASH_REMATCH[$i]}\""
                i=$(( i + 1 ))
            done
            echo
        fi
    done < mystyle.dtx
}

If you really need to output exactly three file names (even empty) for each '\TestFiles' row then here's the code.

function get_filenames () {
    MAX_FILES_CNT=3
    IFS=$'\n'
    for line in $(grep -oP '\\TestFiles\{\K[^}]*' < mystyle.dtx); do
        filenames=()
        for filename in $(grep -m $MAX_FILES_CNT -oP "[^, ]+" <<< "$line"); do
            filenames+=("$filename")
        done
        i=0
        while [ $i -lt $MAX_FILES_CNT ]; do
            echo "Match $(($i+1)): \"${filenames[i]}\""
            i=$(( i + 1 ))
        done
        echo ""
    done
    unset IFS
}

Match 1: "foo-bar"

Match 2: ""

Match 3: ""

Match 1: "foo-bar"

Match 2: "bar+baz"

Match 3: "foo_bar_baz"

By the way, BASH_REMATCH is no good for this task, cause it captures only last rematch. Look

[[ "asdf" =~ (.)* ]]
echo "${BASH_REMATCH[@]}"

asdf f

Also I would recommend to read this question https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice


问:
pyodbc.Error: ('HY000', '[HY000] [Teradata][ODBC] (11560) Unable to locate SQLGetPrivateProfileString function. (11560) (SQLDriverConnect)')
I'm connecting to teradata in python using the pyodbc module, and I keep getting this error. Anyone knows why? I'm using the below code:

import textwrap
import pyodbc
import teradata
import pandas as pd
cnx_tera = ('DRIVER={/Library/Application Support/teradata/client/16.20/lib/tdataodbc_sbu.dylib};'
....)

cnx = pyodbc.connect(cnx_tera)

答:
I was facing a similar problem. Did resolve this problem using the Teradatasql package instead of ODBC, it's very simple to connect using teradatasql. Just put in the right parameters while setting up the connection for teradatasql.

P.S.= Comment for future reference.


问:
measuring Variable vector in omnet++ from C++ code
I am working on Omnet++ where I am using the INET4 framework to simulate TCP between two nodes. I made my own machine learning algorithm and communicate with the TCP code. Now I am facing a problem in recording a variable in C++ ML code. How should I record a variable value in omnet++ without emitting signals? I just want to record a variable and plot it at the end of the simulation.
I tried with the emitting signal by adding a signal variable in the .ned file of TCP and also in TcpConnection.h file. The problem with that is I have to implement variables in the TCP code, which I did but when I use state object in my .cc code it gives me a segmentation error.
Thank you</p>

答: I figure out the solution for it. Basically I am using cOutVector method for storing the data in the varibale you can also look in to it here coutVectoe</p>


问:
Automatically sort Google Sheet by most recently updated row
I want to have a sheet which automatically sorts the most recently edited row to the top, in order to surface freshly edited results and not let them be buried by outdated entries.</p>

答:
Here's the solution I came up with for a Google Apps Script:

```<code>
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var dateColumn = 2; // What column should date be written to
  var headerRows = 2;
  var tableRange = "A3:M101"; // What data to sort.
  var sheetName = 'Sheet name' // Name of the sheet to sort

  if( sheet.getName() == sheetName ) { // Checks that we're on the correct sheet
    var editedCell = sheet.getActiveCell();
    var offset = dateColumn - editedCell.getColumn() // Finds the offset needed to move from edited cell to date column
    if( editedCell.getColumn() != dateColumn && editedCell.getRow() > headerRows) { // Don't overwrite manually set dates or the header row(s)
      var dateCell = editedCell.offset(0, offset); // Go to relevant date cell
      var now = new Date();
      now = Utilities.formatDate(now, "GMT", "yyyy/MM/dd HH:mm:ss"); // Format datetime
      dateCell.setValue(now);
    }

    var range = sheet.getRange(tableRange);

    range.sort( { column : dateColumn, ascending: false } ); // Sort range by date column, newest on top
    // range.setWrapStrategy(SpreadsheetApp.WrapStrategy.WRAP); // Sets text wrapping to wrap if uncommented
  }
}
</code>```

Plus adding an event trigger on form submission.

Body:
Here's the solution I came up with for a Google Apps Script:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();

  var dateColumn = 2; // What column should date be written to
  var headerRows = 2;
  var tableRange = "A3:M101"; // What data to sort.
  var sheetName = 'Sheet name' // Name of the sheet to sort

  if( sheet.getName() == sheetName ) { // Checks that we're on the correct sheet
    var editedCell = sheet.getActiveCell();
    var offset = dateColumn - editedCell.getColumn() // Finds the offset needed to move from edited cell to date column
    if( editedCell.getColumn() != dateColumn && editedCell.getRow() > headerRows) { // Don't overwrite manually set dates or the header row(s)
      var dateCell = editedCell.offset(0, offset); // Go to relevant date cell
      var now = new Date();
      now = Utilities.formatDate(now, "GMT", "yyyy/MM/dd HH:mm:ss"); // Format datetime
      dateCell.setValue(now);
    }

    var range = sheet.getRange(tableRange);

    range.sort( { column : dateColumn, ascending: false } ); // Sort range by date column, newest on top
    // range.setWrapStrategy(SpreadsheetApp.WrapStrategy.WRAP); // Sets text wrapping to wrap if uncommented
  }
}

Plus adding an event trigger on form submission.


问:
I am trying to open custom chrome tab from nested recycler view but couldn't having error Calling startActivity() from outside of an Activity
Here is the code I am using to open the custom chrome tab

```<code>val builder = CustomTabsIntent.Builder()
                val customTabsIntent = builder.build()
                customTabsIntent.launchUrl(context.applicationContext, Uri.parse("https://www.codingkaro.in"))
</code>```

This is set on a button click listener inside nested recycler view. I have passed the context from the MainActivity as this@MainActivity

This is the error I am getting

```<code>Process: com.shyptsolution.classproject, PID: 31505
    android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
</code>```

答:
Earlier I didn't know how to addFlags() to this but now the code looks like this

```<code>val builder = CustomTabsIntent.Builder()
                val customTabsIntent = builder.build()
                customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                customTabsIntent.launchUrl(holder.download.rootView.context, Uri.parse("https://www.codingkaro.in"))
</code>```

and everything works fine.
I just added
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)

Body:
Here is the code I am using to open the custom chrome tab

val builder = CustomTabsIntent.Builder()
                val customTabsIntent = builder.build()
                customTabsIntent.launchUrl(context.applicationContext, Uri.parse("https://www.codingkaro.in"))

This is set on a button click listener inside nested recycler view. I have passed the context from the MainActivity as this@MainActivity

This is the error I am getting

Process: com.shyptsolution.classproject, PID: 31505
    android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Body:
Earlier I didn't know how to addFlags() to this but now the code looks like this

val builder = CustomTabsIntent.Builder()
                val customTabsIntent = builder.build()
                customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                customTabsIntent.launchUrl(holder.download.rootView.context, Uri.parse("https://www.codingkaro.in"))

and everything works fine.
I just added
customTabsIntent.intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)


问:
How can I send a document to the system print dialog on MacOS?
I am wondering if there is a way to use the system print dialog on Mac to print PDF documents.

Everything I have seen so far involved either using lpr or was only valid on Windows.

Particularly, once I have the dialog, I would like to change the print options, possibly even selecting the printer-specific "staple" options (on a Xerox WorkCentre).

答:
There may be a much better way, but this might get you started:

```<code>#!/bin/bash

# Open PDF in Preview app
open FileToPrint.pdf

# Tell Preview to print it
osascript<<EOF
tell application "System Events"
   tell process "Preview"
      delay 1
      keystroke "p" using command down
      --delay 1
      --keystroke return
      --delay 10
      --keystroke "w" using command down
  end tell
end tell
EOF
</code>```

The lines starting with -- are comments, so remove the -- to actually go ahead and print the document without further interaction being required.

If that open command doesn't happen to open in Preview, you can force it with:

```<code>open -a Preview FileToPrint.pdf
</code>```

Body:
There may be a much better way, but this might get you started:

#!/bin/bash

# Open PDF in Preview app
open FileToPrint.pdf

# Tell Preview to print it
osascript<<EOF
tell application "System Events"
   tell process "Preview"
      delay 1
      keystroke "p" using command down
      --delay 1
      --keystroke return
      --delay 10
      --keystroke "w" using command down
  end tell
end tell
EOF

The lines starting with -- are comments, so remove the -- to actually go ahead and print the document without further interaction being required.

If that open command doesn't happen to open in Preview, you can force it with:

open -a Preview FileToPrint.pdf


问:
MongoDB - Removing leading and trailing spaces from array of objects
I have a users collection in MongoDB with the following structure (I removed all irrelevant fields):

```<code>{
    _id: ObjectId,
    labels: Array <{ name: String, category: String }>
}
</code>```

I want to remove leading and trailing spaces from the name property inside the labels array.
I tried to do this:

```<code>db.users.update(
  { "labels.name" : { $regex: /^\s+|\s+$/ } },
  [{ $set: { "labels.$[].name": { $trim: { input: "$labels.$[].name" } } } }],
  { multi: true }
)
</code>```

But I'm getting the following error:

```<code>{
    "message" : "write failed with error: {" +
              "    'nMatched' : 0," +
              "    'nUpserted' : 0," +
              "    'nModified' : 0," +
              "    'writeError' : {" +
              "    \t'code' : 16410," +
              "    \t'errmsg' : 'Invalid $set :: caused by :: FieldPath field names may not start with '$'. Consider using $getField or $setField.'" +
              "    }" +
              "}",
    "stack" : "script:4:2"
}
</code>```

What is the correct way to solve this?

答:
You can not use aggregation operators ($trim) in regular update query, you can try update with aggregation pipeline starting from MongoDB 4.2,

$regex operator to pass ^ to match space from beginning and $ to match space from end.  Note this will not pinpoint names in the labels array with leading or trailing space, but it will eliminate from processing any doc where none of the names have leading or trailing space.

put array bracket in update part

$map to iterate loop of labels array and trim the name using $trim operator

```<code>db.users.update(
  { "labels.name": { $regex: "^ | $" } },
  [{
    $set: {
      labels: {
        $map: {
          input: "$labels",
          in: {
            category: "$$this.category",
            name: { $trim: { input: "$$this.name" } }
          }
        }
      }
    }
  }],
  { multi: true }
)
</code>```

Playground

Body:
I have a users collection in MongoDB with the following structure (I removed all irrelevant fields):

{
    _id: ObjectId,
    labels: Array <{ name: String, category: String }>
}

I want to remove leading and trailing spaces from the name property inside the labels array.
I tried to do this:

db.users.update(
  { "labels.name" : { $regex: /^\s+|\s+$/ } },
  [{ $set: { "labels.$[].name": { $trim: { input: "$labels.$[].name" } } } }],
  { multi: true }
)

But I'm getting the following error:

{
    "message" : "write failed with error: {" +
              "    'nMatched' : 0," +
              "    'nUpserted' : 0," +
              "    'nModified' : 0," +
              "    'writeError' : {" +
              "    \t'code' : 16410," +
              "    \t'errmsg' : 'Invalid $set :: caused by :: FieldPath field names may not start with '$'. Consider using $getField or $setField.'" +
              "    }" +
              "}",
    "stack" : "script:4:2"
}

What is the correct way to solve this?

Body:
You can not use aggregation operators ($trim) in regular update query, you can try update with aggregation pipeline starting from MongoDB 4.2,

$regex operator to pass ^ to match space from beginning and $ to match space from end.  Note this will not pinpoint names in the labels array with leading or trailing space, but it will eliminate from processing any doc where none of the names have leading or trailing space.

put array bracket in update part

$map to iterate loop of labels array and trim the name using $trim operator

db.users.update(
  { "labels.name": { $regex: "^ | $" } },
  [{
    $set: {
      labels: {
        $map: {
          input: "$labels",
          in: {
            category: "$$this.category",
            name: { $trim: { input: "$$this.name" } }
          }
        }
      }
    }
  }],
  { multi: true }
)

Playground


问:
Relational database design for photography website
I'm creating a database for a photography website and I want it to allow three main things -

Allow the owner/admin to create client accounts and credentials,

Specifying which photos should go into three different portfolio galleries on the site, and,

Displaying a unique client's photos (and only their photos!) to them when they log in.

This is my first database design ever - based on responses below, I've added that emphasis ;) and edited the design as below.

IMAGES
image_id,
filename,
description,
client_id,
date_uploaded,

USERS/CLIENTS

client_id,

client_name

username,

password,

PORTFOLIO

portfolio_id,

portfolio_name,

PORTFOLIO_IMAGES

id,

image_id,

portfolio_id,

Am I correct in thinking that the final id in PORTFOLIO_IMAGES would allow me to display one image in multiple galleries?

Thanks

答:
You might want to consider normalization.

Assuming that usernames are unique - two people can't have the same username, come on - then you can eliminate "id" in the Users table in order to help prevent update/insert/delete anomalies (doing this would almost certainly put Users into BCNF, and likely DKNF - this is a good thing).

Clients is fine. What is the difference between Clients and Users, though? Really... seems similar to me.

Make sure that references are done using foreign key constraints, and I think that should be better.

EDIT:

Based on the new design, I have these suggestions:

Change Clients/Users into three tables:

```<code>  ClientNames
  - ClientID (PK)
  - ClientName

  ClientUsernames
  - ClientID (PK)
  - Username

  UsernamePasswords
  - Username (PK)
  - Password
</code>```

This is safe and says that one Client/User has one name, one Client/User has one Username, and one Username has one Password. I don't see another good decomposition (in the sense that it's going to be in a tight normal form).

You can eliminate one of these tables by eliminating the synthetic "ClientID" key, if you want. There are disadvantages to this, and it may not be possible (some people do have the same name!).

The problem here is that it is likely that ClientID, ClientName, and UserName determine each other in a way that isn't amenable to stuffing them in the same table.

Body:
You might want to consider normalization.

Assuming that usernames are unique - two people can't have the same username, come on - then you can eliminate "id" in the Users table in order to help prevent update/insert/delete anomalies (doing this would almost certainly put Users into BCNF, and likely DKNF - this is a good thing).

Clients is fine. What is the difference between Clients and Users, though? Really... seems similar to me.

Make sure that references are done using foreign key constraints, and I think that should be better.

EDIT:

Based on the new design, I have these suggestions:

Change Clients/Users into three tables:

  ClientNames
  - ClientID (PK)
  - ClientName

  ClientUsernames
  - ClientID (PK)
  - Username

  UsernamePasswords
  - Username (PK)
  - Password

This is safe and says that one Client/User has one name, one Client/User has one Username, and one Username has one Password. I don't see another good decomposition (in the sense that it's going to be in a tight normal form).

You can eliminate one of these tables by eliminating the synthetic "ClientID" key, if you want. There are disadvantages to this, and it may not be possible (some people do have the same name!).

The problem here is that it is likely that ClientID, ClientName, and UserName determine each other in a way that isn't amenable to stuffing them in the same table.


答:
Try passing textTheme: ThemeData value
here is an example for textTheme

```<code> textTheme: ThemeData.light().textTheme.copyWith(
          headline6: TextStyle(
            fontFamily: 'OpenSans',
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
</code>```

Just match your implementation with mine, here I have implemented textTheme for titles.
now if I want to refer to this headline6 theme I can do

```<code>Theme.of(context).textTheme.headline6
</code>```

Title: How to change the textTheme in the ThemeData class?

Body:
Try passing textTheme: ThemeData value
here is an example for textTheme

 textTheme: ThemeData.light().textTheme.copyWith(
          headline6: TextStyle(
            fontFamily: 'OpenSans',
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),

Just match your implementation with mine, here I have implemented textTheme for titles.
now if I want to refer to this headline6 theme I can do

Theme.of(context).textTheme.headline6