问:
Can Lazy modify elements in Array in Scala?
I want to define an array, each element of array is a data set read from certain path in the file system, because the data reading is costly and the position in array to be visited is sparse, so I want to use Lazy modifier to realize that one data set will not be read until being visited. How can define this kind of array?</p>

答:
No, you cannot use lazy on the array to make the elements lazy. The most natural thing to do would be to use a caching library like ScalaCache.

You can also make a kind of wrapper class with a lazy field as you suggested in your comment. However, I would prefer not to expose the caching to the clients of the array. You should be able to just write myArray(index) to access an element.

If you don't want to use a library, this is another option (without lazy) that gives you an array like object with caching:

```<code>class CachingArray[A](size: Int, getElement: Int => A) {

  val elements = scala.collection.mutable.Map[Int, A]()

  def apply(index: Int) = elements.getOrElseUpdate(index, getElement(index))

}
</code>```

Just initialize it with the size and a function that computes an element at a given index.

If you like, you can make it extend IndexedSeq[A] so it can be used more like a real array. Just implement length like this:

```<code>override def length: Int = size
</code>```

Body:
No, you cannot use lazy on the array to make the elements lazy. The most natural thing to do would be to use a caching library like ScalaCache.

You can also make a kind of wrapper class with a lazy field as you suggested in your comment. However, I would prefer not to expose the caching to the clients of the array. You should be able to just write myArray(index) to access an element.

If you don't want to use a library, this is another option (without lazy) that gives you an array like object with caching:

class CachingArray[A](size: Int, getElement: Int => A) {

  val elements = scala.collection.mutable.Map[Int, A]()

  def apply(index: Int) = elements.getOrElseUpdate(index, getElement(index))

}

Just initialize it with the size and a function that computes an element at a given index.

If you like, you can make it extend IndexedSeq[A] so it can be used more like a real array. Just implement length like this:

override def length: Int = size


来源: stackexchange

问:
Implementing retry logic for deadlock exceptions
I've implemented a generic repository and was wondering if there is a smart way to implement a retry logic in case of a deadlock exception?

The approach should be the same for all repository methods. So is there anyway I can avoid writing 'try/catch - call method again with retry-count', in every single method?

Any suggetsion are welcome.

A bit of my Repository code:

```<code>public class GenericRepository : IRepository
{
    private ObjectContext _context;

    public List<TEntity> ExecuteStoreQuery<TEntity>(string commandText, params object[] parameters) where TEntity : class
    {
        List<TEntity> myList = new List<TEntity>();

        var groupData = _context.ExecuteStoreQuery<TEntity>(commandText, parameters);

        return myList;
    }

    public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
    {
        var entityName = GetEntityName<TEntity>();
        return _context.CreateQuery<TEntity>(entityName);
    }

    public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
    {
        return GetQuery<TEntity>().AsEnumerable();
    }
</code>```

EDIT:

1.Solution:

Modified slightly from chris.house.00's solution

```<code> public static T DeadlockRetryHelper<T>(Func<T> repositoryMethod, int maxRetries)
    {
        var retryCount = 0;

        while (retryCount < maxRetries)
        {
            try
            {
                return repositoryMethod();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                if (ex.Number == 1205)// Deadlock
                    retryCount++;
                else
                    throw;
            }
        }
        return default(T);
    }
</code>```

And you call it like this:

```<code>    public TEntity FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return RetryUtility.DeadlockRetryHelper<TEntity>( () =>p_FirstOrDefault<TEntity>(predicate), 3);
    }

    protected TEntity p_FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return GetQuery<TEntity>().FirstOrDefault<TEntity>(predicate);
    }
</code>```

答:
EntityFramework 6  add ExecutionStrategy feature. All that is need is to setup up the strategy properly.

My retry policy:

```<code>public class EFRetryPolicy : DbExecutionStrategy
{
    public EFRetryPolicy() : base()
    {
    }
    //Keep this constructor public too in case it is needed to change defaults of exponential back off algorithm.
    public EFRetryPolicy(int maxRetryCount, TimeSpan maxDelay): base(maxRetryCount, maxDelay)
    {
    }
    protected override bool ShouldRetryOn(Exception ex)
    {

        bool retry = false;

        SqlException sqlException = ex as SqlException;
        if (sqlException != null)
        {
            int[] errorsToRetry =
            {
                1205,  //Deadlock
                -2,    //Timeout
            };
            if (sqlException.Errors.Cast<SqlError>().Any(x => errorsToRetry.Contains(x.Number)))
            {
                retry = true;
            }

        }
        return retry;
    }
}
</code>```

Tell EF to apply my strategy:

```<code>public class EFPolicy: DbConfiguration
{
    public EFPolicy()
    {
        SetExecutionStrategy(
            "System.Data.SqlClient",
            () => new EFRetryPolicy());
    }
}
</code>```

Sources:

Implementing Connection Resiliency with Entity Framework 6

Microsoft documentation

The retry strategy will not work with user initiated transactions (transaction created with TransactionScope) as explained here. If used you will get the Error The configured execution strategy  does not support user initiated transactions

ContentLicense: CC BY-SA 3.0

Body:
I've implemented a generic repository and was wondering if there is a smart way to implement a retry logic in case of a deadlock exception?

The approach should be the same for all repository methods. So is there anyway I can avoid writing 'try/catch - call method again with retry-count', in every single method?

Any suggetsion are welcome.

A bit of my Repository code:

public class GenericRepository : IRepository
{
    private ObjectContext _context;

    public List<TEntity> ExecuteStoreQuery<TEntity>(string commandText, params object[] parameters) where TEntity : class
    {
        List<TEntity> myList = new List<TEntity>();

        var groupData = _context.ExecuteStoreQuery<TEntity>(commandText, parameters);

        return myList;
    }

    public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class
    {
        var entityName = GetEntityName<TEntity>();
        return _context.CreateQuery<TEntity>(entityName);
    }

    public IEnumerable<TEntity> GetAll<TEntity>() where TEntity : class
    {
        return GetQuery<TEntity>().AsEnumerable();
    }

EDIT:

1.Solution:

Modified slightly from chris.house.00's solution

 public static T DeadlockRetryHelper<T>(Func<T> repositoryMethod, int maxRetries)
    {
        var retryCount = 0;

        while (retryCount < maxRetries)
        {
            try
            {
                return repositoryMethod();
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                if (ex.Number == 1205)// Deadlock
                    retryCount++;
                else
                    throw;
            }
        }
        return default(T);
    }

And you call it like this:

    public TEntity FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return RetryUtility.DeadlockRetryHelper<TEntity>( () =>p_FirstOrDefault<TEntity>(predicate), 3);
    }

    protected TEntity p_FirstOrDefault<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class
    {
        return GetQuery<TEntity>().FirstOrDefault<TEntity>(predicate);
    }

Body:
EntityFramework 6  add ExecutionStrategy feature. All that is need is to setup up the strategy properly.

My retry policy:

public class EFRetryPolicy : DbExecutionStrategy
{
    public EFRetryPolicy() : base()
    {
    }
    //Keep this constructor public too in case it is needed to change defaults of exponential back off algorithm.
    public EFRetryPolicy(int maxRetryCount, TimeSpan maxDelay): base(maxRetryCount, maxDelay)
    {
    }
    protected override bool ShouldRetryOn(Exception ex)
    {

        bool retry = false;

        SqlException sqlException = ex as SqlException;
        if (sqlException != null)
        {
            int[] errorsToRetry =
            {
                1205,  //Deadlock
                -2,    //Timeout
            };
            if (sqlException.Errors.Cast<SqlError>().Any(x => errorsToRetry.Contains(x.Number)))
            {
                retry = true;
            }

        }
        return retry;
    }
}

Tell EF to apply my strategy:

public class EFPolicy: DbConfiguration
{
    public EFPolicy()
    {
        SetExecutionStrategy(
            "System.Data.SqlClient",
            () => new EFRetryPolicy());
    }
}

Sources:

Implementing Connection Resiliency with Entity Framework 6

Microsoft documentation

The retry strategy will not work with user initiated transactions (transaction created with TransactionScope) as explained here. If used you will get the Error The configured execution strategy  does not support user initiated transactions


问:
Unable to generate HTML table from Powershell function
I have got a powershell function that gets all errors and warnings from the event logs, counts the occurance of each Event ID and returns a Powershell table. THe code that does this is as follows -

```<code>function Get-EventLogs {
[System.Collections.ArrayList]$results = @()

#Do you want to enable transcript for logging all output to file?

$enableLogging = $FALSE

$ExportEnabled = $FALSE

# logging

# if you need detailed logging for troubleshooting this script, you can enable the transcript

# get the script location path and use it as default location for storing logs and results

$log = $MyInvocation.MyCommand.Definition -replace 'ps1','log'

$resultPath = $PSScriptRoot + '\'

Push-Location $resultPath

if ($enableLogging)
{

Start-Transcript -Path $log -ErrorAction SilentlyContinue

Write-Host "Logging enabled..."

Write-Host

Write-Host "Powershell version"

$PSVersionTable.PSVersion

$Host.Version

(Get-Host).Version

Write-host

}

$currentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture

# Configuration

# selected Event log sources

# limit the feedback only to the following logs

$EventLogList = 'System','Application'

#for FIM Health Check the Security log has less signification value and is skipped

#add it to the eventlog list when you need it

#,'Security'

# if the event logs are containing too much data,

#collect x years of logs

$startdate = ((Get-Date).AddDays(-7))

$Count = 0

$Activity = "Checking log properties"

$allEvents = New-Object System.Collections.Hashtable

$Count = 0

$Activity = "Checking log detaills"

foreach ($eventlog in $EventLogList)
{
    #$Count += 1

    $pct = ($Count / $EventLogList.Count * 100)

    $status = $EventLog + " (" + $Count + "/" + $EventLogList.Count +")"

    Write-Progress -Activity $Activity -Status $status -PercentComplete $pct

    write-host $count"." $eventlog

    [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"

    # query the event log

    # store the data in a hashtable, to avoid new queries

    $allEvents = $Null

    $allEvents = Get-WinEvent -FilterHashtable @{logname=$eventlog;StartTime=$startdate;level=0,1,2,3,4,5} -ErrorAction SilentlyContinue

    #DEBUG if ($eventlog -eq "Application") { $allevents}

    if ($allEvents.count -eq 0)
    {
        $message = "No events for " + $eventlog + "log since "+ $startdate + "."

        Write-Host $message

        Write-Host

        # no data to process, skip processing for current loop

        Continue
    }

    #For events detailed reporting we're only interested in error events

    #not interested in informational events (level 0 and 4)

    $evtStats = $allEvents | where -Property level -Notin -Value 0,4 | Group-Object id | Sort-Object Count -Descending

    $allevents = $Null

    #prep export

    $exportfile = $resultPath + "_EventIDStats"+ $eventlog + ".csv.txt"

    if ($exportEnabled) {$export | Export-Csv $exportfile  -NoTypeInformation}

    # evtStats has number and ID attribute

    # other attributes must be added:

    #  - errortype name

    #  - Source

    #  - errortype name

    # for each event id in the event statistics

    # display the most recent event

    $Activity = "Looking up last event occurrence..."

    $i= 0

    foreach ($item in $evtStats)
    {
        $i += 1

        $pct = ($i / $evtStats.Count * 100)

        $eventID = $item.Name

        $status = "EventID: "+ $item.Name

        Write-Progress -Activity $Activity -Status $status -PercentComplete $pct

        $customobj = "" | select Count,ErrorID,ErrorType,Message

        $customobj.Count = $item.Count

        $customobj.ErrorID = $item.Name

        #get most recent event from the eventID

        $id = $item.Name.ToInt32($Null)

        [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"

        $lastevent = get-winevent -FilterHashtable @{LogName=$eventlog;Id=$id} -MaxEvents 1 -ErrorAction SilentlyContinue

        #depending on local settings, query might fail, if it fails reset to local culture

        if ($lastevent.LevelDisplayName.Length -eq 0)

        {

            [System.Threading.Thread]::CurrentThread.CurrentCulture = $currentCulture

            $lastevent = get-winevent -FilterHashtable @{LogName=$eventlog;Id=$id} -MaxEvents 1

        }

        $customobj.ErrorType = $lastevent.LevelDisplayName

        $customobj.Message = $lastevent.Message

        #prep EventID export

        $exportfile = $resultPath + $eventlog +'_EventID_' + $customobj.ErrorID + ".csv.txt"

        if ($exportEnabled)
        {
            $customobj | Export-Csv $exportfile -NoTypeInformation
        }

        $results += $customobj
    }

    #display with format

    $results | Format-Table -AutoSize

    return ,$results

    if ($exportEnabled)
    {
        $exportfile = $resultPath + "_lastEvents_short_" + $eventlog + ".txt"

        $results| Format-Table -AutoSize | out-file $exportfile

        $exportfile = $resultPath + "_lastEvents_detail_" + $eventlog + ".txt"

        $results | out-file $exportfile

    }
}

#Write-Output $results | Format-Table -AutoSize

}
</code>```

I then need to format the output of this function as a HTML table, so I can show it in my report.

```<code>$elogs = (Get-EventLogs) | Out-String
</code>```

The code above outputs it as a long string (to be expected). But I cannot figure out how to format it as a HTML table. THe code that finally generates the report is as follows -

```<code>$Report = ConvertTo-Html -Title "$Computername" `
                     -Head "<center><h1>Server Report for <br><br>$Computername</h1></center><br /><br />" `
                     -Body "$Heading $Hardware $elogs $PercentFree $Output $Restarted $Services $Stopped $Css" }
</code>```

Is there a way to output this as a table?

答:
ConvertTo-Html is able to take an object and render that object as a HTML table. For simplicity's sake, I'll include the -Fragment switch that will ONLY return a HTML table (not all the HTML header, etc.).

Take a simple object, such as some basic process data, and you can create a HTML table:

```<code>[PS] $p = Get-Process | Select -First 3 -Property Name,ID

[PS] $p | ConvertTo-Html -Fragment
<table>
<colgroup><col/><col/></colgroup>
<tr><th>Name</th><th>Id</th></tr>
<tr><td>Process1</td><td>1888</td></tr>
<tr><td>Process2</td><td>1536</td></tr>
<tr><td>Process3</td><td>13920</td></tr>
</table>
</code>```

Note that we don't need to specify a -Body with all the variables; we just need to make sure that we have all the data collected in an object (with the appropriate property names) and the cmdlet does the rest.

Going back to your script, there are a few things to look at:

Don't use Write-Host. If you want debug messages, consider using Write-verbose and Write-Debug. You'll need to set the $VerbosePreference and $DebugPreference variables to "Continue" to make this output visible.

Similarly, avoid using Format-Table

Your script returns an object ,$results. You should be able to pipe this into ConvertTo-Html with additional header and body content.

Note finally that the -Body switch doesn't format your object; it just includes extra HTML in front of the HTML table.

Body:
I have got a powershell function that gets all errors and warnings from the event logs, counts the occurance of each Event ID and returns a Powershell table. THe code that does this is as follows -

function Get-EventLogs {
[System.Collections.ArrayList]$results = @()

#Do you want to enable transcript for logging all output to file?

$enableLogging = $FALSE

$ExportEnabled = $FALSE

# logging

# if you need detailed logging for troubleshooting this script, you can enable the transcript

# get the script location path and use it as default location for storing logs and results

$log = $MyInvocation.MyCommand.Definition -replace 'ps1','log'

$resultPath = $PSScriptRoot + '\'

Push-Location $resultPath

if ($enableLogging)
{

Start-Transcript -Path $log -ErrorAction SilentlyContinue

Write-Host "Logging enabled..."

Write-Host

Write-Host "Powershell version"

$PSVersionTable.PSVersion

$Host.Version

(Get-Host).Version

Write-host

}

$currentCulture = [System.Threading.Thread]::CurrentThread.CurrentCulture

# Configuration

# selected Event log sources

# limit the feedback only to the following logs

$EventLogList = 'System','Application'

#for FIM Health Check the Security log has less signification value and is skipped

#add it to the eventlog list when you need it

#,'Security'

# if the event logs are containing too much data,

#collect x years of logs

$startdate = ((Get-Date).AddDays(-7))

$Count = 0

$Activity = "Checking log properties"

$allEvents = New-Object System.Collections.Hashtable

$Count = 0

$Activity = "Checking log detaills"

foreach ($eventlog in $EventLogList)
{
    #$Count += 1

    $pct = ($Count / $EventLogList.Count * 100)

    $status = $EventLog + " (" + $Count + "/" + $EventLogList.Count +")"

    Write-Progress -Activity $Activity -Status $status -PercentComplete $pct

    write-host $count"." $eventlog

    [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"

    # query the event log

    # store the data in a hashtable, to avoid new queries

    $allEvents = $Null

    $allEvents = Get-WinEvent -FilterHashtable @{logname=$eventlog;StartTime=$startdate;level=0,1,2,3,4,5} -ErrorAction SilentlyContinue

    #DEBUG if ($eventlog -eq "Application") { $allevents}

    if ($allEvents.count -eq 0)
    {
        $message = "No events for " + $eventlog + "log since "+ $startdate + "."

        Write-Host $message

        Write-Host

        # no data to process, skip processing for current loop

        Continue
    }

    #For events detailed reporting we're only interested in error events

    #not interested in informational events (level 0 and 4)

    $evtStats = $allEvents | where -Property level -Notin -Value 0,4 | Group-Object id | Sort-Object Count -Descending

    $allevents = $Null

    #prep export

    $exportfile = $resultPath + "_EventIDStats"+ $eventlog + ".csv.txt"

    if ($exportEnabled) {$export | Export-Csv $exportfile  -NoTypeInformation}

    # evtStats has number and ID attribute

    # other attributes must be added:

    #  - errortype name

    #  - Source

    #  - errortype name

    # for each event id in the event statistics

    # display the most recent event

    $Activity = "Looking up last event occurrence..."

    $i= 0

    foreach ($item in $evtStats)
    {
        $i += 1

        $pct = ($i / $evtStats.Count * 100)

        $eventID = $item.Name

        $status = "EventID: "+ $item.Name

        Write-Progress -Activity $Activity -Status $status -PercentComplete $pct

        $customobj = "" | select Count,ErrorID,ErrorType,Message

        $customobj.Count = $item.Count

        $customobj.ErrorID = $item.Name

        #get most recent event from the eventID

        $id = $item.Name.ToInt32($Null)

        [System.Threading.Thread]::CurrentThread.CurrentCulture = New-Object "System.Globalization.CultureInfo" "en-US"

        $lastevent = get-winevent -FilterHashtable @{LogName=$eventlog;Id=$id} -MaxEvents 1 -ErrorAction SilentlyContinue

        #depending on local settings, query might fail, if it fails reset to local culture

        if ($lastevent.LevelDisplayName.Length -eq 0)

        {

            [System.Threading.Thread]::CurrentThread.CurrentCulture = $currentCulture

            $lastevent = get-winevent -FilterHashtable @{LogName=$eventlog;Id=$id} -MaxEvents 1

        }

        $customobj.ErrorType = $lastevent.LevelDisplayName

        $customobj.Message = $lastevent.Message

        #prep EventID export

        $exportfile = $resultPath + $eventlog +'_EventID_' + $customobj.ErrorID + ".csv.txt"

        if ($exportEnabled)
        {
            $customobj | Export-Csv $exportfile -NoTypeInformation
        }

        $results += $customobj
    }

    #display with format

    $results | Format-Table -AutoSize

    return ,$results

    if ($exportEnabled)
    {
        $exportfile = $resultPath + "_lastEvents_short_" + $eventlog + ".txt"

        $results| Format-Table -AutoSize | out-file $exportfile

        $exportfile = $resultPath + "_lastEvents_detail_" + $eventlog + ".txt"

        $results | out-file $exportfile

    }
}

#Write-Output $results | Format-Table -AutoSize

}

I then need to format the output of this function as a HTML table, so I can show it in my report.

$elogs = (Get-EventLogs) | Out-String

The code above outputs it as a long string (to be expected). But I cannot figure out how to format it as a HTML table. THe code that finally generates the report is as follows -

$Report = ConvertTo-Html -Title "$Computername" `
                     -Head "
Server Report for

$Computername

" `
                     -Body "$Heading $Hardware $elogs $PercentFree $Output $Restarted $Services $Stopped $Css" }

Is there a way to output this as a table?

Body:
ConvertTo-Html is able to take an object and render that object as a HTML table. For simplicity's sake, I'll include the -Fragment switch that will ONLY return a HTML table (not all the HTML header, etc.).

Take a simple object, such as some basic process data, and you can create a HTML table:

[PS] $p = Get-Process | Select -First 3 -Property Name,ID

[PS] $p | ConvertTo-Html -Fragment
<table>
<colgroup><col/><col/></colgroup>
<tr><th>Name</th><th>Id</th></tr>
<tr><td>Process1</td><td>1888</td></tr>
<tr><td>Process2</td><td>1536</td></tr>
<tr><td>Process3</td><td>13920</td></tr>
</table>

Note that we don't need to specify a -Body with all the variables; we just need to make sure that we have all the data collected in an object (with the appropriate property names) and the cmdlet does the rest.

Going back to your script, there are a few things to look at:

Don't use Write-Host. If you want debug messages, consider using Write-verbose and Write-Debug. You'll need to set the $VerbosePreference and $DebugPreference variables to "Continue" to make this output visible.

Similarly, avoid using Format-Table

Your script returns an object ,$results. You should be able to pipe this into ConvertTo-Html with additional header and body content.

Note finally that the -Body switch doesn't format your object; it just includes extra HTML in front of the HTML table.


问:
Using Replace function in Kotlin
I am try to replace the cyrlic characters by using Latin
The following codes works

```<code>val kztext83: String = kztext82.replace('ə','ä')
</code>```

but the actual translation is not ä , it is a'

Since a' is two character i am getting errror for

```<code>val kztext83: String = kztext82.replace('ə','a'')
</code>```

Error is  - too many character in character literal ?

I tried many ways including creating string , not fixing the issues

答:
Instead of replacing chars, try using Strings:

```<code>val kztext83: String = kztext82.replace("ə","a'")
</code>```

Which means replacing the double quotes with single.

You can't have two chars in a single char ('a' is a char object) meaning 'a\'' is not valid.

ContentLicense: CC BY-SA 4.0

Title: Using Replace function in Kotlin

Body:
I am try to replace the cyrlic characters by using Latin
The following codes works

val kztext83: String = kztext82.replace('ə','ä')

but the actual translation is not ä , it is a'

Since a' is two character i am getting errror for

val kztext83: String = kztext82.replace('ə','a'')

Error is  - too many character in character literal ?

I tried many ways including creating string , not fixing the issues

Body:
Instead of replacing chars, try using Strings:

val kztext83: String = kztext82.replace("ə","a'")

Which means replacing the double quotes with single.

You can't have two chars in a single char ('a' is a char object) meaning 'a\'' is not valid.


问:
antlr4 grammar for splitting the number
```<code>grammar Te;

/*
 * Parser Rules
 */

test : (example+ EOF);
example: digit COMMA digit2 NEWLINE;
digit: (INT)+? ;
digit2: (INT INT INT INT)+?;

/*
 * Lexer Rules
 */

INT :[0-9];
COMMA: ',';
NEWLINE : ('\r'? '\n' | '\r')+ ;
</code>```

This is the grammar I have written for considering the number sequence into single digit until a COMMA is detected and afterwards consider the number sequence into 4 digits

for example, let my input be 00000,12345678912345678912
now it should consider 00000 and split it into single digits like

```<code>token 1 =0,
token 2 =0,
token 3 =0,
token 4 =0,
token 5 =0,
</code>```

and after COMMA it should consider 12345678912345678912
and split like

```<code>token 1 =1234,
token 2 =5678,
token 3 =9123,
token 4 =4567,
token 5 =8912,
</code>```

but it's not taking the 2nd rule and printing it as single digits after COMMA

anyone, please help

thanks in advance

答:
You almost got it right. The only error you made is that you want to loop the parser rule and not the lexer rule. Therefore your grammar should look like this:</p>

```<code>example: digit+ COMMA digit2+ NEWLINE ;
digit: INT ;
digit2: INT INT INT INT ;
</code>```

Title: antlr4 grammar for splitting the number

Body:
grammar Te;

/*
 * Parser Rules
 */

test : (example+ EOF);
example: digit COMMA digit2 NEWLINE;
digit: (INT)+? ;
digit2: (INT INT INT INT)+?;

/*
 * Lexer Rules
 */

INT :[0-9];
COMMA: ',';
NEWLINE : ('\r'? '\n' | '\r')+ ;

This is the grammar I have written for considering the number sequence into single digit until a COMMA is detected and afterwards consider the number sequence into 4 digits

for example, let my input be 00000,12345678912345678912
now it should consider 00000 and split it into single digits like

token 1 =0,
token 2 =0,
token 3 =0,
token 4 =0,
token 5 =0,

and after COMMA it should consider 12345678912345678912
and split like

token 1 =1234,
token 2 =5678,
token 3 =9123,
token 4 =4567,
token 5 =8912,

but it's not taking the 2nd rule and printing it as single digits after COMMA

anyone, please help

thanks in advance

Body:
You almost got it right. The only error you made is that you want to loop the parser rule and not the lexer rule. Therefore your grammar should look like this:

example: digit+ COMMA digit2+ NEWLINE ;
digit: INT ;
digit2: INT INT INT INT ;


问:
Stop Python Functions Overwriting Inputs
I have a simple function that is supposed to run down the diagonal of an array and turn all the values to 0.

```<code>def diagonal_zeros(dataset):
    zero = dataset[:]
    length = len(zero)
    for i in range(length):
        zero[i, i] = 0
    return zero
</code>```

When I run this function on an array, it outputs the new, correct 'zero' array, but it also goes back and overwrites the original 'dataset.' I had thought that the line zero = dataset[:] would have prevented this.

I do not, however, get the same behavior with this function:

```<code>def seperate_conditions(dataset, first, last):
    dataset = dataset[first:last, :]
    return dataset
</code>```

Which leaves the first dataset unchanged. I've been reading StackOverflow answers to related questions, but I cannot for the life of me figure this out. I'm working on a scientific analysis pipeline so I really want to be able to refer back to the matrices at every step.

Thanks

答:
Arguments in python are passed by assignment (thanks to @juanpa.arrivillaga for the correction) and not by value. This means that generally the function does not recieve a copy of the argument, but a "pointer" to the argument itself. If you alter the object referenced by the argument in the function, you are modifying the same object outside. Here's a page with some more information.

A possibility is to use the copy module inside your function, to create a copy of the dataset.

As an example, for your code:

```<code>import copy
myDataset = [[1,2,3],[2,3,4],[3,4,5]]

def diagonal_zeros(dataset):
    zero = copy.deepcopy(dataset)
    length = len(zero)
    for i in range(length):
        zero[i][i] = 0
    return zero

result = diagonal_zeros(myDataset)
print(result)     #[[0, 2, 3], [2, 0, 4], [3, 4, 0]]
print(myDataset)  #[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
</code>```

This article helped me a lot with this concept.

Body:
I have a simple function that is supposed to run down the diagonal of an array and turn all the values to 0.

def diagonal_zeros(dataset):
    zero = dataset[:]
    length = len(zero)
    for i in range(length):
        zero[i, i] = 0
    return zero

When I run this function on an array, it outputs the new, correct 'zero' array, but it also goes back and overwrites the original 'dataset.' I had thought that the line zero = dataset[:] would have prevented this.

I do not, however, get the same behavior with this function:

def seperate_conditions(dataset, first, last):
    dataset = dataset[first:last, :]
    return dataset

Which leaves the first dataset unchanged. I've been reading StackOverflow answers to related questions, but I cannot for the life of me figure this out. I'm working on a scientific analysis pipeline so I really want to be able to refer back to the matrices at every step.

Thanks

Body:
Arguments in python are passed by assignment (thanks to @juanpa.arrivillaga for the correction) and not by value. This means that generally the function does not recieve a copy of the argument, but a "pointer" to the argument itself. If you alter the object referenced by the argument in the function, you are modifying the same object outside. Here's a page with some more information.

A possibility is to use the copy module inside your function, to create a copy of the dataset.

As an example, for your code:

import copy
myDataset = [[1,2,3],[2,3,4],[3,4,5]]

def diagonal_zeros(dataset):
    zero = copy.deepcopy(dataset)
    length = len(zero)
    for i in range(length):
        zero[i][i] = 0
    return zero

result = diagonal_zeros(myDataset)
print(result)     #[[0, 2, 3], [2, 0, 4], [3, 4, 0]]
print(myDataset)  #[[1, 2, 3], [2, 3, 4], [3, 4, 5]]

This article helped me a lot with this concept.


问:
Java - method to lookup a specific ID from txt file and return that line details
I am writing a method to lookup a specific ID that is stored within a txt file.

These details are assigned to an arrayList titled list, if the lookup string matches the data stored in list then it reads the id,firstname,surname (IE the whole line of the txt file) and then creates an instance of another class profile.

I then want to add this lookup data to a new arrayList titled lookup then to output it. I have the below method however, it does not work and just jumps to my else clause.
Could anyone tell me where i'm going wrong and how to fix would be appreciated. Thanks.

答:
If you are using Java8, you can use Lambda to help you. Just replace this line:

```<code>    if(list.contains(IDlookup))
</code>```

to this one:

```<code>    boolean containsId = list.stream().anyMatch((Profile p) -> p.getId().equals(IDlookup));
    if (containsId)
</code>```

Body:
If you are using Java8, you can use Lambda to help you. Just replace this line:

    if(list.contains(IDlookup))

to this one:

    boolean containsId = list.stream().anyMatch((Profile p) -> p.getId().equals(IDlookup));
    if (containsId)


答:
The backslash isn't really there. It just shows that the following character (in this case, the quotation mark) is special. When you print(...) things to the console, it shows the data in a way useful to the programmer. In this case, the string is shown the way it would be written in code.

Look at the colors below to see how R would interpret the unescaped code:

```<code>"interpol_df[["gene1565"]][["y"]]"
</code>```

Now here it is with the escapes:

```<code>"interpol_df[[\"gene1565\"]][[\"y\"]]"
</code>```

The language definition lists other escape characters in 10.3.1: Constants.

Title: get rid of slashes after capture.output in R

Body:
In R, I need to write the output of paste0 to variable and need to get rid of slashes before doublequotes.

paste0('interpol_df[["gene',i, '"]][["y"]]')
[1] "interpol_df[[\"gene1565\"]][[\"y\"]]"

With cat one cat get rid of \

cat(paste0('interpol_df[["gene',i, '"]][["y"]]'))
interpol_df[["gene1565"]][["y"]]

To write the result to a variable, one cat use capture.output:

capture.output(cat(paste0('interpol_df[["gene',i, '"]][["y"]]')))

But \ is back again!

[1] "interpol_df[[\"gene1565\"]][[\"y\"]]"

sprintf also did not help. Any suggestion on how to get rid of it?

EDIT:

That piece of code is withing a for loop, which looks like:

inter_data<-NULL
for (i in 0:1565){
  y_col<-cat(paste('interpol_df[["gene',i, '"]][["y"]]'))
  inter_data<-rbind(inter_data,y_col)
  }

EDIT2:

By this loop I want to grab of y values from the following dataframe:

$gene949
$gene949$x
 [1] 1.000000 1.061224 1.122449 1.183673 1.244898 1.306122 1.367347 1.428571 1.489796 1.551020 1.612245 1.673469 1.734694 1.795918 1.857143 1.918367 1.979592 2.040816
[19] 2.102041 2.163265 2.224490 2.285714 2.346939 2.408163 2.469388 2.530612 2.591837 2.653061 2.714286 2.775510 2.836735 2.897959 2.959184 3.020408 3.081633 3.142857
[37] 3.204082 3.265306 3.326531 3.387755 3.448980 3.510204 3.571429 3.632653 3.693878 3.755102 3.816327 3.877551 3.938776 4.000000

$gene949$y
 [1] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[15] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000
[29] 0.00000000 0.00000000 0.00000000 0.00000000 0.00000000 0.02984865 0.11939459 0.20894053 0.29848647 0.38803241 0.47757835 0.56712429 0.65667023 0.74621616
[43] 0.83576210 0.92530804 1.01485398 1.10439992 1.19394586 1.28349180 1.37303774 1.46258368

$gene950
$gene950$x
 [1] 1.000000 1.061224 1.122449 1.183673 1.244898 1.306122 1.367347 1.428571 1.489796 1.551020 1.612245 1.673469 1.734694 1.795918 1.857143 1.918367 1.979592 2.040816
[19] 2.102041 2.163265 2.224490 2.285714 2.346939 2.408163 2.469388 2.530612 2.591837 2.653061 2.714286 2.775510 2.836735 2.897959 2.959184 3.020408 3.081633 3.142857
[37] 3.204082 3.265306 3.326531 3.387755 3.448980 3.510204 3.571429 3.632653 3.693878 3.755102 3.816327 3.877551 3.938776 4.000000

$gene950$y
 [1]  0.00000000 -0.15429366 -0.30858732 -0.46288099 -0.61717465 -0.77146831 -0.92576197 -1.08005564 -1.23434930 -1.38864296 -1.54293662 -1.69723029 -1.85152395
[14] -2.00581761 -2.16011127 -2.31440493 -2.46869860 -2.34260266 -2.07631192 -1.81002118 -1.54373044 -1.27743971 -1.01114897 -0.74485823 -0.47856749 -0.21227675
[27]  0.05401399  0.32030472  0.58659546  0.85288620  1.11917694  1.38546768  1.65175842  1.83847450  1.86604127  1.89360805  1.92117482  1.94874159  1.97630836
[40]  2.00387514  2.03144191  2.05900868  2.08657546  2.11414223  2.14170900  2.16927578  2.19684255  2.22440932  2.25197610  2.27954287

As it was suggested, there are for sure much better ways to achieve it than I do...

Body:
The backslash isn't really there. It just shows that the following character (in this case, the quotation mark) is special. When you print(...) things to the console, it shows the data in a way useful to the programmer. In this case, the string is shown the way it would be written in code.

Look at the colors below to see how R would interpret the unescaped code:

"interpol_df[["gene1565"]][["y"]]"

Now here it is with the escapes:

"interpol_df[[\"gene1565\"]][[\"y\"]]"

The language definition lists other escape characters in 10.3.1: Constants.


问:
What is the most pythonic way to split a 3d array to 2d arrays with different second indexes?
I have a function foo that returns an array with the shape (1000, 3, 1000)
how can I split it to three arrays a(1000, 1000) and b(1000, 1000) and c(1000, 1000)
I'm looking for something like this:

```<code>a,b,c = foo()[:,*,:]
</code>```

that will result in a,b,c equal to:

```<code>res = foo()
a = res[:,0,:]
b = res[:,1,:]
c = res[:,2,:]
</code>```

答:
I believe any of the following will work:</p>

```<code>numpy.split(foo(), 3, axis=1)
numpy.hsplit(foo(),3)
list(numpy.swapaxes(foo(), 0, 1))
</code>```

Body:
I have a function foo that returns an array with the shape (1000, 3, 1000)
how can I split it to three arrays a(1000, 1000) and b(1000, 1000) and c(1000, 1000)
I'm looking for something like this:

a,b,c = foo()[:,*,:]

that will result in a,b,c equal to:

res = foo()
a = res[:,0,:]
b = res[:,1,:]
c = res[:,2,:]

Body:
I believe any of the following will work:

numpy.split(foo(), 3, axis=1)
numpy.hsplit(foo(),3)
list(numpy.swapaxes(foo(), 0, 1))


问:
convert html in a vb.net textbox
I have a textbox which I need to enter html code into (like  or  for example).

The trouble is this is causing an error writing this back to the database.

A potentially dangerous Request.Form value was detected from the client (tbVOther="test

Is there a way around this without turning off the request validation setting?

答:
There is a server setting to prevent posting of HTML that need to be switched of for this to work, I do not remebre where though.

Just make sure that you do correct sanitisation on your own before admitting to the database ;)

Title: convert html in a vb.net textbox

ContentLicense: CC BY-SA 2.5


问:
Can one retrieve the return value of a thread function in C++11?
If a function has a non-void return value and I join it using the .join function then is there any way to retrieve its return value?

Here is a simplified example:

```<code>float myfunc(int k)
{
  return exp(k);
}

int main()
{
  std::thread th=std::thread(myfunc, 10);

  th.join();

  //Where is the return value?
}
</code>```

答:
You can follow this sample code to get the return value from a thread :-

```<code>int main()
{
  auto future = std::async(func_1, 2);

  //More code later

  int number = future.get(); //Whole program waits for this

  // Do something with number

  return 0;
}
</code>```

In short, .get() gets the return value, you can typecast and use it then.

Body:
If a function has a non-void return value and I join it using the .join function then is there any way to retrieve its return value?

Here is a simplified example:

float myfunc(int k)
{
  return exp(k);
}

int main()
{
  std::thread th=std::thread(myfunc, 10);

  th.join();

  //Where is the return value?
}

Body:
You can follow this sample code to get the return value from a thread :-

int main()
{
  auto future = std::async(func_1, 2);

  //More code later

  int number = future.get(); //Whole program waits for this

  // Do something with number

  return 0;
}

In short, .get() gets the return value, you can typecast and use it then.


问:
Stop Thread Runnable impossible
I have this thread:

```<code>myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();
</code>```

Now i need to stop this with button but nothing work, and i have tried with some code like:

```<code>Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();
</code>```

But Thread not stopping =(

答:
The accepted answer is not correct. Android does nothing to manage the threads you start, however you start them.

Technically speaking, threads cannot be "stopped". They can interrupted. Interrupting a thread just means that a flag is set, which you, in your thread's implementation, need to consider and exit from the run() method. For example,

```<code>  Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        // Do stuff
      }
    }
  });
</code>```

Then you can call t.interrupt() later on to "stop" your thread.

If you ignore the interrupted flag in your thread's implementation, your thread will never stop. For example, if you replaced // Do stuff above with SystemClock.sleep(Integer.MAX_VALUE) the thread will never exit, regardless of it being interrupted.

Many IO operations implemented in the SDK also pay attention to the interrupted flag, which is why you can interrupt a thread that's participating in blocking IO. See InterruptedException.

Title: Stop Thread Runnable impossible

Body:
I have this thread:

myThread = new Thread(new Runnable() {
                    public void run() {

                        ServerSocket ss = null;

                        while (!end) {

                            final String incomingMsg;
                            try {
                                ss = new ServerSocket(2201);
                                ss.setSoTimeout(15000);
.. some code ...
    }
                });
                myThread.start();

Now i need to stop this with button but nothing work, and i have tried with some code like:

Handler handler= new Handler();
handler.removeCallbacks(myThread);
myThread.interrupt();

But Thread not stopping =(

Body:
The accepted answer is not correct. Android does nothing to manage the threads you start, however you start them.

Technically speaking, threads cannot be "stopped". They can interrupted. Interrupting a thread just means that a flag is set, which you, in your thread's implementation, need to consider and exit from the run() method. For example,

  Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
      while (!Thread.currentThread().isInterrupted()) {
        // Do stuff
      }
    }
  });

Then you can call t.interrupt() later on to "stop" your thread.

If you ignore the interrupted flag in your thread's implementation, your thread will never stop. For example, if you replaced // Do stuff above with SystemClock.sleep(Integer.MAX_VALUE) the thread will never exit, regardless of it being interrupted.

Many IO operations implemented in the SDK also pay attention to the interrupted flag, which is why you can interrupt a thread that's participating in blocking IO. See InterruptedException.


问:
WebApi Controller is returning class name, not Json. How can I debug this?
Trying to figure out my serialization problem.

When I make a post request to my LoadById method I can't get to serialize my User class, obtaining a MyNamespace.User response instead of a JSON serialized User payload. Other methods work without any issues.

This is Web.Api ApiController..

```<code>public class UserServiceController : System.Web.Http.ApiController
{
  [HttpPost]
  public User LoadById(String id)
  {
     using (UserManager mng = new UserManager())
     {
        user = mng.LoadById(String id);

        //string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings { TraceWriter = traceWriter });
        //Console.WriteLine(traceWriter);
     }
     return user;
  }
}
</code>```

This is the trace for the serialization:

```<code>2017-11-13T15:55:58.237 Info Started serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Info Finished serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Verbose Serialized JSON: "MyNamespace.User"
</code>```

Json as string:

```<code> "MyNamespace.User"
</code>```

User class:

```<code>The user class is quite complex, i only have access to the metadata that
doesn't show much.
</code>```

how can I get more info to understand what's happening?

答:
Sorry for the delay..

I finally had the chance to check all the inherited types of my class User, and during my analysis my eyes stopped on a TypeConverter attribute.

So I remembered what user dbc suggested in a comment, try with NoTypeConverterJsonConverter, as suggested in the following answer.

Newtonsoft.JSON cannot convert model with TypeConverter attribute

Thanks to everybody for your help!

Body:
Trying to figure out my serialization problem.

When I make a post request to my LoadById method I can't get to serialize my User class, obtaining a MyNamespace.User response instead of a JSON serialized User payload. Other methods work without any issues.

This is Web.Api ApiController..

public class UserServiceController : System.Web.Http.ApiController
{
  [HttpPost]
  public User LoadById(String id)
  {
     using (UserManager mng = new UserManager())
     {
        user = mng.LoadById(String id);

        //string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings { TraceWriter = traceWriter });
        //Console.WriteLine(traceWriter);
     }
     return user;
  }
}

This is the trace for the serialization:

2017-11-13T15:55:58.237 Info Started serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Info Finished serializing MyNamespace.User. Path ''.
2017-11-13T15:55:58.237 Verbose Serialized JSON: "MyNamespace.User"

Json as string:

 "MyNamespace.User"

User class:

The user class is quite complex, i only have access to the metadata that
doesn't show much.

how can I get more info to understand what's happening?


问:
Example of Builder Pattern in Java API?
Joshua Bloch's Effective Java describes a Builder Pattern that can be used to build objects with several optionally customizable parameters.  The naming convention he suggests for the Builder functions, which "simulates named optional parameters as found in Ada and Python," doesn't seem to fall in line with Java's standard naming convention.  Java functions tend to rely on a having a verb to start the function and then a noun-based phrase to describe what it does. The Builder class only has the name of the variable that's to be defined by that function.

Are there any APIs within the Java standard libraries that makes use of the Builder Pattern?  I want to compare the suggestions in the book to an actual implementation within the core set of Java libraries before pursuing its use.

答:
Pretty good example from Java 8 Core API is Calendar, for example you can use:

Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
                        .setWeekDate(2013, 1, MONDAY).build();
```

<p>
Another good example from <code>Java 7</code> is <code>Locale</code>, use:
</p>

```Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();
```

The builder pattern is most useful in the context of immutable objects. Interestingly there are many mutable builders in Java, StringBuilder being the most common one. Mutable builders from Java 8:

Stream.Builder

IntStream.Builder

LongStream.Builder

DoubleStream.Builder

Title: Example of Builder Pattern in Java API?

Body:
Pretty good example from Java 8 Core API is Calendar, for example you can use:

Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
                        .setWeekDate(2013, 1, MONDAY).build();

Another good example from Java 7 is Locale, use:

Locale aLocale = new Builder().setLanguage("sr").setScript("Latn").setRegion("RS").build();

The builder pattern is most useful in the context of immutable objects. Interestingly there are many mutable builders in Java, StringBuilder being the most common one. Mutable builders from Java 8:

Stream.Builder

IntStream.Builder

LongStream.Builder

DoubleStream.Builder


问:
How do I configure HikariCP in my Spring Boot app in my application.properties files?
I'm trying to set up HikariCP in my Spring Boot (1.2.0.M1) app so I can test using it in place of Tomcat DBCP. I'd like to configure the connection pool in my application.properties file like I was doing with Tomcat, but I can't figure out how I should be doing it. All examples I've found show either JavaConfig style, or using a separate HikariCP properties file. Can someone help me figure out the property names to configure it in application.properties? I'd like to also switch from using the driverClassName approach to the DataSourceClassName approach since it looks cleaner and is recommended. Is this also possible in my application.properties file(s)?

Here's what I had for Tomcat DBCP (just some basic config, not fully flushed out)

```<code>spring.datasource.validation-query=SELECT 1
spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=5
spring.datasource.test-on-borrow=true
spring.datasource.test-on-return=true
</code>```

And I'm currently using driverClassName and jdbc url to set up the connection:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/myDb
spring.datasource.driverClassName=com.mysql.jdbc.Driver
</code>```

答:
With the later spring-boot releases switching to Hikari can be done entirely in configuration. I'm using 1.5.6.RELEASE and this approach works.

build.gradle:

```<code>compile "com.zaxxer:HikariCP:2.7.3"
</code>```

application YAML

```<code>spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      idleTimeout: 60000
      minimumIdle: 2
      maximumPoolSize: 20
      connectionTimeout: 30000
      poolName: MyPoolName
      connectionTestQuery: SELECT 1
</code>```

Change connectionTestQuery to suit your underlying DB. That's it, no code required.

Body:
I'm trying to set up HikariCP in my Spring Boot (1.2.0.M1) app so I can test using it in place of Tomcat DBCP. I'd like to configure the connection pool in my application.properties file like I was doing with Tomcat, but I can't figure out how I should be doing it. All examples I've found show either JavaConfig style, or using a separate HikariCP properties file. Can someone help me figure out the property names to configure it in application.properties? I'd like to also switch from using the driverClassName approach to the DataSourceClassName approach since it looks cleaner and is recommended. Is this also possible in my application.properties file(s)?

Here's what I had for Tomcat DBCP (just some basic config, not fully flushed out)

spring.datasource.validation-query=SELECT 1
spring.datasource.max-active=10
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=5
spring.datasource.test-on-borrow=true
spring.datasource.test-on-return=true

And I'm currently using driverClassName and jdbc url to set up the connection:

spring.datasource.url=jdbc:mysql://localhost:3306/myDb
spring.datasource.driverClassName=com.mysql.jdbc.Driver

Body:
With the later spring-boot releases switching to Hikari can be done entirely in configuration. I'm using 1.5.6.RELEASE and this approach works.

build.gradle:

compile "com.zaxxer:HikariCP:2.7.3"

application YAML

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      idleTimeout: 60000
      minimumIdle: 2
      maximumPoolSize: 20
      connectionTimeout: 30000
      poolName: MyPoolName
      connectionTestQuery: SELECT 1

Change connectionTestQuery to suit your underlying DB. That's it, no code required.


问:
jQuery Serialize Omits Field
I currently have the following code:

$(document).ready(function() {
  // Initialize the quilljs editor
  var quill = new Quill('.quill-editor', {
    modules: { toolbar: true },
    theme: 'snow'
  });

  $('#frmBusiness').on('submit', function(e) {
    // Prevent the sumbission
    e.preventDefault();

    // Set the path of the PHP file based on if this is a new business or an edit of an existing business
    var path = (!$('#businessHiddenId').val().trim()) ? '../php/insert_business.php' : '../php/update_business.php';

    // Set the value of the signature to the contents of the quilljs editor
    $('#businessSignature').val($('.ql-editor').html());

    // Send the AJAX request
    $.ajax({
      type: 'POST',
      url: path,
      data: $('#frmBusiness').serialize(),
      dataType: 'JSON',
      error: function(data) {console.log(data)},
      success: function(data) {
        // reload the web page
        location.reload();
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/quill/1.3.4/quill.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.quilljs.com/1.3.4/quill.snow.css" />

<form class="modal-body" id='frmBusiness'>
  <input type="text" class="d-none" disabled="disabled" id="businessHiddenId" />
  <fieldset>
    <legend>Owner Information</legend>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="businessFirstName">First Name</label>
        <input type="text" class="form-control" id="businessFirstName" name="first_name" placeholder="First name" required="required" />
      </div>
      <div class="form-group col-md-6">
        <label for="businessLastName">Last Name</label>
        <input type="text" class="form-control" id="businessLastName" name="last_name" placeholder="Last name" required="required" />
      </div>
    </div>
    <div class="form-group">
      <label for="businessEmail">Sending Email</label>
      <input type="email" class="form-control" id="businessEmail" name="email" placeholder="email@insurance.com" required="required" />
    </div>
    <div class="form-group">
      <label for="businessSignature">Signature</label>
      <input type="text" class="form-control d-none" disabled="disabled" id="businessSignature" name="signature" required="required" />
      <div class="form-control quill-editor" style="min-height: 8rem;"></div>
    </div>
  </fieldset>
  <fieldset>
    <legend>Business Information</legend>
    <div class="form-group">
      <label for="businessBusinessName">Business Name</label>
      <input type="text" class="form-control" id="businessBusinessName" name="business_name" placeholder="My Super Cool Business Name" required="required" />
    </div>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label for="businessPhone">Phone Number</label>
        <input type="tel" class="form-control" id="businessPhone" name="phone" placeholder="(555) 555-1234" required="required" />
      </div>
      <div class="form-group col-md-6">
        <label for="businessFax">Fax Number</label>
        <input type="tel" class="form-control" id="businessFax" name="fax" placeholder="(555) 555-1234" required="required" />
      </div>
    </div>
  </fieldset>
  <fieldset>
    <legend>Business Information</legend>
    <div class="form-group">
      <label for="businessAddress">Address</label>
      <input type="text" class="form-control" id="businessAddress" name="address" placeholder="123 S. Main St. STE 1" required="required" />
    </div>
    <div class="form-row">
      <div class="form-group col-md-4">
        <label for="businessCity">City</label>
        <input type="text" class="form-control" id="businessCity" name="city" placeholder="Florence" required="required" />
      </div>
      <div class="form-group col-md-4">
        <label for="businessState">State</label>
        <select class="form-control" name="state" id="businessState" required="required">
          <option value="2">AK</option><option value="1">AL</option><option value="4">AR</option><option value="3">AZ</option><option value="5">CA</option><option value="6">CO</option><option value="7">CT</option><option value="8">DC</option><option value="9">DE</option><option value="10">FL</option><option value="11">GA</option><option value="12">HI</option><option value="16">IA</option><option value="13">ID</option><option value="14">IL</option><option value="15">IN</option><option value="17">KS</option><option value="18">KY</option><option value="19">LA</option><option value="22">MA</option><option value="21">MD</option><option value="20">ME</option><option value="23">MI</option><option value="24">MN</option><option value="26">MO</option><option value="25">MS</option><option value="27">MT</option><option value="34">NC</option><option value="35">ND</option><option value="28">NE</option><option value="30">NH</option><option value="31">NJ</option><option value="32">NM</option><option value="29">NV</option><option value="33">NY</option><option value="36">OH</option><option value="37">OK</option><option value="38">OR</option><option value="39">PA</option><option value="40">RI</option><option value="41">SC</option><option value="42">SD</option><option value="43">TN</option><option value="44">TX</option><option value="45">UT</option><option value="47">VA</option><option value="46">VT</option><option value="48">WA</option><option value="50">WI</option><option value="49">WV</option><option value="51">WY</option>
        </select>
      </div>
      <div class="form-group col-md-4">
        <label for="businessZip">Zip</label>
        <input type="text" pattern="\d{5}" class="form-control" name="zip" id="businessZip" maxlength="5" placeholder="12345" required="required" />
      </div>
    </div>
  </fieldset>
  <input class="col-md-4 offset-md-8 btn btn-primary btn-block" type="submit" value="Save" />
</form></code>```

But whenever I submit the AJAX, the form.Serialize() method omits the value from my hidden input #businessSignature.

As you can tell, the input from the get-go is hidden and has no value, but just prior to the AJAX request the value is changed to get the HTML markup from the quilljs editor.

Whenever I setup a breakpoint, I verify that the val() of the hidden input is as expected, but as I mentioned the return value from the serialize method completely omits the field. I also verify that the field is omitted in the PHP file by calling print_r on the $_POST values.

What could be causing this issue? I understand that I could just pass the desired data manually, but ideally this is what the serialize method is for.

答:
serialize() ignores fields that are either disabled or do not have a name attribute.  The field you gave as an example of one that is not being serialized, businessSignature, is disabled which is why it is not being included.

It looks like you are creating your own quasi-hidden input fields by disabling them and hiding them with css.  This is unnecessary as html already has a form element type to do this for you.

```<code><input type="hidden" name="..." value="...">
</code>```

Hidden inputs are not visible to the user and will be included in the serialize, so long as they are named and not disabled.

Title: jQuery Serialize Omits Field

Body:
I currently have the following code:

$(document).ready(function() {
  // Initialize the quilljs editor
  var quill = new Quill('.quill-editor', {
    modules: { toolbar: true },
    theme: 'snow'
  });

  $('#frmBusiness').on('submit', function(e) {
    // Prevent the sumbission
    e.preventDefault();

    // Set the path of the PHP file based on if this is a new business or an edit of an existing business
    var path = (!$('#businessHiddenId').val().trim()) ? '../php/insert_business.php' : '../php/update_business.php';

    // Set the value of the signature to the contents of the quilljs editor
    $('#businessSignature').val($('.ql-editor').html());

    // Send the AJAX request
    $.ajax({
      type: 'POST',
      url: path,
      data: $('#frmBusiness').serialize(),
      dataType: 'JSON',
      error: function(data) {console.log(data)},
      success: function(data) {
        // reload the web page
        location.reload();
      }
    });
  });
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdn.quilljs.com/1.3.4/quill.snow.css" />

<form class="modal-body" id='frmBusiness'>
  <input type="text" class="d-none" disabled="disabled" id="businessHiddenId" />
  <fieldset>
    <legend>Owner Information</legend>

        First Name
        <input type="text" class="form-control" id="businessFirstName" name="first_name" placeholder="First name" required="required" />

        Last Name
        <input type="text" class="form-control" id="businessLastName" name="last_name" placeholder="Last name" required="required" />

      Sending Email
      <input type="email" class="form-control" id="businessEmail" name="email" placeholder="email@insurance.com" required="required" />

      Signature
      <input type="text" class="form-control d-none" disabled="disabled" id="businessSignature" name="signature" required="required" />

  </fieldset>
  <fieldset>
    <legend>Business Information</legend>

      Business Name
      <input type="text" class="form-control" id="businessBusinessName" name="business_name" placeholder="My Super Cool Business Name" required="required" />

        Phone Number
        <input type="tel" class="form-control" id="businessPhone" name="phone" placeholder="(555) 555-1234" required="required" />

        Fax Number
        <input type="tel" class="form-control" id="businessFax" name="fax" placeholder="(555) 555-1234" required="required" />

  </fieldset>
  <fieldset>
    <legend>Business Information</legend>

      Address
      <input type="text" class="form-control" id="businessAddress" name="address" placeholder="123 S. Main St. STE 1" required="required" />

        City
        <input type="text" class="form-control" id="businessCity" name="city" placeholder="Florence" required="required" />

        State
        <select class="form-control" name="state" id="businessState" required="required">
          <option value="2">AK</option><option value="1">AL</option><option value="4">AR</option><option value="3">AZ</option><option value="5">CA</option><option value="6">CO</option><option value="7">CT</option><option value="8">DC</option><option value="9">DE</option><option value="10">FL</option><option value="11">GA</option><option value="12">HI</option><option value="16">IA</option><option value="13">ID</option><option value="14">IL</option><option value="15">IN</option><option value="17">KS</option><option value="18">KY</option><option value="19">LA</option><option value="22">MA</option><option value="21">MD</option><option value="20">ME</option><option value="23">MI</option><option value="24">MN</option><option value="26">MO</option><option value="25">MS</option><option value="27">MT</option><option value="34">NC</option><option value="35">ND</option><option value="28">NE</option><option value="30">NH</option><option value="31">NJ</option><option value="32">NM</option><option value="29">NV</option><option value="33">NY</option><option value="36">OH</option><option value="37">OK</option><option value="38">OR</option><option value="39">PA</option><option value="40">RI</option><option value="41">SC</option><option value="42">SD</option><option value="43">TN</option><option value="44">TX</option><option value="45">UT</option><option value="47">VA</option><option value="46">VT</option><option value="48">WA</option><option value="50">WI</option><option value="49">WV</option><option value="51">WY</option>
        </select>

        Zip
        <input type="text" pattern="\d{5}" class="form-control" name="zip" id="businessZip" maxlength="5" placeholder="12345" required="required" />

  </fieldset>
  <input class="col-md-4 offset-md-8 btn btn-primary btn-block" type="submit" value="Save" />
</form>

But whenever I submit the AJAX, the form.Serialize() method omits the value from my hidden input #businessSignature.

As you can tell, the input from the get-go is hidden and has no value, but just prior to the AJAX request the value is changed to get the HTML markup from the quilljs editor.

Whenever I setup a breakpoint, I verify that the val() of the hidden input is as expected, but as I mentioned the return value from the serialize method completely omits the field. I also verify that the field is omitted in the PHP file by calling print_r on the $_POST values.

What could be causing this issue? I understand that I could just pass the desired data manually, but ideally this is what the serialize method is for.

Body:
serialize() ignores fields that are either disabled or do not have a name attribute.  The field you gave as an example of one that is not being serialized, businessSignature, is disabled which is why it is not being included.

It looks like you are creating your own quasi-hidden input fields by disabling them and hiding them with css.  This is unnecessary as html already has a form element type to do this for you.

<input type="hidden" name="..." value="...">

Hidden inputs are not visible to the user and will be included in the serialize, so long as they are named and not disabled.


问:
Number of variables doesn't match number of parameters in prepared statement in
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode</p>

```<code><?php
$con = mysqli_connect("hostname", "username", "password", "dbname");

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];

$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>
</code>```

答: I declared the five variables after a $con, and use only four of them mysqli_prepare function. Now it's working. </p>

Body:
I'm writing PHP code to send user input to the database. And http://fwtest.ga/register.php is my URL. every time I click the URL or check the JSON data in JSONLint website I get "mysqli_stmt_bind_param(): "Number of variables doesn't match a number of parameters in prepared statement" here is Mycode

<?php
$con = mysqli_connect("hostname", "username", "password", "dbname");

$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$email = $_POST["email"];
$password = $_POST["password"];
$user_id = $_POST["user_id"];

$statement = mysqli_prepare($con, "INSERT INTO `user` (first_name, last_name, email, password) VALUES
('$first_name', '$last_name', '$email', '$password')");
mysqli_stmt_bind_param($statement, 'ssss', $first_name, $last_name, $email, $password);
mysqli_stmt_execute($statement);

$response = array();
$response["success"] = true;

echo json_encode($response);
?>


问:
Reduce testing overhead when DAO contains action
For accessing objects, a Slick DAO which contains functions returning actions and objects of a stored type were created. Example:

```<code>def findByKeysAction(a: String, b: String, c: String = {
  Users.filter(x => x.a === a && x.b === b && x.c === c).result
}

def findByKeys(a: String, b: String, c: String): Future[Option[foo]] = {
  db.run(findByKeysAction(consumerId, contextId, userId)).map(_.headOption)
}
</code>```

Notice how the non-action-based function wraps the other in db.run().

What is a solid approach to test both functions and minimizing redundancy of code?

I naive method could of course be to test them both with their individual test setups (above is a simple example; there could be a lot of test setup needed to satisfy DB restrictions).

答:
Notice how the non-action-based function wraps the other in db.run().

Not really. Your findByKeys method does not call findByUserIdAction, so I'm adjusting for that minor detail in this answer.

```<code>def findByUserIdAction(userId: String) = {
  Users.filter(_.userId === userId).result
}
</code>```

The above code returns a DBIOAction. As the documentation states:

Just like a query, an I/O action is only a description of an operation. Creating or composing actions does not execute anything on a database.

As far as a user of Slick is concerned, there is no meaningful test for a DBIOAction, because by itself it does nothing; it's only a recipe for what one wants to do. To execute the above DBIOAction, you have to materialize it, which is what the following does:

```<code>def findByUserId(userId: String): Future[Option[User]] = {
  db.run(findByUserIdAction(userId)).map(_.headOption)
}
</code>```

The materialized result is what you want to test. One way to do so is to use ScalaTest's ScalaFutures trait. For example, in a spec that mixes in that trait, you could have something like:

```<code>"Users" should "return a single user by id" in {
  findByUserId("id3").futureValue shouldBe Option(User("id3", ...))
}
</code>```

Take a look at this Slick 3.2.0 test project for more examples: specifically, TestSpec and QueryCoffeesTest.

In summary, don't bother trying to test a DBIOAction in isolation; just test its materialized result.

Body:
For accessing objects, a Slick DAO which contains functions returning actions and objects of a stored type were created. Example:

def findByKeysAction(a: String, b: String, c: String = {
  Users.filter(x => x.a === a && x.b === b && x.c === c).result
}

def findByKeys(a: String, b: String, c: String): Future[Option[foo]] = {
  db.run(findByKeysAction(consumerId, contextId, userId)).map(_.headOption)
}

Notice how the non-action-based function wraps the other in db.run().

What is a solid approach to test both functions and minimizing redundancy of code?

I naive method could of course be to test them both with their individual test setups (above is a simple example; there could be a lot of test setup needed to satisfy DB restrictions).

Body:
Notice how the non-action-based function wraps the other in db.run().

Not really. Your findByKeys method does not call findByUserIdAction, so I'm adjusting for that minor detail in this answer.

def findByUserIdAction(userId: String) = {
  Users.filter(_.userId === userId).result
}

The above code returns a DBIOAction. As the documentation states:

Just like a query, an I/O action is only a description of an operation. Creating or composing actions does not execute anything on a database.

As far as a user of Slick is concerned, there is no meaningful test for a DBIOAction, because by itself it does nothing; it's only a recipe for what one wants to do. To execute the above DBIOAction, you have to materialize it, which is what the following does:

def findByUserId(userId: String): Future[Option[User]] = {
  db.run(findByUserIdAction(userId)).map(_.headOption)
}

The materialized result is what you want to test. One way to do so is to use ScalaTest's ScalaFutures trait. For example, in a spec that mixes in that trait, you could have something like:

"Users" should "return a single user by id" in {
  findByUserId("id3").futureValue shouldBe Option(User("id3", ...))
}

Take a look at this Slick 3.2.0 test project for more examples: specifically, TestSpec and QueryCoffeesTest.

In summary, don't bother trying to test a DBIOAction in isolation; just test its materialized result.


问:
Trying to run a simple app with buttons
I have to make a basic home screen with buttons and images. I was having trouble earlier with extracting string resources but I think I figured that out, and hopefully that's not interfering with the code. I don't even need the buttons to go anywhere, I just need them to appear. My code looks like this:

```<code><Button
    android:id="@+id/button4"
    android:layout_width="139dp"
    android:layout_height="74dp"
    android:text="@string/my_cookbook"

    app:layout_constraintStart_toEndOf="@+id/button2"
    app:layout_constraintTop_toTopOf="@+id/button2" />

<Button
    android:id="@+id/button2"
    android:layout_width="127dp"
    android:layout_height="0dp"
    android:layout_marginBottom="359dp"

    android:text="@string/recipes"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintEnd_toStartOf="@+id/button4"
    app:layout_constraintStart_toEndOf="@+id/imageView4"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="39dp"
    android:text="@string/check_fridge"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="59dp"
    android:layout_height="80dp"
    android:layout_marginBottom="108dp"
    android:contentDescription="@string/heart"
    app:layout_constraintBottom_toTopOf="@+id/imageView3"
    app:layout_constraintEnd_toStartOf="@+id/button2"
    app:layout_constraintStart_toEndOf="@+id/imageView5"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/heart" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="110dp"
    android:layout_marginStart="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView4"
    app:srcCompat="@drawable/fridge"
    android:contentDescription="@string/to_do"
    android:layout_marginLeft="20dp" />

<ImageView
    android:id="@+id/imageView5"
    android:layout_width="31dp"
    android:layout_height="0dp"
    android:layout_marginBottom="134dp"
    app:layout_constraintBottom_toTopOf="@+id/imageView3"
    app:layout_constraintEnd_toStartOf="@+id/imageView4"
    app:layout_constraintHorizontal_chainStyle="spread_inside"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/loaf"
    android:contentDescription="@string/to_do2" />
</code>```

And I'm not getting any errors, and it's saying my build is successful, but I can't get the app to run on my Galaxy S4. The emulators weren't working for me so I decided to use my phone to run it, but it pops up for a second and then says "App has stopped working". Any idea why it won't actually run?

答: If it is the complete XML layout file, then you're missing the "container" of the views, until you add some "container" like LinearLayout or RelativeLayout and then put the views/buttons/imageviews inside that container, it wont show anything. IF it is the complete XML code, also you should try adding a bit more code.</p>

Title: Trying to run a simple app with buttons

Body:
I have to make a basic home screen with buttons and images. I was having trouble earlier with extracting string resources but I think I figured that out, and hopefully that's not interfering with the code. I don't even need the buttons to go anywhere, I just need them to appear. My code looks like this:

<Button
    android:id="@+id/button4"
    android:layout_width="139dp"
    android:layout_height="74dp"
    android:text="@string/my_cookbook"

    app:layout_constraintStart_toEndOf="@+id/button2"
    app:layout_constraintTop_toTopOf="@+id/button2" />

<Button
    android:id="@+id/button2"
    android:layout_width="127dp"
    android:layout_height="0dp"
    android:layout_marginBottom="359dp"

    android:text="@string/recipes"
    app:layout_constraintBottom_toTopOf="@+id/button3"
    app:layout_constraintEnd_toStartOf="@+id/button4"
    app:layout_constraintStart_toEndOf="@+id/imageView4"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="39dp"
    android:text="@string/check_fridge"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/button2" />

<ImageView
    android:id="@+id/imageView4"
    android:layout_width="59dp"
    android:layout_height="80dp"
    android:layout_marginBottom="108dp"
    android:contentDescription="@string/heart"
    app:layout_constraintBottom_toTopOf="@+id/imageView3"
    app:layout_constraintEnd_toStartOf="@+id/button2"
    app:layout_constraintStart_toEndOf="@+id/imageView5"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/heart" />

<ImageView
    android:id="@+id/imageView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="110dp"
    android:layout_marginStart="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/imageView4"
    app:srcCompat="@drawable/fridge"
    android:contentDescription="@string/to_do"
    android:layout_marginLeft="20dp" />

<ImageView
    android:id="@+id/imageView5"
    android:layout_width="31dp"
    android:layout_height="0dp"
    android:layout_marginBottom="134dp"
    app:layout_constraintBottom_toTopOf="@+id/imageView3"
    app:layout_constraintEnd_toStartOf="@+id/imageView4"
    app:layout_constraintHorizontal_chainStyle="spread_inside"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/loaf"
    android:contentDescription="@string/to_do2" />

And I'm not getting any errors, and it's saying my build is successful, but I can't get the app to run on my Galaxy S4. The emulators weren't working for me so I decided to use my phone to run it, but it pops up for a second and then says "App has stopped working". Any idea why it won't actually run?


问:
Group numbers in a list in scheme?
When given a list, I have to split the list into lists that group together elements that are the same.

For example: '(37 37 39 38 38 39 38 40 40 38) has to result in '((37 37) (39 39) (38 38 38 38) (40 40))

Can anyone help me with this?

答:
Here's one way to do it:

```<code>(define (group lst)
  (let iter ((lst lst) (found null) (res null))
    (if (null? lst) ; all done ...
        (reverse res) ; ... return result (reversed)
        (let ((c (car lst))) ; isolate first element
          (if (member c found) ; already processed that
              (iter (cdr lst) found res) ; just go on with the next
              (iter (cdr lst) ; otherwise add this to found and create a list of as many elements ...
                    (cons c found) ; ... as found in the list to the current result ...
                    (cons (make-list (count (curry equal? c) lst) c) res))))))) ; ... and go on with the next
</code>```

Testing

```<code>> (group '(37 37 39 38 38 39 38 40 40 37))
'((37 37 37) (39 39) (38 38 38) (40 40))
> (group '(37 37 39 38 38 39 38 40 40 38))
'((37 37) (39 39) (38 38 38 38) (40 40))
</code>```

Title: Group numbers in a list in scheme?

Body:
Here's one way to do it:

(define (group lst)
  (let iter ((lst lst) (found null) (res null))
    (if (null? lst) ; all done ...
        (reverse res) ; ... return result (reversed)
        (let ((c (car lst))) ; isolate first element
          (if (member c found) ; already processed that
              (iter (cdr lst) found res) ; just go on with the next
              (iter (cdr lst) ; otherwise add this to found and create a list of as many elements ...
                    (cons c found) ; ... as found in the list to the current result ...
                    (cons (make-list (count (curry equal? c) lst) c) res))))))) ; ... and go on with the next

Testing

> (group '(37 37 39 38 38 39 38 40 40 37))
'((37 37 37) (39 39) (38 38 38) (40 40))
> (group '(37 37 39 38 38 39 38 40 40 38))
'((37 37) (39 39) (38 38 38 38) (40 40))


问:
Launch Linux terminal from Matlab
I want to launch a Linux terminal from a Matlab script in order to run an object file from the terminal. After launching the terminal the Matlab script has to continue.

I have tried both the unix() and system() commands, but in both the Matlab script gets stuck in the terminal script and doesn't continue.

Is there a way for a Matlab script to launch a terminal, run an executable file on it and have the Matlab script continue with the rest of the script?

答:
You'll want to launch a separate terminal application such as terminal, gnome-terminal, xterm, konsole, etc (see here) providing the -e flag followed by the command you want to run. Something like this:

```<code>system('gnome-terminal -e ''your command here'' &')
</code>```

Title: Launch Linux terminal from Matlab

Body:
You'll want to launch a separate terminal application such as terminal, gnome-terminal, xterm, konsole, etc (see here) providing the -e flag followed by the command you want to run. Something like this:

system('gnome-terminal -e ''your command here'' &')


问:
How can I redirect the "bin" and "obj" directories to a different location?
Is there a way to tell Visual Studio to use a different location for the bin and obj directories?

For example, if my project is in C:\my\myprojects.csproj, how can I have the obj and bin directories in, say, D:\otherdirectory\bin and D:\otherdirectory\obj. The Visual Studio project option offer only to redirect the bin directory, not the obj directory.

Also, bonus question: Can I use environment variables, not full or relative paths?

Is this possible?

答: In the Project-options in the tab Build you can choose the output path (in the bottom-section).</p>


问:
Transaction Synchronization in Spring Kafka
I want to synchronize a kafka transaction with a repository transaction:

```<code>@Transactional
public void syncTransaction(){
  myRepository.save(someObject)
  kafkaTemplate.send(someEvent)
}
</code>```

Since the merge (https://github.com/spring-projects/spring-kafka/issues/373) and according to the doc this is possible. Nevertheless i have problems to understand and implement that feature.
Looking at the example in https://docs.spring.io/spring-kafka/reference/html/#transaction-synchronization I have to create a MessageListenerContainer to listen to my own events.
Do I still have to send my events using the KafkaTemplate?
Does the MessageListenerContainer prohibit the sending to the broker?

And if i understand correctly the kafkaTemplate und the kafkaTransactionManager have to use the same producerFactory in which i have to enable Transaction setting a transactionIdPrefix. And in my example i have to set the TransactionManager of the messageListenerContainer to the DataSourceTransactionManager. Is that correct?

From my perspective it looks weird that I send an event via kafkaTemplate, listen to my own event and forward the event using the kafkaTemplate again.

I would really help me if i can get an example for a simple synchronization of a kafka transaction with a repository transaction and an explanation.

答:
If the listener container is provisioned with a KafkaTransactionManager, the container will create a producer which will be used by any downstream kafka template and the container will send the offsets to the transaction for you.

If the container has some other transaction manager, the container can't send the offsets since it doesn't have access to the producer (or template).

Another solution is to annotate your method with @Transactional (with the datasource TM) and configure the container with a kafka TM.

That way, your DB tx will commit just before the thread returns to the container which will then send the offsets to the kafka transaction and commit it.

See the framework test cases for examples.

Body:
I want to synchronize a kafka transaction with a repository transaction:

@Transactional
public void syncTransaction(){
  myRepository.save(someObject)
  kafkaTemplate.send(someEvent)
}

Since the merge (https://github.com/spring-projects/spring-kafka/issues/373) and according to the doc this is possible. Nevertheless i have problems to understand and implement that feature.
Looking at the example in https://docs.spring.io/spring-kafka/reference/html/#transaction-synchronization I have to create a MessageListenerContainer to listen to my own events.
Do I still have to send my events using the KafkaTemplate?
Does the MessageListenerContainer prohibit the sending to the broker?

And if i understand correctly the kafkaTemplate und the kafkaTransactionManager have to use the same producerFactory in which i have to enable Transaction setting a transactionIdPrefix. And in my example i have to set the TransactionManager of the messageListenerContainer to the DataSourceTransactionManager. Is that correct?

From my perspective it looks weird that I send an event via kafkaTemplate, listen to my own event and forward the event using the kafkaTemplate again.

I would really help me if i can get an example for a simple synchronization of a kafka transaction with a repository transaction and an explanation.


问:
DOM Not Found Error Confusion
I do the following:</p>

```<code>$container = $element->ownerDocument->createNode($tag);
if ( $anchor->hasChildNodes() &&
     is_object($anchor->lastChild) &&
     $anchor->lastChild->nodeName == 'span' &&
     $container->nodeName == 'span' ) {

        $anchor->parentNode->insertBefore($container, $anchor->lastChild);
}
</code>```

<p>(I realize that the is_object test is likely superfluous, but added it out of frustration) and on the insertBefore receive </p>

```<code>Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error'
</code>```

答:
Your attempting to insert an element based on the parentNode, but inserting it before the lastChild.  This is one generation apart.

So instead of..

```<code> $anchor->parentNode->insertBefore($container, $anchor->lastChild);
</code>```

it should be...

```<code> $anchor->insertBefore($container, $anchor->lastChild);
</code>```

Title: DOM Not Found Error Confusion

Body:
I do the following:

$container = $element->ownerDocument->createNode($tag);
if ( $anchor->hasChildNodes() &&
     is_object($anchor->lastChild) &&
     $anchor->lastChild->nodeName == 'span' &&
     $container->nodeName == 'span' ) {

        $anchor->parentNode->insertBefore($container, $anchor->lastChild);
}

(I realize that the is_object test is likely superfluous, but added it out of frustration) and on the insertBefore receive

Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error'

Body:
Your attempting to insert an element based on the parentNode, but inserting it before the lastChild.  This is one generation apart.

So instead of..

 $anchor->parentNode->insertBefore($container, $anchor->lastChild);

it should be...

 $anchor->insertBefore($container, $anchor->lastChild);


问:
Spring Injecting util:map in Kotlin with type safety
I have the several bean definitions in XML to store my SQL externally. I want to inject them in Kotlin as Map<String,String> however the only way I've been able to make it work so far it injecting it as Map<Any,Any>. Is there a way to ensure type safety here. Injecting it as Map<Any,Any> feels ghetto.

When I try Map<String,String> or even Map<String,Any> I get not qualifying beans found...

Example XML

```<code><?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <util:map id="brandSql" key-type="java.lang.String" value-type="java.lang.String">
        <entry key="selectBrands">
            <value type="java.lang.String">
                <![CDATA[
                SELECT
                    ID,
                    NAME
                FROM BRAND
                ]]>
            </value>
        </entry>
    </util:map>

</beans>
</code>```

Injection into service

```<code>@Service
open class JdbcBrandService @Autowired constructor(
    private val namedJdbcTemplate: NamedParameterJdbcTemplate
): BrandService {

    companion object {
        val logger = LoggerFactory.getLogger(JdbcBrandService::class.java)
    }

    @Autowired
    @Qualifier(value = "brandSql")
    private lateinit var queries: Map<Any,Any>

    /// methods and what not go here
}
</code>```

In Java I can get away with doing something like the following, but Kotlin's type system being more strict seems to prevent this.

```<code>@RestController
public class JavaBrandController {

    private final Map<String, String> brandSql;

    @Autowired
    public JavaBrandController(@Qualifier("brandSql") Map sql) {
        this.brandSql = sql;
    }

    @GetMapping("/javaBrands")
    public Map getBrandSql() {
        return this.brandSql;
    }
}
</code>```

答:
Personally, it feels strange to have beans floating around that are of such generic types as Map<String, String>. It would create confusion when you need other maps.

What I would do is create a container class that holds a reference to the map, so you have a proper type to reference.

Example:

```<code>class SqlConfig(val map: Map<String, String>)
</code>```

Then create a bean of this type in your xml:

```<code><util:map id="brandSql" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="selectBrands">
        <value type="java.lang.String">
            <![CDATA[
            SELECT
                ID,
                NAME
            FROM BRAND
            ]]>
        </value>
    </entry>
</util:map>

<bean id = "sqlConfig" class = "test.package.SqlConfig">
   <constructor-arg ref = "brandSql"/>
</bean>
</code>```

Now you can autowire it as needed with the proper type in a non-guetto way:

```<code>@Autowired
@Qualifier(value = "sqlConfig") // <-- the qualifier is no longer needed
private lateinit var queries: SqlConfig
</code>```

Body:
I have the several bean definitions in XML to store my SQL externally. I want to inject them in Kotlin as Map<String,String> however the only way I've been able to make it work so far it injecting it as Map<Any,Any>. Is there a way to ensure type safety here. Injecting it as Map<Any,Any> feels ghetto.

When I try Map<String,String> or even Map<String,Any> I get not qualifying beans found...

Example XML

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/util  http://www.springframework.org/schema/util/spring-util.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <util:map id="brandSql" key-type="java.lang.String" value-type="java.lang.String">
        <entry key="selectBrands">
            <value type="java.lang.String">
                <![CDATA[
                SELECT
                    ID,
                    NAME
                FROM BRAND
                ]]>
            </value>
        </entry>
    </util:map>

</beans>

Injection into service

@Service
open class JdbcBrandService @Autowired constructor(
    private val namedJdbcTemplate: NamedParameterJdbcTemplate
): BrandService {

    companion object {
        val logger = LoggerFactory.getLogger(JdbcBrandService::class.java)
    }

    @Autowired
    @Qualifier(value = "brandSql")
    private lateinit var queries: Map<Any,Any>

    /// methods and what not go here
}

In Java I can get away with doing something like the following, but Kotlin's type system being more strict seems to prevent this.

@RestController
public class JavaBrandController {

    private final Map<String, String> brandSql;

    @Autowired
    public JavaBrandController(@Qualifier("brandSql") Map sql) {
        this.brandSql = sql;
    }

    @GetMapping("/javaBrands")
    public Map getBrandSql() {
        return this.brandSql;
    }
}

Body:
Personally, it feels strange to have beans floating around that are of such generic types as Map<String, String>. It would create confusion when you need other maps.

What I would do is create a container class that holds a reference to the map, so you have a proper type to reference.

Example:

class SqlConfig(val map: Map<String, String>)

Then create a bean of this type in your xml:

<util:map id="brandSql" key-type="java.lang.String" value-type="java.lang.String">
    <entry key="selectBrands">
        <value type="java.lang.String">
            <![CDATA[
            SELECT
                ID,
                NAME
            FROM BRAND
            ]]>
        </value>
    </entry>
</util:map>

<bean id = "sqlConfig" class = "test.package.SqlConfig">
   <constructor-arg ref = "brandSql"/>
</bean>

Now you can autowire it as needed with the proper type in a non-guetto way:

@Autowired
@Qualifier(value = "sqlConfig") // <-- the qualifier is no longer needed
private lateinit var queries: SqlConfig