问:
Check if in debug mode in PowerShell
How can I check in PowerShell if my script is running in debug mode? I am currently debugging in Visual Studio 2015 with PowerShell Tools installed.

A portion of the script sends an e-mail using Send-MailMessage. I would like to do something similar to below.

```<code>If (Debug)
{
    $messageProperties.To = "$env:username@company.com"
}
Else
{
    $messageProperties.To = "prodmailbox@company.com"
}
</code>```

I know in C# that I can do something like the below. I would like to know how this is handled in PowerShell.

```<code>#if DEBUG
    // Debug code
#endif
</code>```

答:
Here's a function which allows you easily check; along with a few options to alter the behaviour.

```<code>function Test-Debug {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        ((-not $IgnoreDebugPreference.IsPresent) -and ($DebugPreference -ne "SilentlyContinue")) -or
        ((-not $IgnorePSBoundParameters.IsPresent) -and $PSBoundParameters.Debug.IsPresent) -or
        ((-not $IgnorePSDebugContext.IsPresent) -and ($PSDebugContext))
    }
}
</code>```

Here's some code to demonstrate output in certain scenarios:

```<code>#region 'Test Functions'
function Test-InheritExplicit {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        #if we weren't splatting all vars over, we could use this trick:
        #[switch]$DebugCopy = $PSBoundParameters.Debug
        #Test-Debug -Debug:$DebugCopy
        Test-Debug @PSBoundParameters
    }
}

function Test-InheritImplicit {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        Test-Debug -IgnorePSBoundParameters:$IgnorePSBoundParameters -IgnorePSDebugContext:$IgnorePSDebugContext -IgnoreDebugPreference:$IgnoreDebugPreference
    }
}
#endregion 'Test Functions'

#region 'Test Cases'
[hashtable[]]$testCases = 0..15 | %{
    [hashtable]$new = @{}
    if ($_ -band 1) {$new.Debug = [switch]$true}
    if ($_ -band 2) {$new.IgnorePSBoundParameters = [switch]$true}
    if ($_ -band 4) {$new.IgnoreDebugPreference = [switch]$true}
    if ($_ -band 8) {$new.IgnorePSDebugContext = [switch]$true}
    $new
}

[int]$t = 0
$testCases | %{
    [hashtable]$testCase = $_
    (New-Object -TypeName PSObject -Property @{
        TestId = ++$t
        Debug = [bool]$_.Debug
        IgnorePSBoundParameters = [bool]$_.IgnorePSBoundParameters
        IgnoreDebugPreference = [bool]$_.IgnoreDebugPreference
        IgnorePSDebugContext = [bool]$_.IgnorePSDebugContext
        TD = (Test-Debug @testCase)
        TIE = (Test-InheritExplicit @testCase)
        TII = (Test-InheritImplicit @testCase)
    })
} | Format-Table  TestId, Debug, IgnorePSBoundParameters, IgnoreDebugPreference, IgnorePSDebugContext, TD, TIE, TII -AutoSize
</code>```

Here's the output from the above:

```<code>TestId Debug IgnorePSBoundParameters IgnoreDebugPreference IgnorePSDebugContext    TD   TIE   TII
------ ----- ----------------------- --------------------- --------------------    --   ---   ---
     1 False                   False                 False                False False False False
     2  True                   False                 False                False  True  True  True
     3 False                    True                 False                False False False False
     4  True                    True                 False                False  True  True  True
     5 False                   False                  True                False False False False
     6  True                   False                  True                False  True  True False
     7 False                    True                  True                False False False False
     8  True                    True                  True                False False False False
     9 False                   False                 False                 True False False False
    10  True                   False                 False                 True  True  True  True
    11 False                    True                 False                 True False False False
    12  True                    True                 False                 True  True  True  True
    13 False                   False                  True                 True False False False
    14  True                   False                  True                 True  True  True False
    15 False                    True                  True                 True False False False
    16  True                    True                  True                 True False False False
</code>```

Title: Check if in debug mode in PowerShell

Body:
How can I check in PowerShell if my script is running in debug mode? I am currently debugging in Visual Studio 2015 with PowerShell Tools installed.

A portion of the script sends an e-mail using Send-MailMessage. I would like to do something similar to below.

If (Debug)
{
    $messageProperties.To = "$env:username@company.com"
}
Else
{
    $messageProperties.To = "prodmailbox@company.com"
}

I know in C# that I can do something like the below. I would like to know how this is handled in PowerShell.

#if DEBUG
    // Debug code
#endif

Body:
Here's a function which allows you easily check; along with a few options to alter the behaviour.

function Test-Debug {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        ((-not $IgnoreDebugPreference.IsPresent) -and ($DebugPreference -ne "SilentlyContinue")) -or
        ((-not $IgnorePSBoundParameters.IsPresent) -and $PSBoundParameters.Debug.IsPresent) -or
        ((-not $IgnorePSDebugContext.IsPresent) -and ($PSDebugContext))
    }
}

Here's some code to demonstrate output in certain scenarios:

#region 'Test Functions'
function Test-InheritExplicit {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        #if we weren't splatting all vars over, we could use this trick:
        #[switch]$DebugCopy = $PSBoundParameters.Debug
        #Test-Debug -Debug:$DebugCopy
        Test-Debug @PSBoundParameters
    }
}

function Test-InheritImplicit {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSBoundParameters
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnoreDebugPreference
        ,
        [Parameter(Mandatory = $false)]
        [switch]$IgnorePSDebugContext
    )
    process {
        Test-Debug -IgnorePSBoundParameters:$IgnorePSBoundParameters -IgnorePSDebugContext:$IgnorePSDebugContext -IgnoreDebugPreference:$IgnoreDebugPreference
    }
}
#endregion 'Test Functions'

#region 'Test Cases'
[hashtable[]]$testCases = 0..15 | %{
    [hashtable]$new = @{}
    if ($_ -band 1) {$new.Debug = [switch]$true}
    if ($_ -band 2) {$new.IgnorePSBoundParameters = [switch]$true}
    if ($_ -band 4) {$new.IgnoreDebugPreference = [switch]$true}
    if ($_ -band 8) {$new.IgnorePSDebugContext = [switch]$true}
    $new
}

[int]$t = 0
$testCases | %{
    [hashtable]$testCase = $_
    (New-Object -TypeName PSObject -Property @{
        TestId = ++$t
        Debug = [bool]$_.Debug
        IgnorePSBoundParameters = [bool]$_.IgnorePSBoundParameters
        IgnoreDebugPreference = [bool]$_.IgnoreDebugPreference
        IgnorePSDebugContext = [bool]$_.IgnorePSDebugContext
        TD = (Test-Debug @testCase)
        TIE = (Test-InheritExplicit @testCase)
        TII = (Test-InheritImplicit @testCase)
    })
} | Format-Table  TestId, Debug, IgnorePSBoundParameters, IgnoreDebugPreference, IgnorePSDebugContext, TD, TIE, TII -AutoSize

Here's the output from the above:

TestId Debug IgnorePSBoundParameters IgnoreDebugPreference IgnorePSDebugContext    TD   TIE   TII
------ ----- ----------------------- --------------------- --------------------    --   ---   ---
     1 False                   False                 False                False False False False
     2  True                   False                 False                False  True  True  True
     3 False                    True                 False                False False False False
     4  True                    True                 False                False  True  True  True
     5 False                   False                  True                False False False False
     6  True                   False                  True                False  True  True False
     7 False                    True                  True                False False False False
     8  True                    True                  True                False False False False
     9 False                   False                 False                 True False False False
    10  True                   False                 False                 True  True  True  True
    11 False                    True                 False                 True False False False
    12  True                    True                 False                 True  True  True  True
    13 False                   False                  True                 True False False False
    14  True                   False                  True                 True  True  True False
    15 False                    True                  True                 True False False False
    16  True                    True                  True                 True False False False


来源: stackexchange

问:
Change css through jquery after a click on a div
The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

```<code><div class="first">some text</div>
<div class ="second">bunch of text</div>
</code>```

Css

```<code>.second{display=none;}
</code>```

Jquery

```<code> $('.first').click(function() {
  $('.second').css('display', 'block');
});
</code>```

Thanks in advance

答:
In your JQuery, you forgot the period in front of second

```<code>$('.first').click(function() {
     $('.second').css('display', 'block');
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

some text

bunch of text

Css

.second{display=none;}

Jquery

 $('.first').click(function() {
  $('.second').css('display', 'block');
});

Thanks in advance

Body:
In your JQuery, you forgot the period in front of second

$('.first').click(function() {
     $('.second').css('display', 'block');
});


问:
Convert multiple year and month pay data in a monthly sum R
In R: I had two files that I have joined. Both contain commission pay data, I had two files because the pay structure periods of the jobs codes were different. For example, all the job codes in file one are paid commission monthly and all the job codes in file two are paid commission bi-monthly.
  In order to accurately and fairly analyze the data I need to aggregate (sum) pay into a new field (let's call it "monthlypay") by month for each employee id (currently a factor), my problem is that I appear to successfully sum the pay for month for each employee, but currently it ignores the differing years. I'm not opposed to spreading year and month OR dummy coding from 6/2015-6/2017 as pay months 1-24, but I'm wondering if there is a way to do this all at once?

Current:

```<code>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
2015-12-18 99999999 23231606  100880             W           1203
2015-12-24 99999999 23231606  100880             W            597
2015-12-31 99999999 23231606  100880             W            625
2016-01-08 99999999 23231606  100880             W            245
2016-01-13 99999999 23231606  100880             W            480
2016-01-15 99999999 23231606  100880             W            758
2016-01-22 99999999 23231606  100880             W            599
2016-01-29 99999999 23231606  100880             W            551
2016-02-05 99999999 23231606  100880             W            767
2016-02-12 99999999 23231606  100880             W            880
2016-02-19 99999999 23231606  100880             W            557
2016-02-26 99999999 20441606  100880             W            909
2016-03-04 99999999 20441606  100880             W            989
2016-03-11 99999999 20441606  100880             W            751
2016-03-18 99999999 20441606  100880             W            776
2016-03-25 99999999 20441606  100880             W            770
2016-04-01 99999999 20441606  100880             W            712
2016-04-08 99999999 20441606  100880             W            602
2016-04-15 99999999 20441606  100880             W            798
2016-04-22 99999999 20441606  100880             W            527
</code>```

What I want (need actually, I am going to be running cluster analysis):

```<code>>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS Year Month Pay
>2015-12-18 99999999 23231606  100880             W           1203 2015 12 2425
>2015-12-24 99999999 23231606  100880             W            597
>2015-12-31 99999999 23231606  100880             W            625
>2016-01-08 99999999 23231606  100880             W            245 2016 01 2633
>2016-01-13 99999999 23231606  100880             W            480
>2016-01-15 99999999 23231606  100880             W            758
>2016-01-22 99999999 23231606  100880             W            599
>2016-01-29 99999999 23231606  100880             W            551
>2016-02-05 99999999 23231606  100880             W            767
>2016-02-12 99999999 23231606  100880             W            880
>2016-02-19 99999999 23231606  100880             W            557
>2016-02-26 99999999 20441606  100880             W            909
>2016-03-04 99999999 20441606  100880             W            989
>2016-03-11 99999999 20441606  100880             W            751
>2016-03-18 99999999 20441606  100880             W            776
>2016-03-25 99999999 20441606  100880             W            770
>2016-04-01 99999999 20441606  100880             W            712
>2016-04-08 99999999 20441606  100880             W            602
>2016-04-15 99999999 20441606  100880             W            798
>2016-04-22 99999999 20441606  100880             W            527
</code>```

etc...I am not even opposed to the year month and date for every year and month combo to repeated, I can get rid of duplicates. As a reminder some people in the file are paid weekly and others a paid bi-monthly.

Here is what I've done:

```<code>#Convert weekly/bimonthly pay to monthly sum of pay
  paydat_all$monthlypay <- month(paydat_all$Check_DT)
  aggregate(MAX._TTL.GROSS~monthlypay+EMPLID, FUN = sum, data = paydat_all)
</code>```

Body:
In R: I had two files that I have joined. Both contain commission pay data, I had two files because the pay structure periods of the jobs codes were different. For example, all the job codes in file one are paid commission monthly and all the job codes in file two are paid commission bi-monthly.
  In order to accurately and fairly analyze the data I need to aggregate (sum) pay into a new field (let's call it "monthlypay") by month for each employee id (currently a factor), my problem is that I appear to successfully sum the pay for month for each employee, but currently it ignores the differing years. I'm not opposed to spreading year and month OR dummy coding from 6/2015-6/2017 as pay months 1-24, but I'm wondering if there is a way to do this all at once?

Current:

Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
2015-12-18 99999999 23231606  100880             W           1203
2015-12-24 99999999 23231606  100880             W            597
2015-12-31 99999999 23231606  100880             W            625
2016-01-08 99999999 23231606  100880             W            245
2016-01-13 99999999 23231606  100880             W            480
2016-01-15 99999999 23231606  100880             W            758
2016-01-22 99999999 23231606  100880             W            599
2016-01-29 99999999 23231606  100880             W            551
2016-02-05 99999999 23231606  100880             W            767
2016-02-12 99999999 23231606  100880             W            880
2016-02-19 99999999 23231606  100880             W            557
2016-02-26 99999999 20441606  100880             W            909
2016-03-04 99999999 20441606  100880             W            989
2016-03-11 99999999 20441606  100880             W            751
2016-03-18 99999999 20441606  100880             W            776
2016-03-25 99999999 20441606  100880             W            770
2016-04-01 99999999 20441606  100880             W            712
2016-04-08 99999999 20441606  100880             W            602
2016-04-15 99999999 20441606  100880             W            798
2016-04-22 99999999 20441606  100880             W            527

What I want (need actually, I am going to be running cluster analysis):

>Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS Year Month Pay
>2015-12-18 99999999 23231606  100880             W           1203 2015 12 2425
>2015-12-24 99999999 23231606  100880             W            597
>2015-12-31 99999999 23231606  100880             W            625
>2016-01-08 99999999 23231606  100880             W            245 2016 01 2633
>2016-01-13 99999999 23231606  100880             W            480
>2016-01-15 99999999 23231606  100880             W            758
>2016-01-22 99999999 23231606  100880             W            599
>2016-01-29 99999999 23231606  100880             W            551
>2016-02-05 99999999 23231606  100880             W            767
>2016-02-12 99999999 23231606  100880             W            880
>2016-02-19 99999999 23231606  100880             W            557
>2016-02-26 99999999 20441606  100880             W            909
>2016-03-04 99999999 20441606  100880             W            989
>2016-03-11 99999999 20441606  100880             W            751
>2016-03-18 99999999 20441606  100880             W            776
>2016-03-25 99999999 20441606  100880             W            770
>2016-04-01 99999999 20441606  100880             W            712
>2016-04-08 99999999 20441606  100880             W            602
>2016-04-15 99999999 20441606  100880             W            798
>2016-04-22 99999999 20441606  100880             W            527

etc...I am not even opposed to the year month and date for every year and month combo to repeated, I can get rid of duplicates. As a reminder some people in the file are paid weekly and others a paid bi-monthly.

Here is what I've done:

#Convert weekly/bimonthly pay to monthly sum of pay
  paydat_all$monthlypay <- month(paydat_all$Check_DT)
  aggregate(MAX._TTL.GROSS~monthlypay+EMPLID, FUN = sum, data = paydat_all)

Body:
Consider base R's ave for inline aggregation where:

first arg is a column to be aggregated

one or more comma-separated args afterwards are factor levels to group by

with explicit named FUN argument for aggregate type.

R script

data = 'Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS
"2015-12-18" 99999999 23231606  100880             W           1203
"2015-12-24" 99999999 23231606  100880             W            597
"2015-12-31" 99999999 23231606  100880             W            625
"2016-01-08" 99999999 23231606  100880             W            245
"2016-01-13" 99999999 23231606  100880             W            480
"2016-01-15" 99999999 23231606  100880             W            758
"2016-01-22" 99999999 23231606  100880             W            599
"2016-01-29" 99999999 23231606  100880             W            551
"2016-02-05" 99999999 23231606  100880             W            767
"2016-02-12" 99999999 23231606  100880             W            880
"2016-02-19" 99999999 23231606  100880             W            557
"2016-02-26" 99999999 20441606  100880             W            909
"2016-03-04" 99999999 20441606  100880             W            989
"2016-03-11" 99999999 20441606  100880             W            751
"2016-03-18" 99999999 20441606  100880             W            776
"2016-03-25" 99999999 20441606  100880             W            770
"2016-04-01" 99999999 20441606  100880             W            712
"2016-04-08" 99999999 20441606  100880             W            602
"2016-04-15" 99999999 20441606  100880             W            798
"2016-04-22" 99999999 20441606  100880             W            527'

paydat_all <- read.table(text=data, header=TRUE,
                         colClasses=c("Date", "character", "character",
                                      "character", "factor", "integer"))
# MONTH AND YEAR
paydat_all[c("Month", "Year")] <- sapply(c("%m", "%y"),
                                         function(d) format(paydat_all$Check_DT, d))

# THREE GROUP BY VARS WITH FORMAT() TO EXTRACT DATE TYPES
paydat_all$PaySum <- ave(paydat_all$`MAX._TTL.GROSS`, paydat_all$Month,
                         paydat_all$Year, paydat_all$EMPLID, FUN=sum)
head(paydat_all)
#     Check_DT   EMPLID   DEPTID JOBCODE PAY_FREQUENCY MAX._TTL.GROSS Month Year PaySum
# 1 2015-12-18 99999999 23231606  100880             W           1203   12    15   2425
# 2 2015-12-24 99999999 23231606  100880             W            597   12    15   2425
# 3 2015-12-31 99999999 23231606  100880             W            625   12    15   2425
# 4 2016-01-08 99999999 23231606  100880             W            245   01    16   2633
# 5 2016-01-13 99999999 23231606  100880             W            480   01    16   2633
# 6 2016-01-15 99999999 23231606  100880             W            758   01    16   2633


问:
Call "Select an element" from a sidebar button
I am developing a Google Chrome Extension for UI Web Testing. And I need to call the native Chrome selector of elements, which You can invoke by CtrlShiftC or via the toolbar:

But I want to call it after click on my button which located in the elements sidebar:

How can  I do that from a javascript click event of a button?

答:
There's no way to invoke the built-in element selector from within the extension. Well, except the weird method of writing a separately installable native OS application that communicates with your extension via nativeMessaging API and sends a click event to the toolbar or triggers the hotkey.

A workable solution though is to use a 3rd-party JavaScript library that imitates the element selector behavior and once the element is selected you can highlight it in the Elements panel.


问:
How to view error logs generated by mariadb on CentOS 7
I am new to mariadb. Today, I was attempting to import a mysql database to mariadb and during the process the import stops when a warning is encountered as shown below.

Now, I said to myself that I should check a log file so I can see the error but I can't seem to fine any log file. I ran the query below with help from Get the error log of Mariadb:

As you can see there is no path to an error log file.

Next I checked /var/lib/mysql and below is the dir content:

```<code>-rw-rw----. 1 mysql mysql    16384 Jun  5 16:03 aria_log.00000001
-rw-rw----. 1 mysql mysql       52 Jun  5 16:03 aria_log_control
-rw-rw----. 1 mysql mysql 79691776 Jun  8 08:02 ibdata1
-rw-rw----. 1 mysql mysql 50331648 Jun  8 08:02 ib_logfile0
-rw-rw----. 1 mysql mysql 50331648 Jun  5 16:03 ib_logfile1
-rw-rw----. 1 mysql mysql        6 Jun  5 16:12 IMSPRO.pid
drwx------. 2 mysql mysql     4096 Jun  8 08:02 ecommence
-rw-rw----. 1 mysql mysql        0 Jun  5 16:12 multi-master.info
drwx--x--x. 2 mysql mysql     4096 Jun  5 16:03 mysql
srwxrwxrwx. 1 mysql mysql        0 Jun  5 16:12 mysql.sock
drwx------. 2 mysql mysql       20 Jun  5 16:03 performance_schema
-rw-rw----. 1 mysql mysql    24576 Jun  5 16:12 tc.log
</code>```

No file in the above dir logs error.

Below is the content of my /etc/my.cnf

```<code>#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d
</code>```

Below is the content of /etc/my.cnf.d

```<code>drwxr-xr-x.  2 root root  117 Jun  5 16:02 .
drwxr-xr-x. 91 root root 8192 Jun  7 01:14 ..
-rw-r--r--.  1 root root  295 May 29 16:48 client.cnf
-rw-r--r--.  1 root root  763 May 29 16:48 enable_encryption.preset
-rw-r--r--.  1 root root  232 May 29 16:48 mysql-clients.cnf
-rw-r--r--.  1 root root 1080 May 29 16:48 server.cnf
-rw-r--r--.  1 root root  285 May 29 16:48 tokudb.cnf
</code>```

What can I do to get error log?

答:
The way to see the warnings is to type this immediately after receiving that "Warnings: 1":

```<code> SHOW WARNINGS;
</code>```

(As soon as the next other command is run, the warnings are cleared.)

Body:
I am new to mariadb. Today, I was attempting to import a mysql database to mariadb and during the process the import stops when a warning is encountered as shown below.

Now, I said to myself that I should check a log file so I can see the error but I can't seem to fine any log file. I ran the query below with help from Get the error log of Mariadb:

As you can see there is no path to an error log file.

Next I checked /var/lib/mysql and below is the dir content:

-rw-rw----. 1 mysql mysql    16384 Jun  5 16:03 aria_log.00000001
-rw-rw----. 1 mysql mysql       52 Jun  5 16:03 aria_log_control
-rw-rw----. 1 mysql mysql 79691776 Jun  8 08:02 ibdata1
-rw-rw----. 1 mysql mysql 50331648 Jun  8 08:02 ib_logfile0
-rw-rw----. 1 mysql mysql 50331648 Jun  5 16:03 ib_logfile1
-rw-rw----. 1 mysql mysql        6 Jun  5 16:12 IMSPRO.pid
drwx------. 2 mysql mysql     4096 Jun  8 08:02 ecommence
-rw-rw----. 1 mysql mysql        0 Jun  5 16:12 multi-master.info
drwx--x--x. 2 mysql mysql     4096 Jun  5 16:03 mysql
srwxrwxrwx. 1 mysql mysql        0 Jun  5 16:12 mysql.sock
drwx------. 2 mysql mysql       20 Jun  5 16:03 performance_schema
-rw-rw----. 1 mysql mysql    24576 Jun  5 16:12 tc.log

No file in the above dir logs error.

Below is the content of my /etc/my.cnf

#
# This group is read both both by the client and the server
# use it for options that affect everything
#
[client-server]

#
# include all files from the config directory
#
!includedir /etc/my.cnf.d

Below is the content of /etc/my.cnf.d

drwxr-xr-x.  2 root root  117 Jun  5 16:02 .
drwxr-xr-x. 91 root root 8192 Jun  7 01:14 ..
-rw-r--r--.  1 root root  295 May 29 16:48 client.cnf
-rw-r--r--.  1 root root  763 May 29 16:48 enable_encryption.preset
-rw-r--r--.  1 root root  232 May 29 16:48 mysql-clients.cnf
-rw-r--r--.  1 root root 1080 May 29 16:48 server.cnf
-rw-r--r--.  1 root root  285 May 29 16:48 tokudb.cnf

What can I do to get error log?

Body:
The way to see the warnings is to type this immediately after receiving that "Warnings: 1":

 SHOW WARNINGS;

(As soon as the next other command is run, the warnings are cleared.)


问:
Render a custom .jsx Component in $.ajax -ReactJS-
I have next:

```<code>export default class FormularioVerRespuestaInforme extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        $.ajax({
            url: APIBASENAME+"/delegado/informes/" + ObtenerParametroURL('id_informe') + "/entradas",
            data: "",
            type: "GET"
            //dataType: "JSON",
        })
        .done((respuesta) => {
            console.log(respuesta);
            $("#idDivContenedorInforme").append(
                <Caja title="f">
                    <textarea disabled id="idContenidoInforme" class="form-control" value="Hola esto es una prueba del informe y sus respuestas" required></textarea>
                </Caja>
            )
            //this.props.history.push(`/accion_realizada?estado=${respuesta.estado}&backTwice=true`);
        }).fail((xhr, textStatus, errorThrown) => {
            console.log("XHR: ", xhr.responseText);
            //this.props.history.push(`/accion_realizada?estado=Incidencia Rechazada`);
        })
    }

    render() {
        return (
            <div id="idDivContenedorInforme" class="formularioRespuestasInforme"></div>
        );
    }
}
</code>```

Where Caja is a custom component, but it is not returned / renderized. I do not know how could I solve this... Any idea?

Thank you a lot for your help.

答:
To render that component conditionally use state variable, create a state variable with initial value of false, once you get the response update that value to true by using setState.

Write it like this:

```<code>export default class FormularioVerRespuestaInforme extends React.Component {
    constructor() {
        super();
        this.state={
            show: false
        }
    }

    componentDidMount() {
        $.ajax({
            url: APIBASENAME+"/delegado/informes/" + ObtenerParametroURL('id_informe') + "/entradas",
            data: "",
            type: "GET"
            //dataType: "JSON",
        })
        .done((respuesta) => {
            this.setState({show: true});
        }).fail((xhr, textStatus, errorThrown) => {
            console.log("XHR: ", xhr.responseText);
        })
    }

    render() {
        return (
            <div id="idDivContenedorInforme" class="formularioRespuestasInforme">
                {this.state.show?
                    <Caja title="f">
                        <textarea disabled id="idContenidoInforme" class="form-control" value="Hola esto es una prueba del informe y sus respuestas" required></textarea>
                    </Caja>
                :
                    null
                }
            </div>
        );
    }
}
</code>```

Update:  Caja is a custom component, so instead of passing the textarea as children put that part inside Caja component only, if you want to pass some data (initial values) then pass those values only in props.

Using map inside jsx:

class App extends React.Component {

  constructor(){
     super();
  }

  render(){
     return(

          {
            [1,2,3,4,5].map(el => {
               return
 Item: {el}

            })
          }

     )
  }

}

ReactDOM.render(<App/>, document.getElementById('app'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/></code>```

Body:
I have next:

export default class FormularioVerRespuestaInforme extends React.Component {
    constructor() {
        super();
    }

    componentDidMount() {
        $.ajax({
            url: APIBASENAME+"/delegado/informes/" + ObtenerParametroURL('id_informe') + "/entradas",
            data: "",
            type: "GET"
            //dataType: "JSON",
        })
        .done((respuesta) => {
            console.log(respuesta);
            $("#idDivContenedorInforme").append(
                <Caja title="f">
                    <textarea disabled id="idContenidoInforme" class="form-control" value="Hola esto es una prueba del informe y sus respuestas" required></textarea>
                </Caja>
            )
            //this.props.history.push(`/accion_realizada?estado=${respuesta.estado}&backTwice=true`);
        }).fail((xhr, textStatus, errorThrown) => {
            console.log("XHR: ", xhr.responseText);
            //this.props.history.push(`/accion_realizada?estado=Incidencia Rechazada`);
        })
    }

    render() {
        return (

        );
    }
}

Where Caja is a custom component, but it is not returned / renderized. I do not know how could I solve this... Any idea?

Thank you a lot for your help.

Body:
To render that component conditionally use state variable, create a state variable with initial value of false, once you get the response update that value to true by using setState.

Write it like this:

export default class FormularioVerRespuestaInforme extends React.Component {
    constructor() {
        super();
        this.state={
            show: false
        }
    }

    componentDidMount() {
        $.ajax({
            url: APIBASENAME+"/delegado/informes/" + ObtenerParametroURL('id_informe') + "/entradas",
            data: "",
            type: "GET"
            //dataType: "JSON",
        })
        .done((respuesta) => {
            this.setState({show: true});
        }).fail((xhr, textStatus, errorThrown) => {
            console.log("XHR: ", xhr.responseText);
        })
    }

    render() {
        return (
            <div id="idDivContenedorInforme" class="formularioRespuestasInforme">
                {this.state.show?
                    <Caja title="f">
                        <textarea disabled id="idContenidoInforme" class="form-control" value="Hola esto es una prueba del informe y sus respuestas" required></textarea>
                    </Caja>
                :
                    null
                }
            </div>
        );
    }
}

Update:  Caja is a custom component, so instead of passing the textarea as children put that part inside Caja component only, if you want to pass some data (initial values) then pass those values only in props.

Using map inside jsx:

class App extends React.Component {

  constructor(){
     super();
  }

  render(){
     return(
        <div>
          {
            [1,2,3,4,5].map(el => {
               return <div key={el}> Item: {el} </div>
            })
          }
        </div>
     )
  }

}

ReactDOM.render(<App/>, document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>


答:
Use $.toggle() to toggle display

$('.first').click(function() {
  $('.second').toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.second{display=none;}</code>```

some text

bunch of text
```

Title: Change css through jquery after a click on a div

Body:
Use $.toggle() to toggle display

$('.first').click(function() {
  $('.second').toggle();
});

.second{display=none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">some text</div>
<div class ="second">bunch of text</div>


问:
Create multiindex from existing dataframe
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

```<code>newmulti = currentDataFrame.set_index(['user_id','account_num'])
</code>```

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!

答:
The DataFrame returned by currentDataFrame.set_index(['user_id','account_num']) has it's index set to ['user_id','account_num']

newmulti.index will return the MultiIndex object.

Body:
I've spent hours browsing everywhere now to try to create a multiindex from dataframe in pandas. This is the dataframe I have (posting excel sheet mockup. I do have this in pandas dataframe):

And this is what I want:

I have tried

newmulti = currentDataFrame.set_index(['user_id','account_num'])

But it returns a dataframe, not a multiindex. Also, I could not figure out how to make 'user_id' level 0 and 'account_num' level 1. I think this must be trivial but I've read so many posts, tutorials, etc. and still could not figure it out. Partly because I'm a very visual person and most posts are not. Please help!


问:
MVC Dynamic Partial View Data Disappearing In IE7
I'm having problems with dynamic partial view data disappearing from the textbox after a httppost. Here is my scenario:

The user clicks a radio button, and the coapplicant partial view is loaded dynamically.

Index.aspx (Embedded Javascript):

```<code>function showCoApplicant() {
 $.ajax({
  type: "GET",
  url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
  data: {},
  dataType: "html",
  async: true,
  success: function (data) {
   $("#CoApplicantInfo").html(data);
  }
 }); }
</code>```

ApplicationController.cs:

```<code>public ActionResult LoadCoApplicantInfo() {
 Configurator.Models.CreditApplicationModel model = null;
 if (Session["model"] != null)
  model = (Configurator.Models.CreditApplicationModel)Session["model"];

 return PartialView("CoApplicant", model);
}
</code>```

CoApplicant.ascx:

```<code><table>
 <tr>
  <th>
   <%= Html.LabelFor(model => model.CoApplicant.FirstName)%>
  </th>
  <td>
   <%= Html.TextBoxFor(model => model.CoApplicant.FirstName)%>
   <%= Html.ValidationMessageFor(model => model.CoApplicant.FirstName)%>
  </td>
 </tr>
</table>
</code>```

The user enters in data, and clicks the submit button. The model is then validated in the controller. If the ModelState is invalid, I return the view along with the model in session (I do this because I need to return that model to the partial view. This was the only way I could get the data back to it.). On httppost, in Javascript, I determine if the coapplicant partial view should be showing, and if so, I load it again by calling showCoApplicant().

```<code>[HttpPost]
 public ActionResult Index(Configurator.Models.CreditApplicationModel model)
 {
 if (!ModelState.IsValid)
 {
  Session["model"] = model;
        return View();
 }
 }
</code>```

This is where I have the problem. The data for the coapplicant is missing in IE7. It works fine in other versions of IE, Chrome, and Firefox. Why is the data missing in IE7? How can I get it to show?

答:
In your ajax call, try setting cache to false:</p>

```<code>function showCoApplicant() {
   $.ajax({
   type: "GET",
   cache: false,
   url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
   data: {},
   dataType: "html",
   async: true,
   success: function (data) {
   $("#CoApplicantInfo").html(data);
   }
  }); }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm having problems with dynamic partial view data disappearing from the textbox after a httppost. Here is my scenario:

The user clicks a radio button, and the coapplicant partial view is loaded dynamically.

Index.aspx (Embedded Javascript):

function showCoApplicant() {
 $.ajax({
  type: "GET",
  url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
  data: {},
  dataType: "html",
  async: true,
  success: function (data) {
   $("#CoApplicantInfo").html(data);
  }
 }); }

ApplicationController.cs:

public ActionResult LoadCoApplicantInfo() {
 Configurator.Models.CreditApplicationModel model = null;
 if (Session["model"] != null)
  model = (Configurator.Models.CreditApplicationModel)Session["model"];

 return PartialView("CoApplicant", model);
}

CoApplicant.ascx:

   <%= Html.LabelFor(model => model.CoApplicant.FirstName)%>

   <%= Html.TextBoxFor(model => model.CoApplicant.FirstName)%>
   <%= Html.ValidationMessageFor(model => model.CoApplicant.FirstName)%>

The user enters in data, and clicks the submit button. The model is then validated in the controller. If the ModelState is invalid, I return the view along with the model in session (I do this because I need to return that model to the partial view. This was the only way I could get the data back to it.). On httppost, in Javascript, I determine if the coapplicant partial view should be showing, and if so, I load it again by calling showCoApplicant().

[HttpPost]
 public ActionResult Index(Configurator.Models.CreditApplicationModel model)
 {
 if (!ModelState.IsValid)
 {
  Session["model"] = model;
        return View();
 }
 }

This is where I have the problem. The data for the coapplicant is missing in IE7. It works fine in other versions of IE, Chrome, and Firefox. Why is the data missing in IE7? How can I get it to show?

Body:
In your ajax call, try setting cache to false:

function showCoApplicant() {
   $.ajax({
   type: "GET",
   cache: false,
   url: '<%= Url.Action("LoadCoApplicantInfo","Application") %>',
   data: {},
   dataType: "html",
   async: true,
   success: function (data) {
   $("#CoApplicantInfo").html(data);
   }
  }); }


问:
Wildcard expression to search records in Dynamics CRM from an external app in Azure
I need to make a external web app that connects to Dynamics CRM. I need to make it on Azure and connected to Dynamics CRM online.

The real challenge is that I need to have a textbox in the web app, and my idea is while I write, I want to see account records of CRM. Additionally I want to use wildcards while I find (e. g. ABC* should be showing me instantly customers that start with ABC).

I am trying with queryexpression but I have not been able to do that.

答:
You have to use ConditionOperator.Like

```<code>ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "attribute_name";
condition1.Operator = ConditionOperator.Like;
condition1.Values.Add(acc_name.ToLower() + "%");
</code>```

Ref: https://crmbusiness.wordpress.com/2011/04/20/crm-2011-how-to-do-like-statement-in-queryexpression/

Body:
You have to use ConditionOperator.Like

ConditionExpression condition1 = new ConditionExpression();
condition1.AttributeName = "attribute_name";
condition1.Operator = ConditionOperator.Like;
condition1.Values.Add(acc_name.ToLower() + "%");

Ref: https://crmbusiness.wordpress.com/2011/04/20/crm-2011-how-to-do-like-statement-in-queryexpression/


问:
Tensorflow 'nan' Loss and '-inf' weights, Even with 0 Learning Rate
I am training Deep Convolutional Neural Network on AWS GPU Machine.
Dataset -> Google SVHN
Training Size -> 200,000+

I get Loss = 'nan' and W = '-inf'

Even with 0 Learning Rate

```<code>Loss at step 0: 14.024256
Minibatch accuracy: 5.8%
Learning rate :  0.0
W :  [ 0.1968164   0.19992708  0.19999388  0.19999997]
b :  [ 0.1  0.1  0.1  0.1]

Loss at step 52: 14.553226
Minibatch accuracy: 5.9%
Learning rate :  0.0
W :  [ 0.19496706  0.19928116  0.19977403  0.1999999 ]
b :  [ 0.1  0.1  0.1  0.1]

# STEP 53 ---> LOSS : NAN, ALL WEIGHTS STILL OKAY
Loss at step 53: nan
Minibatch accuracy: 6.4%
Learning rate :  0.0
W :  [ 0.19496706  0.19928116  0.19977403  0.1999999 ]
b :  [ 0.1  0.1  0.1  0.1]

# STEP 54 ---> LOSS : NAN, WEIGHTS START GOINT TO -INF
Loss at step 54: nan
Minibatch accuracy: 49.2%
Learning rate :  0.0
W :  [       -inf        -inf  0.19694112        -inf]
b :  [-inf -inf  0.1 -inf]

# STEP 54 ---> LOSS : NAN, W & B  -INF
Loss at step 55: nan
Minibatch accuracy: 46.9%
Learning rate :  0.0
W :  [-inf -inf -inf -inf]
b :  [-inf -inf -inf -inf]
</code>```

I have tried following techniques:

Used Several Different Optimisers (Adam, SGD, etc)

Used different Activation functions on last layer (ReLU, Sigmoid, tanH)

Initialized Weights and biases in different ways

Tried Different Learning rates and rate-decays (from 0.001 to 0.0001)

I thought there might be an error in my dataset, so removed first 10000 entries. Didn't work

None of these things seemed to work for me.
I am still getting 'nan' loss after 1500 steps.

My Code :

Weight Initalization

```<code>W1 = tf.Variable(tf.truncated_normal([6, 6, 1, K], stddev=0.1))
B1 = tf.Variable(tf.constant(0.1, tf.float32, [K]))
# Similarly W2, B2, W3, B3, W4 and B4

W5_1 = tf.Variable(tf.truncated_normal([N, 11], stddev=0.1))
B5_1 = tf.Variable(tf.constant(0.1, tf.float32, [11]))
# Similarly W5_2, B5_2, W5_3, B5_3, W5_4, B5_4, W5_5, B5_5,

# Model
Y1 = tf.nn.relu(tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='SAME') + B1)
# Similarly Y2 and Y3 with stride 2

shape = Y3.get_shape().as_list()
YY = tf.reshape(Y3, shape=[-1, shape[1] * shape[2] * shape[3]])
Y4 = tf.sigmoid(tf.matmul(YY, W4) + B4)
YY4 = tf.nn.dropout(Y4, pkeep)

Ylogits_1 = tf.matmul(YY4, W5_1) + B5_1
# Ylogits_2,3,4,5

Y_1 = tf.nn.softmax(Ylogits_1)
# Y_2,3,4,5
</code>```

Loss

```<code>cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(Ylogits_1, Y_[:,1])) +\
# ....... (Ylogits_5, Y_[:,5]))

train_prediction = tf.pack([Y_1, Y_2, Y_3, Y_4, Y_5])
train_step = tf.train.AdamOptimizer(alpha).minimize(cross_entropy)

W_s = tf.pack([tf.reduce_max(tf.abs(W1)),tf.reduce_max(tf.abs(W2)),tf.reduce_max(tf.abs(W3)),tf.reduce_max(tf.abs(W4))])
b_s = tf.pack([tf.reduce_max(tf.abs(B1)),tf.reduce_max(tf.abs(B2)),tf.reduce_max(tf.abs(B3)),tf.reduce_max(tf.abs(B4))])

model_saver = tf.train.Saver()
</code>```

Tensorflow Session

```<code>for step in range(num_steps):
    # I have set the Learning Rate = 0
    learning_rate = 0
    batch_data = train_data[step*batch_size:(step + 1)*batch_size, :, :, :]
    batch_labels = label_data[step*batch_size:(step + 1)*batch_size, :]

    feed_dict = {X : batch_data, Y_ : batch_labels, pkeep : 0.80, alpha : learning_rate}
    _, l, train_pred, W, b = session.run([train_step, cross_entropy, train_prediction, W_s, b_s], feed_dict=feed_dict)

    if (step % 20 == 0):
        print('Loss at step %d: %f' % (step, l))
        print('Minibatch accuracy: %.1f%%' % acc(train_pred, batch_labels[:,1:6]))
        print('Learning rate : ', learning_rate)
        print('W : ', W)
        print('b : ', b)
        print('    ')
</code>```

Since No learning takes place if Learning Rate is 0, How can loss and weights change and ho to nan and -inf.

Any Help is appreciated.

答:
While I cannot say for certain what problem your code has, there are two general ways to debug NaN's and Inf's that I can recommmend.

The first is simply going over your code and look for any operation that might not be defined over its input. The operations that come to my mind immediately (since they are very common) are division (by 0) and logs (of negative values). This includes part of your code where this is not obvious, since you apply a more complex function that entails these operations. In your code, this include stf.reduce_mean (which includes a problematic division if your input set sums to 0 - which might happen if it has length 0, too).

The second is one of tensorflow's most useful op's: tf.add_check_numerics_ops that creates an op (i.e. an operation that you need to call with session.run) that will tell you which computation node is either inf of nan ...

Body:
I am training Deep Convolutional Neural Network on AWS GPU Machine.
Dataset -> Google SVHN
Training Size -> 200,000+

I get Loss = 'nan' and W = '-inf'

Even with 0 Learning Rate

Loss at step 0: 14.024256
Minibatch accuracy: 5.8%
Learning rate :  0.0
W :  [ 0.1968164   0.19992708  0.19999388  0.19999997]
b :  [ 0.1  0.1  0.1  0.1]

Loss at step 52: 14.553226
Minibatch accuracy: 5.9%
Learning rate :  0.0
W :  [ 0.19496706  0.19928116  0.19977403  0.1999999 ]
b :  [ 0.1  0.1  0.1  0.1]

# STEP 53 ---> LOSS : NAN, ALL WEIGHTS STILL OKAY
Loss at step 53: nan
Minibatch accuracy: 6.4%
Learning rate :  0.0
W :  [ 0.19496706  0.19928116  0.19977403  0.1999999 ]
b :  [ 0.1  0.1  0.1  0.1]

# STEP 54 ---> LOSS : NAN, WEIGHTS START GOINT TO -INF
Loss at step 54: nan
Minibatch accuracy: 49.2%
Learning rate :  0.0
W :  [       -inf        -inf  0.19694112        -inf]
b :  [-inf -inf  0.1 -inf]

# STEP 54 ---> LOSS : NAN, W & B  -INF
Loss at step 55: nan
Minibatch accuracy: 46.9%
Learning rate :  0.0
W :  [-inf -inf -inf -inf]
b :  [-inf -inf -inf -inf]

I have tried following techniques:

Used Several Different Optimisers (Adam, SGD, etc)

Used different Activation functions on last layer (ReLU, Sigmoid, tanH)

Initialized Weights and biases in different ways

Tried Different Learning rates and rate-decays (from 0.001 to 0.0001)

I thought there might be an error in my dataset, so removed first 10000 entries. Didn't work

None of these things seemed to work for me.
I am still getting 'nan' loss after 1500 steps.

My Code :

Weight Initalization

W1 = tf.Variable(tf.truncated_normal([6, 6, 1, K], stddev=0.1))
B1 = tf.Variable(tf.constant(0.1, tf.float32, [K]))
# Similarly W2, B2, W3, B3, W4 and B4

W5_1 = tf.Variable(tf.truncated_normal([N, 11], stddev=0.1))
B5_1 = tf.Variable(tf.constant(0.1, tf.float32, [11]))
# Similarly W5_2, B5_2, W5_3, B5_3, W5_4, B5_4, W5_5, B5_5,

# Model
Y1 = tf.nn.relu(tf.nn.conv2d(X, W1, strides=[1, 1, 1, 1], padding='SAME') + B1)
# Similarly Y2 and Y3 with stride 2

shape = Y3.get_shape().as_list()
YY = tf.reshape(Y3, shape=[-1, shape[1] * shape[2] * shape[3]])
Y4 = tf.sigmoid(tf.matmul(YY, W4) + B4)
YY4 = tf.nn.dropout(Y4, pkeep)

Ylogits_1 = tf.matmul(YY4, W5_1) + B5_1
# Ylogits_2,3,4,5

Y_1 = tf.nn.softmax(Ylogits_1)
# Y_2,3,4,5

Loss

cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(Ylogits_1, Y_[:,1])) +\
# ....... (Ylogits_5, Y_[:,5]))

train_prediction = tf.pack([Y_1, Y_2, Y_3, Y_4, Y_5])
train_step = tf.train.AdamOptimizer(alpha).minimize(cross_entropy)

W_s = tf.pack([tf.reduce_max(tf.abs(W1)),tf.reduce_max(tf.abs(W2)),tf.reduce_max(tf.abs(W3)),tf.reduce_max(tf.abs(W4))])
b_s = tf.pack([tf.reduce_max(tf.abs(B1)),tf.reduce_max(tf.abs(B2)),tf.reduce_max(tf.abs(B3)),tf.reduce_max(tf.abs(B4))])

model_saver = tf.train.Saver()

Tensorflow Session

for step in range(num_steps):
    # I have set the Learning Rate = 0
    learning_rate = 0
    batch_data = train_data[step*batch_size:(step + 1)*batch_size, :, :, :]
    batch_labels = label_data[step*batch_size:(step + 1)*batch_size, :]

    feed_dict = {X : batch_data, Y_ : batch_labels, pkeep : 0.80, alpha : learning_rate}
    _, l, train_pred, W, b = session.run([train_step, cross_entropy, train_prediction, W_s, b_s], feed_dict=feed_dict)

    if (step % 20 == 0):
        print('Loss at step %d: %f' % (step, l))
        print('Minibatch accuracy: %.1f%%' % acc(train_pred, batch_labels[:,1:6]))
        print('Learning rate : ', learning_rate)
        print('W : ', W)
        print('b : ', b)
        print('    ')

Since No learning takes place if Learning Rate is 0, How can loss and weights change and ho to nan and -inf.

Any Help is appreciated.


问:
Chrome console script to select options in a drop down menu
I have a page with a lot of food items there are a few options for me to select for each food item. I want to sequentially select Order for everything on the menu. Is there a script to make this happen? Thanks! </p>

```<code><select class="form-control" onchange="setFlag(999$(this).val(),$('option:selected', this).html());">                                                                               </select>
    <option value="Order"> Make this order </option>
    <option value="Veto"> Veto this order </option>
</code>```

答:
HTML

```<code><select id="sel">
<option value="Order"> Make this order </option>
<option value="Veto"> Veto this order </option>
  </select>
</code>```

JS

```<code>document.querySelector("#sel").value = "Veto" // selects 2nd option from dropdown
</code>```

Body:
I have a page with a lot of food items there are a few options for me to select for each food item. I want to sequentially select Order for everything on the menu. Is there a script to make this happen? Thanks!

<select class="form-control" onchange="setFlag(999$(this).val(),$('option:selected', this).html());">                                                                               </select>
    <option value="Order"> Make this order </option>
    <option value="Veto"> Veto this order </option>

Body:
HTML

<select id="sel">
<option value="Order"> Make this order </option>
<option value="Veto"> Veto this order </option>
  </select>

JS

document.querySelector("#sel").value = "Veto" // selects 2nd option from dropdown


问:
Python: building an LRU cache
I have around 6,00,000 entries in MongoDB in the following format:

```<code>feature:category:count
</code>```

where

feature could be any word,

category is positive or negative, and

count tells how many times a feature occurred in a document for that category.

I want to cache the top 1000 tuples, let's say so as not to query database each time.

How does one build an LRU cache in Python?  Or are there any known solutions to this?

答: Besides the version included in Python 3.2, there are LRU cache recipes in the Python Cookbook including these by Python core developer Raymond Hettinger.</p>

Title: Python: building an LRU cache

Body:
I have around 6,00,000 entries in MongoDB in the following format:

feature:category:count

where

feature could be any word,

category is positive or negative, and

count tells how many times a feature occurred in a document for that category.

I want to cache the top 1000 tuples, let's say so as not to query database each time.

How does one build an LRU cache in Python?  Or are there any known solutions to this?


答:
Use  $('.second').toggle();

 $('.first').click(function() {
  $('.second').toggle();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.second{display=none;}</code>```

some text

bunch of text
```

Body:
The below code isn't working, Is there anything wrong in this code, when I click on div.first it has to show div.second and a click again should make it display none.

Html

some text

bunch of text

Css

.second{display=none;}

Jquery

 $('.first').click(function() {
  $('.second').css('display', 'block');
});

Thanks in advance

Body:
Use  $('.second').toggle();

 $('.first').click(function() {
  $('.second').toggle();
});

.second{display=none;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">some text</div>
<div class ="second">bunch of text</div>


答:
You simply need this

```<code>$('.first').click(function() {
  $('.second').toggle();
});
</code>```

Here is an example

$('.first').click(function() {
  $('.second').toggle();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first">some text</div>
<div class ="second">bunch of text</div></code>```

Body:
You simply need this

$('.first').click(function() {
  $('.second').toggle();
});

Here is an example

$('.first').click(function() {
  $('.second').toggle();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="first">some text</div>
<div class ="second">bunch of text</div>


问:
creating query in C# console (Visual studio 2013)
hello every one when i create querygenerate Assign dollar will be Error how can i fixed </p>

```<code>query = "INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer)"
+ $"VALUES("{name}","{answerList[0]}","{answerList[1]}","{answerList[2]}","{answerList[3]}","{name}");";

Error 1 Unexpected character '$'
Error 2 Invalid expression term ''
Error 3 ; expected
</code>```

答:
This should be the right way to create that script

```<code>var query = $"INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer) VALUES('{name}','{answerList[0]}','{answerList[1]}','{answerList[2]}','{answerList[3]}','{name}');";
</code>```

And as we always say, We (the community) strongly recommend you to use parameterized queries.

Body:
hello every one when i create querygenerate Assign dollar will be Error how can i fixed

query = "INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer)"
+ $"VALUES("{name}","{answerList[0]}","{answerList[1]}","{answerList[2]}","{answerList[3]}","{name}");";

Error 1 Unexpected character '$'
Error 2 Invalid expression term ''
Error 3 ; expected

Body:
This should be the right way to create that script

var query = $"INSERT INTO Question(Image,AnswerA,AnswerB,AnswerC,AnswerD,CorrectAnswer) VALUES('{name}','{answerList[0]}','{answerList[1]}','{answerList[2]}','{answerList[3]}','{name}');";

And as we always say, We (the community) strongly recommend you to use parameterized queries.


答:
I would take a look at this answer https://stackoverflow.com/a/6068322/1115876

something like

```<code>$('[value="Order"]').prop('selected', true)
</code>```

should work

Title: Chrome console script to select options in a drop down menu

Body:
I would take a look at this answer https://stackoverflow.com/a/6068322/1115876

something like

$('[value="Order"]').prop('selected', true)

should work


问:
Font issue with PDFtk
I'm having difficulties filling in a form using pdftk with text fields with true type fonts.

Font files (.ttf) are added to /Library/Fonts (OSX Mavericks)

The form is created with Adobe Acrobat Pro

The form includes normal (non form) text using these fonts

The form text fields also use these fonts

The form can successfully be filled and printed using Adobe Acrobat Pro and even Preview

However, pdftk throws an error when trying to fill it using the command:

```<code>pdftk ./my_form.pdf fill_form my_data.fdf output ./the_output.pdf
</code>```

The output is:

```<code>Unhandled Java Exception in create_output():
java.lang.ArrayIndexOutOfBoundsException: 0
   at pdftk.com.lowagie.text.pdf.DocumentFont.fillEncoding(pdftk)
   at pdftk.com.lowagie.text.pdf.DocumentFont.doType1TT(pdftk)
   at pdftk.com.lowagie.text.pdf.DocumentFont.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.getAppearance(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.setField(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.setFields(pdftk)
</code>```

If I change the font of the text inputs to Helvetica, Times Roman or Courier, pdftk will successfully create a PDF. Oddly though, Arial and Georgia also throw the same error.

I have tried to no avail to embed the fonts in the PDF using Ghostscript as suggested in this question How to repair a PDF file and embed missing fonts. gs may have embedded the fonts, but it removes the form fields so the resulting PDF can't feed back into pdftk.

A working resolution would be greatly appreciated.

答:
I was getting the same java.lang.ArrayIndexOutOfBoundsException: 0 error using pdftk to fill forms on an Adobe Acrobat generated PDF. This question is super old, but I couldn't find a consistent answer on stackoverflow or elsewhere so I figured I'd post my fix.

What ended up working for me:

Opening the PDF in the OS X app Preview

Clicking into a form field, adding text then deleting that text (so nothing is actually changed)

Saving it

Running the PDF through pdftk again

I'm not that familiar with encoding or PDFs in general, but saving the PDF with Preview seems to fix the encoding or at least get it to a place where pdftk can work with it. Good luck.

Title: Font issue with PDFtk

Body:
I'm having difficulties filling in a form using pdftk with text fields with true type fonts.

Font files (.ttf) are added to /Library/Fonts (OSX Mavericks)

The form is created with Adobe Acrobat Pro

The form includes normal (non form) text using these fonts

The form text fields also use these fonts

The form can successfully be filled and printed using Adobe Acrobat Pro and even Preview

However, pdftk throws an error when trying to fill it using the command:

pdftk ./my_form.pdf fill_form my_data.fdf output ./the_output.pdf

The output is:

Unhandled Java Exception in create_output():
java.lang.ArrayIndexOutOfBoundsException: 0
   at pdftk.com.lowagie.text.pdf.DocumentFont.fillEncoding(pdftk)
   at pdftk.com.lowagie.text.pdf.DocumentFont.doType1TT(pdftk)
   at pdftk.com.lowagie.text.pdf.DocumentFont.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.getAppearance(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.setField(pdftk)
   at pdftk.com.lowagie.text.pdf.AcroFields.setFields(pdftk)

If I change the font of the text inputs to Helvetica, Times Roman or Courier, pdftk will successfully create a PDF. Oddly though, Arial and Georgia also throw the same error.

I have tried to no avail to embed the fonts in the PDF using Ghostscript as suggested in this question How to repair a PDF file and embed missing fonts. gs may have embedded the fonts, but it removes the form fields so the resulting PDF can't feed back into pdftk.

A working resolution would be greatly appreciated.


问:
Nesting two ng-repeats
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

```<code><tbody>
    <tr class="admin-detail-rows" ng-repeat="lesson in lessons | orderBy:sortType:sortReverse">
       <div ng-repeat="group in lesson.groups">
           <td>{{ working_days[lesson.day - 1] }}</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}</td>
           <td>{{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}</td>
           <td>{{ lesson.room }}</td>
           <td>{{ lesson.teacher }}</td>
           <td>{{ group.group_name }}</td>
           <td>{{ lesson.groupDetails  }}</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
      </div>
   </tr>
</tbody>
</code>```

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

```<code> {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}
</code>```

Assigning the lesson to the scope:

```<code>$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});
</code>```

What am I doing wrong?

答:
As your row should show lessons - your first ng-repeat should be at tr
and then second ng-repeat at td level.
HTML:

```<code><div ng-app="testApp" ng-controller="testCtrl">
<table>
<thead>
        <tr>
          <td>working_days</td>
          <td>lesson.start_time - lesson.end_time</td>
          <td>group.available_seats / group.max_seats</td>
          <td>lesson.room</td>
          <td>lesson.teacher</td>
          <td>group.group_name</td>
          <td>lesson.groupDetails </td>
        </tr>
      </thead>
  <tbody  ng-repeat="lesson in lessons ">
  <tr ng-repeat="group in lesson.groups">
     <td >working_days {{lesson.day - 1}}</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}</td>
           <td >{{ group.available_seats  }} / {{ group.max_seats }}</td>
           <td>{{ lesson.room }}</td>
           <td>{{ lesson.teacher }}</td>
           <td>{{ group.group_name }}</td>
           <td>{{ lesson.groupDetails  }}</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
  </tr>

      </tbody>

</table>
</div>
</code>```

JS:

```<code>angular.module('testApp',[]).controller('testCtrl', function($scope){

        $scope.lessons  =[
    {
        "id": 140,
        "course_id": 156,
        "start_time": "08:45",
        "end_time": "10:30",
        "day": 2,
        "type": 1,
        "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
        "room": "OVk.41 left",
        "teacher": "Kerkhof van de B.K.W.",
        "created_at": "2017-04-11 13:43:29",
        "course": {
            "id": 156,
            "code": "ES-ISBMDIMEUR-16",
            "name": "The Business Dimension of Europe",
            "credits": 3,
            "category_id": 20,
            "entry_requirements": null,
            "assessment_materials": null,
            "study_materials": null,
            "outline": null,
            "description": null,
            "created_at": "2017-04-11 13:41:45"
        },
        "groups": [
            {
                "id": 181,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "P",
                "group_details": null,
                "max_seats": 3,
                "available_seats": -4,
                "created_at": "2017-04-11 13:43:29"
            },
            {
                "id": 182,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "Q",
                "group_details": null,
                "max_seats": 3,
                "available_seats": null,
                "created_at": "2017-04-11 13:43:29"
            },
            {
                "id": 183,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "R",
                "group_details": null,
                "max_seats": 3,
                "available_seats": null,
                "created_at": "2017-04-11 13:43:29"
            }
        ]
    }
];

 });
</code>```

And for you Working days, it should be working_days {{lesson.day - 1}} unless if you have a different list variable
Check the demo: https://jsfiddle.net/sathvike/efq9djpy/

Title: Nesting two ng-repeats

Body:
I'm trying to show some data in a table with two ng-repeats. But the second ng-repeat doesn't seem to work. This is what I'm trying:

           {{ working_days[lesson.day - 1] }}
           {{ lesson.start_time }} - {{ lesson.end_time }}
           {{ group.available_seats ? group.max_seats - group.available_seats : 0 }} / {{ group.max_seats }}
           {{ lesson.room }}
           {{ lesson.teacher }}
           {{ group.group_name }}
           {{ lesson.groupDetails  }}
           ✖

But it never does the second repeat more than once, and it doesn't know a lot of the properties.

A lesson that I'm iterating through in the first ng-repeat could look like this:

 {
    "id":140,
    "course_id":156,
    "start_time":"08:45",
    "end_time":"10:30",
    "day":2,
    "type":1,
    "course_description":"The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
    "room":"OVk.41 left",
    "teacher":"Test teacher","created_at":"2017-04-11 13:43:29",
    "course": {
    "id":156,
    "code":"Test code",
    "name":"The Business Dimension of Europe",
    "credits":3,
    "category_id":20,
    "entry_requirements":null,
    "assessment_materials":null,
    "study_materials":null,
    "outline":null,
    "description":null,
    "created_at":"2017-04-11 13:41:45"
},
    "groups":[{
    "id":181,"timetable_id":140,
    "course_id":156,
    "group_name":"P",
    "group_details":null,
    "max_seats":3,
    "available_seats":-4,
    "created_at":"2017-04-11 13:43:29"
    }, {
    "id":182,
    "timetable_id":140,
    "course_id":156,
    "group_name":"Q",
    "group_details":null,"max_seats":3,
    "available_seats":null,
    "created_at":"2017-04-11 13:43:29"
    },{"id":183,
    "timetable_id":140,
    "course_id":156,
    "group_name":"R",
    "group_details":null,
    "max_seats":3,"available_seats":null,
    "created_at":"2017-04-11 13:43:29"}
    ]}

Assigning the lesson to the scope:

$scope.$watch(function () {
  return lessonsService.getLessons();
}, function (lessons) {
  $scope.lessons = lessons;
});

What am I doing wrong?

Body:
As your row should show lessons - your first ng-repeat should be at tr
and then second ng-repeat at td level.
HTML:

<div ng-app="testApp" ng-controller="testCtrl">
<table>
<thead>
        <tr>
          <td>working_days</td>
          <td>lesson.start_time - lesson.end_time</td>
          <td>group.available_seats / group.max_seats</td>
          <td>lesson.room</td>
          <td>lesson.teacher</td>
          <td>group.group_name</td>
          <td>lesson.groupDetails </td>
        </tr>
      </thead>
  <tbody  ng-repeat="lesson in lessons ">
  <tr ng-repeat="group in lesson.groups">
     <td >working_days {{lesson.day - 1}}</td>
           <td>{{ lesson.start_time }} - {{ lesson.end_time }}</td>
           <td >{{ group.available_seats  }} / {{ group.max_seats }}</td>
           <td>{{ lesson.room }}</td>
           <td>{{ lesson.teacher }}</td>
           <td>{{ group.group_name }}</td>
           <td>{{ lesson.groupDetails  }}</td>
           <td ng-click="removeLesson(lesson)" class="delete-button">✖</td>
  </tr>

      </tbody>

</table>
</div>

JS:

angular.module('testApp',[]).controller('testCtrl', function($scope){

        $scope.lessons  =[
    {
        "id": 140,
        "course_id": 156,
        "start_time": "08:45",
        "end_time": "10:30",
        "day": 2,
        "type": 1,
        "course_description": "The Business Dimension of Europe (lecture; group P:3+Q:3+R:3)",
        "room": "OVk.41 left",
        "teacher": "Kerkhof van de B.K.W.",
        "created_at": "2017-04-11 13:43:29",
        "course": {
            "id": 156,
            "code": "ES-ISBMDIMEUR-16",
            "name": "The Business Dimension of Europe",
            "credits": 3,
            "category_id": 20,
            "entry_requirements": null,
            "assessment_materials": null,
            "study_materials": null,
            "outline": null,
            "description": null,
            "created_at": "2017-04-11 13:41:45"
        },
        "groups": [
            {
                "id": 181,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "P",
                "group_details": null,
                "max_seats": 3,
                "available_seats": -4,
                "created_at": "2017-04-11 13:43:29"
            },
            {
                "id": 182,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "Q",
                "group_details": null,
                "max_seats": 3,
                "available_seats": null,
                "created_at": "2017-04-11 13:43:29"
            },
            {
                "id": 183,
                "timetable_id": 140,
                "course_id": 156,
                "group_name": "R",
                "group_details": null,
                "max_seats": 3,
                "available_seats": null,
                "created_at": "2017-04-11 13:43:29"
            }
        ]
    }
];

 });

And for you Working days, it should be working_days {{lesson.day - 1}} unless if you have a different list variable
Check the demo: https://jsfiddle.net/sathvike/efq9djpy/


问:
"No project ID could be determined from the Cloud SDK configuration" when running psqworker
When I was going through the Google Cloud tutorial: https://cloud.google.com/python/getting-started/using-pub-sub#running_the_app_on_your_local_machine

I got the following error:

google.auth._default No project ID could be determined from the Cloud SDK configuration. Consider running gcloud config set project or setting the GOOGLE_CLOUD_PROJECT environment variable

I did 'gcloud config set project [my project name]' with no success.

What's the problem?

Update: I've deployed app engines previously without any problem. The problem only happens when I run the psqworker for this Pub/Sub function. I know my project ID and used it before.

答:
The first thing I would try would be:

gcloud info

This will tell you the account and project that gcloud is currently set to.

You may also find the available projects for your account with the following gcloud command:

gcloud projects list


问:
Issue on ngOptions track by
I have some issue with AngularJs option/selector which I uses ngOptions to create. The problem I have is that it doesn't trigger the method I have in ngChange. I found out that's because in actionList the name property isn't unique. So if I change so they are unique it will works as intended. However I want them to be named like how it is now.

So I guess I could try something like ng-options="action.name for action in ctrl.actionList track by action.value". But it doesn't work. Anyone who can help me out here?

HTML

```<code><select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>
</code>```

Data structure

```<code>actionList = [{
    name: "Running Man"
    value: "RUN"
}, {
    name: "Running Man"
    value: "JUMP"
}]
</code>```

JS

```<code>public onChangeAction(): void {
    console.log(this.settingAction);
}
</code>```

答:
You seem to be using 'controller as' syntax. Can you confirm that the onChangeAction() function is being set in the vm/self like this?

```<code>var vm = this;
vm.onChangeAction = function (): void {
    console.log(this.settingAction);
}
</code>```

Title: Issue on ngOptions track by

Body:
I have some issue with AngularJs option/selector which I uses ngOptions to create. The problem I have is that it doesn't trigger the method I have in ngChange. I found out that's because in actionList the name property isn't unique. So if I change so they are unique it will works as intended. However I want them to be named like how it is now.

So I guess I could try something like ng-options="action.name for action in ctrl.actionList track by action.value". But it doesn't work. Anyone who can help me out here?

HTML

<select id="someOptions" class="dropdown dropdown-md"
    ng-model="ctrl.settingAction"
    ng-change="ctrl.onChangeAction()"
    ng-options="action.name for action in ctrl.actionList">
</select>

Data structure

actionList = [{
    name: "Running Man"
    value: "RUN"
}, {
    name: "Running Man"
    value: "JUMP"
}]

JS

public onChangeAction(): void {
    console.log(this.settingAction);
}

Body:
You seem to be using 'controller as' syntax. Can you confirm that the onChangeAction() function is being set in the vm/self like this?

var vm = this;
vm.onChangeAction = function (): void {
    console.log(this.settingAction);
}


问:
UFT scripting will highlight object, but won't click it
Why does the WebElement object highlight just fine, but the click doesn't do anything?

Browser is Chrome.

Statement are:

```<code>Browser("Message Validators | ETT").Page("Message Validators | ETT").WebElement("css:=SPAN.btn.btn-default").Highlight

Browser("Message Validators | ETT").Page("Message Validators | ETT").WebElement("css:=SPAN.btn.btn-default").Click
</code>```

答:
Setting.WebPackage will do the trick. Tested the code on Chrome.

```<code>'~~> Runs mouse operations using the mouse
Setting.WebPackage("ReplayType") = 2
Browser("name:=Message Validators.*ETT").Page("title:=Message Validators.*ETT").WebElement("xpath:=//span[contains(.,'Upload File')]").Click
'~~> Runs mouse operations using browser events
Setting.WebPackage("ReplayType") = 1
</code>```

Body:
Why does the WebElement object highlight just fine, but the click doesn't do anything?

Browser is Chrome.

Statement are:

Browser("Message Validators | ETT").Page("Message Validators | ETT").WebElement("css:=SPAN.btn.btn-default").Highlight

Browser("Message Validators | ETT").Page("Message Validators | ETT").WebElement("css:=SPAN.btn.btn-default").Click

Body:
Setting.WebPackage will do the trick. Tested the code on Chrome.

'~~> Runs mouse operations using the mouse
Setting.WebPackage("ReplayType") = 2
Browser("name:=Message Validators.*ETT").Page("title:=Message Validators.*ETT").WebElement("xpath:=//span[contains(.,'Upload File')]").Click
'~~> Runs mouse operations using browser events
Setting.WebPackage("ReplayType") = 1


问:
Oracle sql pattern sorting
I have a pattern like this - "pqrst ##ind##123456##ind## hggff 1234". I have to extract numbers between ##ind## and ##ind##. Using pl/sql. Suggest</p>

答:
Try this:

```<code>select  to_number(trim(
            replace(
                    replace(
                            'pqrst ##ind##123456##ind## hggff 1234',
                            SUBSTR('pqrst ##ind##123456##ind## hggff 1234', 1, INSTR('pqrst ##ind##123456##ind## hggff 1234', '#',1,4)), -- <-- 4th occurrence of "#"
                            null),
                    SUBSTR('pqrst ##ind##123456##ind## hggff 1234', INSTR('pqrst ##ind##123456##ind## hggff 1234', '#',1,5), -- <-- 5th occurrence of "#"
                    length('pqrst ##ind##123456##ind## hggff 1234')),
                    null)
        )) as result
from dual;
</code>```

Works by identifying 4th and 5th occurrence of '#' and just extracting string from between them.

Title: Oracle sql pattern sorting

Body:
Try this:

select  to_number(trim(
            replace(
                    replace(
                            'pqrst ##ind##123456##ind## hggff 1234',
                            SUBSTR('pqrst ##ind##123456##ind## hggff 1234', 1, INSTR('pqrst ##ind##123456##ind## hggff 1234', '#',1,4)), -- <-- 4th occurrence of "#"
                            null),
                    SUBSTR('pqrst ##ind##123456##ind## hggff 1234', INSTR('pqrst ##ind##123456##ind## hggff 1234', '#',1,5), -- <-- 5th occurrence of "#"
                    length('pqrst ##ind##123456##ind## hggff 1234')),
                    null)
        )) as result
from dual;

Works by identifying 4th and 5th occurrence of '#' and just extracting string from between them.


问:
Am I marshalling this C function correctly in C#?
In C#, I am trying to PInvoke the following C method:

```<code>// C code:
BOOL VstSetLineDetail(
   tVstHdl pDataHdl, // type is void*
   long pLineItemNo,
   tVstTransType pTransType, // enum type
   tVstTransSubType pTransSubType, // enum type
   tVstTransCd pTransCd, // enum type
   char *pTransDate,
   tVstTaxedGeo *pTaxedGeoFlag, // enum type
   double *pExtdAmt,
   double *pTotalTax,
   double *pCombRate,
   char *pUserArea,
   tVstTaxingJuris *pTaxingJuris, // enum type
   char *pCustExmtCertifNum,
   char *pDivCd,
   char *pStoreCd,
   char *pGLAcct)
</code>```

I am marshalling it in C# the following way:

```<code>// C# code:
[DllImport(@"VertexNative\Vst.dll")]
public static extern bool VstSetLineDetail(
   [In]IntPtr dataHandle,
   [In]long lineItemNumber,
   [In]VstTransactionType transactionType, // an enum I defined in C#
   [In]VstTransactionSubtype transactionSubtype, // C# enum
   [In]VstTransactionCode transactionCode, // C# enum
   [In]string transactionDate,
   [In]ref VstTaxedGeo taxedGeo, // C# enum
   [In]ref double totalAmount,
   [In]ref double totalTax,
   [In]ref double combinedTaxRate,
   [In]string userArea,
   [In]ref VstTaxingJurisdiction jurisdiction, // C# enum
   [In]string exceptionCertificate,
   [In]string divisionCode,
   [In]string storeCode,
   [In]string generalLedgerAccount);
</code>```

Calling it always produces a System.AccessViolationException. I've tried many combinations of values when calling the function, but get no better results. Can anyone tell me if it looks like I am marshalling the data types correctly?

It would be great if I had access to the C source code so I could debug, but it's a third-party set of DLLs. I can only see the header files.

The enums in C are:

```<code>typedef enum
{
    eVstTransTypeIgnore = 99,   /* Means ignore this parameter */
    eVstTransTypeSale = 0,
    eVstTransTypePurchase,
    eVstTransTypeService,
    eVstTransTypeRentalLease,
    eVstTransTypeNumElems,
    eVstTransTypeFirstElem = eVstTransTypeSale
} tVstTransType;

typedef enum
{
    eVstTransSubTypeIgnore = 99,    /* Means ignore this parameter */
    eVstTransSubTypeNone = 0,
    eVstTransSubTypeProperty,
    eVstTransSubTypeFreight,
    eVstTransSubTypeService,
    eVstTransSubTypeRentalLease,
    eVstTransSubTypeExpense,
    eVstTransSubTypeMisc,
    eVstTransSubTypeNumElems,
    eVstTransSubTypeFirstElem = eVstTransSubTypeNone
} tVstTransSubType;

typedef enum
{
    eVstTransCdIgnore = 99, /* Means ignore this parameter */
    eVstTransCdNormal = 0,
    eVstTransCdAdjustment,
    eVstTransCdTaxOnlyDebit,
    eVstTransCdTaxOnlyCredit,
    eVstTransCdDistributeRate,
    eVstTransCdDistributeTax,
    eVstTransCdNumElems,
    eVstTransCdFirstElem = eVstTransCdNormal
} tVstTransCd;

typedef enum
{
    eVstTaxedGeoNone = 0,
    eVstTaxedGeoDetermine,
    eVstTaxedGeoShipTo,
    eVstTaxedGeoShipFrom,
    eVstTaxedGeoOrderAccept,
    eVstTaxedGeoNumElems,
    eVstTaxedGeoFirstElem = eVstTaxedGeoNone
} tVstTaxedGeo;

typedef enum {
    eVstTaxingJurisPrimary,
    eVstTaxingJurisAddtl,
    eVstTaxingJurisNumElems,
    eVstTaxingJurisFirstElem = eVstTaxingJurisPrimary
} tVstTaxingJuris;
</code>```

And I've defined them in C# as:

```<code>public enum VstTransactionType
{
      Sale,
      Purchase,
      Service,
      RentalLease,
      Ignore = 99
}

public enum VstTransactionSubtype
{
     None,
     Property,
     Freight,
     Service,
     RentalLease,
     Expense,
     Misc,
     Ignore = 99
}

public enum VstTransactionCode
{
     Normal,
     Adjustment,
     TaxOnlyDebit,
     TaxOnlyCredit,
     DistributeRate,
     DistributeTax,
     Ignore = 99
}

public enum VstTaxedGeo
{
     None,
     Determine,
     ShipTo,
     ShipFrom,
     OrderAccept
}

public enum VstTaxingJurisdiction
{
      Primary,
      Additional
}
</code>```

答: No, it's not right, because long in C isn't 8 bytes like it is in C# (it's often 4 bytes). Also, a char* isn't necessarily a string, because strings are meant to be immutable, and you can only safely marshal them to const char*, since only that can guarantee that the C code won't modify them. If you need to make them mutable, use StringBuilder instead of string, and use [MarshalAs(UnmanagedType.LPTStr)] or the like.

Body:
In C#, I am trying to PInvoke the following C method:

// C code:
BOOL VstSetLineDetail(
   tVstHdl pDataHdl, // type is void*
   long pLineItemNo,
   tVstTransType pTransType, // enum type
   tVstTransSubType pTransSubType, // enum type
   tVstTransCd pTransCd, // enum type
   char *pTransDate,
   tVstTaxedGeo *pTaxedGeoFlag, // enum type
   double *pExtdAmt,
   double *pTotalTax,
   double *pCombRate,
   char *pUserArea,
   tVstTaxingJuris *pTaxingJuris, // enum type
   char *pCustExmtCertifNum,
   char *pDivCd,
   char *pStoreCd,
   char *pGLAcct)

I am marshalling it in C# the following way:

// C# code:
[DllImport(@"VertexNative\Vst.dll")]
public static extern bool VstSetLineDetail(
   [In]IntPtr dataHandle,
   [In]long lineItemNumber,
   [In]VstTransactionType transactionType, // an enum I defined in C#
   [In]VstTransactionSubtype transactionSubtype, // C# enum
   [In]VstTransactionCode transactionCode, // C# enum
   [In]string transactionDate,
   [In]ref VstTaxedGeo taxedGeo, // C# enum
   [In]ref double totalAmount,
   [In]ref double totalTax,
   [In]ref double combinedTaxRate,
   [In]string userArea,
   [In]ref VstTaxingJurisdiction jurisdiction, // C# enum
   [In]string exceptionCertificate,
   [In]string divisionCode,
   [In]string storeCode,
   [In]string generalLedgerAccount);

Calling it always produces a System.AccessViolationException. I've tried many combinations of values when calling the function, but get no better results. Can anyone tell me if it looks like I am marshalling the data types correctly?

It would be great if I had access to the C source code so I could debug, but it's a third-party set of DLLs. I can only see the header files.

The enums in C are:

typedef enum
{
    eVstTransTypeIgnore = 99,   /* Means ignore this parameter */
    eVstTransTypeSale = 0,
    eVstTransTypePurchase,
    eVstTransTypeService,
    eVstTransTypeRentalLease,
    eVstTransTypeNumElems,
    eVstTransTypeFirstElem = eVstTransTypeSale
} tVstTransType;

typedef enum
{
    eVstTransSubTypeIgnore = 99,    /* Means ignore this parameter */
    eVstTransSubTypeNone = 0,
    eVstTransSubTypeProperty,
    eVstTransSubTypeFreight,
    eVstTransSubTypeService,
    eVstTransSubTypeRentalLease,
    eVstTransSubTypeExpense,
    eVstTransSubTypeMisc,
    eVstTransSubTypeNumElems,
    eVstTransSubTypeFirstElem = eVstTransSubTypeNone
} tVstTransSubType;

typedef enum
{
    eVstTransCdIgnore = 99, /* Means ignore this parameter */
    eVstTransCdNormal = 0,
    eVstTransCdAdjustment,
    eVstTransCdTaxOnlyDebit,
    eVstTransCdTaxOnlyCredit,
    eVstTransCdDistributeRate,
    eVstTransCdDistributeTax,
    eVstTransCdNumElems,
    eVstTransCdFirstElem = eVstTransCdNormal
} tVstTransCd;

typedef enum
{
    eVstTaxedGeoNone = 0,
    eVstTaxedGeoDetermine,
    eVstTaxedGeoShipTo,
    eVstTaxedGeoShipFrom,
    eVstTaxedGeoOrderAccept,
    eVstTaxedGeoNumElems,
    eVstTaxedGeoFirstElem = eVstTaxedGeoNone
} tVstTaxedGeo;

typedef enum {
    eVstTaxingJurisPrimary,
    eVstTaxingJurisAddtl,
    eVstTaxingJurisNumElems,
    eVstTaxingJurisFirstElem = eVstTaxingJurisPrimary
} tVstTaxingJuris;

And I've defined them in C# as:

public enum VstTransactionType
{
      Sale,
      Purchase,
      Service,
      RentalLease,
      Ignore = 99
}

public enum VstTransactionSubtype
{
     None,
     Property,
     Freight,
     Service,
     RentalLease,
     Expense,
     Misc,
     Ignore = 99
}

public enum VstTransactionCode
{
     Normal,
     Adjustment,
     TaxOnlyDebit,
     TaxOnlyCredit,
     DistributeRate,
     DistributeTax,
     Ignore = 99
}

public enum VstTaxedGeo
{
     None,
     Determine,
     ShipTo,
     ShipFrom,
     OrderAccept
}

public enum VstTaxingJurisdiction
{
      Primary,
      Additional
}


问:
Text Analysis in R - word frequency
I only have R available at work and I have done this before in Python. I need to get a count of each set of incidents in a CSV file. I have done a sentiment analysis in Python, where I had a dictionary Python searched in a  provided a table with the count for each phrase. I am researching how to do this in R and have only found ways to do a general word count using a predetermined frequency. </p>

<p>Please let me know if anyone has any resource links on how to perform this in R. Thank you :) </p>

答:
The package tidytext is a good solution.  Another option is to use the text mining package tm:

```<code>library(tm)
df<-read.csv(myfile)

corpus<-Corpus(VectorSource(df$text))
corpus<-tm_map(corpus, content_transformer(tolower))
corpus<-tm_map(corpus, removeNumbers)
corpus<-tm_map(corpus, removeWords, stopwords('english'))
#corpus<-tm_map(corpus, stemDocument, language = "english")
corpus<-tm_map(corpus, removePunctuation)

tdm<-TermDocumentMatrix(corpus)

tdmatrix<-as.matrix(tdm)
wordfreq<-sort(rowSums(tdmatrix), decreasing = TRUE)
</code>```

the code example cleans up the text by removing stop words, any numbers and punctuation.  The final answer wordfreq is ready for with the wordcloud package if interested.

Title: Text Analysis in R - word frequency

Body:
I only have R available at work and I have done this before in Python. I need to get a count of each set of incidents in a CSV file. I have done a sentiment analysis in Python, where I had a dictionary Python searched in a  provided a table with the count for each phrase. I am researching how to do this in R and have only found ways to do a general word count using a predetermined frequency.

Please let me know if anyone has any resource links on how to perform this in R. Thank you :)

Body:
The package tidytext is a good solution.  Another option is to use the text mining package tm:

library(tm)
df<-read.csv(myfile)

corpus<-Corpus(VectorSource(df$text))
corpus<-tm_map(corpus, content_transformer(tolower))
corpus<-tm_map(corpus, removeNumbers)
corpus<-tm_map(corpus, removeWords, stopwords('english'))
#corpus<-tm_map(corpus, stemDocument, language = "english")
corpus<-tm_map(corpus, removePunctuation)

tdm<-TermDocumentMatrix(corpus)

tdmatrix<-as.matrix(tdm)
wordfreq<-sort(rowSums(tdmatrix), decreasing = TRUE)

the code example cleans up the text by removing stop words, any numbers and punctuation.  The final answer wordfreq is ready for with the wordcloud package if interested.


问:
Enter on a file, modify the rows and overwrite the file. With a .bat file
I am doing some modifications on a text file; however the program is adding lines instead of modifying them.

As i am new to it, can you help or guide me?

Here is my code:

```<code>setlocal enabledelayedexpansion
for /f "delims=" %%a in (economic_changes.txt) do (
   SET s='%%a
   SET s=!s:;= !
   SET s=!s:- =-;;!
   SET s=!s: -=-!
   SET s=!s:-;;-=-;-!
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s!
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"
</code>```

答:
Since the same file cannot be read and written at the same time, create a temporary file to store the changed lines into.

Several of the modifications have a SPACE character at the end. Using quotes makes it clear where those occur. Perhaps you want those. I do not know.

Then, of course, delete the temporary file once completed.

```<code>setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
   SET "s='%%a "
   SET "s=!s:;= ! "
   SET "s=!s:- =-;;! "
   SET "s=!s: -=-! "
   SET "s=!s:-;;-=-;-! "
   SET "s=!s:-=%!"
   SET "s=!s:_= %!"
   SET "s=!s:;=';'%!"
   SET "s=!s:;'';'=;;%!"

   echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")
</code>```

Body:
I am doing some modifications on a text file; however the program is adding lines instead of modifying them.

As i am new to it, can you help or guide me?

Here is my code:

setlocal enabledelayedexpansion
for /f "delims=" %%a in (economic_changes.txt) do (
   SET s='%%a
   SET s=!s:;= !
   SET s=!s:- =-;;!
   SET s=!s: -=-!
   SET s=!s:-;;-=-;-!
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s!
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"

Body:
Since the same file cannot be read and written at the same time, create a temporary file to store the changed lines into.

Several of the modifications have a SPACE character at the end. Using quotes makes it clear where those occur. Perhaps you want those. I do not know.

Then, of course, delete the temporary file once completed.

setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
   SET "s='%%a "
   SET "s=!s:;= ! "
   SET "s=!s:- =-;;! "
   SET "s=!s: -=-! "
   SET "s=!s:-;;-=-;-! "
   SET "s=!s:-=%!"
   SET "s=!s:_= %!"
   SET "s=!s:;=';'%!"
   SET "s=!s:;'';'=;;%!"

   echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")


问:
docker-compose: Service 'web' failed to build
I'm trying to install apach2, libapache2-mod-wsgi-py3 and openssl in the container. I've removed some packages and fix typos in Dockerfile but the error is still there.

When i run docker-compose build my setup is running ok, until it hit the part in the Dockerfile where I'm initializing this install and I've got this error:

```<code>E: Unable to locate package RUN
E: Unable to locate package apt-get
E: Unable to locate package install
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y     apache2     libapache2-mod-wsgi-py3     curl     dpgk-sig RUN apt-get install -yq openssh-server' returned a non-zero code: 100
</code>```

You can check the whole installation process here, and this is my Dockerfile:

```<code>FROM ubuntu:16.04
FROM python:3.5
ENV PYTHONUNBUFFERED 1

RUN cat /etc/passwd
RUN cat /etc/group

RUN apt-get update && apt-get install -y \
    apache2 \
    libapache2-mod-wsgi-py3 \
RUN apt-get install -y openssl
RUN mkdir /var/run/sshd

ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_LOG_DIR /var/log/apache

RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code

EXPOSE 80

ADD config/apache/000-default.conf /etc/apache/sites-available/000-default.conf
ADD config/start.sh /tmp/start.sh
ADD src /var/www

RUN chown -R root:www-data /var/www
RUN chmod u+rwx,g+rx,o+rx /var/www
RUN find /var/www -type d -exec chmod u+rwx,g+rx,o+rx {} +
RUN find /var/www -type f -exec chmod u+rw,g+rw,o+r {} +

#essentially: CMD ["/usr/sbin/apachectl", "-D", "FOREGROUND"]
CMD ["/tmp/start.sh"]
</code>```

Can someone explain me why is this happening, and how to fix it, thanks.

答:
Your problem is this line:

```<code>    libapache2-mod-wsgi-py3 \
</code>```

The \ is a continuation and the next thing it sees is RUN so is treating that like a package (which it can't find). Lose the \ and it should work fine.

Body:
I'm trying to install apach2, libapache2-mod-wsgi-py3 and openssl in the container. I've removed some packages and fix typos in Dockerfile but the error is still there.

When i run docker-compose build my setup is running ok, until it hit the part in the Dockerfile where I'm initializing this install and I've got this error:

E: Unable to locate package RUN
E: Unable to locate package apt-get
E: Unable to locate package install
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y     apache2     libapache2-mod-wsgi-py3     curl     dpgk-sig RUN apt-get install -yq openssh-server' returned a non-zero code: 100

You can check the whole installation process here, and this is my Dockerfile:

FROM ubuntu:16.04
FROM python:3.5
ENV PYTHONUNBUFFERED 1

RUN cat /etc/passwd
RUN cat /etc/group

RUN apt-get update && apt-get install -y \
    apache2 \
    libapache2-mod-wsgi-py3 \
RUN apt-get install -y openssl
RUN mkdir /var/run/sshd

ENV APACHE_RUN_USER www-data
ENV APACHE_RUN_GROUP www-data
ENV APACHE_LOG_DIR /var/log/apache

RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip install -r requirements.txt
ADD . /code

EXPOSE 80

ADD config/apache/000-default.conf /etc/apache/sites-available/000-default.conf
ADD config/start.sh /tmp/start.sh
ADD src /var/www

RUN chown -R root:www-data /var/www
RUN chmod u+rwx,g+rx,o+rx /var/www
RUN find /var/www -type d -exec chmod u+rwx,g+rx,o+rx {} +
RUN find /var/www -type f -exec chmod u+rw,g+rw,o+r {} +

#essentially: CMD ["/usr/sbin/apachectl", "-D", "FOREGROUND"]
CMD ["/tmp/start.sh"]

Can someone explain me why is this happening, and how to fix it, thanks.

Body:
Your problem is this line:

    libapache2-mod-wsgi-py3 \

The \ is a continuation and the next thing it sees is RUN so is treating that like a package (which it can't find). Lose the \ and it should work fine.


问:
convergence criteria in while loop
I have an equation Y = DX. Y is n by k, D is n by m and X is m by k. In each iteration, I use a column of Y and algorithm runs and some columns of D are updated. In iteration 1 algorithm uses column 1 of Y and dictionary is updated, for iteration 2 it uses column 2 of Y and so on.

In each iteration D is updated, I want to use criteria [(norm(D-D1),'fro')^2 < 0.0001]  in which it does not need to run algorithm k times. D means current dictionary which is updated and D1 is the dictionary that updated in the previous iteration.

```<code>D1=D1+0.05*randn(n,m);   % initializing D1 for first iteration to calculate d
d=D-D1;
delta= norm(d,'fro')^2;
k1=0;

while delta>0.0001
    D1=D;

    for i=1:k
    Y(:,i) = ..
     ...
    algorithm
      ...
    end
    d=D-D1;
    delta= norm(d,'fro')^2;
end
</code>```

I write it in this form, but it is not correct since it iterates k times but I want iterate j < k times that satisfies convergence criteria.

thanks for your attentions

答:
Is this what you are looking for? I believe you want it to exit the loop if convergence is met. So you just return if convergence is met.</p>

```<code>for i=1:k
    D1=D;
    Y(:,i) = ..
    ...
    algorithm
    ...
    d=D-D1;
    delta= norm(d,'fro')^2;
    if delta>.0001
        return
    end
end
</code>```

Title: convergence criteria in while loop

Body:
I have an equation Y = DX. Y is n by k, D is n by m and X is m by k. In each iteration, I use a column of Y and algorithm runs and some columns of D are updated. In iteration 1 algorithm uses column 1 of Y and dictionary is updated, for iteration 2 it uses column 2 of Y and so on.

In each iteration D is updated, I want to use criteria [(norm(D-D1),'fro')^2 < 0.0001]  in which it does not need to run algorithm k times. D means current dictionary which is updated and D1 is the dictionary that updated in the previous iteration.

D1=D1+0.05*randn(n,m);   % initializing D1 for first iteration to calculate d
d=D-D1;
delta= norm(d,'fro')^2;
k1=0;

while delta>0.0001
    D1=D;

    for i=1:k
    Y(:,i) = ..
     ...
    algorithm
      ...
    end
    d=D-D1;
    delta= norm(d,'fro')^2;
end

I write it in this form, but it is not correct since it iterates k times but I want iterate j < k times that satisfies convergence criteria.

thanks for your attentions

Body:
Is this what you are looking for? I believe you want it to exit the loop if convergence is met. So you just return if convergence is met.

for i=1:k
    D1=D;
    Y(:,i) = ..
    ...
    algorithm
    ...
    d=D-D1;
    delta= norm(d,'fro')^2;
    if delta>.0001
        return
    end
end