问:
How to pivot on multiple columns?
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

```<code>DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)
</code>```

Which produces the following result:

```<code>Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00
</code>```

To bring those rows into columns, I've tried this:

```<code>SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1
</code>```

Which produces the following result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5
</code>```

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

```<code>TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00
</code>```

答:
IN oracle i would do something like tihs. it works fine for me

```<code>select * from (
SELECT   Name, TypeId,TotalOrders
--hier
,GrandTotal
FROM test_b )
PIVOT (  SUM(TotalOrders)TotalOrders,
--hier
SUM(grandtotal) grandtotal FOR Name IN
('Yesterday'Yesterday,'This Week'ThisWeek,'Last Week'LastWeek,'This
Month'ThisMonth )
) ;
</code>```

so try this in sql server

```<code>SELECT *
   /* TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
   ISNULL([Last Week], 0) AS LastWeekTotalOrders,
   ISNULL([This Month], 0) AS ThisMonthTotalOrders*/
FROM
   (SELECT Name, TypeId, TotalOrders
   ,grandtotal
  FROM @Table) AS src
PIVOT (
    SUM(TotalOrders)TotalOrders, SUM(grandtotal)grandtotal FOR Name IN (
    [Yesterday]Yesterday,
    [This Week]ThisWeek,
    [Last Week]LastWeek,
    [This Month]ThisMonth
   )
 ) AS p1
</code>```

Title: How to pivot on multiple columns?

Body:
I'm trying to pivot on multiple columns and I'm using SQL Server 2014, however, I cannot figure out how to do that. Here's what I've tried so far:

DECLARE @Table TABLE (
    Name NVARCHAR(MAX),
    TypeId INT,
    TotalOrders INT,
    GrandTotal MONEY
)

INSERT INTO @Table
    (Name, TypeId, TotalOrders, GrandTotal)
VALUES
    ('This Month', 1, 10, 1),
    ('This Month', 2, 5, 7),
    ('This Week', 1, 8, 3),
    ('Last Week', 1, 8, 12),
    ('Yesterday', 1, 10, 1),
    ('Yesterday', 2, 1, 5)

Which produces the following result:

Name                             TypeId      TotalOrders GrandTotal
-------------------------------- ----------- ----------- ---------------------
This Month                       1           10          1.00
This Month                       2           5           7.00
This Week                        1           8           3.00
Last Week                        1           8           12.00
Yesterday                        1           10          1.00
Yesterday                        2           1           5.00

To bring those rows into columns, I've tried this:

SELECT
    TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
    ISNULL([Last Week], 0) AS LastWeekTotalOrders,
    ISNULL([This Month], 0) AS ThisMonthTotalOrders
FROM
    (SELECT Name, TypeId, TotalOrders FROM @Table) AS src
PIVOT (
    SUM(TotalOrders) FOR Name IN (
        [Yesterday],
        [This Week],
        [Last Week],
        [This Month]
    )
) AS p1

Which produces the following result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders
----------- -------------------- ------------------- ------------------- --------------------
1           10                   8                   8                   10
2           1                    0                   0                   5

Now, I need to have few other columns for GrandTotal such as YesterdayGrandTotal, ThisWeekGrandTotal, and so on and so forth but I can't figure out how to achieve this.

Any help would be highly appreciated.

UPDATE#1: Here's the expected result set:

TypeId      YesterdayTotalOrders ThisWeekTotalOrders LastWeekTotalOrders ThisMonthTotalOrders YesterdayGrandTotal   ThisWeekGrandTotal    LastWeekGrandTotal    ThisMonthGrandTotal
----------- -------------------- ------------------- ------------------- -------------------- --------------------- --------------------- --------------------- ---------------------
1           10                   8                   8                   10                   1.00                  3.00                  12.00                 1.00
2           1                    0                   0                   5                    5.00                  0.00                  0.00                  7.00

Body:
IN oracle i would do something like tihs. it works fine for me

select * from (
SELECT   Name, TypeId,TotalOrders
--hier
,GrandTotal
FROM test_b )
PIVOT (  SUM(TotalOrders)TotalOrders,
--hier
SUM(grandtotal) grandtotal FOR Name IN
('Yesterday'Yesterday,'This Week'ThisWeek,'Last Week'LastWeek,'This
Month'ThisMonth )
) ;

so try this in sql server

SELECT *
   /* TypeId,
    ISNULL([Yesterday], 0) AS YesterdayTotalOrders,
    ISNULL([This Week], 0) AS ThisWeekTotalOrders,
   ISNULL([Last Week], 0) AS LastWeekTotalOrders,
   ISNULL([This Month], 0) AS ThisMonthTotalOrders*/
FROM
   (SELECT Name, TypeId, TotalOrders
   ,grandtotal
  FROM @Table) AS src
PIVOT (
    SUM(TotalOrders)TotalOrders, SUM(grandtotal)grandtotal FOR Name IN (
    [Yesterday]Yesterday,
    [This Week]ThisWeek,
    [Last Week]LastWeek,
    [This Month]ThisMonth
   )
 ) AS p1


来源: stackexchange

问:
How to extract array of names from array of email ids
Given this input array:

```<code>var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];
</code>```

I to output an array that looks like this:

```<code>["ramu","ravi","karthik"];
</code>```

I have tried this, but it doesn't produce the correct result:

```<code>names = data.map(s => s.split('@'));
</code>```

答:
You don't need regex for this . This can be done in a simpler way</p>

```<code>var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

var  finalData = data.map(function(email){
    return email.split('@')[0]

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given this input array:

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

I to output an array that looks like this:

["ramu","ravi","karthik"];

I have tried this, but it doesn't produce the correct result:

names = data.map(s => s.split('@'));

Body:
You don't need regex for this . This can be done in a simpler way

var data = ["ramu@xerago.com","ravi@xerago.com","karthik@xerago.com"];

var  finalData = data.map(function(email){
    return email.split('@')[0]

}


问:
built SIP client in JAVASCRIPT
Is it possible to build a SIP client using JAVASCRIPT for a server not supporting WEBSOCKET or WEBRTC?</p>

答:
Yes, you can use a UDP or TCP socket to send your SIP messages towards the SIP server. Since Javascript supports UDP sockets(link), it should be possible. Anyhow since it is not that easy to implement a SIP useragent/transaction-layer, so I would google for Javascript SIP stacks, that supports TCP/UDP.

Hope that helps.

Title: built SIP client in JAVASCRIPT


问:
Mark variable as not NULL after BOOST_REQUIRE in PVS-Studio
I'm using PVS-Studio to analyze my Testcode. There are often constructs of the form

```<code>const noAnimal* animal = dynamic_cast<noAnimal*>(...);
BOOST_REQUIRE(animal);
BOOST_REQUIRE_EQUAL(animal->GetSpecies(), ...);
</code>```

However I still get a warning V522 There might be dereferencing of a potential null pointer 'animal' for the last line.

I know it is possible, to mark functions as "not returning NULL" but is it also possible to mark a function as a valid NULL check or make PVS-Studio somehow else aware that animal can't be NULL after BOOST_REQUIRE(animal);?

This also happens if the pointer is checked via any assert flavour first.

答:
Responding to a comment with a large one is a bad idea, so here is my detailed response on the following subject:

Although this is possible it would be a pain to include that define in
  all testcase files. Also this is not limited to BOOST_REQUIRE only but
  also applies to assert, SDL_Assert or any other custom macro the user
  might use.

One should understand that there are three types of test macros and each should be discussed separately.

Macros of the first type simply warn you that something went wrong in the Debug version. A typical example is assert macro. The following code will cause PVS-Studio analyzer to generate a warning:

```<code>T* p = dynamic_cast<T *>(x);
assert(p);
p->foo();
</code>```

The analyzer will point out a possible null-pointer dereferencing here and will be right. A check that uses assert is not sufficient because it will be removed from the Release version. That is, it turns out there’s no check. A better way to implement it is to rewrite the code into something like this:

```<code>T* p = dynamic_cast<T *>(x);
if (p == nullptr)
{
  assert(false);
  throw Error;
}
p->foo();
</code>```

This code won’t trigger the warning.

You may argue that you are 100% sure that dynamic_cast will never return nullptr. I don’t accept this argument. If you are totally sure that the cast is ALWAYS correct, you should use the faster static_cast. If you are not that sure, you must test the pointer before dereferencing it.

Well, OK, I see your point. You are sure that the code is alright, but you need to have that check with dynamic_cast just in case. OK, use the following code then:

```<code>assert(dynamic_cast<T *>(x) != nullptr);
T* p = static_cast<T *>(x);
p->foo();
</code>```

I don’t like it, but at least it’s faster, since the slower dynamic_cast operator will be left out in the Release version, while the analyzer will keep silent.

Moving on to the next type of macros.

Macros of the second type simply warn you that something went wrong in the Debug version and are used in tests. What makes them different from the previous type is that they stop the algorithm under test if the condition is false and generate an error message.

The basic problem with these macros is that the functions are not marked as non-returning. Here’s an example.

Suppose we have a function that generates an error message by throwing an exception. This is what its declaration looks like:

```<code>void Error(const char *message);
</code>```

And this is how the test macro is declared:

```<code>#define ENSURE(x) do { if (!x) Error("zzzz"); } while (0)
</code>```

Using the pointer:

```<code>T* p = dynamic_cast<T *>(x);
ENSURE(p);
p->foo();
</code>```

The analyzer will issue a warning about a possible null-pointer dereferencing, but the code is actually safe. If the pointer is null, the Error function will throw an exception and thus prevent the pointer dereferencing.

We simply need to tell the analyzer about that by using one of the function annotation means, for example:

```<code>[[noreturn]] void Error(const char *message);
</code>```

or:

```<code>__declspec(noreturn) void Error(const char *message);
</code>```

This will help eliminate the false warning. So, as you can see, it’s quite easy to fix things in most cases when using your own macros.

It might be trickier, however, if you deal with carelessly implemented macros from third-party libraries.

This leads us to the third type of macros. You can’t change them, and the analyzer can’t figure out how exactly they work. This is a common situation, as macros may be implemented in quite exotic ways.

There are three options left for you in this case:

suppress the warning using one of the false-positive suppression means described in the documentation;

use the technique I described in the previous answer;

email us.

We are gradually adding support for various tricky macros from popular libraries. In fact, the analyzer is already familiar with most of the specific macros you might encounter, but programmers’ imagination is inexhaustible and we just can’t foresee every possible implementation.

Body:
I'm using PVS-Studio to analyze my Testcode. There are often constructs of the form

const noAnimal* animal = dynamic_cast<noAnimal*>(...);
BOOST_REQUIRE(animal);
BOOST_REQUIRE_EQUAL(animal->GetSpecies(), ...);

However I still get a warning V522 There might be dereferencing of a potential null pointer 'animal' for the last line.

I know it is possible, to mark functions as "not returning NULL" but is it also possible to mark a function as a valid NULL check or make PVS-Studio somehow else aware that animal can't be NULL after BOOST_REQUIRE(animal);?

This also happens if the pointer is checked via any assert flavour first.

Body:
Responding to a comment with a large one is a bad idea, so here is my detailed response on the following subject:

Although this is possible it would be a pain to include that define in
  all testcase files. Also this is not limited to BOOST_REQUIRE only but
  also applies to assert, SDL_Assert or any other custom macro the user
  might use.

One should understand that there are three types of test macros and each should be discussed separately.

Macros of the first type simply warn you that something went wrong in the Debug version. A typical example is assert macro. The following code will cause PVS-Studio analyzer to generate a warning:

T* p = dynamic_cast<T *>(x);
assert(p);
p->foo();

The analyzer will point out a possible null-pointer dereferencing here and will be right. A check that uses assert is not sufficient because it will be removed from the Release version. That is, it turns out there’s no check. A better way to implement it is to rewrite the code into something like this:

T* p = dynamic_cast<T *>(x);
if (p == nullptr)
{
  assert(false);
  throw Error;
}
p->foo();

This code won’t trigger the warning.

You may argue that you are 100% sure that dynamic_cast will never return nullptr. I don’t accept this argument. If you are totally sure that the cast is ALWAYS correct, you should use the faster static_cast. If you are not that sure, you must test the pointer before dereferencing it.

Well, OK, I see your point. You are sure that the code is alright, but you need to have that check with dynamic_cast just in case. OK, use the following code then:

assert(dynamic_cast<T *>(x) != nullptr);
T* p = static_cast<T *>(x);
p->foo();

I don’t like it, but at least it’s faster, since the slower dynamic_cast operator will be left out in the Release version, while the analyzer will keep silent.

Moving on to the next type of macros.

Macros of the second type simply warn you that something went wrong in the Debug version and are used in tests. What makes them different from the previous type is that they stop the algorithm under test if the condition is false and generate an error message.

The basic problem with these macros is that the functions are not marked as non-returning. Here’s an example.

Suppose we have a function that generates an error message by throwing an exception. This is what its declaration looks like:

void Error(const char *message);

And this is how the test macro is declared:

#define ENSURE(x) do { if (!x) Error("zzzz"); } while (0)

Using the pointer:

T* p = dynamic_cast<T *>(x);
ENSURE(p);
p->foo();

The analyzer will issue a warning about a possible null-pointer dereferencing, but the code is actually safe. If the pointer is null, the Error function will throw an exception and thus prevent the pointer dereferencing.

We simply need to tell the analyzer about that by using one of the function annotation means, for example:

[[noreturn]] void Error(const char *message);

or:

__declspec(noreturn) void Error(const char *message);

This will help eliminate the false warning. So, as you can see, it’s quite easy to fix things in most cases when using your own macros.

It might be trickier, however, if you deal with carelessly implemented macros from third-party libraries.

This leads us to the third type of macros. You can’t change them, and the analyzer can’t figure out how exactly they work. This is a common situation, as macros may be implemented in quite exotic ways.

There are three options left for you in this case:

suppress the warning using one of the false-positive suppression means described in the documentation;

use the technique I described in the previous answer;

email us.

We are gradually adding support for various tricky macros from popular libraries. In fact, the analyzer is already familiar with most of the specific macros you might encounter, but programmers’ imagination is inexhaustible and we just can’t foresee every possible implementation.


问:
Running a Powershell command to another ws that requires administrator privileges
I'm required to run a TPM command (requires admin access).

Lets use these for the legend:

Angelo - Standard user

AngeloAdmin - Admin user

Windows7 - Computer that has a standard user in it

How can I use my standard account to run the script as an Administrator to execute a script to another computer with a standard account remotely?

Heres the partial code I will run:

```<code>Set-Variable -Name BuildLog -Scope Global -Force
Set-Variable -Name Errors -Value $null -Scope Global -Force
Set-Variable -Name LogFile -Scope Global -Force
Set-Variable -Name Phase -Scope Global -Force
Set-Variable -Name RelativePath -Scope Global -Force
Set-Variable -Name Sequence -Scope Global -Force
Set-Variable -Name Title -Scope Global -Force

Function ConsoleTitle ($Title){
    $host.ui.RawUI.WindowTitle = $Title
}

Function DeclareGlobalVariables {
    $Global:BuildLog = $Env:windir+"\Logs\BuildLogs\Build.csv"
    $Global:LogFile = $Env:windir+"\Logs\BuildLogs\TPM_On.log"
    $Global:Phase = "Final Build"
    $Global:Sequence = ""
    $Global:Title = "TPM Clear Ownership"
}

Function GetRelativePath {
    $Global:RelativePath = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent)+"\"
}

Function ClearTPM {
    #Declare Local Memory
    Set-Variable -Name ClassName -Value "Win32_Tpm" -Scope Local -Force
    Set-Variable -Name Computer -Value $env:COMPUTERNAME -Scope Local -Force
    Set-Variable -Name NameSpace -Value "ROOT\CIMV2\Security\MicrosoftTpm" -Scope Local -Force
    Set-Variable -Name oTPM -Scope Local -Force

    $oTPM = Get-WmiObject -Class $ClassName -ComputerName $Computer -Namespace $NameSpace
    $Output = "Clearing TPM Ownership....."
    Write-Host "Clearing TPM Ownership....." -NoNewline
    $Temp = $oTPM.SetPhysicalPresenceRequest(5)
    If ($Temp.ReturnValue -eq 0) {
        $Output = "Success"
        Write-Host "Success" -ForegroundColor Yellow
    } else {
        $Output = "Failure"
        Write-Host "Failure" -ForegroundColor Red
        $Global:Errors++
    }
    Out-File -FilePath $Global:LogFile -InputObject $Output -Append -Force

    #Cleanup Local Memory
    Remove-Variable -Name oTPM -Scope Local -Force
}

Function ProcessLogFile {
    If ((Test-Path $Env:windir"\Logs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs"
    }
    If ((Test-Path $Env:windir"\Logs\ApplicationLogs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs\ApplicationLogs"
    }
    If ((Test-Path $Env:windir"\Logs\BuildLogs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs\BuildLogs"
    }
    If ($Global:Errors -eq $null) {
        If (Test-Path $Global:LogFile) {
            Remove-Item $Global:LogFile -Force
        }
        $File1 = $Global:LogFile.Split(".")
        $Filename1 = $File1[0]+"_ERROR"+"."+$File1[1]
        If (Test-Path $Filename1) {
            Remove-Item $Filename1 -Force
        }
        $Global:Errors = 0
    } elseIf ($Global:Errors -ne 0) {
        If (Test-Path $Global:LogFile) {
            $Global:LogFile.ToString()
            $File1 = $Global:LogFile.Split(".")
            $Filename1 = $File1[0]+"_ERROR"+"."+$File1[1]
            Rename-Item $Global:LogFile -NewName $Filename1 -Force
        }
    } else {
        $date = get-date
        $LogTitle = $Global:Phase+[char]9+$Global:Sequence+[char]9+$Global:Title+[char]9+$date.month+"/"+$date.day+"/"+$date.year+" "+$date.hour+":"+$date.minute
        Out-File -FilePath $Global:BuildLog -InputObject $LogTitle -Append -Force
    }
}

Function ExitPowerShell {
    If (($Global:Errors -ne $null) -and ($Global:Errors -ne 0)) {
        Exit 1
    }
}

cls
GetRelativePath
DeclareGlobalVariables
ConsoleTitle $Global:Title
ProcessLogFile
ClearTPM
ProcessLogFile
Start-Sleep -Seconds 5
ExitPowerShell
</code>```

答:
If you want to run the script as a different user you can 'SHIFT+Right click > Run as a different user' but that works only on applications, so you have to run Powershell as a different user and then the script, you can make a batch file to do that. Here is an example of what you will need in the batch file.

```<code>runas /user:yourdomain.com\administrator powershell
</code>```

If you dont have a domain use the computer name

```<code>runas /noprofile /user:computername\administrator powershell
</code>```

Body:
I'm required to run a TPM command (requires admin access).

Lets use these for the legend:

Angelo - Standard user

AngeloAdmin - Admin user

Windows7 - Computer that has a standard user in it

How can I use my standard account to run the script as an Administrator to execute a script to another computer with a standard account remotely?

Heres the partial code I will run:

Set-Variable -Name BuildLog -Scope Global -Force
Set-Variable -Name Errors -Value $null -Scope Global -Force
Set-Variable -Name LogFile -Scope Global -Force
Set-Variable -Name Phase -Scope Global -Force
Set-Variable -Name RelativePath -Scope Global -Force
Set-Variable -Name Sequence -Scope Global -Force
Set-Variable -Name Title -Scope Global -Force

Function ConsoleTitle ($Title){
    $host.ui.RawUI.WindowTitle = $Title
}

Function DeclareGlobalVariables {
    $Global:BuildLog = $Env:windir+"\Logs\BuildLogs\Build.csv"
    $Global:LogFile = $Env:windir+"\Logs\BuildLogs\TPM_On.log"
    $Global:Phase = "Final Build"
    $Global:Sequence = ""
    $Global:Title = "TPM Clear Ownership"
}

Function GetRelativePath {
    $Global:RelativePath = (split-path $SCRIPT:MyInvocation.MyCommand.Path -parent)+"\"
}

Function ClearTPM {
    #Declare Local Memory
    Set-Variable -Name ClassName -Value "Win32_Tpm" -Scope Local -Force
    Set-Variable -Name Computer -Value $env:COMPUTERNAME -Scope Local -Force
    Set-Variable -Name NameSpace -Value "ROOT\CIMV2\Security\MicrosoftTpm" -Scope Local -Force
    Set-Variable -Name oTPM -Scope Local -Force

    $oTPM = Get-WmiObject -Class $ClassName -ComputerName $Computer -Namespace $NameSpace
    $Output = "Clearing TPM Ownership....."
    Write-Host "Clearing TPM Ownership....." -NoNewline
    $Temp = $oTPM.SetPhysicalPresenceRequest(5)
    If ($Temp.ReturnValue -eq 0) {
        $Output = "Success"
        Write-Host "Success" -ForegroundColor Yellow
    } else {
        $Output = "Failure"
        Write-Host "Failure" -ForegroundColor Red
        $Global:Errors++
    }
    Out-File -FilePath $Global:LogFile -InputObject $Output -Append -Force

    #Cleanup Local Memory
    Remove-Variable -Name oTPM -Scope Local -Force
}

Function ProcessLogFile {
    If ((Test-Path $Env:windir"\Logs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs"
    }
    If ((Test-Path $Env:windir"\Logs\ApplicationLogs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs\ApplicationLogs"
    }
    If ((Test-Path $Env:windir"\Logs\BuildLogs") -eq $false) {
        New-Item -ItemType Directory -Path $Env:windir"\Logs\BuildLogs"
    }
    If ($Global:Errors -eq $null) {
        If (Test-Path $Global:LogFile) {
            Remove-Item $Global:LogFile -Force
        }
        $File1 = $Global:LogFile.Split(".")
        $Filename1 = $File1[0]+"_ERROR"+"."+$File1[1]
        If (Test-Path $Filename1) {
            Remove-Item $Filename1 -Force
        }
        $Global:Errors = 0
    } elseIf ($Global:Errors -ne 0) {
        If (Test-Path $Global:LogFile) {
            $Global:LogFile.ToString()
            $File1 = $Global:LogFile.Split(".")
            $Filename1 = $File1[0]+"_ERROR"+"."+$File1[1]
            Rename-Item $Global:LogFile -NewName $Filename1 -Force
        }
    } else {
        $date = get-date
        $LogTitle = $Global:Phase+[char]9+$Global:Sequence+[char]9+$Global:Title+[char]9+$date.month+"/"+$date.day+"/"+$date.year+" "+$date.hour+":"+$date.minute
        Out-File -FilePath $Global:BuildLog -InputObject $LogTitle -Append -Force
    }
}

Function ExitPowerShell {
    If (($Global:Errors -ne $null) -and ($Global:Errors -ne 0)) {
        Exit 1
    }
}

cls
GetRelativePath
DeclareGlobalVariables
ConsoleTitle $Global:Title
ProcessLogFile
ClearTPM
ProcessLogFile
Start-Sleep -Seconds 5
ExitPowerShell

Body:
If you want to run the script as a different user you can 'SHIFT+Right click > Run as a different user' but that works only on applications, so you have to run Powershell as a different user and then the script, you can make a batch file to do that. Here is an example of what you will need in the batch file.

runas /user:yourdomain.com\administrator powershell

If you dont have a domain use the computer name

runas /noprofile /user:computername\administrator powershell


问:
VBA - enable and disable validation
I would like to ask is there a way to enable and disable data validation on excel? I would like to disable validation on a certain input,'others'. And enable it if the input is not others.

I had a list data validation, when option cell== others, user is able to free text. Else disable free text.

My list validation is done by the excel build in data validation, not using VBA.

This is the code that I have tried:

```<code>Sub Remove_Data_Validation_Selection()

Selection.Validation.Delete

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Cells(2, 6).Value = "Others" Then
            Selection.Validation.Delete
    Else
           //Enable the validation
    End If
End Sub
</code>```

Right now, when 'Others' is being selected, the validation will be DELETED. How do I enable it back? As Selection.Validation.Delete deletes the object, will I be able to enable it back?

答:
If you want to use it in the same procedure, declare object variable

```<code>Dim Valid As Validation
</code>```

and assign value before deleting. EDIT here.

```<code>If Cells(2, 6).Value = "Others" Then
        set Valid = Selection.Validation
        Selection.Validation.Delete
</code>```

If you want to set up validation in other procedure:

```<code>SomeRange.Validation = valid
</code>```

I don't know why you would do it, but this is answer for your question. However, if you want to preserve validation for another procedure, you could do this way:

```<code>Dim wsHid As Worksheet
Dim rngValid As Range

Set rngValid = Selection
Set wsHid = ThisWorkbook.Worksheets.Add
wsHid.Visible = xlSheetVeryHidden
rngValid.Copy
wsHid.Range("A1").PasteSpecial Paste:=xlPasteValidation
</code>```

and then, if you need recreate validation, you just copy it from wsHid.Range("A1") and PasteSpecial Paste: xlPasteValidation. Of course, this is just bunch of ideas, you should adjust it to your code.

Title: VBA - enable and disable validation

Body:
I would like to ask is there a way to enable and disable data validation on excel? I would like to disable validation on a certain input,'others'. And enable it if the input is not others.

I had a list data validation, when option cell== others, user is able to free text. Else disable free text.

My list validation is done by the excel build in data validation, not using VBA.

This is the code that I have tried:

Sub Remove_Data_Validation_Selection()

Selection.Validation.Delete

End Sub

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    If Cells(2, 6).Value = "Others" Then
            Selection.Validation.Delete
    Else
           //Enable the validation
    End If
End Sub

Right now, when 'Others' is being selected, the validation will be DELETED. How do I enable it back? As Selection.Validation.Delete deletes the object, will I be able to enable it back?

Body:
If you want to use it in the same procedure, declare object variable

Dim Valid As Validation

and assign value before deleting. EDIT here.

If Cells(2, 6).Value = "Others" Then
        set Valid = Selection.Validation
        Selection.Validation.Delete

If you want to set up validation in other procedure:

SomeRange.Validation = valid

I don't know why you would do it, but this is answer for your question. However, if you want to preserve validation for another procedure, you could do this way:

Dim wsHid As Worksheet
Dim rngValid As Range

Set rngValid = Selection
Set wsHid = ThisWorkbook.Worksheets.Add
wsHid.Visible = xlSheetVeryHidden
rngValid.Copy
wsHid.Range("A1").PasteSpecial Paste:=xlPasteValidation

and then, if you need recreate validation, you just copy it from wsHid.Range("A1") and PasteSpecial Paste: xlPasteValidation. Of course, this is just bunch of ideas, you should adjust it to your code.


问:
Firebase Authentication FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred
I'm creating an authentication workflow for my android app. I'm allowing users to sign in with username/password and various OAuth providers. I'm validating emails and password so that, I know the information I'm passing to Firebase is valid. I'm using com.google.firebase:firebase-auth:9.6.1

When I execute the following code, I get a callback that says the operation not successful with an error.

```<code>mFirebaseAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener(this);
</code>```

Callback function or completion listener tells me

```<code>com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.
</code>```

The username I'm passing doesn't exist yet. So, I would assume to see some kind of error stating the user doesn't exist. Am I passing something incorrectly or am I assuming incorrectly? I can also see that in the Firebase documentation, the iOS library has a various error codes common to all API methods section where as the Android section doesn't show this. One of these exceptions is FIRAuthErrorCodeUserNotFound. So, does that functionality even exists in the Android library?

答:
In your AndroidManifest.xml add, it works for me</p>

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</code>```

Body:
I'm creating an authentication workflow for my android app. I'm allowing users to sign in with username/password and various OAuth providers. I'm validating emails and password so that, I know the information I'm passing to Firebase is valid. I'm using com.google.firebase:firebase-auth:9.6.1

When I execute the following code, I get a callback that says the operation not successful with an error.

mFirebaseAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener(this);

Callback function or completion listener tells me

com.google.firebase.FirebaseNetworkException: A network error (such as timeout, interrupted connection or unreachable host) has occurred.

The username I'm passing doesn't exist yet. So, I would assume to see some kind of error stating the user doesn't exist. Am I passing something incorrectly or am I assuming incorrectly? I can also see that in the Firebase documentation, the iOS library has a various error codes common to all API methods section where as the Android section doesn't show this. One of these exceptions is FIRAuthErrorCodeUserNotFound. So, does that functionality even exists in the Android library?

Body:
In your AndroidManifest.xml add, it works for me

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

ContentLicense: CC BY-SA 4.0


问:
Based on selection, dates should show some specific difference between from and to
I have dropdown button. Based on selection, there should be an difference between from and to date. If I select 1st option, there should be difference of 10 days like from:16/11/2017 to:26/11/2017 and if I select 2nd option, difference is 30 days. I tried like this:

```<code><select class="form-control" name="slct" id="slct" required style="font-
family : Verdana; font-size: 20px; height: 40px;" onchange="getResult()">
                                <option value="">Select</option>
                                <option value="10">select 1</option>
                                <option value="30">select 2</option>
                                <option value="60">select 3</option>
                            </select>
    <table style="margin-top:10px;">
                    <tr>
                    <div class="form-group">
                    <td><label for="from" style="margin-left:30px">From:
    </label>
                    <?php echo  "<input type='date' class='form-control'
   name='dte' id='dat' value='" . date('Y-m-d') . "' required />" ?>
   </td>
                    <td><label for="from">To:</label>
                    <input type="date" name="to" id="todate" value=""
   required /> </td>
                    </div>
                    </tr></table>
   <script>
                    function getResult() {
                    var dateval = $("#frmdate").val();
                    var offset = $("#slct").value();
                    if (dateval != "" && offset != "") {
                    var dat = $("#frmdate").datepicker("getDate");
                    dat.setDate(dat.getDate() + parseInt(offset));
                    $("#todate").text($.datepicker.formatDate("yy-mm-dd",
                       dat));
                    }
                    }
     </script>
</code>```

But the result is not shown. How can I get that? here I am displaying today's date before selection. But I want to display today's date after selection. Please suggest me how to display after selection.

答:
You can achieve this by getting the "from" date value and using some JavaScript functions to add days and format it.

First check the select value then add the number of days to the "todate" accordingly. Here is the JavaScript to do that:

```<code>function getResult() {
    var startDate = document.getElementById('dat').value;  //Get from date
    if(document.getElementById('slct').value == "10"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 10));
    }
    else if(document.getElementById('slct').value == "30"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 30));
    }
    else if(document.getElementById('slct').value == "60"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 60));
    }
}

//Function to add days https://stackoverflow.com/a/19691491/5612132
function addDays(date, days) {
     var result = new Date(date);
     result.setDate(result.getDate() + days);
     return result;
}

//Format date https://stackoverflow.com/questions/23593052/format-javascript-date-to-yyyy-mm-dd
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}
</code>```

Here I some functions I found on SO to add days and format date.

Add days

Format date

Body:
I have dropdown button. Based on selection, there should be an difference between from and to date. If I select 1st option, there should be difference of 10 days like from:16/11/2017 to:26/11/2017 and if I select 2nd option, difference is 30 days. I tried like this:

<select class="form-control" name="slct" id="slct" required style="font-
family : Verdana; font-size: 20px; height: 40px;" onchange="getResult()">
                                <option value="">Select</option>
                                <option value="10">select 1</option>
                                <option value="30">select 2</option>
                                <option value="60">select 3</option>
                            </select>

                    From:

                    <?php echo  "<input type='date' class='form-control'
   name='dte' id='dat' value='" . date('Y-m-d') . "' required />" ?>

                    To:
                    <input type="date" name="to" id="todate" value=""
   required />

But the result is not shown. How can I get that? here I am displaying today's date before selection. But I want to display today's date after selection. Please suggest me how to display after selection.

Body:
You can achieve this by getting the "from" date value and using some JavaScript functions to add days and format it.

First check the select value then add the number of days to the "todate" accordingly. Here is the JavaScript to do that:

function getResult() {
    var startDate = document.getElementById('dat').value;  //Get from date
    if(document.getElementById('slct').value == "10"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 10));
    }
    else if(document.getElementById('slct').value == "30"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 30));
    }
    else if(document.getElementById('slct').value == "60"){
        var endDate = document.getElementById('todate').value = formatDate(addDays(startDate, 60));
    }
}

//Function to add days https://stackoverflow.com/a/19691491/5612132
function addDays(date, days) {
     var result = new Date(date);
     result.setDate(result.getDate() + days);
     return result;
}

//Format date https://stackoverflow.com/questions/23593052/format-javascript-date-to-yyyy-mm-dd
function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) month = '0' + month;
    if (day.length < 2) day = '0' + day;

    return [year, month, day].join('-');
}

Here I some functions I found on SO to add days and format date.

Add days

Format date


问:
Get a textbox to fill 100% of the width of its container div
I have a form, in which there's a textbox followed by a submit button in the same row.

I'd like the submit button to be a little small but the textbox to take up all of the remaining width.

So, I'd like to just stretch the textbox to fill all the width but for the width required by the button.

However, at present, my UI looks like so:

Notice all the empty horizontal space between the textbox and the button.

I have tried setting the width of the textbox to 100% in the CSS but nothing happens.

Below is my HTML.

```<code><div class="row" id="rowFormContainer">
    <form id="frm">
        <div id="divUserURLContainer" class="col-md-10">
            <input type="text"
                   id="txtUserURL"
                   placeholder="Stack Overflow URL" />
        </div>

        <div id="divGetButtonContainer" class="col-md-2">
            <input type="submit" value="Get" class="btn btn-success"/>
        </div>
    </form>

</div>
</code>```

As you may observe, I am using the bootstrap classes row and md-col-x in order to define the layout of the container divs. I'd like the input control that reresents my textbox to fill 100% of the width of its container div.

And this is my CSS:

```<code>#rowFormContainer {
    padding-left: 7px;
    padding-right: 7px;
    padding-bottom: 10px;

    border-width: 2px;
    border-style: dashed;
}

#divUserURLContainer {
    border-width: 2px;
    border-style: solid;
    border-color: red;

    padding: 0px;
}

#txtUserURL {
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    color: cadetblue;
    font-size: 22px;

    padding-left: 7px;
    padding-right: 7px;
    padding-top: 4px;
    padding-bottom: 4px;

    border-radius: 7px;
    width: 100%;
}
</code>```

答:
You can simply use flex like this :

form {
  display: flex;
}

input[type="text"] {
  flex: 1
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div id="rowFormContainer">
  <form id="frm">
    <input type="text" id="txtUserURL" placeholder="Stack Overflow URL" />
    <input type="submit" value="Get" class="btn btn-success" />
  </form>
</div></code>```

Body:
I have a form, in which there's a textbox followed by a submit button in the same row.

I'd like the submit button to be a little small but the textbox to take up all of the remaining width.

So, I'd like to just stretch the textbox to fill all the width but for the width required by the button.

However, at present, my UI looks like so:

Notice all the empty horizontal space between the textbox and the button.

I have tried setting the width of the textbox to 100% in the CSS but nothing happens.

Below is my HTML.

    <form id="frm">

            <input type="text"
                   id="txtUserURL"
                   placeholder="Stack Overflow URL" />

            <input type="submit" value="Get" class="btn btn-success"/>

    </form>

As you may observe, I am using the bootstrap classes row and md-col-x in order to define the layout of the container divs. I'd like the input control that reresents my textbox to fill 100% of the width of its container div.

And this is my CSS:

#rowFormContainer {
    padding-left: 7px;
    padding-right: 7px;
    padding-bottom: 10px;

    border-width: 2px;
    border-style: dashed;
}

#divUserURLContainer {
    border-width: 2px;
    border-style: solid;
    border-color: red;

    padding: 0px;
}

#txtUserURL {
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    color: cadetblue;
    font-size: 22px;

    padding-left: 7px;
    padding-right: 7px;
    padding-top: 4px;
    padding-bottom: 4px;

    border-radius: 7px;
    width: 100%;
}

Body:
You can simply use flex like this :

form {
  display: flex;
}

input[type="text"] {
  flex: 1
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div id="rowFormContainer">
  <form id="frm">
    <input type="text" id="txtUserURL" placeholder="Stack Overflow URL" />
    <input type="submit" value="Get" class="btn btn-success" />
  </form>
</div>


问:
How to find the source css code when dev tools does not specify a file name?
I am making a website in wordpress and I'm using a paid template. The template comes with a bootstrap grid. The issue I have is editing some css code, because I can't find the source of the css codes.

As you can see on the screenshot, the media queries are located at grid-responsive.css. The code I want to edit is the css above it. I want to remove the padding-right: 30px !important; from .mpce-prvt-4661-5a018ae17a157:not(.mpce-dsbl-padding-right) and same for the left side.

But I can't find the css file and on the right side it doesn't tell me which file the source is. I searched in all the css files I have and couldn't find it. Someone having an idea how to locate it?

答:
You can write your CSS in an other file. Usually, paid templates offer the possibility to add your own custom CSS in admin or in a custom CSS file. Check your WordPress theme parameter or documentation.

This method is called "override". It means that you don’t modify original template (otherwise your modifications could be deleted when you update the template).

You just copy and modify the CSS you want to change.

original CSS file :

```<code>.test {
    color: red;
}
</code>```

In custom.css :

```<code>.test {
    color: blue;
}
</code>```

Body:
You can write your CSS in an other file. Usually, paid templates offer the possibility to add your own custom CSS in admin or in a custom CSS file. Check your WordPress theme parameter or documentation.

This method is called "override". It means that you don’t modify original template (otherwise your modifications could be deleted when you update the template).

You just copy and modify the CSS you want to change.

original CSS file :

.test {
    color: red;
}

In custom.css :

.test {
    color: blue;
}


问:
Has anyone ever created A VR UML Class model using A-Frame
I'm looking to auto-generate a UML class model in virtual reality using A-Frame.io (or another technology) by passing in values. Has anyone ever done something similar in the past? Not sure where to start.
Thanks</p>

答:
You might want to look into plantuml which is a nice UML generator. Most of it's diagrams are generated as input to graphviz's dot. Dot is a layout engine - it takes a list of nodes and connections and puts them into 2D space and then renders them to one of it's output formats - or just returns the graph, but this time with coordinates on where to draw what. You could meddle with this data and render the elements with volume but on a 2D plane with dot generated coordinates. Perhaps even you could modify it to place them in 3D space instead of a plane.

Or you could just render the plantuml output on a 2D plane, place it in 3D space and it would probably be good enough. There are even online generators for plantuml.


问:
C#'s equivalent of Java's <? extends Base> in generics
In Java, I can do the following: (assume Subclass extends Base):

```<code>ArrayList<? extends Base> aList = new ArrayList<Subclass>();
</code>```

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

```<code>List<Base> aList = new List<Subclass>();
</code>```

答:
Look into Covariance and Contravariance introduced with .Net 4.0. But it only works with interfaces right now.

Example:

```<code>IEnumerable<Base> list = new List<SubClass>();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In Java, I can do the following: (assume Subclass extends Base):

ArrayList<? extends Base> aList = new ArrayList<Subclass>();

What is the equivalent in C# .NET? There is no ? extends keyword apparently and this does not work:

List<Base> aList = new List<Subclass>();

Body:
Look into Covariance and Contravariance introduced with .Net 4.0. But it only works with interfaces right now.

Example:

IEnumerable<Base> list = new List<SubClass>();


问:
How to access a network shared drive inside Invoke-command
I was using below script to copy files from network share to local drive. But,I was not able to access path and getting Path not found error. MY use case is I need to execute this script from Jenkins server and remote into server1 and then have copy files from shared directory (\server2\QlikView) which is already mounted to the server1 as S:\ drive. I was able to access this shared path from powershell If I run the command from server1.But, not inside Invoke-Command script block as shown. Any thoughts on this?</p>

```<code>$server = "server1"
$source_dir = "\\server2\QlikView"
$processing_dir = "M:\script_test\processing"
$processed_dir = ""
$user = 'Domain\user1'
$Password = '******'
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

 Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
  param ($server,$source_dir,$processing_dir)
echo "$source_dir"
 Test-path $source_dir
 copy-item -Path $source_dir\* -Destination M:\script_test
  } -ArgumentList $server,$source_dir,$processing_dir
</code>```

答: By default PowerShell remoting does not allow credential delegation or "second hop". If you want to connect to a remote machine (in this case a network share) from a remoting session, you need to allow the credentials to be delegated to that machine. To allow it you need to configure CredSSP. Take a look here for details on the problems as well as how to set it up: https://blogs.technet.microsoft.com/heyscriptingguy/2012/11/14/enable-powershell-second-hop-functionality-with-credssp/ </p>

Body:
I was using below script to copy files from network share to local drive. But,I was not able to access path and getting Path not found error. MY use case is I need to execute this script from Jenkins server and remote into server1 and then have copy files from shared directory (\server2\QlikView) which is already mounted to the server1 as S:\ drive. I was able to access this shared path from powershell If I run the command from server1.But, not inside Invoke-Command script block as shown. Any thoughts on this?

$server = "server1"
$source_dir = "\\server2\QlikView"
$processing_dir = "M:\script_test\processing"
$processed_dir = ""
$user = 'Domain\user1'
$Password = '******'
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword

 Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock {
  param ($server,$source_dir,$processing_dir)
echo "$source_dir"
 Test-path $source_dir
 copy-item -Path $source_dir\* -Destination M:\script_test
  } -ArgumentList $server,$source_dir,$processing_dir


问:
Failed to add data to database
im trying to add data to a database, via a form i have created, but i just can't seem to get it to work. Can anyone please help me?

I have included some of the code, which i think is the problem, but also included a pastbin link to all the code.

https://pastebin.com/PpfCvjhf

$user_id = $_POST['user_id'];
            $grafik_name = $_POST['grafik_name'];
            $grafik_coin = $_POST['grafik_coin'];
            $grafik_hashrate = $_POST['grafik_hashrate'];
            $grafik_bios_mod = $_POST['grafik_bios_mod'];
            $grafik_core_clock = $_POST['grafik_core_clock'];
            $grafik_memory_clock = $_POST['grafik_memory_clock'];
            $grafik_power_draw = $_POST['grafik_power_draw'];
            $grafik_additional_info = $_POST['grafik_additional_info'];

            $sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";

            mysql_select_db('grafik');
            $retval = mysql_query( $sql, $conn );```
</div>
</div>
</p>

```<?php
```

https://pastebin.com/PpfCvjhf

答:
Error in this query :

```<code>$sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";
</code>```

Number of columns is less than values !!

Title: Failed to add data to database

Body:
im trying to add data to a database, via a form i have created, but i just can't seem to get it to work. Can anyone please help me?

I have included some of the code, which i think is the problem, but also included a pastbin link to all the code.

https://pastebin.com/PpfCvjhf

$user_id = $_POST['user_id'];
            $grafik_name = $_POST['grafik_name'];
            $grafik_coin = $_POST['grafik_coin'];
            $grafik_hashrate = $_POST['grafik_hashrate'];
            $grafik_bios_mod = $_POST['grafik_bios_mod'];
            $grafik_core_clock = $_POST['grafik_core_clock'];
            $grafik_memory_clock = $_POST['grafik_memory_clock'];
            $grafik_power_draw = $_POST['grafik_power_draw'];
            $grafik_additional_info = $_POST['grafik_additional_info'];

            $sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";

            mysql_select_db('grafik');
            $retval = mysql_query( $sql, $conn );

<?php

https://pastebin.com/PpfCvjhf

Body:
Error in this query :

$sql = "INSERT INTO `cards` (`id`, `name`, `coin`, `hashrate`, `bios_mod`, `core_clock`, `memory_clock`, `power_draw`, `additional_info`) VALUES ('$user_id','$grafik_name','$grafik_coin','$grafik_hashrate','$grafik_bios_mod','$grafik_core_clock','$grafik_memory_clock','$grafik_power_draw','$grafik_additional_info', NOW())";

Number of columns is less than values !!


问:
What are the generic functions defined by the standard?
In Common Lisp there are a few generic functions defined by the standard, for instance functions to manipulate sequences.

However looking at Graham's book ANSI Common Lisp and Steele's book Common Lisp – The language at the relevant chapters, I could not find any list of the generic functions defined in the standard.

What are the generic functions defined by the standard?

答:
I currently see no better way than to go through the pages of the CLHS Master Index and grep for "Generic Function".

Applying this suggestion a local copy of the HyperSpec using the script

```<code>% sed -n -e '
/Standard Generic Function/{
 s/.*Standard Generic Function *//
 s|</A>||
 p
}' X_Mast_*.htm | sort -u
</code>```

yielded the following list

```<code>(SETF CLASS-NAME)
ADD-METHOD
ALLOCATE-INSTANCE
CHANGE-CLASS
CLASS-NAME
COMPUTE-APPLICABLE-METHODS
DESCRIBE-OBJECT
DOCUMENTATION, (SETF DOCUMENTATION)
FIND-METHOD
FUNCTION-KEYWORDS
INITIALIZE-INSTANCE
MAKE-INSTANCE
MAKE-INSTANCES-OBSOLETE
MAKE-LOAD-FORM
METHOD-QUALIFIERS
NO-APPLICABLE-METHOD
NO-NEXT-METHOD
PRINT-OBJECT
REINITIALIZE-INSTANCE
REMOVE-METHOD
SHARED-INITIALIZE
SLOT-MISSING
SLOT-UNBOUND
UPDATE-INSTANCE-FOR-DIFFERENT-CLASS
UPDATE-INSTANCE-FOR-REDEFINED-CLASS
</code>```

Body:
I currently see no better way than to go through the pages of the CLHS Master Index and grep for "Generic Function".

Applying this suggestion a local copy of the HyperSpec using the script

% sed -n -e '
/Standard Generic Function/{
 s/.*Standard Generic Function *//
 s|</A>||
 p
}' X_Mast_*.htm | sort -u

yielded the following list

(SETF CLASS-NAME)
ADD-METHOD
ALLOCATE-INSTANCE
CHANGE-CLASS
CLASS-NAME
COMPUTE-APPLICABLE-METHODS
DESCRIBE-OBJECT
DOCUMENTATION, (SETF DOCUMENTATION)
FIND-METHOD
FUNCTION-KEYWORDS
INITIALIZE-INSTANCE
MAKE-INSTANCE
MAKE-INSTANCES-OBSOLETE
MAKE-LOAD-FORM
METHOD-QUALIFIERS
NO-APPLICABLE-METHOD
NO-NEXT-METHOD
PRINT-OBJECT
REINITIALIZE-INSTANCE
REMOVE-METHOD
SHARED-INITIALIZE
SLOT-MISSING
SLOT-UNBOUND
UPDATE-INSTANCE-FOR-DIFFERENT-CLASS
UPDATE-INSTANCE-FOR-REDEFINED-CLASS


问:
Quartz - Allow concurrent execution
Is it possible to trigger a Job instance on two (or more) nodes in an environment using Clustering with JDBC-JobStore?

For most usecases we trigger one Job instance on one node. In this particular case I want to have a Job triggered on all nodes at the same time. Each instance of the Job handles a chunk of a large dataset, and I want the Jobs to run in parallel.

Environment:
Java/Jetty/Docker/Rancher.
Using quartz-config.xml

答: When I want to trigger a Job on only one node I use Quartz, and when I want to trigger a job on all nodes I use EJBTimer. (but I don't know if you are using EJB in your project).

Title: Quartz - Allow concurrent execution


问:
Perl Locale warning Debian
```<code>perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
    LANGUAGE = (unset),
    LC_ALL = (unset),
    LANG = "en_CA.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").
</code>```

I keep getting this message.  I am running Debian on a VPS.  I've tried numerous solutions I've found through Google, none have helped. What do I do?

答: Configuring Locales in Debian: http://people.debian.org/~schultmc/locales.html</p>

Title: Perl Locale warning Debian

Body:
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
    LANGUAGE = (unset),
    LC_ALL = (unset),
    LANG = "en_CA.UTF-8"
    are supported and installed on your system.
perl: warning: Falling back to the standard locale ("C").

I keep getting this message.  I am running Debian on a VPS.  I've tried numerous solutions I've found through Google, none have helped. What do I do?


问:
Use legend in stacked bar Graph along with tooltip d3 js
I have done stacked bar graph with the help of this link https://bl.ocks.org/mbostock/1134768 but i want to customize my existing code of stacked graph in which i have to add d3.legend along with tooltip.

Right now i have completed till tooltip but there is label problem because i have to give value like this 'A:100' from my array data as shown below

```<code> var data = [
        {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
        {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
        {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"},
        {month: "7/1854",total:"400" ,A: "200", B:"100", C:"100"},
        {month: "8/1854",total:"500" ,A:"100", B:"200", C:"200"},
        {month: "9/1854",total:"600" ,A:"100", B:"200", C:"300"},
        {month: "10/1854",total:"700" ,A: "400", B:"100", C:"200"},
        {month: "11/1854",total:"800" ,A:"500", B:"200", C:"100"},
        {month: "12/1854",total:"900" ,A:"100", B:"400", C:"500"},
        {month: "13/1854",total:"1000" ,A:"500", B:"0", C:"500"}
    ];
</code>```

And about d3.legend i don't find any suitable example that give me proper picture that how to use it in my existing code but i have to show like this

Here is my full working code

```<code>var xData = ["A", "B", "C"];

  var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 500 - margin.left - margin.right,
        height = 350 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();
//console.info(color(0));

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#pie").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      d.month = parseDate(d.month);
      xData.forEach(function(c) {
        d[c] = +d[c];
      });

    })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};
    });
});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x;
}));

y.domain([0,
   d3.max(data, function(d) { return d.total; })
    ])
  .nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);
        });

layer.selectAll("rect")
        .data(function (d) {
            return d;
        })
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);
        })
        .attr("y", function (d) {
            return y(d.y + d.y0);
        })
        .attr("height", function (d) {
            // console.info(d.y0, d.y, y(d.y0), y(d.y))
            return y(d.y0) - y(d.y + d.y0);
        })
        .attr("width", x.rangeBand() -1)

        .on("mouseover", function(d){

          var delta = d.y1 - d.y0;
          var xPos = parseFloat(d3.select(this).attr("x"));
          var yPos = parseFloat(d3.select(this).attr("y"));
          var height = parseFloat(d3.select(this).attr("height"))

          d3.select(this).attr("stroke","blue").attr("stroke-width",0.8);

          svg.append("text")
          .attr("x",xPos)
          .attr("y",yPos +height/2)
          .attr("class","tooltip")
          .text(d +": "+ delta);

       })
       .on("mouseout",function(){
          svg.select(".tooltip").remove();
          d3.select(this).attr("stroke","pink").attr("stroke-width",0.2);

        });

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
</code>```

Please provide me some useful suggestion about my graph any help should be appreciated.

答:
Let's add a legend and a tooltip for blocks what you mentioned (I cannot use your code because of it is incomplete). Look at the demo in the hidden snippet below (I rewrite data loading to d3.tsv.parse to simplify the example).

First of all, let's increase bottom margin to the legend fits to svg:

```<code>var margin = {top: 20, right: 50, bottom: 130, left: 20};
</code>```

Adds the legend this way (pay attention to the comments):

```<code>var legend = svg.append("g") // add g element it will be the container for our legend
    .attr("transform", "translate(0," + (height + 25) + ")") // move it under the bar cart
    .selectAll(".legend")
    .data(causes.reverse()) // bind data
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); // put legend items one above the other

legend.append("rect") // append legend items rect
    .attr("x", width - 18)
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d, i) { return z(causes.length - 1 - i);}); // set appropriate color with z scale

legend.append("text") // append legend items text
    .attr("x", width - 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .style("text-anchor", "end")
    .text(function(d) { return d; }); // set appropriate text
</code>```

The fastest way to add tooltip use d3-tip library. Add it to your project with npm or script tag.

Define tooltip this way:

```<code>var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(data, cause) {
    return "<div class=\"tooltip\">" + cause + ":" + data.y + "</div>";
  })

svg.call(tip);
</code>```

Attach appropriate event handler functions for mouseover and mouseout event for rect elements:

```<code>layer.selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y + d.y0); })
  .attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
  .attr("width", x.rangeBand() - 1)
  .on('mouseover', function(d,i,j) { tip.show(d, causes[causes.length - 1 - j]); })
  .on('mouseout', tip.hide);
</code>```

Note: it works for d3v3 if you use d3v4 you will be forced to rewrite mouseover handler function a bit.

var causes = ["wounds", "other", "disease"];

var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 130, left: 20},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width]);

var y = d3.scale.linear()
    .rangeRound([height, 0]);

var z = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("right");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var dataAsString = `date total disease wounds other
4/1854 8571 1 0 5
5/1854 23333 12 0 9
6/1854 28333 11 0 6
7/1854 28772 359 0 23
8/1854 30246 828 1 30
9/1854 30290 788 81 70
10/1854 30643 503 132 128
11/1854 29736 844 287 106
12/1854 32779 1725 114 131
1/1855 32393 2761 83 324
2/1855 30919 2120 42 361
3/1855 30107 1205 32 172
4/1855 32252 477 48 57
5/1855 35473 508 49 37
6/1855 38863 802 209 31
7/1855 42647 382 134 33
8/1855 44614 483 164 25
9/1855 47751 189 276 20
10/1855 46852 128 53 18
11/1855 37853 178 33 32
12/1855 43217 91 18 28
1/1856 44212 42 2 48
2/1856 43485 24 0 19
3/1856 46140 15 0 35`;

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(data, cause) {
    return "
" + cause + ":" + data.y + "
";
  })

svg.call(tip);

var crimea = d3.tsv.parse(dataAsString, function(item) {
 return {
   date: parseDate(item.date),
    total: +item.total,
    disease: +item.disease,
    wounds: +item.wounds,
    other: +item.other
  };
});

var layers = d3.layout.stack()(causes.map(function(c) {
  return crimea.map(function(d) {
    return {x: d.date, y: d[c]};
  });
}));

x.domain(layers[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(layers[layers.length - 1], function(d) { return d.y0 + d.y; })]).nice();

var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return z(i); });

layer.selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y + d.y0); })
  .attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
  .attr("width", x.rangeBand() - 1)
  .on('mouseover', function(d,i,j) { tip.show(d, causes[causes.length - 1 - j]); })
  .on('mouseout', tip.hide);

svg.append("g")
  .attr("class", "axis axis--x")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "axis axis--y")
  .attr("transform", "translate(" + width + ",0)")
  .call(yAxis);

var legend = svg.append("g")
  .attr("transform", "translate(0," + (height + 25) + ")")
  .selectAll(".legend")
    .data(causes.reverse())
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

legend.append("rect")
    .attr("x", width - 18)
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d, i) { return z(causes.length - 1 - i);});

legend.append("text")
    .attr("x", width - 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .style("text-anchor", "end")
    .text(function(d) { return d; });

function type(d) {
  d.date = parseDate(d.date);
  causes.forEach(function(c) { d[c] = +d[c]; });
  return d;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.axis text {
  font: 10px sans-serif;
}

.legend {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 60%;
}

.axis line,
.axis path {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.axis--x path {
  display: none;
}

.tooltip {
  background-color: lightblue;
  border-radius: 5px;
  padding: 6px;
}</code>```

```

Body:
I have done stacked bar graph with the help of this link https://bl.ocks.org/mbostock/1134768 but i want to customize my existing code of stacked graph in which i have to add d3.legend along with tooltip.

Right now i have completed till tooltip but there is label problem because i have to give value like this 'A:100' from my array data as shown below

 var data = [
        {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
        {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
        {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"},
        {month: "7/1854",total:"400" ,A: "200", B:"100", C:"100"},
        {month: "8/1854",total:"500" ,A:"100", B:"200", C:"200"},
        {month: "9/1854",total:"600" ,A:"100", B:"200", C:"300"},
        {month: "10/1854",total:"700" ,A: "400", B:"100", C:"200"},
        {month: "11/1854",total:"800" ,A:"500", B:"200", C:"100"},
        {month: "12/1854",total:"900" ,A:"100", B:"400", C:"500"},
        {month: "13/1854",total:"1000" ,A:"500", B:"0", C:"500"}
    ];

And about d3.legend i don't find any suitable example that give me proper picture that how to use it in my existing code but i have to show like this

Here is my full working code

var xData = ["A", "B", "C"];

  var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 500 - margin.left - margin.right,
        height = 350 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();
//console.info(color(0));

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#pie").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      d.month = parseDate(d.month);
      xData.forEach(function(c) {
        d[c] = +d[c];
      });

    })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};
    });
});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x;
}));

y.domain([0,
   d3.max(data, function(d) { return d.total; })
    ])
  .nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);
        });

layer.selectAll("rect")
        .data(function (d) {
            return d;
        })
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);
        })
        .attr("y", function (d) {
            return y(d.y + d.y0);
        })
        .attr("height", function (d) {
            // console.info(d.y0, d.y, y(d.y0), y(d.y))
            return y(d.y0) - y(d.y + d.y0);
        })
        .attr("width", x.rangeBand() -1)

        .on("mouseover", function(d){

          var delta = d.y1 - d.y0;
          var xPos = parseFloat(d3.select(this).attr("x"));
          var yPos = parseFloat(d3.select(this).attr("y"));
          var height = parseFloat(d3.select(this).attr("height"))

          d3.select(this).attr("stroke","blue").attr("stroke-width",0.8);

          svg.append("text")
          .attr("x",xPos)
          .attr("y",yPos +height/2)
          .attr("class","tooltip")
          .text(d +": "+ delta);

       })
       .on("mouseout",function(){
          svg.select(".tooltip").remove();
          d3.select(this).attr("stroke","pink").attr("stroke-width",0.2);

        });

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

Please provide me some useful suggestion about my graph any help should be appreciated.

Body:
Let's add a legend and a tooltip for blocks what you mentioned (I cannot use your code because of it is incomplete). Look at the demo in the hidden snippet below (I rewrite data loading to d3.tsv.parse to simplify the example).

First of all, let's increase bottom margin to the legend fits to svg:

var margin = {top: 20, right: 50, bottom: 130, left: 20};

Adds the legend this way (pay attention to the comments):

var legend = svg.append("g") // add g element it will be the container for our legend
    .attr("transform", "translate(0," + (height + 25) + ")") // move it under the bar cart
    .selectAll(".legend")
    .data(causes.reverse()) // bind data
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); // put legend items one above the other

legend.append("rect") // append legend items rect
    .attr("x", width - 18)
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d, i) { return z(causes.length - 1 - i);}); // set appropriate color with z scale

legend.append("text") // append legend items text
    .attr("x", width - 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .style("text-anchor", "end")
    .text(function(d) { return d; }); // set appropriate text

The fastest way to add tooltip use d3-tip library. Add it to your project with npm or script tag.

Define tooltip this way:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(data, cause) {
    return "<div class=\"tooltip\">" + cause + ":" + data.y + "</div>";
  })

svg.call(tip);

Attach appropriate event handler functions for mouseover and mouseout event for rect elements:

layer.selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y + d.y0); })
  .attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
  .attr("width", x.rangeBand() - 1)
  .on('mouseover', function(d,i,j) { tip.show(d, causes[causes.length - 1 - j]); })
  .on('mouseout', tip.hide);

Note: it works for d3v3 if you use d3v4 you will be forced to rewrite mouseover handler function a bit.

var causes = ["wounds", "other", "disease"];

var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 130, left: 20},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width]);

var y = d3.scale.linear()
    .rangeRound([height, 0]);

var z = d3.scale.category10();

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("right");

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var dataAsString = `date total disease wounds other
4/1854 8571 1 0 5
5/1854 23333 12 0 9
6/1854 28333 11 0 6
7/1854 28772 359 0 23
8/1854 30246 828 1 30
9/1854 30290 788 81 70
10/1854 30643 503 132 128
11/1854 29736 844 287 106
12/1854 32779 1725 114 131
1/1855 32393 2761 83 324
2/1855 30919 2120 42 361
3/1855 30107 1205 32 172
4/1855 32252 477 48 57
5/1855 35473 508 49 37
6/1855 38863 802 209 31
7/1855 42647 382 134 33
8/1855 44614 483 164 25
9/1855 47751 189 276 20
10/1855 46852 128 53 18
11/1855 37853 178 33 32
12/1855 43217 91 18 28
1/1856 44212 42 2 48
2/1856 43485 24 0 19
3/1856 46140 15 0 35`;

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(data, cause) {
    return "<div class=\"tooltip\">" + cause + ":" + data.y + "</div>";
  })

svg.call(tip);

var crimea = d3.tsv.parse(dataAsString, function(item) {
 return {
   date: parseDate(item.date),
    total: +item.total,
    disease: +item.disease,
    wounds: +item.wounds,
    other: +item.other
  };
});

var layers = d3.layout.stack()(causes.map(function(c) {
  return crimea.map(function(d) {
    return {x: d.date, y: d[c]};
  });
}));

x.domain(layers[0].map(function(d) { return d.x; }));
y.domain([0, d3.max(layers[layers.length - 1], function(d) { return d.y0 + d.y; })]).nice();

var layer = svg.selectAll(".layer")
.data(layers)
.enter().append("g")
.attr("class", "layer")
.style("fill", function(d, i) { return z(i); });

layer.selectAll("rect")
  .data(function(d) { return d; })
  .enter().append("rect")
  .attr("x", function(d) { return x(d.x); })
  .attr("y", function(d) { return y(d.y + d.y0); })
  .attr("height", function(d) { return y(d.y0) - y(d.y + d.y0); })
  .attr("width", x.rangeBand() - 1)
  .on('mouseover', function(d,i,j) { tip.show(d, causes[causes.length - 1 - j]); })
  .on('mouseout', tip.hide);

svg.append("g")
  .attr("class", "axis axis--x")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis);

svg.append("g")
  .attr("class", "axis axis--y")
  .attr("transform", "translate(" + width + ",0)")
  .call(yAxis);

var legend = svg.append("g")
  .attr("transform", "translate(0," + (height + 25) + ")")
  .selectAll(".legend")
    .data(causes.reverse())
    .enter().append("g")
    .attr("class", "legend")
    .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

legend.append("rect")
    .attr("x", width - 18)
    .attr("width", 18)
    .attr("height", 18)
    .style("fill", function(d, i) { return z(causes.length - 1 - i);});

legend.append("text")
    .attr("x", width - 24)
    .attr("y", 9)
    .attr("dy", ".35em")
    .style("text-anchor", "end")
    .text(function(d) { return d; });

function type(d) {
  d.date = parseDate(d.date);
  causes.forEach(function(c) { d[c] = +d[c]; });
  return d;
}

.axis text {
  font: 10px sans-serif;
}

.legend {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 60%;
}

.axis line,
.axis path {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}

.axis--x path {
  display: none;
}

.tooltip {
  background-color: lightblue;
  border-radius: 5px;
  padding: 6px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.js"></script>


问:
Disable Submit button on selection from DropDownListFor
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

```<code>      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />
</code>```

js code:

```<code>   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });
</code>```

No error message just the submit button is always enabled. Any help?

答:
I am not familiar with @Html.DropDownListFor;

But given your questions's demand (which was mainly on js part); I used direct html tags;

nonetheless this solution should work for you;

Hope this helps;

let allOptions = document.querySelectorAll("#year option");
let allChoices = [];
for(i=0;i<allOptions.length;i++) {
 allChoices.push(allOptions[i].innerHTML);
}

$("#inputBox").on('keyup',function () {

        if (allChoices.indexOf(document.getElementById("inputBox").value) != -1)
            $('.submit').attr("disabled", true);
        else
            $('.submit').attr("disabled", false);
    });```
<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>
<select id="year">
 <option>defaultvalue</option>
 <option>option1</option>
 <option>option2</option>
 </select>

<input type="text" id="inputBox"/>
 <button type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" >submit
 </button></code>```

Body:
I am working on this code when the submit button will be enabled only when user selects values from a DropDownListFor.

      @Html.DropDownListFor(m => m.Year, Model.YearList, "--Select Year--", new { @class = "form-control",id = "Year" })
      @Html.ValidationMessageFor(m => m.Year)

 <input type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" />

js code:

   $("#Year").change(function () {
        if ($('#Year').val()!="--Select Year--")
            $('.submit').prop("disabled", false);
        else
            $('.submit').prop("disabled", true);
    });

No error message just the submit button is always enabled. Any help?

Body:
I am not familiar with @Html.DropDownListFor;

But given your questions's demand (which was mainly on js part); I used direct html tags;

nonetheless this solution should work for you;

Hope this helps;

let allOptions = document.querySelectorAll("#year option");
let allChoices = [];
for(i=0;i<allOptions.length;i++) {
 allChoices.push(allOptions[i].innerHTML);
}

$("#inputBox").on('keyup',function () {

        if (allChoices.indexOf(document.getElementById("inputBox").value) != -1)
            $('.submit').attr("disabled", true);
        else
            $('.submit').attr("disabled", false);
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="year">
 <option>defaultvalue</option>
 <option>option1</option>
 <option>option2</option>
 </select>

<input type="text" id="inputBox"/>
 <button type="submit" id="submit" name="submit" value="Submit" class="btn btn-lg btn-success" >submit
 </button>


问:
python __name__ global variable gives different output than expected
I am trying to get a hands-on in python modules.

my code is,

```<code>#filename:module.py
def printname():
    print __name__

printname()
</code>```

when I am executing the code with interpreter

```<code>python module.py
</code>```

It gives output(i.e. module name as)

```<code>main
</code>```

and when I import the module into another file and calling the module there it gives output as module name(expected).

```<code>module
</code>```

according to docs, It should give module name as output. Why is the variation in output??

答:
The main script is always called __main__. This is entirely correct behaviour.

From the very same page you linked to,
 in the preceding Executing modules as scripts section, you'll find:

When you run a Python module with

```<code>python fibo.py <arguments>
</code>```

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".

For everything you import, __name__ will reflect the module name under which it was first available.

Also see the Interface options documentation:

Body:
I am trying to get a hands-on in python modules.

my code is,

#filename:module.py
def printname():
    print __name__

printname()

when I am executing the code with interpreter

python module.py

It gives output(i.e. module name as)

main

and when I import the module into another file and calling the module there it gives output as module name(expected).

module

according to docs, It should give module name as output. Why is the variation in output??

Body:
The main script is always called __main__. This is entirely correct behaviour.

From the very same page you linked to,
 in the preceding Executing modules as scripts section, you'll find:

When you run a Python module with

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__".

For everything you import, __name__ will reflect the module name under which it was first available.

Also see the Interface options documentation:

<script>

[...]

If the script name refers directly to a Python file, the directory containing that file is added to the start of sys.path, and the file is executed as the __main__ module.

and the __main__ Top-level script environment documentation:

This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt.


问:
matlab on linux can't plot anything(can't load libstdc++.so.6: version `CXXABI_1.3.8' not found)
I'm running matlab R2016a on Fedora 24 and I can't use the plot command.

This is the error I get:

Error using gca

While setting the 'Parent' property of 'Axes':

Can't load
  '/usr/local/MATLAB/R2016a/bin/glnxa64/libmwosgserver.so':
  /usr/local/MATLAB/R2016a/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6:
  version 'CXXABI_1.3.8' not found (required by /lib64/libGLU.so.1)

Error in newplot (line 73)

```<code>ax = gca(fig);
</code>```

Also I have seen
How to fix: [program name] /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found (required by [program name])
and it doesn't help.

答:
Alternate fix:

Rename the libstdc++.so.6 library file so that MATLAB cannot find it and is forced to use the system's version of the library. This file is located in matlabroot/sys/os/glnxa64/

Source: https://in.mathworks.com/matlabcentral/answers/329796-issue-with-libstdc-so-6

I tried and it worked like charm.

Body:
I'm running matlab R2016a on Fedora 24 and I can't use the plot command.

This is the error I get:

Error using gca

While setting the 'Parent' property of 'Axes':

Can't load
  '/usr/local/MATLAB/R2016a/bin/glnxa64/libmwosgserver.so':
  /usr/local/MATLAB/R2016a/bin/glnxa64/../../sys/os/glnxa64/libstdc++.so.6:
  version 'CXXABI_1.3.8' not found (required by /lib64/libGLU.so.1)

Error in newplot (line 73)

ax = gca(fig);

Also I have seen
How to fix: [program name] /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version CXXABI_1.3.8' not found (required by [program name])
and it doesn't help.


问:
Catch error in combined pipe of pipeable rxjs operators
We've just upgraded one of our applications to Angular 5, and started to transition into lettable operators as introduced in rxjs v5.5.

Because of this, we have rewritten our observable pipelines to the new syntax with the .pipe() operator.

Our previous code would look like this, with a .catch() inside the .switchMap() as to not interrupt the running of effects if an error is thrown.

```<code>@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.map((action: LoadData) => action.payload)
.withLatestFrom(this.store.select(getCultureCode))
.switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)
  .map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  .catch((err, caught) => {
    return Observable.empty();
  });
  );
</code>```

In the case of an error thrown in the call to the dataService it would be caught and handled (simplified the error handling here).

With the new syntax and use of .pipe(), we now have this

```<code>@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
  map((action: LoadData) => action.payload),
  withLatestFrom(this.store.select(getCultureCode)),
  switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)),
  map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  );
</code>```

How can I in a similar fashion catch any thrown errors in the observable pipeline, using the new syntax?

答:
After refactoring you moved map out of switchMap projection, so any error will close the outer stream. To keep both streams equivalent, you need to use pipe in the projection itself like that:

```<code>import { EMPTY } from 'rxjs';

// ...

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
  map((action: LoadData) => action.payload),
  withLatestFrom(this.store.select(getCultureCode)),
  switchMap(([payload, cultureCode]) =>
    this.dataService.loadData(payload, cultureCode)
      .pipe(
         map(result => {
           if (!result) {
             return new LoadDataFailed('Could not fetch data!');
           } else {
             return new LoadDataSuccessful(result);
           }
          }),
         catchError((err, caught) => {
           return EMPTY;
         })
      )
  )
);
</code>```

Body:
We've just upgraded one of our applications to Angular 5, and started to transition into lettable operators as introduced in rxjs v5.5.

Because of this, we have rewritten our observable pipelines to the new syntax with the .pipe() operator.

Our previous code would look like this, with a .catch() inside the .switchMap() as to not interrupt the running of effects if an error is thrown.

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.map((action: LoadData) => action.payload)
.withLatestFrom(this.store.select(getCultureCode))
.switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)
  .map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  .catch((err, caught) => {
    return Observable.empty();
  });
  );

In the case of an error thrown in the call to the dataService it would be caught and handled (simplified the error handling here).

With the new syntax and use of .pipe(), we now have this

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
  map((action: LoadData) => action.payload),
  withLatestFrom(this.store.select(getCultureCode)),
  switchMap(([payload, cultureCode]) => this.dataService.loadData(payload, cultureCode)),
  map(result => {
    if (!result) {
      return new LoadDataFailed('Could not fetch data!');
    } else {
      return new LoadDataSuccessful(result);
    }
  })
  );

How can I in a similar fashion catch any thrown errors in the observable pipeline, using the new syntax?

Body:
After refactoring you moved map out of switchMap projection, so any error will close the outer stream. To keep both streams equivalent, you need to use pipe in the projection itself like that:

import { EMPTY } from 'rxjs';

// ...

@Effect()
loadData$ = this.actions$
.ofType(LOAD_DATA)
.pipe(
  map((action: LoadData) => action.payload),
  withLatestFrom(this.store.select(getCultureCode)),
  switchMap(([payload, cultureCode]) =>
    this.dataService.loadData(payload, cultureCode)
      .pipe(
         map(result => {
           if (!result) {
             return new LoadDataFailed('Could not fetch data!');
           } else {
             return new LoadDataSuccessful(result);
           }
          }),
         catchError((err, caught) => {
           return EMPTY;
         })
      )
  )
);


问:
How properly calculate cornerRadius depending on the button frame
How to calculate cornerRadius property based on frame of the button to create rounded corners.

I do not like to redefine each time corner cornerRadius for each button item.

I create extension for the UIButton.

```<code>extension UIButton {

    func setRoundedCorners(){
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 1
    }

}
</code>```

And i would like to know how too calculate dynamically cornerRadius each time i use this function.

The main issue to find function that will calculate .cornerRadius for different button sizes. Example below will show small difference.

Example:

Corner radius is 10:

:

Corner radius is 15:

Is it possible to find function that will calculate proper value that will give corner radius?

答:
I was looking for the same thing and found myself a very clear and easy solution. As it is an extension to UIView you can not only use it on buttons but several objects.

```<code>extension UIView{
    func cornerCalculation(r: CGFloat) {
        self.layer.cornerRadius = self.frame.height/2 * r
    }
}
</code>```

and then just call:

```<code>button.cornerCalculation(r: 1)
</code>```

r would be any number between 0 (sharp edges) and 1 (completley rounded edges)

Body:
How to calculate cornerRadius property based on frame of the button to create rounded corners.

I do not like to redefine each time corner cornerRadius for each button item.

I create extension for the UIButton.

extension UIButton {

    func setRoundedCorners(){
        self.layer.cornerRadius = 10
        self.layer.borderWidth = 1
    }

}

And i would like to know how too calculate dynamically cornerRadius each time i use this function.

The main issue to find function that will calculate .cornerRadius for different button sizes. Example below will show small difference.

Example:

Corner radius is 10:

:

Corner radius is 15:

Is it possible to find function that will calculate proper value that will give corner radius?

Body:
I was looking for the same thing and found myself a very clear and easy solution. As it is an extension to UIView you can not only use it on buttons but several objects.

extension UIView{
    func cornerCalculation(r: CGFloat) {
        self.layer.cornerRadius = self.frame.height/2 * r
    }
}

and then just call:

button.cornerCalculation(r: 1)

r would be any number between 0 (sharp edges) and 1 (completley rounded edges)


问:
Integrating CKEditor in an ASP.Net Webforms Application
I'm trying to use CKEditor in my Webforms application and I have tried many other methods without success. Can someone help? The site uses a Site.Master file which all the aspx files provide content for using content place-holders. So I place the JavaScript call in the ASPX rather than in the master file.

I'm also trying to get it to edit in a content editable div element. It works fine in a small test site but not in my application. Any ideas?

My Site.master has two content placeholders I want to use:

<asp:ContentPlaceHolder ID="Scripts" runat="server" />

and

<asp:ContentPlaceHolder ID="MainContent" runat="server">

An then my aspx files have:

```<code><asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">
<script src="ckeditor/ckeditor.js"></script>
</asp:Content>`
</code>```

and

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

</asp:Content>
</asp:Content>

Somewhere in my JavaScript, I set the content editable of my renderTarget div to true.

$(".contentbox[dynamic='true']").attr("contenteditable", "true");

And at this point, I expect CKedtor to add its controls to the div. But It doesn't. i use the same process with TinyMCE  and it works fine.

答:
all you need is to install the version for asp.net in your project and then just use it as simple as adding a usercontrol:

```<code><ckeditor:ckeditorcontrol ID="CkEditor1" runat="server"></ckeditor:ckeditorcontrol>
</code>```

Documentation from ckEditor

Body:
I'm trying to use CKEditor in my Webforms application and I have tried many other methods without success. Can someone help? The site uses a Site.Master file which all the aspx files provide content for using content place-holders. So I place the JavaScript call in the ASPX rather than in the master file.

I'm also trying to get it to edit in a content editable div element. It works fine in a small test site but not in my application. Any ideas?

My Site.master has two content placeholders I want to use:

<asp:ContentPlaceHolder ID="Scripts" runat="server" />

and

<asp:ContentPlaceHolder ID="MainContent" runat="server">

An then my aspx files have:

<asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">

</asp:Content>`

and

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

</asp:Content>
</asp:Content>

Somewhere in my JavaScript, I set the content editable of my renderTarget div to true.

$(".contentbox[dynamic='true']").attr("contenteditable", "true");

And at this point, I expect CKedtor to add its controls to the div. But It doesn't. i use the same process with TinyMCE  and it works fine.

Body:
all you need is to install the version for asp.net in your project and then just use it as simple as adding a usercontrol:

<ckeditor:ckeditorcontrol ID="CkEditor1" runat="server"></ckeditor:ckeditorcontrol>

Documentation from ckEditor