问:
Alternative to dir command to query a directory in C
I am trying to create a program where the user can add different path regex-s so that a specific set of operations on the files that match the regex.

I tried using opendir() of the dirent.h header file but soon realized that it does not use the concept of regex.

The dir command I am trying to emulate is

```<code>dir [regex] /b
</code>```

I need the output in a (char) buffer**. Piping the output could be a solution but I am looking for a more efficient way to do it.

Is there any predefined function in the standard (C90) library or will we have to create our own implementation?

答:
C does not know about directories. They are operating system specific, usually provided by your OS kernel (look however inside GNU Hurd as an exception, and into unikernels). Read the C11 standard n1570 and forget, in 2020, about the obsolete C89  standard and TurboC. Consider trying some Linux distribution (such as Ubuntu or Debian or others). Most of them provide GCC or Clang (or the non-optimizing TinyCC compiler) and are very developer-friendly. My recommendation: use GCC as gcc -Wall -Wextra -g. Choose a good enough built automation tool (maybe GNU make) with an appropriate source-code editor (such as GNU emacs or vim or geany or others). Learn how to debug small programs and use the GDB debugger and the git version control tool.

POSIX does know about directories (it is an API specification written in English,  also defining regex(3)). See here, and read the Linux man pages. And also the WinAPI.

On Linux, see mkdir(2), chdir(2),  readdir(3), getcwd(3), unlink(2), stat(2), open(2), nftw(3), path_resolution(7) etc etc; you could want to study the source code of a Linux kernel and of some common C library for it, such as GNU glibc or musl-libc. Budget for that several months full time of your efforts. They are open source, so with some conditions you are allowed to study, improve and reuse their source code. See also http://linuxfromscratch.org/

Notice also popen. You probably don't want to use it and would prefer using more primitive system calls (see syscalls(2) for their list on Linux). You could use a library like Glib (from GTK).

Remember that C programs (of the freestanding kind) could run on the bare metal (e.g. Arduino). In those cases, speaking of directories does not make any sense. See also osdev.org for more, and observe that the Linux kernel is written in C (with a tiny amount of assembler code).

GrassHopper was an OS written mostly in C without any files or directories. See also old discussions archived on tunes.org and tccboot.

Body:
I am trying to create a program where the user can add different path regex-s so that a specific set of operations on the files that match the regex.

I tried using opendir() of the dirent.h header file but soon realized that it does not use the concept of regex.

The dir command I am trying to emulate is

dir [regex] /b

I need the output in a (char) buffer**. Piping the output could be a solution but I am looking for a more efficient way to do it.

Is there any predefined function in the standard (C90) library or will we have to create our own implementation?


来源: stackexchange

问:
ImportError: No module named pywintypes
I am working to make a small keylogger with Python, by using the pyHook, pythoncom and Pywin32 modules. Here is my code:

```<code>import pyHook, pythoncom, sys, logging

file_log = 'C:\\important\\log.txt'

def OnKeyboardEvent (event):
    logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
    chr(event.Ascii)
    logging.log(10, chr(Event.Ascii))
    return True
hooks_manager=pyHook.HookManager()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()
</code>```

When it runs, it returns this error message:

```<code> File "C:\Python27\lib\site-packages\pythoncom.py", line 2, in <module>
    import pywintypes
ImportError: No module named pywintypes
</code>```

How do I fix this error?

答:
For me it worked to copy the files (pythoncom38.dll and pywintypes38.dll)  from:

```<code>C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\pywin32_system32
</code>```

To the path:

```<code>C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\win32\lib
</code>```

and

```<code>C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\win32
</code>```

After installation of Visual Studio, I need sometimes to restart computer after copy the files.

ContentLicense: CC BY-SA 3.0

Title: ImportError: No module named pywintypes

Body:
I am working to make a small keylogger with Python, by using the pyHook, pythoncom and Pywin32 modules. Here is my code:

import pyHook, pythoncom, sys, logging

file_log = 'C:\\important\\log.txt'

def OnKeyboardEvent (event):
    logging.basicConfig(filename=file_log, level=logging.DEBUG, format='%(message)s')
    chr(event.Ascii)
    logging.log(10, chr(Event.Ascii))
    return True
hooks_manager=pyHook.HookManager()
hooks_manager.KeyDown = OnKeyboardEvent
hooks_manager.HookKeyboard()
pythoncom.PumpMessages()

When it runs, it returns this error message:

 File "C:\Python27\lib\site-packages\pythoncom.py", line 2, in <module>
    import pywintypes
ImportError: No module named pywintypes

How do I fix this error?

Body:
For me it worked to copy the files (pythoncom38.dll and pywintypes38.dll)  from:

C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\pywin32_system32

To the path:

C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\win32\lib

and

C:\Users\"Your user id"\AppData\Roaming\Python\Python38\site-packages\win32

After installation of Visual Studio, I need sometimes to restart computer after copy the files.

ContentLicense: CC BY-SA 4.0


问:
Asp.net Core 2 publish project on IIS returns just a blank page?
I am working on a Asp.net core 2.0 project and i publish it and want to run on IIS.
When the project runs for first time on IIS the database created automatically and seed some tables on IIS and everything is ok. But nothing will by displayed and just returns a blank page without any error.

web.config :

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
  <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule"     resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\LibraryProject.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
<!--ProjectGuid: b874d2d9-471b-494a-828c-257173c5a413-->
</code>```

and Program.cs :

```<code>public class Program
{

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
                var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
                var context = services.GetRequiredService<ApplicationDbContext>();
                SeedData.Seeding(userManager, roleManager, context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseIISIntegration()
               .UseStartup<Startup>()
               .Build();

}
</code>```

Also i created logs\stdout folder in publish folder near other dll`s.
I set up IIS from this link. what is wrong in my project?

答:
I am a little late to the game here but I don't see anyone else answering.  Hopefully this will help someone.

When you see just a blank page and have no response other that the blank page, it can be caused by one of two things.  I am sure there are others but these are the two that I have seen:

A corrupt web.config

A web.config that is clashing with IIS.  This could happen when a particular section is locked in your IIS configuration.

Body:
I am working on a Asp.net core 2.0 project and i publish it and want to run on IIS.
When the project runs for first time on IIS the database created automatically and seed some tables on IIS and everything is ok. But nothing will by displayed and just returns a blank page without any error.

web.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
  <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule"     resourceType="Unspecified" />
</handlers>
<aspNetCore processPath="dotnet" arguments=".\LibraryProject.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>

and Program.cs :

public class Program
{

    public static void Main(string[] args)
    {
        var host = BuildWebHost(args);

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;
            try
            {
                var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
                var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
                var context = services.GetRequiredService<ApplicationDbContext>();
                SeedData.Seeding(userManager, roleManager, context);
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred while seeding the database.");
            }
        }

        host.Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
         WebHost.CreateDefaultBuilder(args)
               .UseKestrel()
               .UseContentRoot(Directory.GetCurrentDirectory())
               .UseIISIntegration()
               .UseStartup<Startup>()
               .Build();

}

Also i created logs\stdout folder in publish folder near other dll`s.
I set up IIS from this link. what is wrong in my project?


问:
msiexec not doing the exaction to the provided path
The issue has already been discussed here, but did not end up with any clear answer, so it is raised again.

I am trying to extract the contents of an .msi file as follows:

```<code>function script:Export-MsiContents
{
[CmdletBinding()]
param
(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [ValidateScript({$_.EndsWith(".msi")})]
    [String] $MsiPath,

    [Parameter(Mandatory=$false, Position = 1)]
    [String] $TargetDirectory
)

if(-not($TargetDirectory))
{
    $currentDir = [System.IO.Path]::GetDirectoryName($MsiPath)
    Write-Warning "A target directory is not specified. The contents of the MSI will be extracted to the location, $currentDir\Temp"

    $TargetDirectory = Join-Path $currentDir "Temp"
}

$MsiPath = Resolve-Path $MsiPath

Write-Verbose "Extracting the contents of $MsiPath to $TargetDirectory"
Start-Process "MSIEXEC" -ArgumentList "/a $MsiPath /qn TARGETDIR=$TargetDirectory" -Wait -NoNewWindow
}
</code>```

Once called I get the window pop up . Please take a look at the attached screenshot

And there is no extraction of the .msi file.

答:
1. Escaping: The escape character in PowerShell is the grave-accent: ` (ASCII: 96, Unicode: U+0060 - I think). Grave accent use in programming. Try to escape as follows:

```<code>Start-Process "MSIEXEC" -ArgumentList "/a `"C:\my setup.msi`" /qn TARGETDIR=`"C:\Extract here`"" -Wait -NoNewWindow
</code>```

2. "Stop Parsing": PSv3+ offers --%, the stop-parsing symbol (more from ss64.com). It passes the rest of the command line as-is to the external utility, save for potential expansion of %...%-style environment variables:

```<code># Everything after --% is passed as-is.
msiexec --% /a "C:\my setup.msi" /qn TARGETDIR="C:\Extract here"
</code>```

I am not a Powershell expert. The above based on:

Command line arguments for msiexec break on powershell if they contain space

How to suppress quotes in PowerShell commands to executables

Other Links:

Using --% in PowerShell

What is the purpose of administrative installation initiated using msiexec /a?

How can I use powershell to run through an installer?

Body:
The issue has already been discussed here, but did not end up with any clear answer, so it is raised again.

I am trying to extract the contents of an .msi file as follows:

function script:Export-MsiContents
{
[CmdletBinding()]
param
(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [ValidateScript({$_.EndsWith(".msi")})]
    [String] $MsiPath,

    [Parameter(Mandatory=$false, Position = 1)]
    [String] $TargetDirectory
)

if(-not($TargetDirectory))
{
    $currentDir = [System.IO.Path]::GetDirectoryName($MsiPath)
    Write-Warning "A target directory is not specified. The contents of the MSI will be extracted to the location, $currentDir\Temp"

    $TargetDirectory = Join-Path $currentDir "Temp"
}

$MsiPath = Resolve-Path $MsiPath

Write-Verbose "Extracting the contents of $MsiPath to $TargetDirectory"
Start-Process "MSIEXEC" -ArgumentList "/a $MsiPath /qn TARGETDIR=$TargetDirectory" -Wait -NoNewWindow
}

Once called I get the window pop up . Please take a look at the attached screenshot

And there is no extraction of the .msi file.

Body:
1. Escaping: The escape character in PowerShell is the grave-accent: ` (ASCII: 96, Unicode: U+0060 - I think). Grave accent use in programming. Try to escape as follows:

Start-Process "MSIEXEC" -ArgumentList "/a `"C:\my setup.msi`" /qn TARGETDIR=`"C:\Extract here`"" -Wait -NoNewWindow

2. "Stop Parsing": PSv3+ offers --%, the stop-parsing symbol (more from ss64.com). It passes the rest of the command line as-is to the external utility, save for potential expansion of %...%-style environment variables:

# Everything after --% is passed as-is.
msiexec --% /a "C:\my setup.msi" /qn TARGETDIR="C:\Extract here"

I am not a Powershell expert. The above based on:

Command line arguments for msiexec break on powershell if they contain space

How to suppress quotes in PowerShell commands to executables

Other Links:

Using --% in PowerShell

What is the purpose of administrative installation initiated using msiexec /a?

How can I use powershell to run through an installer?


问:
help with a PHP regex to extract text around a string
I am trying to use a regular expression and it's just breaking my brain.  I'll think I have it and the the script just breaks. I need to try to give people a way to report their location via SMS. I ask them to text me a string that looks like this:

I give up, stopping for the night.
  Find me at Main Street and Pine,
  Atlanta, GA.

And I want to break it at Find me at. I need to capture everything to the right of that (essentially their street corner) and I need to be able to detect if they didn't use proper capitalization for Find.

Any suggestions?

答:
Well, a non-regexp solution comes to mind.

```<code>$string = 'I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA.';
$findMe = 'Find me at';
$address = substr(strstr($string, $findMe), strlen($findMe));
if ($address == '') {
    // no match
}
</code>```

Then there is a regexp-based solution.

```<code>preg_match('/Find me at (.*)$/', $string, $match);
if (!isset($match[1])) {
    // no match found
} else {
    $address = $match[1];
}
</code>```

Body:
Well, a non-regexp solution comes to mind.

$string = 'I give up, stopping for the night. Find me at Main Street and Pine, Atlanta, GA.';
$findMe = 'Find me at';
$address = substr(strstr($string, $findMe), strlen($findMe));
if ($address == '') {
    // no match
}

Then there is a regexp-based solution.

preg_match('/Find me at (.*)$/', $string, $match);
if (!isset($match[1])) {
    // no match found
} else {
    $address = $match[1];
}


问:
Vert.x @ConsumeEvent for a List of events
Just a quick question related to a @ConsumeEvent method that has a list of objects.
A full project example can be found here.

Long story short:

In the consumer side (see my ConfigManager implementation), this method is accepted and it works just fine:

```<code>@ConsumeEvent(Config.EBA_CONFIG_RELOAD)
public String reload(ReloadConfigEvent event) { ... }
</code>```

but a method like the one below makes the Quarkus startup to fail due to the error ClassNotFoundException: java.util.List<org.acme.config.events.ReloadConfigEvent>:

```<code>@ConsumeEvent(Config.EBA_CONFIG_RELOAD)
public String reload(List<ReloadConfigEvent> events) { ... }
</code>```

Although a MessageCodec is being registered at startup (in another @ApplicationScoped class, see my Config's onStart() method), it looks that this registration will happen so late in the process that the issue persists.

Any idea whether I could set an order of processing these two @ApplicationScoped beans, or if I could do the registration of the MessageCodec in another (more earlier considered) case?

Many thanks in advance!

答:
Collections and arrays are not directly supported. What you already did is a good workaround, which is wrapping a collection into a class and use that class as an event.

One extra note is that you don't need to register codec because they are registered  automatically if they are used within @ConsumeEvent.

If you want to override an event codec, you can do as below

```<code> @ConsumeEvent(value = Config.EBA_CONFIGS_RELOAD, codec = YourCodec.class)
</code>```

Body:
Just a quick question related to a @ConsumeEvent method that has a list of objects.
A full project example can be found here.

Long story short:

In the consumer side (see my ConfigManager implementation), this method is accepted and it works just fine:

@ConsumeEvent(Config.EBA_CONFIG_RELOAD)
public String reload(ReloadConfigEvent event) { ... }

but a method like the one below makes the Quarkus startup to fail due to the error ClassNotFoundException: java.util.List<org.acme.config.events.ReloadConfigEvent>:

@ConsumeEvent(Config.EBA_CONFIG_RELOAD)
public String reload(List<ReloadConfigEvent> events) { ... }

Although a MessageCodec is being registered at startup (in another @ApplicationScoped class, see my Config's onStart() method), it looks that this registration will happen so late in the process that the issue persists.

Any idea whether I could set an order of processing these two @ApplicationScoped beans, or if I could do the registration of the MessageCodec in another (more earlier considered) case?

Many thanks in advance!

Body:
Collections and arrays are not directly supported. What you already did is a good workaround, which is wrapping a collection into a class and use that class as an event.

One extra note is that you don't need to register codec because they are registered  automatically if they are used within @ConsumeEvent.

If you want to override an event codec, you can do as below

 @ConsumeEvent(value = Config.EBA_CONFIGS_RELOAD, codec = YourCodec.class)


问:
How to update array in a multiple array keeping same key
I have an array below. What i need to do is unset one array inside "Urunler" than updating a new array. Very crucial one is how can push new array by keeping same key value which is same deleted one.

```<code>stdClass Object
(
    [Urun] => Array
        (
            [0] => stdClass Object
                (
                    [Id] => 1384
                    [Urun_kodu] => UKy74GhoD1LZ
                    [Urun_adi] => Bizim Ayçiçek Yağı Teneke 5 Lt
                    [Urun_resim] => uploads/urunler_v/UKy74GhoD1LZ/637b4-bizim-aycicek-yagi-tenekelxwbmlgpdh.jpg
                    [Esas_tutar] => 27.00
                    [Esas_tutar_kdvsiz] => 25.00
                    [Kdv_tutar] => 2.00
                    [Kdv_tutar_adetli] => 6.00
                    [Adetli_tutar] => 81.00
                    [Adetli_tutar_kdvsiz] => 75.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 100
                )

            [1] => stdClass Object
                (
                    [Id] => 4518
                    [Urun_kodu] => UK6FfrWzDPLE
                    [Urun_adi] => Besler Ton Balığı 2x160 Gr
                    [Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
                    [Esas_tutar] => 10.80
                    [Esas_tutar_kdvsiz] => 10.00
                    [Kdv_tutar] => 0.80
                    [Kdv_tutar_adetli] => 2.40
                    [Adetli_tutar] => 32.40
                    [Adetli_tutar_kdvsiz] => 30.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 32
                )
            [2] => stdClass Object
                (
                    [Id] => 4518
                    [Urun_kodu] => UK6FfrWzDPLE
                    [Urun_adi] => Besler Ton Balığı 2x160 Gr
                    [Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
                    [Esas_tutar] => 10.80
                    [Esas_tutar_kdvsiz] => 10.00
                    [Kdv_tutar] => 0.80
                    [Kdv_tutar_adetli] => 2.40
                    [Adetli_tutar] => 32.40
                    [Adetli_tutar_kdvsiz] => 30.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 32
                )

        )
)
</code>```

Below, you can see my steps when pushing new array

```<code>$Urun = $SepetBilgisi->Urun;

        $MevcutUrunSayisi=count($Urun);
        $YeniUrun=[];
        foreach($Urun as $Key => $Value)
        {
            if($Value->Id== $UrunId){  // My target is $UrunId=4518 that means  $Urun[Urun][1] one
                unset($Urun[$Key]);

                if(count($Urun)< $MevcutUrunSayisi){

                    //Şimdi Yeni Array Buraya Ekleyelim

                    $YeniUrun[$Key]=[

                        "Id"=> $Value->Id,
                        "Urun_kodu" => $Value->Urun_kodu,
                        "Urun_resim" => $Value->Urun_resim,
                        "Esas_tutar" => $Value->Esas_tutar,
                        "Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
                        "Kdv_tutar" => $Value->Kdv_tutar,
                        "Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
                        "Adetli_tutar" => $Value->Adetli_tutar,
                        "Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
                        "Urun_adeti" => $YeniAdet,
                        "Urun_kuru" => $Value->Urun_kuru,
                        "Urun_ds" => $Value->Urun_ds
                    ];

                    array_push($Urun , $YeniUrun);

                }else{
                    return false;
                }

            }
        }
</code>```

Using 'array_push' only put new array end of main array as you know.

答:
You want to replace the key, not push to the end of the array:</p>

```<code>    $Urun = $SepetBilgisi->Urun;

    $MevcutUrunSayisi=count($Urun);
    $YeniUrun=[];
    foreach($Urun as $Key => $Value)
    {
        if($Value->Id== $UrunId){  // My target is $UrunId=4518 that means  $Urun[Urun][1] one

            if(count($Urun)< $MevcutUrunSayisi){

                //Şimdi Yeni Array Buraya Ekleyelim

                $replace=[
                    "Id"=> $Value->Id,
                    "Urun_kodu" => $Value->Urun_kodu,
                    "Urun_resim" => $Value->Urun_resim,
                    "Esas_tutar" => $Value->Esas_tutar,
                    "Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
                    "Kdv_tutar" => $Value->Kdv_tutar,
                    "Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
                    "Adetli_tutar" => $Value->Adetli_tutar,
                    "Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
                    "Urun_adeti" => $YeniAdet,
                    "Urun_kuru" => $Value->Urun_kuru,
                    "Urun_ds" => $Value->Urun_ds
                ];

                $Urun[$Key] = $replace;

            }else{
                return false;
            }

        }
    }
</code>```

Body:
I have an array below. What i need to do is unset one array inside "Urunler" than updating a new array. Very crucial one is how can push new array by keeping same key value which is same deleted one.

stdClass Object
(
    [Urun] => Array
        (
            [0] => stdClass Object
                (
                    [Id] => 1384
                    [Urun_kodu] => UKy74GhoD1LZ
                    [Urun_adi] => Bizim Ayçiçek Yağı Teneke 5 Lt
                    [Urun_resim] => uploads/urunler_v/UKy74GhoD1LZ/637b4-bizim-aycicek-yagi-tenekelxwbmlgpdh.jpg
                    [Esas_tutar] => 27.00
                    [Esas_tutar_kdvsiz] => 25.00
                    [Kdv_tutar] => 2.00
                    [Kdv_tutar_adetli] => 6.00
                    [Adetli_tutar] => 81.00
                    [Adetli_tutar_kdvsiz] => 75.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 100
                )

            [1] => stdClass Object
                (
                    [Id] => 4518
                    [Urun_kodu] => UK6FfrWzDPLE
                    [Urun_adi] => Besler Ton Balığı 2x160 Gr
                    [Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
                    [Esas_tutar] => 10.80
                    [Esas_tutar_kdvsiz] => 10.00
                    [Kdv_tutar] => 0.80
                    [Kdv_tutar_adetli] => 2.40
                    [Adetli_tutar] => 32.40
                    [Adetli_tutar_kdvsiz] => 30.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 32
                )
            [2] => stdClass Object
                (
                    [Id] => 4518
                    [Urun_kodu] => UK6FfrWzDPLE
                    [Urun_adi] => Besler Ton Balığı 2x160 Gr
                    [Urun_resim] => uploads/urunler_v/UK6FfrWzDPLE/bfeec-besler-ton-baligi-2x160-grqrgy6fl2hv.jpg
                    [Esas_tutar] => 10.80
                    [Esas_tutar_kdvsiz] => 10.00
                    [Kdv_tutar] => 0.80
                    [Kdv_tutar_adetli] => 2.40
                    [Adetli_tutar] => 32.40
                    [Adetli_tutar_kdvsiz] => 30.00
                    [Urun_adeti] => 3
                    [Urun_kuru] => TRY
                    [Urun_ds] => 32
                )

        )
)

Below, you can see my steps when pushing new array

$Urun = $SepetBilgisi->Urun;

        $MevcutUrunSayisi=count($Urun);
        $YeniUrun=[];
        foreach($Urun as $Key => $Value)
        {
            if($Value->Id== $UrunId){  // My target is $UrunId=4518 that means  $Urun[Urun][1] one
                unset($Urun[$Key]);

                if(count($Urun)< $MevcutUrunSayisi){

                    //Şimdi Yeni Array Buraya Ekleyelim

                    $YeniUrun[$Key]=[

                        "Id"=> $Value->Id,
                        "Urun_kodu" => $Value->Urun_kodu,
                        "Urun_resim" => $Value->Urun_resim,
                        "Esas_tutar" => $Value->Esas_tutar,
                        "Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
                        "Kdv_tutar" => $Value->Kdv_tutar,
                        "Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
                        "Adetli_tutar" => $Value->Adetli_tutar,
                        "Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
                        "Urun_adeti" => $YeniAdet,
                        "Urun_kuru" => $Value->Urun_kuru,
                        "Urun_ds" => $Value->Urun_ds
                    ];

                    array_push($Urun , $YeniUrun);

                }else{
                    return false;
                }

            }
        }

Using 'array_push' only put new array end of main array as you know.

Body:
You want to replace the key, not push to the end of the array:

    $Urun = $SepetBilgisi->Urun;

    $MevcutUrunSayisi=count($Urun);
    $YeniUrun=[];
    foreach($Urun as $Key => $Value)
    {
        if($Value->Id== $UrunId){  // My target is $UrunId=4518 that means  $Urun[Urun][1] one

            if(count($Urun)< $MevcutUrunSayisi){

                //Şimdi Yeni Array Buraya Ekleyelim

                $replace=[
                    "Id"=> $Value->Id,
                    "Urun_kodu" => $Value->Urun_kodu,
                    "Urun_resim" => $Value->Urun_resim,
                    "Esas_tutar" => $Value->Esas_tutar,
                    "Esas_tutar_kdvsiz" => $Value->Esas_tutar_kdvsiz,
                    "Kdv_tutar" => $Value->Kdv_tutar,
                    "Kdv_tutar_adetli" => $Value->Kdv_tutar_adetli,
                    "Adetli_tutar" => $Value->Adetli_tutar,
                    "Adetli_tutar_kdvsiz" => $Value->Adetli_tutar_kdvsiz,
                    "Urun_adeti" => $YeniAdet,
                    "Urun_kuru" => $Value->Urun_kuru,
                    "Urun_ds" => $Value->Urun_ds
                ];

                $Urun[$Key] = $replace;

            }else{
                return false;
            }

        }
    }


问:
How to create a ggplot2 bar chart out of a 2d data frame?

I have a 2d data frame created by a matrix data type in R, that has labels on both vertical and horizontal side.

How can I refer to them in the aes() tag in ggplot to draw a bar chart?

I appeal to add all columns (Up1-5) in X bar, and add vertical labels as legend.

data frame:

```<code>            Up1     Up2     Up3     Up4     Up5

Desktop     45026   99184   93127   1498    1597

Laptop      10451   87969   3546    1285    1251

Tablet      45282   12318   8850    7321    8709

Cell-Phone  54754   28377   10380   6363    9179

</code>```

Code:

```<code>ggplot(mydata, aes(x=???, y=???, fill=???) ) +
  geom_bar(width = 0.5, stat = "identity")
</code>```

答:
You need to convert the data frame to long format. Here is an example using pivot_longer.

```<code>library(tidyverse)

dat2 <- dat %>%
  rownames_to_column() %>%
  pivot_longer(cols = -rowname, names_to = "Up")

ggplot(dat2, aes(x = Up, y = value, fill = rowname)) +
  geom_bar(width = 0.5, stat = "identity")
</code>```

DATA

```<code>dat <- read.table(text = "        Up1     Up2     Up3     Up4     Up5
Desktop 45026 99184 93127 1498 1597

Laptop 10451 87969 3546 1285 1251

Tablet 45282 12318 8850 7321 8709

'Cell-Phone' 54754 28377 10380 6363 9179",
                  stringsAsFactors = FALSE, header = TRUE)
</code>```

Body:
I have a 2d data frame created by a matrix data type in R, that has labels on both vertical and horizontal side.

How can I refer to them in the aes() tag in ggplot to draw a bar chart?

I appeal to add all columns (Up1-5) in X bar, and add vertical labels as legend.

data frame:

            Up1     Up2     Up3     Up4     Up5

Desktop     45026   99184   93127   1498    1597

Laptop      10451   87969   3546    1285    1251

Tablet      45282   12318   8850    7321    8709

Cell-Phone  54754   28377   10380   6363    9179

Code:

ggplot(mydata, aes(x=???, y=???, fill=???) ) +
  geom_bar(width = 0.5, stat = "identity")

Body:
You need to convert the data frame to long format. Here is an example using pivot_longer.

library(tidyverse)

dat2 <- dat %>%
  rownames_to_column() %>%
  pivot_longer(cols = -rowname, names_to = "Up")

ggplot(dat2, aes(x = Up, y = value, fill = rowname)) +
  geom_bar(width = 0.5, stat = "identity")

DATA

dat <- read.table(text = "        Up1     Up2     Up3     Up4     Up5
Desktop 45026 99184 93127 1498 1597

Laptop 10451 87969 3546 1285 1251

Tablet 45282 12318 8850 7321 8709

'Cell-Phone' 54754 28377 10380 6363 9179",
                  stringsAsFactors = FALSE, header = TRUE)


问:
Save login form data using php
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

```<code>
    <html>
    <head>
    <title>Yahoo Signin And Signup Form</title>
    </head>
    <body>
     <h2 style="color: midnightblue">yahoo!</h2>
     <hr color="magenta">
    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    <label for ="firstName">Enter First Name</label><br>
    <input type="text" placeholder="First name" id="firstName" name ="firstName">
    <br>
    <label for ="lastName">Enter Last Name</label><br>
    <input type="text" placeholder="Last name" id="lastName" name ="lastName">
    <br>
    <label for ="email">Enter Email</label><br>
    <input type="text" placeholder="Email" id="email" name ="email"><br>
    <label for ="password">Enter Password</label><br>
    <input type="password" placeholder="Password" id="password" name ="password">
    <br>
    <label for ="number">Enter Mobile Number</label><br>
    <input placeholder="03---" id="number" name ="number"><br>
    <label for ="date">Enter Date of Birth</label><br>
    <input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
    <label for ="gender">Enter Gender</label><br>
    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender"><br>
    <br><button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>
    </body>
    </html>
</code>```

my connect.php

```<code>    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>
</code>```

答:
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.</p>

```<code><?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];

// Making Connection with database

$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{

    $sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
    values('$firstName','$lastName','$email','$password','$number','$date','$gender')";

if ($con->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

$con->close();

}//end of else of connection
?>
</code>```

Title: Save login form data using php

Body:
html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.

my html code

    <title>Yahoo Signin And Signup Form</title>

yahoo!

    <form method="post" action="connect.php" >
    <fieldset style="background:#6495ED;">
    <legend style="padding:20px 0; font-size:20px;">Signup:</legend>
    Enter First Name

    <input type="text" placeholder="First name" id="firstName" name ="firstName">

    Enter Last Name

    <input type="text" placeholder="Last name" id="lastName" name ="lastName">

    Enter Email

    <input type="text" placeholder="Email" id="email" name ="email">

    Enter Password

    <input type="password" placeholder="Password" id="password" name ="password">

    Enter Mobile Number

    <input placeholder="03---" id="number" name ="number">

    Enter Date of Birth

    <input type="text" placeholder="DD/MM/YY" id="date" name ="date">

    Enter Gender

    <input type="text" placeholder="Male/Female/Other" id="gender" name
    ="gender">

<button style="background-color:orangered;border-
    color:dodgerblue;color:lightyellow">Signup</button>
    </fielsdet>
    </form>

my connect.php

    <?php
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $number = $_POST['number'];
    $date = $_POST['date'];
    $gender = $_POST['gender'];

    // Making Connection with database

    $con = new mysqli('localhost','root','','phpdata');
    if ($con -> connect_error) {
    die('Connection failed :'.$conn -> connect_error);
    }
    else{
    $stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
    number, date, gender)
        values(?,?,?,?,?,?,?)");
    $stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
    $number, $date, $gender);
    $stmt->execute();
    echo "Sign up successful";
    $stmt->close();
    $con->close();
     }?>

Body:
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.

<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];

// Making Connection with database

$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{

    $sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
    values('$firstName','$lastName','$email','$password','$number','$date','$gender')";

if ($con->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $con->error;
}

$con->close();

}//end of else of connection
?>


问:
Saving Facebook access_token in NSUserDefaults on iOS
iOS beginner here. I'm using the following code to save my facebook accessToken and expirationDate in NSUserDefaults:

```<code>facebook = [[Facebook alloc] initWithAppId:@"225083222506272"];
    [facebook authorize:nil delegate:self];
    NSString *access=[facebook accessToken];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:access, @"accessToken",[facebook expirationDate], @"expirationDate",nil];
    [defaults registerDefaults:appDefaults];
</code>```

And I'm trying to retrieve accessToken and expirationDate in a later call with:

```<code> NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *access=[defaults valueForKey:@"accessToken"];
    NSDate *date=[defaults objectForKey:@"expirationDate"];
    [facebook fbDialogLogin:access expirationDate:date];
</code>```

but access and date are null. What am I doing wrong?

答:
The code here is not synchronous. It means it does not block after the call to [facebook authorize:nil delegate:self];. You should instead implement the fbDidLogin delegate method to be notified of when the user has actually logged in successfully. At that point, retrieve the access tokens and save them to user defaults.

Here's a partial sample:

```<code>- (void)userClickedFacebookLogin {
    [facebook authorize:nil delegate:self]; // delegate is self
}

// Delegate method that you should implement to get notified
// when user actualy logs in.
- (void)fbDidLogin {
    // now get the access token and save to user defaults
    NSString *access = [facebook accessToken];
    // ..
}
</code>```

Also make sure that the class which has the above code implements the FBSessionDelegate protocol at minimum.

```<code>@interface MyClass <FBSessionDelegate> {

}

@end
</code>```

Look at the DemoApp sample and specifically the DemoAppViewController class from Facebook to get a better idea.

Body:
iOS beginner here. I'm using the following code to save my facebook accessToken and expirationDate in NSUserDefaults:

facebook = [[Facebook alloc] initWithAppId:@"225083222506272"];
    [facebook authorize:nil delegate:self];
    NSString *access=[facebook accessToken];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:access, @"accessToken",[facebook expirationDate], @"expirationDate",nil];
    [defaults registerDefaults:appDefaults];

And I'm trying to retrieve accessToken and expirationDate in a later call with:

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *access=[defaults valueForKey:@"accessToken"];
    NSDate *date=[defaults objectForKey:@"expirationDate"];
    [facebook fbDialogLogin:access expirationDate:date];

but access and date are null. What am I doing wrong?

Body:
The code here is not synchronous. It means it does not block after the call to [facebook authorize:nil delegate:self];. You should instead implement the fbDidLogin delegate method to be notified of when the user has actually logged in successfully. At that point, retrieve the access tokens and save them to user defaults.

Here's a partial sample:

- (void)userClickedFacebookLogin {
    [facebook authorize:nil delegate:self]; // delegate is self
}

// Delegate method that you should implement to get notified
// when user actualy logs in.
- (void)fbDidLogin {
    // now get the access token and save to user defaults
    NSString *access = [facebook accessToken];
    // ..
}

Also make sure that the class which has the above code implements the FBSessionDelegate protocol at minimum.

@interface MyClass <FBSessionDelegate> {

}

@end

Look at the DemoApp sample and specifically the DemoAppViewController class from Facebook to get a better idea.


问:
Are the await / async keywords needed under Task.Run?
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

```<code>t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

vs

```<code>var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);
</code>```

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

答:
Without knowing what DoSomethingExpensiveAsync it's impossible to tell for certain what will happen.

Let's assume DoSomethingExpensiveAsync is something like this:

```<code>async Task DoSomethingExpensiveAsync()
{
     SynchronousMethod();
     await AsynchronousMethod();
}
</code>```

In the first snippet, Task.Run will schedule the invocation of DoSomethingExpensiveAsync to the thread pool and returns as soon as SynchronousMethod returns.

In the second snippet, Task.Run will schedule the invocation of DoSomethingExpensiveAsync to the thread pool and returns when the Task return by DoSomethingExpensiveAsync is completed.

Body:
I have an async lambda expression wrapped under Task.Run.
However, it looks like I can drop the async and await keywords and they will produce the same result.

t1 = Task.Run(() => DoSomethingExpensiveAsync());
t2 = Task.Run(() => DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

vs

var t1 = Task.Run(async () => await DoSomethingExpensiveAsync());
var t2 = Task.Run(async () => await DoSomethingExpensiveAsync());
await Task.WhenAll(t1, t2);

How come the compiler let me do this and what is happening behind
the scene?

Is there a situation where adding them will make a
difference?

Body:
Without knowing what DoSomethingExpensiveAsync it's impossible to tell for certain what will happen.

Let's assume DoSomethingExpensiveAsync is something like this:

async Task DoSomethingExpensiveAsync()
{
     SynchronousMethod();
     await AsynchronousMethod();
}

In the first snippet, Task.Run will schedule the invocation of DoSomethingExpensiveAsync to the thread pool and returns as soon as SynchronousMethod returns.

In the second snippet, Task.Run will schedule the invocation of DoSomethingExpensiveAsync to the thread pool and returns when the Task return by DoSomethingExpensiveAsync is completed.


问:
Check, whether an array contains an object with id that matches list of ids
is there an elegant way to determine, whether an array like this:

```<code>[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]
</code>```

contains an item with an id that is listed in another array like this:

```<code>[1,5]
</code>```

In this case only these values should be returned:

```<code>  {id: 1, value: false},
  {id: 5, value: true}
</code>```

I was trying to use includes(), but it's not working:

```<code>let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])
</code>```

答:
you can do this </p>

```<code>const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

const searchTerm = [1,5];

const result = data.filter((dataObject) => {

    // dataObject will be each item in the data array;
    return searchTerm.includes(dataObject.id)}
})
</code>```

Body:
is there an elegant way to determine, whether an array like this:

[
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
]

contains an item with an id that is listed in another array like this:

[1,5]

In this case only these values should be returned:

  {id: 1, value: false},
  {id: 5, value: true}

I was trying to use includes(), but it's not working:

let array = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

array.includes([1,5])

Body:
you can do this

const data = [
  {id: 1, value: false},
  {id: 2, value: true},
  {id: 3, value: false},
  {id: 4, value: true},
  {id: 5, value: true}
];

const searchTerm = [1,5];

const result = data.filter((dataObject) => {

    // dataObject will be each item in the data array;
    return searchTerm.includes(dataObject.id)}
})


问:
search in array for string match
What i have

```<code>var sentence = 'My country is India';
var array = ['Intel,' 'Goa', 'Green Day', 'India', 'Ice', 'India'];
</code>```

Result i need

```<code>  index = array.indexOf(sentence); // it should return 3
</code>```

And this is what i tried it works but its very slow and freezes and stop working when use big data

```<code>words = sentence.split(' ');
var i;
for (i = 0; i < words.length; i++) {
    w = words[i];
    a = array.indexOf(w);
    console.log(a);
}
</code>```

Update : i tried below solutions but still stop working i am working on google audio to speech so its run continually some one speeak so sentence array triggers again and again i think this is why its freezing after some point

Update 2: In above example i search for single word i.e. "India" but what if i its more than one word like if its a person name like "Neil Armstrong" then split method will not work.

答:
```<code>const sentence = 'My country is India';
const array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice', 'India'];
const my_vals =  array.map((val, inx)=> sentence
                     .match(val)? inx : -1)
                     .filter(x => x>-1);
</code>```

this will return an array with all the matching indexes.

```<code>[3, 5]
</code>```

Title: search in array for string match

Body:
What i have

var sentence = 'My country is India';
var array = ['Intel,' 'Goa', 'Green Day', 'India', 'Ice', 'India'];

Result i need

  index = array.indexOf(sentence); // it should return 3

And this is what i tried it works but its very slow and freezes and stop working when use big data

words = sentence.split(' ');
var i;
for (i = 0; i < words.length; i++) {
    w = words[i];
    a = array.indexOf(w);
    console.log(a);
}

Update : i tried below solutions but still stop working i am working on google audio to speech so its run continually some one speeak so sentence array triggers again and again i think this is why its freezing after some point

Update 2: In above example i search for single word i.e. "India" but what if i its more than one word like if its a person name like "Neil Armstrong" then split method will not work.

Body:
const sentence = 'My country is India';
const array = ['Intel', 'Goa', 'Green Day', 'India', 'Ice', 'India'];
const my_vals =  array.map((val, inx)=> sentence
                     .match(val)? inx : -1)
                     .filter(x => x>-1);

this will return an array with all the matching indexes.

[3, 5]


问:
Spring boot reading configuration yaml hashmap based
is it possible to read the yaml file in Spring boot using the @configurationproperties ?

```<code>app:
  X1:
    key1: value1
    key2: value2

  X2:
    key1: value3
    key2: value4
  X3:
    key1: value5
    key2: value6
  X4:
    key1: value7
    key2: value8
</code>```

I would like to read and put it as Hashmap

答:
One of the way is to use EnvironmentPostProcessor. You will have to put them in Hahsmap manually in the post-processor. Read the property value as "key:value", then use String split to set them in HashMap.</p>

```<code>public class CreatehashMapPostProcessor implements EnvironmentPostProcessor {

  private static final String PROPERTY_SOURCE_NAME = "app.properties";

  @Override
  public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {
    Map<String, Object> map = new HashMap<String, String>();
    String []val = env.getProperty("...");
   map.put(val[0], val[1]);
  }
</code>```

Body:
is it possible to read the yaml file in Spring boot using the @configurationproperties ?

app:
  X1:
    key1: value1
    key2: value2

  X2:
    key1: value3
    key2: value4
  X3:
    key1: value5
    key2: value6
  X4:
    key1: value7
    key2: value8

I would like to read and put it as Hashmap

Body:
One of the way is to use EnvironmentPostProcessor. You will have to put them in Hahsmap manually in the post-processor. Read the property value as "key:value", then use String split to set them in HashMap.

public class CreatehashMapPostProcessor implements EnvironmentPostProcessor {

  private static final String PROPERTY_SOURCE_NAME = "app.properties";

  @Override
  public void postProcessEnvironment(ConfigurableEnvironment env, SpringApplication application) {
    Map<String, Object> map = new HashMap<String, String>();
    String []val = env.getProperty("...");
   map.put(val[0], val[1]);
  }


问:
Glitchy collision resolution between mouse-controlled player and obstacle squares
I am trying to make a game with collision detection and resolution. For some reason, when I move the player to the right of the 'enemy blocks', the player moves to the left of the 'enemy'. How can I solve this problem? I have been working on this for hours and cannot find any solution. I am not sure if it is a small problem or if I have to change the whole enemy object.

//declare variables
var body = document.getElementById("body");
var canvas = document.getElementById("canvas");
var iwidth = window.innerWidth;
var iheight = window.innerHeight;
//variable for drawing
var draw = canvas.getContext("2d");
//variables for character paramaters
var playerwidth = 20;
var playerheight = 20;
var playerx = iwidth / 2 - playerwidth / 2;
var playery = iheight / 2 - playerheight / 2;
var playerspeed = 20;
//mouse co-ordinates
var mousex;
var mousey;
//enemy's parameters
var enemyxpositions = [43, 94, 200];
var enemyypositions = [41, 120, 83];
var enemywidths = [12, 43, 45];
var enemyheights = [43, 11, 87];
var i = 0;
var collision = false;
///////////////////////////////////////////////////////////////////////////////////
///////         separating variables and rest of the code                   ///////
///////////////////////////////////////////////////////////////////////////////////

//puts canvas in top right corner
body.style.margin = "0";

//changes the canvas's style namely color, margin, width and height
canvas.style.backgroundColor = "black";
canvas.style.margin = "0";
canvas.width = iwidth;
canvas.height = iheight;

//the function that the player is drawn in
function drawplayer() {

 //allows animation
 requestAnimationFrame(drawplayer);

 //clears the canvas every time the function runs so that the image doesn't leave a mark
 draw.clearRect(0, 0, iwidth, iheight);

 //drawing the player
 draw.fillStyle = "#ffff00";
 draw.fillRect(playerx, playery, playerwidth, playerheight);
 draw.fill();

 //checking where the mouse is and letting the player follow it
 if (mousex > playerx + playerwidth / 2) {
  playerx += (mousex - playerx + playerwidth) / playerspeed;
 }
 if (mousex < playerx + playerwidth / 2) {
  playerx -= (playerx - mousex + playerwidth) / playerspeed;
 }
 if (mousey > playery + playerheight / 2) {
  playery += (mousey - playery + playerheight) / playerspeed;
 }
 if (mousey < playery + playerheight / 2) {
  playery -= (playery - mousey + playerheight) / playerspeed;
 }

 //the obstacles' object
 function Enemy(enemyx, enemyy, enemywidth, enemyheight) {
  this.enemyx = enemyx;
  this.enemyy = enemyy;
  this.enemywidth = enemywidth;
  this.enemyheight = enemyheight;
  this.enemies = function() {
   draw.fillStyle = "#0000ff";
   draw.fillRect(enemyx, enemyy, enemywidth, enemyheight);
   draw.fill();
  }

  //collision detection
  if (mousex + playerwidth / 2 > this.enemyx &&
   mousex - playerwidth / 2 < this.enemyx + this.enemywidth &&
   mousey + playerheight / 2 > this.enemyy &&
   mousey - playerheight / 2 < this.enemyy + this.enemyheight) {
    collision = true;
  }
  else {
   collision = false;
  }

  //collision implementation
  //left collision
  if (collision == true && mousex + playerwidth / 2 > this.enemyx) {
   playerx = this.enemyx - playerwidth;
  }
  //right collision
  else if (collision == true && mousex - playerwidth / 2 < this.enemyx + this.enemywidth) {
   playerx = this.enemyx + this.enemywidth + 50;
  }

 }

  //draws all the obstacles
  for (i = 0; i < enemyxpositions.length; i++) {
   new Enemy( enemyxpositions[i],
      enemyypositions[i],
      enemywidths[i],
      enemyheights[i]).enemies();
  }

}
drawplayer();

//gets the mouse co-ordinates
window.onmousemove = function mousepos(event) {
 mousex = event.clientX;
 mousey = event.clientY;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>DUNGE</title>
 <style>
  ::-webkit-scrollbar {
   display: none;
  }
  canvas {
   display: block;
  }
  #obstacles {
   opacity: 1;
   margin-top: -100vh;
  }
 </style>
</head>
<body id="body">

 <canvas id="canvas"></canvas>
 <script src="script.js"></script>
</body>
</html></code>```

答:
Collision resolution is a pretty tricky domain and there are a many approaches you can take. For the purposes of squares with mouse control as in your case, a naive approach might be as follows:

If a collision is detected between a player and an immobile obstacle (enemy, wall, whatever), we can resolve the collision by gradually "undoing" the player's motion until it's no longer colliding with the obstacle.

For example, if on the current frame, the player is moving with a y velocity of 5 and an x velocity of 2 and we detect a collision, then we can avoid the collision by undoing the move. However, this would create an unrealistic air gap between the obstacle and the player that can result in a bouncing effect. Instead, we can slowly move the obstacle's x and y positions by a small value like -0.5 until no collision is detected. However, undoing the move on both axes might be incorrect if only one axis experienced a collision.

Here's an initial attempt at separating the x and y axes into distinct steps:

const canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 180;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const mouse = {x: 0, y: 0};
const enemy = {x: 130, y: 70, width: 40, height: 40};
const player = {
  x: 0, y: 0, width: 20, height: 20, vx: 0, vy: 0,
  velocityDamp: 0.06, collisionDamp: 0.3
};

const collides = (a, b) =>
  a.x + a.width >= b.x && a.x <= b.x + b.width &&
  a.y + a.height >= b.y && a.y <= b.y + b.height
;

(function render() {
  player.vx = (mouse.x - player.x) * player.velocityDamp;
  player.vy = (mouse.y - player.y) * player.velocityDamp;
  player.x += player.vx;
  player.y += player.vy;

  while (collides(player, enemy)) {
    player.y -= Math.sign(player.vy) * player.collisionDamp;
  }

  while (collides(player, enemy)) {
    player.x -= Math.sign(player.vx) * player.collisionDamp;
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "blue";
  ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  ctx.fillStyle = "yellow";
  ctx.fillRect(player.x, player.y, player.width, player.height);
  requestAnimationFrame(render);
})();

onmousemove = e => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {margin: 0;}
canvas {background: #000;}</code>```

This works fine when the collision is on the y-axis, but collisions on the x-axis cause the player to "pop" out of the obstacle. Ordering the adjustments so that the least offending velocity adjustment is handled first should fix the problem. We do this by "undoing" the last move on one axis, checking if this single-axis move resolved the collision, and adjusting accordingly.

Putting it all together, here's a proof-of-concept:

const canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 180;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const mouse = {x: 0, y: 0};
const enemy = {x: 130, y: 70, width: 40, height: 40};
const player = {
  x: 0, y: 0, width: 20, height: 20, vx: 0, vy: 0,
  velocityDamp: 0.06, collisionDamp: 0.3
};

const collides = (a, b) =>
  a.x + a.width >= b.x && a.x <= b.x + b.width &&
  a.y + a.height >= b.y && a.y <= b.y + b.height
;

const resolveOnAxis = (player, enemy, axis) => {
  while (collides(player, enemy)) {
    player[axis] -= Math.sign(player["v"+axis]) * player.collisionDamp;
  }
};

const resolveCollision = (player, enemy) => {
  player.x -= player.vx;

  if (collides(player, enemy)) {
    player.x += player.vx;
    resolveOnAxis(player, enemy, "y");
    resolveOnAxis(player, enemy, "x");
  }
  else {
    player.x += player.vx;
    resolveOnAxis(player, enemy, "x");
    resolveOnAxis(player, enemy, "y");
  }
};

(function render() {
  player.vx = (mouse.x - player.x) * player.velocityDamp;
  player.vy = (mouse.y - player.y) * player.velocityDamp;
  player.x += player.vx;
  player.y += player.vy;

  if (collides(player, enemy)) {
    resolveCollision(player, enemy);
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "blue";
  ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  ctx.fillStyle = "yellow";
  ctx.fillRect(player.x, player.y, player.width, player.height);
  requestAnimationFrame(render);
})();

onmousemove = e => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {margin: 0;}
canvas {background: #000;}</code>```

This isn't perfect collision resolution by any means, but it introduces a few fundamental concepts and should be sufficient for simple games.

Note that I'm only handling one enemy; it's left to the reader to create an array of enemies and loop over them to detect and resolve collisions. Problems can arise if multiple enemies are close together; resolving one collision could push the player into another collision. It gets worse if the obstacles are also moving. If you're making a platformer, a collision grid might be worth looking into to circumvent some of these issues.

If dealing with collision becomes increasingly complicated and overwhelming, there's no shame in using a library like matter.js.

Be careful when using while to resolve these collisions as an infinite loop can easily occur. Consider adding a tries counter to these loops and bail if they exceed more than 20 or 30 iterations (this is a bit unsatisfactory and reveals that this solution is not industrial-strength; this prevents infinite loops but may result in incorrect behavior).

Capping the player's maximum velocity is another important preventative measure: it can avoid situations where the velocity becomes so high the player clips right through obstacles. Explore other ad-hoc solutions to problems as they arise.

Beyond collision detection, I have a few other suggestions:

Use objects to encapsulate all properties associated with a game entity. This makes the code much easier to manage than loose variables like playerwidth, playerheight, playerspeed, etc.

Avoid pointless and noisy comments that reiterate what the code clearly does.

Instead of adding comments to delimit logical parts of a function, create helper functions with the appropriate names. My POC above is not great in this regard--as the game expands, objects, functions and overall design become increasingly important; inlining everything in the update loop makes for a painful coding experience as soon as you want to add features or run into bugs.

Put Enemy's constructor function outside of the game loop. Create enemies one time in an initialization function and scope constructors appropriately.

Use camelCased variables instead of everythinginlowercase.

Body:
I am trying to make a game with collision detection and resolution. For some reason, when I move the player to the right of the 'enemy blocks', the player moves to the left of the 'enemy'. How can I solve this problem? I have been working on this for hours and cannot find any solution. I am not sure if it is a small problem or if I have to change the whole enemy object.

//declare variables
var body = document.getElementById("body");
var canvas = document.getElementById("canvas");
var iwidth = window.innerWidth;
var iheight = window.innerHeight;
//variable for drawing
var draw = canvas.getContext("2d");
//variables for character paramaters
var playerwidth = 20;
var playerheight = 20;
var playerx = iwidth / 2 - playerwidth / 2;
var playery = iheight / 2 - playerheight / 2;
var playerspeed = 20;
//mouse co-ordinates
var mousex;
var mousey;
//enemy's parameters
var enemyxpositions = [43, 94, 200];
var enemyypositions = [41, 120, 83];
var enemywidths = [12, 43, 45];
var enemyheights = [43, 11, 87];
var i = 0;
var collision = false;
///////////////////////////////////////////////////////////////////////////////////
///////         separating variables and rest of the code                   ///////
///////////////////////////////////////////////////////////////////////////////////

//puts canvas in top right corner
body.style.margin = "0";

//changes the canvas's style namely color, margin, width and height
canvas.style.backgroundColor = "black";
canvas.style.margin = "0";
canvas.width = iwidth;
canvas.height = iheight;

//the function that the player is drawn in
function drawplayer() {

 //allows animation
 requestAnimationFrame(drawplayer);

 //clears the canvas every time the function runs so that the image doesn't leave a mark
 draw.clearRect(0, 0, iwidth, iheight);

 //drawing the player
 draw.fillStyle = "#ffff00";
 draw.fillRect(playerx, playery, playerwidth, playerheight);
 draw.fill();

 //checking where the mouse is and letting the player follow it
 if (mousex > playerx + playerwidth / 2) {
  playerx += (mousex - playerx + playerwidth) / playerspeed;
 }
 if (mousex < playerx + playerwidth / 2) {
  playerx -= (playerx - mousex + playerwidth) / playerspeed;
 }
 if (mousey > playery + playerheight / 2) {
  playery += (mousey - playery + playerheight) / playerspeed;
 }
 if (mousey < playery + playerheight / 2) {
  playery -= (playery - mousey + playerheight) / playerspeed;
 }

 //the obstacles' object
 function Enemy(enemyx, enemyy, enemywidth, enemyheight) {
  this.enemyx = enemyx;
  this.enemyy = enemyy;
  this.enemywidth = enemywidth;
  this.enemyheight = enemyheight;
  this.enemies = function() {
   draw.fillStyle = "#0000ff";
   draw.fillRect(enemyx, enemyy, enemywidth, enemyheight);
   draw.fill();
  }

  //collision detection
  if (mousex + playerwidth / 2 > this.enemyx &&
   mousex - playerwidth / 2 < this.enemyx + this.enemywidth &&
   mousey + playerheight / 2 > this.enemyy &&
   mousey - playerheight / 2 < this.enemyy + this.enemyheight) {
    collision = true;
  }
  else {
   collision = false;
  }

  //collision implementation
  //left collision
  if (collision == true && mousex + playerwidth / 2 > this.enemyx) {
   playerx = this.enemyx - playerwidth;
  }
  //right collision
  else if (collision == true && mousex - playerwidth / 2 < this.enemyx + this.enemywidth) {
   playerx = this.enemyx + this.enemywidth + 50;
  }

 }

  //draws all the obstacles
  for (i = 0; i < enemyxpositions.length; i++) {
   new Enemy( enemyxpositions[i],
      enemyypositions[i],
      enemywidths[i],
      enemyheights[i]).enemies();
  }

}
drawplayer();

//gets the mouse co-ordinates
window.onmousemove = function mousepos(event) {
 mousex = event.clientX;
 mousey = event.clientY;
}

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>DUNGE</title>

 <canvas id="canvas"></canvas>

Body:
Collision resolution is a pretty tricky domain and there are a many approaches you can take. For the purposes of squares with mouse control as in your case, a naive approach might be as follows:

If a collision is detected between a player and an immobile obstacle (enemy, wall, whatever), we can resolve the collision by gradually "undoing" the player's motion until it's no longer colliding with the obstacle.

For example, if on the current frame, the player is moving with a y velocity of 5 and an x velocity of 2 and we detect a collision, then we can avoid the collision by undoing the move. However, this would create an unrealistic air gap between the obstacle and the player that can result in a bouncing effect. Instead, we can slowly move the obstacle's x and y positions by a small value like -0.5 until no collision is detected. However, undoing the move on both axes might be incorrect if only one axis experienced a collision.

Here's an initial attempt at separating the x and y axes into distinct steps:

const canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 180;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const mouse = {x: 0, y: 0};
const enemy = {x: 130, y: 70, width: 40, height: 40};
const player = {
  x: 0, y: 0, width: 20, height: 20, vx: 0, vy: 0,
  velocityDamp: 0.06, collisionDamp: 0.3
};

const collides = (a, b) =>
  a.x + a.width >= b.x && a.x <= b.x + b.width &&
  a.y + a.height >= b.y && a.y <= b.y + b.height
;

(function render() {
  player.vx = (mouse.x - player.x) * player.velocityDamp;
  player.vy = (mouse.y - player.y) * player.velocityDamp;
  player.x += player.vx;
  player.y += player.vy;

  while (collides(player, enemy)) {
    player.y -= Math.sign(player.vy) * player.collisionDamp;
  }

  while (collides(player, enemy)) {
    player.x -= Math.sign(player.vx) * player.collisionDamp;
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "blue";
  ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  ctx.fillStyle = "yellow";
  ctx.fillRect(player.x, player.y, player.width, player.height);
  requestAnimationFrame(render);
})();

onmousemove = e => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
};

body {margin: 0;}
canvas {background: #000;}

This works fine when the collision is on the y-axis, but collisions on the x-axis cause the player to "pop" out of the obstacle. Ordering the adjustments so that the least offending velocity adjustment is handled first should fix the problem. We do this by "undoing" the last move on one axis, checking if this single-axis move resolved the collision, and adjusting accordingly.

Putting it all together, here's a proof-of-concept:

const canvas = document.createElement("canvas");
canvas.width = 300;
canvas.height = 180;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
const mouse = {x: 0, y: 0};
const enemy = {x: 130, y: 70, width: 40, height: 40};
const player = {
  x: 0, y: 0, width: 20, height: 20, vx: 0, vy: 0,
  velocityDamp: 0.06, collisionDamp: 0.3
};

const collides = (a, b) =>
  a.x + a.width >= b.x && a.x <= b.x + b.width &&
  a.y + a.height >= b.y && a.y <= b.y + b.height
;

const resolveOnAxis = (player, enemy, axis) => {
  while (collides(player, enemy)) {
    player[axis] -= Math.sign(player["v"+axis]) * player.collisionDamp;
  }
};

const resolveCollision = (player, enemy) => {
  player.x -= player.vx;

  if (collides(player, enemy)) {
    player.x += player.vx;
    resolveOnAxis(player, enemy, "y");
    resolveOnAxis(player, enemy, "x");
  }
  else {
    player.x += player.vx;
    resolveOnAxis(player, enemy, "x");
    resolveOnAxis(player, enemy, "y");
  }
};

(function render() {
  player.vx = (mouse.x - player.x) * player.velocityDamp;
  player.vy = (mouse.y - player.y) * player.velocityDamp;
  player.x += player.vx;
  player.y += player.vy;

  if (collides(player, enemy)) {
    resolveCollision(player, enemy);
  }

  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "blue";
  ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  ctx.fillStyle = "yellow";
  ctx.fillRect(player.x, player.y, player.width, player.height);
  requestAnimationFrame(render);
})();

onmousemove = e => {
  mouse.x = e.clientX;
  mouse.y = e.clientY;
};

body {margin: 0;}
canvas {background: #000;}

This isn't perfect collision resolution by any means, but it introduces a few fundamental concepts and should be sufficient for simple games.

Note that I'm only handling one enemy; it's left to the reader to create an array of enemies and loop over them to detect and resolve collisions. Problems can arise if multiple enemies are close together; resolving one collision could push the player into another collision. It gets worse if the obstacles are also moving. If you're making a platformer, a collision grid might be worth looking into to circumvent some of these issues.

If dealing with collision becomes increasingly complicated and overwhelming, there's no shame in using a library like matter.js.

Be careful when using while to resolve these collisions as an infinite loop can easily occur. Consider adding a tries counter to these loops and bail if they exceed more than 20 or 30 iterations (this is a bit unsatisfactory and reveals that this solution is not industrial-strength; this prevents infinite loops but may result in incorrect behavior).

Capping the player's maximum velocity is another important preventative measure: it can avoid situations where the velocity becomes so high the player clips right through obstacles. Explore other ad-hoc solutions to problems as they arise.

Beyond collision detection, I have a few other suggestions:

Use objects to encapsulate all properties associated with a game entity. This makes the code much easier to manage than loose variables like playerwidth, playerheight, playerspeed, etc.

Avoid pointless and noisy comments that reiterate what the code clearly does.

Instead of adding comments to delimit logical parts of a function, create helper functions with the appropriate names. My POC above is not great in this regard--as the game expands, objects, functions and overall design become increasingly important; inlining everything in the update loop makes for a painful coding experience as soon as you want to add features or run into bugs.

Put Enemy's constructor function outside of the game loop. Create enemies one time in an initialization function and scope constructors appropriately.

Use camelCased variables instead of everythinginlowercase.


问:
PHP7 Undefined class constant triggering php7:notice
I have been renaming some constants in our code and when releasing to production I get regulary in the apache log the following message :

```<code>[Sun Feb 16 19:56:29.437393 2020] [php7:notice] [pid 15948] [client 10.0.1.10:24984] Undefined class constant 'SUBMIT_STA_', referer: https://xxxx.yyyy.com/runtest/QuestionDisplayer
</code>```

Nothing after, nothing before. There are many things I don't understand :

How can an undefined class constant trigger a notice rather than a fatal error ?

Why don't I get any more information about where in the code the error appears (like script and line number) as for other errors?
Obviously, when I look into my code I don't find any instance of SUBMIT_STA_, I find some SUBMIT_STA_XX or SUBMIT_STA_YY but no SUBMIT_STA with nothing after.

答:
If a constant doesn't exist, it will treat the constant name as a string,

Usually, what happens is that you write a string and forget the quotes, so for PHP that is a constant, not a string, but since there is no constant with that name, it converts it to a string and caries on the execution of the code.

so you want to look through your code and find the string SUBMIT_STA_ where it is missing the quotes (or the $ sign if it is supposed to be a variable)

Body:
I have been renaming some constants in our code and when releasing to production I get regulary in the apache log the following message :

[Sun Feb 16 19:56:29.437393 2020] [php7:notice] [pid 15948] [client 10.0.1.10:24984] Undefined class constant 'SUBMIT_STA_', referer: https://xxxx.yyyy.com/runtest/QuestionDisplayer

Nothing after, nothing before. There are many things I don't understand :

How can an undefined class constant trigger a notice rather than a fatal error ?

Why don't I get any more information about where in the code the error appears (like script and line number) as for other errors?
Obviously, when I look into my code I don't find any instance of SUBMIT_STA_, I find some SUBMIT_STA_XX or SUBMIT_STA_YY but no SUBMIT_STA with nothing after.


问:
asp.net core mvc displays empty page
Please, I need help with a nagging issue with an asp.net core mvc app.

The app only shows blank home page - no contents at all including html markups. No controller is invoked even by typing url directly on the browser and no error is displayed.

I've created new app all over again a couple of times with the same result. Also, I've added statements below to the Configure method in the Startup class to no avail.

```<code>app.UseDefaultFiles();
app.UseStaticFiles();
app.UseIdentity();
</code>```

Any guide to resolve this mystery would be highly appreciated.

Thanks.

```<code> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //add NLog to ASP.NET Core
        //loggerFactory.AddNLog();

        ////add NLog.Web
        //app.AddNLogWeb();

        //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
        //env.ConfigureNLog("nlog.config");

        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        } else {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
        app.UseMvcWithDefaultRoute();
        //app.UseMvc(routes => {
        //    routes.MapRoute(
        //        name: "default",
        //        template: "{controller=Home}/{action=Index}/{id?}");
        //});

        // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
        try {
            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                .CreateScope()) {
                serviceScope.ServiceProvider.GetService<ChurBaseContext>()
                     .Database.Migrate();

                var userManager = serviceScope.ServiceProvider.GetService<UserManager<ChurchMember>>();
                var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();

                serviceScope.ServiceProvider.GetService<ChurBaseContext>().EnsureSeedData(userManager, roleManager);
            }
        } catch { }
    }
</code>```

答:
When you see just a blank page and have no response other that the blank page, it can be caused by many things. These are two that I have seen:

A corrupt web.config

A web.config that is clashing with IIS.  This could happen when a particular section is locked in your IIS configuration.

Title: asp.net core mvc displays empty page

Body:
Please, I need help with a nagging issue with an asp.net core mvc app.

The app only shows blank home page - no contents at all including html markups. No controller is invoked even by typing url directly on the browser and no error is displayed.

I've created new app all over again a couple of times with the same result. Also, I've added statements below to the Configure method in the Startup class to no avail.

app.UseDefaultFiles();
app.UseStaticFiles();
app.UseIdentity();

Any guide to resolve this mystery would be highly appreciated.

Thanks.

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        //add NLog to ASP.NET Core
        //loggerFactory.AddNLog();

        ////add NLog.Web
        //app.AddNLogWeb();

        //needed for non-NETSTANDARD platforms: configure nlog.config in your project root
        //env.ConfigureNLog("nlog.config");

        if (env.IsDevelopment()) {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        } else {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseIdentity();

        // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
        app.UseMvcWithDefaultRoute();
        //app.UseMvc(routes => {
        //    routes.MapRoute(
        //        name: "default",
        //        template: "{controller=Home}/{action=Index}/{id?}");
        //});

        // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
        try {
            using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                .CreateScope()) {
                serviceScope.ServiceProvider.GetService<ChurBaseContext>()
                     .Database.Migrate();

                var userManager = serviceScope.ServiceProvider.GetService<UserManager<ChurchMember>>();
                var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();

                serviceScope.ServiceProvider.GetService<ChurBaseContext>().EnsureSeedData(userManager, roleManager);
            }
        } catch { }
    }


问:
vb.net 2012 Error 1 Resource file "My Project\Resources.resx" cannot be found.
In a vb.net 2012 vb.net desktop application that I am opening for the first time, I am getting the following error and warning message:
Error   1   Resource file "My Project\Resources.resx" cannot be found.

Warning 2   A custom tool 'VbMyResourcesResXFileCodeGenerator' is associated with file 'My Project\Resources.resx', but the output of the custom tool was not found in the project.  You may try re-running the custom tool by right-clicking on the file in the Solution Explorer and choosing Run Custom Tool.

I tried to run the custom tool that was suggested in the warning message and that did not help.
Thus can you tell me what I can do to get the Resources.resx file that is missing?

答:
I have fixed this issue by copying "My Project" folder from different project and pasting it into project where I had this error.

You also need to change root namespaces from files inside so it matches your solution's root namespace where error occurs.


问:
Spring: How to add XSS protection to @RequestBody in a RESTful service?
I am trying to add custom XSS protection by creating a RequestWrapper extending HttpServletRequestWrapper in an XSS filter. The below code provides XSS protection to:
1. Request Params
2. Payload.

```<code>public class XssRequestWrapper extends HttpServletRequestWrapper {

  XssRequestWrapper(HttpServletRequest request) {
    super(request);
  }

    @Override
    public String getQueryString() {
    /*
    Custom XSS logic
    */
    }

    @Override
    public String getParameterMap() {
    /*
    Custom XSS logic
    */
    }

    @Override
    public String getParameterValues() {
    /*
    Custom XSS logic
    */
    }

}
</code>```

But when I configure my REST Api with @RequestBody Annotation in my controller, the overridden getParameterValues is not invoked. Instead, getInputStream is invoked, which results in the addition of the following:

```<code> @Override
  public ServletInputStream getInputStream() throws IOException {
    /*
    Custom XSS logic
    */
  }
</code>```

Is there any better/ideal way to provide XSS protection to data passed via @RequestBody annotation?

Edit:
Solution: https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times
Since I was using ContentCachingRequestWrapper in one of my previous filters, I was unable to use the same and hence went forward with the above solution.
By Caching the request, I was able to read it multiple times and perform XSS check over the cached content.

答:
I am a bit confused of what you are trying to achieve with the code.

First thing first - there are three types of Cross-site Scripting (XSS) vulnerabilities:

DOM based - runs in the browser often due a flaw in JavaScript. No server calls are needed for the vulnerability to be exploited.

Reflected XSS - the payload gets reflected in the HTML body by the web server.

Persistent XSS - the payload lands in the DB and is embedded in the HTML body by the web server.

So there are no ways you can address the DOM based XSS with a request wrapper because there is no need for a request to be made.

You might try to address the points 2 and 3, but handling with the request values is a uncommon thing to be done. XSS vulnerabilities are context sensitive, and if you try to encode or escape without knowing the context in which the value is to be used later - you might and will fail.

Please look over the XSS prevention cheat sheet from OWASP to learn how to prevent XSS flaws in the code.

Body:
I am trying to add custom XSS protection by creating a RequestWrapper extending HttpServletRequestWrapper in an XSS filter. The below code provides XSS protection to:
1. Request Params
2. Payload.

public class XssRequestWrapper extends HttpServletRequestWrapper {

  XssRequestWrapper(HttpServletRequest request) {
    super(request);
  }

    @Override
    public String getQueryString() {
    /*
    Custom XSS logic
    */
    }

    @Override
    public String getParameterMap() {
    /*
    Custom XSS logic
    */
    }

    @Override
    public String getParameterValues() {
    /*
    Custom XSS logic
    */
    }

}

But when I configure my REST Api with @RequestBody Annotation in my controller, the overridden getParameterValues is not invoked. Instead, getInputStream is invoked, which results in the addition of the following:

 @Override
  public ServletInputStream getInputStream() throws IOException {
    /*
    Custom XSS logic
    */
  }

Is there any better/ideal way to provide XSS protection to data passed via @RequestBody annotation?

Edit:
Solution: https://www.baeldung.com/spring-reading-httpservletrequest-multiple-times
Since I was using ContentCachingRequestWrapper in one of my previous filters, I was unable to use the same and hence went forward with the above solution.
By Caching the request, I was able to read it multiple times and perform XSS check over the cached content.


问:
I'm getting a warning message in R I don't understand
** When I train my SVM models I get this warning message:

Warning message: In .local(x, ...): Variable(s) `' constant. Cannot scale data.

Could someone shine some light on this warning? Is this something I should be concerned with? I was thinking the warning maybe because of my dummy variable coding I did. If so, does anyone know a way around this warning message? Thanks for y'all's time!    **

```<code># importing libraries
library(tidyverse)
library(caret)

# importing the data and changing data types ----
loan <- read_csv("loan_data.csv", col_types = cols(
    credit.policy    = col_factor(),
    inq.last.6mths = col_factor(),
    delinq.2yrs    = col_factor(),
    pub.rec        = col_factor(),
    not.fully.paid = col_factor(),
    purpose        = col_factor()
))

# dummy coding purpose column for SVM models
loan_dum <- loan %>%
    fastDummies::dummy_cols(select_columns = "purpose",
                            remove_first_dummy  = TRUE,
                            remove_selected_columns = TRUE)
loan_dum %>% View()

# Checking classes of new dummy variables
loan_dum %>% glimpse()

# Changing the data type of new dummy variables from int to factors
loan_dum <- loan_dum %>%
    mutate(
        purpose_credit_card      = as.factor(purpose_credit_card),
        purpose_all_other        = as.factor(purpose_all_other),
        purpose_home_improvement = as.factor(purpose_home_improvement),
        purpose_small_business   = as.factor(purpose_small_business),
        purpose_major_purchase   = as.factor(purpose_major_purchase),
        purpose_educational      = as.factor(purpose_educational)
    )
loan_dum %>% glimpse()

# standardizing continuous values
loan_dum_stand <- loan_dum %>%
    mutate(
        int.rate          = as.vector(scale(int.rate,center = TRUE,scale = TRUE)),
        installment       = as.vector(scale(installment,center = TRUE,scale = TRUE)),
        log.annual.inc    = as.vector(scale(log.annual.inc,center = TRUE,scale = TRUE)),
        dti               = as.vector(scale(dti,center = TRUE,scale = TRUE)),
        fico              = as.vector(scale(fico,center = TRUE,scale = TRUE)),
        days.with.cr.line = as.vector(scale(days.with.cr.line,center = TRUE,scale = TRUE)),
        revol.bal         = as.vector(scale(revol.bal,center = TRUE,scale = TRUE)),
        revol.util        = as.vector(scale(revol.util,center = TRUE,scale = TRUE))
    )
loan_dum_stand %>% view()

# splitting the data into train test ----
set.seed(123)
trainIndexDum <- createDataPartition(loan_dum_stand$not.fully.paid,p = 0.70,list = FALSE,times = 1)
loan_dum_train <- loan_dum_stand[trainIndexDum,]
loan_dum_test  <- loan_dum_stand[-trainIndexDum,]

loan_dum_train %>% glimpse()

#  SVM model with default settings ----
####################################################################################
# Runing model building in parallel
cl <- makePSOCKcluster(10)
registerDoParallel(cl)

# fitting svm model with radial kernel no tuning
set.seed(123)
svm_model_radial <- train(
    form = not.fully.paid ~.,
    data = loan_dum_train,
    method = "svmRadial"
)
svm_model_radial
plot(svm_model_radial)
</code>```

答: This error is generally due the fact that you might have a column in your training data which has constant data (same value in each row) and therefore, If the variable is constant, it cannot be scaled to unit variance (and zero mean).</p>

Body:
** When I train my SVM models I get this warning message:

Warning message: In .local(x, ...): Variable(s) `' constant. Cannot scale data.

Could someone shine some light on this warning? Is this something I should be concerned with? I was thinking the warning maybe because of my dummy variable coding I did. If so, does anyone know a way around this warning message? Thanks for y'all's time!    **

# importing libraries
library(tidyverse)
library(caret)

# importing the data and changing data types ----
loan <- read_csv("loan_data.csv", col_types = cols(
    credit.policy    = col_factor(),
    inq.last.6mths = col_factor(),
    delinq.2yrs    = col_factor(),
    pub.rec        = col_factor(),
    not.fully.paid = col_factor(),
    purpose        = col_factor()
))

# dummy coding purpose column for SVM models
loan_dum <- loan %>%
    fastDummies::dummy_cols(select_columns = "purpose",
                            remove_first_dummy  = TRUE,
                            remove_selected_columns = TRUE)
loan_dum %>% View()

# Checking classes of new dummy variables
loan_dum %>% glimpse()

# Changing the data type of new dummy variables from int to factors
loan_dum <- loan_dum %>%
    mutate(
        purpose_credit_card      = as.factor(purpose_credit_card),
        purpose_all_other        = as.factor(purpose_all_other),
        purpose_home_improvement = as.factor(purpose_home_improvement),
        purpose_small_business   = as.factor(purpose_small_business),
        purpose_major_purchase   = as.factor(purpose_major_purchase),
        purpose_educational      = as.factor(purpose_educational)
    )
loan_dum %>% glimpse()

# standardizing continuous values
loan_dum_stand <- loan_dum %>%
    mutate(
        int.rate          = as.vector(scale(int.rate,center = TRUE,scale = TRUE)),
        installment       = as.vector(scale(installment,center = TRUE,scale = TRUE)),
        log.annual.inc    = as.vector(scale(log.annual.inc,center = TRUE,scale = TRUE)),
        dti               = as.vector(scale(dti,center = TRUE,scale = TRUE)),
        fico              = as.vector(scale(fico,center = TRUE,scale = TRUE)),
        days.with.cr.line = as.vector(scale(days.with.cr.line,center = TRUE,scale = TRUE)),
        revol.bal         = as.vector(scale(revol.bal,center = TRUE,scale = TRUE)),
        revol.util        = as.vector(scale(revol.util,center = TRUE,scale = TRUE))
    )
loan_dum_stand %>% view()

# splitting the data into train test ----
set.seed(123)
trainIndexDum <- createDataPartition(loan_dum_stand$not.fully.paid,p = 0.70,list = FALSE,times = 1)
loan_dum_train <- loan_dum_stand[trainIndexDum,]
loan_dum_test  <- loan_dum_stand[-trainIndexDum,]

loan_dum_train %>% glimpse()

#  SVM model with default settings ----
####################################################################################
# Runing model building in parallel
cl <- makePSOCKcluster(10)
registerDoParallel(cl)

# fitting svm model with radial kernel no tuning
set.seed(123)
svm_model_radial <- train(
    form = not.fully.paid ~.,
    data = loan_dum_train,
    method = "svmRadial"
)
svm_model_radial
plot(svm_model_radial)


问:
Save a picture in wrong folder using opencv
Directory I would need to save to:

```<code>DataBase-Faces\name
</code>```

Directory where the code is saving:

```<code>DataBase-Faces
</code>```

My code:

```<code>cv2.imwrite("DataBase-Faces\\"+name+str(frames)+".png",Faceimage)
</code>```

My program creates a folder with the typed name, I have to record these images in that folder, and the name of each image will be called Nome Typed + (frame number) .png

答:
It looks like you're forgetting to put a directory separator between name and str(frames).

Try

```<code>image_path = '\\'.join(['DataBase-Faces', name, str(frames) + '.png'])
cv2.imwrite(image_path, Faceimage)
</code>```

As a side note, you should not be concatenating paths by hand. Consider looking into the os.path module, which can save you from this sort of headache in the future.

Body:
Directory I would need to save to:

DataBase-Faces\name

Directory where the code is saving:

DataBase-Faces

My code:

cv2.imwrite("DataBase-Faces\\"+name+str(frames)+".png",Faceimage)

My program creates a folder with the typed name, I have to record these images in that folder, and the name of each image will be called Nome Typed + (frame number) .png

Body:
It looks like you're forgetting to put a directory separator between name and str(frames).

Try

image_path = '\\'.join(['DataBase-Faces', name, str(frames) + '.png'])
cv2.imwrite(image_path, Faceimage)

As a side note, you should not be concatenating paths by hand. Consider looking into the os.path module, which can save you from this sort of headache in the future.


问:
html ascii code "not well formed" error
I'm working on a webpage in spanish an english, so I have to use special characters like á, é, etc.

For this i took this info of codes: http://www.ascii.cl/htmlcodes.htm

and I wrote a:

```<code><h3>Energ&#237a;</h3>
</code>```

but on the error console it says this: not well-formed I had it with no ; but then I put it, but the error is still there, any ideas?

Thanks!

答:
You need to flip the semicolon and the "a":</p>

```<code><h3>Energía</h3>
</code>```

Title: html ascii code "not well formed" error

Body:
I'm working on a webpage in spanish an english, so I have to use special characters like á, é, etc.

For this i took this info of codes: http://www.ascii.cl/htmlcodes.htm

and I wrote a:

Energ&#237a;

but on the error console it says this: not well-formed I had it with no ; but then I put it, but the error is still there, any ideas?

Thanks!

Body:
You need to flip the semicolon and the "a":

<h3>Energ&#237;a</h3>


问:
How to split a string into fixed length rows?
I have a code that asks user to give lines with different amount of words in them, the next line is always given on another row.
I want to split the given text into user inputted lenght in different rows.

Right now I have a piece of code that splits the lines to wanted user inputted length, but since it counts the space (" ") as one "word",some lines start with space. How do i stop that from happening?

```<code>def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

def main():

    print("Enter text rows. Quit by entering an empty row.")
    msg = read_message()
    lines = (i.strip() for i in msg.splitlines())
    get_line = int(input("Enter the number of characters per line: "))
    for line in lines:
        for chunk in chunkstring(line, get_line):
            print(chunk)
``
</code>```

答:
The best option is to use regular expressions. Also, you don't need to do a splitlines before:

import re

print("Enter text rows. Quit by entering an empty row.")
msg = read_message()
width = int(input("Enter the number of characters per line: "))

pat = re.compile(f" *.{{1,{width}}}")

chunks = pat.findall(msg)
for chunk in chunks:
    print(chunk)
```

Body:
I have a code that asks user to give lines with different amount of words in them, the next line is always given on another row.
I want to split the given text into user inputted lenght in different rows.

Right now I have a piece of code that splits the lines to wanted user inputted length, but since it counts the space (" ") as one "word",some lines start with space. How do i stop that from happening?

def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

def main():

    print("Enter text rows. Quit by entering an empty row.")
    msg = read_message()
    lines = (i.strip() for i in msg.splitlines())
    get_line = int(input("Enter the number of characters per line: "))
    for line in lines:
        for chunk in chunkstring(line, get_line):
            print(chunk)
``


问:
Gitignore config - how to make git aware
I configured git with:

```<code>git config --global core.excludesFile ~/.gitignore
</code>```

I added new rules:

*.png
*.h5
*.mat

each one on a different line (consecutive lines)
then saved.

Then went to my git folder (with my source code, other files etc.). I do git add *, but git still wants to add h5 files!!. Do I have to do something else? How to make git aware of the new ignore rules before git add?

I have read that creating a .gitignore file and running the aforementioned command was enough to force git to be aware of the ignored files in a global way?

答:
You can remove the git cache and then add all files again

```<code>git rm -r --cached .
</code>```

Add all files again

```<code>git add .
</code>```

And then commit changes

```<code>git commit -m ".gitignore is now working"
</code>```

Note: be aware to commit all your changes before, otherwise you will lose control on all the changed files

See here for more info

Body:
I configured git with:

git config --global core.excludesFile ~/.gitignore

I added new rules:

*.png
*.h5
*.mat

each one on a different line (consecutive lines)
then saved.

Then went to my git folder (with my source code, other files etc.). I do git add *, but git still wants to add h5 files!!. Do I have to do something else? How to make git aware of the new ignore rules before git add?

I have read that creating a .gitignore file and running the aforementioned command was enough to force git to be aware of the ignored files in a global way?

Body:
You can remove the git cache and then add all files again

git rm -r --cached .

Add all files again

git add .

And then commit changes

git commit -m ".gitignore is now working"

Note: be aware to commit all your changes before, otherwise you will lose control on all the changed files

See here for more info