问:
Sphinx autosummary when generating documentation for torch.nn.Module: Type object has no attribute "Training"
I have run into this issue with Sphinx autosummary when trying to let it generate documentation for a torch.nn.Module class.

Minimal example: https://github.com/longyuxi/sphinx-autosummary-debug

Folder structure:

```<code>.
├── README.md
├── docs
│   ├── Makefile
│   ├── api.rst
│   ├── conf.py
│   ├── index.rst
│   ├── make.bat
│   └── templates
│       ├── custom-class-template.rst
│       └── custom-module-template.rst
└── package
    └── module.py
</code>```

The module.py file is taken from a PyTorch example and contains a torch.nn.Module:

```<code>import torch
import math

class Polynomial3(torch.nn.Module):

...
</code>```

I get this error when I run make html in the docs directory.

```<code>➜  docs git:(main) ✗ make html
Running Sphinx v6.1.3
WARNING: html_static_path entry '_static' does not exist
loading pickled environment... failed
failed: Can't get attribute '_stable_repr_object' on <sphinx.deprecation._ModuleWrapper object at 0x7fe704e8b220>
[autosummary] generating autosummary for: _autosummary/package.module.Polynomial3.rst, _autosummary/package.module.rst, _autosummary/package.rst, api.rst, index.rst
building [mo]: targets for 0 po files that are out of date
writing output...
building [html]: targets for 5 source files that are out of date
updating environment: [new config] 5 added, 0 changed, 0 removed
reading sources... [100%] index
/Users/longyuxi/Documents/sphinx-autosummary-debug/docs/_autosummary/package.module.Polynomial3.rst:70: WARNING: autosummary: failed to import Polynomial3.training.
Possible hints:
* AttributeError: type object 'Polynomial3' has no attribute 'Polynomial3'
* ModuleNotFoundError: No module named 'Polynomial3'
* AttributeError: type object 'Polynomial3' has no attribute 'training'
* ImportError:
* ModuleNotFoundError: No module named 'package.module.Polynomial3'; 'package.module' is not a package
* KeyError: 'Polynomial3'
looking for now-outdated files... none found
pickling environment... done
checking consistency... /Users/longyuxi/Documents/sphinx-autosummary-debug/docs/api.rst: WARNING: document isn't included in any toctree
done
preparing documents... done
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:1: WARNING: undefined label: 'nn-init-doc'
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:4: WARNING: undefined label: 'locally-disable-grad-doc'
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:4: WARNING: undefined label: 'locally-disable-grad-doc'
writing output... [100%] index
generating indices... genindex py-modindex done
copying linked files...
copying notebooks ...
highlighting module code... [100%] package.module
writing additional pages... search done
copying static files... done
copying extra files... done
dumping search index in English (code: en)... done
dumping object inventory... done
build succeeded, 6 warnings.
</code>```

The error seems to have originated from Sphinx trying to import training from this nn.Module, yet I don't understand why is it trying to do that? I have tried mocking import using autodoc_mock_imports = ['torch.nn'] or autodoc_mock_imports = ['torch.nn.Module'], but neither of them worked. Any possible ideas / help as to how this happened?

Body:
I have run into this issue with Sphinx autosummary when trying to let it generate documentation for a torch.nn.Module class.

Minimal example: https://github.com/longyuxi/sphinx-autosummary-debug

Folder structure:

.
├── README.md
├── docs
│   ├── Makefile
│   ├── api.rst
│   ├── conf.py
│   ├── index.rst
│   ├── make.bat
│   └── templates
│       ├── custom-class-template.rst
│       └── custom-module-template.rst
└── package
    └── module.py

The module.py file is taken from a PyTorch example and contains a torch.nn.Module:

import torch
import math

class Polynomial3(torch.nn.Module):

...

I get this error when I run make html in the docs directory.

➜  docs git:(main) ✗ make html
Running Sphinx v6.1.3
WARNING: html_static_path entry '_static' does not exist
loading pickled environment... failed
failed: Can't get attribute '_stable_repr_object' on <sphinx.deprecation._ModuleWrapper object at 0x7fe704e8b220>
[autosummary] generating autosummary for: _autosummary/package.module.Polynomial3.rst, _autosummary/package.module.rst, _autosummary/package.rst, api.rst, index.rst
building [mo]: targets for 0 po files that are out of date
writing output...
building [html]: targets for 5 source files that are out of date
updating environment: [new config] 5 added, 0 changed, 0 removed
reading sources... [100%] index
/Users/longyuxi/Documents/sphinx-autosummary-debug/docs/_autosummary/package.module.Polynomial3.rst:70: WARNING: autosummary: failed to import Polynomial3.training.
Possible hints:
* AttributeError: type object 'Polynomial3' has no attribute 'Polynomial3'
* ModuleNotFoundError: No module named 'Polynomial3'
* AttributeError: type object 'Polynomial3' has no attribute 'training'
* ImportError:
* ModuleNotFoundError: No module named 'package.module.Polynomial3'; 'package.module' is not a package
* KeyError: 'Polynomial3'
looking for now-outdated files... none found
pickling environment... done
checking consistency... /Users/longyuxi/Documents/sphinx-autosummary-debug/docs/api.rst: WARNING: document isn't included in any toctree
done
preparing documents... done
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:1: WARNING: undefined label: 'nn-init-doc'
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:4: WARNING: undefined label: 'locally-disable-grad-doc'
/Users/longyuxi/Documents/sphinx-autosummary-debug/package/module.py:docstring of package.module.Polynomial3:4: WARNING: undefined label: 'locally-disable-grad-doc'
writing output... [100%] index
generating indices... genindex py-modindex done
copying linked files...
copying notebooks ...
highlighting module code... [100%] package.module
writing additional pages... search done
copying static files... done
copying extra files... done
dumping search index in English (code: en)... done
dumping object inventory... done
build succeeded, 6 warnings.

The error seems to have originated from Sphinx trying to import training from this nn.Module, yet I don't understand why is it trying to do that? I have tried mocking import using autodoc_mock_imports = ['torch.nn'] or autodoc_mock_imports = ['torch.nn.Module'], but neither of them worked. Any possible ideas / help as to how this happened?


来源: stackexchange

问:
Calling this from Super class Constructor
Can any one please help me in understanding the output.

public class A {
    public A() {
        this.print();
    }

    public void print() {
        System.out.println("A");

    }
}
```
<p>Class B extending class A:</p>
<pre class="lang-java prettyprint-override"><code>public class B extends A {
    int i;

    public B() {
        i=4;
    }

    @Override
    public void print() {
        System.out.println("calling B.print");
        System.out.println(i);
    }
</code>```

Finally creating object of class B

```<code>public class Tester {
    public static void main(String[] args) {
        A obj = new B();
        obj.print();
    }
}
</code>```

Output:

calling B.print
0
calling B.print
4
```

Shouldn't this.print() from inside A() constructor call A's method()?

ContentLicense: CC BY-SA 4.0

Body:
Can any one please help me in understanding the output.

public class A {
    public A() {
        this.print();
    }

    public void print() {
        System.out.println("A");

    }
}

Class B extending class A:

public class B extends A {
    int i;

    public B() {
        i=4;
    }

    @Override
    public void print() {
        System.out.println("calling B.print");
        System.out.println(i);
    }

Finally creating object of class B

public class Tester {
    public static void main(String[] args) {
        A obj = new B();
        obj.print();
    }
}

Output:

calling B.print
0
calling B.print
4

Shouldn't this.print() from inside A() constructor call A's method()?


问:
Add gcloud "Google Auth Library" to App Access Control on Google Workspace Admin
I use gcloud auth application-default login to authenticate my local applications to Google Cloud Platform services.

One of them is a Python app that performs a query on many BigQuery tables and they work well except for one Table, which its values come from a Drive Spreadsheet (if you go in the table details on the Console it has the link to the drive spreadsheet).

I did some research and found that, in order for it to work, I have to explicitly inform the scope https://www.googleapis.com/auth/drive. So I did like this and it worked for production environemnt since the credentials are loaded from Kubernetes Workload Identity:

```<code>credentials, _ = google.auth.default(scopes=[
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/drive"
])
</code>```

But for running it locally I need to specify the scopes to my gcloud auth application-default login like this:

```<code>gcloud auth application-default login --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform
</code>```

I've ran the command and was prompted with the authorization issue:

```<code>Access blocked: Authorization Error

myuser@domain.com
Access to your account data is restricted by policies within your organization. Please contact the administrator of your organization for more information.
If you are a developer of Google Auth Library, see error details.
Error 400: admin_policy_enforced
</code>```

This error happens because the Google Workspace Admin restricts access to all applications , except the ones whitelisted at "App Access Control" section.

I contacted my Workspace admin so we went to the "App Access Controll" to add the gcloud to the Apps whitelist. We tried to search anything related to Google like "Google Cloud Platform" or "Google Auth Library" to add to the whitelist, but there isn't anything. I tried removing the restriction and it works, but it's  not acceptable for our security standards.

Is there any way to get around this issue?

Body:
I use gcloud auth application-default login to authenticate my local applications to Google Cloud Platform services.

One of them is a Python app that performs a query on many BigQuery tables and they work well except for one Table, which its values come from a Drive Spreadsheet (if you go in the table details on the Console it has the link to the drive spreadsheet).

I did some research and found that, in order for it to work, I have to explicitly inform the scope https://www.googleapis.com/auth/drive. So I did like this and it worked for production environemnt since the credentials are loaded from Kubernetes Workload Identity:

credentials, _ = google.auth.default(scopes=[
    "https://www.googleapis.com/auth/cloud-platform",
    "https://www.googleapis.com/auth/drive"
])

But for running it locally I need to specify the scopes to my gcloud auth application-default login like this:

gcloud auth application-default login --scopes=https://www.googleapis.com/auth/drive,https://www.googleapis.com/auth/cloud-platform

I've ran the command and was prompted with the authorization issue:

Access blocked: Authorization Error

myuser@domain.com
Access to your account data is restricted by policies within your organization. Please contact the administrator of your organization for more information.
If you are a developer of Google Auth Library, see error details.
Error 400: admin_policy_enforced

This error happens because the Google Workspace Admin restricts access to all applications , except the ones whitelisted at "App Access Control" section.

I contacted my Workspace admin so we went to the "App Access Controll" to add the gcloud to the Apps whitelist. We tried to search anything related to Google like "Google Cloud Platform" or "Google Auth Library" to add to the whitelist, but there isn't anything. I tried removing the restriction and it works, but it's  not acceptable for our security standards.

Is there any way to get around this issue?


问:
rebase mybranch with master when we have 20-30 number of commits
I am trying to rebase mybranch with master and changes are a lot. I am getting so many merge conflict and have 20-30 number of commits. I even tried to squash all commits and rebase it but that also taking too much time. Is there any smart/easy way to do that.


问:
Split character column by date into new date column
I am working with a character vector describing locations and dates. I am trying to separate the vector into a location and date column. The character line does not possess clear rules for using stringer or separate functions, however, the character line always ends with a date like "April 20." I have tried separating on months of the year, but then lose the month name.

#sample

```<code>    locations <- c("Molino November 28.", "Wolf River Bridge December 4.")
    df <- data.frame(locations)e here
</code>```

#using stringr produces error

```<code>     df1[c('location', 'date')] <- str_split_fixed(df$locations, c('November', 'December'), 2)
</code>```

Trying to produce vectors like below:

```<code>Location                      Date
"Molino"                  "November 28"
"Wolf River Bridge"       "December 4"
</code>```

Body:
I am working with a character vector describing locations and dates. I am trying to separate the vector into a location and date column. The character line does not possess clear rules for using stringer or separate functions, however, the character line always ends with a date like "April 20." I have tried separating on months of the year, but then lose the month name.

#sample

    locations <- c("Molino November 28.", "Wolf River Bridge December 4.")
    df <- data.frame(locations)e here

#using stringr produces error

     df1[c('location', 'date')] <- str_split_fixed(df$locations, c('November', 'December'), 2)

Trying to produce vectors like below:

Location                      Date
"Molino"                  "November 28"
"Wolf River Bridge"       "December 4"


问:
Crash gutter icon in Android Studio not showing?
I'm using Android Studio Electric Eel | 2022.1.1 version and the App Quality Insights are a really great addition to the tool. I can see the list of crashes in that windows, but it doesn't highlight the codebase with that gutter icon for a crash next to the lines of code.

Anyone else with the same problem?


问:
Page posts scheduled via Graph API do not appear in Meta Business Suite
I schedule photo posts to be published later on my Facebook page via Graph API. These scheduled posts contain a message, one photo and a comment.

The scheduled posts DO appear in Creator Studio, but do NOT appear in Meta Business Suite. (Once the post is published, instantly appears in Meta Business Suite as well)

I have been fine with it, but Facebook plans to shut down Creator Studio, thus I will need to have these posts in Meta Business Suite.

How could I solve this problem and make scheduled posts appear in Meta Business Suite?

I tried simpler posts (e.g. only photo, without message and comment) to no avail.


问:
How to parse JSON string with un-escaped characters
Am receiving a string which represents a JSON object, the issue is some values have unescaped characters which causing the JSON.parse to fail, for simplicity the json could look like this

```<code>'{"desc":" ""#keyword"" click "}'
</code>```

I have tried couple of solutions, like replacing the qoutes with regex before parsing

```<code>/("desc":"[^"]*)([^\\])"/g
</code>```

but it also failed to parse, also tried a library called json5 but it's also failing to parse.

Body:
Am receiving a string which represents a JSON object, the issue is some values have unescaped characters which causing the JSON.parse to fail, for simplicity the json could look like this

'{"desc":" ""#keyword"" click "}'

I have tried couple of solutions, like replacing the qoutes with regex before parsing

/("desc":"[^"]*)([^\\])"/g

but it also failed to parse, also tried a library called json5 but it's also failing to parse.


问:
Laravel execute function inside relation
I have some troubles after implementing polymorphic relations into my Laravel database.
Namely, I'm trying to execute two queries, one to save some counts and the other to update the polymorphic table. But update never happens, and I have no errors. Actually, update function works, but it's not executing function before that.

So, here is what my function looks like:

```<code>public function setThreadLastInteraction(Thread $thread)
    {
        return $this->ancestorsAndSelf->map(function ($c) use ($thread) {
            try {
                $c->statistics(function ($query) use ($thread) {
                    try {
                        $query->interaction()->save($thread);
                    } catch (\Exception $e) {
                        Log::error($e, __NAMESPACE__, __FUNCTION__);
                    }
                })->update([
                    'threads_count' => DB::raw('threads_count + 1'),
                ]);
            } catch (\Exception $e) {
                Log::error($e, __NAMESPACE__, __FUNCTION__);
            }
        })->toArray();
    }
</code>```

First, I have to update every category related to the other one, after that I'm doing some function for each of them.

As you see, I'm accessing the Statistics model. Only thing that is not working is inside the statistics function:

```<code>try {
    $query->interaction()->save($thread);
} catch (\Exception $e) {
    Log::error($e, __NAMESPACE__, __FUNCTION__);
}
</code>```

I'm obviously calling relation as it should be, cause It's updating 'threads_count'.
But here is how it looks like:

```<code>public function statistics(): HasOne
    {
        return $this->hasOne(Statistics::class);
    }
</code>```

And finally, inside Statistics class, relation that should be updated but it's not.

```<code>public function interaction(): MorphTo
    {
        return $this->morphTo();
    }
</code>```

I tried to remove everything inside statistics function and do it like (still inside map function):

```<code>$c->statistics()->interaction()->save($thread);
$c->statistics()->update([
                    'threads_count' => DB::raw('threads_count + 1'),
                ]);
</code>```

That way, I'm accessing directly to the model. But it says that interaction relationship is not existing.

What could be the issue? Why Interaction function is not accessible within relation?

Body:
I have some troubles after implementing polymorphic relations into my Laravel database.
Namely, I'm trying to execute two queries, one to save some counts and the other to update the polymorphic table. But update never happens, and I have no errors. Actually, update function works, but it's not executing function before that.

So, here is what my function looks like:

public function setThreadLastInteraction(Thread $thread)
    {
        return $this->ancestorsAndSelf->map(function ($c) use ($thread) {
            try {
                $c->statistics(function ($query) use ($thread) {
                    try {
                        $query->interaction()->save($thread);
                    } catch (\Exception $e) {
                        Log::error($e, __NAMESPACE__, __FUNCTION__);
                    }
                })->update([
                    'threads_count' => DB::raw('threads_count + 1'),
                ]);
            } catch (\Exception $e) {
                Log::error($e, __NAMESPACE__, __FUNCTION__);
            }
        })->toArray();
    }

First, I have to update every category related to the other one, after that I'm doing some function for each of them.

As you see, I'm accessing the Statistics model. Only thing that is not working is inside the statistics function:

try {
    $query->interaction()->save($thread);
} catch (\Exception $e) {
    Log::error($e, __NAMESPACE__, __FUNCTION__);
}

I'm obviously calling relation as it should be, cause It's updating 'threads_count'.
But here is how it looks like:

public function statistics(): HasOne
    {
        return $this->hasOne(Statistics::class);
    }

And finally, inside Statistics class, relation that should be updated but it's not.

public function interaction(): MorphTo
    {
        return $this->morphTo();
    }

I tried to remove everything inside statistics function and do it like (still inside map function):

$c->statistics()->interaction()->save($thread);
$c->statistics()->update([
                    'threads_count' => DB::raw('threads_count + 1'),
                ]);

That way, I'm accessing directly to the model. But it says that interaction relationship is not existing.

What could be the issue? Why Interaction function is not accessible within relation?


问:
'Create' button on ECS Service creation doesn't do anything
I want to create an ECS service with ELB ('create new' option) and EC2 as backend. I am using AWS console and I amusing Frankfurt region.

When I click 'Create' button on the console, nothing happens! I cannot see any errors.

I tried the above with admin rights and even with the root account (!).

When I remove ELB, clicking 'Create' operates properly and the service is created.


问:
✘ [ERROR] Could not resolve "async_hooks"
Gettiing eroor, asking to add "platform: 'node'". Can someone help me where to add it.
project is > https://github.com/dicebear/api

```<code>$wrangler dev                                                                                 1 ✘  65%   09:02:34 PM 
 ⛅ wrangler 2.7.1
-------------------
▲ [WARNING] Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details.

⬣ Listening at http://0.0.0.0:8787
- http://127.0.0.1:8787
- http://192.168.0.112:8787
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ [b] open a browser, [d] open Devtools, [l] turn on local mode, [c] clear console, [x] to exit                                                                                │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

✘ [ERROR] Could not resolve "async_hooks"

    node_modules/fastify/lib/contentTypeParser.js:3:34:
      3 │ const { AsyncResource } = require('async_hooks')
        ╵                                   ~~~~~~~~~~~~~

  The package "async_hooks" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

✘ [ERROR] Build failed with 1 error:

  node_modules/fastify/lib/contentTypeParser.js:3:34: ERROR: Could not resolve "async_hooks"
</code>```

Gettiing eroor, asking to add "platform: 'node'". Can some one help me where to add it.
project is > https://github.com/dicebear/api

Body:
Gettiing eroor, asking to add "platform: 'node'". Can someone help me where to add it.
project is > https://github.com/dicebear/api

$wrangler dev                                                                                 1 ✘  65%   09:02:34 PM 
 ⛅ wrangler 2.7.1
-------------------
▲ [WARNING] Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details.

⬣ Listening at http://0.0.0.0:8787
- http://127.0.0.1:8787
- http://192.168.0.112:8787
╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│ [b] open a browser, [d] open Devtools, [l] turn on local mode, [c] clear console, [x] to exit                                                                                │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯

✘ [ERROR] Could not resolve "async_hooks"

    node_modules/fastify/lib/contentTypeParser.js:3:34:
      3 │ const { AsyncResource } = require('async_hooks')
        ╵                                   ~~~~~~~~~~~~~

  The package "async_hooks" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

✘ [ERROR] Build failed with 1 error:

  node_modules/fastify/lib/contentTypeParser.js:3:34: ERROR: Could not resolve "async_hooks"

Gettiing eroor, asking to add "platform: 'node'". Can some one help me where to add it.
project is > https://github.com/dicebear/api


问:
How to print  tag from cshtml, only other tags printed
I am about to export my cshtml view into pdf, it works but only on text, not the image /  tag. Please help

here is my cshtml

```<code>@model VDITest_MuhammadRidwan.Models.MemberModel

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div id="PrintPDF">
    <h4>Member Details</h4>
    <hr />
        <img src='@Model.AvatarUrl' alt='avatar' style='width:250px; height:250px; border-radius:50%;' />
    <dl class="row">
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.NIK)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.NIK)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Address)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Address)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.Phone)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.Phone)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.BirthPlace)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.BirthPlace)
        </dd>
        <dt class="col-sm-2">
            @Html.DisplayNameFor(model => model.BirthDate)
        </dt>
        <dd class="col-sm-10">
            @Html.DisplayFor(model => model.BirthDate)
        </dd>
    </dl>
</div>

<div>

    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
   <form method="post" asp-controller="Home" asp-action="ExportExcel">
        <input type="hidden" name="ExportData" id="ExportData" />
        <input type="submit" id="btnSubmit" value="Export" class="btn btn-primary" />
    </form>

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">
    $(function () {
        $("#btnSubmit").click(function () {
            $("input[name='ExportData']").val($("#PrintPDF").html());
        });
    });
</script>

</code>```

and here is my controller action

```<code>       [HttpPost]
        public FileResult ExportExcel(string ExportData)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                StringReader reader = new StringReader(ExportData);
                Document PdfFile = new Document(PageSize.A4);
                PdfWriter writer = PdfWriter.GetInstance(PdfFile, stream);

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                PdfFile.Open();
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, PdfFile, reader);
                PdfFile.Close();
                return File(stream.ToArray(), "application/pdf", "ExportData.pdf");
            }
        }
</code>```

I have already debug the controller to check the string ExportData parameter, so this is what I got from string ExportData parameter

```<code><h4>Member Details</h4>
<hr>
    <img src="/avatar\/0effac8e-7bb7-4727-a77d-165bb7eecf38bocilkematian.PNG" alt="avatar" style="width:250px; height:250px; border-radius:50%;">
<dl class="row">
    <dt class="col-sm-2">
        Name
    </dt>
    <dd class="col-sm-10">
        Joko
    </dd>
    <dt class="col-sm-2">
        Birth Date
    </dt>
    <dd class="col-sm-10">
        1233456789
    </dd>
    <dt class="col-sm-2">
        Address
    </dt>
    <dd class="col-sm-10">
        India
    </dd>
    <dt class="col-sm-2">
        Phone
    </dt>
    <dd class="col-sm-10">
        123456789654
    </dd>
    <dt class="col-sm-2">
        Birth Place
    </dt>
    <dd class="col-sm-10">
        Jombang
    </dd>
    <dt class="col-sm-2">
        Birth Date
    </dt>
    <dd class="col-sm-10">
        18/01/2023
    </dd>
</dl>
</code>```

All converted to pdf except the image. Please kindly help, I am new here thank you

I tried to convert my cshtml into pdf, I expected all cshtml converted including the image tag, but the actual result is all printed except the image tag.

the result is like this

Title: How to print <img> tag from cshtml, only other tags printed

Body:
I am about to export my cshtml view into pdf, it works but only on text, not the image /  tag. Please help

here is my cshtml

@model VDITest_MuhammadRidwan.Models.MemberModel

@{
    ViewData["Title"] = "Details";
}

Details

Member Details

            @Html.DisplayNameFor(model => model.Name)

            @Html.DisplayFor(model => model.Name)

            @Html.DisplayNameFor(model => model.NIK)

            @Html.DisplayFor(model => model.NIK)

            @Html.DisplayNameFor(model => model.Address)

            @Html.DisplayFor(model => model.Address)

            @Html.DisplayNameFor(model => model.Phone)

            @Html.DisplayFor(model => model.Phone)

            @Html.DisplayNameFor(model => model.BirthPlace)

            @Html.DisplayFor(model => model.BirthPlace)

            @Html.DisplayNameFor(model => model.BirthDate)

            @Html.DisplayFor(model => model.BirthDate)

    Edit |
    Back to List
   <form method="post" asp-controller="Home" asp-action="ExportExcel">
        <input type="hidden" name="ExportData" id="ExportData" />
        <input type="submit" id="btnSubmit" value="Export" class="btn btn-primary" />
    </form>

and here is my controller action

       [HttpPost]
        public FileResult ExportExcel(string ExportData)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                StringReader reader = new StringReader(ExportData);
                Document PdfFile = new Document(PageSize.A4);
                PdfWriter writer = PdfWriter.GetInstance(PdfFile, stream);

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                PdfFile.Open();
                XMLWorkerHelper.GetInstance().ParseXHtml(writer, PdfFile, reader);
                PdfFile.Close();
                return File(stream.ToArray(), "application/pdf", "ExportData.pdf");
            }
        }

I have already debug the controller to check the string ExportData parameter, so this is what I got from string ExportData parameter

Member Details

        Name

        Joko

        Birth Date

        1233456789

        Address

        India

        Phone

        123456789654

        Birth Place

        Jombang

        Birth Date

        18/01/2023

All converted to pdf except the image. Please kindly help, I am new here thank you

I tried to convert my cshtml into pdf, I expected all cshtml converted including the image tag, but the actual result is all printed except the image tag.

the result is like this


问:
Error exit code 1 on building project with msbuild.exe
I have one script gulpfile.js in which below code is present :

```<code>return exec (`msbuild.exe ElasticSearchApp.sfproj -t:Package -p:Configuration=Release`,function(err,stdout,stderr) {

console.log (stdout);
console.log (stdout);
console.log (stdout);
done(err);
});
</code>```

Running command: **gulp package **
Build is getting failed at this msbuild.exe sfproj file.It is a random behaviour.

```<code>**Error:

Error: exited with error code: 1
at childProcess.emit(node:events:513:28)
at childProcess.emit(node:domain:552:15)
at Process.ChildProcess._handle.onexit(node:internal/child_process:283:12)**
</code>```

Ran the musbuild.exe line manually and it worked. Its not working when running it through gulp package command (calling gulfile.js)

Body:
I have one script gulpfile.js in which below code is present :

return exec (`msbuild.exe ElasticSearchApp.sfproj -t:Package -p:Configuration=Release`,function(err,stdout,stderr) {

console.log (stdout);
console.log (stdout);
console.log (stdout);
done(err);
});

Running command: **gulp package **
Build is getting failed at this msbuild.exe sfproj file.It is a random behaviour.

**Error:

Error: exited with error code: 1
at childProcess.emit(node:events:513:28)
at childProcess.emit(node:domain:552:15)
at Process.ChildProcess._handle.onexit(node:internal/child_process:283:12)**

Ran the musbuild.exe line manually and it worked. Its not working when running it through gulp package command (calling gulfile.js)


问:
Voice Command for action.devices.traits.Dispense
I have an ESP32 device that weighs my kettle and tells me how many cups of water are in the kettle. I have a rest server that returns the cups, so this will be Cloud-to-cloud.
I have used the smart washer codelab as a starting point https://developers.home.google.com/codelabs/smarthome-washer#2, got it working perfectly. I then added a Dispense trait. (all the other washer code remains. So device is still called washer)
https://developers.home.google.com/cloud-to-cloud/traits/dispense

```<code>supportedDispenseItems: [
                        {
                          item_name: "kettle-cups",
                          item_name_synonyms: [
                            {
                              lang: "en",
                              synonyms: [
                              "cups",
                                "cups in kettle",
                                "water",
                                "kettle water"
                              ]
                            }
                          ],
                          supported_units: [
                            "CUPS"
                          ],
                          default_portion: {
                            amount: 2,
                            unit: "CUPS"
                          }
                        }
                      ]
</code>```

Using the same firebase database code in the sample I added the cups to the db. I'm manually changing the value via the webpage that came with the sample. All working fine. However, I can't access the values via the google home app or the google assistant app. I have a Google Home speaker too.

this is the update state in main.js - it posts to the db

```<code>  const pkg = {
    OnOff: { on: elOnOff.classList.contains('is-checked') },
    RunCycle: { dummy: elRunCycle.classList.contains('is-checked') },
    StartStop: {
      isPaused: elStartStopPaused.classList.contains('is-checked'),
      isRunning: elStartStopRunning.classList.contains('is-checked')
    },
    Dispense: {
      dispenseItems: {
      itemName: "kettle-cups",
        amountRemaining: {
          amount: elDispenseCupsRemaining.value,
          unit: "CUPS"
        }
      }
    }
  };
</code>```

**1. Am I missing something in how I've configured the Dispense part?
2. What commands can I try to access the washer -> Dispense -> amountRemaining -> amount? **

I have confirmed that I can use voice commands to turn the washer on/off etc. and it will tell me if the washer is on/off if I ask Hey Google is the washer on? I get the correct answer.
I tried different commands that combined "Washer" and Kettle cups" etc. and the nicknames. I tried "Hey google what is the washer amount remaining", " ... what is the washer cups"
I am expecting it to be able to tell me how many cups of water are in the washer but suspect I haven't got the command right or the configuration.

Body:
I have an ESP32 device that weighs my kettle and tells me how many cups of water are in the kettle. I have a rest server that returns the cups, so this will be Cloud-to-cloud.
I have used the smart washer codelab as a starting point https://developers.home.google.com/codelabs/smarthome-washer#2, got it working perfectly. I then added a Dispense trait. (all the other washer code remains. So device is still called washer)
https://developers.home.google.com/cloud-to-cloud/traits/dispense

supportedDispenseItems: [
                        {
                          item_name: "kettle-cups",
                          item_name_synonyms: [
                            {
                              lang: "en",
                              synonyms: [
                              "cups",
                                "cups in kettle",
                                "water",
                                "kettle water"
                              ]
                            }
                          ],
                          supported_units: [
                            "CUPS"
                          ],
                          default_portion: {
                            amount: 2,
                            unit: "CUPS"
                          }
                        }
                      ]

Using the same firebase database code in the sample I added the cups to the db. I'm manually changing the value via the webpage that came with the sample. All working fine. However, I can't access the values via the google home app or the google assistant app. I have a Google Home speaker too.

this is the update state in main.js - it posts to the db

  const pkg = {
    OnOff: { on: elOnOff.classList.contains('is-checked') },
    RunCycle: { dummy: elRunCycle.classList.contains('is-checked') },
    StartStop: {
      isPaused: elStartStopPaused.classList.contains('is-checked'),
      isRunning: elStartStopRunning.classList.contains('is-checked')
    },
    Dispense: {
      dispenseItems: {
      itemName: "kettle-cups",
        amountRemaining: {
          amount: elDispenseCupsRemaining.value,
          unit: "CUPS"
        }
      }
    }
  };

**1. Am I missing something in how I've configured the Dispense part?
2. What commands can I try to access the washer -> Dispense -> amountRemaining -> amount? **

I have confirmed that I can use voice commands to turn the washer on/off etc. and it will tell me if the washer is on/off if I ask Hey Google is the washer on? I get the correct answer.
I tried different commands that combined "Washer" and Kettle cups" etc. and the nicknames. I tried "Hey google what is the washer amount remaining", " ... what is the washer cups"
I am expecting it to be able to tell me how many cups of water are in the washer but suspect I haven't got the command right or the configuration.


问:
Getting ` SyntaxError: Cannot use import statement outside a module` in NEXT.js
I'm using lightweight-chart library in next.js.(typescript)

And I got this error while using the lightweight-chart library.

```<code>error - /home/my-project/node_modules/lightweight-charts/dist/lightweight-charts.esm.development.js:7
import { bindToDevicePixelRatio } from 'fancy-canvas/coordinate-space';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at compileFunction (<anonymous>)
</code>```

I tried updating my tsconfig.json file with below:

```<code>"esModuleInterop": true,
    "module": "esnext",
</code>```

but still having same issue.

here, I'm adding my component:

import { createChart } from "lightweight-charts";
import React, { useEffect, useRef } from "react";

const PriceChart = (): JSX.Element => {
  const chartContainerRef = useRef();

  useEffect(() => {
    if (chartContainerRef.current) {
      const chart = createChart(chartContainerRef.current, {
        width: 1000,
        height: 600,
        layout: {
          textColor: "black",
          background: { type: "solid", color: "white" },
        },
        grid: {
          vertLines: {
            color: "rgba(197, 203, 206, 0.5)",
          },
          horzLines: {
            color: "rgba(197, 203, 206, 0.5)",
          },
        },

        rightPriceScale: {
          borderColor: "rgba(197, 203, 206, 0.8)",
        },
        timeScale: {
          borderColor: "rgba(197, 203, 206, 0.8)",
        },
      });

      const candleSeries = chart.addCandlestickSeries({
        upColor: "#26a69a",
        downColor: "#ef5350",
        wickDownColor: "#ef5350",
        wickUpColor: "#26a69a",
        borderVisible: false,
      });

      candleSeries.setData([
        {
          time: "2018-10-19",
          open: 180.34,
          high: 180.99,
          low: 178.57,
          close: 179.85,
        },
        {
          time: "2018-10-22",
          open: 180.82,
          high: 181.4,
          low: 177.56,
          close: 178.75,
        },
      ]);

      return () => {
        chart.remove();
      };
    }
  }, []);

  return
;
};

export default PriceChart;```

Anyone know how to fix it?

I tried the same code with plain react.js and worked well!

Body:
I'm using lightweight-chart library in next.js.(typescript)

And I got this error while using the lightweight-chart library.

error - /home/my-project/node_modules/lightweight-charts/dist/lightweight-charts.esm.development.js:7
import { bindToDevicePixelRatio } from 'fancy-canvas/coordinate-space';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at compileFunction (<anonymous>)

I tried updating my tsconfig.json file with below:

"esModuleInterop": true,
    "module": "esnext",

but still having same issue.

here, I'm adding my component:

import { createChart } from "lightweight-charts";
import React, { useEffect, useRef } from "react";

const PriceChart = (): JSX.Element => {
  const chartContainerRef = useRef();

  useEffect(() => {
    if (chartContainerRef.current) {
      const chart = createChart(chartContainerRef.current, {
        width: 1000,
        height: 600,
        layout: {
          textColor: "black",
          background: { type: "solid", color: "white" },
        },
        grid: {
          vertLines: {
            color: "rgba(197, 203, 206, 0.5)",
          },
          horzLines: {
            color: "rgba(197, 203, 206, 0.5)",
          },
        },

        rightPriceScale: {
          borderColor: "rgba(197, 203, 206, 0.8)",
        },
        timeScale: {
          borderColor: "rgba(197, 203, 206, 0.8)",
        },
      });

      const candleSeries = chart.addCandlestickSeries({
        upColor: "#26a69a",
        downColor: "#ef5350",
        wickDownColor: "#ef5350",
        wickUpColor: "#26a69a",
        borderVisible: false,
      });

      candleSeries.setData([
        {
          time: "2018-10-19",
          open: 180.34,
          high: 180.99,
          low: 178.57,
          close: 179.85,
        },
        {
          time: "2018-10-22",
          open: 180.82,
          high: 181.4,
          low: 177.56,
          close: 178.75,
        },
      ]);

      return () => {
        chart.remove();
      };
    }
  }, []);

  return
;
};

export default PriceChart;

Anyone know how to fix it?

I tried the same code with plain react.js and worked well!


问:
.net 5.0 resolve dependencies from a separate folder
with two .net 5.0 projects outputs client and server, each folder includes about 200 mb of the same dependencies dll files (managed),

how to put these common dlls in a separate folder common and force both client.dll and server.dll to resolve their dependencies from it so a space of redundant 200 mb is gained?

client and server have to stay separate.

client.csproj

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

    <PropertyGroup>
      <OutputType>WinExe</OutputType>
      <UseWindowsForms>true</UseWindowsForms>
      <TargetFrameworks>net5.0-windows</TargetFrameworks>
      <SelfContained>false</SelfContained>
      <LangVersion>9.0</LangVersion>
      <Platforms>AnyCPU;x64;x86</Platforms>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
      <OutputPath>..\..\release\client\</OutputPath>
      <AssemblyName>client</AssemblyName>
      <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
      <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
    </PropertyGroup>

    ...

</Project>
</code>```

server.csproj

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net5.0-windows</TargetFramework>
        <SelfContained>false</SelfContained>
        <LangVersion>9.0</LangVersion>
        <Configuration>Release</Configuration>
        <Platforms>AnyCPU;x64;x86</Platforms>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
        <OutputPath>..\..\release\server\</OutputPath>
        <AssemblyName>server</AssemblyName>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
    </PropertyGroup>

    ...

</Project>
</code>```

Body:
with two .net 5.0 projects outputs client and server, each folder includes about 200 mb of the same dependencies dll files (managed),

how to put these common dlls in a separate folder common and force both client.dll and server.dll to resolve their dependencies from it so a space of redundant 200 mb is gained?

client and server have to stay separate.

client.csproj

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

    <PropertyGroup>
      <OutputType>WinExe</OutputType>
      <UseWindowsForms>true</UseWindowsForms>
      <TargetFrameworks>net5.0-windows</TargetFrameworks>
      <SelfContained>false</SelfContained>
      <LangVersion>9.0</LangVersion>
      <Platforms>AnyCPU;x64;x86</Platforms>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
      <OutputPath>..\..\release\client\</OutputPath>
      <AssemblyName>client</AssemblyName>
      <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
      <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
    </PropertyGroup>

    ...

</Project>

server.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
    <PropertyGroup>
        <TargetFramework>net5.0-windows</TargetFramework>
        <SelfContained>false</SelfContained>
        <LangVersion>9.0</LangVersion>
        <Configuration>Release</Configuration>
        <Platforms>AnyCPU;x64;x86</Platforms>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
        <OutputPath>..\..\release\server\</OutputPath>
        <AssemblyName>server</AssemblyName>
        <AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
        <AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
    </PropertyGroup>

    ...

</Project>


问:
Is there a native HTTP response caching facility / step in Microsoft Power Automate?
I'm using Power Automate to build an API in front of an ETL process, but am finding that the performance of this product is nightmarishly slow and unpredictable.

This process receives an HTTP request with some parameters, reads and converts some rows from an Excel file hosted in Sharepoint to JSON and sends a response.

Example request:

```<code>{{ url }}?id_to_fetch=ABC123
</code>```

Example response

```<code>{ records: ["X", "Y", "Z"] }
</code>```

I would like to avoid the overhead of setting up a full-blown CDN in front of what should be an extraordinarily simple operation.

Is there any way to serve a cached response from a Power Automate pipeline without adding any other non-free products to the mix?

Body:
I'm using Power Automate to build an API in front of an ETL process, but am finding that the performance of this product is nightmarishly slow and unpredictable.

This process receives an HTTP request with some parameters, reads and converts some rows from an Excel file hosted in Sharepoint to JSON and sends a response.

Example request:

{{ url }}?id_to_fetch=ABC123

Example response

{ records: ["X", "Y", "Z"] }

I would like to avoid the overhead of setting up a full-blown CDN in front of what should be an extraordinarily simple operation.

Is there any way to serve a cached response from a Power Automate pipeline without adding any other non-free products to the mix?


问:
Self-signed certificates not allowed. What does it mean?
I have created a moodle website on a shared webhosting using cpanel:
https://class.rafiee.net

I also have created a Nextcloud on this hosting :
https://cloud.rafiee.net

I followed all configurations explained [Here][1] and [Here][2] to integrate Nextcloud to be as an Repository in my Moodle website.

Everything worked fine, and I could log in to my Nextcloud account in Moodle. However, I can't see my files. After searching forum for hours, I found this note:

Authentication seems to have succeeded, but the filepicker shows
"There are no files". It is possible that HTTPS is not configured
correctly on the Nextcloud end. You need a valid and trusted
certificate for your Nextcloud server! A self-signed certificate will
not work. Unlike in the browser, you cannot manually "trust" a
self-signed server certificate. You should also check that the Apache
modules "rewrite", "headers" and "env" are installed and enabled in
the Nextcloud server.

This is exactly my issue, I can login successfully, but I can't see my files there.
I created a ticket to my hosting admin and he sent me Apache report:

```<code>[root@nl-s2 ~]# httpd -M | grep rewrite
 rewrite_module (shared)
[root@nl-s2 ~]# httpd -M | grep headers
 headers_module (shared)
[root@nl-s2 ~]# httpd -M | grep env
 setenvif_module (shared)
</code>```

So, as far as I understand, everything is fine. So, my guess is that the problem related to my certificate. I use free SSL certificate which will be extended every three month by my hosting. Is it related to my ssl certificate?

I hope someone explain me the issue clearly since I'm not very expert in such a problem.
Thanks in adnace.
[1]: https://docs.moodle.org/401/en/Nextcloud_repository
[2]: https://docs.moodle.org/401/en/OAuth_2_Nextcloud_service#Nextcloud_configuration

Body:
I have created a moodle website on a shared webhosting using cpanel:
https://class.rafiee.net

I also have created a Nextcloud on this hosting :
https://cloud.rafiee.net

I followed all configurations explained [Here][1] and [Here][2] to integrate Nextcloud to be as an Repository in my Moodle website.

Everything worked fine, and I could log in to my Nextcloud account in Moodle. However, I can't see my files. After searching forum for hours, I found this note:

Authentication seems to have succeeded, but the filepicker shows
"There are no files". It is possible that HTTPS is not configured
correctly on the Nextcloud end. You need a valid and trusted
certificate for your Nextcloud server! A self-signed certificate will
not work. Unlike in the browser, you cannot manually "trust" a
self-signed server certificate. You should also check that the Apache
modules "rewrite", "headers" and "env" are installed and enabled in
the Nextcloud server.

This is exactly my issue, I can login successfully, but I can't see my files there.
I created a ticket to my hosting admin and he sent me Apache report:

[root@nl-s2 ~]# httpd -M | grep rewrite
 rewrite_module (shared)
[root@nl-s2 ~]# httpd -M | grep headers
 headers_module (shared)
[root@nl-s2 ~]# httpd -M | grep env
 setenvif_module (shared)

So, as far as I understand, everything is fine. So, my guess is that the problem related to my certificate. I use free SSL certificate which will be extended every three month by my hosting. Is it related to my ssl certificate?

I hope someone explain me the issue clearly since I'm not very expert in such a problem.
Thanks in adnace.
[1]: https://docs.moodle.org/401/en/Nextcloud_repository
[2]: https://docs.moodle.org/401/en/OAuth_2_Nextcloud_service#Nextcloud_configuration


问:
What's the best practices in C# for public members that must be used for internal use only?
In a scenario similar to the one described here, I have 2 different assemblies and I need to declare some members in classes of assembly A that must be used only by my classes in assembly B (I mean, who uses a class of the assembly A must be discouraged to call/use those methods/properties/fields).

What is the best practice to declare them?

Creating an interface for them (so you need to explicitly cast the class of assembly A to the interface to see them)

Naming them with a particular prefix (so I can "train my user" to avoid calling/using them)

Naming them with the first letter lowercase (so Intellisense will put them at the end and they will be "more hidden")

Notes:

Assembly A is built against .net6 (cross-platform) and assembly B is built against net6-windows (O.S. Windows specific)

I can't use InternalsVisibleTo because Assembly A must be obfuscated and this prevents obfuscation for internal members.

Listed below is the code for a better explanation of those cases.

assembly A

case 1

```<code>public class Workspace : IWorkspaceInternal
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   void IWorkspaceInternal.MyMethod1() { //do something }
}

/// <summary>
/// Interfaces with methods/properties/classes for internal use only.
/// </summary>
public interface IWorkspaceInternal
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyMethod1() { //do something }
}
</code>```

case 2

```<code>public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void Foo_Method1() { //do something }
}
</code>```

case 3

```<code>public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void myInternalMethod1() { //do something }
}
</code>```

Other ideas?

Body:
In a scenario similar to the one described here, I have 2 different assemblies and I need to declare some members in classes of assembly A that must be used only by my classes in assembly B (I mean, who uses a class of the assembly A must be discouraged to call/use those methods/properties/fields).

What is the best practice to declare them?

Creating an interface for them (so you need to explicitly cast the class of assembly A to the interface to see them)

Naming them with a particular prefix (so I can "train my user" to avoid calling/using them)

Naming them with the first letter lowercase (so Intellisense will put them at the end and they will be "more hidden")

Notes:

Assembly A is built against .net6 (cross-platform) and assembly B is built against net6-windows (O.S. Windows specific)

I can't use InternalsVisibleTo because Assembly A must be obfuscated and this prevents obfuscation for internal members.

Listed below is the code for a better explanation of those cases.

assembly A

case 1

public class Workspace : IWorkspaceInternal
{
   ///
   /// Does stuff.
   ///
   public void MyRealPublicMethod() { //do something }

   ///
   /// For internal use only.
   ///
   void IWorkspaceInternal.MyMethod1() { //do something }
}

///
/// Interfaces with methods/properties/classes for internal use only.
///
public interface IWorkspaceInternal
{
   ///
   /// Does stuff.
   ///
   public void MyMethod1() { //do something }
}

case 2

public class Workspace
{
   ///
   /// Does stuff.
   ///
   public void MyRealPublicMethod() { //do something }

   ///
   /// For internal use only.
   ///
   public void Foo_Method1() { //do something }
}

case 3

public class Workspace
{
   ///
   /// Does stuff.
   ///
   public void MyRealPublicMethod() { //do something }

   ///
   /// For internal use only.
   ///
   public void myInternalMethod1() { //do something }
}

Other ideas?


问:
How to fetch changes from a forked repository which is a subtree
So I have an issue wherein I forked Repository A to create Repository B.

Then I added Repository B into a subdirectory of Repository C via the subtree command as follows:

git subtree add --prefix={SubdirectoryForRepositoryC} /remote-name {RepositoryBRemoteName} master --squash

I had been using the following command to update the subtree:

git subtree pull --prefix={SubdirectoryForRepositoryC} /remote-name {RepositoryBRemoteName} master --squash

While I pulls changes from Repository B, it doesn't update Repository B based on Repository A and then pull those changes, which is what I need.

Effectively, is it possible to run a command within Repository C which updates Repository B based upon Repository A and then updates the Repository B subtree within Repository C?

Thank you so much!


问:
Azure bot creation failed - unreachable code reached
Bot creation failed for the single and multi-tenant.


问:
Custom import in Python
Idea is to import package or install it if not found from inside of python script
Basically my problem is in ability of importing package with passing string with name instead of name

```<code>import "time"               # this is invalid syntax
print(time.localtime())
</code>```

Full script

```<code>requirements =
{"jupyterlab":"python -m pip install jupyterlab",
"pandas":"python -m pip install pandas"}

for key in requirements:
    try:
        import key
    except:
        import os
        os.system(requirements[key])
</code>```

Maybe it can be solved some other way, but i am not familiar with that (except docker)

Title: Custom import in Python

Body:
Idea is to import package or install it if not found from inside of python script
Basically my problem is in ability of importing package with passing string with name instead of name

import "time"               # this is invalid syntax
print(time.localtime())

Full script

requirements =
{"jupyterlab":"python -m pip install jupyterlab",
"pandas":"python -m pip install pandas"}

for key in requirements:
    try:
        import key
    except:
        import os
        os.system(requirements[key])

Maybe it can be solved some other way, but i am not familiar with that (except docker)


问:
plotting more than 5 ellipses with venn eulerr
I would like to plot a venn diagram with more than 5 ellipses using the package eulerr.
Here is a reproducible example:

```<code>library(eulerr)
m <- venn(organisms, weights = c(10, 20, 5, 4, 8, 9, 2))
plot(m)
</code>```

I have checked the function the venn function: https://github.com/cran/eulerr/blob/master/R/venn.R, however it is not enough just to source locally and changing the number of combinations.
Is there a way around it?
thanks a lot!

Body:
I would like to plot a venn diagram with more than 5 ellipses using the package eulerr.
Here is a reproducible example:

library(eulerr)
m <- venn(organisms, weights = c(10, 20, 5, 4, 8, 9, 2))
plot(m)

I have checked the function the venn function: https://github.com/cran/eulerr/blob/master/R/venn.R, however it is not enough just to source locally and changing the number of combinations.
Is there a way around it?
thanks a lot!


问:
JSFrame method is being overwritten by Jquery
I am using both the JSFrame and JQuery libraries.
I want to use the JSFrame.on method in order to trigger an event when the window closes.
The problem is JQuery also has a .on method, and they are conflicting.
Any ideas?</p>


问:
Scroll content of iframe with main window scrollbar
Here is the example page that I'm working with:

https://www.midstory.org/toledos-water-issue-is-an-affordability-issue-too/

I have an iframe with an embedded storymap article on our WordPress site. The storymap article is meant to appear to be seamless with the rest of the website, filling the whole viewport and scrolling as if it were part of the main page. The problem is that, as you can see in the link, there are two scrollbars on the right-hand side. Because below the embedded article we have the comments box and footer for the website, which needs to be able to be scrolled to after the user reaches the bottom of the embedded article.

The current solution "works" but looks pretty cludgy. Is there a way to scroll the iframe article with the main scrollbar and then have it scroll the rest of the main page once reaching the bottom of the embedded article?

One idea I have is to make the embedded window fixed in the viewport and make the main article the height of the embedded one. Then I can scroll the page. But there's two problems:

How do I get the height of the embedded article?

How would I control the scroll position of the embedded article from the main one?


问:
Google In app purchase (consumable) listener is not working
I have an issue that is Payment is successful but addSubscriptionListener and addPurchaseListener not call

I am using this library:-
implementation  'com.github.akshaaatt:Google-IAP:1.2.5'

From this link:-
https://github.com/akshaaatt/Google-IAP

Here the listener is working after clicking twice on item to purchase.

Here is the listener:-

```<code> iapConnector.addPurchaseListener(object : PurchaseServiceListener {
            override fun onPricesUpdated(iapKeyPrices: Map<String, DataWrappers.SkuDetails>) {
                // list of available products will be received here, so you can update UI with prices if needed
            }

            override fun onProductPurchased(purchaseInfo: DataWrappers.PurchaseInfo) {
               // will be triggered whenever purchase succeeded
            }

            override fun onProductRestored(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered fetching owned products using IapConnector
            }
        })

 iapConnector.addSubscriptionListener(object : SubscriptionServiceListener {
            override fun onSubscriptionRestored(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered upon fetching owned subscription upon initialization
            }

            override fun onSubscriptionPurchased(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered whenever subscription succeeded
            }

            override fun onPricesUpdated(iapKeyPrices: Map<String, DataWrappers.SkuDetails>) {
                // list of available products will be received here, so you can update UI with prices if needed
            }
        })

</code>```

I have put in the button click listener but still it is not called at once.

Body:
I have an issue that is Payment is successful but addSubscriptionListener and addPurchaseListener not call

I am using this library:-
implementation  'com.github.akshaaatt:Google-IAP:1.2.5'

From this link:-
https://github.com/akshaaatt/Google-IAP

Here the listener is working after clicking twice on item to purchase.

Here is the listener:-

 iapConnector.addPurchaseListener(object : PurchaseServiceListener {
            override fun onPricesUpdated(iapKeyPrices: Map<String, DataWrappers.SkuDetails>) {
                // list of available products will be received here, so you can update UI with prices if needed
            }

            override fun onProductPurchased(purchaseInfo: DataWrappers.PurchaseInfo) {
               // will be triggered whenever purchase succeeded
            }

            override fun onProductRestored(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered fetching owned products using IapConnector
            }
        })

 iapConnector.addSubscriptionListener(object : SubscriptionServiceListener {
            override fun onSubscriptionRestored(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered upon fetching owned subscription upon initialization
            }

            override fun onSubscriptionPurchased(purchaseInfo: DataWrappers.PurchaseInfo) {
                // will be triggered whenever subscription succeeded
            }

            override fun onPricesUpdated(iapKeyPrices: Map<String, DataWrappers.SkuDetails>) {
                // list of available products will be received here, so you can update UI with prices if needed
            }
        })

I have put in the button click listener but still it is not called at once.


问:
Setting the margin on a entire row based on the value of a single cell?
I'm not that great with WPF/XAML hence the question. Here's my code so far

```<code><igDp:XamDataGrid DataSource="{Binding Items}" >
    <igDp:XamDataGrid.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type igDp:DataRecordPresenter}">
                <Setter Property="Margin" Value="{Binding Path=DataItem.Margin}"/>
            </Style>
        </ResourceDictionary>
    </igDp:XamDataGrid.Resources>

    <igDp:XamDataGrid.FieldLayouts>
        <igDp:FieldLayout>
            <igDp:FieldLayout.Fields>
                <igDp:Field Label="Status" Name="Status"/>
            </igDp:FieldLayout.Fields>
        </igDp:FieldLayout>
    </igDp:XamDataGrid.FieldLayouts>
</igDp:XamDataGrid>
</code>```

I've also tried the following style

```<code><Style TargetType="{x:Type igDp:DataRecordPresenter}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding Path=DataItem.Margin, RelativeSource={RelativeSource Self}}" Value="True">
            <Setter Property="Margin" Value="0,10,0,10"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
</code>```

The DataItem class contains a Thickness property

```<code>public Thickness Margin => (row % 2 == 0) ? new Thickness(0, 0, 0, 0) : new Thickness(0, 20, 0, 0);
</code>```

Seems like it's a binding error

```<code>System.Windows.Data Error: 40 : BindingExpression path error: 'Margin' property not found on 'object' ''DataRecord' (HashCode=17208979)'. BindingExpression:Path=Margin; DataItem='DataRecord' (HashCode=17208979); target element is 'DataRecordPresenter' (Name=''); target property is 'NoTarget' (type 'Object')
</code>```

Not sure what went wrong originally but the first code snippet is working as expected.

Body:
I'm not that great with WPF/XAML hence the question. Here's my code so far

<igDp:XamDataGrid DataSource="{Binding Items}" >
    <igDp:XamDataGrid.Resources>
        <ResourceDictionary>

        </ResourceDictionary>
    </igDp:XamDataGrid.Resources>

    <igDp:XamDataGrid.FieldLayouts>
        <igDp:FieldLayout>
            <igDp:FieldLayout.Fields>
                <igDp:Field Label="Status" Name="Status"/>
            </igDp:FieldLayout.Fields>
        </igDp:FieldLayout>
    </igDp:XamDataGrid.FieldLayouts>
</igDp:XamDataGrid>

I've also tried the following style

</Style>

The DataItem class contains a Thickness property

public Thickness Margin => (row % 2 == 0) ? new Thickness(0, 0, 0, 0) : new Thickness(0, 20, 0, 0);

Seems like it's a binding error

System.Windows.Data Error: 40 : BindingExpression path error: 'Margin' property not found on 'object' ''DataRecord' (HashCode=17208979)'. BindingExpression:Path=Margin; DataItem='DataRecord' (HashCode=17208979); target element is 'DataRecordPresenter' (Name=''); target property is 'NoTarget' (type 'Object')

Not sure what went wrong originally but the first code snippet is working as expected.


问:
Serilog Eventid is logged as Json
logger:

```<code>    ILogger logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration, "Logging")
                    .Enrich.FromLogContext()
                    .CreateLogger();
</code>```

settings:

```<code>  "Logging": {
    "Using": [ "Serilog.Exceptions", "Serilog", "Serilog.Sinks.File"],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "System": "Information",
        "Microsoft": "Information",
        "Microsoft.EntityFrameworkCore": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "./logs/events.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7,
          "buffered": true,
          "outputTemplate": "{Timestamp:u};{host_ip};{enviroment_hostname};{EventId};{EventCategory};{EventSeverity};{Message:lj};{UserId};{ResourceType};{ResourceId}",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ],
    "Enrich": [ "WithExceptionDetails", "WithProcId", "WithFacility", "ProcessHostEnricher", "WithSeverity" ]
  }
</code>```

In the file I get the following output:

```<code>2023-01-13 15:43:25Z;;;{ Id: 101 };UserRolesUnAssigned;UserManagement;Medium;User:system roles un-assigned:role1,role2,role3;system;;
</code>```

{EventId} comes out as a json object.
I would need just the Id. so 101 instead of { Id: 101 }

EDIT:
LoggerMessageDefinition:

```<code>private static Action<ILogger, string, string, Exception?> UserRolesUnAssigned =>
    LoggerMessage.Define<string, string>(LogLevel.Information, 101, UserMessageCodes[101].Template);
public static void LogUserRolesUnAssigned(this ILogger logger, string userId, string roleNames)
{
    EventDefinition eventDefinition = UserMessageCodes[101];
    using (LogContext.PushProperty(EventConstants.EventName, eventDefinition.Name))
    using (LogContext.PushProperty(EventConstants.EventCategory, eventDefinition.Category))
    using (LogContext.PushProperty(EventConstants.EventSeverity, eventDefinition.Severity))
        UserRolesUnAssigned(logger,userId, roleNames, null);
}
</code>```

Is there a way to do this out of the box or do I need to create a custom enricher for this?

Title: Serilog Eventid is logged as Json

Body:
logger:

    ILogger logger = new LoggerConfiguration()
                    .ReadFrom.Configuration(configuration, "Logging")
                    .Enrich.FromLogContext()
                    .CreateLogger();

settings:

  "Logging": {
    "Using": [ "Serilog.Exceptions", "Serilog", "Serilog.Sinks.File"],
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "System": "Information",
        "Microsoft": "Information",
        "Microsoft.EntityFrameworkCore": "Information"
      }
    },
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "./logs/events.log",
          "rollingInterval": "Day",
          "retainedFileCountLimit": 7,
          "buffered": true,
          "outputTemplate": "{Timestamp:u};{host_ip};{enviroment_hostname};{EventId};{EventCategory};{EventSeverity};{Message:lj};{UserId};{ResourceType};{ResourceId}",
          "restrictedToMinimumLevel": "Information"
        }
      }
    ],
    "Enrich": [ "WithExceptionDetails", "WithProcId", "WithFacility", "ProcessHostEnricher", "WithSeverity" ]
  }

In the file I get the following output:

2023-01-13 15:43:25Z;;;{ Id: 101 };UserRolesUnAssigned;UserManagement;Medium;User:system roles un-assigned:role1,role2,role3;system;;

{EventId} comes out as a json object.
I would need just the Id. so 101 instead of { Id: 101 }

EDIT:
LoggerMessageDefinition:

private static Action<ILogger, string, string, Exception?> UserRolesUnAssigned =>
    LoggerMessage.Define<string, string>(LogLevel.Information, 101, UserMessageCodes[101].Template);
public static void LogUserRolesUnAssigned(this ILogger logger, string userId, string roleNames)
{
    EventDefinition eventDefinition = UserMessageCodes[101];
    using (LogContext.PushProperty(EventConstants.EventName, eventDefinition.Name))
    using (LogContext.PushProperty(EventConstants.EventCategory, eventDefinition.Category))
    using (LogContext.PushProperty(EventConstants.EventSeverity, eventDefinition.Severity))
        UserRolesUnAssigned(logger,userId, roleNames, null);
}

Is there a way to do this out of the box or do I need to create a custom enricher for this?


问:
How to keep VScode terminal tab in editor from closing once exit
I usually put my terminal as tab on top of my editor, just because I like how that look more. But I hate to reopen and put them back up when exiting VScode. Is there a setting to keep them there like open file.

It would also be great if the terminal keep the icon and color


问:
Override Third Party Type Definitions in TypeScript
My doubt is how to override a type definition provided by a third party package (in my case @mui) using only d.ts file

USE CASE:

I want to indicate for all Button Components that the id prop is required, so any dev that use any Button will know that needs to provide an Id

I have tried a file *d.ts with something like this:

```<code>declare module '@mui/material/ButtonBase' {
 interface ExtendButtonBaseTypeMap<M extends OverridableTypeMap> {
     props: { id: string }
     defaultComponent: M['defaultComponent']
 }
}
</code>```

but did not work :(

For chakra-ui I know that this works:

```<code>declare module React {
 interface ButtonHTMLAttributes {
     id: string
 }
}
</code>```

Body:
My doubt is how to override a type definition provided by a third party package (in my case @mui) using only d.ts file

USE CASE:

I want to indicate for all Button Components that the id prop is required, so any dev that use any Button will know that needs to provide an Id

I have tried a file *d.ts with something like this:

declare module '@mui/material/ButtonBase' {
 interface ExtendButtonBaseTypeMap<M extends OverridableTypeMap> {
     props: { id: string }
     defaultComponent: M['defaultComponent']
 }
}

but did not work :(

For chakra-ui I know that this works:

declare module React {
 interface ButtonHTMLAttributes {
     id: string
 }
}


问:
How to store a file in Laravel from its content
I have the contents of an SVG file in a variable in my code, and I would like to store it using the documented Automatic Streaming method of Laravel (basically using putFile or putFileAs methods) in a remote AWS S3 bucket.

SVG content (QR code) is dynamically generated by a package, so I do not have it previously stored in the filesystem (do not have a path):

```<code>$svg_contents = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...';
</code>```

The problem is Laravel's putFile and putFileAs methods only accept Illuminate\Http\File or Illuminate\Http\UploadedFile instances as arguments. From Laravel docs:

```<code>// Automatically generate a unique ID for filename...
$path = Storage::putFile('photos', new File('/path/to/photo'));

// Manually specify a filename...
$path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');
</code>```

Any thoughts?
In other words, I am asking for a smart way to avoid storing it temporarily in local filesystem and then remotely store it in S3.

Thanks in advance.

Body:
I have the contents of an SVG file in a variable in my code, and I would like to store it using the documented Automatic Streaming method of Laravel (basically using putFile or putFileAs methods) in a remote AWS S3 bucket.

SVG content (QR code) is dynamically generated by a package, so I do not have it previously stored in the filesystem (do not have a path):

$svg_contents = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ...';

The problem is Laravel's putFile and putFileAs methods only accept Illuminate\Http\File or Illuminate\Http\UploadedFile instances as arguments. From Laravel docs:

// Automatically generate a unique ID for filename...
$path = Storage::putFile('photos', new File('/path/to/photo'));

// Manually specify a filename...
$path = Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

Any thoughts?
In other words, I am asking for a smart way to avoid storing it temporarily in local filesystem and then remotely store it in S3.

Thanks in advance.


问:
Maven can't get plugin from axon repo
I am currently having problems with a Maven project. I would like to use the doc-factory from axon ivy. And I get the following error:

```<code>[ERROR] Failed to execute goal
com.axonivy.ivy.ci:project-build-plugin:10.0.1:installEngine
(default-installEngine) on project doc-factory: Failed to find engine download link in list page
https://developer.axonivy.com/download/maven.html: Unknown host developer.axonivy.com
</code>```

When I open the URL https://developer.axonivy.com/download/maven.html in the browser or send a get request with Postman, the page opens or is returned in Postman. If I want to build my project with mvn via mvn clean install, this does not work and the above error appears.

I have already configured the proxy in the maven settings. Other repositories such as the maven repository can be accessed without any problems.

Any hints for me what I can do to fix this issue?

Thanks in advance

UPDATE:
Proxy Settings

```<code><proxies>
     <!-- proxy
      | Specification for one proxy, to be used in connecting to the network.
      |
     <proxy>
       <id>optional</id>
       <active>true</active>
       <protocol>http</protocol>
       <username>proxyuser</</username>
       <password>proxypass</password>
       <host>squid.URL</host>
       <port>8080</port>
       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
     </proxy>
     -->
        <proxy>
       <id>2</id>
       <active>true</active>
       <protocol>https</protocol>
       <host>squid.URL</host>
       <port>8080</port>
       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
     </proxy>
    <proxy>
       <id>1</id>
       <active>true</active>
       <protocol>http</protocol>
       <host>squid.URL</host>
       <port>8080</port>
       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
     </proxy>

</proxies>
</code>```

Title: Maven can't get plugin from axon repo

Body:
I am currently having problems with a Maven project. I would like to use the doc-factory from axon ivy. And I get the following error:

[ERROR] Failed to execute goal
com.axonivy.ivy.ci:project-build-plugin:10.0.1:installEngine
(default-installEngine) on project doc-factory: Failed to find engine download link in list page
https://developer.axonivy.com/download/maven.html: Unknown host developer.axonivy.com

When I open the URL https://developer.axonivy.com/download/maven.html in the browser or send a get request with Postman, the page opens or is returned in Postman. If I want to build my project with mvn via mvn clean install, this does not work and the above error appears.

I have already configured the proxy in the maven settings. Other repositories such as the maven repository can be accessed without any problems.

Any hints for me what I can do to fix this issue?

Thanks in advance

UPDATE:
Proxy Settings

<proxies>

        <proxy>
       <id>2</id>
       <active>true</active>
       <protocol>https</protocol>
       <host>squid.URL</host>
       <port>8080</port>
       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
     </proxy>
    <proxy>
       <id>1</id>
       <active>true</active>
       <protocol>http</protocol>
       <host>squid.URL</host>
       <port>8080</port>
       <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
     </proxy>

</proxies>


问:
Where does business logic go in Django API
I am very new to Django. I am able to set up a basic endpoint thanks to all the tutorials but what many of them miss is Where does one put the business logic of the app? Does it just go in a random file? Do I need to connect it somehow?

File structure that I have now

I think that I should create a file in apps, then add file with any name inside that folder


问:
How do I keep a copy of the DOM in Sorry Cypress?
When a Cypress test fails in CI pipeline, the screenshot is not enough to determine the cause.

How do I upload a copy of the DOM to the server so I can examine the node structure post-mortem when a test fails?