问:
Target Encoding : Fill NaN generated in expanding mean encoded values
I am working on multi-class classification problem having five classes in the target column. I have generated features for categorical variables using expanding mean encoding(Target encoding). The method is based on encoding categorical variable values with mean of target variable per value.

This also results in some NaN values like in 'Transaction-Type_mean_target' column.

What is the best way to fill these NaN values? Should I fill
these with the column mean.

How do I generate mean encoding for my test data as the
target/Dependent variable 'Complaint-Status' is not present?

Input data :

Generating mean encoding :

```<code>def add_feat_mean_encoding(col_list):
    """
        Expanding mean encoding
    """
    for i in col_list:
        cumsum = train.groupby(i)['Complaint-Status'].cumsum() - train['Complaint-Status']
        cumcnt = train.groupby(i).cumcount()
        train[i+'_mean_target'] = cumsum/cumcnt

cat_var = ['Transaction-Type','Complaint-reason','Company-response','Consumer-disputes']
add_feat_mean_encoding(cat_var)
</code>```

答:
If your features are categorical, imputing with mean does not make sense, at least it means that you create a new value for Nans. is that what you want ?

In order  to answer your questions :

For categorical features, you may try different ways. You may start with SimpleImputer of scikit (see here), try for example :

FILL_VALUE=100
imp_1 = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
imp_2 = SimpleImputer(missing_values=np.nan, strategy='constant', fille_value=FILL_VALUE)
```

Please provide information on your testset : which are the features ? If you do not have the feature Complaint-Status in the testset, there are two ways :

You can predict the feature Complaint-Status, for the test set, using the training set (and the feature you wish to predict, Complaint-Status, as Y). Try different classifiers and choose the one which provides the best result.

You can also use a 2 dimension Y, with your actual Y + Complaint-Status.

Body:
I am working on multi-class classification problem having five classes in the target column. I have generated features for categorical variables using expanding mean encoding(Target encoding). The method is based on encoding categorical variable values with mean of target variable per value.

This also results in some NaN values like in 'Transaction-Type_mean_target' column.

What is the best way to fill these NaN values? Should I fill
these with the column mean.

How do I generate mean encoding for my test data as the
target/Dependent variable 'Complaint-Status' is not present?

Input data :

Generating mean encoding :

def add_feat_mean_encoding(col_list):
    """
        Expanding mean encoding
    """
    for i in col_list:
        cumsum = train.groupby(i)['Complaint-Status'].cumsum() - train['Complaint-Status']
        cumcnt = train.groupby(i).cumcount()
        train[i+'_mean_target'] = cumsum/cumcnt

cat_var = ['Transaction-Type','Complaint-reason','Company-response','Consumer-disputes']
add_feat_mean_encoding(cat_var)

Body:
If your features are categorical, imputing with mean does not make sense, at least it means that you create a new value for Nans. is that what you want ?

In order  to answer your questions :

For categorical features, you may try different ways. You may start with SimpleImputer of scikit (see here), try for example :

FILL_VALUE=100
imp_1 = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
imp_2 = SimpleImputer(missing_values=np.nan, strategy='constant', fille_value=FILL_VALUE)

Please provide information on your testset : which are the features ? If you do not have the feature Complaint-Status in the testset, there are two ways :

You can predict the feature Complaint-Status, for the test set, using the training set (and the feature you wish to predict, Complaint-Status, as Y). Try different classifiers and choose the one which provides the best result.

You can also use a 2 dimension Y, with your actual Y + Complaint-Status.


来源: stackexchange

问:
Pass through folder with any specific pattern
I have a batch script that would only copy pdf file, based on the user inputted code. As soon as they hit enter it will look for a folder that has same filename with the inputted code.. then if exist it will copy the pdf inside..

Now I'm having a problem because in one sub-folder, it's file name doesn't have standard filename.

Like for ex : sometimes its filename is UV DATA others is UV-DATA , UV

example folder structure storage for the pdf file :

```<code>server
'----22050-022
     '----Folder1
               22050-022-DATA.pdf
</code>```

example folder destination :

```<code>server2
'----Folder
     '----22050-022
          '----UV DATA
               '----DOCUMENTS
</code>```

The UV DATA folder is the only one is changing..
How can I set only only UV and second word is any specific pattern?

Sample XCopy if it is a static code and make default file name is UV DATA:

```<code>set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV DATA\DOCUMENTS\" /D /E /C /I /Y /H
</code>```

I only tried something like this but doesn't work:

```<code>set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV*.*\DOCUMENTS\" /D /E /C /I /Y /H
</code>```

答:
Give this a go. You need to setup the source and the destination paths below to ensure you have the best level to search, but as dir /s is used, you can go to the lowest level of both source and destination paths:

```<code>@echo off
:start
set /p "code=Input Control Number: "
set "source=%HOMEPATH%\%code%"
set "destination=%HOMEPATH%\folder"
if "%code%" == "" echo Please input a valid Control number & goto start
for /f "delims=" %%i in ('dir /b /a-d /s "%source%" ^| findstr /i "%code%" ^| findstr /i "pdf"') do for /f "delims=" %%a in ('dir /b /s /ad "%destination%" ^| findstr /i "%code%" ^| findstr /i "UV" ^| findstr /i "Documents"') do (
    echo "%%a"
    echo xcopy "%%~i" "%%~a" "/D /E /C /I /Y /H
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a batch script that would only copy pdf file, based on the user inputted code. As soon as they hit enter it will look for a folder that has same filename with the inputted code.. then if exist it will copy the pdf inside..

Now I'm having a problem because in one sub-folder, it's file name doesn't have standard filename.

Like for ex : sometimes its filename is UV DATA others is UV-DATA , UV

example folder structure storage for the pdf file :

server
'----22050-022
     '----Folder1
               22050-022-DATA.pdf

example folder destination :

server2
'----Folder
     '----22050-022
          '----UV DATA
               '----DOCUMENTS

The UV DATA folder is the only one is changing..
How can I set only only UV and second word is any specific pattern?

Sample XCopy if it is a static code and make default file name is UV DATA:

set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV DATA\DOCUMENTS\" /D /E /C /I /Y /H

I only tried something like this but doesn't work:

set /p code=Input Control Number:

xcopy "%MySetPath%\Folder\%code%\%code%-DATA.pdf" "%MySetDestination%\Folder1\%code%\UV*.*\DOCUMENTS\" /D /E /C /I /Y /H

Body:
Give this a go. You need to setup the source and the destination paths below to ensure you have the best level to search, but as dir /s is used, you can go to the lowest level of both source and destination paths:

@echo off
:start
set /p "code=Input Control Number: "
set "source=%HOMEPATH%\%code%"
set "destination=%HOMEPATH%\folder"
if "%code%" == "" echo Please input a valid Control number & goto start
for /f "delims=" %%i in ('dir /b /a-d /s "%source%" ^| findstr /i "%code%" ^| findstr /i "pdf"') do for /f "delims=" %%a in ('dir /b /s /ad "%destination%" ^| findstr /i "%code%" ^| findstr /i "UV" ^| findstr /i "Documents"') do (
    echo "%%a"
    echo xcopy "%%~i" "%%~a" "/D /E /C /I /Y /H
)


问:
Edit the default login.html felogin plugin in my own fluid extension
I use typo 10 and add the Felogin extension, but I want to customize / edit the login template as I want it in my own fluid extension

I have tried adding

```<code>plugin.tx_felogin_pi1 {
  templateFile = EXT: my_extension/Resources/Private/Templates/Pages/Login.html
}
</code>```

but instead the default template appears. is there still less code?

答:
first, you need to look if the feature toggle is set correctly.
If you activated "Extbase" for felogin, the customization is done different (with plugin.xxx.view.templateRootpaths like in other Extbase/Fluid extensions).

Just take a look at the TypoScript code of Fluid and the small documentation of the change: https://docs.typo3.org/c/typo3/cms-core/master/en-us/Changelog/10.2/Feature-88102-FrontendLoginViaFluidAndExtbase.html

Body:
I use typo 10 and add the Felogin extension, but I want to customize / edit the login template as I want it in my own fluid extension

I have tried adding

plugin.tx_felogin_pi1 {
  templateFile = EXT: my_extension/Resources/Private/Templates/Pages/Login.html
}

but instead the default template appears. is there still less code?


问:
Create table - Mysql
I'm looking for a little help with this table.  First:  The table isn't being accepted by mysql. I'm getting a 150 error, which doesn't tell me much.  Second, I'm very certain that I'm not using the best data types & way to go about things.... please give me a little input!  </p>

```<code>CREATE  TABLE IF NOT EXISTS `axis`.`Employee` (
`idEmployee` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`idAccount` INT(10) UNSIGNED NOT NULL ,
`user` VARCHAR(45) NULL DEFAULT NULL ,
`pass` VARCHAR(45) NULL DEFAULT NULL ,
`firstName` VARCHAR(45) NULL DEFAULT NULL ,
`lastName` VARCHAR(45) NULL DEFAULT NULL ,
`middleName` VARCHAR(45) NULL DEFAULT NULL ,
`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCompany` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idLocation` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idUnit` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCrew` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idPosition` INT(10) UNSIGNED NULL DEFAULT NULL ,
`officeLoc` VARCHAR(45) NULL DEFAULT NULL ,
`wPhone` VARCHAR(12) NULL DEFAULT NULL ,
`wCell` VARCHAR(12) NULL DEFAULT NULL ,
`wFax` VARCHAR(12) NULL DEFAULT NULL ,
`wEmail` VARCHAR(45) NULL DEFAULT NULL ,
`radio` VARCHAR(12) NULL DEFAULT NULL ,
`hPhone` VARCHAR(12) NULL DEFAULT NULL ,
`hCell` VARCHAR(12) NULL DEFAULT NULL ,
`hEmail` VARCHAR(45) NULL DEFAULT NULL ,
`addrOne` VARCHAR(45) NULL DEFAULT NULL ,
`addrTwo` VARCHAR(45) NULL DEFAULT NULL ,
`city` VARCHAR(45) NULL DEFAULT NULL ,
`state` VARCHAR(45) NULL DEFAULT NULL ,
`zip` VARCHAR(10) NULL DEFAULT NULL ,
`emergContact` VARCHAR(45) NULL DEFAULT NULL ,
`emergPhone` VARCHAR(12) NULL DEFAULT NULL ,
`gender` ENUM('male','female') NULL DEFAULT NULL ,
`birthDate` DATE NULL DEFAULT NULL ,
`ssn` VARCHAR(5) NULL DEFAULT NULL ,
`hireDate` DATE NULL DEFAULT NULL ,
`sepDate` DATE NULL DEFAULT NULL ,
`comment` VARCHAR(255) NULL DEFAULT NULL ,
`photo` MEDIUMBLOB NULL DEFAULT NULL ,
`isActive` BIT(1) NOT NULL DEFAULT 1 ,
`allowLogin` BIT(1) NOT NULL DEFAULT 0 ,
`trackTravel` BIT(1) NOT NULL DEFAULT 1 ,
`trackTimesheet` BIT(1) NOT NULL DEFAULT 1 ,
`defFltArr` VARCHAR(10) NULL DEFAULT NULL ,
`defFltDep` VARCHAR(10) NULL DEFAULT NULL ,
`defDayTimeStart` TIME NOT NULL DEFAULT '06:00:00' ,
`defHoursPerDay` DECIMAL(4,2) NOT NULL DEFAULT '11.50' ,
`userType` ENUM('root','admin','view','acl','report','employee') NOT NULL DEFAULT 'employee',
`created` DATETIME NOT NULL ,
`modified` TIMESTAMP NOT NULL ,
`modifiedBy` INT(10) UNSIGNED NULL DEFAULT NULL ,
PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, `idCompany`, `idLocation`, `idUnit`, `idCrew`, `idPosition`, `modifiedBy`) ,
UNIQUE INDEX `UNIQUE` (`idEmployee` ASC) ,
INDEX `fk_Employee_Grp` (`idGrp` ASC) ,
INDEX `fk_Employee_Company` (`idCompany` ASC) ,
INDEX `fk_Employee_Unit` (`idUnit` ASC) ,
INDEX `fk_Employee_Location` (`idLocation` ASC) ,
INDEX `fk_Employee_Crew` (`idCrew` ASC) ,
INDEX `fk_Employee_Position` (`idPosition` ASC) ,
INDEX `fk_Employee_Employee` (`modifiedBy` ASC) ,
CONSTRAINT `fk_Employee_Grp`
FOREIGN KEY (`idGrp` )
REFERENCES `axis`.`Grp` (`idGrp` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Company`
FOREIGN KEY (`idCompany` )
REFERENCES `axis`.`Company` (`idCompany` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Unit`
FOREIGN KEY (`idUnit` )
REFERENCES `axis`.`Unit` (`idUnit` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Location`
FOREIGN KEY (`idLocation` )
REFERENCES `axis`.`Location` (`idLocation` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Crew`
FOREIGN KEY (`idCrew` )
REFERENCES `axis`.`Crew` (`idCrew` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Position`
FOREIGN KEY (`idPosition` )
REFERENCES `axis`.`Position` (`idPosition` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Employee`
FOREIGN KEY (`modifiedBy` )
REFERENCES `axis`.`Employee` (`idEmployee` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci
</code>```

答:
One of many mistakes :

```<code>`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL`
</code>```

then

```<code>PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, ... )
</code>```

(Column that is part of PRIMARY KEY must be NOT NULL - mysql silently makes it not null,
finally

```<code>CONSTRAINT `fk_Employee_Grp` FOREIGN KEY (`idGrp` )
 REFERENCES `axis`.`Grp` (`idGrp` ) ON DELETE SET NULL ON UPDATE CASCADE
</code>```

(which is impossible - ON DELETE SET NULL - column is not null.

And why do you create composite key at all? auto_increment column uniquely identifies your record. All other stuff is redundant. It might possible make sense in some cases for MyIsam tables (I would not recommend to use it anyway), because a value for auto_increment column will be generated differently if it's a part of composite index , but not for INNODB engine.

ContentLicense: CC BY-SA 3.0

Title: Create table - Mysql

Body:
I'm looking for a little help with this table.  First:  The table isn't being accepted by mysql. I'm getting a 150 error, which doesn't tell me much.  Second, I'm very certain that I'm not using the best data types & way to go about things.... please give me a little input!

CREATE  TABLE IF NOT EXISTS `axis`.`Employee` (
`idEmployee` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT ,
`idAccount` INT(10) UNSIGNED NOT NULL ,
`user` VARCHAR(45) NULL DEFAULT NULL ,
`pass` VARCHAR(45) NULL DEFAULT NULL ,
`firstName` VARCHAR(45) NULL DEFAULT NULL ,
`lastName` VARCHAR(45) NULL DEFAULT NULL ,
`middleName` VARCHAR(45) NULL DEFAULT NULL ,
`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCompany` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idLocation` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idUnit` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idCrew` INT(10) UNSIGNED NULL DEFAULT NULL ,
`idPosition` INT(10) UNSIGNED NULL DEFAULT NULL ,
`officeLoc` VARCHAR(45) NULL DEFAULT NULL ,
`wPhone` VARCHAR(12) NULL DEFAULT NULL ,
`wCell` VARCHAR(12) NULL DEFAULT NULL ,
`wFax` VARCHAR(12) NULL DEFAULT NULL ,
`wEmail` VARCHAR(45) NULL DEFAULT NULL ,
`radio` VARCHAR(12) NULL DEFAULT NULL ,
`hPhone` VARCHAR(12) NULL DEFAULT NULL ,
`hCell` VARCHAR(12) NULL DEFAULT NULL ,
`hEmail` VARCHAR(45) NULL DEFAULT NULL ,
`addrOne` VARCHAR(45) NULL DEFAULT NULL ,
`addrTwo` VARCHAR(45) NULL DEFAULT NULL ,
`city` VARCHAR(45) NULL DEFAULT NULL ,
`state` VARCHAR(45) NULL DEFAULT NULL ,
`zip` VARCHAR(10) NULL DEFAULT NULL ,
`emergContact` VARCHAR(45) NULL DEFAULT NULL ,
`emergPhone` VARCHAR(12) NULL DEFAULT NULL ,
`gender` ENUM('male','female') NULL DEFAULT NULL ,
`birthDate` DATE NULL DEFAULT NULL ,
`ssn` VARCHAR(5) NULL DEFAULT NULL ,
`hireDate` DATE NULL DEFAULT NULL ,
`sepDate` DATE NULL DEFAULT NULL ,
`comment` VARCHAR(255) NULL DEFAULT NULL ,
`photo` MEDIUMBLOB NULL DEFAULT NULL ,
`isActive` BIT(1) NOT NULL DEFAULT 1 ,
`allowLogin` BIT(1) NOT NULL DEFAULT 0 ,
`trackTravel` BIT(1) NOT NULL DEFAULT 1 ,
`trackTimesheet` BIT(1) NOT NULL DEFAULT 1 ,
`defFltArr` VARCHAR(10) NULL DEFAULT NULL ,
`defFltDep` VARCHAR(10) NULL DEFAULT NULL ,
`defDayTimeStart` TIME NOT NULL DEFAULT '06:00:00' ,
`defHoursPerDay` DECIMAL(4,2) NOT NULL DEFAULT '11.50' ,
`userType` ENUM('root','admin','view','acl','report','employee') NOT NULL DEFAULT 'employee',
`created` DATETIME NOT NULL ,
`modified` TIMESTAMP NOT NULL ,
`modifiedBy` INT(10) UNSIGNED NULL DEFAULT NULL ,
PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, `idCompany`, `idLocation`, `idUnit`, `idCrew`, `idPosition`, `modifiedBy`) ,
UNIQUE INDEX `UNIQUE` (`idEmployee` ASC) ,
INDEX `fk_Employee_Grp` (`idGrp` ASC) ,
INDEX `fk_Employee_Company` (`idCompany` ASC) ,
INDEX `fk_Employee_Unit` (`idUnit` ASC) ,
INDEX `fk_Employee_Location` (`idLocation` ASC) ,
INDEX `fk_Employee_Crew` (`idCrew` ASC) ,
INDEX `fk_Employee_Position` (`idPosition` ASC) ,
INDEX `fk_Employee_Employee` (`modifiedBy` ASC) ,
CONSTRAINT `fk_Employee_Grp`
FOREIGN KEY (`idGrp` )
REFERENCES `axis`.`Grp` (`idGrp` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Company`
FOREIGN KEY (`idCompany` )
REFERENCES `axis`.`Company` (`idCompany` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Unit`
FOREIGN KEY (`idUnit` )
REFERENCES `axis`.`Unit` (`idUnit` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Location`
FOREIGN KEY (`idLocation` )
REFERENCES `axis`.`Location` (`idLocation` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Crew`
FOREIGN KEY (`idCrew` )
REFERENCES `axis`.`Crew` (`idCrew` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Position`
FOREIGN KEY (`idPosition` )
REFERENCES `axis`.`Position` (`idPosition` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `fk_Employee_Employee`
FOREIGN KEY (`modifiedBy` )
REFERENCES `axis`.`Employee` (`idEmployee` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci

Body:
One of many mistakes :

`idGrp` INT(10) UNSIGNED NULL DEFAULT NULL`

then

PRIMARY KEY (`idEmployee`, `idAccount`, `idGrp`, ... )

(Column that is part of PRIMARY KEY must be NOT NULL - mysql silently makes it not null,
finally

CONSTRAINT `fk_Employee_Grp` FOREIGN KEY (`idGrp` )
 REFERENCES `axis`.`Grp` (`idGrp` ) ON DELETE SET NULL ON UPDATE CASCADE

(which is impossible - ON DELETE SET NULL - column is not null.

And why do you create composite key at all? auto_increment column uniquely identifies your record. All other stuff is redundant. It might possible make sense in some cases for MyIsam tables (I would not recommend to use it anyway), because a value for auto_increment column will be generated differently if it's a part of composite index , but not for INNODB engine.


问:
Running a Kotlin application from a build.gradle.kt script
I have build.gradle.kts file, I am trying to define a task which will call a Kotlin function to load a SQL script.

```<code>tasks.register("dbTestDataLoader", JavaExec::class) {
    println("Running db test data")

    // starts postgresql service
    dependsOn("startPostgres")

    // run SQL
    main = "com.org.business.DbTestDataLoader"
}
</code>```

However this gives me an error:

Task :dbTestDataLoader FAILED
  Error: Could not find or load main class com.org.business.DbTestDataLoader

I've tried adding:

```<code>sourceSets["main"].withConvention(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::class) {
    kotlin.srcDir("src/main/kotlin")
}
</code>```

And I've tried using src.main.kotlin.com.business as the source, but either way I get the mentioned error.

This is my file structure:

```<code>application-name
    build.gradle.kts
    - src
        - main
            - kotlin
                - com
                    - org
                        - business
                            - DbTestDataLoader.kt
</code>```

Here is my DbTestDataLoader.kt file:

```<code>open class DbTestDataLoader {
    /*fun main(args : Array<String>) {
        println("hello world")
    }*/

    companion object {
        @JvmStatic
        open fun main(cmdArgs: Array<String>) {
            println("Hello World")
        }
    }
}
</code>```

Edit

Following the answer posted I placed the file inside build/src, but still get the same error.

So my layout not looks like this (.gradle and build were auto generated):

```<code>application-name
    buildSrc
        .gradle
        build
        DbTestDataLoader.kt
    src
        ...
</code>```

Here's the results when I add --stacktrace to the call:

```<code>> Task :dbTestDataLoader FAILED
Error: Could not find or load main class DbTestDataLoader

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':dbTestDataLoader'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_202\bin\java.exe'' finished with non-zero exit value 1

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':dbTestDataLoader'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:117)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:184)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ResolveIncrementalChangesTaskExecuter.execute(ResolveIncrementalChangesTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:74)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
        at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:46)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_202\bin\java.exe'' finished with non-zero exit value 1
        at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:396)
        at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:37)
        at org.gradle.api.tasks.JavaExec.exec(JavaExec.java:81)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:48)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:672)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$4.run(ExecuteActionsTaskExecuter.java:338)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:327)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:312)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:75)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:158)
        at org.gradle.internal.execution.impl.steps.ExecuteStep.execute(ExecuteStep.java:46)
        at org.gradle.internal.execution.impl.steps.CancelExecutionStep.execute(CancelExecutionStep.java:34)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:69)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.execute(TimeoutStep.java:49)
        at org.gradle.internal.execution.impl.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
        at org.gradle.internal.execution.impl.steps.CreateOutputsStep.execute(CreateOutputsStep.java:49)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:42)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:28)
        at org.gradle.internal.execution.impl.steps.CacheStep.executeWithoutCache(CacheStep.java:133)
        at org.gradle.internal.execution.impl.steps.CacheStep.lambda$execute$5(CacheStep.java:83)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:82)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:37)
        at org.gradle.internal.execution.impl.steps.PrepareCachingStep.execute(PrepareCachingStep.java:33)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:38)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:23)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:95)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:88)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
        at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:34)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:109)
        ... 37 more
</code>```

答:
The folder src/main/kotlin is meant for application code, that you want to build (jar, war or whatever)

Code that supports building or testing should be separated from application code, since you don't want to deliver it together with your actual artifact.

If you want to use kotlin code during the build (not merely compile or package it), place it under buildSrc/ as explained in the docs.

Body:
I have build.gradle.kts file, I am trying to define a task which will call a Kotlin function to load a SQL script.

tasks.register("dbTestDataLoader", JavaExec::class) {
    println("Running db test data")

    // starts postgresql service
    dependsOn("startPostgres")

    // run SQL
    main = "com.org.business.DbTestDataLoader"
}

However this gives me an error:

Task :dbTestDataLoader FAILED
  Error: Could not find or load main class com.org.business.DbTestDataLoader

I've tried adding:

sourceSets["main"].withConvention(org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet::class) {
    kotlin.srcDir("src/main/kotlin")
}

And I've tried using src.main.kotlin.com.business as the source, but either way I get the mentioned error.

This is my file structure:

application-name
    build.gradle.kts
    - src
        - main
            - kotlin
                - com
                    - org
                        - business
                            - DbTestDataLoader.kt

Here is my DbTestDataLoader.kt file:

open class DbTestDataLoader {
    /*fun main(args : Array<String>) {
        println("hello world")
    }*/

    companion object {
        @JvmStatic
        open fun main(cmdArgs: Array<String>) {
            println("Hello World")
        }
    }
}

Edit

Following the answer posted I placed the file inside build/src, but still get the same error.

So my layout not looks like this (.gradle and build were auto generated):

application-name
    buildSrc
        .gradle
        build
        DbTestDataLoader.kt
    src
        ...

Here's the results when I add --stacktrace to the call:

> Task :dbTestDataLoader FAILED
Error: Could not find or load main class DbTestDataLoader

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':dbTestDataLoader'.
> Process 'command 'C:\Program Files\Java\jdk1.8.0_202\bin\java.exe'' finished with non-zero exit value 1

* Try:
Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':dbTestDataLoader'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:121)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$2.accept(ExecuteActionsTaskExecuter.java:117)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:184)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:110)
        at org.gradle.api.internal.tasks.execution.ResolveIncrementalChangesTaskExecuter.execute(ResolveIncrementalChangesTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:91)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:74)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
        at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
        at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:63)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:46)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
        at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_202\bin\java.exe'' finished with non-zero exit value 1
        at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:396)
        at org.gradle.process.internal.DefaultJavaExecAction.execute(DefaultJavaExecAction.java:37)
        at org.gradle.api.tasks.JavaExec.exec(JavaExec.java:81)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:103)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:48)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:41)
        at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:705)
        at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:672)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$4.run(ExecuteActionsTaskExecuter.java:338)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
        at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:327)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:312)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$200(ExecuteActionsTaskExecuter.java:75)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:158)
        at org.gradle.internal.execution.impl.steps.ExecuteStep.execute(ExecuteStep.java:46)
        at org.gradle.internal.execution.impl.steps.CancelExecutionStep.execute(CancelExecutionStep.java:34)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:69)
        at org.gradle.internal.execution.impl.steps.TimeoutStep.execute(TimeoutStep.java:49)
        at org.gradle.internal.execution.impl.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
        at org.gradle.internal.execution.impl.steps.CreateOutputsStep.execute(CreateOutputsStep.java:49)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:42)
        at org.gradle.internal.execution.impl.steps.SnapshotOutputStep.execute(SnapshotOutputStep.java:28)
        at org.gradle.internal.execution.impl.steps.CacheStep.executeWithoutCache(CacheStep.java:133)
        at org.gradle.internal.execution.impl.steps.CacheStep.lambda$execute$5(CacheStep.java:83)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:82)
        at org.gradle.internal.execution.impl.steps.CacheStep.execute(CacheStep.java:37)
        at org.gradle.internal.execution.impl.steps.PrepareCachingStep.execute(PrepareCachingStep.java:33)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:38)
        at org.gradle.internal.execution.impl.steps.StoreSnapshotsStep.execute(StoreSnapshotsStep.java:23)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:95)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:88)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:52)
        at org.gradle.internal.execution.impl.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:36)
        at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:34)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:109)
        ... 37 more


问:
Navigating between two fragments on backpress
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

```<code>    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();
</code>```

In second Fragment i have implemented an interface OnBackpress and over riding the below method

```<code>@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}
</code>```

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

答:
You need to add you first fragment to back stack properly, you are doing it wrong in your first part of the code.
Use the following code instead.

```<code>    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.replace(android.R.id.content, frag, "UserActivity");
    transaction.commit();
</code>```

Also there is no need to add any code in your onBackPressed after above change.

Body:
I am having trouble going back to previous fragment on backpress from current fragment.
I have Two fragments and i navigate to second fragment on click and when i try to click back from the second fragment, i want to go back to the previous fragment but instead the app exits on backpress. below is the code i am using..

Fragment1 calling second fragment

    UserFragment frag = new UserFragment()
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        frag.setArguments(bundle);
        transaction.addToBackStack("UserActivity");
             transaction.replace(android.R.id.content, frag, "UserActivity").addToBackStack(null);
transaction.commit();

In second Fragment i have implemented an interface OnBackpress and over riding the below method

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() != 0) {
        if(getFragmentManager().findFragmentByTag("UserActivity") != null){
            Log.e("UserActivity",getFragmentManager().findFragmentByTag("UserActivity").toString());
            getFragmentManager().popBackStack();
        };
    }

}

But on back press the app exits. Instead i want to go back to previous fragment. What mistake am i doing? please help. thanks

Body:
You need to add you first fragment to back stack properly, you are doing it wrong in your first part of the code.
Use the following code instead.

    UserFragment frag = new UserFragment()
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    frag.setArguments(bundle);
    transaction.addToBackStack("UserActivity");
    transaction.replace(android.R.id.content, frag, "UserActivity");
    transaction.commit();

Also there is no need to add any code in your onBackPressed after above change.


问:
"Invalid platform app" error using Instagram Basic Display API
I am trying to use Instagram Basic display API but when I post the authorization code to get the access token I keep getting the following error

{"error_type": "OAuthException", "code": 400, "error_message":
"Invalid platform app"}

I am following all the steps mentioned here -> https://developers.facebook.com/docs/instagram-basic-display-api/getting-started and Yes I am using the Instagram app ID and It's client secret which is in Products -> Instagram -> Display and following is the URL I am sending the request

"https://api.instagram.com/oauth/access_token?client_id=".$app_id."&client_secret=".$app_secret."&grant_type=authorization_code&redirect_uri=".$redirecturi."&code=".$code,

答:
When you exchange the code you need to use a POST request.

From the looks of your url, you've formed it as a GET request with all the parameters as part of the url rather than as form data. Try sending the parameters as part of the post body instead


问:
NameError: name 'Model' is not defined after importing models in a newly created file
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this.

Here is a screenshot showing where the file is located.

Models

```<code>from django.utils import timezone
from django_smalluuid.models import SmallUUIDField, uuid_default
from django.db import models
import pytz
from .utilities import (calc_expiry_date,convert_date)
from monthdelta import monthdelta

class LiquorCostCentre(models.Model):
    cost_centre_id = models.CharField(max_length=250,null=True,blank=True,default="0304-05-05")
    cost_centre_name = models.CharField(max_length=250,null=True,blank=True)
</code>```

utilities.py

```<code>from .models import *

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill
</code>```

Error

```<code>eb_1         |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
web_1         |     __import__(module)
web_1         |   File "/app/core/wsgi.py", line 16, in <module>
web_1         |     application = get_wsgi_application()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
web_1         |     django.setup(set_prefix=False)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
web_1         |     apps.populate(settings.INSTALLED_APPS)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
web_1         |     app_config.import_models()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
web_1         |     self.models_module = import_module(models_module_name)
web_1         |   File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1         |     return _bootstrap._gcd_import(name[level:], package, level)
web_1         |   File "/app/liquor/models.py", line 10, in <module>
web_1         |     from .utilities import (calc_expiry_date,convert_date)
web_1         |   File "/app/liquor/utilities.py", line 2, in <module>
web_1         |     from liquor.models import LiquorCostCentre
web_1         | ImportError: cannot import name 'LiquorCostCentre' from 'liquor.models' (/app/liquor/models.py)
web_1         | [2020-02-17 11:19:23 +0300] [17] [INFO] Worker exiting (pid: 17)
web_1         | Sentry is attempting to send 0 pending error messages
web_1         | Waiting up to 2 seconds
web_1         | Press Ctrl-C to quit
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Shutting down: Master
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Reason: Worker failed to boot.
</code>```

答:
Issue is of circular import.

You are importing
from .utilities import (calc_expiry_date,convert_date) in models.py and then in utilities.py, you are importing

This is a classic case of circular import.

Solution is to import locally i.e

```<code>def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from models import LiquorCostCentre, LiqourBillTrack
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill
</code>```

Body:
I have created a file called utilities.py within a Django app but I'm getting errors after importing a model from the same app in the file. This is weird because the same file is within the app, I should not be getting that error. Please advise on this.

Here is a screenshot showing where the file is located.

Models

from django.utils import timezone
from django_smalluuid.models import SmallUUIDField, uuid_default
from django.db import models
import pytz
from .utilities import (calc_expiry_date,convert_date)
from monthdelta import monthdelta

class LiquorCostCentre(models.Model):
    cost_centre_id = models.CharField(max_length=250,null=True,blank=True,default="0304-05-05")
    cost_centre_name = models.CharField(max_length=250,null=True,blank=True)

utilities.py

from .models import *

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill

Error

eb_1         |   File "/usr/local/lib/python3.7/site-packages/gunicorn/util.py", line 350, in import_app
web_1         |     __import__(module)
web_1         |   File "/app/core/wsgi.py", line 16, in <module>
web_1         |     application = get_wsgi_application()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application
web_1         |     django.setup(set_prefix=False)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
web_1         |     apps.populate(settings.INSTALLED_APPS)
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/registry.py", line 112, in populate
web_1         |     app_config.import_models()
web_1         |   File "/usr/local/lib/python3.7/site-packages/django/apps/config.py", line 198, in import_models
web_1         |     self.models_module = import_module(models_module_name)
web_1         |   File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
web_1         |     return _bootstrap._gcd_import(name[level:], package, level)
web_1         |   File "/app/liquor/models.py", line 10, in <module>
web_1         |     from .utilities import (calc_expiry_date,convert_date)
web_1         |   File "/app/liquor/utilities.py", line 2, in <module>
web_1         |     from liquor.models import LiquorCostCentre
web_1         | ImportError: cannot import name 'LiquorCostCentre' from 'liquor.models' (/app/liquor/models.py)
web_1         | [2020-02-17 11:19:23 +0300] [17] [INFO] Worker exiting (pid: 17)
web_1         | Sentry is attempting to send 0 pending error messages
web_1         | Waiting up to 2 seconds
web_1         | Press Ctrl-C to quit
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Shutting down: Master
web_1         | [2020-02-17 11:19:26 +0300] [14] [INFO] Reason: Worker failed to boot.

Body:
Issue is of circular import.

You are importing
from .utilities import (calc_expiry_date,convert_date) in models.py and then in utilities.py, you are importing

This is a classic case of circular import.

Solution is to import locally i.e

def process_bill(bill_type, liquor_license, cost_centre, account_number_list, description, license_category,user,amount,schedule_type):
    from models import LiquorCostCentre, LiqourBillTrack
    cost_centre_obj, _ = LiquorCostCentre.objects.get_or_create(cost_centre_id=cost_centre)
    bill = LiqourBillTrack.objects.create(
        fee_choice=schedule_type,
        bill_type=bill_type,
        cost_centre=cost_centre_obj.cost_centre_id,
        balance=float(              amount),
        description=description,
        created_by=user,
        year=CURRENT_YEAR,
        liquor_license= liquor_license

    )
    [bill.accounts.add(account_number) for account_number in account_number_list]
    account_values = []
    account_list = bill.accounts.all()
    account_total = [account_values.append(acc_value.amount) for acc_value in account_list ]

    bill_total =sum(account_values)
    bill.total = bill_total
    bill.balance = bill_total
    bill.ref_no = 'LIQ-' + str(NOW.year) + str(NOW.month)+ str(bill.id)
    bill.bill_no = bill.ref_no
    bill.save()
    return bill


问:
how to make a method that push items to empty array with lit-element
I have an empty array with lit-element to add the ages between 2 to 13 years that I generate with a loop. I need to add each element within the array using a method but I don't know how to make it work. This is what I have:</p>

```<code>import { LitElement, html } from 'lit-element';

class ChildrenInput extends LitElement {
    static get properties() {
        return {
            ages: {type: Array},
        };
    }

    constructor() {
        super();
        this.minAge = 2;
        this.maxAge = 13;
        this.ages = [];
    }

    ages() {
        for (let age = this.minAge; age <= this.maxAge; age++) {
            this.ages.push(age);
        }
    }

    render(){
        return html`
            <div>
                <select>
                    <option selected>--</option>
                    <option>${this.ages.map(item => html`<li>${item}</li>`)}</option>
                </select>
            </div>
        `;
    }
}

customElements.define('children-input', ChildrenInput);
</code>```

答:
You first need to call your function, having given a different name from the array property, and use the option element in the loop mechanism as follows:

import { LitElement, html } from 'lit-element';

class ChildrenInput extends LitElement {
    static get properties() {
        return {
            ages: {type: Array},
        };
    }

    constructor() {
        super();
        this.minAge = 2;
        this.maxAge = 13;
        this.ages = [];
        this.loopAges();
    }

    loopAges() {
        for (let age = this.minAge; age <= this.maxAge; age++) {
            this.ages.push(age);
        }

        // Alternative syntax:
        // let age = this.minAge; while ( age <= this.maxAge ) this.ages.push( age++ );

    }

    render(){
        return html`

                <select>
                    <option selected>--</option>
                    ${this.ages.map(item => html`<option value="${item}">${item}</option>`)}
                </select>

        `;
    }
}

customElements.define('children-input', ChildrenInput);
```

Here's a working version

Body:
I have an empty array with lit-element to add the ages between 2 to 13 years that I generate with a loop. I need to add each element within the array using a method but I don't know how to make it work. This is what I have:

import { LitElement, html } from 'lit-element';

class ChildrenInput extends LitElement {
    static get properties() {
        return {
            ages: {type: Array},
        };
    }

    constructor() {
        super();
        this.minAge = 2;
        this.maxAge = 13;
        this.ages = [];
    }

    ages() {
        for (let age = this.minAge; age <= this.maxAge; age++) {
            this.ages.push(age);
        }
    }

    render(){
        return html`

                <select>
                    <option selected>--</option>
                    <option>${this.ages.map(item => html`<li>${item}</li>`)}</option>
                </select>

        `;
    }
}

customElements.define('children-input', ChildrenInput);

Body:
You first need to call your function, having given a different name from the array property, and use the option element in the loop mechanism as follows:

import { LitElement, html } from 'lit-element';

class ChildrenInput extends LitElement {
    static get properties() {
        return {
            ages: {type: Array},
        };
    }

    constructor() {
        super();
        this.minAge = 2;
        this.maxAge = 13;
        this.ages = [];
        this.loopAges();
    }

    loopAges() {
        for (let age = this.minAge; age <= this.maxAge; age++) {
            this.ages.push(age);
        }

        // Alternative syntax:
        // let age = this.minAge; while ( age <= this.maxAge ) this.ages.push( age++ );

    }

    render(){
        return html`
            <div>
                <select>
                    <option selected>--</option>
                    ${this.ages.map(item => html`<option value="${item}">${item}</option>`)}
                </select>
            </div>
        `;
    }
}

customElements.define('children-input', ChildrenInput);

Here's a working version


问:
How to query/scan a table in DynamoDB using AND and OR in the same statement using python?
I want to query a table on DynamoDB and using python. The thing with this query is that I want to use an AND and OR condition in the same query. I want the query to retrieve values from one column when the value is B or C.

I have the following table:

```<code>domain          validation_A        validation_B        validation_C
---------       -----------------   ---------------     ---------------
drene.com       pass                pass                pass
drene.com       pass                true                pass
drene.com       fail                pass                pass
</code>```

In regular SQL expression I will use:

```<code>Select *
from
    ValidationTable
where
    domain = 'drene.com' and
    validation_A = 'pass' and
    (validation_B = 'pass' or validation_B = 'true')
</code>```

I do not know how to do this in DynamoDB / Pythom

I tried the following:

```<code>response = table.scan(
                 IndexName="Date-index",
                 FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') || Attr('validation_B').eq('true'))
</code>```

)

But it is not working

I need the query bring me the first 2 rows.

答:
Use | instead of ||

```<code>response = table.scan(
                 IndexName="Date-index",
                 FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') | Attr('validation_B').eq('true'))
</code>```

Body:
I want to query a table on DynamoDB and using python. The thing with this query is that I want to use an AND and OR condition in the same query. I want the query to retrieve values from one column when the value is B or C.

I have the following table:

domain          validation_A        validation_B        validation_C
---------       -----------------   ---------------     ---------------
drene.com       pass                pass                pass
drene.com       pass                true                pass
drene.com       fail                pass                pass

In regular SQL expression I will use:

Select *
from
    ValidationTable
where
    domain = 'drene.com' and
    validation_A = 'pass' and
    (validation_B = 'pass' or validation_B = 'true')

I do not know how to do this in DynamoDB / Pythom

I tried the following:

response = table.scan(
                 IndexName="Date-index",
                 FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') || Attr('validation_B').eq('true'))

)

But it is not working

I need the query bring me the first 2 rows.

Body:
Use | instead of ||

response = table.scan(
                 IndexName="Date-index",
                 FilterExpression=Key('domain').eq('drene.com') & Attr('validation_A').eq('pass') & (Attr('validation_B').eq('pass') | Attr('validation_B').eq('true'))


问:
Update muliple column values based on condition in python
I have a dataframe like this,

```<code>ID    00:00  01:00  02:00  ...   23:00   avg_value
22      4.7     5.3     6   ...    8         5.5
37       0      9.2    4.5  ...    11.2      9.2
4469     2      9.8    11   ...    2         6.4
</code>```

Can I use np.where to apply conditions on multiple columns at once?
I want to update the values from 00:00 to 23:00 to 0 and 1. If the value at the time of day is greater than avg_value then I change it to 1, else to 0.

I know how to apply this method to one single column.

```<code>np.where(df['00:00']>df['avg_value'],1,0)
</code>```

Can I change it to multiple columns?

Output will be like,

```<code>ID    00:00  01:00  02:00  ...   23:00   avg_value
22      0     1       1    ...      1       5.5
37      0     0       0    ...      1       9.2
4469    0     1       1    ...      0       6.4
</code>```

答:
Select all columns without last by DataFrame.iloc, compare by DataFrame.gt and casting to integers and last add avg_value column by DataFrame.join:

```<code>df = df.iloc[:, :-1].gt(df['avg_value'], axis=0).astype(int).join(df['avg_value'])
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22        0      0      1      1        5.5
37        0      0      0      1        9.2
4469      0      1      1      0        6.4
</code>```

Or use DataFrame.pop for extract column:

```<code>s = df.pop('avg_value')
df = df.gt(s, axis=0).astype(int).join(s)
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22        0      0      1      1        5.5
37        0      0      0      1        9.2
4469      0      1      1      0        6.4
</code>```

Because if assign to same columns integers are converted to floats (it is bug):

```<code>df.iloc[:, :-1] = df.iloc[:, :-1].gt(df['avg_value'], axis=0).astype(int)
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22      0.0    0.0    1.0    1.0        5.5
37      0.0    0.0    0.0    1.0        9.2
4469    0.0    1.0    1.0    0.0        6.4
</code>```

Body:
I have a dataframe like this,

ID    00:00  01:00  02:00  ...   23:00   avg_value
22      4.7     5.3     6   ...    8         5.5
37       0      9.2    4.5  ...    11.2      9.2
4469     2      9.8    11   ...    2         6.4

Can I use np.where to apply conditions on multiple columns at once?
I want to update the values from 00:00 to 23:00 to 0 and 1. If the value at the time of day is greater than avg_value then I change it to 1, else to 0.

I know how to apply this method to one single column.

np.where(df['00:00']>df['avg_value'],1,0)

Can I change it to multiple columns?

Output will be like,

ID    00:00  01:00  02:00  ...   23:00   avg_value
22      0     1       1    ...      1       5.5
37      0     0       0    ...      1       9.2
4469    0     1       1    ...      0       6.4

Body:
Select all columns without last by DataFrame.iloc, compare by DataFrame.gt and casting to integers and last add avg_value column by DataFrame.join:

df = df.iloc[:, :-1].gt(df['avg_value'], axis=0).astype(int).join(df['avg_value'])
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22        0      0      1      1        5.5
37        0      0      0      1        9.2
4469      0      1      1      0        6.4

Or use DataFrame.pop for extract column:

s = df.pop('avg_value')
df = df.gt(s, axis=0).astype(int).join(s)
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22        0      0      1      1        5.5
37        0      0      0      1        9.2
4469      0      1      1      0        6.4

Because if assign to same columns integers are converted to floats (it is bug):

df.iloc[:, :-1] = df.iloc[:, :-1].gt(df['avg_value'], axis=0).astype(int)
print (df)
      00:00  01:00  02:00  23:00  avg_value
ID
22      0.0    0.0    1.0    1.0        5.5
37      0.0    0.0    0.0    1.0        9.2
4469    0.0    1.0    1.0    0.0        6.4


问:
Highlighting all match words TypeScript
Currently, I'm trying to implement highlighting on searched word in a text in my Angular project. I have the search operation as a separated component and I want to create a pipe that will highlight all the matches of the searched word in the text..

```<code>@Pipe({name: 'highlight'})
export class TextHighLightPipe implements PipeTransform {

 constructor(private _sanitizer: DomSanitizer) {
 }

 transform(text: any, search: string): SafeHtml {

 //takes care of any special characters
 if (search !== undefined && search !== null) {
   search = search.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
 }
 text += '';
 return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
   '<span style="background-color: yellow">' + `${search}` + '</span>') : text);
 }
}
</code>```

This code works fine but it replaces all the matches with the searched word, so in case that I have a word that starts with upper case, when I search it with lower case, the transform function will replace it will the lower case one, which is the actual problem..
For example:

Text to search in: This is just an example text of this code

Search word: this

Result: this is just an example text of this code

答:
I figured it out. So I only had to change this piece of code:

```<code>return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
  '<span style="background-color: yellow">' + `${search}` + '</span>') : text);
</code>```

}

To this:

```<code>return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(`(${search})`, 'gi'),
  '<span style="background-color: yellow">' + `$1` + '</span>') : text);
</code>```

Title: Highlighting all match words TypeScript

Body:
Currently, I'm trying to implement highlighting on searched word in a text in my Angular project. I have the search operation as a separated component and I want to create a pipe that will highlight all the matches of the searched word in the text..

@Pipe({name: 'highlight'})
export class TextHighLightPipe implements PipeTransform {

 constructor(private _sanitizer: DomSanitizer) {
 }

 transform(text: any, search: string): SafeHtml {

 //takes care of any special characters
 if (search !== undefined && search !== null) {
   search = search.toString().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
 }
 text += '';
 return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
   '' + `${search}` + '') : text);
 }
}

This code works fine but it replaces all the matches with the searched word, so in case that I have a word that starts with upper case, when I search it with lower case, the transform function will replace it will the lower case one, which is the actual problem..
For example:

Text to search in: This is just an example text of this code

Search word: this

Result: this is just an example text of this code

Body:
I figured it out. So I only had to change this piece of code:

return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(search, 'gi'),
  '<span style="background-color: yellow">' + `${search}` + '</span>') : text);

}

To this:

return this._sanitizer.bypassSecurityTrustHtml(search ? text.replace(new RegExp(`(${search})`, 'gi'),
  '<span style="background-color: yellow">' + `$1` + '</span>') : text);


问:
Java Stream filter - how can i filter data without wrapping the filter code in 'if' condition for checking null on the filtering keys?
I am doing the following:

```<code>List<Objects> filtered = objects.stream()
    .filter(o -> source.equals(o.getSource()) && date.equals(o.getDate()) && id.equals(o.getId()))
    .collect(Collectors.toList());
</code>```

where both date and id could possibiliy be null, as the are coming from method parameters.

How can I ignore them if null, without wrapping the above code in an if statement tp check 'id' and 'date' for null values ? I want to do it inside the filter.

Edit : To make it more clear, i want the filter to act only on the non-null values, i.e if date is non-null and id is null, then filter only on date and ignore id, and so on..

Thanks

答:
You could use the static method Objects::equals. Chances are that this method is designed for just this:

```<code>List<Objects> filtered = objects.stream()
    .filter(o -> Objects.equals(source, o.getSource()) && Objects.equals(date, o.getDate()) && Objects.equals(id, o.getId()))
    .collect(Collectors.toList());
</code>```

Note: as Scratte mentioned in the comments, this may not filter out objects for which getDate() returns null, if date is also null. Same goes for id. If that's the case, then the abovementioned code snippet does not comply. In that case, then we have to explicitly filter for non-null dates and ids:

```<code>.filter(o -> Objects.nonNull(o.getId()) && Objects.nonNull(o.getDate()))
</code>```

Update

If you want to skip the comparison for getDate() if date is null (and same for id), then you could check first for null, just like in ernest_k's answer.

You could easily build a small method for it:

```<code>public static boolean nullOrEquals(Object baseObject, Object compareObject) {
    return baseObject == null || Objects.equals(baseObject, compareObject);
}
</code>```

```<code>.filter(o -> Objects.equals(source, o.getSource())
    && nullOrEquals(date, o.getDate())
    && nullOrEquals(id, o.getId()))
</code>```

Here's an Ideone example.

Body:
I am doing the following:

List<Objects> filtered = objects.stream()
    .filter(o -> source.equals(o.getSource()) && date.equals(o.getDate()) && id.equals(o.getId()))
    .collect(Collectors.toList());

where both date and id could possibiliy be null, as the are coming from method parameters.

How can I ignore them if null, without wrapping the above code in an if statement tp check 'id' and 'date' for null values ? I want to do it inside the filter.

Edit : To make it more clear, i want the filter to act only on the non-null values, i.e if date is non-null and id is null, then filter only on date and ignore id, and so on..

Thanks

Body:
You could use the static method Objects::equals. Chances are that this method is designed for just this:

List<Objects> filtered = objects.stream()
    .filter(o -> Objects.equals(source, o.getSource()) && Objects.equals(date, o.getDate()) && Objects.equals(id, o.getId()))
    .collect(Collectors.toList());

Note: as Scratte mentioned in the comments, this may not filter out objects for which getDate() returns null, if date is also null. Same goes for id. If that's the case, then the abovementioned code snippet does not comply. In that case, then we have to explicitly filter for non-null dates and ids:

.filter(o -> Objects.nonNull(o.getId()) && Objects.nonNull(o.getDate()))

Update

If you want to skip the comparison for getDate() if date is null (and same for id), then you could check first for null, just like in ernest_k's answer.

You could easily build a small method for it:

public static boolean nullOrEquals(Object baseObject, Object compareObject) {
    return baseObject == null || Objects.equals(baseObject, compareObject);
}

.filter(o -> Objects.equals(source, o.getSource())
    && nullOrEquals(date, o.getDate())
    && nullOrEquals(id, o.getId()))

Here's an Ideone example.


问:
Random initialization of local variable C++
While creating and running a small piece of code to see how global and local variables are initialized,the global array outputs a zero(because global variables are initialzed with zero).

But why is it that the printed values of the local array change randomly everytime you re-build the program?

 #include<iostream>

using namespace std;

int global[1];

int main()
{
    int local[1];
    cout<<"global is:"<<global[0]<<global[1]<<"\n";
    cout<<"local is:"<<local[0]<<local[1]<<"\n";
    return 0;
}
```

答:
Global variables behave like static in C++ (behaviour defined by standard). Their values are set to 0. They also have a special place in memory.

Local variables, on the other hand, if left unitialized have their values undefined. Which means when you run the program it just reads the data there are at the memory where the structure is allocated. Those are the seemingly random values you encounter.


问:
Ipywidgets interact won't apply datepicker to DataFrame ("TypeError: 'DataFrame' object is not callable")
I'm building a jupyter notebook that uses some interactive widgets to help move through some dataframes.  My jupyter and python experience is limited, and most of my notebook so far is recreating consolidations and calculations I'd previously created in a series of Excel PivotTables.

The first try at an interactive widget worked ok.  It calls up the dataframe, with a sliding widget to limit returned rows by the result of a column (how many days was an assignment opened):

```<code>from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
@interact
def days_open_widget(column='days_open', x=(0,2000,5)):
    return df.loc[df[column] > x]
</code>```

Next, I wanted to be able to separately explore the DataFrame using two datepickers to constrain the results by the date the assignment was created.  Parts of it are working, like the datepickers populate with the earliest and latest dates but they are not tied to the dataframe.  Here's the code:

```<code>interact(df,
        start_date=widgets.DatePicker(value=df.assignment_creation_date.min()),
        end_date=widgets.DatePicker(value=df.assignment_creation_date.max()))
</code>```

After Jupyter displays the datepickers, it follows up with the following error, then displays the unfiltered dataframe.

```<code>TypeError                                 Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
    254                     value = widget.get_interact_value()
    255                     self.kwargs[widget._kwarg] = value
--> 256                 self.result = self.f(**self.kwargs)
    257                 show_inline_matplotlib_plots()
    258                 if self.auto_display and self.result is not None:

TypeError: 'DataFrame' object is not callable
</code>```

I'm not sure what I'm missing.  I'm not sure why trying to access the DataFrame is giving me an "object is not callable" error when I accessed it earlier, or why the DatePickers successfully read the DataFrame column, but then disconnect.

The behavior I'm trying to create would call the entire dataframe, but let me filter the resulting rows between dates selected from the datepicker.  What am I missing?

Edit: I know the code is messy and in hindsight, I don't think I should be importing interact, interactive, fixed, interact_manual separately and then be importing all of ipywidgets.

Edit 2: I couldn't get AC24's solution to work, but I think that's more to do with my own inability to properly define a function that filtered the dataframe.  I ended up finding QGrid instead, which has a datepicker along with other filters.

More info on QGrid at https://qgrid.readthedocs.io/en/latest/ but if anyone has a more explicit description for how to define the function to pass the dataframe as an function please feel free to add it.

答:
Note that interact behaves differently to the interactive decorator. When using interact, the first argument should be a function/callable that gets called when you change any of the widgets. You passed in the dataframe df as the first argument, and therefore interact is trying to call df as a function with the start_date and end_date keywords. Hence the error, as dataframes are not callable.

Have a look at the documentation for examples, you probably want to build a simple function to filter your dataframe, and use that function name as the first argument to interact.

https://ipywidgets.readthedocs.io/en/latest/examples/Using%20Interact.html#Basic-interact

Body:
I'm building a jupyter notebook that uses some interactive widgets to help move through some dataframes.  My jupyter and python experience is limited, and most of my notebook so far is recreating consolidations and calculations I'd previously created in a series of Excel PivotTables.

The first try at an interactive widget worked ok.  It calls up the dataframe, with a sliding widget to limit returned rows by the result of a column (how many days was an assignment opened):

from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
@interact
def days_open_widget(column='days_open', x=(0,2000,5)):
    return df.loc[df[column] > x]

Next, I wanted to be able to separately explore the DataFrame using two datepickers to constrain the results by the date the assignment was created.  Parts of it are working, like the datepickers populate with the earliest and latest dates but they are not tied to the dataframe.  Here's the code:

interact(df,
        start_date=widgets.DatePicker(value=df.assignment_creation_date.min()),
        end_date=widgets.DatePicker(value=df.assignment_creation_date.max()))

After Jupyter displays the datepickers, it follows up with the following error, then displays the unfiltered dataframe.

TypeError                                 Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\ipywidgets\widgets\interaction.py in update(self, *args)
    254                     value = widget.get_interact_value()
    255                     self.kwargs[widget._kwarg] = value
--> 256                 self.result = self.f(**self.kwargs)
    257                 show_inline_matplotlib_plots()
    258                 if self.auto_display and self.result is not None:

TypeError: 'DataFrame' object is not callable

I'm not sure what I'm missing.  I'm not sure why trying to access the DataFrame is giving me an "object is not callable" error when I accessed it earlier, or why the DatePickers successfully read the DataFrame column, but then disconnect.

The behavior I'm trying to create would call the entire dataframe, but let me filter the resulting rows between dates selected from the datepicker.  What am I missing?

Edit: I know the code is messy and in hindsight, I don't think I should be importing interact, interactive, fixed, interact_manual separately and then be importing all of ipywidgets.

Edit 2: I couldn't get AC24's solution to work, but I think that's more to do with my own inability to properly define a function that filtered the dataframe.  I ended up finding QGrid instead, which has a datepicker along with other filters.

More info on QGrid at https://qgrid.readthedocs.io/en/latest/ but if anyone has a more explicit description for how to define the function to pass the dataframe as an function please feel free to add it.


问:
Does a pointer need to be nulled after it is freed?
```<code>int main(){

(int*) pointer = (int*) malloc(sizeof(int));
free(pointer);

}
</code>```

I learned from 'Prata, Stephen. C Primer Plus (Developer's Library)' that
"When the function terminates, the pointer, being an automatic variable, disappears."  so simply, i don't need to null the pointer

however, I also learned from school that the pointer becomes a dangling pointer if it doesn't get nulled after it free.

Two ideas are contradicting each other. Which one is the right one?

答: What free does is to deallocate the space that pointer holds before the execution of free. The pointer holds an integer value(the address) before and after the execution therefore the address that the pointer holds is now an invalid address that is not allocated by the program. As said, if you plan to use the pointer again in future cases, you wouldn't wanna have an invalid undefined value in it that you cannot check, having null makes the checks easier.</p>

Body:
int main(){

(int*) pointer = (int*) malloc(sizeof(int));
free(pointer);

}

I learned from 'Prata, Stephen. C Primer Plus (Developer's Library)' that
"When the function terminates, the pointer, being an automatic variable, disappears."  so simply, i don't need to null the pointer

however, I also learned from school that the pointer becomes a dangling pointer if it doesn't get nulled after it free.

Two ideas are contradicting each other. Which one is the right one?


问:
Convert bigger dimension matrix to smaller dimension matrix with a loop
I currently have 185*185 matrix and the goal is to convert this matrix into a 35*35 matrix by aggregating the value based on the rows and cols of the 185 matrix.

Example:

I have a 8*8 matrix as below:

```<code>matrix_x <- matrix(1:64, nrow = 8)
</code>```

Then I want to convert it into a 4*4 matrix:

```<code>matrix_y <- matrix(NA, nrow = 4, ncol = 4)
</code>```

The list below is created for aggregating the 8*8 matrix cols to a 4*4 matrix

```<code>col_list <- list(
  1,
  2:3,
  c(4,8),
  5:7
)
</code>```

What I've done to achieve this is by assigning the value manually as below

```<code>matrix_y[1,1] <- sum(matrix_x[col_list[[1]],col_list[[1]]])
matrix_y[1,2] <- sum(matrix_x[col_list[[1]],col_list[[2]]])
matrix_y[1,3] <- sum(matrix_x[col_list[[1]],col_list[[3]]])
matrix_y[1,4] <- sum(matrix_x[col_list[[1]],col_list[[4]]])

matrix_y[2,1] <- sum(matrix_x[col_list[[2]],col_list[[1]]])
matrix_y[2,2] <- sum(matrix_x[col_list[[2]],col_list[[2]]])
matrix_y[2,3] <- sum(matrix_x[col_list[[2]],col_list[[3]]])
matrix_y[2,4] <- sum(matrix_x[col_list[[2]],col_list[[4]]])

matrix_y[3,1] <- sum(matrix_x[col_list[[3]],col_list[[1]]])
matrix_y[3,2] <- sum(matrix_x[col_list[[3]],col_list[[2]]])
matrix_y[3,3] <- sum(matrix_x[col_list[[3]],col_list[[3]]])
matrix_y[3,4] <- sum(matrix_x[col_list[[3]],col_list[[4]]])

matrix_y[4,1] <- sum(matrix_x[col_list[[4]],col_list[[1]]])
matrix_y[4,2] <- sum(matrix_x[col_list[[4]],col_list[[2]]])
matrix_y[4,3] <- sum(matrix_x[col_list[[4]],col_list[[3]]])
matrix_y[4,4] <- sum(matrix_x[col_list[[4]],col_list[[4]]])
</code>```

This approach works well, but I'm looking for a more efficient way to achieve this since the approach I've done takes so many code lines.

答:
There should be a neater/easier way to do this but here is one straight-forward option :

```<code>n <- 4
t(sapply(seq_len(n), function(p) sapply(col_list, function(q) sum(matrix_x[p, q]))))

#     [,1] [,2] [,3] [,4]
#[1,]    1   26   82  123
#[2,]    2   28   84  126
#[3,]    3   30   86  129
#[4,]    4   32   88  132
</code>```

This gives the same matrix as matrix_y in the post.

For the updated question, we can use outer

```<code>apply_fun <- function(x, y) sum(matrix_x[x, y])
outer(col_list, col_list, Vectorize(apply_fun))

#     [,1] [,2] [,3] [,4]
#[1,]    1   26   82  123
#[2,]    5   58  170  255
#[3,]   12   72  184  276
#[4,]   18  108  276  414
</code>```

Or following the same approach as in original answer with nested sapply

```<code>t(sapply(col_list, function(p) sapply(col_list, function(q) sum(matrix_x[p, q]))))
</code>```

Body:
I currently have 185*185 matrix and the goal is to convert this matrix into a 35*35 matrix by aggregating the value based on the rows and cols of the 185 matrix.

Example:

I have a 8*8 matrix as below:

matrix_x <- matrix(1:64, nrow = 8)

Then I want to convert it into a 4*4 matrix:

matrix_y <- matrix(NA, nrow = 4, ncol = 4)

The list below is created for aggregating the 8*8 matrix cols to a 4*4 matrix

col_list <- list(
  1,
  2:3,
  c(4,8),
  5:7
)

What I've done to achieve this is by assigning the value manually as below

matrix_y[1,1] <- sum(matrix_x[col_list[[1]],col_list[[1]]])
matrix_y[1,2] <- sum(matrix_x[col_list[[1]],col_list[[2]]])
matrix_y[1,3] <- sum(matrix_x[col_list[[1]],col_list[[3]]])
matrix_y[1,4] <- sum(matrix_x[col_list[[1]],col_list[[4]]])

matrix_y[2,1] <- sum(matrix_x[col_list[[2]],col_list[[1]]])
matrix_y[2,2] <- sum(matrix_x[col_list[[2]],col_list[[2]]])
matrix_y[2,3] <- sum(matrix_x[col_list[[2]],col_list[[3]]])
matrix_y[2,4] <- sum(matrix_x[col_list[[2]],col_list[[4]]])

matrix_y[3,1] <- sum(matrix_x[col_list[[3]],col_list[[1]]])
matrix_y[3,2] <- sum(matrix_x[col_list[[3]],col_list[[2]]])
matrix_y[3,3] <- sum(matrix_x[col_list[[3]],col_list[[3]]])
matrix_y[3,4] <- sum(matrix_x[col_list[[3]],col_list[[4]]])

matrix_y[4,1] <- sum(matrix_x[col_list[[4]],col_list[[1]]])
matrix_y[4,2] <- sum(matrix_x[col_list[[4]],col_list[[2]]])
matrix_y[4,3] <- sum(matrix_x[col_list[[4]],col_list[[3]]])
matrix_y[4,4] <- sum(matrix_x[col_list[[4]],col_list[[4]]])

This approach works well, but I'm looking for a more efficient way to achieve this since the approach I've done takes so many code lines.

Body:
There should be a neater/easier way to do this but here is one straight-forward option :

n <- 4
t(sapply(seq_len(n), function(p) sapply(col_list, function(q) sum(matrix_x[p, q]))))

#     [,1] [,2] [,3] [,4]
#[1,]    1   26   82  123
#[2,]    2   28   84  126
#[3,]    3   30   86  129
#[4,]    4   32   88  132

This gives the same matrix as matrix_y in the post.

For the updated question, we can use outer

apply_fun <- function(x, y) sum(matrix_x[x, y])
outer(col_list, col_list, Vectorize(apply_fun))

#     [,1] [,2] [,3] [,4]
#[1,]    1   26   82  123
#[2,]    5   58  170  255
#[3,]   12   72  184  276
#[4,]   18  108  276  414

Or following the same approach as in original answer with nested sapply

t(sapply(col_list, function(p) sapply(col_list, function(q) sum(matrix_x[p, q]))))