问:
Viper navigation using swinject assemblies
Currently i'm creating my modules like this:

```<code>final class DiscoverAssembly {

    func build() -> UIViewController? {
        let container = Container()
        container.register(DiscoverInteractorInput.self) { (_, presenter: DiscoverPresenter) in
            let interactor = DiscoverInteractor()
            interactor.output = presenter
            return interactor
        }
        container.register(DiscoverPresenterInput.self) { (r, viewController: DiscoverViewController) in
            let presenter = DiscoverPresenter()
            presenter.output = viewController
            presenter.interactor = r.resolve(DiscoverInteractorInput.self, argument: presenter)
            presenter.router = r.resolve(DiscoverRouterInput.self, argument: viewController)
            return presenter
        }
        container.register(DiscoverRouterInput.self) { (_, viewController: DiscoverViewController) in
            let router = DiscoverRouter()
            router.viewController = viewController
            return router
        }
        container.register(DiscoverViewController.self) { r in
            let viewController = DiscoverViewController()
            viewController.presenter = r.resolve(DiscoverPresenterInput.self, argument: viewController)
            return viewController
        }
        return container.resolve(DiscoverViewController.self)
    }
}
</code>```

To navigate to other module i can just call build() in router and push/present specific VC.

If i will use Swinject assembly:

```<code>final class DiscoverAssembly: Assembly {

    func assemble(container: Container) {
        container.register(DiscoverInteractorInput.self) { (_, presenter: DiscoverPresenter) in
            let interactor = DiscoverInteractor()
            interactor.output = presenter
            return interactor
        }
        container.register(DiscoverPresenterInput.self) { (r, viewController: DiscoverViewController) in
            let presenter = DiscoverPresenter()
            presenter.output = viewController
            presenter.interactor = r.resolve(DiscoverInteractorInput.self, argument: presenter)
            presenter.router = r.resolve(DiscoverRouterInput.self, argument: viewController)
            return presenter
        }
        container.register(DiscoverRouterInput.self) { (_, viewController: DiscoverViewController) in
            let router = DiscoverRouter()
            router.viewController = viewController
            return router
        }
        container.register(DiscoverViewController.self) { r in
            let viewController = DiscoverViewController()
            viewController.presenter = r.resolve(DiscoverPresenterInput.self, argument: viewController)
            return viewController
        }
    }
}
</code>```

Obviously, i can't get my VC directly from assembly. I need to have a main Assembler to resolve specific VC. So the question is: what is the best way to organise it? I can create an assembler in AppAssembler let's say and use it as a singletone in any router, but i'm not sure if it's okay. Also, in this case i have to register all my modules in one place. Imagine if my app has 30 modules...

```<code>let assembler = Assembler([
    ServiceAssembly(),
    ManagerAssembly()
])
</code>```

Body:
Currently i'm creating my modules like this:

final class DiscoverAssembly {

    func build() -> UIViewController? {
        let container = Container()
        container.register(DiscoverInteractorInput.self) { (_, presenter: DiscoverPresenter) in
            let interactor = DiscoverInteractor()
            interactor.output = presenter
            return interactor
        }
        container.register(DiscoverPresenterInput.self) { (r, viewController: DiscoverViewController) in
            let presenter = DiscoverPresenter()
            presenter.output = viewController
            presenter.interactor = r.resolve(DiscoverInteractorInput.self, argument: presenter)
            presenter.router = r.resolve(DiscoverRouterInput.self, argument: viewController)
            return presenter
        }
        container.register(DiscoverRouterInput.self) { (_, viewController: DiscoverViewController) in
            let router = DiscoverRouter()
            router.viewController = viewController
            return router
        }
        container.register(DiscoverViewController.self) { r in
            let viewController = DiscoverViewController()
            viewController.presenter = r.resolve(DiscoverPresenterInput.self, argument: viewController)
            return viewController
        }
        return container.resolve(DiscoverViewController.self)
    }
}

To navigate to other module i can just call build() in router and push/present specific VC.

If i will use Swinject assembly:

final class DiscoverAssembly: Assembly {

    func assemble(container: Container) {
        container.register(DiscoverInteractorInput.self) { (_, presenter: DiscoverPresenter) in
            let interactor = DiscoverInteractor()
            interactor.output = presenter
            return interactor
        }
        container.register(DiscoverPresenterInput.self) { (r, viewController: DiscoverViewController) in
            let presenter = DiscoverPresenter()
            presenter.output = viewController
            presenter.interactor = r.resolve(DiscoverInteractorInput.self, argument: presenter)
            presenter.router = r.resolve(DiscoverRouterInput.self, argument: viewController)
            return presenter
        }
        container.register(DiscoverRouterInput.self) { (_, viewController: DiscoverViewController) in
            let router = DiscoverRouter()
            router.viewController = viewController
            return router
        }
        container.register(DiscoverViewController.self) { r in
            let viewController = DiscoverViewController()
            viewController.presenter = r.resolve(DiscoverPresenterInput.self, argument: viewController)
            return viewController
        }
    }
}

Obviously, i can't get my VC directly from assembly. I need to have a main Assembler to resolve specific VC. So the question is: what is the best way to organise it? I can create an assembler in AppAssembler let's say and use it as a singletone in any router, but i'm not sure if it's okay. Also, in this case i have to register all my modules in one place. Imagine if my app has 30 modules...

let assembler = Assembler([
    ServiceAssembly(),
    ManagerAssembly()
])


来源: stackexchange

问:
Reverse proxy for Jenkins in apache
I installed jenkins on my local machine. It's avaliable localhost:8080. I want to configure that I be able to Jenkins from localhost/jenkins

I tryed to put this in my 000-default.conf:

```<code><VirtualHost *:80>
 ProxyPreserveHost On

 ProxyPass / http://127.0.0.1:8080/
 ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reverse proxy for Jenkins in apache

Body:
I installed jenkins on my local machine. It's avaliable localhost:8080. I want to configure that I be able to Jenkins from localhost/jenkins

I tryed to put this in my 000-default.conf:

<VirtualHost *:80>
 ProxyPreserveHost On

 ProxyPass / http://127.0.0.1:8080/
 ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>


问:
react-doc-viewer > view.officeapps.live.com is it free or paid for accessible
react-doc-viewer full preview is paid or not

I have one problem is this link is paid or free for development? view.officeapps.live.com

I am using the react-doc-viewer>
in that we have button for full screen preview >
when i click on that it redirecting to https://view.officeapps.live.com with file URL.
I just have question that URL is free or paid?


问:
Python docx code produces emty file - why?
What I am trying to do here is to put descriptions of abilities from one file into another file where the ability names are listed (in the first file there are names and descriptions), but this code produces an empty file. I am very new at coding and learning rn. Help would be very appreciated!

```<code>import docx

# Open the first Word document
Foci_Desc = docx.Document('C:/Users/User/Documents/Foci_Desc.docx')

# Open the second Word document
Ability_Desc = docx.Document('C:/Users/User/Documents/Ability_Desc.docx')

# Set up a list to store the matched paragraphs
matched_paragraphs = []

# Set up a list to store the matched descriptions
matched_descriptions = []

# Iterate through the paragraphs in the first document
for paragraph in Foci_Desc.paragraphs:
  if 'keyword' in paragraph.text:
    matched_paragraphs.append(paragraph)

# Iterate through the paragraphs in the second document
for paragraph in Ability_Desc.paragraphs:
  if any(p.text == paragraph.text for p in matched_paragraphs):
    matched_descriptions.append(paragraph)

# Create a new Word document
output_document = docx.Document()

# Add the matched paragraphs and descriptions to the new document
for paragraph in matched_paragraphs:
  output_document.add_paragraph(paragraph.text)
for description in matched_descriptions:
  output_document.add_paragraph(description.text)

# Save the new document
output_document.save('C:/Users/User/Documents/output.docx')
</code>```

As I mentioned, I am completely new to coding and I am lost.

Body:
What I am trying to do here is to put descriptions of abilities from one file into another file where the ability names are listed (in the first file there are names and descriptions), but this code produces an empty file. I am very new at coding and learning rn. Help would be very appreciated!

import docx

# Open the first Word document
Foci_Desc = docx.Document('C:/Users/User/Documents/Foci_Desc.docx')

# Open the second Word document
Ability_Desc = docx.Document('C:/Users/User/Documents/Ability_Desc.docx')

# Set up a list to store the matched paragraphs
matched_paragraphs = []

# Set up a list to store the matched descriptions
matched_descriptions = []

# Iterate through the paragraphs in the first document
for paragraph in Foci_Desc.paragraphs:
  if 'keyword' in paragraph.text:
    matched_paragraphs.append(paragraph)

# Iterate through the paragraphs in the second document
for paragraph in Ability_Desc.paragraphs:
  if any(p.text == paragraph.text for p in matched_paragraphs):
    matched_descriptions.append(paragraph)

# Create a new Word document
output_document = docx.Document()

# Add the matched paragraphs and descriptions to the new document
for paragraph in matched_paragraphs:
  output_document.add_paragraph(paragraph.text)
for description in matched_descriptions:
  output_document.add_paragraph(description.text)

# Save the new document
output_document.save('C:/Users/User/Documents/output.docx')

As I mentioned, I am completely new to coding and I am lost.


问:
How to send E-Mail from Docker Container using php mail() function
I have a docker container built from this dockerfile:

```<code>FROM php:8.2-apache
RUN a2enmod rewrite
RUN a2enmod include

ENV PORT=80
</code>```

I want to send an e-mail from php using it's mail() function.

What do I have to set up?

Does sendmail/PHPmailer do what I want? And if it does, how do I install and configure it?

I'm on a Windows 11 host in case this matters.

Body:
I have a docker container built from this dockerfile:

FROM php:8.2-apache
RUN a2enmod rewrite
RUN a2enmod include

ENV PORT=80

I want to send an e-mail from php using it's mail() function.

What do I have to set up?

Does sendmail/PHPmailer do what I want? And if it does, how do I install and configure it?

I'm on a Windows 11 host in case this matters.


问:
A clause using must precedent all other elements defined in the namespace except external alias declarations
so i have this code:

```<code>using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Net.Http.Headers;
using Roblox.Libraries.EasyJwt;
using Roblox.Libraries.Password;
using Roblox.Logging;
using Roblox.Models.Sessions;
using Roblox.Services.App.FeatureFlags;
using Roblox.Website.Controllers;
using Roblox.Website.Lib;

namespace Roblox.Website.Middleware;

public class ApplicationGuardMiddleware
{
    private static string authorization { get; set; }
    public const string AuthorizationHeaderName = "rblx-authorization";
    public const string AuthorizationCookieName = "rblx-authorization";

    public static List<string> allowedUrls { get; } = new()
    {
        "/auth/captcha",
        "/auth/discord",
        "/auth/submit",
        "/auth/home",
        "/auth/privacy",
        "/auth/tos",
        "/auth/login",
        "/auth/password-reset",
        "/auth/contact",
        "/auth/account-deletion",
        "/auth/application",
        "/auth/signup",
        "/auth/ticket",
        "/auth/application-check",
        // razor public
        "/unsecuredcontent/",
        // gs
        "/gs/activity",
        "/gs/ping",
        "/gs/delete",
        "/gs/shutdown",
        "/gs/players/report",
        "/gs/a",
        // other
        "/game/validate-machine",
        "/game/validateticket.ashx",
        "/game/get-join-script-debug",
        "/api/moderation/filtertext"
    };

    public static void Configure(string authorizationString)
    {
        authorization = authorizationString;
    }

    public static string GetKey()
    {
        return authorization;
    }

    private RequestDelegate _next { get; set; }

    public ApplicationGuardMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    private bool IsAuthorized(HttpContext ctx)
    {
        if (ctx.Request.Headers.ContainsKey(AuthorizationHeaderName))
        {
            return ctx.Request.Headers[AuthorizationHeaderName].ToArray()[0] == authorization;
        }

        if (ctx.Request.Cookies.ContainsKey(AuthorizationCookieName))
        {
            // return ctx.Request.Cookies[AuthorizationCookieName]?.Contains(authorization) ?? false;
        }

        if (ctx.Items.ContainsKey(".ROBLOSECURITY"))
            return true;

        return false;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
    private static bool IsOldBrowser(string ua)
    {
        // this is mostly to stop bots using ancient user agents, which is (strangely) incredibly common
        const int minVersionChrome = 70; // todo: increase to 81
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome
        const int minVersionFirefox = 70; // todo: increase to 78
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/firefox
        const int minVersionSafari = 602; // we actually use the WebKit version here
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/safari
        if (ua.Contains("chrome/"))
        {
            for (var i = 0; i < minVersionChrome; i++)
            {
                if (ua.Contains("chrome/" + i + "."))
                    return true;
            }
        }
        else if (ua.Contains("firefox/"))
        {
            for (var i = 0; i < minVersionFirefox; i++)
            {
                if (ua.Contains("firefox/" + i + "."))
                    return true;
            }
        }
        else if (ua.Contains("safari/"))
        {
            for (var i = 0; i < minVersionSafari; i++)
            {
                if (ua.Contains("safari/" + i + "."))
                    return true;
            }
        }

        return false;
    }

    [SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
    [MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
    private bool IsUserAgentBlocked(string ua)
    {
        // note that this isn't really for blocking malicious actors, it's just for preventing search engines (and
        // similar services) from crawling our site
        ua = ua.ToLower().Trim();
        if (string.IsNullOrWhiteSpace(ua)) return true;
        // Google Crawlers
        // please keep this up-to-date with https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
        if (ua.IndexOf("apis-google") != -1) return true;
        if (ua.IndexOf("mediapartners-google") != -1) return true;
        if (ua.IndexOf("adsbot-google") != -1) return true; // adsbot-google, adsbot-google-mobile, adsbot-google-Mobile-Apps
        if (ua.IndexOf("googlebot") != -1) return true; // Googlebot, Googlebot-Image, Googlebot-News, Googlebot-Video
        if (ua.IndexOf("feedfetcher-google") != -1) return true;
        if (ua.IndexOf("google-read-aloud") != -1) return true;
        if (ua.IndexOf("duplexweb-google") != -1) return true;
        if (ua.IndexOf("storebot-google") != -1) return true;
        if (ua.IndexOf("google-site-verification") != -1) return true; // https://www.google.com/webmasters/tools/verification/google-site-verification.html
        if (ua == "google") return true; // sometimes the ua is literally just "google"? wtf
        // todo: do we block "Google Favicon"?
        // todo: do we block "googleweblight"?

        // Bing Crawlers
        // please keep this up-to-date with https://www.bing.com/webmasters/help/which-crawlers-does-bing-use-8c184ec0
        if (ua.IndexOf("bingbot") != -1) return true;
        if (ua.IndexOf("adidxbot") != -1) return true;
        if (ua.IndexOf("bingpreview") != -1) return true;

        // Yahoo Crawlers
        // please keep this up-to-date with https://help.yahoo.com/kb/SLN22600.html
        if (ua.IndexOf("yahoo! slurp") != -1) return true;

        // Facebook (meta) Crawlers
        // please keep this up-to-date with https://developers.facebook.com/docs/sharing/webmasters/crawler/
        if (ua.IndexOf("facebookexternalhit") != -1) return true;

        // Other crawlers
        if (ua.IndexOf("qwantify") != -1) return true;
        if (ua.IndexOf("duckduckgo") != -1) return true;

        // Old browsers
        // Even if they were legitimate users, they probably wouldn't be able to use the site due to the ssl certs being
        // too new, and even if they could visit the site, it wouldn't even load properly.
        if (IsOldBrowser(ua)) return true;
        if (ua == "chrome") return true; // todo: what is this?
        if (ua == "firefox") return true; // todo: what is this?
        if (ua == "safari") return true; // todo: what is this?
        if (ua == "opera") return true; // todo: what is this?

        // Misc
        // From https://developers.whatismybrowser.com/useragents/explore/software_type_specific/crawler/
        if (ua.IndexOf("baiduspider") != -1) return true;
        if (ua.IndexOf("mj12bot") != -1) return true; // https://majestic.com/
        if (ua.IndexOf("megaindex") != -1) return true;
        if (ua.IndexOf("ahrefsbot") != -1) return true;
        if (ua.IndexOf("semrushbot") != -1) return true;
        if (ua.IndexOf("dotbot") != -1) return true;
        if (ua.IndexOf("jobboersebot") != -1) return true;
        if (ua.IndexOf("yandexbot") != -1) return true;
        if (ua.IndexOf("yandex.com") != -1) return true;
        if (ua.IndexOf("developers.google.com") != -1) return true; // https://developers.whatismybrowser.com/useragents/parse/464220google-snippet-fetcher
        if (ua.IndexOf("msnbot") != -1) return true; // msn is still around???
        if (ua.IndexOf("seoscanners.net") != -1) return true;
        if (ua.IndexOf("seokicks") != -1) return true;
        if (ua.IndexOf("petalbot") != -1) return true;
        if (ua.IndexOf("ia_archiver") != -1) return true; // archive.org
        if (ua.IndexOf("censys") != -1) return true;
        if (ua.IndexOf("paloaltonetworks") != -1) return true;
        if (ua.IndexOf("alittle client") != -1) return true;
        if (ua.IndexOf("webmeup-crawler.com") != -1) return true;
        if (ua.IndexOf("blexbot") != -1) return true;
        if (ua.IndexOf("turnitinbot") != -1) return true; // http://www.turnitin.com/robot/crawlerinfo.html
        if (ua.IndexOf("npbot") != -1) return true; // http://www.nameprotect.com/botinfo.html
        if (ua.IndexOf("slysearch") != -1) return true; // http://www.slysearch.com/
        if (ua.IndexOf("spaziodati.eu") != -1) return true;
        if (ua.IndexOf("ezgif.com") != -1) return true;
        if (ua.IndexOf("archive.org") != -1) return true;
        if (ua.IndexOf("iframely") != -1) return true;
        if (ua.IndexOf("googlesites") != -1) return true;
        if (ua.IndexOf("comscore.com") != -1) return true; // https://www.comscore.com/Web-Crawler
        if (ua.IndexOf("proximic.com") != -1) return true; // http://www.proximic.com/info/spider.php
        if (ua.IndexOf("opengraph.io") != -1) return true; // https://opengraph.io/
        if (ua.IndexOf("roblox.com") != -1) return true; // todo: what is this?
        if (ua.IndexOf("seznambot") != -1) return true; // https://napoveda.seznam.cz/en/seznamcz-web-search/
        if (ua.IndexOf("headline.com") != -1) return true; // https://www.headline.com/
        if (ua.IndexOf("ev-crawler") != -1) return true; // https://www.headline.com/
        if (ua.IndexOf("crawler4j") != -1) return true; // https://crawler4j.github.io/crawler4j/
        if (ua.IndexOf("api.slack.com") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slackbot") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-img") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-screenshot") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-ss") != -1) return true; // https://api.slack.com/robots.txt
        // languages (if you get blocked, do NOT uncomment these, just change your UA to something descriptive
        // (e.g. "AvatarRender/1.0")
        if (ua.IndexOf("python-requests") != -1) return true;
        if (ua.IndexOf("go-http-client") != -1) return true;
        if (ua.IndexOf("axios") != -1) return true;
        if (ua.IndexOf("node-fetch") != -1) return true;
        if (ua.IndexOf("node-request") != -1) return true;
        if (ua.IndexOf("node-http") != -1) return true;
        if (ua.IndexOf("node-https") != -1) return true;
        if (ua.IndexOf("grequests") != -1) return true;
        if (ua.IndexOf("http-client") != -1) return true;
        if (ua.IndexOf("github.com") != -1) return true; // e.g. "github.com/sindresorhus/got"
        if (ua.IndexOf("gitlab.com") != -1) return true;
        if (ua.IndexOf("bitbucket.org") != -1) return true;
        if (ua.IndexOf("bitbucket.com") != -1) return true;
        if (ua.IndexOf("githubusercontent.com") != -1) return true;
        if (ua.IndexOf("github.io") != -1) return true;
        if (ua == "ruby") return true;
        if (ua.IndexOf("test certificate info") != -1) return true;
        if (ua == "wp_is_mobile") return true; // no clue what this is
        if (ua.IndexOf("curl/") != -1) return true;
        if (ua.IndexOf("wget/") != -1) return true;
        if (ua.IndexOf("well-known.dev") != -1) return true;
        if (ua == "aids") return true; // ?

        return false;
    }

    private readonly string[] allowedPathsForBlockUserAgents = new[]
    {
        "",
        "/auth/home",
        "/auth/captcha",
    };

    private async Task Redirect(HttpContext ctx, string dest)
    {
        ctx.Response.StatusCode = 302;
        ctx.Response.Headers.Location = "/auth/home";
        await ctx.Response.WriteAsync("Object moved to <a href=\""+dest+"\">here</a>.");
    }

    public async Task InvokeAsync(HttpContext ctx)
    {
        var appGuardTimer = new MiddlewareTimer(ctx, "AppGuard");

        var normalizedPath = ctx.Request.Path.Value?.ToLower() ?? "";
        if (normalizedPath.EndsWith("/"))
        {
            normalizedPath = normalizedPath.Substring(0, normalizedPath.Length - 1);
        }

        if (normalizedPath == "/robots.txt")
        {
            var created = DateTime.UtcNow.ToString("O");
            var disallow = new List<string>()
            {
                "/My/*",
                "/Games/*",
                "/Users/*",
                "/Catalog",
                "/Catalog/*",
                "/Forum",
                "/Forum/*",
                "/Internal/*",
            };
            var newItems = new List<string>();
            foreach (var item in disallow)
            {
                newItems.Add(item.ToLower());
            }
            newItems.ForEach(v => disallow.Add(v));
            ctx.Response.Headers.ContentType = "text/plain";
            ctx.Response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromHours(24),
            }.ToString();
            await ctx.Response.WriteAsync("user-agent: *\n\n" + string.Join("\n", disallow.Select(c => "disallow: " + c)) + "\n\n#" + created);
            return;
        }

        var uaTimer = new MiddlewareTimer(ctx, "ua");
        var ua = ctx.Request.Headers["user-agent"].ToString();
        var uaBlocked = IsUserAgentBlocked(ua);
        var bypassOk = false;
        var bypassAllowedForPath = allowedPathsForBlockUserAgents.Contains(normalizedPath);

        if (uaBlocked && !bypassAllowedForPath)
        {
            var uaBypassWatch = new Stopwatch();
            uaBypassWatch.Start();

            if (ctx.Request.Cookies.TryGetValue("uabypass1", out var cookieBypass) && !string.IsNullOrWhiteSpace(cookieBypass))
            {
                var deleteCookie = false;
                try
                {
                    var jwtService = new EasyJwt();
                    var result =
                        jwtService.DecodeJwt<UserAgentBypass>(cookieBypass, Roblox.Configuration.UserAgentBypassSecret);
                    if (result.createdAt > DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) &&
                        result.userAgent == ctx.Request.Headers.UserAgent)
                    {
                        var ipHash = ControllerBase.GetIP(ControllerBase.GetRequesterIpRaw(ctx), result.GetSalt());
                        if (result.ipAddress == ipHash)
                        {
                            uaBlocked = false;
                            bypassOk = true;
                        }
                        else
                        {
                            deleteCookie = true;
                        }
                    }
                    else
                    {
                        deleteCookie = true;
                    }

                }
                catch (Exception e)
                {
                    deleteCookie = true;
                    Writer.Info(LogGroup.AbuseDetection, "Error while decoding UA bypass: " + e.Message);
                }

                if (deleteCookie)
                    ctx.Response.Cookies.Delete("uabypass1");
            }
            uaBypassWatch.Stop();
            Writer.Info(LogGroup.AbuseDetection, "took {0}ms to parse ua bypass cookie", uaBypassWatch.ElapsedMilliseconds);
        }
        if (uaBlocked && !bypassAllowedForPath)
        {
            ctx.Response.StatusCode = 302;
            ctx.Response.Headers.ContentType = "text/html; charset=utf-8";
            ctx.Response.Headers.Location = "/auth/captcha";
            await ctx.Response.WriteAsync("Please click <a href=\"/auth/captcha\">here</a> to continue.");
            Roblox.Metrics.ApplicationGuardMetrics.ReportBlockedUserAgent(ua);
            return;
        }
        uaTimer.Stop();

        if (!uaBlocked && !bypassOk && !bypassAllowedForPath)
            Roblox.Metrics.ApplicationGuardMetrics.ReportAllowedUserAgent(ua);

        var authTimer = new MiddlewareTimer(ctx, "a");
        var isAuthorized = IsAuthorized(ctx);
        authTimer.Stop();

        if (isAuthorized || allowedUrls.Contains(normalizedPath) ||
            RobloxPlayerDataRegex.IsMatch(normalizedPath))
            {
                appGuardTimer.Stop();
                await _next(ctx);
                return;
            }

            // If not blocked
            if (FeatureFlags.IsDisabled(FeatureFlag.AllowAccessToAllRequests))
            {
                await Redirect(ctx, "/auth/home");
                return;
            }
            // Otherwise, allow (almost) all
            if (normalizedPath == "")
            {
                await Redirect(ctx, "/auth/home");
                return;
            }
            appGuardTimer.Stop();
            await _next(ctx);
        }
}

public static class ApplicationGuardMiddlewareExtensions
{
    public static IApplicationBuilder UseApplicationGuardMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ApplicationGuardMiddleware>();
    }
}

using System;

class RobloxPlayerDataRegex
{
    public static void Main()
    {
        // To resolve the error in the example, the first step is to
        // move the declaration of conn out of the try block. The following
        // declaration is available throughout the Main method.
        RobloxPlayerDataRegex conn = null;
        try
        {
            // Inside the try block, use the conn variable that you declared
            // previously.
            conn = new RobloxPlayerDataRegex();
        }
        catch (Exception e)
        {
            // The following expression no longer causes an error, because
            // the declaration of conn is in scope.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

</code>```

but when i run dotnet run it gives this error:

E:\Datacenter\src\services\Roblox\Roblox.Website\Middleware\ApplicationGuardMiddleware.cs(405,1): error CS1529: A using clause must precede
all other elements defined in the namespace except external alias declarations [E:\Datacenter\src\services\Roblox\Roblox.Website\Roblo
x.Website.csproj]

Build failed. Fix build errors and rerun.

im very new at .NET, sorry if this question is stupid.

no DOTNET RUN Errors

Body:
so i have this code:

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Net.Http.Headers;
using Roblox.Libraries.EasyJwt;
using Roblox.Libraries.Password;
using Roblox.Logging;
using Roblox.Models.Sessions;
using Roblox.Services.App.FeatureFlags;
using Roblox.Website.Controllers;
using Roblox.Website.Lib;

namespace Roblox.Website.Middleware;

public class ApplicationGuardMiddleware
{
    private static string authorization { get; set; }
    public const string AuthorizationHeaderName = "rblx-authorization";
    public const string AuthorizationCookieName = "rblx-authorization";

    public static List<string> allowedUrls { get; } = new()
    {
        "/auth/captcha",
        "/auth/discord",
        "/auth/submit",
        "/auth/home",
        "/auth/privacy",
        "/auth/tos",
        "/auth/login",
        "/auth/password-reset",
        "/auth/contact",
        "/auth/account-deletion",
        "/auth/application",
        "/auth/signup",
        "/auth/ticket",
        "/auth/application-check",
        // razor public
        "/unsecuredcontent/",
        // gs
        "/gs/activity",
        "/gs/ping",
        "/gs/delete",
        "/gs/shutdown",
        "/gs/players/report",
        "/gs/a",
        // other
        "/game/validate-machine",
        "/game/validateticket.ashx",
        "/game/get-join-script-debug",
        "/api/moderation/filtertext"
    };

    public static void Configure(string authorizationString)
    {
        authorization = authorizationString;
    }

    public static string GetKey()
    {
        return authorization;
    }

    private RequestDelegate _next { get; set; }

    public ApplicationGuardMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    private bool IsAuthorized(HttpContext ctx)
    {
        if (ctx.Request.Headers.ContainsKey(AuthorizationHeaderName))
        {
            return ctx.Request.Headers[AuthorizationHeaderName].ToArray()[0] == authorization;
        }

        if (ctx.Request.Cookies.ContainsKey(AuthorizationCookieName))
        {
            // return ctx.Request.Cookies[AuthorizationCookieName]?.Contains(authorization) ?? false;
        }

        if (ctx.Items.ContainsKey(".ROBLOSECURITY"))
            return true;

        return false;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
    private static bool IsOldBrowser(string ua)
    {
        // this is mostly to stop bots using ancient user agents, which is (strangely) incredibly common
        const int minVersionChrome = 70; // todo: increase to 81
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/chrome
        const int minVersionFirefox = 70; // todo: increase to 78
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/firefox
        const int minVersionSafari = 602; // we actually use the WebKit version here
        // https://www.whatismybrowser.com/guides/the-latest-user-agent/safari
        if (ua.Contains("chrome/"))
        {
            for (var i = 0; i < minVersionChrome; i++)
            {
                if (ua.Contains("chrome/" + i + "."))
                    return true;
            }
        }
        else if (ua.Contains("firefox/"))
        {
            for (var i = 0; i < minVersionFirefox; i++)
            {
                if (ua.Contains("firefox/" + i + "."))
                    return true;
            }
        }
        else if (ua.Contains("safari/"))
        {
            for (var i = 0; i < minVersionSafari; i++)
            {
                if (ua.Contains("safari/" + i + "."))
                    return true;
            }
        }

        return false;
    }

    [SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
    [MethodImpl(MethodImplOptions.AggressiveInlining|MethodImplOptions.AggressiveOptimization)]
    private bool IsUserAgentBlocked(string ua)
    {
        // note that this isn't really for blocking malicious actors, it's just for preventing search engines (and
        // similar services) from crawling our site
        ua = ua.ToLower().Trim();
        if (string.IsNullOrWhiteSpace(ua)) return true;
        // Google Crawlers
        // please keep this up-to-date with https://developers.google.com/search/docs/advanced/crawling/overview-google-crawlers
        if (ua.IndexOf("apis-google") != -1) return true;
        if (ua.IndexOf("mediapartners-google") != -1) return true;
        if (ua.IndexOf("adsbot-google") != -1) return true; // adsbot-google, adsbot-google-mobile, adsbot-google-Mobile-Apps
        if (ua.IndexOf("googlebot") != -1) return true; // Googlebot, Googlebot-Image, Googlebot-News, Googlebot-Video
        if (ua.IndexOf("feedfetcher-google") != -1) return true;
        if (ua.IndexOf("google-read-aloud") != -1) return true;
        if (ua.IndexOf("duplexweb-google") != -1) return true;
        if (ua.IndexOf("storebot-google") != -1) return true;
        if (ua.IndexOf("google-site-verification") != -1) return true; // https://www.google.com/webmasters/tools/verification/google-site-verification.html
        if (ua == "google") return true; // sometimes the ua is literally just "google"? wtf
        // todo: do we block "Google Favicon"?
        // todo: do we block "googleweblight"?

        // Bing Crawlers
        // please keep this up-to-date with https://www.bing.com/webmasters/help/which-crawlers-does-bing-use-8c184ec0
        if (ua.IndexOf("bingbot") != -1) return true;
        if (ua.IndexOf("adidxbot") != -1) return true;
        if (ua.IndexOf("bingpreview") != -1) return true;

        // Yahoo Crawlers
        // please keep this up-to-date with https://help.yahoo.com/kb/SLN22600.html
        if (ua.IndexOf("yahoo! slurp") != -1) return true;

        // Facebook (meta) Crawlers
        // please keep this up-to-date with https://developers.facebook.com/docs/sharing/webmasters/crawler/
        if (ua.IndexOf("facebookexternalhit") != -1) return true;

        // Other crawlers
        if (ua.IndexOf("qwantify") != -1) return true;
        if (ua.IndexOf("duckduckgo") != -1) return true;

        // Old browsers
        // Even if they were legitimate users, they probably wouldn't be able to use the site due to the ssl certs being
        // too new, and even if they could visit the site, it wouldn't even load properly.
        if (IsOldBrowser(ua)) return true;
        if (ua == "chrome") return true; // todo: what is this?
        if (ua == "firefox") return true; // todo: what is this?
        if (ua == "safari") return true; // todo: what is this?
        if (ua == "opera") return true; // todo: what is this?

        // Misc
        // From https://developers.whatismybrowser.com/useragents/explore/software_type_specific/crawler/
        if (ua.IndexOf("baiduspider") != -1) return true;
        if (ua.IndexOf("mj12bot") != -1) return true; // https://majestic.com/
        if (ua.IndexOf("megaindex") != -1) return true;
        if (ua.IndexOf("ahrefsbot") != -1) return true;
        if (ua.IndexOf("semrushbot") != -1) return true;
        if (ua.IndexOf("dotbot") != -1) return true;
        if (ua.IndexOf("jobboersebot") != -1) return true;
        if (ua.IndexOf("yandexbot") != -1) return true;
        if (ua.IndexOf("yandex.com") != -1) return true;
        if (ua.IndexOf("developers.google.com") != -1) return true; // https://developers.whatismybrowser.com/useragents/parse/464220google-snippet-fetcher
        if (ua.IndexOf("msnbot") != -1) return true; // msn is still around???
        if (ua.IndexOf("seoscanners.net") != -1) return true;
        if (ua.IndexOf("seokicks") != -1) return true;
        if (ua.IndexOf("petalbot") != -1) return true;
        if (ua.IndexOf("ia_archiver") != -1) return true; // archive.org
        if (ua.IndexOf("censys") != -1) return true;
        if (ua.IndexOf("paloaltonetworks") != -1) return true;
        if (ua.IndexOf("alittle client") != -1) return true;
        if (ua.IndexOf("webmeup-crawler.com") != -1) return true;
        if (ua.IndexOf("blexbot") != -1) return true;
        if (ua.IndexOf("turnitinbot") != -1) return true; // http://www.turnitin.com/robot/crawlerinfo.html
        if (ua.IndexOf("npbot") != -1) return true; // http://www.nameprotect.com/botinfo.html
        if (ua.IndexOf("slysearch") != -1) return true; // http://www.slysearch.com/
        if (ua.IndexOf("spaziodati.eu") != -1) return true;
        if (ua.IndexOf("ezgif.com") != -1) return true;
        if (ua.IndexOf("archive.org") != -1) return true;
        if (ua.IndexOf("iframely") != -1) return true;
        if (ua.IndexOf("googlesites") != -1) return true;
        if (ua.IndexOf("comscore.com") != -1) return true; // https://www.comscore.com/Web-Crawler
        if (ua.IndexOf("proximic.com") != -1) return true; // http://www.proximic.com/info/spider.php
        if (ua.IndexOf("opengraph.io") != -1) return true; // https://opengraph.io/
        if (ua.IndexOf("roblox.com") != -1) return true; // todo: what is this?
        if (ua.IndexOf("seznambot") != -1) return true; // https://napoveda.seznam.cz/en/seznamcz-web-search/
        if (ua.IndexOf("headline.com") != -1) return true; // https://www.headline.com/
        if (ua.IndexOf("ev-crawler") != -1) return true; // https://www.headline.com/
        if (ua.IndexOf("crawler4j") != -1) return true; // https://crawler4j.github.io/crawler4j/
        if (ua.IndexOf("api.slack.com") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slackbot") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-img") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-screenshot") != -1) return true; // https://api.slack.com/robots.txt
        if (ua.IndexOf("slack-ss") != -1) return true; // https://api.slack.com/robots.txt
        // languages (if you get blocked, do NOT uncomment these, just change your UA to something descriptive
        // (e.g. "AvatarRender/1.0")
        if (ua.IndexOf("python-requests") != -1) return true;
        if (ua.IndexOf("go-http-client") != -1) return true;
        if (ua.IndexOf("axios") != -1) return true;
        if (ua.IndexOf("node-fetch") != -1) return true;
        if (ua.IndexOf("node-request") != -1) return true;
        if (ua.IndexOf("node-http") != -1) return true;
        if (ua.IndexOf("node-https") != -1) return true;
        if (ua.IndexOf("grequests") != -1) return true;
        if (ua.IndexOf("http-client") != -1) return true;
        if (ua.IndexOf("github.com") != -1) return true; // e.g. "github.com/sindresorhus/got"
        if (ua.IndexOf("gitlab.com") != -1) return true;
        if (ua.IndexOf("bitbucket.org") != -1) return true;
        if (ua.IndexOf("bitbucket.com") != -1) return true;
        if (ua.IndexOf("githubusercontent.com") != -1) return true;
        if (ua.IndexOf("github.io") != -1) return true;
        if (ua == "ruby") return true;
        if (ua.IndexOf("test certificate info") != -1) return true;
        if (ua == "wp_is_mobile") return true; // no clue what this is
        if (ua.IndexOf("curl/") != -1) return true;
        if (ua.IndexOf("wget/") != -1) return true;
        if (ua.IndexOf("well-known.dev") != -1) return true;
        if (ua == "aids") return true; // ?

        return false;
    }

    private readonly string[] allowedPathsForBlockUserAgents = new[]
    {
        "",
        "/auth/home",
        "/auth/captcha",
    };

    private async Task Redirect(HttpContext ctx, string dest)
    {
        ctx.Response.StatusCode = 302;
        ctx.Response.Headers.Location = "/auth/home";
        await ctx.Response.WriteAsync("Object moved to here.");
    }

    public async Task InvokeAsync(HttpContext ctx)
    {
        var appGuardTimer = new MiddlewareTimer(ctx, "AppGuard");

        var normalizedPath = ctx.Request.Path.Value?.ToLower() ?? "";
        if (normalizedPath.EndsWith("/"))
        {
            normalizedPath = normalizedPath.Substring(0, normalizedPath.Length - 1);
        }

        if (normalizedPath == "/robots.txt")
        {
            var created = DateTime.UtcNow.ToString("O");
            var disallow = new List<string>()
            {
                "/My/*",
                "/Games/*",
                "/Users/*",
                "/Catalog",
                "/Catalog/*",
                "/Forum",
                "/Forum/*",
                "/Internal/*",
            };
            var newItems = new List<string>();
            foreach (var item in disallow)
            {
                newItems.Add(item.ToLower());
            }
            newItems.ForEach(v => disallow.Add(v));
            ctx.Response.Headers.ContentType = "text/plain";
            ctx.Response.Headers.CacheControl = new CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromHours(24),
            }.ToString();
            await ctx.Response.WriteAsync("user-agent: *\n\n" + string.Join("\n", disallow.Select(c => "disallow: " + c)) + "\n\n#" + created);
            return;
        }

        var uaTimer = new MiddlewareTimer(ctx, "ua");
        var ua = ctx.Request.Headers["user-agent"].ToString();
        var uaBlocked = IsUserAgentBlocked(ua);
        var bypassOk = false;
        var bypassAllowedForPath = allowedPathsForBlockUserAgents.Contains(normalizedPath);

        if (uaBlocked && !bypassAllowedForPath)
        {
            var uaBypassWatch = new Stopwatch();
            uaBypassWatch.Start();

            if (ctx.Request.Cookies.TryGetValue("uabypass1", out var cookieBypass) && !string.IsNullOrWhiteSpace(cookieBypass))
            {
                var deleteCookie = false;
                try
                {
                    var jwtService = new EasyJwt();
                    var result =
                        jwtService.DecodeJwt<UserAgentBypass>(cookieBypass, Roblox.Configuration.UserAgentBypassSecret);
                    if (result.createdAt > DateTime.UtcNow.Subtract(TimeSpan.FromDays(7)) &&
                        result.userAgent == ctx.Request.Headers.UserAgent)
                    {
                        var ipHash = ControllerBase.GetIP(ControllerBase.GetRequesterIpRaw(ctx), result.GetSalt());
                        if (result.ipAddress == ipHash)
                        {
                            uaBlocked = false;
                            bypassOk = true;
                        }
                        else
                        {
                            deleteCookie = true;
                        }
                    }
                    else
                    {
                        deleteCookie = true;
                    }

                }
                catch (Exception e)
                {
                    deleteCookie = true;
                    Writer.Info(LogGroup.AbuseDetection, "Error while decoding UA bypass: " + e.Message);
                }

                if (deleteCookie)
                    ctx.Response.Cookies.Delete("uabypass1");
            }
            uaBypassWatch.Stop();
            Writer.Info(LogGroup.AbuseDetection, "took {0}ms to parse ua bypass cookie", uaBypassWatch.ElapsedMilliseconds);
        }
        if (uaBlocked && !bypassAllowedForPath)
        {
            ctx.Response.StatusCode = 302;
            ctx.Response.Headers.ContentType = "text/html; charset=utf-8";
            ctx.Response.Headers.Location = "/auth/captcha";
            await ctx.Response.WriteAsync("Please click here to continue.");
            Roblox.Metrics.ApplicationGuardMetrics.ReportBlockedUserAgent(ua);
            return;
        }
        uaTimer.Stop();

        if (!uaBlocked && !bypassOk && !bypassAllowedForPath)
            Roblox.Metrics.ApplicationGuardMetrics.ReportAllowedUserAgent(ua);

        var authTimer = new MiddlewareTimer(ctx, "a");
        var isAuthorized = IsAuthorized(ctx);
        authTimer.Stop();

        if (isAuthorized || allowedUrls.Contains(normalizedPath) ||
            RobloxPlayerDataRegex.IsMatch(normalizedPath))
            {
                appGuardTimer.Stop();
                await _next(ctx);
                return;
            }

            // If not blocked
            if (FeatureFlags.IsDisabled(FeatureFlag.AllowAccessToAllRequests))
            {
                await Redirect(ctx, "/auth/home");
                return;
            }
            // Otherwise, allow (almost) all
            if (normalizedPath == "")
            {
                await Redirect(ctx, "/auth/home");
                return;
            }
            appGuardTimer.Stop();
            await _next(ctx);
        }
}

public static class ApplicationGuardMiddlewareExtensions
{
    public static IApplicationBuilder UseApplicationGuardMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<ApplicationGuardMiddleware>();
    }
}

using System;

class RobloxPlayerDataRegex
{
    public static void Main()
    {
        // To resolve the error in the example, the first step is to
        // move the declaration of conn out of the try block. The following
        // declaration is available throughout the Main method.
        RobloxPlayerDataRegex conn = null;
        try
        {
            // Inside the try block, use the conn variable that you declared
            // previously.
            conn = new RobloxPlayerDataRegex();
        }
        catch (Exception e)
        {
            // The following expression no longer causes an error, because
            // the declaration of conn is in scope.
            if (conn != null)
                Console.WriteLine("{0}", e);
        }
    }
}

but when i run dotnet run it gives this error:

E:\Datacenter\src\services\Roblox\Roblox.Website\Middleware\ApplicationGuardMiddleware.cs(405,1): error CS1529: A using clause must precede
all other elements defined in the namespace except external alias declarations [E:\Datacenter\src\services\Roblox\Roblox.Website\Roblo
x.Website.csproj]

Build failed. Fix build errors and rerun.

im very new at .NET, sorry if this question is stupid.

no DOTNET RUN Errors


问:
In reactjs I am getting this error I installed react before in C drive and later in G drive please
$ npm start
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path G:\devtown\Projects\React/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'G:\devtown\Projects\React\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\dell\AppData\Local\npm-cache_logs\2022-12-19T14_22_32_193Z-debug-0.log

dell@DESKTOP-1BP11MN MINGW64 /g/devtown/Projects/React
$ npm run
npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path G:\devtown\Projects\React/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'G:\devtown\Projects\React\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\dell\AppData\Local\npm-cache_logs\2022-12-19T14npm ERR! enoent ENOENT: no such file or directory, open 'G:\devtown\Projects\React\package.json'npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\dell\AppData\Local\npm-cache_logs\2022-12-19T14_25_05_840Z-debug-0.log

I tried to uninstall the npm-cache but it won't really worked!


问:
When to use an event instead of a delegate in C#?
I have these two sample classes:

```<code>void Main()
{
    Provider1 myProvider1 = new Provider1();
    myProvider1.MyEvent += (sender, eventData) => Console.WriteLine($"the event1 handled : {eventData.Data}");

    myProvider1.DoSth();

    //
    Provider2 myProvider2 = new Provider2();
    myProvider2.MyEvent = (sender, eventData) => Console.WriteLine($"the event2 handled : {eventData.Data}");

    myProvider2.DoSth();
}

public class SampleEventArgs : EventArgs
{
    public string Data { get; }
    public SampleEventArgs(string data)
    {
        Data = data;
    }
}

public class Provider1
{
    public event EventHandler<SampleEventArgs> MyEvent;

    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}

public class Provider2
{
    public Action<object, SampleEventArgs> MyEvent;
    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}
</code>```

Provider1 has a event MyEvent and Provider2 has a Action<object> MyEvent (to act just like the event in Provider1).
I can achieve the same result from both of them, but I want to know when to use each pattern and why (I know that Action is just a delegate).

Updated based on comments

Body:
I have these two sample classes:

void Main()
{
    Provider1 myProvider1 = new Provider1();
    myProvider1.MyEvent += (sender, eventData) => Console.WriteLine($"the event1 handled : {eventData.Data}");

    myProvider1.DoSth();

    //
    Provider2 myProvider2 = new Provider2();
    myProvider2.MyEvent = (sender, eventData) => Console.WriteLine($"the event2 handled : {eventData.Data}");

    myProvider2.DoSth();
}

public class SampleEventArgs : EventArgs
{
    public string Data { get; }
    public SampleEventArgs(string data)
    {
        Data = data;
    }
}

public class Provider1
{
    public event EventHandler<SampleEventArgs> MyEvent;

    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}

public class Provider2
{
    public Action<object, SampleEventArgs> MyEvent;
    public void DoSth()
    {
        MyEvent?.Invoke(this, new SampleEventArgs("TestData"));
    }
}

Provider1 has a event MyEvent and Provider2 has a Action<object> MyEvent (to act just like the event in Provider1).
I can achieve the same result from both of them, but I want to know when to use each pattern and why (I know that Action is just a delegate).

Updated based on comments


问:
Making a list of installed programs in Linux and install them using the file, that listed the name of the packages.?
I was thinking if there is any way to list all installed packages/programs in a file in Linux and install them in a new installed Linux from that file just like we do in python or PHP using pip and composer?

For example list some installed programs in a file :

nano

lsb_release

htop

...

and run a command to install them without typing them one by one in apt or other package manager.

I listed the installed programs using:
sudo apt list --installed -> list.txt

and then
sudo apt install list.txt

but of course it does not work.


问:
Nested extension module cannot be imported
I am trying to import an extension module contained inside a nested package. For the purposes of this example, it's the only element of the root module, but the real case has others. When I attempt to test the following module setup using tox (or cibuildwheel/pytest, it's the same result) I get the following error:

```<code>ImportError: cannot import name 'dummyext' from 'rootpack'
</code>```

Here is the code for setup.py:

```<code>import setuptools
import numpy

PACKAGE_NAME = 'rootpack'

setuptools.setup(
    name=PACKAGE_NAME,
    version="0.0.1",
    description="Testing extension module",
    packages=[PACKAGE_NAME],
    #ext_package=PACKAGE_NAME,
    ext_modules = [
        setuptools.Extension(
            'rootpack.dummyext',
            ['ext/dummy.c'],
            extra_compile_args=["-std=c99"],
            include_dirs=[numpy.get_include()],
        ),
    ],
    install_requires=[
        'numpy',
    ],
)
</code>```

And dummy.c:

```<code>#include <Python.h>
#include <numpy/arrayobject.h>

static PyObject* dummy_method(PyObject* self, PyObject* args)
{
    npy_int rows = 3;
    npy_int cols = 4;
    npy_intp dims[2] = {rows, cols};
    PyObject* arr_obj = PyArray_ZEROS(2, dims, NPY_INTP, 0);
    int* arr_data = PyArray_DATA(arr_obj);

    for(int i = 0; i < rows; ++i)
    {
        for(int j = 0; j < cols; ++j)
        {
            arr_data[i*cols + j] = i+j;
        }
    }
    return arr_obj;
}

static PyMethodDef dummyext_methods[] = {
    {"dummy_method", dummy_method, METH_VARARGS, "Returns a dummy array"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef dummyext_module = {
    PyModuleDef_HEAD_INIT,
    "dummyext",
    NULL,
    -1,
    dummyext_methods
};

PyMODINIT_FUNC PyInit_dummyext(void)
{
    PyObject* module = PyModule_Create(&dummyext_module);
    import_array();
    return module;
}
</code>```

Note that __init__.py files exist in both the rootpack and test directories. There is a trivial test file test/dummy.py that contains the from rootpack import dummyext line triggering the error.

I've tried using ext_package and changing the ext module name to just dummyext, but that results in the same error. If I remove the ext module from the nested hierarchy, it can be imported.

Body:
I am trying to import an extension module contained inside a nested package. For the purposes of this example, it's the only element of the root module, but the real case has others. When I attempt to test the following module setup using tox (or cibuildwheel/pytest, it's the same result) I get the following error:

ImportError: cannot import name 'dummyext' from 'rootpack'

Here is the code for setup.py:

import setuptools
import numpy

PACKAGE_NAME = 'rootpack'

setuptools.setup(
    name=PACKAGE_NAME,
    version="0.0.1",
    description="Testing extension module",
    packages=[PACKAGE_NAME],
    #ext_package=PACKAGE_NAME,
    ext_modules = [
        setuptools.Extension(
            'rootpack.dummyext',
            ['ext/dummy.c'],
            extra_compile_args=["-std=c99"],
            include_dirs=[numpy.get_include()],
        ),
    ],
    install_requires=[
        'numpy',
    ],
)

And dummy.c:

#include <Python.h>
#include <numpy/arrayobject.h>

static PyObject* dummy_method(PyObject* self, PyObject* args)
{
    npy_int rows = 3;
    npy_int cols = 4;
    npy_intp dims[2] = {rows, cols};
    PyObject* arr_obj = PyArray_ZEROS(2, dims, NPY_INTP, 0);
    int* arr_data = PyArray_DATA(arr_obj);

    for(int i = 0; i < rows; ++i)
    {
        for(int j = 0; j < cols; ++j)
        {
            arr_data[i*cols + j] = i+j;
        }
    }
    return arr_obj;
}

static PyMethodDef dummyext_methods[] = {
    {"dummy_method", dummy_method, METH_VARARGS, "Returns a dummy array"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef dummyext_module = {
    PyModuleDef_HEAD_INIT,
    "dummyext",
    NULL,
    -1,
    dummyext_methods
};

PyMODINIT_FUNC PyInit_dummyext(void)
{
    PyObject* module = PyModule_Create(&dummyext_module);
    import_array();
    return module;
}

Note that __init__.py files exist in both the rootpack and test directories. There is a trivial test file test/dummy.py that contains the from rootpack import dummyext line triggering the error.

I've tried using ext_package and changing the ext module name to just dummyext, but that results in the same error. If I remove the ext module from the nested hierarchy, it can be imported.


问:
Template parameter type deduction fails in GCC, not in Clang
Consider the following code (Godbolt):

```<code>#include <tuple>
#include <type_traits> // std::false_type, std::true_type

template <typename t_tuple, auto t_size = std::tuple_size_v<t_tuple>>
struct test : std::false_type {};

template <typename t_tuple>
struct test<t_tuple, 0> : std::true_type {};

int main(int argc, char **argv)
{
    static_assert(test<std::tuple<>>::value);
    return 0;
}
</code>```

Clang and some other compilers accept the code but in GCC and ICC the static assertion fails. Either changing the type of t_size from auto to std::size_t or casting the zero in the specialisation to std::size_t alleviates the issue. What I would like to know is:

Should I be able to pass the zero in the specialisation as int instead of std::size_t when setting the type of the second template parameter to auto? Obviously (?) the types do not match (since the type of std::tuple_size_v is std::size_t) but I was expecting the compiler to at least warn me about something.

Is there a best practice for using auto with non-type template parameters?

(I checked this question but it had to do with const/volatile.)

Body:
Consider the following code (Godbolt):

#include <tuple>
#include <type_traits> // std::false_type, std::true_type

template <typename t_tuple, auto t_size = std::tuple_size_v<t_tuple>>
struct test : std::false_type {};

template <typename t_tuple>
struct test<t_tuple, 0> : std::true_type {};

int main(int argc, char **argv)
{
    static_assert(test<std::tuple<>>::value);
    return 0;
}

Clang and some other compilers accept the code but in GCC and ICC the static assertion fails. Either changing the type of t_size from auto to std::size_t or casting the zero in the specialisation to std::size_t alleviates the issue. What I would like to know is:

Should I be able to pass the zero in the specialisation as int instead of std::size_t when setting the type of the second template parameter to auto? Obviously (?) the types do not match (since the type of std::tuple_size_v is std::size_t) but I was expecting the compiler to at least warn me about something.

Is there a best practice for using auto with non-type template parameters?

(I checked this question but it had to do with const/volatile.)


问:
Objective function for pendulum genetic algorithm
I am looking for help developing an objective function to minimise, to evolve (through genetic algorithm) a control system for this frictionless inverted pendulum (https://www.gymlibrary.dev/environments/classic_control/pendulum/).

The goal is to get the pendulum to stand upright.

I have modified the environment to provide the following inputs the

velocity ( +1/-1 anti-clockwise/clockwise) and
angle (-pi/+pi from top anti-clockwise/clockwise).

I am looking to define a function that is:

zero in the upright position when velocity is zero

high the further away the pendulum is from the upright position (function of angle)

high when the velocity is low the further away the pendulum is from the upright position (function of angle and inverse function of velocity)

What is the best way this could be represented?

Thanks,
Rupert


问:
How to define the "example" attribute of the swagger generated for a record?
When I create an API definition by hand in the swagger editor, I can specify an "example" field :

```<code>components:
  schemas:
    foo:
      required:
        - bar
      type: object
      properties:
        bar:
          type: string
          example: "a custom string example here"
</code>```

In C# I have a record with different attributes. When I launch my application, visual studio automatically generates a swagger, but for each of my fields the "example" attribute is the default one : "string". How can I define this example, directly in my .cs file? I'm looking for something like this:

```<code>public record Foo(
    /// <swagger.example>
    /// a custom string example here
    /// </swagger.example>
    string Bar
);
</code>```

Thank you in advance for your help, let me know if anything is not clear :)

Body:
When I create an API definition by hand in the swagger editor, I can specify an "example" field :

components:
  schemas:
    foo:
      required:
        - bar
      type: object
      properties:
        bar:
          type: string
          example: "a custom string example here"

In C# I have a record with different attributes. When I launch my application, visual studio automatically generates a swagger, but for each of my fields the "example" attribute is the default one : "string". How can I define this example, directly in my .cs file? I'm looking for something like this:

public record Foo(
    /// <swagger.example>
    /// a custom string example here
    /// </swagger.example>
    string Bar
);

Thank you in advance for your help, let me know if anything is not clear :)


问:
Debug jupyter notebook that uses multiprocessing in Visual Studio Code
I use multiprocessing in a juypter notebook to cut down the processing time. Unfortunately it seems it's not possible to use the debugger in Visual Studio Code to debug anything after the Pool has been created. At first I get this error message:

Couldn't find a debug adapter descriptor for debug type 'Python Kernel Debug Adapter'
(extension might have failed to activate)

Followed by this error message for every child process that was created:

Failed to launch debugger for child process X

This is the code in the jupyter cell

from multiprocessing import Pool
from func import x

with Pool(4) as p:
    results = p.map(x, [1,2,3,4])

for i in results:  # breakpoint
    print(i)
```
<p>It also requires a file 'func.py':</p>
<pre class="lang-py prettyprint-override"><code>def x(y):
    return y
</code>```

I also tried adding this as suggested in the vscode documentation, but with no effect:

import debugpy
debugpy.debug_this_thread()
```

Is there any way to debug a jupyter notebook that uses multiprocessing with vscode?

OS: Windows 10

Python: 3.11

VSCode: 1.74.1

Body:
I use multiprocessing in a juypter notebook to cut down the processing time. Unfortunately it seems it's not possible to use the debugger in Visual Studio Code to debug anything after the Pool has been created. At first I get this error message:

Couldn't find a debug adapter descriptor for debug type 'Python Kernel Debug Adapter'
(extension might have failed to activate)

Followed by this error message for every child process that was created:

Failed to launch debugger for child process X

This is the code in the jupyter cell

from multiprocessing import Pool
from func import x

with Pool(4) as p:
    results = p.map(x, [1,2,3,4])

for i in results:  # breakpoint
    print(i)

It also requires a file 'func.py':

def x(y):
    return y

I also tried adding this as suggested in the vscode documentation, but with no effect:

import debugpy
debugpy.debug_this_thread()

Is there any way to debug a jupyter notebook that uses multiprocessing with vscode?

OS: Windows 10

Python: 3.11

VSCode: 1.74.1


问:
What is a format for static documents like PDF but not divided into pages?
PDF is for static documents, so a document is shown the same in different applications, even if it has an unusual layout. But PDF documents are divided into pages because the format is designed for documents to be printed.

I would like to have a document with static content but with no page breaks. Which document format can do that? I guess that it could be achieved with PDF with a single page as long as it needs to be, but I don't know that any software could do that, and it seems like abuse of PDF.

I create PDF documents in LATEX, and they almost never are printed, and the page layout is in the way when they are read on a screen. So I'm looking for how I could have documents where the layout is fixed because of hyphenation, mathematics and graphics, but more suitable for reading on screens.


问:
Double hop issue? - SSIS gives access denied when writing to a flat CSV file on a network share
I'm hoping someone can help me resolve and issue I'm running into.  I have a user run app that calls an SSIS package to create a CSV file on a network file share.  The app then processes the CSV file.  This had been working but then we started getting an Access denied error coming from the SSIS package.  The app it self is able to read/write to the file and the directory.  When I run the SSIS package in Visual Studio on a VM then the package is able to create the output file and the app can process it.  I was getting issues even reading the file from TSQL.  I have been working with our support staff to edit the user delegation settings in Active Directory and I have gotten to the point where I can use TSQL to read the CSV file without issues.  If I start the SSIS job using TSQL the job runs without errors.  When I execute the package from the App using DT_EXEC then I get access denied.  When I start the job using SSMS, I get access denied.  I'm thinking this is still a double hop issue.

The msDS-allowedToDelegateTo setting on both server A and file server B are:

server A (running SQL Server and SSIS):

cifs/VM-SQL-B

cifs/VM-SQL-A.Domain.Biz

cifs/VM-SQL-A

cifs/VM-SQL-B.Domain.Biz

WSMAN/VM-SQL-B.Domain.Biz

HOST/VM-SQL-B

MSSQLSvc/VM-SQL-A.Domain.Biz:1433

MSSQLSvc/VM-SQL-B.Domain.Biz:1433

server B (File server):

cifs/VM-SQL-A.Domain.Biz

cifs/VM-SQL-A

cifs/VM-SQL-B.Domain.Biz

cifs/VM-SQL-B

WSMAN/VM-SQL-A.Domain.Biz

HOST/VM-SQL-A

MSSQLSvc/VM-SQL-A.Domain.Biz:1433

MSSQLSvc/VM-SQL-B.Domain.Biz:1433

I looking for input as to what I am missing.

Thanks much,


问:
Oracle apex clear value in select2 plugin with plsql
I have a Select2 plugin field called :P10_X

I'm trying to clear the field with Pl/SQL in dynamic action

```<code>:P10_X := null;
</code>```

But instead, it inserts the first option of the select list.
when I'm trying any other (valid) value such as :P10_X := 5; it works ok.
The attributes "Display Extra Values" and "Display Null Value" are set to "Yes" so this field can handle null.
Any idea how can I clear this field with PL/SQL? Thanks

Body:
I have a Select2 plugin field called :P10_X

I'm trying to clear the field with Pl/SQL in dynamic action

:P10_X := null;

But instead, it inserts the first option of the select list.
when I'm trying any other (valid) value such as :P10_X := 5; it works ok.
The attributes "Display Extra Values" and "Display Null Value" are set to "Yes" so this field can handle null.
Any idea how can I clear this field with PL/SQL? Thanks


问:
How do I import libraries for use in my Firefox Extension?
How should I import a library to use in a Firefox extension? I am not experienced with JS, so I apologize. For example, how should I import something like DOMPurify/

I'm not sure if I should just use imports like normal, or use NPM, or copy the src from the project page, etc.


问:
Match Hex To Nearest HTML Defined Color
Working on a PHP project with a large product list. Each product has an image. I've taken the main colors off the image, but its let me with thousands of colours. I am trying to "match" the colors to the closest HTML standard colour.

Cannot find any documentation on this being accurate, any help would be brilliant...

I have tried multiple efforts to make this work, with little success. When i've had it running, its thrown too many anamolies, clueless, please help...

Title: Match Hex To Nearest HTML Defined Color


问:
Adding "Uno.Cupertino" or "Uno.Material" to an Uno-Platform project make the project not compile. Even a blank project
After adding "Uno.Cupertino" or "Uno.Material" to any Uno-Platform project even a newly created blank project, the project no longer builds and throws tons of build errors.

Here are some of the common errors:

Error  CS0433  The type 'SuspendingEventArgs' exists in both 'Microsoft.Windows.SDK.NET, Version=10.0.19041.24, Culture=neutral, PublicKeyToken=31bf3856ad364e35' and 'Uno, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null'

Error  UXAML0001   Unable to find type Windows.UI.Xaml.ElementStub (net6.0-android)

I tried to solve the dependency errors by uninstalling or updating some of the packages to latest version but it makes no difference and it does not compile.


问:
Cannot use the package "openexr" in python within Blender
I've installed the "openexr" package within my windows system. To do this, i used powershell from my blender installation folder "C:\Program Files\Blender Foundation\Blender 3.0\3.0\python" to launch the command ".\bin\python.exe -m ensurepip", for installing pip, and then "pip install openexer" to install the package.

Everything seems fine, but when I open blender and start to code with a simple

import openexr

I obtain this error:

```<code>Traceback (most recent call last):
  File "\Text", line 1, in <module>
ModuleNotFoundError: No module named 'openexr'
Error: Python script failed, check the message in the system console
</code>```

The module seems installed, but it's like blender cannot access it. Someone can help me? I would be extremely happy if this could work !

At the moment I tried to re-install pip or the openexr package, but the problem persist.
Also, if I try to re-install openexr, the system answer me that the package is already installed.

Body:
I've installed the "openexr" package within my windows system. To do this, i used powershell from my blender installation folder "C:\Program Files\Blender Foundation\Blender 3.0\3.0\python" to launch the command ".\bin\python.exe -m ensurepip", for installing pip, and then "pip install openexer" to install the package.

Everything seems fine, but when I open blender and start to code with a simple

import openexr

I obtain this error:

Traceback (most recent call last):
  File "\Text", line 1, in <module>
ModuleNotFoundError: No module named 'openexr'
Error: Python script failed, check the message in the system console

The module seems installed, but it's like blender cannot access it. Someone can help me? I would be extremely happy if this could work !

At the moment I tried to re-install pip or the openexr package, but the problem persist.
Also, if I try to re-install openexr, the system answer me that the package is already installed.


问:
jwtGenerator - invalid input syntax for type uuid: "{}"
i am trying to create login register page with using PERN Stack and jwt

i have a database(vetmed) which consist of

```<code>CREATE TABLE  veterinaryInfo(
vetId uuid PRIMARY KEY DEFAULT
uuid_generate_v4(),
vetName VARCHAR(30) NOT NULL,
vetSurname VARCHAR(30) NOT NULL,
branch_Name VARCHAR(50) NOT NULL,
address VARCHAR(100) NOT NULL ,
email VARCHAR(30) NOT NULL,
phone VARCHAR(11) NOT NULL,
password VARCHAR(255) NOT NULL);
</code>```

Here is my jwt.Auth.js code:

```<code>const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const pool = require('../db');
const validInfo = require('../middleware/validInfo');
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');

//authorizeentication

router.post('/register', validInfo, async (req, res) => {
 try {
 //1. destructure the req.body ( )
   const { name, surname, branch, address_, mail, phone_, password_ } =
     req.body;

// 2. check if user exist ( if exist then throw error)
const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE email = $1',
  [mail]
);
//res.json(user.rows);

if (user.rows.length !== 0) {
  // user already exist
  return res.status(401).send('user already exist');
}

// 3. Bcrypty the user password

const saltRound = 10;
const salt = await bcrypt.genSalt(saltRound);

const bcryptPassword = await bcrypt.hash(password_, salt);

// 4. enter the new user inside the database

let newUser = await pool.query(
  'INSERT INTO veterinaryInfo(vetName, vetSurname, branch_Name,address,email,phone,password) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *',
  [name, surname, branch, address_, mail, phone_, bcryptPassword]
);

//res.json(newUser.rows[0]);

// 5 generating our jwt token
const token = jwtGenerator(newUser.rows[0].vetId);
res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});

//login route
router.post('/login', validInfo, async (req, res) => {
try {
// 1. destructure the req.body
const { name, surname, branch, address_, mail, phone_, password_ } =
  req.body;

// 2. check if user doesn't exist (if not then throw error)
const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE email = $1',
  [mail]
);

if (user.rows.length === 0) {
  return res.status(401).json('Password or Email is incorrect');
}

// 3. check if incoming password is the same the database password

const validPassword = await bcrypt.compare(
  password_,
  user.rows[0].password
);

// console.log(validPassword);

if (!validPassword) {
  return res.status(401).json('Password or Email is incorrect');
}

// 4. give them the twt token
const token = jwtGenerator(user.rows[0].vetId);
return res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});

router.get('/is-verify', authorization, async (req, res) => {
try {
res.json(true);
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});

module.exports = router;
</code>```

In postman i can create a new register successfully, i can use login and is-verify method succesfully. However,

Here is my dashboard.js code :

```<code>  const router = require('express').Router();
  const authorization = require('../middleware/authorization');
  const pool = require('../db');

  router.get('/', authorization, async (req, res) => {
  try {
  const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE vetId = $1',
  [req.user]
  );

  //res.json(user.rows[0]);
  // res.json('hello');
  res.json(user.rows[0]);
  } catch (err) {
  console.error(err.message);
  res.status(500).send('Server error');
  }
  });

  module.exports = router;
</code>```

In postman with http://localhost:5000/dashboard/ when i write the token value on the header which relative to login and is-verify. i can not access the vetId from res.json(user.rows[0])

Here is my jwtGenerator.js code:

```<code>  const jwt = require('jsonwebtoken');
  require('dotenv').config();
 //Look at file server/routes/dashboard.js to see the change code for this code

 function jwtGenerator(vetId) {
 const payload = {
 user: vetId,
 };
/*function jwtGenerator(vetId) {
 const payload = {
 user: {
  id: vetId,
 },
};*/

 return jwt.sign(payload, process.env.jwtSecret, { expiresIn: '1h' });
 }

 module.exports = jwtGenerator;
</code>```

authorization.js code :

```<code> const jwt = require('jsonwebtoken');
 require('dotenv').config();

 //this middleware will on continue on if the token is inside the local storage

 module.exports = async (req, res, next) => {
 try {
 // Get token from header
 const jwtToken = req.header('token');

 // Check if not token
 if (!jwtToken) {
   return res.status(403).json('not authorize');
 }

 // Verify token

 //it is going to give use the user id (user:{id: user.id})
 const payload = jwt.verify(jwtToken, process.env.jwtSecret);
 //console.log(jwtToken);
 req.user = payload.user;
 console.log(req.user);
 next();
 }catch (err) {
 console.error(err.message);
 res.status(403).json('not authorize');
 }
 };
</code>```

index.js code :

```<code> const express = require('express');
 const app = express();
 const cors = require('cors');

 app.use(express.json()); // req body
 app.use(cors());

 //ROUTES

 //register and login routes
 app.use('/auth', require('./routes/jwtAuth')); // activate routes
 app.use('/dashboard', require('./routes/dashboard')); // dashboard route

 app.listen(5000, () => {
 console.log('server is running on port 5000');
 });
</code>```

the output is

```<code> [nodemon] restarting due to changes...
 [nodemon] starting `node index index.js`
 server is running on port 5000
 {}
 invalid input syntax for type uuid: "{}"
</code>```

Body:
i am trying to create login register page with using PERN Stack and jwt

i have a database(vetmed) which consist of

CREATE TABLE  veterinaryInfo(
vetId uuid PRIMARY KEY DEFAULT
uuid_generate_v4(),
vetName VARCHAR(30) NOT NULL,
vetSurname VARCHAR(30) NOT NULL,
branch_Name VARCHAR(50) NOT NULL,
address VARCHAR(100) NOT NULL ,
email VARCHAR(30) NOT NULL,
phone VARCHAR(11) NOT NULL,
password VARCHAR(255) NOT NULL);

Here is my jwt.Auth.js code:

const express = require('express');
const router = express.Router();
const bcrypt = require('bcrypt');
const pool = require('../db');
const validInfo = require('../middleware/validInfo');
const jwtGenerator = require('../utils/jwtGenerator');
const authorization = require('../middleware/authorization');

//authorizeentication

router.post('/register', validInfo, async (req, res) => {
 try {
 //1. destructure the req.body ( )
   const { name, surname, branch, address_, mail, phone_, password_ } =
     req.body;

// 2. check if user exist ( if exist then throw error)
const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE email = $1',
  [mail]
);
//res.json(user.rows);

if (user.rows.length !== 0) {
  // user already exist
  return res.status(401).send('user already exist');
}

// 3. Bcrypty the user password

const saltRound = 10;
const salt = await bcrypt.genSalt(saltRound);

const bcryptPassword = await bcrypt.hash(password_, salt);

// 4. enter the new user inside the database

let newUser = await pool.query(
  'INSERT INTO veterinaryInfo(vetName, vetSurname, branch_Name,address,email,phone,password) VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *',
  [name, surname, branch, address_, mail, phone_, bcryptPassword]
);

//res.json(newUser.rows[0]);

// 5 generating our jwt token
const token = jwtGenerator(newUser.rows[0].vetId);
res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});

//login route
router.post('/login', validInfo, async (req, res) => {
try {
// 1. destructure the req.body
const { name, surname, branch, address_, mail, phone_, password_ } =
  req.body;

// 2. check if user doesn't exist (if not then throw error)
const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE email = $1',
  [mail]
);

if (user.rows.length === 0) {
  return res.status(401).json('Password or Email is incorrect');
}

// 3. check if incoming password is the same the database password

const validPassword = await bcrypt.compare(
  password_,
  user.rows[0].password
);

// console.log(validPassword);

if (!validPassword) {
  return res.status(401).json('Password or Email is incorrect');
}

// 4. give them the twt token
const token = jwtGenerator(user.rows[0].vetId);
return res.json({ token });
} catch (err) {
console.error(err.message);
res.status(500).send('Server error');
}
});

router.get('/is-verify', authorization, async (req, res) => {
try {
res.json(true);
} catch (err) {
console.error(err.message);
res.status(500).send('server error');
}
});

module.exports = router;

In postman i can create a new register successfully, i can use login and is-verify method succesfully. However,

Here is my dashboard.js code :

  const router = require('express').Router();
  const authorization = require('../middleware/authorization');
  const pool = require('../db');

  router.get('/', authorization, async (req, res) => {
  try {
  const user = await pool.query(
  'SELECT * FROM veterinaryInfo WHERE vetId = $1',
  [req.user]
  );

  //res.json(user.rows[0]);
  // res.json('hello');
  res.json(user.rows[0]);
  } catch (err) {
  console.error(err.message);
  res.status(500).send('Server error');
  }
  });

  module.exports = router;

In postman with http://localhost:5000/dashboard/ when i write the token value on the header which relative to login and is-verify. i can not access the vetId from res.json(user.rows[0])

Here is my jwtGenerator.js code:

  const jwt = require('jsonwebtoken');
  require('dotenv').config();
 //Look at file server/routes/dashboard.js to see the change code for this code

 function jwtGenerator(vetId) {
 const payload = {
 user: vetId,
 };
/*function jwtGenerator(vetId) {
 const payload = {
 user: {
  id: vetId,
 },
};*/

 return jwt.sign(payload, process.env.jwtSecret, { expiresIn: '1h' });
 }

 module.exports = jwtGenerator;

authorization.js code :

 const jwt = require('jsonwebtoken');
 require('dotenv').config();

 //this middleware will on continue on if the token is inside the local storage

 module.exports = async (req, res, next) => {
 try {
 // Get token from header
 const jwtToken = req.header('token');

 // Check if not token
 if (!jwtToken) {
   return res.status(403).json('not authorize');
 }

 // Verify token

 //it is going to give use the user id (user:{id: user.id})
 const payload = jwt.verify(jwtToken, process.env.jwtSecret);
 //console.log(jwtToken);
 req.user = payload.user;
 console.log(req.user);
 next();
 }catch (err) {
 console.error(err.message);
 res.status(403).json('not authorize');
 }
 };

index.js code :

 const express = require('express');
 const app = express();
 const cors = require('cors');

 app.use(express.json()); // req body
 app.use(cors());

 //ROUTES

 //register and login routes
 app.use('/auth', require('./routes/jwtAuth')); // activate routes
 app.use('/dashboard', require('./routes/dashboard')); // dashboard route

 app.listen(5000, () => {
 console.log('server is running on port 5000');
 });

the output is

 [nodemon] restarting due to changes...
 [nodemon] starting `node index index.js`
 server is running on port 5000
 {}
 invalid input syntax for type uuid: "{}"


问:
Angular http call does not convert nested array
My application has Angular 12 client and Java Spring REST API.
For one of the API that returns array, the http call converts the instances to associated instances in TypeScript correctly. This is as follows:

```<code>this.http.post<UserSearchResult[]>(serverURL, userSearchCriteria, httpOptions )
              .subscribe(
              (response) => {
               console.table(response);
               regComp.processSearchCallBack(response);
              );
</code>```

The associated API signature is as follows:

```<code>public UserSearchResult[] searchUser(@RequestBody UserSearchCriteria userContactInfoRemote)
</code>```

But when I nest the array in another wrapper class called UserSearchCriteria like this:

Server side VO:

```<code>public class UserSearchCriteria {

  String scFirstName;
  String scLastName;

  UserSearchResult[] usr;
}
</code>```

Server side API signature :

```<code>public UserSearchCriteria searchUser(@RequestBody UserSearchCriteria userContactInfoRemote)
</code>```

Client side TypeSript :

```<code>export class UserSearchCriteria{

  scFirstName : string = "";
  scLastName : string = "";
  usr : UserSearchResult[] = [];
}
</code>```

and http call as :

```<code>this.http.post<UserSearchCriteria>(serverURL, userSearchCriteria, httpOptions )
              .subscribe(
              (response) => {
                console.log('callForUserSearch : response');
                console.table(response);

                regComp.processSearchCallBack(response);

              });
</code>```

I end up with usr as undefined error.
I tried casting it using as and <> operator with first casting to unknown. I also tried casting to Object[] and any[] but usr stays as undefined.

So I have two questions :

What changes are necessary in http call to directly get the array of UserSearchResult in the UserSearchCriteria wrapper.

Secondly,
How to cast a reference (which is pointing to an array of Object) into array of UserSearchCriteria.

Thanks,

Nealesh

Here is sample output of API that return UserSearchCriteria:

Body:
My application has Angular 12 client and Java Spring REST API.
For one of the API that returns array, the http call converts the instances to associated instances in TypeScript correctly. This is as follows:

this.http.post<UserSearchResult[]>(serverURL, userSearchCriteria, httpOptions )
              .subscribe(
              (response) => {
               console.table(response);
               regComp.processSearchCallBack(response);
              );

The associated API signature is as follows:

public UserSearchResult[] searchUser(@RequestBody UserSearchCriteria userContactInfoRemote)

But when I nest the array in another wrapper class called UserSearchCriteria like this:

Server side VO:

public class UserSearchCriteria {

  String scFirstName;
  String scLastName;

  UserSearchResult[] usr;
}

Server side API signature :

public UserSearchCriteria searchUser(@RequestBody UserSearchCriteria userContactInfoRemote)

Client side TypeSript :

export class UserSearchCriteria{

  scFirstName : string = "";
  scLastName : string = "";
  usr : UserSearchResult[] = [];
}

and http call as :

this.http.post<UserSearchCriteria>(serverURL, userSearchCriteria, httpOptions )
              .subscribe(
              (response) => {
                console.log('callForUserSearch : response');
                console.table(response);

                regComp.processSearchCallBack(response);

              });

I end up with usr as undefined error.
I tried casting it using as and <> operator with first casting to unknown. I also tried casting to Object[] and any[] but usr stays as undefined.

So I have two questions :

What changes are necessary in http call to directly get the array of UserSearchResult in the UserSearchCriteria wrapper.

Secondly,
How to cast a reference (which is pointing to an array of Object) into array of UserSearchCriteria.

Thanks,

Nealesh

Here is sample output of API that return UserSearchCriteria:


问:
How can I fix the issue of unknown layer: PruneLowMagnitude when loading a pruned model?
I have a CNN that I pruned using Tensorflow. Keras and saved it as a
.h5 file.

Now when I try to load it with pr_model=load_model('Pruned_CNN.h5'), I always get the following error:

```<code>/tmp/ipykernel_4729/1589964011.py in <module>
----> 1 pmod = tensorflow.keras.models.load_model('Pruned_CNN.h5')

/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

/usr/local/lib/python3.8/dist-packages/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    603     cls = get_registered_object(class_name, custom_objects, module_objects)
    604     if cls is None:
--> 605         raise ValueError(
    606             f"Unknown {printable_module_name}: {class_name}. "
    607             "Please ensure this "

ValueError: Unknown layer: PruneLowMagnitude. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.
</code>```

How can I possibly fix this issue?

Body:
I have a CNN that I pruned using Tensorflow. Keras and saved it as a
.h5 file.

Now when I try to load it with pr_model=load_model('Pruned_CNN.h5'), I always get the following error:

/tmp/ipykernel_4729/1589964011.py in <module>
----> 1 pmod = tensorflow.keras.models.load_model('Pruned_CNN.h5')

/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py in error_handler(*args, **kwargs)
     68             # To get the full stack trace, call:
     69             # `tf.debugging.disable_traceback_filtering()`
---> 70             raise e.with_traceback(filtered_tb) from None
     71         finally:
     72             del filtered_tb

/usr/local/lib/python3.8/dist-packages/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    603     cls = get_registered_object(class_name, custom_objects, module_objects)
    604     if cls is None:
--> 605         raise ValueError(
    606             f"Unknown {printable_module_name}: {class_name}. "
    607             "Please ensure this "

ValueError: Unknown layer: PruneLowMagnitude. Please ensure this object is passed to the `custom_objects` argument. See https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object for details.

How can I possibly fix this issue?


问:
Prevent script from modifying specific object
The problem I have is that there's a bootstrap-slider in a bootstrap-slider in my website and firing the data-slide="next" button affects both of the sliders.

Note: Code is not working in this example because it's drastically shortened to make it readable.

      Previous

      Previous

```
<p>It currently removes the "active" class from the "#subTeaserCarousel .item" to. That shouldn't happen.</p>
<p>I hoped there could be a way to fix this problem without changing the bootstrap library script. I thought there might be something like that, that could work:</p>
<p><strong>Pseudo code:</strong></p>
```$(".changeTeaser").on("click", function() {
   ("#subTeaserCarousel").preventDefault();
});
```

Any other solutions which prevent the second slider from changing are also very welcomed.

Body:
The problem I have is that there's a bootstrap-slider in a bootstrap-slider in my website and firing the data-slide="next" button affects both of the sliders.

Note: Code is not working in this example because it's drastically shortened to make it readable.

      Previous

      Previous

It currently removes the "active" class from the "#subTeaserCarousel .item" to. That shouldn't happen.

I hoped there could be a way to fix this problem without changing the bootstrap library script. I thought there might be something like that, that could work:

Pseudo code:

$(".changeTeaser").on("click", function() {
   ("#subTeaserCarousel").preventDefault();
});

Any other solutions which prevent the second slider from changing are also very welcomed.


问:
How to configure HTTP request body parser using Bigquery Java client library
I need to configure a parser which can add few default fields(such as default labels) in the request body of underlying BQ HTTP request whenever any query is run via this bqserv instance (like mentioned in the code snippet below). How to build bqserv?

```<code>bqserv.query(QueryJobConfiguration.newBuilder(query).build)
</code>```

I found BigQueryOptions.newBuilder().setTransportOptions() to set transport options, but I am unable to figure out exactly how to configure/(or set a parser for) HTTP request body ? I came across com.google.cloud.spark.bigquery.repackaged.com.google.api.client.util.ObjectParser as well, but again not sure how to use it and create bqserv (class com.google.cloud.spark.bigquery.repackaged.com.google.cloud.bigquery.BigQueryImpl) object.

Body:
I need to configure a parser which can add few default fields(such as default labels) in the request body of underlying BQ HTTP request whenever any query is run via this bqserv instance (like mentioned in the code snippet below). How to build bqserv?

bqserv.query(QueryJobConfiguration.newBuilder(query).build)

I found BigQueryOptions.newBuilder().setTransportOptions() to set transport options, but I am unable to figure out exactly how to configure/(or set a parser for) HTTP request body ? I came across com.google.cloud.spark.bigquery.repackaged.com.google.api.client.util.ObjectParser as well, but again not sure how to use it and create bqserv (class com.google.cloud.spark.bigquery.repackaged.com.google.cloud.bigquery.BigQueryImpl) object.


问:
What is the correct syntax to add no_cache to a docker-compose file?
I'm trying to specify a container should not use cache when docker builds the container.  Support for the --no-cache command-line argument was added in docker-compose 2.4.0.  This works fine for me, no trouble at all.

It is also listed in the official compose file build reference, see types.go line 313 and compose-spec.json, line 98.

However, when I try to add any variation of no_cache: true under my compose.yaml build: stanza, I get the following error:

ERROR: The Compose file '/opt/docker-compose.yaml' is invalid because: services.pleroma.build contains unsupported option: 'no_cache'

Am I using incorrect syntax here, or is this simply not possible to currently do in the compose file itself?  Below is the entire config for the image I want to build.

```<code>  pleroma:
    image: pleroma
    hostname: pleroma
    container_name: pleroma
    networks:
      dockerapps:
        ipv4_address: 172.18.0.77
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "wget -q --spider --proxy=off localhost:4000 || exit 1",
        ]
    restart: unless-stopped
    build:
      context: /opt/pleroma/.
      dockerfile: /opt/pleroma/Dockerfile
      no_cache: true
      # Feel free to remove or override this section
      # See 'Build-time variables' in README.md
      args:
        - "UID=1000"
        - "GID=1000"
        - "PLEROMA_VER=develop"
    volumes:
      - ./uploads:/var/lib/pleroma/uploads
      - ./static:/var/lib/pleroma/static
      - ./config.exs:/etc/pleroma/config.exs:ro
      - ./config-override.exs:/var/lib/pleroma/config.exs:ro
    env_file:
      - /opt/pleroma/.docker.env
    depends_on:
      - pleroma_db
</code>```

Body:
I'm trying to specify a container should not use cache when docker builds the container.  Support for the --no-cache command-line argument was added in docker-compose 2.4.0.  This works fine for me, no trouble at all.

It is also listed in the official compose file build reference, see types.go line 313 and compose-spec.json, line 98.

However, when I try to add any variation of no_cache: true under my compose.yaml build: stanza, I get the following error:

ERROR: The Compose file '/opt/docker-compose.yaml' is invalid because: services.pleroma.build contains unsupported option: 'no_cache'

Am I using incorrect syntax here, or is this simply not possible to currently do in the compose file itself?  Below is the entire config for the image I want to build.

  pleroma:
    image: pleroma
    hostname: pleroma
    container_name: pleroma
    networks:
      dockerapps:
        ipv4_address: 172.18.0.77
    healthcheck:
      test:
        [
          "CMD-SHELL",
          "wget -q --spider --proxy=off localhost:4000 || exit 1",
        ]
    restart: unless-stopped
    build:
      context: /opt/pleroma/.
      dockerfile: /opt/pleroma/Dockerfile
      no_cache: true
      # Feel free to remove or override this section
      # See 'Build-time variables' in README.md
      args:
        - "UID=1000"
        - "GID=1000"
        - "PLEROMA_VER=develop"
    volumes:
      - ./uploads:/var/lib/pleroma/uploads
      - ./static:/var/lib/pleroma/static
      - ./config.exs:/etc/pleroma/config.exs:ro
      - ./config-override.exs:/var/lib/pleroma/config.exs:ro
    env_file:
      - /opt/pleroma/.docker.env
    depends_on:
      - pleroma_db