问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答:
You could pass it as a constructor parameter, rather than a method parameter, e.g.:

```<code>public class InputEngine
{
    public InputEngine(IGuiEngine guiEngine)
    {
         // set private member to store guiEngine
    }
}
</code>```

Note I've also changed the GuiEngine to an interface - this way you can use a Dependency Injection container, such as StructureMap to automatically pass the GUI engine to your instances as required.  Helps with testing too.

Alternatively, you could use a DI container, or a factory class, to provide a singleton instance of the GUI Engine.

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

Body:
You could pass it as a constructor parameter, rather than a method parameter, e.g.:

public class InputEngine
{
    public InputEngine(IGuiEngine guiEngine)
    {
         // set private member to store guiEngine
    }
}

Note I've also changed the GuiEngine to an interface - this way you can use a Dependency Injection container, such as StructureMap to automatically pass the GUI engine to your instances as required.  Helps with testing too.

Alternatively, you could use a DI container, or a factory class, to provide a singleton instance of the GUI Engine.


来源: stackexchange

问:
sql - Joining one table to two more tables
I am trying to join a table (employee table) to two other tables (employee earnings and employee deductions) to display the amount for the particular type of earning and deduction of employee. Now, when my query duplicates the deduction when the employee has a record for two different types of earning and only one record for a deduction type. Employee has a one-to-many relationship to both earning and deduction tables.

Here is my query:

```<code>SELECT EmployeeMaster.EmployeeNumber, FirstName, LastName, MiddleName, empEarnings.EarningCode, empEarnings.amt, empDeduc.DeductionId, empDeduc.amt
from EmployeeMaster
LEFT OUTER JOIN
(
    SELECT EmployeeNumber, EarningCode, SUM(Amount) AS amt FROM EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
) AS empEarnings
ON EmployeeMaster.EmployeeNumber = empEarnings.EmployeeNumber
LEFT OUTER JOIN
(
    SELECT EmployeeID, DeductionID, SUM(Amount) AS amt FROM EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS empDeduc
ON EmployeeMaster.EmployeeNumber = empDeduc.EmployeeId
</code>```

This returns (sample data only)

```<code>00001   First Name  Last Name   EARN       1000000.0000000000000000 SSS 1000.0000000000000000
00001   First Name  Last Name   EARN2      1000.0000000000000000    SSS 1000.0000000000000000
00002   First Name2 Last Name2  EARN       10000.0000000000000000   SSS 100.0000000000000000
00002   First Name2 Last Name2  EARN2      10000.0000000000000000   SSS 100.0000000000000000
</code>```

The result is almost correct except, these employees only have one record of a deduction type. However, the result set duplicates the deduction table result which results to the sum of the total deduction being wrong (double of the supposed value) in my ssrs report.

How should I modify my query to fit these requirements, and also being able to generate an ssrs report in a format like:

```<code>Emp# First Name Last Name EarnType1 EarnType2 [...] DeducType1 DeducType2 [...]
#1    John        Doe       100000    100000        100        100
</code>```

答:
I would go about this differently.

What you need to do it produce a flat list of employees with earnings and deductions and then simply get your report to group the earning/deductions by code.

I've put together a simple script which does this. It's more or less the same as yours (obvious exception is the table names are variables so just swap these for you real table names)

```<code>DECLARE @EmployeeMaster TABLE (EmployeeNumber int, FirstName varchar(30), LastName varchar(30), MiddleName varchar(30))
DECLARE @EmployeeEarnings TABLE (EmployeeNumber int, EarningCode varchar(10), Amount float)
DECLARE @EmployeeDeduction TABLE (EmployeeID int, DeductionID varchar(10), Amount float)

INSERT INTO @EmployeeMaster
VALUES (1, 'Bob', 'Smith', 'W'), (2, 'Jane', 'Jones', 'A')

INSERT INTO @EmployeeEarnings
VALUES (1, 'Earn1', 1000000), (1, 'Earn2', 1000), (2, 'Earn1', 500000), (2, 'Earn2', 500)

INSERT INTO @EmployeeDeduction
VALUES (1, 'Deduct1', 1000), (1, 'Deduct2', 800), (2, 'Deduct1', 500), (2, 'Deduct2', 200)

SELECT
    emp.EmployeeNumber, FirstName, LastName, MiddleName
    , amts.AmountCode, amts.amt, amts.AmountType
from @EmployeeMaster emp
LEFT OUTER JOIN
(
    SELECT 'Earning' as AmountType, EmployeeNumber, EarningCode as AmountCode
            , SUM(Amount) AS amt
            FROM @EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
    UNION ALL
    SELECT 'Deduction', EmployeeID, DeductionID
            , SUM(Amount) AS amt FROM @EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS amts
ON emp.EmployeeNumber = amts.EmployeeNumber
</code>```

All we've done here is union all the earnings and deductions into a single set and labelled each as whatever type they are (the amount type is not actually necessary unless you want you report to keep earnings and deductions bunched togther)

This gives us the following output

```<code>        EmployeeNumber  FirstName   LastName    MiddleName  AmountCode  amt     AmountType
        1               Bob         Smith       W           Deduct1     1000    Deduction
        1               Bob         Smith       W           Deduct2     800 Deduction
        1               Bob         Smith       W           Earn1       1000000 Earning
        1               Bob         Smith       W           Earn2       1000    Earning
        2               Jane        Jones       A           Deduct1     1000    Deduction
        2               Jane        Jones       A           Deduct2     800 Deduction
        2               Jane        Jones       A           Earn1       1000000 Earning
        2               Jane        Jones       A           Earn2       1000    Earning
</code>```

Then I created a simple matrix reports, here's the design...

When we run the report, we get this...

As you can see there are two column groups, one to group by type (earn/deduct) and the other by code. The matrix will expand to accommodate any number of earning and deduction codes automatically.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to join a table (employee table) to two other tables (employee earnings and employee deductions) to display the amount for the particular type of earning and deduction of employee. Now, when my query duplicates the deduction when the employee has a record for two different types of earning and only one record for a deduction type. Employee has a one-to-many relationship to both earning and deduction tables.

Here is my query:

SELECT EmployeeMaster.EmployeeNumber, FirstName, LastName, MiddleName, empEarnings.EarningCode, empEarnings.amt, empDeduc.DeductionId, empDeduc.amt
from EmployeeMaster
LEFT OUTER JOIN
(
    SELECT EmployeeNumber, EarningCode, SUM(Amount) AS amt FROM EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
) AS empEarnings
ON EmployeeMaster.EmployeeNumber = empEarnings.EmployeeNumber
LEFT OUTER JOIN
(
    SELECT EmployeeID, DeductionID, SUM(Amount) AS amt FROM EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS empDeduc
ON EmployeeMaster.EmployeeNumber = empDeduc.EmployeeId

This returns (sample data only)

00001   First Name  Last Name   EARN       1000000.0000000000000000 SSS 1000.0000000000000000
00001   First Name  Last Name   EARN2      1000.0000000000000000    SSS 1000.0000000000000000
00002   First Name2 Last Name2  EARN       10000.0000000000000000   SSS 100.0000000000000000
00002   First Name2 Last Name2  EARN2      10000.0000000000000000   SSS 100.0000000000000000

The result is almost correct except, these employees only have one record of a deduction type. However, the result set duplicates the deduction table result which results to the sum of the total deduction being wrong (double of the supposed value) in my ssrs report.

How should I modify my query to fit these requirements, and also being able to generate an ssrs report in a format like:

Emp# First Name Last Name EarnType1 EarnType2 [...] DeducType1 DeducType2 [...]
#1    John        Doe       100000    100000        100        100

Body:
I would go about this differently.

What you need to do it produce a flat list of employees with earnings and deductions and then simply get your report to group the earning/deductions by code.

I've put together a simple script which does this. It's more or less the same as yours (obvious exception is the table names are variables so just swap these for you real table names)

DECLARE @EmployeeMaster TABLE (EmployeeNumber int, FirstName varchar(30), LastName varchar(30), MiddleName varchar(30))
DECLARE @EmployeeEarnings TABLE (EmployeeNumber int, EarningCode varchar(10), Amount float)
DECLARE @EmployeeDeduction TABLE (EmployeeID int, DeductionID varchar(10), Amount float)

INSERT INTO @EmployeeMaster
VALUES (1, 'Bob', 'Smith', 'W'), (2, 'Jane', 'Jones', 'A')

INSERT INTO @EmployeeEarnings
VALUES (1, 'Earn1', 1000000), (1, 'Earn2', 1000), (2, 'Earn1', 500000), (2, 'Earn2', 500)

INSERT INTO @EmployeeDeduction
VALUES (1, 'Deduct1', 1000), (1, 'Deduct2', 800), (2, 'Deduct1', 500), (2, 'Deduct2', 200)

SELECT
    emp.EmployeeNumber, FirstName, LastName, MiddleName
    , amts.AmountCode, amts.amt, amts.AmountType
from @EmployeeMaster emp
LEFT OUTER JOIN
(
    SELECT 'Earning' as AmountType, EmployeeNumber, EarningCode as AmountCode
            , SUM(Amount) AS amt
            FROM @EmployeeEarnings GROUP BY EmployeeNumber, EarningCode
    UNION ALL
    SELECT 'Deduction', EmployeeID, DeductionID
            , SUM(Amount) AS amt FROM @EmployeeDeduction GROUP BY EmployeeID, DeductionId
) AS amts
ON emp.EmployeeNumber = amts.EmployeeNumber

All we've done here is union all the earnings and deductions into a single set and labelled each as whatever type they are (the amount type is not actually necessary unless you want you report to keep earnings and deductions bunched togther)

This gives us the following output

        EmployeeNumber  FirstName   LastName    MiddleName  AmountCode  amt     AmountType
        1               Bob         Smith       W           Deduct1     1000    Deduction
        1               Bob         Smith       W           Deduct2     800 Deduction
        1               Bob         Smith       W           Earn1       1000000 Earning
        1               Bob         Smith       W           Earn2       1000    Earning
        2               Jane        Jones       A           Deduct1     1000    Deduction
        2               Jane        Jones       A           Deduct2     800 Deduction
        2               Jane        Jones       A           Earn1       1000000 Earning
        2               Jane        Jones       A           Earn2       1000    Earning

Then I created a simple matrix reports, here's the design...

When we run the report, we get this...

As you can see there are two column groups, one to group by type (earn/deduct) and the other by code. The matrix will expand to accommodate any number of earning and deduction codes automatically.


问:
Customized validation rule on laravel form request validation
I do have a registration  form in my laravel 5.4 application and laravel form request validation is used for server side validation. Some fields in this form are populated dynamically using calculations in javascript which need to be validated against user inputs.

The user input fields in the form are 'quantity', 'rate' and 'discount'.

The populated fields are 'total' and 'bill_amount'.

What i need to validate are :

Check 'total' equal to 'quantity' * 'rate'.

Check 'bill_amount' equal to 'total' - 'rate'

I would prefer laravel form request validation methods for this validation. I have tried to use methods like After Hooks and conditionally adding rule etc. and failed.

In simple words the requirement is : check if a field is equal to product of other two fields, and invalidate if not equal and validate if equal.(using form request validation.)

Thanks in advance!

答:
After a long time I was able to find this solution.

Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]

```<code>public function withValidator($validator)
    {
        $quanty     = $this->request->get("quantity");
        $rate       = $this->request->get("rate");
        $billAmount = $this->request->get("bill_amount");

        $validator->after(function ($validator) {
            if(($quanty * $rate) != $billAmount) {
                $validator->errors()->add('bill_amount', 'Something went wrong with this field!');
            }
        });
    }
</code>```

Body:
After a long time I was able to find this solution.

Form request After Hooks can be used to achieve the result:
[I was unable to find this logic before]

public function withValidator($validator)
    {
        $quanty     = $this->request->get("quantity");
        $rate       = $this->request->get("rate");
        $billAmount = $this->request->get("bill_amount");

        $validator->after(function ($validator) {
            if(($quanty * $rate) != $billAmount) {
                $validator->errors()->add('bill_amount', 'Something went wrong with this field!');
            }
        });
    }


问:
How to count each element from a pdb file
I am having trouble trying to count the amount of each element provided in a pdb file. So far, the code has achieved to take the lines from the file that starts with ATOM. I have also gotten to the point where I can print each element. But  now I want to count each element such as C,O,N, and so on and list them in alphabetical order.
The data looks like this:

```<code> ATOM   4851  O   PRO A 715      89.164  76.083  75.292  1.00 99.41           O
 ATOM   4852  CB  PRO A 715      88.324  78.267  73.865  1.00 95.88           C
 ATOM   4853  CG  PRO A 715      88.836  78.838  72.540  1.00 95.93           C
 ATOM   4854  CD  PRO A 715      90.288  78.546  72.593  1.00 94.99           C
 ATOM   4855  N   PHE A 716      90.009  77.320  76.994  1.00100.00           N
 ATOM   4856  CA  PHE A 716      90.100  76.203  77.966  1.00 99.66           C
 ATOM   4857  C   PHE A 716      89.942  76.667  79.419  1.00 99.17           C
 ATOM   4858  O   PHE A 716      88.895  76.334  80.027  1.00100.00           O
 ATOM   4859  CB  PHE A 716      91.409  75.402  77.819  1.00 97.04           C
 ATOM   4860  CG  PHE A 716      91.290  74.219  76.899  1.00 96.00           C
 ATOM   4861  CD1 PHE A 716      90.323  73.236  77.133  1.00 94.17           C
 ATOM   4862  CD2 PHE A 716      92.112  74.107  75.774  1.00 94.87           C
 ATOM   4863  CE1 PHE A 716      90.170  72.157  76.260  1.00 93.04           C
 ATOM   4864  CE2 PHE A 716      91.971  73.037  74.894  1.00 93.41           C
 ATOM   4865  CZ  PHE A 716      90.996  72.057  75.137  1.00 95.29           C
</code>```

My code is :

```<code>open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters
#The function will also sort each element alphabetically and count them
sub atomfreq {
    foreach my $record1(@newlines) {
      my @element = substr($record1, 76, 2);
      my @sortelement = sort(@element);
      print "@sortelement\n";
    }
}
</code>```

Thanks.

答:
There's no need to open a file passed as a parameter on the command line: you can just read from it using <>. It is also much more concise to use grep rather a read loop, a test, and a push

I also don't see why you need a subroutine here

This code will do what you ask

use strict;
use warnings 'all';

my @lines = grep /^ATOM/, <>;

my %counts;
++$counts{ unpack '@77 A2' } for @lines;
printf "%-4s%4d\n", $_, $counts{$_} for sort keys %counts;
```

<h3>output</h3>

<pre class="lang-none prettyprint-override"><code>C     12
N      1
O      2
</code>```

Body:
I am having trouble trying to count the amount of each element provided in a pdb file. So far, the code has achieved to take the lines from the file that starts with ATOM. I have also gotten to the point where I can print each element. But  now I want to count each element such as C,O,N, and so on and list them in alphabetical order.
The data looks like this:

 ATOM   4851  O   PRO A 715      89.164  76.083  75.292  1.00 99.41           O
 ATOM   4852  CB  PRO A 715      88.324  78.267  73.865  1.00 95.88           C
 ATOM   4853  CG  PRO A 715      88.836  78.838  72.540  1.00 95.93           C
 ATOM   4854  CD  PRO A 715      90.288  78.546  72.593  1.00 94.99           C
 ATOM   4855  N   PHE A 716      90.009  77.320  76.994  1.00100.00           N
 ATOM   4856  CA  PHE A 716      90.100  76.203  77.966  1.00 99.66           C
 ATOM   4857  C   PHE A 716      89.942  76.667  79.419  1.00 99.17           C
 ATOM   4858  O   PHE A 716      88.895  76.334  80.027  1.00100.00           O
 ATOM   4859  CB  PHE A 716      91.409  75.402  77.819  1.00 97.04           C
 ATOM   4860  CG  PHE A 716      91.290  74.219  76.899  1.00 96.00           C
 ATOM   4861  CD1 PHE A 716      90.323  73.236  77.133  1.00 94.17           C
 ATOM   4862  CD2 PHE A 716      92.112  74.107  75.774  1.00 94.87           C
 ATOM   4863  CE1 PHE A 716      90.170  72.157  76.260  1.00 93.04           C
 ATOM   4864  CE2 PHE A 716      91.971  73.037  74.894  1.00 93.41           C
 ATOM   4865  CZ  PHE A 716      90.996  72.057  75.137  1.00 95.29           C

My code is :

open (FILE, $ARGV[0])
    or die "Could not open file\n";

my @newlines;
while ( my $line = <FILE> ) {
    if ($line =~ m/^ATOM.*/) {
    push @newlines, $line;
    }
}

##############################################################
#This function will take out the element from each line
#The element is from column 77 and contains one or two letters
#The function will also sort each element alphabetically and count them
sub atomfreq {
    foreach my $record1(@newlines) {
      my @element = substr($record1, 76, 2);
      my @sortelement = sort(@element);
      print "@sortelement\n";
    }
}

Thanks.

Body:
There's no need to open a file passed as a parameter on the command line: you can just read from it using <>. It is also much more concise to use grep rather a read loop, a test, and a push

I also don't see why you need a subroutine here

This code will do what you ask

use strict;
use warnings 'all';

my @lines = grep /^ATOM/, <>;

my %counts;
++$counts{ unpack '@77 A2' } for @lines;
printf "%-4s%4d\n", $_, $counts{$_} for sort keys %counts;

output

C     12
N      1
O      2


问:
xtable for conditional cell formatting not with special characters
I'm apply solution from xtable for conditional cell formatting significant p-values of table to my data set; however, I can't use sanitize.text.function = function(x) x as per the suggested answer.

Example

Data set

The data set contains text columns that utilise _ character, as in the example below:

```<code>dta <- data.frame(
    varA = c("this_and_that", "something_else", "def"),
    varB = c("other_thing", "something_different", "abc")
)
</code>```

xtable

When passed to xtable it using the syntax:

```<code>print.xtable(x = xtable(dta),
             booktabs = TRUE,
             comment = FALSE,
             floating = TRUE,
             type = "latex",
             include.rownames = FALSE,
             NA.string = "NA",
             # Font and linespace size
             size = "\\fontsize{5pt}{5pt}\\selectfont")
</code>```

the code generates usable latex snippet:

```<code>\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this\_and\_that & other\_thing \\
  something\_else & something\_different \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}
</code>```

Problem

I would like to apply \textbf{} to columns with word something. Following the answers discussed in the linked question this could be done via ifelse and sanitize.text.function = function(x) x as in the example below:

```<code>print.xtable(
    x = xtable(dta %>%
                   mutate_all(funs(
                       ifelse(grepl("something", .), paste0("\\textbf{", ., "}"), .)
                   ))),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
        x
    }
)
</code>```

This will generate correct syntax with respect to the \\textbf{} but the _ is not escaped due to : sanitize.text.function = function(x) {x}.

```<code>\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this_and_that & other_thing \\
  \textbf{something_else} & \textbf{something_different} \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}
</code>```

Removed sanitize.text.function

The code:

```<code>print.xtable(
    x = xtable(dta %>%
                   mutate_all(funs(
                       ifelse(grepl("something", .), paste0("\\textbf{", ., "}"), .)
                   ))),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont"
)
</code>```

will generate awful mess as default sanitize behaviour will attempt to escape \\textbf

```<code>\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this\_and\_that & other\_thing \\
  $\backslash$textbf\{something\_else\} & $\backslash$textbf\{something\_different\} \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}
</code>```

Alternative approach / side point

Probably better approach would be to make use of the sanitize function:

```<code>print.xtable(
    x = xtable(dta),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
        ifelse(grepl("something", x), paste0("\\textbf{", x, "}"), x)
    }
)
</code>```

Summary

Is there other way of addressing this problem than greping all the special characters in my table and manually escaping them via custom sanitize function that would handle both elements textbf{} and _ correctly?

Working solution

Using:

```<code>  sanitize.text.function = function(x) {
    gsub(fixed = TRUE, pattern = "_", replacement = "\\_",
         x = ifelse(grepl(pattern = "something", x = x), paste0("\\textbf{", x, "}"), x)
         )
  }
</code>```

will work as it manually escapes _, ideally I would like to find a solution where I wouldn't have to manually espace each single character.

答:
There is a function in Hmisc which does the work : latexTranslate. Run it first and then apply the LATEX format commands.

```<code>library("Hmisc")
library("xtable")
dta <- data.frame(
    varA = c("this_and_that", "something_else", "def"),
    varB = c("other_thing", "something_different", "abc")
)
print.xtable(
    x = xtable(dta),
    file=paste0(getwd(),"/table/sanitize_test.tex"),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
      x <- latexTranslate(x)
      x <- ifelse(grepl("something", x), paste0("\\textbf{", x, "}"), x)
      return(x)
    }
)
</code>```

Body:
I'm apply solution from xtable for conditional cell formatting significant p-values of table to my data set; however, I can't use sanitize.text.function = function(x) x as per the suggested answer.

Example

Data set

The data set contains text columns that utilise _ character, as in the example below:

dta <- data.frame(
    varA = c("this_and_that", "something_else", "def"),
    varB = c("other_thing", "something_different", "abc")
)

xtable

When passed to xtable it using the syntax:

print.xtable(x = xtable(dta),
             booktabs = TRUE,
             comment = FALSE,
             floating = TRUE,
             type = "latex",
             include.rownames = FALSE,
             NA.string = "NA",
             # Font and linespace size
             size = "\\fontsize{5pt}{5pt}\\selectfont")

the code generates usable latex snippet:

\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this\_and\_that & other\_thing \\
  something\_else & something\_different \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}

Problem

I would like to apply \textbf{} to columns with word something. Following the answers discussed in the linked question this could be done via ifelse and sanitize.text.function = function(x) x as in the example below:

print.xtable(
    x = xtable(dta %>%
                   mutate_all(funs(
                       ifelse(grepl("something", .), paste0("\\textbf{", ., "}"), .)
                   ))),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
        x
    }
)

This will generate correct syntax with respect to the \\textbf{} but the _ is not escaped due to : sanitize.text.function = function(x) {x}.

\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this_and_that & other_thing \\
  \textbf{something_else} & \textbf{something_different} \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}

Removed sanitize.text.function

The code:

print.xtable(
    x = xtable(dta %>%
                   mutate_all(funs(
                       ifelse(grepl("something", .), paste0("\\textbf{", ., "}"), .)
                   ))),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont"
)

will generate awful mess as default sanitize behaviour will attempt to escape \\textbf

\begin{table}[ht]
\centering
\begingroup\fontsize{5pt}{5pt}\selectfont
\begin{tabular}{ll}
  \toprule
varA & varB \\
  \midrule
this\_and\_that & other\_thing \\
  $\backslash$textbf\{something\_else\} & $\backslash$textbf\{something\_different\} \\
  def & abc \\
   \bottomrule
\end{tabular}
\endgroup
\end{table}

Alternative approach / side point

Probably better approach would be to make use of the sanitize function:

print.xtable(
    x = xtable(dta),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
        ifelse(grepl("something", x), paste0("\\textbf{", x, "}"), x)
    }
)

Summary

Is there other way of addressing this problem than greping all the special characters in my table and manually escaping them via custom sanitize function that would handle both elements textbf{} and _ correctly?

Working solution

Using:

  sanitize.text.function = function(x) {
    gsub(fixed = TRUE, pattern = "_", replacement = "\\_",
         x = ifelse(grepl(pattern = "something", x = x), paste0("\\textbf{", x, "}"), x)
         )
  }

will work as it manually escapes _, ideally I would like to find a solution where I wouldn't have to manually espace each single character.

Body:
There is a function in Hmisc which does the work : latexTranslate. Run it first and then apply the LATEX format commands.

library("Hmisc")
library("xtable")
dta <- data.frame(
    varA = c("this_and_that", "something_else", "def"),
    varB = c("other_thing", "something_different", "abc")
)
print.xtable(
    x = xtable(dta),
    file=paste0(getwd(),"/table/sanitize_test.tex"),
    booktabs = TRUE,
    comment = FALSE,
    floating = TRUE,
    type = "latex",
    include.rownames = FALSE,
    NA.string = "NA",
    # Font and linespace size
    size = "\\fontsize{5pt}{5pt}\\selectfont",
    sanitize.text.function = function(x) {
      x <- latexTranslate(x)
      x <- ifelse(grepl("something", x), paste0("\\textbf{", x, "}"), x)
      return(x)
    }
)


问:
Azure app performance
I am completely new to the Azure and cloud overall and I have been asked this question:

Imagine you are managing a web application hosted in Azure with a large user base in United States and Europe.

  In order to improve performance and user experience you want to host 2 instances of the same application one for US based users and one for Europe based users.
  Can you briefly explain how would you accomplish this with Azure services?

We cannot use two links

```<code>Http://myapp-us
Http://myapp-eu
</code>```

We have only one url;

```<code>Http://myapp
</code>```

Therefore we just cannot deploy two instances in eu region server, and american region server. Is there any way to improve performance without that?

答:
You would use the Azure Traffic Manager to control the distribution for user traffic. It directs client traffic to the appropriate instance of your app based on the proximity of the request and the health of the available instances.
Some useful links

Traffic Manager overview

You would need to use the Geographic routing method to route traffic to specific endpoints based on the request location.

A good description of how the Geographic traffic routing works.

Title: Azure app performance

Body:
I am completely new to the Azure and cloud overall and I have been asked this question:

Imagine you are managing a web application hosted in Azure with a large user base in United States and Europe.

  In order to improve performance and user experience you want to host 2 instances of the same application one for US based users and one for Europe based users.
  Can you briefly explain how would you accomplish this with Azure services?

We cannot use two links

Http://myapp-us
Http://myapp-eu

We have only one url;

Http://myapp

Therefore we just cannot deploy two instances in eu region server, and american region server. Is there any way to improve performance without that?


问:
Accessing object's property inside generic method
How can access the property of an object inside generic method?

I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.

(I also can't make for them a common interface)

```<code>public class A
{
    public int Number {get;set;}
}

List<A> listA = new List<A>{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work<A>(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}
</code>```

An update: I need also to set the property

答:
If you don't need the list - just the items, I would use a projection outside the method:

```<code>static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA.Select(a => a.Number));

}
public static void Work(IEnumerable<int> items)
{
    foreach (number item in items)
    {
        // do something with number;
    }
}
</code>```

If you need the list - a projection inside the method via a selector:

```<code>static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA, a => a.Number);

}
public static void Work<T>(IList<T> list, Func<T, int> selector)
{
    foreach (T obj in list)
    {
        int number = selector(obj);
        // do something with number;
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How can access the property of an object inside generic method?

I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.

(I also can't make for them a common interface)

public class A
{
    public int Number {get;set;}
}

List listA = new List{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}

An update: I need also to set the property

Body:
If you don't need the list - just the items, I would use a projection outside the method:

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA.Select(a => a.Number));

}
public static void Work(IEnumerable<int> items)
{
    foreach (number item in items)
    {
        // do something with number;
    }
}

If you need the list - a projection inside the method via a selector:

static void Main()
{
    List<A> listA = new List<A>{
            new A {Number =4},
            new A {Number =1},
            new A {Number =5}
    };

    Work(listA, a => a.Number);

}
public static void Work<T>(IList<T> list, Func<T, int> selector)
{
    foreach (T obj in list)
    {
        int number = selector(obj);
        // do something with number;
    }
}


问:
Tail-recursive program in prolog which outputs odd numbers in a list
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

```<code>numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).
</code>```

Query:

```<code>?- numbers(3,6, K).
   K=[3,4,5,6]
</code>```

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

答:
Another possibility is to use DCG :</p>

```<code>numbers(A,B,K) :-
    phrase(odd(A,B), K).

odd(A,B) --> {A > B, !}, [].

odd(A,B) --> {A mod2 =:= 0, !, C is A+1}, odd(C,B).
odd(A,B) --> {C is A+2}, [A], odd(C, B).
</code>```

Body:
I've written a tail-recursive predicate in Prolog which outputs the integers between A and B in a list K. I've used "reverse" to bring the numbers into the right order:

numbers(A,B,K) :- numbers(A,B,[],K).
numbers(Y,Y,X,K) :- !, reverse([Y|X],K).
numbers(A,B,X,K) :- A<B, C is A+1, numbers(C,B,[A|X],K).

Query:

?- numbers(3,6, K).
   K=[3,4,5,6]

All works fine. What I now want to do is that I only want to have odd numbers of the range between A and B in the list K. How can I do that? Thanks in advance!

Body:
Another possibility is to use DCG :

numbers(A,B,K) :-
    phrase(odd(A,B), K).

odd(A,B) --> {A > B, !}, [].

odd(A,B) --> {A mod2 =:= 0, !, C is A+1}, odd(C,B).
odd(A,B) --> {C is A+2}, [A], odd(C, B).


答:
First of all, it is not clear what you mean with a curve.
If your x/y coordinates define a polygon then, it is not a big deal.
But if they define a cubic curve like BSplines, the things get complicated.
I assume, you need the angle of the tangent to a polygon.

The easiest way to achive that, is to compute the slope for all lines through the point (0,0) and each of your coordinates.
s=(y[i]-0)/(x[i]-0) = y[i]/x[i]

Then you take the max slope whitch is the slope of the tangent. All other lines will intersect the curve because their slope is less than the tangents slope. (Draw yourself a polygon and try it. ;-) )

Now you perform the inverse tangens tan⁻¹(max slope) of the maximal slope and you'll get the angle.

Title: tangent line with python

Body:
Could some one help me to calculate tangent line angle to curve.
my curve is defined

x=0.          0.02743333  0.05486667  0.0823      0.10973333  0.13716667
  0.1646      0.19203333  0.21946667  0.2469      0.27433333  0.30176667
  0.3292      0.35663333  0.38406667  0.4115

y=
0.0,                 0.041685454222222217, 0.078408362666666648, 0.11047814399999997,
0.13820421688888887, 0.16189599999999998,  0.18186291199999996,  0.19841437155555552,
0.21185979733333329, 0.22250860799999994,  0.23067022222222222,  0.23665405866666664,
0.24076953599999995, 0.24332607288888886,  0.244633088,          0.24499999999999986

I would need to know the angle between tangent line and x-axis at 0,0

I just don't understand how to do this.


问:
Download file from NAS attached to server through http
I have many files stored in a NAS. The NAS is attached to a server as network drive (lets say, it is on Y://).

I use xampp to serve my application built in php. The application was built to serve users to download the files from NAS, directly through http instead of ftp.

So can I set the files from NAS, so it can be downloaded by using http URL, like example.com/files/the-file.zip ?

The xampp is located at C:// directory

Note: The xampp htdocs has already set to accessed by a domain. So it is not domain pointing problem

答:
You could try so through PHP:

```<code><?php
$downloadFolder = 'Y:/';

$fileName = $downloadFolder . $_GET['file'];
$sanitizedFileName = realpath($fileName);

if($fileName !== $sanitizedFileName) {
  throw new RuntimeException('Someone tried to escape');
}

// As seen in http://php.net/readfile:
if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileName));
    readfile($fileName);
    exit;
}
</code>```

Or find a way to run everything through .htaccess, but that might give you less control over security handling (probably, you don't want to serve files from other directories or other drives)

Body:
You could try so through PHP:

<?php
$downloadFolder = 'Y:/';

$fileName = $downloadFolder . $_GET['file'];
$sanitizedFileName = realpath($fileName);

if($fileName !== $sanitizedFileName) {
  throw new RuntimeException('Someone tried to escape');
}

// As seen in http://php.net/readfile:
if (file_exists($fileName)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($fileName));
    readfile($fileName);
    exit;
}

Or find a way to run everything through .htaccess, but that might give you less control over security handling (probably, you don't want to serve files from other directories or other drives)


问:
Translate from sql statement to linq statment
How can I translate

```<code>select * from employees where (emp_id=@emp or @emp is null) and (dep_id=@dep or @dep is null)
</code>```

to a LINQ statment?

答: Sorry, no way of doing this. The LINQ providers are designed to take code and translate to SQL statements, not the other way around.</p>

Body:
How can I translate

select * from employees where (emp_id=@emp or @emp is null) and (dep_id=@dep or @dep is null)

to a LINQ statment?


问:
Segfault when calling, but not jumping to, address in rax
I'm working with an assembler-like API (it's not really an assembler, but it can emit machine code) that I am debugging and toying with. It's specifically for System V x86_64 ABI, so I'm only going to be talking about SysV calling conventions and such.

For some reason, when I emit some contrived code like this, for testing purposes

```<code>builder.emit_sub(rsp, 1);
builder.emit_movq_vr(reinterpret_cast<uint64_t>(&hello_world), rax);
builder.emit_call(rax);
builder.emit_add(rsp, 1);
builder.emit_ret();
</code>```

a segmentation fault occurs at the call (when it is run, not when being assembled), and yet

```<code>builder.emit_movq_vr(reinterpret_cast<uint64_t>(&hello_world), rax);
builder.emit_jmp(rax);
</code>```

succeeds just fine. The point of failure seems to be at the call instruction, but I don't know what is bugging out the pseudo-assembler. It might be emitting the wrong opcode operands or something, but I'm not sure. The raw emitted machine code looks something like this for the buggy code, alongside the opcode that it is supposed to represent, as printed by some simple debug statements

```<code>sub    48 81 EC 01 00 00 00
movqvr 48 B8 63 80 AA 01 01 00 00 00
call   FF D0
add    48 81 C4 01 00 00 00
ret    C3
</code>```

Remark: movqvr is not a real instruction [mnemonic]; the vr at the end is just a debug annotation to me saying it's a "move imm64 to reg" kind of instruction.

Remark: The sub and add are to align the stack on a 16-byte boundary, which I believe is a necessity in this ABI. They could've been better written as a push rax and a pop rax (or pop rcx if rax is needed for a return value), but ignore that, unless it is this that is messing up the call (e.g. if rsp is not being modified correctly).

答:
Yes, in the System V ABI, the stack is aligned to a 16-byte boundary before every call instruction.  Thus, on function entry it takes another 8 bytes (not 1) to reach the next 16-byte boundary.  Remember that in C, pointer differences are scaled by sizeof(type), but in asm they aren't.

And yes, push rax / pop rcx would be a good choice, and is what clang / LLVM does if it doesn't already need to push an odd number of call-preserved registers or reserve any extra stack space.  If you do need to reserve any stack space for locals, use an offset that will leave rsp 16-byte aligned.

BTW, you could save code size by using the sub r/m64, imm8 encoding when the immediate fits in a sign-extended 8-bit value (i.e. if ((int8_t)imm == imm)).  Also, if you ever need to add / subtract +128, note that -128 fits in an imm8, so you can add rsp, -128 (e.g. after an odd number of push instructions).

If you know the address where your code will run from, you should use the call rel32 encoding, rather than a register-indirect call.  But you're right that jumping to an arbitrary 64-bit address requires this mov r64, imm64 sequence, not a direct call.

Did you use a debugger to find out where hello_world crashed?  Maybe if it calls printf (rather than puts), it forgot to zero al (with xor eax,eax) to indicate no FP args in XMM registers, so maybe printf used some 16-byte SSE alignement-required stores to the stack?

Having RSP not even qword-aligned is very bad, but I wouldn't expect it to have crashed anything that would crash with it 8-byte aligned (but not 16).

Body:
I'm working with an assembler-like API (it's not really an assembler, but it can emit machine code) that I am debugging and toying with. It's specifically for System V x86_64 ABI, so I'm only going to be talking about SysV calling conventions and such.

For some reason, when I emit some contrived code like this, for testing purposes

builder.emit_sub(rsp, 1);
builder.emit_movq_vr(reinterpret_cast<uint64_t>(&hello_world), rax);
builder.emit_call(rax);
builder.emit_add(rsp, 1);
builder.emit_ret();

a segmentation fault occurs at the call (when it is run, not when being assembled), and yet

builder.emit_movq_vr(reinterpret_cast<uint64_t>(&hello_world), rax);
builder.emit_jmp(rax);

succeeds just fine. The point of failure seems to be at the call instruction, but I don't know what is bugging out the pseudo-assembler. It might be emitting the wrong opcode operands or something, but I'm not sure. The raw emitted machine code looks something like this for the buggy code, alongside the opcode that it is supposed to represent, as printed by some simple debug statements

sub    48 81 EC 01 00 00 00
movqvr 48 B8 63 80 AA 01 01 00 00 00
call   FF D0
add    48 81 C4 01 00 00 00
ret    C3

Remark: movqvr is not a real instruction [mnemonic]; the vr at the end is just a debug annotation to me saying it's a "move imm64 to reg" kind of instruction.

Remark: The sub and add are to align the stack on a 16-byte boundary, which I believe is a necessity in this ABI. They could've been better written as a push rax and a pop rax (or pop rcx if rax is needed for a return value), but ignore that, unless it is this that is messing up the call (e.g. if rsp is not being modified correctly).


问:
How to disable and put limits on checkboxes with radio button (Javascript)
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

```<code><label>
    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive
    </label>
    <label>
    <input type="radio" value="package1" id="package1" name="packages"> Package 1
    </label>
    <label>
    <input type="radio" value="package2" id="package2" name="packages"> Package 2
    </label>
<br />
    <label><h2>Rice </h2></label>
    <br />
    <a style="color: darkred;">2 Choices</a>
    <br />
    <div class="checkboxfood">
      <label>
      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Buttered Rice
      </label>
      <label>
      <input type="checkbox" class="food" value=""> Garlic Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Kimchi Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Adobo Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Yang Chow Rice
      </label>
    <br />
    <label>
      <input type="checkbox" class="food" value=""> Shanghai Rice
      </label>
    <label>
      <input type="checkbox" class="food" value=""> Bagoong Rice
      </label>
    </div>
</code>```

I've tried this javascript:

```<code>$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});
</code>```

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

```<code>var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});
</code>```

Which limits my checkboxes but isn't responsive to my radio buttons.

答:
Incase you are familiar with JQuery use this
To disable the checkboxes when you choose non-exclusive

```<code>$('input[type=radio]').change(function(){
  if($(this).attr('id') == 'non-exclusive'){
    $("input[type=checkbox]").attr("disabled","disabled");
  } else {
    $("input[type=checkbox]").removeAttr("disabled");
  }
 });
</code>```

To Limit the checkboxes to 2 when you choose package1

```<code>$('input[type=checkbox]').change(function(){
   //get the checked radio id
   var radio = $('input[type=radio]:checked').attr('id');

   if(radio == 'package1'){
      //check the number of the checked checkboxes
      if($('input[type=checkbox]:checked').length > 2){
         //do what you want here  ex: display alert message
         this.checked=false;
         return false;
      }//end if
    }//end if
});
</code>```

Of course you have to write more code to uncheck all boxes or implement your logic if the user choose package1 after he selects more than two checkboxes when package2 was selected before

Body:
I have a radio-type button and a few checkboxes. I basically want to disable the checkboxes when I choose Non-Exclusive then limit the checkboxes to 2 if I choose Package 1.

Here's my html code:

    <input type="radio" value="non-exclusive" id="non-exclusive" name="packages"> Non-Exclusive

    <input type="radio" value="package1" id="package1" name="packages"> Package 1

    <input type="radio" value="package2" id="package2" name="packages"> Package 2

Rice

    2 Choices

      <input type="checkbox" class="food" value=""> Plain Rice (Mandatory)

      <input type="checkbox" class="food" value=""> Buttered Rice

      <input type="checkbox" class="food" value=""> Garlic Rice

      <input type="checkbox" class="food" value=""> Kimchi Rice

      <input type="checkbox" class="food" value=""> Adobo Rice

      <input type="checkbox" class="food" value=""> Yang Chow Rice

      <input type="checkbox" class="food" value=""> Shanghai Rice

      <input type="checkbox" class="food" value=""> Bagoong Rice

I've tried this javascript:

$('#package1').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1), :checkbox:eq(2), :checkbox:eq(3), :checkbox:eq(4), :checkbox:eq(5)\n\
, :checkbox:eq(6), :checkbox:eq(7), :checkbox:eq(8), :checkbox:eq(9), :checkbox:eq(10), :checkbox:eq(11), :checkbox:eq(12)\n\
, :checkbox:eq(13), :checkbox:eq(14), :checkbox:eq(15)').prop('disabled', false);

});

$('#package2').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
$(':checkbox:eq(0), :checkbox:eq(1)').prop('disabled', false);
});

$('#non-exclusive').on('change', function() {
$('.checkBoxes :checkbox').prop('disabled', true);
});

It enables checkboxes but it won't limit it. Also if I press back to Non-Exlusive the checkboxes doesn't go back to being "disabled".

I've also tried this code:

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
   this.checked = false;
}
});

Which limits my checkboxes but isn't responsive to my radio buttons.

Body:
Incase you are familiar with JQuery use this
To disable the checkboxes when you choose non-exclusive

$('input[type=radio]').change(function(){
  if($(this).attr('id') == 'non-exclusive'){
    $("input[type=checkbox]").attr("disabled","disabled");
  } else {
    $("input[type=checkbox]").removeAttr("disabled");
  }
 });

To Limit the checkboxes to 2 when you choose package1

$('input[type=checkbox]').change(function(){
   //get the checked radio id
   var radio = $('input[type=radio]:checked').attr('id');

   if(radio == 'package1'){
      //check the number of the checked checkboxes
      if($('input[type=checkbox]:checked').length > 2){
         //do what you want here  ex: display alert message
         this.checked=false;
         return false;
      }//end if
    }//end if
});

Of course you have to write more code to uncheck all boxes or implement your logic if the user choose package1 after he selects more than two checkboxes when package2 was selected before


问:
Is MeteorJS still en vogue to learn?

I am about to learn my next programming language. I came across MeteorJS and am curious if it is still a good idea to learn more about it, is it? </p>

答:
in my opinion Meteor is somewhat underestimated. In combination with React you can create great web applications.
I can only recommend learning it.</p>

Title: Is MeteorJS still en vogue to learn?


问:
Required <Object> and found <Object>?
```<code>class TaskRepo(taskData: TaskData) {

companion object {
    private val repoByTask: LRUMap<String, OrderFormRepo> = LRUMap(2, 10);

     fun getInstance(taskData: TaskData): OrderFormRepo {
        if (notFoundObject(taskData.taskId)) {
            repoByTask[taskData.taskId] = OrderFormRepo(taskData);
        }
        return repoByTask[taskData.taskId];//PROBLEM HERE
    }

    private fun notFoundObject(taskId: String): Boolean {
        if (repoByTask.containsKey(taskId) && repoByTask[taskId] != null) {
            return false
        }
        return true
    }
}
</code>```

}

in getInstance method of companion object I am getting compile time error:
Required TaskRepo and found TaskRepo?

答:
LRUMap implements the Map interface, the get method of which in Kotlin returns a V?, as it returns null when no element is present for the given key.

As you've already done the checking beforehand in this case, you can be reasonably sure (assuming no other threads are modifying the map at the same time) that this value won't be null, and force a conversion to the non-nullable type with the !! operator:

```<code>return repoByTask[taskData.taskId]!!
</code>```

For other ways to handle a missing key when reading from a Map, see the getOrDefault and getOrElse methods.

Title: Required <Object> and found <Object>?

Body:
class TaskRepo(taskData: TaskData) {

companion object {
    private val repoByTask: LRUMap<String, OrderFormRepo> = LRUMap(2, 10);

     fun getInstance(taskData: TaskData): OrderFormRepo {
        if (notFoundObject(taskData.taskId)) {
            repoByTask[taskData.taskId] = OrderFormRepo(taskData);
        }
        return repoByTask[taskData.taskId];//PROBLEM HERE
    }

    private fun notFoundObject(taskId: String): Boolean {
        if (repoByTask.containsKey(taskId) && repoByTask[taskId] != null) {
            return false
        }
        return true
    }
}

}

in getInstance method of companion object I am getting compile time error:
Required TaskRepo and found TaskRepo?

Body:
LRUMap implements the Map interface, the get method of which in Kotlin returns a V?, as it returns null when no element is present for the given key.

As you've already done the checking beforehand in this case, you can be reasonably sure (assuming no other threads are modifying the map at the same time) that this value won't be null, and force a conversion to the non-nullable type with the !! operator:

return repoByTask[taskData.taskId]!!

For other ways to handle a missing key when reading from a Map, see the getOrDefault and getOrElse methods.


问:
Using typedef keyword in c
I was going through one of the lecture slide taught in the class which included a typedef keyword in it. As opposed to normal use of typedef keyword where we usually put a alias for particular data, there was no alias put up for that example. Following is the example:See the typedef in the slide

Is the use of typedef correct, or am I interpreting differently?

答:
It is a function pointer. And it is perfectly valid syntax.

Ptr is declared as a pointer to a function where the function takes two int arguments and return an int. Here you can use Ptr as the alias to the typedefed type.

Title: Using typedef keyword in c


问:
Where is the PHP folder on XAMPP for MAC OS 10.12 system?
I've been tried to export a custom PATH on ~/bash_profile file by adding:

```<code>export XAMPP_HOME=/Applications/XAMPP
export PATH=${XAMPP_HOME}/bin:${PATH}
export PATH
</code>```

But this doesn't work because the PHP path is incorrect.

Furthermore, I also ran phpinfo() and get the Configuration File but the path is /opt/lampp/etc that doesn't exist.

Therefore, I just need to change the default PHP CLI from version 5.5.6 to 7.1.11.

Can someone here please give me a help!!!?

答:
After hours searching on Google, I've reached at this video that pointed me to the right point: https://www.youtube.com/watch?v=vT5luUaAcQ8

Yes! Now I can change my PHP CLI version to any other since 5.3.

Here are the steps from the video:

To get started, go to https://php-osx.liip.ch/

Scroll down to the One Line Installation section and copy the command for the version of PHP that you want to install

Open up a Terminal window

Paste the command and press Enter

The PHP OSX installer will take care of loading the new version of PHP into the pre-installed copy of Apache

If you want to run the new version of PHP from the command line, you’ll need to update your PATH

To do that, you’ll need to add a line to your .bash_profile file.

Type vim ~/.bash_profile and press Enter

Press Shift-G to jump to the end of the file

Press i to enter Insert mode

Type export PATH=/usr/local/php5/bin:$PATH

Press Escape to exit Insert mode

Type :wq to save and quit

Now you can close your Terminal window and open a new window to use the new path

Body:
I've been tried to export a custom PATH on ~/bash_profile file by adding:

export XAMPP_HOME=/Applications/XAMPP
export PATH=${XAMPP_HOME}/bin:${PATH}
export PATH

But this doesn't work because the PHP path is incorrect.

Furthermore, I also ran phpinfo() and get the Configuration File but the path is /opt/lampp/etc that doesn't exist.

Therefore, I just need to change the default PHP CLI from version 5.5.6 to 7.1.11.

Can someone here please give me a help!!!?


问:
AJAX returns response but does not attach the HTML code from response to div
html:

```<code><form method="POST">
<input type="text" name="unu" id="unu">
<input type="text" name="doi" id="doi">
<button type="button" onclick="check()">OK</button>
</form>
<div id="show_panels"></div>
</code>```

jquery:

```<code>function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });

  var result_input = document.getElementById('result');
  console.log(result_input.value);
}
</code>```

php:

```<code><?php
$var_unu = $_POST['unu'];
$var_doi = $_POST['doi'];
$rezultat = $var_unu + $var_doi;
?>
<input type='text' value='<?php echo $rezultat ?>' id='result'/>
</code>```

As you can see, I am trying to get in my console (for testing), the value from returned input with id result, but console return:

Uncaught TypeError: Cannot read property 'value' of null.

In page source I don`t have the htmlcode for my ajaxreturned input.
What I do wrong?

Browser view:

View page source:

答:
Because the HTML input result exists after the success callback is executed.

Try with this:

```<code>function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);

      var result_input = document.getElementById('result');
      console.log(result_input.value);
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });
}
</code>```

Thanks @Titus for the correction.

Update:

If you need to reuse the returned value you need some changes:

html: Add the HTML input result in the form.

```<code><form method="POST">
  <input type="text" name="unu" id="unu">
  <input type="text" name="doi" id="doi">
  <button type="button" onclick="check()">OK</button>
  <input type="text" value="" id="result" />
</form>
<div id="show_panels"></div>
</code>```

jquery: Prints the returned value in the HTML input result.

```<code>function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);

      document.getElementById('result').value = result;
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });
}
</code>```

php: In the PHP file, just return the $rezultat by using echo.

```<code><?php
$var_unu = $_POST['unu'];
$var_doi = $_POST['doi'];
$rezultat = $var_unu + $var_doi;
echo $rezultat;
?>
</code>```

Body:
html:

<form method="POST">
<input type="text" name="unu" id="unu">
<input type="text" name="doi" id="doi">
<button type="button" onclick="check()">OK</button>
</form>

jquery:

function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });

  var result_input = document.getElementById('result');
  console.log(result_input.value);
}

php:

<?php
$var_unu = $_POST['unu'];
$var_doi = $_POST['doi'];
$rezultat = $var_unu + $var_doi;
?>
<input type='text' value='<?php echo $rezultat ?>' id='result'/>

As you can see, I am trying to get in my console (for testing), the value from returned input with id result, but console return:

Uncaught TypeError: Cannot read property 'value' of null.

In page source I don`t have the htmlcode for my ajaxreturned input.
What I do wrong?

Browser view:

View page source:

Body:
Because the HTML input result exists after the success callback is executed.

Try with this:

function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);

      var result_input = document.getElementById('result');
      console.log(result_input.value);
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });
}

Thanks @Titus for the correction.

Update:

If you need to reuse the returned value you need some changes:

html: Add the HTML input result in the form.

<form method="POST">
  <input type="text" name="unu" id="unu">
  <input type="text" name="doi" id="doi">
  <button type="button" onclick="check()">OK</button>
  <input type="text" value="" id="result" />
</form>
<div id="show_panels"></div>

jquery: Prints the returned value in the HTML input result.

function check() {
  $.ajax({
    type: "POST",
    url: "2.php",
    data: $("form").serialize(),
    success: function(result) {
      $('#show_panels').html(result);

      document.getElementById('result').value = result;
    },
    error: function(result) {
      console.log("Eroare:");
      console.log(result);
    }
  });
}

php: In the PHP file, just return the $rezultat by using echo.

<?php
$var_unu = $_POST['unu'];
$var_doi = $_POST['doi'];
$rezultat = $var_unu + $var_doi;
echo $rezultat;
?>


问:
What is a possible alternative to these static variables?
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

```<code>class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}
</code>```

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).

答:
Now the first thing about statics being evil is IMHO not that the static function, singleton classes themselves are evil. But if you wanted to create some automated tests for classes that use your static context, that would be virtually impossible.

So if you want to complete disregard any hopes of creating automated tests, then go ahead, make the class static with static data.

Should you however want to keep this option open, then I would suggest that you look into stuff like IOC containers (structuremap being my favourite). You can have a (ahem) static IOC container which you use to create instances of your dependencies. The dependencies would take an instance of the, e.g. GuiEngine, as a constructor argument. And your IOC container will make sure that all dependencies receive the same instance, assuming that you've configured it correctly.

As Tim points out, extracting an interface for your engine classes would be a good idea, as it will allow you to create alternate implementations for said tests, e.g. mock, stub, spy, dummy objects etc.

Body:
I have created a simple GUI engine which I plan to use in a game.
The issue I am having is understanding how to instance a class that will be accessed in multiple stack frames without being static (people have made it quite clear that static variables are just evil).

I have a code example below:

class MyGame
{
    class InputEngine
    {
        internal void DoInput()
        {
            if (Keys["F1"].IsPressed)
            {
                // Create a window using the gui engine
            }
        }
    }
    class GuiEngine
    {
        internal void Update() { }
        internal void Draw() { }
    }
    private GuiEngine engine;
    private InputEngine input;

    internal MyGame()
    {
        this.input = new InputEngine();
        this.engine = new GuiEngine();
    }

    internal void Update()
    {
        this.engine.Update();
        this.input.DoInput();
    }
    internal void Draw()
    {
        this.engine.Draw();
    }
}

How can I access the gui engine instance not only from the input example, but from tens of other places without making it static. (I would really rather not pass it as a parameter).


问:
Default constructor setting random value
I'm writing a simple class for atoms objects. Here's what I've written so far:

```<code>#include <random>

class Atom {
    int mSpin;

public:
    Atom();
    Atom(int);
    Atom(const Atom&);
    ~Atom() {}

    Atom& operator= (const Atom &atom);
};
</code>```

And the .cpp file:

```<code>include "Atom.h"

Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}

/*  OPERATORS  */

Atom& Atom::operator= (const Atom &copy) {
    mSpin = copy.mSpin;
    return *this;
}
</code>```

I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here.
Usually I'd do something like this:

```<code>#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);
</code>```

but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?

Hope the question is clear.

答:
You should make the random device and generator static members of the Atom class. This way, like global variables, they are initialized only once for the duration of your program.</p>

```<code>class Atom {
  // declaration
  static std::random_device rd;
  static std::mt13397 gen;

  ...
};

// definition - this must be in Atom.cpp
std::random_device Atom::rd;
std::mt13397 Atom::gen(Atom::rd());
</code>```

Body:
I'm writing a simple class for atoms objects. Here's what I've written so far:

#include <random>

class Atom {
    int mSpin;

public:
    Atom();
    Atom(int);
    Atom(const Atom&);
    ~Atom() {}

    Atom& operator= (const Atom &atom);
};

And the .cpp file:

include "Atom.h"

Atom::Atom() {
}
Atom::Atom(int spin) : mSpin(spin) {}
Atom::Atom(const Atom& copy) : mSpin(copy.mSpin) {}

/*  OPERATORS  */

Atom& Atom::operator= (const Atom &copy) {
    mSpin = copy.mSpin;
    return *this;
}

I want to make the default constructor such that when I'm creating an object, mSpin will be randomly set as 1 or -1. I understand how to do it with rand() but rand() is not very good and I'd like to use . I'm kind of confused by the use of , even after reading the documentation and other answers on here.
Usually I'd do something like this:

#include <random>
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,1);
int random_number = dis(gen);

but I'm not sure how to use it inside a class. I tried placing it inside the default constructor but I think it's wrong because it would seed each time I create an atom?

Hope the question is clear.

Body:
You should make the random device and generator static members of the Atom class. This way, like global variables, they are initialized only once for the duration of your program.

class Atom {
  // declaration
  static std::random_device rd;
  static std::mt13397 gen;

  ...
};

// definition - this must be in Atom.cpp
std::random_device Atom::rd;
std::mt13397 Atom::gen(Atom::rd());


问:
SQLite many to many selection
I'm trying to select data from my android sqlite database. I have 3 tables - table Players (list of all players), table Matches (list of all matches) and table PlayersMatches (list of players in each match, created as many to many relationship). I want to write SELECT command, which returns all matches, where played two players together. Here is a little example:

```<code>Table PLAYERS
-------------
id    name
1     John
2     Jamie
3     Joe

Table MATCHES
-------------
id    date
1     17/12/01
2     17/12/02
3     17/12/03

Table PLAYERS_MATCHES
---------------------
id    id_Player    id_Match
1     1            1
2     2            1
3     1            2
4     3            2
5     1            3
6     2            3
</code>```

So, I want to write select command, which return all matches, where played John (1) and Jamie (2). Result should be:

```<code>SELECT RETURNED
-------------
id_match
1
3
</code>```

Note, that there can be more than 2 players in each match.

It is possible to write a single sql command or I should do it in different way? (for example select command for the first player, another for the second player and programatically in Android filter theese matches).

答:
It is perfectly OK to do it in single sql. This is the kind of queries SQL was built for.

You do a self join on PlayerMatches table like:

```<code>SELECT distinct M1.id_match
From PLAYERS_MATCHES M1 CROSS JOIN PLAYERS_MATCHES M2
WHERE M1.id_match=M2.id_match AND M1.id_player=1 AND M2.id_player=2
</code>```

Verification:

```<code>sqlite> select * from matches;
id          p           m
----------  ----------  ----------
1           1           1
2           2           1
3           1           2
4           3           2
5           1           3
6           2           3
sqlite>

sqlite> select distinct m1.m from matches m1 cross join matches m2
   ...> where m1.m=m2.m and m1.p=1 and m2.p=2;
m
----------
1
3
sqlite>
</code>```

Title: SQLite many to many selection

Body:
I'm trying to select data from my android sqlite database. I have 3 tables - table Players (list of all players), table Matches (list of all matches) and table PlayersMatches (list of players in each match, created as many to many relationship). I want to write SELECT command, which returns all matches, where played two players together. Here is a little example:

Table PLAYERS
-------------
id    name
1     John
2     Jamie
3     Joe

Table MATCHES
-------------
id    date
1     17/12/01
2     17/12/02
3     17/12/03

Table PLAYERS_MATCHES
---------------------
id    id_Player    id_Match
1     1            1
2     2            1
3     1            2
4     3            2
5     1            3
6     2            3

So, I want to write select command, which return all matches, where played John (1) and Jamie (2). Result should be:

SELECT RETURNED
-------------
id_match
1
3

Note, that there can be more than 2 players in each match.

It is possible to write a single sql command or I should do it in different way? (for example select command for the first player, another for the second player and programatically in Android filter theese matches).

Body:
It is perfectly OK to do it in single sql. This is the kind of queries SQL was built for.

You do a self join on PlayerMatches table like:

SELECT distinct M1.id_match
From PLAYERS_MATCHES M1 CROSS JOIN PLAYERS_MATCHES M2
WHERE M1.id_match=M2.id_match AND M1.id_player=1 AND M2.id_player=2

Verification:

sqlite> select * from matches;
id          p           m
----------  ----------  ----------
1           1           1
2           2           1
3           1           2
4           3           2
5           1           3
6           2           3
sqlite>

sqlite> select distinct m1.m from matches m1 cross join matches m2
   ...> where m1.m=m2.m and m1.p=1 and m2.p=2;
m
----------
1
3
sqlite>


问:
Python: How to efficiently count the number of "1"s in the binary representation of 1 to n numbers?
E.g. For the input 5, the output should be 7.
(bin(1) = 1, bin(2) = 10 ... bin(5) = 101) --> 1 + 1 + 2 + 1 + 2 = 7

Here's what I've tried, but it isn't a very efficient algorithm, considering that I iterate the loop once for each integer. My code (Python 3):

```<code>i = int(input())
a = 0
for b in range(i+1):
  a = a + bin(b).count("1")
print(a)
</code>```

Thank you!

答:
gmpy2, due to Alex Martella et al, seems to perform better, at least on my Win10 machine.

```<code>from time import time
import gmpy2

def onecount(n):
    if n == 0:
        return 0
    if n % 2 == 0:
        m = n/2
        return onecount(m) + onecount(m-1) + m
    m = (n-1)/2
    return 2*onecount(m)+m+1

N = 10000

initial = time()
for _ in range(N):
    for i in range(30):
        onecount(i)
print (time()-initial)

initial = time()
for _ in range(N):
    total = 0
    for i in range(30):
        total+=gmpy2.popcount(i)
print (time()-initial)
</code>```

Here's the output:

```<code>1.7816979885101318
0.07404899597167969
</code>```

If you want a list, and you're using >Py3.2:

```<code>>>> from itertools import accumulate
>>> result = list(accumulate([gmpy2.popcount(_) for _ in range(30)]))
>>> result
[0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71]
</code>```

Body:
E.g. For the input 5, the output should be 7.
(bin(1) = 1, bin(2) = 10 ... bin(5) = 101) --> 1 + 1 + 2 + 1 + 2 = 7

Here's what I've tried, but it isn't a very efficient algorithm, considering that I iterate the loop once for each integer. My code (Python 3):

i = int(input())
a = 0
for b in range(i+1):
  a = a + bin(b).count("1")
print(a)

Thank you!

Body:
gmpy2, due to Alex Martella et al, seems to perform better, at least on my Win10 machine.

from time import time
import gmpy2

def onecount(n):
    if n == 0:
        return 0
    if n % 2 == 0:
        m = n/2
        return onecount(m) + onecount(m-1) + m
    m = (n-1)/2
    return 2*onecount(m)+m+1

N = 10000

initial = time()
for _ in range(N):
    for i in range(30):
        onecount(i)
print (time()-initial)

initial = time()
for _ in range(N):
    total = 0
    for i in range(30):
        total+=gmpy2.popcount(i)
print (time()-initial)

Here's the output:

1.7816979885101318
0.07404899597167969

If you want a list, and you're using >Py3.2:

>>> from itertools import accumulate
>>> result = list(accumulate([gmpy2.popcount(_) for _ in range(30)]))
>>> result
[0, 1, 2, 4, 5, 7, 9, 12, 13, 15, 17, 20, 22, 25, 28, 32, 33, 35, 37, 40, 42, 45, 48, 52, 54, 57, 60, 64, 67, 71]


问:
error when adding a repository to install programs on ubuntu
I am trying to install the Atom to be able to develop my sites, but this is having some conflict at the moment that I try to add the repository. The following output is displayed:

```<code>    marcius@Marcius-PC:~$ sudo add-apt-repository ppa:webupd8team/atom
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 335, in get_ppa_info
    ret = get_ppa_info_from_lp(user, ppa)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 92, in get_ppa_info_from_lp
    return get_info_from_lp(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 88, in get_info_from_lp
    return _get_https_content_py3(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 110, in _get_https_content_py3
    lp_page = urllib.request.urlopen(request, cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.5/urllib/request.py", line 153, in urlopen
    capath=capath)
  File "/usr/lib/python3.5/ssl.py", line 470, in create_default_context
    context.load_verify_locations(cafile, capath, cadata)
ssl.SSLError: unknown error (_ssl.c:3053)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 122, in <module>
    shortcut = shortcut_handler(line)
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 864, in shortcut_handler
    ret = factory(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 407, in shortcut_handler
    return PPAShortcutHandler(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 364, in __init__
    info = get_ppa_info(self.shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 347, in get_ppa_info
    _get_suggested_ppa_message(user, ppa))
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 304, in _get_suggested_ppa_message
    lp_user = get_info_from_lp(LAUNCHPAD_USER_API % user)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 88, in get_info_from_lp
    return _get_https_content_py3(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 110, in _get_https_content_py3
    lp_page = urllib.request.urlopen(request, cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.5/urllib/request.py", line 153, in urlopen
    capath=capath)
  File "/usr/lib/python3.5/ssl.py", line 470, in create_default_context
    context.load_verify_locations(cafile, capath, cadata)
ssl.SSLError: unknown error (_ssl.c:3053)
marcius@Marcius-PC:~$
</code>```

It seems to me that some problem with the dependencies of python, someone knows exactly what it is, and better how to correct?

答:
Removing all certs in /usr/share/ca-certificates and then reinstalling worked for me.

Try this:

```<code>sudo rm -rf /usr/share/ca-certificates

sudo apt-get --reinstall install ca-certificates
</code>```

Source: https://ubuntuforums.org/showthread.php?t=2113326

Body:
I am trying to install the Atom to be able to develop my sites, but this is having some conflict at the moment that I try to add the repository. The following output is displayed:

    marcius@Marcius-PC:~$ sudo add-apt-repository ppa:webupd8team/atom
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 335, in get_ppa_info
    ret = get_ppa_info_from_lp(user, ppa)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 92, in get_ppa_info_from_lp
    return get_info_from_lp(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 88, in get_info_from_lp
    return _get_https_content_py3(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 110, in _get_https_content_py3
    lp_page = urllib.request.urlopen(request, cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.5/urllib/request.py", line 153, in urlopen
    capath=capath)
  File "/usr/lib/python3.5/ssl.py", line 470, in create_default_context
    context.load_verify_locations(cafile, capath, cadata)
ssl.SSLError: unknown error (_ssl.c:3053)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 122, in <module>
    shortcut = shortcut_handler(line)
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 864, in shortcut_handler
    ret = factory(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 407, in shortcut_handler
    return PPAShortcutHandler(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 364, in __init__
    info = get_ppa_info(self.shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 347, in get_ppa_info
    _get_suggested_ppa_message(user, ppa))
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 304, in _get_suggested_ppa_message
    lp_user = get_info_from_lp(LAUNCHPAD_USER_API % user)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 88, in get_info_from_lp
    return _get_https_content_py3(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 110, in _get_https_content_py3
    lp_page = urllib.request.urlopen(request, cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.5/urllib/request.py", line 153, in urlopen
    capath=capath)
  File "/usr/lib/python3.5/ssl.py", line 470, in create_default_context
    context.load_verify_locations(cafile, capath, cadata)
ssl.SSLError: unknown error (_ssl.c:3053)
marcius@Marcius-PC:~$

It seems to me that some problem with the dependencies of python, someone knows exactly what it is, and better how to correct?

Body:
Removing all certs in /usr/share/ca-certificates and then reinstalling worked for me.

Try this:

sudo rm -rf /usr/share/ca-certificates

sudo apt-get --reinstall install ca-certificates

Source: https://ubuntuforums.org/showthread.php?t=2113326


问:
Javascript, what are (n) and the square brackets doing in this function?
Just got a couple of questions to help me understand this script, as where it is OP, the explanation is pretty thin.

1) (n) is passed into the functions plusDivs and showDivs. How does this (n) work? Is it just an empty container to store the data in the function.

2) With this line x[i].style.display="none"; and x[slideIndex-1].style.display="block"; with the square brackets used, is the code inside the square brackets executed first? What are the square brackets doing or called in this instance.

Although functions are explained in online tutorials in a basic way, some of this information I'm asking is quite hard to find out so would appreciate some help .

Thanks Emma.

JS:

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    if (n > x.length) { slideIndex = 1 }
    if (n < 1) { slideIndex = x.length };
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    x[slideIndex-1].style.display = "block";
}
</code>```

HTML:

```<code><button style="border:none; font-size: 22px;background-color:black; color:white; position:fixed; top:30%; left:5%" onclick="plusDivs(-1)">❮</button>
<button id="rightbutton" style="border:none; font-size: 22px;background-color:black; color:white;position:fixed; top:30%; right:5%" onclick="plusDivs(1)">❯</button>
</code>```

答:
In JavaScript, functions are portions of code that take caller-supplied information called "arguments" and use them in the code. The syntax of a function is

```<code>function (x, y) {
    return x + y;
}
</code>```

If the above function were to be called:

```<code>(function (x, y) {
    return x + y;
})(1, 1)
</code>```

The result would be 2.

The [brackets] are subscript operators. In the context of arrays, they take a numeric index and return the element at that location:

```<code>[1, 2, 3][0] === 1
</code>```

In the context of objects, they take a key and return the mapped value:

```<code>(({
     'foo' : 'bar'
})['foo']) === 'bar'
</code>```

In your case, the function getElementsByClassName returns an array of elements, so the brackets denote array subscription and are used to retrieve an element of the array.

Body:
Just got a couple of questions to help me understand this script, as where it is OP, the explanation is pretty thin.

1) (n) is passed into the functions plusDivs and showDivs. How does this (n) work? Is it just an empty container to store the data in the function.

2) With this line x[i].style.display="none"; and x[slideIndex-1].style.display="block"; with the square brackets used, is the code inside the square brackets executed first? What are the square brackets doing or called in this instance.

Although functions are explained in online tutorials in a basic way, some of this information I'm asking is quite hard to find out so would appreciate some help .

Thanks Emma.

JS:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
    showDivs(slideIndex += n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    if (n > x.length) { slideIndex = 1 }
    if (n < 1) { slideIndex = x.length };
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    x[slideIndex-1].style.display = "block";
}

HTML:

<button style="border:none; font-size: 22px;background-color:black; color:white; position:fixed; top:30%; left:5%" onclick="plusDivs(-1)">❮</button>
<button id="rightbutton" style="border:none; font-size: 22px;background-color:black; color:white;position:fixed; top:30%; right:5%" onclick="plusDivs(1)">❯</button>

Body:
In JavaScript, functions are portions of code that take caller-supplied information called "arguments" and use them in the code. The syntax of a function is

function (x, y) {
    return x + y;
}

If the above function were to be called:

(function (x, y) {
    return x + y;
})(1, 1)

The result would be 2.

The [brackets] are subscript operators. In the context of arrays, they take a numeric index and return the element at that location:

[1, 2, 3][0] === 1

In the context of objects, they take a key and return the mapped value:

(({
     'foo' : 'bar'
})['foo']) === 'bar'

In your case, the function getElementsByClassName returns an array of elements, so the brackets denote array subscription and are used to retrieve an element of the array.


答:
1) (n) is passed into the functions plusDivs and showDivs. How does this (n) work? Is it just an empty container to store the data in the function.

an integer passed into plusDivs() function, its mean by pressing buttons you pass "-1 and +1" integer as argument to your function and in your function it will add/contact it from you current slide index that will cause your slider moves to forward(next slide) or backward(prev slide)

2) With this line x[i].style.display="none"; and x[slideIndex-1].style.display="block"; with the square brackets used, is the code inside the square brackets executed first? What are the square brackets doing or called in this instance.

As i mentioned in comments they are for finding nth element inside an array. at first of your code you find all slides and cached them into a variable, so when you need to find nth slide youmost use something like this slide[slide number 2] (this is just pseudo code)

Title: Javascript, what are (n) and the square brackets doing in this function?