问:
onDestroy() onTaskRemoved both not working on Redmi MI device
I'm here developed a hybrid cordova based android app in which i need to do some task before killing app for this i wrote below code onDestroy() in MainActivity and onTaskRemoved in one of service class which is calling perfectly on Samsum, Motorola, Asus etc. many device except Redmi MI Devices.

Some days back the same code was working in MI device but now its not after updating MI with MIUI 9.6.0 and above. I have tested one of MI device with MI 9.5.0 in which its working both the method but after upgrade of my device now its not working.

So is someone having the same issue? what we can do to achieve app killing event? is there any option through which it should start working or having any other way to do the same only for MI device?

I have checked over the internet and did changes for Autostart options as well still not working.

```<code>@Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d(getClass().getName(), "App just got removed from Recents!");
        Toast.makeText(getApplicationContext(),"18. onTaskRemoved()", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"16. onDestroy()", Toast.LENGTH_SHORT).show();
    }
</code>```

答:
Few OEMs including (RedMi) customizes the stack ROM for battery/memory optimization and have blocked the "onDestroy()" and "onTaskRemoved" callbacks.
As an user you can prevent the App's service from killing by locking the App.
Or, White listing the app by enabling "Autostart" setting for the App. Programmatically you can prompt the user to enable the Autostart for the App: Please find details here

Please note: I have tested the Autostart enabling programatically on few devices but found that it does not works always. So not sure how to fix in a proper way, but this solution might worked at-least up-to certain extent.

Body:
I'm here developed a hybrid cordova based android app in which i need to do some task before killing app for this i wrote below code onDestroy() in MainActivity and onTaskRemoved in one of service class which is calling perfectly on Samsum, Motorola, Asus etc. many device except Redmi MI Devices.

Some days back the same code was working in MI device but now its not after updating MI with MIUI 9.6.0 and above. I have tested one of MI device with MI 9.5.0 in which its working both the method but after upgrade of my device now its not working.

So is someone having the same issue? what we can do to achieve app killing event? is there any option through which it should start working or having any other way to do the same only for MI device?

I have checked over the internet and did changes for Autostart options as well still not working.

@Override
    public void onTaskRemoved(Intent rootIntent) {
        Log.d(getClass().getName(), "App just got removed from Recents!");
        Toast.makeText(getApplicationContext(),"18. onTaskRemoved()", Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(getApplicationContext(),"16. onDestroy()", Toast.LENGTH_SHORT).show();
    }


来源: stackexchange

问:
how to fix "Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)"
I have a matrix of weather stations and average rainfall that I want to run a clustering algorithm on - but I am getting an error - any help very welcome please.

```<code>     station        avg
[1,] "aberporth"    "12.6366666666667"
[2,] "armagh"       "12.8739130434783"
[3,] "ballypatrick" "12.3982857142857"
[4,] "bradford"     "12.3962441314554"
[5,] "braemar"      "12.025641025641"
[6,] "camborne"     "12.2855855855856"
</code>```

when I run this code:

```<code> k2<-kmeans(na.omit(C),centers = 2,nstart=25)
</code>```

I get this error message:

```<code>Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)
</code>```

答:
There are multiple errors:

The column "avg" is a string, but it has to be a numeric variable.

Kmeans calculates the euclidiean distance, which can only be done with numeric variables. You can not include the "Station" variable in your analysis.

Use a data.frame instead of a matrix, because the matrix can only handle one data type (character) in your example.

This is the way your would perform Kmeans Clustering:

```<code>df <- data.frame(
  station = c("aberporth", "armagh", "ballypatrick", "bradford", "braemar", "camborne"),
  avg = c("12.6366666666667", "12.8739130434783", "12.3982857142857", "12.3962441314554",
          "12.025641025641", "12.2855855855856")
)

    df$avg <- as.numeric(as.character(df$avg))

    kmeans(df[,2], 2, nstart=20)

K-means clustering with 2 clusters of sizes 2, 4

Cluster means:
      [,1]
1 12.75529
2 12.27644

Clustering vector:
[1] 1 1 2 2 2 2

Within cluster sum of squares by cluster:
[1] 0.02814292 0.09218318
 (between_SS / total_SS =  71.8 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"    "size"
[8] "iter"         "ifault"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a matrix of weather stations and average rainfall that I want to run a clustering algorithm on - but I am getting an error - any help very welcome please.

     station        avg
[1,] "aberporth"    "12.6366666666667"
[2,] "armagh"       "12.8739130434783"
[3,] "ballypatrick" "12.3982857142857"
[4,] "bradford"     "12.3962441314554"
[5,] "braemar"      "12.025641025641"
[6,] "camborne"     "12.2855855855856"

when I run this code:

 k2<-kmeans(na.omit(C),centers = 2,nstart=25)

I get this error message:

Error in do_one(nmeth) : NA/NaN/Inf in foreign function call (arg 1)

Body:
There are multiple errors:

The column "avg" is a string, but it has to be a numeric variable.

Kmeans calculates the euclidiean distance, which can only be done with numeric variables. You can not include the "Station" variable in your analysis.

Use a data.frame instead of a matrix, because the matrix can only handle one data type (character) in your example.

This is the way your would perform Kmeans Clustering:

df <- data.frame(
  station = c("aberporth", "armagh", "ballypatrick", "bradford", "braemar", "camborne"),
  avg = c("12.6366666666667", "12.8739130434783", "12.3982857142857", "12.3962441314554",
          "12.025641025641", "12.2855855855856")
)

    df$avg <- as.numeric(as.character(df$avg))

    kmeans(df[,2], 2, nstart=20)

K-means clustering with 2 clusters of sizes 2, 4

Cluster means:
      [,1]
1 12.75529
2 12.27644

Clustering vector:
[1] 1 1 2 2 2 2

Within cluster sum of squares by cluster:
[1] 0.02814292 0.09218318
 (between_SS / total_SS =  71.8 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss" "betweenss"    "size"
[8] "iter"         "ifault"


问:
Batch RPG Game with Login Function
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

```<code>title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit
</code>```

I expect it to create the batch file after creating an account so that you can log in later.

答:
Ooh - so many errors!

First, add an extra line setlocal enabledelayedexpansion directly after the @echo off line. This has two effects - first, when your batch ends, your environment is restored to its original condition so that you don't get confused with variables that have been established by prior runs. second, it turns on delayed expansion mode - which is where the !variable! syntax you are using is activated, otherwise ! is simply an ordinary character.

Next, having accepted input from the ketboard with a set /p, you have no idea whether the user entered. In your validation if statements, use if "%var%"=="value" which overcomes most input problems.

Next, the syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.

And a little tip for games that need a save/restore feature:
If you reserve a character as a prefix for variables-you-want-to-save (eg all variables I want to save/reload start with #) then all you need to save a game is

```<code>set #>"mygamefile.txt"
</code>```

and all you need to reload a game is

```<code>for /f "usebackqdelims=" %%a in ("mygamefile.txt") do set "%%a"
</code>```

To zap all # variables (useful before reloading a game) use

```<code>for /f "delims==" %%a in ('set # 2^>nul') do set "%%a="
</code>```

You should look at the thousands of code examples here on SO to find out how to use subroutines - you appear to be using "spaghetti code".

This code may help with your password-checking:

```<code>for /f "tokens=1,2" %%a in (passwordfilename) do if "%%a"=="%playername%" set "playerpass=%%b"
if "%playerpass%"=="%enteredpass%" goto gameon
</code>```

This uses a single password file of the form

```<code>player1 password1
player2 password2
</code>```

If player1 changes password, then append the new data to the file like this:

```<code>player1 password1
player2 password2
player1 newpassword
</code>```

and the above for /f construct will then set playerpass to the last occurrence of player1 found.

This should provide you with a start and obviate your need for a subsidiary batch file. You'll have enough on your plate implementing these suggestions, but you should be able then to see the wood for the trees.

And implement changes one at a time, then test and debug them. Small steps will make the process a lot easier.

Title: Batch RPG Game with Login Function

Body:
I'm creating a D&D style RPG game using batch files and I saw another person using a login feature that creates a batch file that returns you to where you left off. so I tried to replicate it. Almost everything works except for the fact that it won't create the batch file to allow you to go back. When you go through the process of creating a login it goes through it like normal and on the next screen under start even displays that your username is what you set it as but it won't create the batch file. Some of the code might be scattered because I'm still learning and some of it unfinished but this is what I have so far.

title Lost Mine of Phandelvor
@echo off
:entergame
cls
echo.
echo Welcome to Lost Mine of Phandelvor
echo -------------------
echo.
echo 1. Create Account
echo 2. Login
echo 3. Exit
echo.
set /p input=

if %input% EQU 1 goto createuser
if %input% EQU 2 goto login
if %input% EQU 3 exit
if %input% GEQ 4 goto entergame

:createuser
cls
echo.
echo What would you like your Username to be?
set /p username1=
set v1f=0
goto checkforspaces

:checkforspaces
set x=!v1f!
set Letter%v1f%=!username1:~%x%,1!
if "!Letter%v1f%!" EQU " " (
echo.
echo.
echo Sorry you can't use spaces in your Username.
pause>nul
goto entergame
)
if NOT "!Letter%v1f%!" EQU "" (
set /a v1f=%v1f%+1
)
echo.
echo What would you like your Password to be?
set /p password1=
goto DATA_VALUES

:login
cls
set /p name=Username:
if not exist "%name%.bat" (
echo That is not a valid Username.
pause>nul
goto entergame
)
set /p pass1=Password:
call %name1%.bat
if not %password1% EQU %pass1% (
echo That is not a valid Password.
pause>nul
goto entergame
)
goto create

:DATA_FILES
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
set destination=SAVE_GAME_FILES
set destination2=SAVE_GAME_FILES
goto SAVE_GAME_FILES

:SAVE_GAME_FILES
(
echo set username1=%username1%
echo set password1=%password1%
:DATA_VALUES
echo set lvl1=%lvl1%
echo set exp1=%exp1%
echo set expmax1=%expmax1%
echo set gp1=%gp1%
echo set hp1=%hp1%
echo set ac1=%ac1%
echo set profbonus1=%profbonus1%
echo set str1=%str1%
echo set dex1=%dex1%
echo set con1=%con1%
echo set int1=%int1%
echo set wis1=%wis1%
echo set cha1=%cha1%
echo set destination=%destination%
echo set destination2=%destination2%
)>%username1%.bat
goto start

:start
cls
echo.
echo Currently logged in as %username1%
echo.
echo Welcome to my fantasy style role playing game.
echo You will need to create a character.
echo.
echo Enjoy!
echo.
echo 1. Continue to Character Selection
echo 2. Exit
echo.
set /p input=

if %input% EQU 1 goto create
if %input% EQU 2 exit
if %input% GEQ 3 goto start

:create
cls
echo.
echo Welcome to Character Creation
echo.
echo Pick your race!
echo.
echo 1. Human
echo 2. Dwarf
echo 3. Elf
echo 4. Dragonborn
echo 5. Tiefling
echo.
set /p input=Choice:
if %input%==1 goto createHuman
if %input%==2 goto createDwarf
if %input%==3 goto createElf
if %input%==4 goto createDragonborn
if %input%==5 goto createTiefling
goto create

:createHuman
cls
echo.
echo You have chosen Human as your race!
echo.
echo Choose your class
echo.
echo 1. Fighter
echo 2. Ranger
echo 3. Rogue
echo 4. Wizard
echo.
set /p input=Choise
if %input%==1 goto humanFighter
if %input%==2 goto humanRanger
if %input%==3 goto humanRogue
if %input%==4 goto humanWizard
goto createHuman

:humanFighter
cls
echo.
echo You have chosen Fighter as your class!
echo.
echo Choose your weapon
echo.
echo 1. Battleaxe 1D8 Slashing
echo 2. Longsword 1D8 Slashing
echo 3. Rapier 1D8 Piercing
echo.
set /p input=choise
if %input%==1 goto humanFighter1
if %input%==2 goto humanFighter2
if %input%==3 goto humanFighter3
goto humanFighter

:humanfighter1
set lvl1=1
set exp1=0
set expmax1=300
set gp1=10
set hp1=12
set ac1=15
set profbonus1=2
set str1=4
set dex1=1
set con1=2
set int1=0
set wis1=2
set cha1=2
cls
echo.
echo To find your stats open your character sheet labeled humanfighter1_cs.txt
echo.
echo What's your name?
echo.
set /p name1=Enter:
goto hf1main

:hf1main
cls
echo.
echo %name1% Human Fighter
echo Lvl: %lvl1% Money:%gp1%
echo Hit Points: %hp1%/12
echo Armor: Breastplate Armor Class: %ac1%
echo Exp: %exp1%/%expmax1%
echo Weapon: Battleaxe 1D8 Slashing
echo Stat Modifiers:
echo Strength: +%str1%
echo Dexterity: +%dex1%
echo Constitution: +%con1%
echo Intelligence: +%int1%
echo Wisdom: +%wis1%
echo Charisma: +%cha1%
echo -------------------------------------
echo 1) Continue
echo 2) Exit
echo.
set /p input=Enter:
if %input%==1 goto hf1continue
if %input%==2 exit

I expect it to create the batch file after creating an account so that you can log in later.

Body:
Ooh - so many errors!

First, add an extra line setlocal enabledelayedexpansion directly after the @echo off line. This has two effects - first, when your batch ends, your environment is restored to its original condition so that you don't get confused with variables that have been established by prior runs. second, it turns on delayed expansion mode - which is where the !variable! syntax you are using is activated, otherwise ! is simply an ordinary character.

Next, having accepted input from the ketboard with a set /p, you have no idea whether the user entered. In your validation if statements, use if "%var%"=="value" which overcomes most input problems.

Next, the syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.

And a little tip for games that need a save/restore feature:
If you reserve a character as a prefix for variables-you-want-to-save (eg all variables I want to save/reload start with #) then all you need to save a game is

set #>"mygamefile.txt"

and all you need to reload a game is

for /f "usebackqdelims=" %%a in ("mygamefile.txt") do set "%%a"

To zap all # variables (useful before reloading a game) use

for /f "delims==" %%a in ('set # 2^>nul') do set "%%a="

You should look at the thousands of code examples here on SO to find out how to use subroutines - you appear to be using "spaghetti code".

This code may help with your password-checking:

for /f "tokens=1,2" %%a in (passwordfilename) do if "%%a"=="%playername%" set "playerpass=%%b"
if "%playerpass%"=="%enteredpass%" goto gameon

This uses a single password file of the form

player1 password1
player2 password2

If player1 changes password, then append the new data to the file like this:

player1 password1
player2 password2
player1 newpassword

and the above for /f construct will then set playerpass to the last occurrence of player1 found.

This should provide you with a start and obviate your need for a subsidiary batch file. You'll have enough on your plate implementing these suggestions, but you should be able then to see the wood for the trees.

And implement changes one at a time, then test and debug them. Small steps will make the process a lot easier.


问:
How to get last month record from databse in laravel?

i have a table remaining_bus_fees.

```<code>id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300
</code>```

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

```<code>$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();
</code>```

答:
Here is useful queries : </p>

```<code> $today=DB::table('remaining_bus_fees')->whereRaw('Date(created_at) = CURDATE()')->where('student_id', 2)->get();

 $yesterday= DB::table('remaining_bus_fees')->whereDate('created_at',Carbon::yesterday())->get();

 $last_7_days= DB::table('remaining_bus_fees')->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();

 $this_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->month)->whereYear('created_at', date('Y'))->where('student_id', 2)->get();

 $last_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->subMonth()->format('m'))->whereYear('created_at', date('Y'))->where('student_id', 2)->get();
</code>```

Body:
i have a table remaining_bus_fees.

id    | date         | student_id | remaining_balance
-----------------------------------------------------
1     | 2019-04-05   | 1          |     500
2     | 2019-05-10   | 2          |     400
3     | 2019-05-13   | 3          |     300

Now i need how to get last month record against student_id. here is
  query i am using. but this is not working for me.

$remain_fee = \DB::table('remaining_bus_fees')
        ->whereMonth('date', '<', Carbon::now()->subMonth()->month)
        ->where('student_id', '=', 2)->get();

Body:
Here is useful queries :

 $today=DB::table('remaining_bus_fees')->whereRaw('Date(created_at) = CURDATE()')->where('student_id', 2)->get();

 $yesterday= DB::table('remaining_bus_fees')->whereDate('created_at',Carbon::yesterday())->get();

 $last_7_days= DB::table('remaining_bus_fees')->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->get();

 $this_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->month)->whereYear('created_at', date('Y'))->where('student_id', 2)->get();

 $last_month=DB::table('remaining_bus_fees')->whereMonth('created_at',Carbon::now()->subMonth()->format('m'))->whereYear('created_at', date('Y'))->where('student_id', 2)->get();


问:
Capitalization convention for JavaScript objects
I know this question has no answer, but I'm curious to know what other people think.

In a language like Java, it's a convention to begin classes with capital letters, and objects with lowercase letters. But what about JavaScript, where everything is an object?

I've seen some people suggest capitalizing only objects that are treated as classes; i.e. function objects with a prototype, that are intended to be used with the new operator. Instances of those objects would be lowercased.

That sounds logical. But what do you do about "global objects", where there's only one instance? Most people seem to capitalize these (for example, Math or Ext.History). This intuitively feels right, but it's hard to justify it with a consistent rule.

And what about objects that are used as namespaces? These seem to be all over the map: YUI, Ext.util, jQuery, etc.

Please provide secular rationalizations for your heart-felt religious views.

答:
You can follow this Google JavaScript Style Guide

In general, use functionNamesLikeThis, variableNamesLikeThis, ClassNamesLikeThis, EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
I do need help to understand a runtime error
I have following following error which will cause my android app to jump out, where it jumps out is very inconsistent i can't pin point the code causing it. Anyone can read and understand what it is?</p>

```<code>E/AndroidRuntime: FATAL EXCEPTION: Thread-22
    Process: my.zen.com.uselessapp.xxxxxxxx, PID: 16384
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_dependencies_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_0_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_1_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_2_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_3_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_4_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_5_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_6_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_7_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_8_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/lib/arm64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5798)
        at android.app.ActivityThread.access$1100(ActivityThread.java:200)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Application terminated.

</code>```

答:
You are getting a NoClassDefError

```<code>java.lang.NoClassDefFoundError: Failed resolution of:
                          Lorg/apache/http/ProtocolVersion;
</code>```

caused by

```<code>java.lang.ClassNotFoundException:
</code>```

because the Dalvik executable (Dex) class loader couldn't find a particular class for run time
:

```<code>Didn't find class: "org.apache.http.ProtocolVersion"
</code>```

when it tries to run your app

```<code>on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk",
</code>```

That is basically what it means. So check where this class could be used, I suspect one of your dependencies, and make sure everything is in order there, then try building again.

Body:
I have following following error which will cause my android app to jump out, where it jumps out is very inconsistent i can't pin point the code causing it. Anyone can read and understand what it is?

E/AndroidRuntime: FATAL EXCEPTION: Thread-22
    Process: my.zen.com.uselessapp.xxxxxxxx, PID: 16384
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_dependencies_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_0_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_1_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_2_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_3_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_4_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_5_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_6_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_7_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_8_apk.apk", zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/lib/arm64, /system/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at com.google.android.gms.internal.ads.zzaj.zzb(Unknown Source:3)
        at com.google.android.gms.internal.ads.zzai.zza(Unknown Source:4)
        at com.google.android.gms.internal.ads.zzak.zzc(Unknown Source:32)
        at com.google.android.gms.internal.ads.zzayl.zzc(Unknown Source:27)
        at com.google.android.gms.internal.ads.zzn.processRequest(Unknown Source:28)
        at com.google.android.gms.internal.ads.zzn.run(Unknown Source:12)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/split_lib_resources_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:354)
        at dalvik.system.DexFile.<init>(DexFile.java:101)
        at dalvik.system.DexFile.<init>(DexFile.java:75)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:394)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:354)
        at dalvik.system.DexPathList.<init>(DexPathList.java:164)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:74)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:65)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:73)
        at com.android.internal.os.ClassLoaderFactory.createClassLoader(ClassLoaderFactory.java:88)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:74)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:40)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:727)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:810)
        at android.app.LoadedApk.getResources(LoadedApk.java:1032)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2345)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5798)
        at android.app.ActivityThread.access$1100(ActivityThread.java:200)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1656)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6718)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Application terminated.

Body:
You are getting a NoClassDefError

java.lang.NoClassDefFoundError: Failed resolution of:
                          Lorg/apache/http/ProtocolVersion;

caused by

java.lang.ClassNotFoundException:

because the Dalvik executable (Dex) class loader couldn't find a particular class for run time
:

Didn't find class: "org.apache.http.ProtocolVersion"

when it tries to run your app

on path: DexPathList[[zip file "/data/app/my.zen.com.uselessapp.xxxxxxxx-CoQm7REaeOORs9mK5raYJw==/base.apk",

That is basically what it means. So check where this class could be used, I suspect one of your dependencies, and make sure everything is in order there, then try building again.


问:
Previous layout get clicked from overlaped layout in Activity
I have two reletive layout. First has spinner and recyclerview and second has a imageview. Second layout overlap first layout on button click. But when I click on second layout, first layout spinner and recylerview get clicked and it shows on second layout.</p>

答:
Add

android:clickable="true"
android:focusable="true"

to your image view layout. It will not propagate your clicks to your first layout.


问:
MySQL SELECT row based on prefix
Im attempting to do a SELECT on data in a table that contains prefixes, and I have the "keyword".

So unlike a normal search where the prefix/keyword is contained in the row data, and that the prefix/keyword is shorter (or contained in) a possible row of data.

This is the opposite. If have prefixes in rows and I want to find the best matching row based on the (longer) word/phase.

```<code>CREATE TABLE table1 (id INT NOT NULL AUTO_INCREMENT, keyCode VARCHAR(45) NULL, Username VARCHAR(45) NULL, PRIMARY KEY (id));

INSERT INTO table1(keyCode,Username)VALUES('123','Peter')
INSERT INTO table1(keyCode,Username)VALUES('456','Paul')
INSERT INTO table1(keyCode,Username)VALUES('1234','John')

</code>```

Now let's say the phrase I have been given is longer than the prefix in the data.

Like this:

```<code>SELECT * FROM table1 WHERE keyCode LIKE '123456%';
</code>```

I know this will not work, but I would like to return the Row with User 'John'.

How?
(I can use stored procedures)

答:
You may phrase your LIKE expression in the reverse order:

```<code>SELECT *
FROM table1
WHERE '123456' LIKE CONCAT(keyCode, '%');
</code>```

This would compare, for example, '123456' against '1234%', which should be a match in this case.

Title: MySQL SELECT row based on prefix

Body:
Im attempting to do a SELECT on data in a table that contains prefixes, and I have the "keyword".

So unlike a normal search where the prefix/keyword is contained in the row data, and that the prefix/keyword is shorter (or contained in) a possible row of data.

This is the opposite. If have prefixes in rows and I want to find the best matching row based on the (longer) word/phase.

CREATE TABLE table1 (id INT NOT NULL AUTO_INCREMENT, keyCode VARCHAR(45) NULL, Username VARCHAR(45) NULL, PRIMARY KEY (id));

INSERT INTO table1(keyCode,Username)VALUES('123','Peter')
INSERT INTO table1(keyCode,Username)VALUES('456','Paul')
INSERT INTO table1(keyCode,Username)VALUES('1234','John')

Now let's say the phrase I have been given is longer than the prefix in the data.

Like this:

SELECT * FROM table1 WHERE keyCode LIKE '123456%';

I know this will not work, but I would like to return the Row with User 'John'.

How?
(I can use stored procedures)

Body:
You may phrase your LIKE expression in the reverse order:

SELECT *
FROM table1
WHERE '123456' LIKE CONCAT(keyCode, '%');

This would compare, for example, '123456' against '1234%', which should be a match in this case.


问:
Best way to automatic change update_time in mongoengine only under some conditions
Say I defined a model Story, and in my save method I automatically update the update_time field:

```
class Article(Document):
    ...
    content = StringField()
    likes = IntField(default=0)
    some_mark = BooleanField()
    update_time = DateTimeField(default=datetime.datetime.now)

    def save(...)
        self.updated_at = datetime.datetime.now()
        ...
```

But I would NOT like to only update the update_time when only the likes count or some_mark are changed. Or, if I only want to update the update_time when some fields like the content is changed. What will be the best way to do this?

答:
You can check the ._changed_fields attribute on your Document class to check the fields that were changed

```<code>class Person(Document):
    name = StringField()
    enter code here

p = Person(name='John').save()

print(p._changed_fields)   # []

p.name = 'Bob'
print(p._changed_fields)   # ['name']

</code>```

Body:
Say I defined a model Story, and in my save method I automatically update the update_time field:

class Article(Document):
    ...
    content = StringField()
    likes = IntField(default=0)
    some_mark = BooleanField()
    update_time = DateTimeField(default=datetime.datetime.now)

    def save(...)
        self.updated_at = datetime.datetime.now()
        ...

But I would NOT like to only update the update_time when only the likes count or some_mark are changed. Or, if I only want to update the update_time when some fields like the content is changed. What will be the best way to do this?

Body:
You can check the ._changed_fields attribute on your Document class to check the fields that were changed

class Person(Document):
    name = StringField()
    enter code here

p = Person(name='John').save()

print(p._changed_fields)   # []

p.name = 'Bob'
print(p._changed_fields)   # ['name']


问:
vectors iteration compiles to very different instructions
I am surprised that iterating over a vector with up to date compilers show a very different code for the same result.
Here is the code:

```<code>void fun1(vector <uint8_t> &a,unsigned num) {

    for (auto &&value : a) {
        value += num;
    }
}

void fun2(vector <uint8_t> &a,unsigned num){

    for (uint32_t x = 0, p = a.size(); x < p; x++){
        a[x] += num;
    }
}
void fun4(vector <uint8_t> &a,unsigned num){

    for (uint32_t x = 0; x < a.size(); x++){
        a[x] += num;
    }
}
void fun3(vector <uint8_t> &a,unsigned num) {

    for (auto it = a.begin(); it!=a.end(); ++it) {
        *it += num;
    }
}
void fun5(vector <uint8_t> &a,unsigned num) {

    std::for_each(a.begin(), a.end(), [num](auto &&val) {
        val += num;
    });
}
</code>```

You can run it on godbolt.

The generated assembly is very different (fun1 && fun5 even have proposal for SIMD). I get that for fun4 since a.size() may change. But the others? Different compilers approximate to the same result.

The compiler should be able to generate the same code since, the intent here is really basic (and the same).

I really like fun2 version. Any way to improve it?

Update:

When giving enough info to the compiler, this becomes a non issue. So it tells that the compilers in their current version (gcc 9.x) are tailored differently for those loops when only partial info is accessible.

The code is still NOT the same but they all propose vectorization now. We will have to accept it I guess.
Maybe future versions will improve that.

See the updated code (with useless allocations, but still)

答:
Compilers now optimize code for out-of-order execution. The same C++ code can be compiled to different assembly code.

So, try not to leave any space for an optimization :-)

Here are two the version of fun4:

```<code>void fun4_a(vector <uint8_t> &a, uint8_t num) {
    size_t n = a.size();
f1: if (n <= 0) goto f2;
    a[--n] += num;
    goto f1;
f2: return;
}

void fun4_b(vector <uint8_t> &a, uint8_t num) {
    size_t n = a.size();
    while (n > 0) a[--n] += num;
}
</code>```

You can run it on godbolt.

Compiler x86_64 gcc 9.1 produced the same assembly for fun4_a and fun4_b but still unrolled one 'add' loop:

```<code>fun4_a(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov     rdx, QWORD PTR [rdi]
        mov     rax, QWORD PTR [rdi+8]
        mov     ecx, esi
        sub     rax, rdx
        je      .L1
        sub     rax, 1
        add     BYTE PTR [rdx+rax], sil
        test    rax, rax
        je      .L1
.L3:
        mov     rdx, QWORD PTR [rdi]
        sub     rax, 1
        add     rdx, rax
        add     BYTE PTR [rdx], cl
        test    rax, rax
        jne     .L3
.L1:
</code>```

While compiler x86-64 icc 19.0.1 decided to produce more optimizations for fun4_b:

```<code>fun4_a(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov       rcx, QWORD PTR [8+rdi]                        #806.26
        mov       rdx, rcx                                      #806.26
        mov       rax, QWORD PTR [rdi]                          #806.52
        sub       rdx, rax                                      #806.26
        je        ..B1.6        # Prob 18%                      #10.14
        xor       eax, eax                                      #10.5
..B1.3:                         # Preds ..B1.4 ..B1.2
        inc       rax                                           #10.5
        mov       r8, rcx                                       #9.11
        lea       r9, QWORD PTR [rax+rax]                       #9.11
        sub       r8, r9                                        #9.11
        neg       r9                                            #9.11
        add       r9, rdx                                       #9.11
        mov       rdi, r9                                       #9.11
        add       BYTE PTR [1+r8], sil                          #11.3
        inc       rdi                                           #9.11
        je        ..B1.6        # Prob 18%                      #10.14
        add       BYTE PTR [r8], sil                            #11.3
        test      r9, r9                                        #10.14
        jne       ..B1.3        # Prob 82%                      #10.14
..B1.6:                         # Preds ..B1.3 ..B1.4 ..B1.1
        ret                                                     #13.5
fun4_b(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov       r8d, esi                                      #16.47
        mov       rsi, QWORD PTR [rdi]                          #806.52
        mov       rcx, QWORD PTR [8+rdi]                        #806.26
        sub       rcx, rsi                                      #806.26
        je        ..B2.17       # Prob 50%                      #18.16
        cmp       rcx, 16                                       #18.5
        jb        ..B2.18       # Prob 10%                      #18.5
        mov       rdx, rsi                                      #18.5
        and       rdx, 15                                       #18.5
        je        ..B2.9        # Prob 50%                      #18.5
        mov       rax, rdx                                      #18.5
        neg       rax                                           #18.5
        lea       rdx, QWORD PTR [16+rax]                       #18.5
        add       rax, 32                                       #18.5
        cmp       rcx, rax                                      #18.5
        jb        ..B2.18       # Prob 10%                      #18.5
        mov       rax, rcx                                      #18.5
        xor       r10d, r10d                                    #18.5
        sub       rax, rdx                                      #18.5
        mov       r9, rsi                                       #18.5
        and       rax, 15                                       #18.5
        neg       rax                                           #18.5
        add       rax, rcx                                      #18.5
        mov       edi, r8d                                      #18.20
..B2.7:                         # Preds ..B2.7 ..B2.6
        inc       r10                                           #18.5
        add       BYTE PTR [r9], dil                            #18.20
        inc       r9                                            #18.5
        cmp       r10, rdx                                      #18.5
        jb        ..B2.7        # Prob 82%                      #18.5
        jmp       ..B2.10       # Prob 100%                     #18.5
..B2.9:                         # Preds ..B2.3
        mov       rax, rcx                                      #18.5
        and       rax, 15                                       #18.5
        neg       rax                                           #18.5
        add       rax, rcx                                      #18.5
..B2.10:                        # Preds ..B2.7 ..B2.9
        movzx     edi, r8b                                      #18.29
        movd      xmm0, edi                                     #18.29
        punpcklbw xmm0, xmm0                                    #18.29
        punpcklwd xmm0, xmm0                                    #18.29
        punpckldq xmm0, xmm0                                    #18.29
        punpcklqdq xmm0, xmm0                                   #18.29
..B2.11:                        # Preds ..B2.11 ..B2.10
        movdqu    xmm1, XMMWORD PTR [rsi+rdx]                   #18.20
        paddb     xmm1, xmm0                                    #18.20
        movdqu    XMMWORD PTR [rdx+rsi], xmm1                   #18.20
        add       rdx, 16                                       #18.5
        cmp       rdx, rax                                      #18.5
        jb        ..B2.11       # Prob 82%                      #18.5
..B2.13:                        # Preds ..B2.11 ..B2.18
        add       rsi, rax                                      #18.5
        cmp       rax, rcx                                      #18.5
        jae       ..B2.17       # Prob 9%                       #18.5
..B2.15:                        # Preds ..B2.13 ..B2.15
        inc       rax                                           #18.5
        add       BYTE PTR [rsi], r8b                           #18.20
        inc       rsi                                           #18.5
        cmp       rax, rcx                                      #18.5
        jb        ..B2.15       # Prob 82%                      #18.5
..B2.17:                        # Preds ..B2.15 ..B2.1 ..B2.13
        ret                                                     #19.1
..B2.18:                        # Preds ..B2.2 ..B2.4
        xor       eax, eax                                      #18.5
        jmp       ..B2.13       # Prob 100%                     #18.5
</code>```

Body:
I am surprised that iterating over a vector with up to date compilers show a very different code for the same result.
Here is the code:

void fun1(vector <uint8_t> &a,unsigned num) {

    for (auto &&value : a) {
        value += num;
    }
}

void fun2(vector <uint8_t> &a,unsigned num){

    for (uint32_t x = 0, p = a.size(); x < p; x++){
        a[x] += num;
    }
}
void fun4(vector <uint8_t> &a,unsigned num){

    for (uint32_t x = 0; x < a.size(); x++){
        a[x] += num;
    }
}
void fun3(vector <uint8_t> &a,unsigned num) {

    for (auto it = a.begin(); it!=a.end(); ++it) {
        *it += num;
    }
}
void fun5(vector <uint8_t> &a,unsigned num) {

    std::for_each(a.begin(), a.end(), [num](auto &&val) {
        val += num;
    });
}

You can run it on godbolt.

The generated assembly is very different (fun1 && fun5 even have proposal for SIMD). I get that for fun4 since a.size() may change. But the others? Different compilers approximate to the same result.

The compiler should be able to generate the same code since, the intent here is really basic (and the same).

I really like fun2 version. Any way to improve it?

Update:

When giving enough info to the compiler, this becomes a non issue. So it tells that the compilers in their current version (gcc 9.x) are tailored differently for those loops when only partial info is accessible.

The code is still NOT the same but they all propose vectorization now. We will have to accept it I guess.
Maybe future versions will improve that.

See the updated code (with useless allocations, but still)

Body:
Compilers now optimize code for out-of-order execution. The same C++ code can be compiled to different assembly code.

So, try not to leave any space for an optimization :-)

Here are two the version of fun4:

void fun4_a(vector <uint8_t> &a, uint8_t num) {
    size_t n = a.size();
f1: if (n <= 0) goto f2;
    a[--n] += num;
    goto f1;
f2: return;
}

void fun4_b(vector <uint8_t> &a, uint8_t num) {
    size_t n = a.size();
    while (n > 0) a[--n] += num;
}

You can run it on godbolt.

Compiler x86_64 gcc 9.1 produced the same assembly for fun4_a and fun4_b but still unrolled one 'add' loop:

fun4_a(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov     rdx, QWORD PTR [rdi]
        mov     rax, QWORD PTR [rdi+8]
        mov     ecx, esi
        sub     rax, rdx
        je      .L1
        sub     rax, 1
        add     BYTE PTR [rdx+rax], sil
        test    rax, rax
        je      .L1
.L3:
        mov     rdx, QWORD PTR [rdi]
        sub     rax, 1
        add     rdx, rax
        add     BYTE PTR [rdx], cl
        test    rax, rax
        jne     .L3
.L1:

While compiler x86-64 icc 19.0.1 decided to produce more optimizations for fun4_b:

fun4_a(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov       rcx, QWORD PTR [8+rdi]                        #806.26
        mov       rdx, rcx                                      #806.26
        mov       rax, QWORD PTR [rdi]                          #806.52
        sub       rdx, rax                                      #806.26
        je        ..B1.6        # Prob 18%                      #10.14
        xor       eax, eax                                      #10.5
..B1.3:                         # Preds ..B1.4 ..B1.2
        inc       rax                                           #10.5
        mov       r8, rcx                                       #9.11
        lea       r9, QWORD PTR [rax+rax]                       #9.11
        sub       r8, r9                                        #9.11
        neg       r9                                            #9.11
        add       r9, rdx                                       #9.11
        mov       rdi, r9                                       #9.11
        add       BYTE PTR [1+r8], sil                          #11.3
        inc       rdi                                           #9.11
        je        ..B1.6        # Prob 18%                      #10.14
        add       BYTE PTR [r8], sil                            #11.3
        test      r9, r9                                        #10.14
        jne       ..B1.3        # Prob 82%                      #10.14
..B1.6:                         # Preds ..B1.3 ..B1.4 ..B1.1
        ret                                                     #13.5
fun4_b(std::vector<unsigned char, std::allocator<unsigned char> >&, unsigned char):
        mov       r8d, esi                                      #16.47
        mov       rsi, QWORD PTR [rdi]                          #806.52
        mov       rcx, QWORD PTR [8+rdi]                        #806.26
        sub       rcx, rsi                                      #806.26
        je        ..B2.17       # Prob 50%                      #18.16
        cmp       rcx, 16                                       #18.5
        jb        ..B2.18       # Prob 10%                      #18.5
        mov       rdx, rsi                                      #18.5
        and       rdx, 15                                       #18.5
        je        ..B2.9        # Prob 50%                      #18.5
        mov       rax, rdx                                      #18.5
        neg       rax                                           #18.5
        lea       rdx, QWORD PTR [16+rax]                       #18.5
        add       rax, 32                                       #18.5
        cmp       rcx, rax                                      #18.5
        jb        ..B2.18       # Prob 10%                      #18.5
        mov       rax, rcx                                      #18.5
        xor       r10d, r10d                                    #18.5
        sub       rax, rdx                                      #18.5
        mov       r9, rsi                                       #18.5
        and       rax, 15                                       #18.5
        neg       rax                                           #18.5
        add       rax, rcx                                      #18.5
        mov       edi, r8d                                      #18.20
..B2.7:                         # Preds ..B2.7 ..B2.6
        inc       r10                                           #18.5
        add       BYTE PTR [r9], dil                            #18.20
        inc       r9                                            #18.5
        cmp       r10, rdx                                      #18.5
        jb        ..B2.7        # Prob 82%                      #18.5
        jmp       ..B2.10       # Prob 100%                     #18.5
..B2.9:                         # Preds ..B2.3
        mov       rax, rcx                                      #18.5
        and       rax, 15                                       #18.5
        neg       rax                                           #18.5
        add       rax, rcx                                      #18.5
..B2.10:                        # Preds ..B2.7 ..B2.9
        movzx     edi, r8b                                      #18.29
        movd      xmm0, edi                                     #18.29
        punpcklbw xmm0, xmm0                                    #18.29
        punpcklwd xmm0, xmm0                                    #18.29
        punpckldq xmm0, xmm0                                    #18.29
        punpcklqdq xmm0, xmm0                                   #18.29
..B2.11:                        # Preds ..B2.11 ..B2.10
        movdqu    xmm1, XMMWORD PTR [rsi+rdx]                   #18.20
        paddb     xmm1, xmm0                                    #18.20
        movdqu    XMMWORD PTR [rdx+rsi], xmm1                   #18.20
        add       rdx, 16                                       #18.5
        cmp       rdx, rax                                      #18.5
        jb        ..B2.11       # Prob 82%                      #18.5
..B2.13:                        # Preds ..B2.11 ..B2.18
        add       rsi, rax                                      #18.5
        cmp       rax, rcx                                      #18.5
        jae       ..B2.17       # Prob 9%                       #18.5
..B2.15:                        # Preds ..B2.13 ..B2.15
        inc       rax                                           #18.5
        add       BYTE PTR [rsi], r8b                           #18.20
        inc       rsi                                           #18.5
        cmp       rax, rcx                                      #18.5
        jb        ..B2.15       # Prob 82%                      #18.5
..B2.17:                        # Preds ..B2.15 ..B2.1 ..B2.13
        ret                                                     #19.1
..B2.18:                        # Preds ..B2.2 ..B2.4
        xor       eax, eax                                      #18.5
        jmp       ..B2.13       # Prob 100%                     #18.5


问:
How to create Dynamic Drop in Symfony OneToMany Relationship?
Diocese:

```<code>-----------------
|id|diocese_name|
-----------------

|1 |   DJ       |
|2 |   Kpg      |
</code>```

OneToMany

```<code>Parish:
---------------------------
|id|diocese_id|parish_name|
---------------------------
|1 |    1     |St. Jude   |
|2 |    1     |St. Mark   |
|3 |    2     |St. Peter  |
|4 |    2     |St. thomas |
</code>```

I want to make a drop down dynamic:
when the user clicks on Diocese name, It should Display the related Parish Name.

I tried with Form Event, but I couldn't follow the documentation.
Here is the Code.

```<code>        $builder
        ->add('diocese_name', EntityType::class,[

            'class' => 'App\Entity\Diocese',
            'choice_label' => 'diocese_name'
        ])
    ;

    $builder
        ->addEventListener(

            FormEvents::PRE_SET_DATA,
            function(FormEvent $event){
                $form = $event->getForm();
                $data = $event->getData();

                $parish = $data->getParish();

                dump($parish);

            }
        );
</code>```

答:
You don't need to use any event listener. The best way is to use "Custom Form" of Symfony.

Look at the documentation :

https://symfony.com/doc/current/form/create_custom_field_type.html
https://symfony.com/doc/current/form/form_customization.html

You have to create a "choicetype" for your diocese and custom the field(like first link above). In your twig ( by default the file: '.../fields.html.twig'), make a

```<code>{{ dump(form) }}
</code>```

to see what variable you can access !

If you want to use the entity manager to make Doctrine request, you can ! You could create a custom FormType, then pass result of this request in your twig with attr or other.

Hope it will help,
Best regards !

Body:
Diocese:

-----------------
|id|diocese_name|
-----------------

|1 |   DJ       |
|2 |   Kpg      |

OneToMany

Parish:
---------------------------
|id|diocese_id|parish_name|
---------------------------
|1 |    1     |St. Jude   |
|2 |    1     |St. Mark   |
|3 |    2     |St. Peter  |
|4 |    2     |St. thomas |

I want to make a drop down dynamic:
when the user clicks on Diocese name, It should Display the related Parish Name.

I tried with Form Event, but I couldn't follow the documentation.
Here is the Code.

        $builder
        ->add('diocese_name', EntityType::class,[

            'class' => 'App\Entity\Diocese',
            'choice_label' => 'diocese_name'
        ])
    ;

    $builder
        ->addEventListener(

            FormEvents::PRE_SET_DATA,
            function(FormEvent $event){
                $form = $event->getForm();
                $data = $event->getData();

                $parish = $data->getParish();

                dump($parish);

            }
        );

Body:
You don't need to use any event listener. The best way is to use "Custom Form" of Symfony.

Look at the documentation :

https://symfony.com/doc/current/form/create_custom_field_type.html
https://symfony.com/doc/current/form/form_customization.html

You have to create a "choicetype" for your diocese and custom the field(like first link above). In your twig ( by default the file: '.../fields.html.twig'), make a

{{ dump(form) }}

to see what variable you can access !

If you want to use the entity manager to make Doctrine request, you can ! You could create a custom FormType, then pass result of this request in your twig with attr or other.

Hope it will help,
Best regards !


问:
Performing SQL Update Using Join and Matching Specific Columns
I have a one database with a table containing a column CLASS_LEVEL. I have another database containing a column CLASS_LEVEL as well. In the first table there is only one row for each student, in the second table there are multiple rows for each student, thus multiple CLASS_LEVELS. I need to update the values in TABLE1 with the values from TABLE2. Here is my current code:

```<code>UPDATE R
SET R.CLASS_LEVEL = A.CLASS_LEVEL
FROM Residents R
INNER JOIN
CAMPUS..ACADEMIC A
ON
R.PEOPLE_CODE_ID = A.PEOPLE_ID
</code>```

But I need to add a where clause somehow so that it updates using a specific A.CLASS_LEVEL result, not just any one associated with that student, something like:

```<code>WHERE A.ACADEMIC_TERM='Fall' AND A.ACADEMIC_YEAR='2011'
</code>```

I don't know how to use a where term or something similar with a SQL table though...Any suggestions?

答:
It is this simple

```<code>UPDATE
 R
SET
  R.CLASS_LEVEL = A.CLASS_LEVEL
FROM
  Residents R
  INNER JOIN
  CAMPUS..ACADEMIC A ON R.PEOPLE_CODE_ID = A.PEOPLE_ID
WHERE
  A.ACADEMIC_TERM='Fall' AND A.ACADEMIC_YEAR='2011'
</code>```

Join R and A on the relevant IDs

Restrict A to a set of rows

The net effect is to restrict R to match rows in a filtered subset of A

Body:
I have a one database with a table containing a column CLASS_LEVEL. I have another database containing a column CLASS_LEVEL as well. In the first table there is only one row for each student, in the second table there are multiple rows for each student, thus multiple CLASS_LEVELS. I need to update the values in TABLE1 with the values from TABLE2. Here is my current code:

UPDATE R
SET R.CLASS_LEVEL = A.CLASS_LEVEL
FROM Residents R
INNER JOIN
CAMPUS..ACADEMIC A
ON
R.PEOPLE_CODE_ID = A.PEOPLE_ID

But I need to add a where clause somehow so that it updates using a specific A.CLASS_LEVEL result, not just any one associated with that student, something like:

WHERE A.ACADEMIC_TERM='Fall' AND A.ACADEMIC_YEAR='2011'

I don't know how to use a where term or something similar with a SQL table though...Any suggestions?

Body:
It is this simple

UPDATE
 R
SET
  R.CLASS_LEVEL = A.CLASS_LEVEL
FROM
  Residents R
  INNER JOIN
  CAMPUS..ACADEMIC A ON R.PEOPLE_CODE_ID = A.PEOPLE_ID
WHERE
  A.ACADEMIC_TERM='Fall' AND A.ACADEMIC_YEAR='2011'

Join R and A on the relevant IDs

Restrict A to a set of rows

The net effect is to restrict R to match rows in a filtered subset of A


问:
CO currency for settlement process in CJ88
We have an issue with settlement in SAP.

If we post 1000CAD in settlement rule (cj02) for an asset #123456 to a project then it get settled 1000USD after settlement run.
But my question is why the CAD allocation is settling as USD? How can we solve this issue?

答:
All transactions (incl. settlements) in CO-PA are done in Controlling Area currency that couldn't be changed. It seems that your CA currency is USD.

Check if flag All currencies is set in tcode OKKP, node Activate component indicators

If this is the case then your company uses different currencies for documents which are:

controlling area currency

object currency (=company code currency)

transaction currency (specified for each transaction).

By default all settlements are reconciled in company code currency so check if it is USD and change to desired value.

By and large, currency determination in CO-PA is very complex, check SAP note 1320586 for more details.


问:
I need a button to only during a certain time at certain days
I need a button to only appear from 12pm-3pm on Monday-Friday. When it is not during those times, the item (button) needs to not be shown. We also need to account the different time zones for people who will be viewing the site. Any help would be greatly appreciated

My code right now only disables the button during 12pm-3pm. I have not been able to input for it to only work on certain days. Also, I think the time only accounts for the server's time zone (Pacific Standard) and not the user's.

```<code><a href="#" target="_blank"><input id="live" class="bttHider live"
type="submit" onclick="showHidden(); showbttHidden();"
value="Livestream Video - STREAMING NOW" disabled></a>

<script>
var h = new Date().getHours();

if (h >= 12 && h <= 15) {

document.getElementById('live').disabled=false;
}
</script>
</code>```

答:
var today = new Date();
  var day = today.getDay();
  var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"];
  console.log("Today is : " + daylist[day] + ".");
  if(daylist[day]!="" && daylist[day]!="Sunday"){
  var hour = today.getHours();
  var minute = today.getMinutes();
  var second = today.getSeconds();
  if(hour>="12" && (hour<=3&&minute==0)){
  $("#btn1").show();}
  else{$("#btn1").hide()}
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Button Styles</h2>
  <button type="button" class="btn btn-info" id=btn1>Basic</button></div></body></html></code>```

Body:
I need a button to only appear from 12pm-3pm on Monday-Friday. When it is not during those times, the item (button) needs to not be shown. We also need to account the different time zones for people who will be viewing the site. Any help would be greatly appreciated

My code right now only disables the button during 12pm-3pm. I have not been able to input for it to only work on certain days. Also, I think the time only accounts for the server's time zone (Pacific Standard) and not the user's.

<input id="live" class="bttHider live"
type="submit" onclick="showHidden(); showbttHidden();"
value="Livestream Video - STREAMING NOW" disabled>

Body:
var today = new Date();
  var day = today.getDay();
  var daylist = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"];
  console.log("Today is : " + daylist[day] + ".");
  if(daylist[day]!="" && daylist[day]!="Sunday"){
  var hour = today.getHours();
  var minute = today.getMinutes();
  var second = today.getSeconds();
  if(hour>="12" && (hour<=3&&minute==0)){
  $("#btn1").show();}
  else{$("#btn1").hide()}
  }

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Button Styles</h2>
  <button type="button" class="btn btn-info" id=btn1>Basic</button></div></body></html>


问:
Sorting of IEnumerable<T> in MVC 2
My Service layer returns a IEnumerable<ResortsView> to my Controller and I have to provide an option to SORT the results on UI by following criteria: Price (Excluding ZERO Price Items), SupplierName & Rating. Here is the code snippet of my objects/classes:

```<code>[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}
</code>```

What is the best way to handle sorting of results inside IEnumerable<ResortsView>?

答:
Most likely if you'll want to use the Dynamic LINQ library, here are some instructions and a download link.

You'll need to have your action accept some sorting parameters:

```<code>public ActionResult MyAction(string sortField)
{
    return View(myService.MyData().OrderBy(sortField));
}
</code>```

Title: Sorting of IEnumerable<T> in MVC 2

Body:
My Service layer returns a IEnumerable<ResortsView> to my Controller and I have to provide an option to SORT the results on UI by following criteria: Price (Excluding ZERO Price Items), SupplierName & Rating. Here is the code snippet of my objects/classes:

[Serializable]
public class ResortsView : SupplierView
{
    public IList<ProductView> ResortProducts { get; set; }
    public string CheckInTime { get; set; }
    public string CheckOutTime { get; set; }
    public virtual IList<ImageView> Images { get; set; }
}

[Serializable]
public class SupplierView
{
    public string SupplierID { get; set; }
    public string SupplierName { get; set; }
    public string Description { get; set; }
    public string Rating { get; set; }
    public string URL { get; set; }
}

[Serializable]
public class ProductView
{
    public string Code { get; set; }
    public string Description { get; set; }
    public decimal? Price { get; set; }
    public ErrorView PricingError { get; set; }
}

What is the best way to handle sorting of results inside IEnumerable<ResortsView>?

Body:
Most likely if you'll want to use the Dynamic LINQ library, here are some instructions and a download link.

You'll need to have your action accept some sorting parameters:

public ActionResult MyAction(string sortField)
{
    return View(myService.MyData().OrderBy(sortField));
}


问:
I want to insert value in text box but as the elements are dynamically created, I'm unable to define the element id in the javascript
I want to populate the text area with some text. I wrote a script which does this on a button click. The bottleneck here is that the elements of the HTML are dynamic and are created as per the user's count working on it. Well, my script works for a static text area. How can i make my script helpful for dynamic text area.

```<code>  function insertText(elemID, text)
  {
    var elem = document.getElementById(elemID);
    elem.innerHTML += text;
  }

</script>

<input type="button" name="review_type" value="Postitive"  onclick="insertText('txt1', 'Negative - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt1', 'Positive - ')"; />
</code>```

Thanks!

答:
Got It, it's working well. Below is the solution-

In your dynamically changing HTML element, add the following code-

```<code><textarea style="height: auto" rows="1" id="txt{{user.id}}" />
</code>```

Add txt{{user.id}} for fetching id of the dynamic text area -

```<code><input type="button" name="review_type" value="Postitive"  onclick="insertText('txt{{user.id}}', 'Positive - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt{{user.id}}', 'Negative - ')"; />
</code>```

Body:
I want to populate the text area with some text. I wrote a script which does this on a button click. The bottleneck here is that the elements of the HTML are dynamic and are created as per the user's count working on it. Well, my script works for a static text area. How can i make my script helpful for dynamic text area.

  function insertText(elemID, text)
  {
    var elem = document.getElementById(elemID);
    elem.innerHTML += text;
  }

</script>

<input type="button" name="review_type" value="Postitive"  onclick="insertText('txt1', 'Negative - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt1', 'Positive - ')"; />

Thanks!

Body:
Got It, it's working well. Below is the solution-

In your dynamically changing HTML element, add the following code-

<textarea style="height: auto" rows="1" id="txt{{user.id}}" />

Add txt{{user.id}} for fetching id of the dynamic text area -

<input type="button" name="review_type" value="Postitive"  onclick="insertText('txt{{user.id}}', 'Positive - ')"; />
<input type="button" name="review_type" value="Nagative" onclick="insertText('txt{{user.id}}', 'Negative - ')"; />


问:
Sweet alert is overriding the one alert in a loop
i am call the sweet alert function on inside a loop but sweetalert is only showing me one time,i think it is overriding the previous sweetalert,bcz when i do the simple alert it does pop up twice then but sweet alert is only showing me one time. What i want to do is to to sweet alert to show the second or third alert when i click on ok aor cancel button otherwise dont't shwo the second or next alert according to loop itreration Here is my code     </p>

```<code> $(document).on('submit', 'form#tenant_login', function(e){
        e.preventDefault();
        var data = $(this).serialize();
        $.ajax({
            method: "POST",
            url: '{{ url('/tenant/login') }}',
            data: data,
            success: function(result){

                if(result ) {
                    window.location = "{{ route('about') }}";
                }

            },

            error: function (err) {

                if (err.status == 422) { // when status code is 422, it's a validation issue
                    console.log(err.responseJSON);
                    $('#success_message').fadeIn().html(err.responseJSON.message);

                    // you can loop through the errors object and show it to the user
                    console.warn(err.responseJSON.errors);
                    // display errors on each form field
                    $.each(err.responseJSON.errors, function (i, error) {
                        var el = $(document).find('[name="'+i+'"]');
                        var testVar = error[0];

                         swal({
                             title: "Error!",
                            text: " " + error,
                            type: "error",
                            confirmButtonText: "OK"
                         });

                    });
                }
            }
        });
    });
</code>```

答:
After checking the plugin documentation, one can find a chaining alert method here.

We can see on the exemple that the queue method takes an array of objects as a parameter, so you can use your $.each function to build that array then pass it to the function like so (please note that I set a custom array of errors as I don't have your exact code so can't reproduce the exact array but you can rearrange it to fit your own code) :

```<code>var errors = ['error one', 'error two', 'error three']; //errors array from the response of AJAX request
var arrayOfErrorsToDisplay = []; //initialize the errors to display with the plugin

$.each(errors, function (i, error) {
    arrayOfErrorsToDisplay.push({ title: 'Error!', text: error }); //add each error to the array
});

Swal.mixin({
  confirmButtonText: 'Next →',
  showCancelButton: true,
  progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay) //we pass the array of errors to display to the queue
.then((result) => { //here you can set your own preferences for what to do when user clicks on OK, I just took the basic example for the plugin's documentation
  if (result.value) {
    Swal({
      title: 'All errors have been shown!',
      html:
        'Your answers: ```' +
          JSON.stringify(result.value) +
        '```',
      confirmButtonText: 'Done!'
    })
  }
});
</code>```

Working snippet below :

var errors = ['error one', 'error two', 'error three'];
var arrayOfErrorsToDisplay = [];

$.each(errors, function (i, error) {
 arrayOfErrorsToDisplay.push({ title: 'Error!', text: error });
});

Swal.mixin({
  confirmButtonText: 'Next →',
  showCancelButton: true,
  progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay)
.then((result) => {
  if (result.value) {
    Swal({
      title: 'All errors have been shown!',
      html:
        'Your answers: ```<code>' +
          JSON.stringify(result.value) +
        '</code>```',
      confirmButtonText: 'Done!'
    })
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.all.min.js"></script></code>```

Body:
i am call the sweet alert function on inside a loop but sweetalert is only showing me one time,i think it is overriding the previous sweetalert,bcz when i do the simple alert it does pop up twice then but sweet alert is only showing me one time. What i want to do is to to sweet alert to show the second or third alert when i click on ok aor cancel button otherwise dont't shwo the second or next alert according to loop itreration Here is my code

 $(document).on('submit', 'form#tenant_login', function(e){
        e.preventDefault();
        var data = $(this).serialize();
        $.ajax({
            method: "POST",
            url: '{{ url('/tenant/login') }}',
            data: data,
            success: function(result){

                if(result ) {
                    window.location = "{{ route('about') }}";
                }

            },

            error: function (err) {

                if (err.status == 422) { // when status code is 422, it's a validation issue
                    console.log(err.responseJSON);
                    $('#success_message').fadeIn().html(err.responseJSON.message);

                    // you can loop through the errors object and show it to the user
                    console.warn(err.responseJSON.errors);
                    // display errors on each form field
                    $.each(err.responseJSON.errors, function (i, error) {
                        var el = $(document).find('[name="'+i+'"]');
                        var testVar = error[0];

                         swal({
                             title: "Error!",
                            text: " " + error,
                            type: "error",
                            confirmButtonText: "OK"
                         });

                    });
                }
            }
        });
    });

Body:
After checking the plugin documentation, one can find a chaining alert method here.

We can see on the exemple that the queue method takes an array of objects as a parameter, so you can use your $.each function to build that array then pass it to the function like so (please note that I set a custom array of errors as I don't have your exact code so can't reproduce the exact array but you can rearrange it to fit your own code) :

var errors = ['error one', 'error two', 'error three']; //errors array from the response of AJAX request
var arrayOfErrorsToDisplay = []; //initialize the errors to display with the plugin

$.each(errors, function (i, error) {
    arrayOfErrorsToDisplay.push({ title: 'Error!', text: error }); //add each error to the array
});

Swal.mixin({
  confirmButtonText: 'Next &rarr;',
  showCancelButton: true,
  progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay) //we pass the array of errors to display to the queue
.then((result) => { //here you can set your own preferences for what to do when user clicks on OK, I just took the basic example for the plugin's documentation
  if (result.value) {
    Swal({
      title: 'All errors have been shown!',
      html:
        'Your answers: <pre><code>' +
          JSON.stringify(result.value) +
        '</code></pre>',
      confirmButtonText: 'Done!'
    })
  }
});

Working snippet below :

var errors = ['error one', 'error two', 'error three'];
var arrayOfErrorsToDisplay = [];

$.each(errors, function (i, error) {
 arrayOfErrorsToDisplay.push({ title: 'Error!', text: error });
});

Swal.mixin({
  confirmButtonText: 'Next &rarr;',
  showCancelButton: true,
  progressSteps: ['1', '2', '3']
})
.queue(arrayOfErrorsToDisplay)
.then((result) => {
  if (result.value) {
    Swal({
      title: 'All errors have been shown!',
      html:
        'Your answers: <pre><code>' +
          JSON.stringify(result.value) +
        '</code></pre>',
      confirmButtonText: 'Done!'
    })
  }
});

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.all.min.js"></script>


问:
How can I update/refresh Google MDL elements that I add to my page dynamically?
I'm working with Google Material Design components which are stripped down for simplicity, then rendered more fully when the page is loaded. Simplified below to illustrate the issue:

What shows in the index.html file:

What renders to the DOM when the page is loaded:

```<code><div class="switch">
   <div class="switch_track"></div>
   <div class="switch_thumb"></div>
</div>
</code>```

I am creating a drag and drop HTML editor and have template files for each component type. The template file for a switch is simply:

switch.html

The problem is when I drag this to the canvas. jQuery looks at switch.html and renders

 to the DOM, but since it was dynamically added, it is not being "seen" by the scripts that added the additional track and thumb tags.

How can I fix this issue so that whenever the DOM is updated, it reruns any scripts? Ideally I would like to avoid touching any of the Material Design script files.

答:
You can use the  componentHandler.upgradeDom(); for dynamically upgrade the element or use the following lines for downgrade the existing element and upgrade it again

Type 1:

```<code>   $(".data").find(".is-upgraded").each(function(){
       $(this).removeAttr("data-upgraded").find(".mdl-switch__ripple-container,.mdl-switch__track").remove();  //downgrade the existing upgraded elements
   });
    componentHandler.upgradeDom(); // upgrade the elements
</code>```

Type 2:

```<code> $(".data").html("{{content}}").promise().done(function(){
           componentHandler.upgradeDom(); // upgrade the newest elements
 });
</code>```

Body:
I'm working with Google Material Design components which are stripped down for simplicity, then rendered more fully when the page is loaded. Simplified below to illustrate the issue:

What shows in the index.html file:

What renders to the DOM when the page is loaded:

I am creating a drag and drop HTML editor and have template files for each component type. The template file for a switch is simply:

switch.html

The problem is when I drag this to the canvas. jQuery looks at switch.html and renders

 to the DOM, but since it was dynamically added, it is not being "seen" by the scripts that added the additional track and thumb tags.

How can I fix this issue so that whenever the DOM is updated, it reruns any scripts? Ideally I would like to avoid touching any of the Material Design script files.

Body:
You can use the  componentHandler.upgradeDom(); for dynamically upgrade the element or use the following lines for downgrade the existing element and upgrade it again

Type 1:

   $(".data").find(".is-upgraded").each(function(){
       $(this).removeAttr("data-upgraded").find(".mdl-switch__ripple-container,.mdl-switch__track").remove();  //downgrade the existing upgraded elements
   });
    componentHandler.upgradeDom(); // upgrade the elements

Type 2:

 $(".data").html("{{content}}").promise().done(function(){
           componentHandler.upgradeDom(); // upgrade the newest elements
 });


问:
Footer issue using flexlayout
using flexlayout in my project, footer not render properly

scenario:
if there is no text then footer should be stick in bottom of screen, if more then screen content then footer should be push to bottom of screen.

below is my code:

```<code><mat-sidenav-container fxLayout="column" fxFlexFill>
   <mat-sidenav></mat-sidenav>
   <mat-sidenav-content>
     <header>
       <mat-toolbar></mat-toolbar>
     </header>
     <section fxFlexFill>
       <!--Content Area -->
     </section>
     <footer>
        <mat-toolbar></mat-toolbar>
     </footer>
   </mat-sidenav-content>
</mat-sidenav-container>
</code>```

above code taking extra space in footer its mean appearing scroll bar even though less content. can suggest what i missed here.

Using css

```<code>body,html{
height:100%;
}
</code>```

答:
Here is a solution in few lines:

app.component.html:

```<code><div fxLayout="column" fxFlexFill>
    <app-header></app-header> // your header
    <div fxFlex>
        <router-outlet></router-outlet> // your content
    </div>
    <app-footer></app-footer> // your footer
</div>
</code>```

styles.css:

```<code>html, body {
    height: 100%;
    box-sizing: border-box;
    margin: 0;
}
</code>```

Another alternative if you prefer to fill the footer instead of your content:

app.component.html:

```<code><div fxLayout="column" style="height: 100%;">
    <app-header></app-header> // your header
    <router-outlet></router-outlet> // your content
    <app-footer fxFlexOffset="auto"></app-footer> // your footer
</div>
</code>```

styles.css:

```<code>html, body {
    height: 100%;
}
</code>```

Title: Footer issue using flexlayout

Body:
using flexlayout in my project, footer not render properly

scenario:
if there is no text then footer should be stick in bottom of screen, if more then screen content then footer should be push to bottom of screen.

below is my code:

<mat-sidenav-container fxLayout="column" fxFlexFill>
   <mat-sidenav></mat-sidenav>
   <mat-sidenav-content>

       <mat-toolbar></mat-toolbar>

        <mat-toolbar></mat-toolbar>

   </mat-sidenav-content>
</mat-sidenav-container>

above code taking extra space in footer its mean appearing scroll bar even though less content. can suggest what i missed here.

Using css

body,html{
height:100%;
}

Body:
Here is a solution in few lines:

app.component.html:

<div fxLayout="column" fxFlexFill>
    <app-header></app-header> // your header
    <div fxFlex>
        <router-outlet></router-outlet> // your content
    </div>
    <app-footer></app-footer> // your footer
</div>

styles.css:

html, body {
    height: 100%;
    box-sizing: border-box;
    margin: 0;
}

Another alternative if you prefer to fill the footer instead of your content:

app.component.html:

<div fxLayout="column" style="height: 100%;">
    <app-header></app-header> // your header
    <router-outlet></router-outlet> // your content
    <app-footer fxFlexOffset="auto"></app-footer> // your footer
</div>

styles.css:

html, body {
    height: 100%;
}


问:
How to draw axis in the beggining of the system of equations in R
I would like to draw X and Y axis in the beggining of the system of equations, but i don't know how. When i'm trying to set axis it always putting them under the plotted function.

pi=3.141592
x= seq(-pi,pi,0.1)
plot(x,sin(x), axes=FALSE)
axis (1,-3:3)

I don't wanna put simple lines, because i wanna have values in those axis, and would like to change those values.

答:
Alright!

I get it, to draw Y axis in 0 position i need to add

axis(4, labels=TRUE, pos=0)

after plotting, thanks buddy!
No problem!


问:
Precompiled Multi-Dimensional Array Access
Imagine calculating a three dimensional array like this:

```<code>for (int i = 0; i < I; i++)
{
    for (int j = 0; j < J; j++)
    {
        for (int k = 0; k < K; k++)
        {
            array[k + j * K + i * K * J] = someValue(i, j, k);
        }
    }
}
</code>```

But the k + j * K + i * K * J part is kinda expensive. Is it possible to tell the compiler to convert the loops into something like this?

```<code>array[0] = someValue(0, 0, 0);
array[1] = someValue(0, 0, 1);
array[2] = someValue(0, 0, 2);
array[3] = someValue(0, 1, 0);
...
</code>```

This would ofcourse make the binaries larger, but would also speed up performance, if this code is executed a lot. Is it possible to do this? Or would I have to generate the code myself and paste it into the source file?

答:
I believe in your particular case, we can re-write the loop as:

```<code>auto* scan = array;
for (int i = 0; i < I; i++)
{
    for (int j = 0; j < J; j++)
    {
        for (int k = 0; k < K; k++)
        {
            *scan++ = someValue(i, j, k);
        }
    }
}
</code>```

This is a micro-optimization, and not something you usually have to worry about. Here's why.

Reason 1: integer multiplication is incredibly cheap. Calculating k + j * K + i * K * J is cheaper than retrieving a value from the computer's RAM, and it'll be about as cheap as (if not cheaper than) retrieving it from the CPU's fastest cache.

Reason 2: Compilers are incredibly smart. They can recognize which values change and which values stay the same, and optimize common sub-expressions out of loops (so that they're not performing the same computation multiple times).

Reason 3: Compilers are capable of taking advantage of vectorization instructions. Depending on what someValue does, it may be able to compute multiple values in parallel on the same core by taking advantage of this. This is true for either method of indexing into array.

C++ code isn't strictly imperative. Compilers can and do make major and complex optimizations to make code more efficient, and code like the one in your example are easy for them to optimize.

Body:
Imagine calculating a three dimensional array like this:

for (int i = 0; i < I; i++)
{
    for (int j = 0; j < J; j++)
    {
        for (int k = 0; k < K; k++)
        {
            array[k + j * K + i * K * J] = someValue(i, j, k);
        }
    }
}

But the k + j * K + i * K * J part is kinda expensive. Is it possible to tell the compiler to convert the loops into something like this?

array[0] = someValue(0, 0, 0);
array[1] = someValue(0, 0, 1);
array[2] = someValue(0, 0, 2);
array[3] = someValue(0, 1, 0);
...

This would ofcourse make the binaries larger, but would also speed up performance, if this code is executed a lot. Is it possible to do this? Or would I have to generate the code myself and paste it into the source file?

Body:
I believe in your particular case, we can re-write the loop as:

auto* scan = array;
for (int i = 0; i < I; i++)
{
    for (int j = 0; j < J; j++)
    {
        for (int k = 0; k < K; k++)
        {
            *scan++ = someValue(i, j, k);
        }
    }
}

This is a micro-optimization, and not something you usually have to worry about. Here's why.

Reason 1: integer multiplication is incredibly cheap. Calculating k + j * K + i * K * J is cheaper than retrieving a value from the computer's RAM, and it'll be about as cheap as (if not cheaper than) retrieving it from the CPU's fastest cache.

Reason 2: Compilers are incredibly smart. They can recognize which values change and which values stay the same, and optimize common sub-expressions out of loops (so that they're not performing the same computation multiple times).

Reason 3: Compilers are capable of taking advantage of vectorization instructions. Depending on what someValue does, it may be able to compute multiple values in parallel on the same core by taking advantage of this. This is true for either method of indexing into array.

C++ code isn't strictly imperative. Compilers can and do make major and complex optimizations to make code more efficient, and code like the one in your example are easy for them to optimize.


问:
FontAwesome Icons in Angular 6?
I'm trying to use icons from FontAwesome in an Angular project.

I started with the "Getting Started" guide you can find here: FontAwesome Angular Getting Started

Everything works fine, i can see the faCoffee icon wherever i put it in my templates. But if I try to change it to another icon (ex. the "check" icon), nothing is shown.

I changed my icon declaration at component-level to make it look like this:

```<code>import { faCheck } from '@fortawesome/free-solid-svg-icons';
</code>```

Changed the html template to show my new icon:

```<code><fa-icon [icon]="faCheck"></fa-icon>
</code>```

Then the icon field assignment in my component:

```<code>faCheck = faCheck;
</code>```

Please note that i'm changing essentially only the name of the icon from the examples that i tested and are working at the Url i posted above. Even if I go to the definition of "faCheck" on my declaration, i see that it's defined so I expect it to be available.

Chrome console shows this error when page is loading:

FontAwesome: Could not find icon. It looks like you've provided a null or undefined icon object to this component.

First attempt to use FontAwesome in my projects, useful general informations are welcome.

UPDATE: Got it working rebuilding my entire application. I was using VS Code, so when you save a file he tries to recreate the final bundle to let you navigate and check your development. I don't know what really happens with components in-memory state. I think the icon was not showing because of some misalignment of references.

答:
1- Install this npm install @fortawesome/fontawesome-free

2- Add this to angular.json (angular-cli.json)

```<code>"styles": [
    "...",
    "./node_modules/@fortawesome/fontawesome-free/css/all.min.css"
]
</code>```

3- Now you can use fonts with  tag

Title: FontAwesome Icons in Angular 6?

Body:
I'm trying to use icons from FontAwesome in an Angular project.

I started with the "Getting Started" guide you can find here: FontAwesome Angular Getting Started

Everything works fine, i can see the faCoffee icon wherever i put it in my templates. But if I try to change it to another icon (ex. the "check" icon), nothing is shown.

I changed my icon declaration at component-level to make it look like this:

import { faCheck } from '@fortawesome/free-solid-svg-icons';

Changed the html template to show my new icon:

<fa-icon [icon]="faCheck"></fa-icon>

Then the icon field assignment in my component:

faCheck = faCheck;

Please note that i'm changing essentially only the name of the icon from the examples that i tested and are working at the Url i posted above. Even if I go to the definition of "faCheck" on my declaration, i see that it's defined so I expect it to be available.

Chrome console shows this error when page is loading:

FontAwesome: Could not find icon. It looks like you've provided a null or undefined icon object to this component.

First attempt to use FontAwesome in my projects, useful general informations are welcome.

UPDATE: Got it working rebuilding my entire application. I was using VS Code, so when you save a file he tries to recreate the final bundle to let you navigate and check your development. I don't know what really happens with components in-memory state. I think the icon was not showing because of some misalignment of references.

Body:
1- Install this npm install @fortawesome/fontawesome-free

2- Add this to angular.json (angular-cli.json)

"styles": [
    "...",
    "./node_modules/@fortawesome/fontawesome-free/css/all.min.css"
]

3- Now you can use fonts with <i> tag