问:
Questions about registers in Assembly Language
For code like:

```<code>;; Data definitions go here
.section .data
n1:     .byte 12
n2:     .byte 34
n3:     .byte 21
n4:     .byte 10
result: .space 1

;; Code definition goes here
.section .text
    .global main

main:
    push R17

    ldi R26, lo8(n1)        ; Loading the address of n1 in X
        ldi R27, hi8(n1)

        ld R24, X+              ; Load n1 in R24 and increase address
        ld R17, X+              ; Load n2 in R17 and increase address
        add R24, R17            ; R4 = n1 + n2
        ld R17, X+              ; Load n3 in R17 and increase address
        add R24, R17            ; R4 = n1 + n2 + n3
        ld R17, X+              ; Load n4 in R17 and increase address
        add R24, R17            ; Final result in R24 = n1 + n2 + n3 + n4

        ;; At this point R27:R26 contains the address of result
        st X, R24               ; Store the result

    ;; The result of this function is returned in R25:R24
        clr R25         ; So that R25:R24 has the result in 16 bits.

    pop R17
    ret
.end
</code>```

1) Would the result be the same even if we use R18 instead of R17 and remove popping and pushing R17?

2) Also, just doing clr R25 concatenate R25 to R24? (hence make R25:R24?)

3) Moreover, when performing an operation of instruction like:

ADD R17, R18, is ADD an instruction and R17 & R18 a register? And Where are they stored in AVR architecture?

4) Lastly, why does it save the result in R25:R24, not just returning the value of R24 (that contains n1 + n2 + n3 + n4)?

I am really really new to Assembly language... please enlighten me about it... Any help would be great! Thanks

答:
Yes, but presumably R18 would have to be saved according to calling convention too

That's just zero extending.

Yes. They are internal to the cpu but also mapped to SRAM memory address range 0-31.

Presumably because the function is expected to return a 16 bit value. Note that it would then be better to perform 16 bit additions too.

Body:
For code like:

;; Data definitions go here
.section .data
n1:     .byte 12
n2:     .byte 34
n3:     .byte 21
n4:     .byte 10
result: .space 1

;; Code definition goes here
.section .text
    .global main

main:
    push R17

    ldi R26, lo8(n1)        ; Loading the address of n1 in X
        ldi R27, hi8(n1)

        ld R24, X+              ; Load n1 in R24 and increase address
        ld R17, X+              ; Load n2 in R17 and increase address
        add R24, R17            ; R4 = n1 + n2
        ld R17, X+              ; Load n3 in R17 and increase address
        add R24, R17            ; R4 = n1 + n2 + n3
        ld R17, X+              ; Load n4 in R17 and increase address
        add R24, R17            ; Final result in R24 = n1 + n2 + n3 + n4

        ;; At this point R27:R26 contains the address of result
        st X, R24               ; Store the result

    ;; The result of this function is returned in R25:R24
        clr R25         ; So that R25:R24 has the result in 16 bits.

    pop R17
    ret
.end

1) Would the result be the same even if we use R18 instead of R17 and remove popping and pushing R17?

2) Also, just doing clr R25 concatenate R25 to R24? (hence make R25:R24?)

3) Moreover, when performing an operation of instruction like:

ADD R17, R18, is ADD an instruction and R17 & R18 a register? And Where are they stored in AVR architecture?

4) Lastly, why does it save the result in R25:R24, not just returning the value of R24 (that contains n1 + n2 + n3 + n4)?

I am really really new to Assembly language... please enlighten me about it... Any help would be great! Thanks


来源: stackexchange

答:
This is a short[].

You can translate it like any other array:

```<code>short[] x = { 1,2,3 };
</code>```

ContentLicense: CC BY-SA 2.5

Title: decoding G711 converting from c++ to c#

Body:
i try to decoding G711 packet i find this code in c++ but i do not know how to convert this  code to c#

this the code

gint16 alaw_exp_table[256] = {
      -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736,
      -7552, -7296, -8064, -7808, -6528, -6272, -7040, -6784,
      -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368,
      -3776, -3648, -4032, -3904, -3264, -3136, -3520, -3392,
     -22016,-20992,-24064,-23040,-17920,-16896,-19968,-18944,
     -30208,-29184,-32256,-31232,-26112,-25088,-28160,-27136,
     -11008,-10496,-12032,-11520, -8960, -8448, -9984, -9472,
     -15104,-14592,-16128,-15616,-13056,-12544,-14080,-13568,
       -344,  -328,  -376,  -360,  -280,  -264,  -312,  -296,
       -472,  -456,  -504,  -488,  -408,  -392,  -440,  -424,
        -88,   -72,  -120,  -104,   -24,    -8,   -56,   -40,
       -216,  -200,  -248,  -232,  -152,  -136,  -184,  -168,
      -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184,
      -1888, -1824, -2016, -1952, -1632, -1568, -1760, -1696,
       -688,  -656,  -752,  -720,  -560,  -528,  -624,  -592,
       -944,  -912, -1008,  -976,  -816,  -784,  -880,  -848,
       5504,  5248,  6016,  5760,  4480,  4224,  4992,  4736,
       7552,  7296,  8064,  7808,  6528,  6272,  7040,  6784,
       2752,  2624,  3008,  2880,  2240,  2112,  2496,  2368,
       3776,  3648,  4032,  3904,  3264,  3136,  3520,  3392,
      22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944,
      30208, 29184, 32256, 31232, 26112, 25088, 28160, 27136,
      11008, 10496, 12032, 11520,  8960,  8448,  9984,  9472,
      15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568,
        344,   328,   376,   360,   280,   264,   312,   296,
        472,   456,   504,   488,   408,   392,   440,   424,
         88,    72,   120,   104,    24,     8,    56,    40,
        216,   200,   248,   232,   152,   136,   184,   168,
       1376,  1312,  1504,  1440,  1120,  1056,  1248,  1184,
       1888,  1824,  2016,  1952,  1632,  1568,  1760,  1696,
        688,   656,   752,   720,   560,   528,   624,   592,
        944,   912,  1008,   976,   816,   784,   880,   848};

#include <glib.h>
#include "G711adecode.h"
#include "G711atable.h"

int
decodeG711a(void *input, int inputSizeBytes, void *output, int *outputSizeBytes)
{
  guint8 *dataIn = (guint8 *)input;
  gint16 *dataOut = (gint16 *)output;
  int i;

  for (i=0; i<inputSizeBytes; i++)
  {
    dataOut[i] = alaw_exp_table[dataIn[i]];
  }
  *outputSizeBytes = inputSizeBytes * 2;
  return 0;
}

can any body help me ?

thanks in advance

Body:
This is a short[].

You can translate it like any other array:

short[] x = { 1,2,3 };


问:
Swift - Avoiding strong reference cycles in closure-based configuration
Please note: I have read many of the (very many) answers and articles on the subject of avoiding strong reference cycles. However, I'm looking for guidance on how to handle a specific by-product of avoiding these cycles.

In the following example, the class Foo is designed to be configured using a closure. A reference to the closure is cached for later use.

The closure will be called whenever the Model data is needed. In order for Foo to work properly, the data must exist.

```<code>class Foo
{
    typealias ModelGetter = (() -> Model)
    fileprivate var _modelGetter: ModelGetter!

    ...

    func configure(with modelGetter: @escaping ModalGetter)
    {
        _modelGetter = modelGetter
    }

    func printLastestModel()
    {
        // Get the latest model, do something with it.
        precondition(_modelGetter != nil)
        let model = _modelGetter()
        print(model)
    }
}
</code>```

In the above code, _modelGetter is implicitly unwrapped. Although I could define it as an Optional, and unwrap it as needed, Foo always needs the closure to be set in order to work properly, hence the implicit unwrapping.

Making an instance of Foo, and configuring it:

```<code>let foo = Foo()
foo.configure(with: { self.makeModel() })
foo.printLatestModel()
</code>```

But, this creates a retain cycle.

So, [weak self] is used, and we check for self's optionality:

```<code>foo.configure(with: { [weak self] in
    guard let strongSelf = self else { return **WHAT** }
    return strongSelf.makeModel()
})
</code>```

Problem

This requires that even though self may be nil, the closure still needs to return a Model (i.e. WHAT?) to the caller of the closure (the Foo instance.) But, since self is nil, I don't have a Model to hand over.

Question

Can someone recommend a pattern to use in this situation? Preferably, I don't want Foo to be checking if the modelGetter is valid or not, or left wondering if the Model is valid. For Foo's purposes, if Foo exists, then it must always be able to get the Model it needs.

Or, should I just redesign Foo's needs, to take in to account the possibility of not being able to procure a Model? Thankyou for any help.

答:
But, this creates a retain cycle.

No it doesn't. foo owns a reference to the closure and the closure owns a reference to self (which is clearly not foo). You will only get a retain cycle, if you have a strong property of type Foo in self and you set it to foo.

On the assumption that you are going to do that, I would use one of two patterns:

I make the assumption as a programmer that self will always be there for the lifetime of foo. In that case, I would use [unowned self] instead of [weak self]. If my assumption proves to be wrong, the program will abort and I'll be able to fix the bug based on the stack trace. Obviously, you'll want a fairly extensive test suite to validate the assumption as far as possible.

I decide that it is valid for self to disappear in which case you have three choices about how to handle the disappearance:

Make the return type of the closure optional i.e. () -> Model? and make Foo capable of handling a nil model

Have a default Model that you return if self is nil.

Make the closure declare that it throws and throw an error if self is nil.

I think I'd probably go with [unowned self] and make sure I explicitly kept a strong reference to it somewhere.

ContentLicense: CC BY-SA 3.0

Body:
Please note: I have read many of the (very many) answers and articles on the subject of avoiding strong reference cycles. However, I'm looking for guidance on how to handle a specific by-product of avoiding these cycles.

In the following example, the class Foo is designed to be configured using a closure. A reference to the closure is cached for later use.

The closure will be called whenever the Model data is needed. In order for Foo to work properly, the data must exist.

class Foo
{
    typealias ModelGetter = (() -> Model)
    fileprivate var _modelGetter: ModelGetter!

    ...

    func configure(with modelGetter: @escaping ModalGetter)
    {
        _modelGetter = modelGetter
    }

    func printLastestModel()
    {
        // Get the latest model, do something with it.
        precondition(_modelGetter != nil)
        let model = _modelGetter()
        print(model)
    }
}

In the above code, _modelGetter is implicitly unwrapped. Although I could define it as an Optional, and unwrap it as needed, Foo always needs the closure to be set in order to work properly, hence the implicit unwrapping.

Making an instance of Foo, and configuring it:

let foo = Foo()
foo.configure(with: { self.makeModel() })
foo.printLatestModel()

But, this creates a retain cycle.

So, [weak self] is used, and we check for self's optionality:

foo.configure(with: { [weak self] in
    guard let strongSelf = self else { return **WHAT** }
    return strongSelf.makeModel()
})

Problem

This requires that even though self may be nil, the closure still needs to return a Model (i.e. WHAT?) to the caller of the closure (the Foo instance.) But, since self is nil, I don't have a Model to hand over.

Question

Can someone recommend a pattern to use in this situation? Preferably, I don't want Foo to be checking if the modelGetter is valid or not, or left wondering if the Model is valid. For Foo's purposes, if Foo exists, then it must always be able to get the Model it needs.

Or, should I just redesign Foo's needs, to take in to account the possibility of not being able to procure a Model? Thankyou for any help.


问:
Increment and Decrement c++ and java difference
here i want a brief explain about answer(24).but i tried this code in java.I had answer 23 in java. </p>

```<code>#include <iostream>

using namespace std;

int main()
{

    int a=10,b=2,c=0;
    c=(++a + ++a);
    cout <<c<<endl;
    return 0;
     //Here how to get answer 24

}
</code>```

答:
```<code>c=(++a + ++a);
</code>```

In C++, it is undefined behaviour. I don't know behaviour of that code in java.

C++03 5 Expressions [expr]:

Paragraph 4:

....

  Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full
  expression; otherwise the behavior is undefined.

C++11 §1.9/14 says:

Every value computation and side effect associated with a
  full-expression is sequenced before every value computation and side
  effect associated with the next full-expression to be evaluated.

In C++17, it is unspecified behaviour.

Body:
here i want a brief explain about answer(24).but i tried this code in java.I had answer 23 in java.

#include <iostream>

using namespace std;

int main()
{

    int a=10,b=2,c=0;
    c=(++a + ++a);
    cout <<c<<endl;
    return 0;
     //Here how to get answer 24

}

Body:
c=(++a + ++a);

In C++, it is undefined behaviour. I don't know behaviour of that code in java.

C++03 5 Expressions [expr]:

Paragraph 4:

....

  Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full
  expression; otherwise the behavior is undefined.

C++11 §1.9/14 says:

Every value computation and side effect associated with a
  full-expression is sequenced before every value computation and side
  effect associated with the next full-expression to be evaluated.

In C++17, it is unspecified behaviour.


问:
Mysql query join table and let fill with empty if value same
I Have problem with joining 2 table
this is mysql query

select *
  from tbl_perspective a
  inner join tbl_objective b on b.idperspective=a.idperspective

The result is:
Query Result

I Want to display first row of perspectivename and blank or null

Final Result:
enter image description here

答:
Join to a subquery which identifies the first row for each idperspective group:

```<code>SELECT t1.*
FROM tbl_perspective t1
INNER JOIN
(
    SELECT idperspective, MIN(idobjective) AS min_idobjective
    FROM tbl_perspective
    GROUP BY idperspective
) t2
    ON t1.idperspective = t2.idperspective AND
       t1.idobjective   = t2.min_idobjective;
</code>```

Body:
Join to a subquery which identifies the first row for each idperspective group:

SELECT t1.*
FROM tbl_perspective t1
INNER JOIN
(
    SELECT idperspective, MIN(idobjective) AS min_idobjective
    FROM tbl_perspective
    GROUP BY idperspective
) t2
    ON t1.idperspective = t2.idperspective AND
       t1.idobjective   = t2.min_idobjective;


问:
Converting Enum between modules
I have an enum definition in one module(A), e.g. SUCCESS = 0, INVALID_REQ = 1 etc. Then I have another dll (module B) which has its own set of status enum. Once we add a new enum value in A, we have to manually add it to B since A is in .NET and B is C code. Beside, enum in A is only part of the status enum in B (B has its own internal status besides status from A).
This seems a very tight coupling between these two modules. Any suggestions to make them less coupled?
Thx!</p>

答: What would be fun would be to use reflection here. Write a little program that reads the enum by reflection from module A, and generates a .h file for use in the c module.</p>

Title: Converting Enum between modules


问:
Using variable number of float arguments
I'm trying to implement a flexible constructor for my struct Polynomial :

```<code>struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};
</code>```

The degree of the polynomial is variable.
What I would like is to have a constructor like

```<code>Polynomial(float... _coefficients);
</code>```

I've tried variadic template :

```<code>template<float... Args>
Polynomial(Args... args);
</code>```

But float is a non-type, so I've done :

```<code>template<typename... Args>
Polynomial(Args... args);
</code>```

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

```<code>Polynomial(size_t _degree, ...);
</code>```

But it is really unsafe.

At the moment I'm using :

```<code>Polynomial(std::vector<float>);
</code>```

But this force the call to be like :

```<code>Polynomial P({f1, f2, f3}); // with fn floats
</code>```

So I would like to know if there is a good way to do this.

Thank you !

答:
You can use a recursive template parameter processing. The general idea is to use a private method that adds first parameter to the coefficient vectors and recurse with other parameters until they have all been processed:

```<code>struct Polynomial
{
    template<class...Args>
    Polynomial(Args... coeffs) {
        init(coeffs...);
        degree = coefficients.size() - 1;
    }
    std::vector<float> coefficients;
    size_t degree;
private:
    void init(float coeff) {
        coefficients.push_back(coeff);
    }
    template<class...Args> void init(float first, Args...others) {
        init(first);
        init(others...);
    }
};
</code>```

Body:
I'm trying to implement a flexible constructor for my struct Polynomial :

struct Polynomial
{
    std::vector<float> coefficients;
    size_t degree;
};

The degree of the polynomial is variable.
What I would like is to have a constructor like

Polynomial(float... _coefficients);

I've tried variadic template :

template<float... Args>
Polynomial(Args... args);

But float is a non-type, so I've done :

template<typename... Args>
Polynomial(Args... args);

But this allow my coefficients to be anything, not realy what I want.
I know I could use :

Polynomial(size_t _degree, ...);

But it is really unsafe.

At the moment I'm using :

Polynomial(std::vector<float>);

But this force the call to be like :

Polynomial P({f1, f2, f3}); // with fn floats

So I would like to know if there is a good way to do this.

Thank you !

Body:
You can use a recursive template parameter processing. The general idea is to use a private method that adds first parameter to the coefficient vectors and recurse with other parameters until they have all been processed:

struct Polynomial
{
    template<class...Args>
    Polynomial(Args... coeffs) {
        init(coeffs...);
        degree = coefficients.size() - 1;
    }
    std::vector<float> coefficients;
    size_t degree;
private:
    void init(float coeff) {
        coefficients.push_back(coeff);
    }
    template<class...Args> void init(float first, Args...others) {
        init(first);
        init(others...);
    }
};


问:
Excel VBA run macro across dynamic range of sheets
As an extension from the last question I asked, I'm trying to run a macro across all worksheets, which you guys successfully helped me to do.
I've been told that the worksheet names can't be hardcoded, so I'm going to have to modify my current solution.

```<code>Sub RemoveCarriageReturns()
Dim MyRange As Range
Dim NameList() As Variant
NameList = Array("OTCUEXTR", "OTFBCUDS", "OTFBCUEL")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For i = 0 To 2
    With Worksheets(NameList(i))
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
</code>```

I've tried to populate the array with a For loop that gathers names of each worksheet however I feel after 2 days blankly staring at this,  my limited VBA knowledge has run out and I'm stuck, I would really appreciate some pointers on how to get this macro to work across an range of sheets that can change in quantity and names.

Happy to provide any more information you need in a comment

答:
```<code>Public Function GetSheetNames(ByVal wbk As workbook) As String()
    Dim names() As String
    Dim count As Integer
    Dim i As Integer

        count = wbk.Worksheets.count

        ReDim names(count - 1)
        For i = 1 To wbk.Worksheets.count
            names(i - 1) = wbk.Worksheets(i).Name
        Next

        GetSheetNames = names

    End Function
</code>```

Usage: GetSheetNames(Application.ActiveWorkbook)

UPDATE: For selected sheets only:

```<code>Public Function GetActiveSheetNames(ByVal wbk As workbook) As String()
Dim names() As String
Dim count As Integer
Dim i As Integer

    count = wbk.Windows(1).SelectedSheets.count

    ReDim names(count - 1)
    For i = 1 To wbk.Windows(1).SelectedSheets.count
        names(i - 1) = wbk.Windows(1).SelectedSheets(i).Name
    Next

    GetActiveSheetNames = names

End Function
</code>```

Body:
As an extension from the last question I asked, I'm trying to run a macro across all worksheets, which you guys successfully helped me to do.
I've been told that the worksheet names can't be hardcoded, so I'm going to have to modify my current solution.

Sub RemoveCarriageReturns()
Dim MyRange As Range
Dim NameList() As Variant
NameList = Array("OTCUEXTR", "OTFBCUDS", "OTFBCUEL")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For i = 0 To 2
    With Worksheets(NameList(i))
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

I've tried to populate the array with a For loop that gathers names of each worksheet however I feel after 2 days blankly staring at this,  my limited VBA knowledge has run out and I'm stuck, I would really appreciate some pointers on how to get this macro to work across an range of sheets that can change in quantity and names.

Happy to provide any more information you need in a comment

Body:
Public Function GetSheetNames(ByVal wbk As workbook) As String()
    Dim names() As String
    Dim count As Integer
    Dim i As Integer

        count = wbk.Worksheets.count

        ReDim names(count - 1)
        For i = 1 To wbk.Worksheets.count
            names(i - 1) = wbk.Worksheets(i).Name
        Next

        GetSheetNames = names

    End Function

Usage: GetSheetNames(Application.ActiveWorkbook)

UPDATE: For selected sheets only:

Public Function GetActiveSheetNames(ByVal wbk As workbook) As String()
Dim names() As String
Dim count As Integer
Dim i As Integer

    count = wbk.Windows(1).SelectedSheets.count

    ReDim names(count - 1)
    For i = 1 To wbk.Windows(1).SelectedSheets.count
        names(i - 1) = wbk.Windows(1).SelectedSheets(i).Name
    Next

    GetActiveSheetNames = names

End Function


问:
Why does Subversion fail to flag a modified Microsoft Excel spreadsheet file?
I have encountered some behaviour I didn't expect from Subversion, and discovered this almost accidentally: A modified file is not being flagged as modified.

I have a unit test involving a Microsoft Excel spreadsheet as an input file. The unit test calculates a CRC checksum; my test started failing due to the checksum changing.

The test file is stored in SVN, and has MIME type "application/octet-stream", and is therefore considered as binary by SVN.

I get the same behaviour from TortoiseSVN and the SVN command line client, in this case both based on SVN 1.6: When the file is opened in Excel, the fact that it is open must be encoded in the file itself; SVN shows that the file is modified. However, when the file is closed again (without saving), it seems to return to its unmodified state: that is, svn status does not list the Excel file; svn diff produces no output anyway due to the data being binary.

The catch is that the file does not now binary compare with the file stored in the repository. (If a fresh copy is exported, it does not binary compare with the opened-and-closed copy.) The file is apparently unchanged from the user's point of view, so in a semantic sense, the SVN response is reasonable. But not syntactically; and SVN is essentially syntactic.

The part for which I can't find a reason is why SVN does not flag the file as modified. I can't imagine SVN has any special handling for Excel files (and in any case the MIME type is not specifically one associated with MS Excel); there is no SNV keyword property defined. Likewise, I can imagine Excel knows anything about the contents of the hidden .svn subdirectory in which the SVN working copy information is stored.

Do you have any clues as to what is going on here?

Thanks, Rob.

答: Is it possible the file is locked by excel while it is open and svn can't access it to see if it has changed or not? </p>


问:
how to get the maximum amplitude value from the Python PSD function
I plotted this spectrum with the following code:

PSD plot

```<code>[Y,F]=psd(samples, NFFT=1024, Fs=sdr.sample_rate/1e6,
Fc=sdr.center_freq/1e6, noverlap=0)
xlabel('Frequency (MHz)')
ylabel('Relative power (dB)')
max=np.max(Y)
print(max)
</code>```

but then I get

max=0.000458510518667

Actually, if I print the values of Y, I get:

[  8.60400008e-06   7.85361760e-06   9.00300444e-06 ...,

  9.55738417e-06
     1.14888955e-05   1.12340323e-05]

maybe I need to do something else to get the amplitudes that I see in the plot?

答:
The result isn't given in dB so actually:

10*log(0.000458) = -33 dB (approx.)

Therefore, the previous code is correct and you can use it if you need to get the maximum value of the PSD function. You could add this code:

```<code>    max=np.max(Y)
    log=10*math.log10(max)
    print(max)
    print(log)
</code>```

I realize about this thanks to the user @ImportanceOfBeingErnest who is an expert in the Python library I'm using, matplotlib.

Body:
I plotted this spectrum with the following code:

PSD plot

[Y,F]=psd(samples, NFFT=1024, Fs=sdr.sample_rate/1e6,
Fc=sdr.center_freq/1e6, noverlap=0)
xlabel('Frequency (MHz)')
ylabel('Relative power (dB)')
max=np.max(Y)
print(max)

but then I get

max=0.000458510518667

Actually, if I print the values of Y, I get:

[  8.60400008e-06   7.85361760e-06   9.00300444e-06 ...,

  9.55738417e-06
     1.14888955e-05   1.12340323e-05]

maybe I need to do something else to get the amplitudes that I see in the plot?

Body:
The result isn't given in dB so actually:

10*log(0.000458) = -33 dB (approx.)

Therefore, the previous code is correct and you can use it if you need to get the maximum value of the PSD function. You could add this code:

    max=np.max(Y)
    log=10*math.log10(max)
    print(max)
    print(log)

I realize about this thanks to the user @ImportanceOfBeingErnest who is an expert in the Python library I'm using, matplotlib.


问:
CSS/Javascript - using hover to show dropdown div
I am having a hard time of this... I have an existing navigation bar that uses a table (i know it would be better to use a UL tag but i'm editing a pre existing page so would rather not reinvent the wheel). I have a javascript snipped that shows a dropdown menu when you hover. However, i'm at a loss to figure out how in the world to make it disappear at the right time. As in... when you hover over anavbar1, the div is shown as expected. but then, how to make it hide after say a certain number of seconds, or as soon as another navbar dropdown is triggered (like a normal dropdown)? here is my entire code :</p>

```<code><link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:600" rel="stylesheet">
<style type="text/css">
    #anavbar0 {
        display: block;
        width: 633px; height: 107px;
        background: url("../GFX/slice0.png") no-repeat 0 0;
    }
    #anavbar0:hover {}
    #anavbar0 span {
        display: none;
    }

    .anavbar1 {
        display: block;
        width: 104px; height: 107px;
        background: url("../GFX/slice1.png") no-repeat 0 0;
    }
    .anavbar1:hover .dropdown1 {
        display: block;
    }
    .anavbar1:hover {
        background-position: 0 -107px;
    }
    .anavbar1 span {
        display: none;
    }

    #anavbar2 {
        display: block;
        width: 169px; height: 107px;
        background: url("../GFX/slice2.png") no-repeat 0 0;
    }
    #anavbar2:hover {
        background-position: 0 -107px;
    }
    #anavbar2 span {
        display: none;
    }

    #anavbar3 {
        display: block;
        width: 134px; height: 107px;
        background: url("../GFX/slice3.png") no-repeat 0 0;
    }
    #anavbar3:hover {
        background-position: 0 -107px;
    }
    #anavbar3 span {
        display: none;
    }

    #anavbar4 {
        display: block;
        width: 102px; height: 107px;
        background: url("../GFX/slice4.png") no-repeat 0 0;
    }
    #anavbar4:hover {
        background-position: 0 -107px;
    }
    #anavbar4 span {
        display: none;
    }

    #anavbar5 {
        display: block;
        width: 103px; height: 107px;
        background: url("../GFX/slice5.png") no-repeat 0 0;
    }
    #anavbar5:hover {
        background-position: 0 -107px;
    }
    #anavbar5 span {
        display: none;
    }

    #anavbar6 {
        display: block;
        width: 144px; height: 107px;
        background: url("../GFX/slice6.png") no-repeat 0 0;
    }
    #anavbar6:hover {
        background-position: 0 -107px;
    }
    #anavbar6 span {
        display: none;
    }

    #anavbar7 {
        display: block;
        width: 111px; height: 107px;
        background: url("../GFX/slice7.png") no-repeat 0 0;
    }
    #anavbar7:hover {
        background-position: 0 -107px;
    }
    #anavbar7 span {
        display: none;
    }

    .dropdown1 {
        display:none;
       position: absolute;
       top:200px;
       background-color: #f9f9f9;
       min-width: 160px;
       box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
       z-index: 1;
    }

    #drop1 {
        position: absolute;
        width: 119px;
        height: 117px;
        z-index: 1;
        left: 634px;
        top: 115px;
        visibility: hidden;
        font-family: 'Source Sans Pro', sans-serif;
        font-size: 36px;
    }
    .hoverTable{
        width:100%; border-collapse:collapse;
    }
    .hoverTable td{
        padding:7px;
        border:#888888 1px solid;
    }
    .hoverTable tr{
        background: #444444;
        color:#EEE;
    }
    .hoverTable tr:hover {
        background-color:#294E7A
    }
</style>
<script type="text/javascript">
    div = {show: function(elem) {document.getElementById(elem).style.visibility = 'visible';},
    hide: function(elem) {document.getElementById(elem).style.visibility = 'hidden';}}
</script>
<table width="900" border="0" cellpadding="0" cellspacing="0" >
    <tr>
        <td width="98"><a id="anavbar0" ></a></td>
        <td onMouseOver="div.show('drop1')"  width="98" class="anavbar1"><a id="anavbar1" href="home.php" ></a></td>
        <td width="117"><a id="anavbar2" href="link1.php"></a></td>
        <td width="115"><a id="anavbar3" href="link2.php"></a></td>
        <td width="134"><a id="anavbar4" href="link3.php"></a></td>
        <td width="78"><a id="anavbar5" href="link4.php"></a></td>
        <td width="117"><a id="anavbar6" href="link5.php"></a></td>
        <td width="117"><a id="anavbar7" href="link6.php"></a></td>
    </tr>
</table>
<div id="drop1" >
    <table align="right" class="hoverTable">
        <tr>
            <td align="right">Text 1A</td>
        </tr>
        <tr>
            <td align="right">Text 2A</td>
        </tr>
        <tr>
            <td align="right">Text 3A</td>
        </tr>
    </table>
</div>
</code>```

答:
If you move
 into td with onmouseover than technically that div will be inside td and so onmouseout event will fire when mouse leaves table cell and "drop1" div.

But if you need to style drop1 you should take into account that top margin will break continuity of td and onmouseout event will fire when arrow touches margin.

Here is (rather rough) jsfiddle to demonstrate it: https://jsfiddle.net/uxnu65wf/

P.S. with this approach you may not need javascript as the same can be achieved by using :hover in css.

Body:
I am having a hard time of this... I have an existing navigation bar that uses a table (i know it would be better to use a UL tag but i'm editing a pre existing page so would rather not reinvent the wheel). I have a javascript snipped that shows a dropdown menu when you hover. However, i'm at a loss to figure out how in the world to make it disappear at the right time. As in... when you hover over anavbar1, the div is shown as expected. but then, how to make it hide after say a certain number of seconds, or as soon as another navbar dropdown is triggered (like a normal dropdown)? here is my entire code :

<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:600" rel="stylesheet">

            Text 1A

            Text 2A

            Text 3A

Body:
If you move <div id="drop1"> into td with onmouseover than technically that div will be inside td and so onmouseout event will fire when mouse leaves table cell and "drop1" div.

But if you need to style drop1 you should take into account that top margin will break continuity of td and onmouseout event will fire when arrow touches margin.

Here is (rather rough) jsfiddle to demonstrate it: https://jsfiddle.net/uxnu65wf/

P.S. with this approach you may not need javascript as the same can be achieved by using :hover in css.


问:
AWS EMR- Yarn Container
I was running an application on AWS EMR-Spark. Here, is the spark-submit job;-

```<code>Arguments : spark-submit --deploy-mode cluster --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08
</code>```

AWS uses YARN for resource management. I was looking at the metrics (screenshot below), and have a doubt regarding the YARN 'container' metrics.

Here, the container allocated is shown as 2. However, I was using 4 nodes (3 slave + 1 master),all 8 cores CPU. So, how are only 2 container allocated?

答:
A couple of thing you need to do. First of all, you need to set the following configuration in capacity-scheduler.xml

```<code>"yarn.scheduler.capacity.resource-calculator":"org.apache.hadoop.yarn.util.resource.DominantResourceCalculator"
</code>```

otherwise YARN will not use all the cores you specify. Secondly, you need to actually specify the number of executors you need, and also the number of cores you need and the amount of memory you want allocated on executors (and possibly on the driver as well, if you either have many shuffle partitions or if you collect data to the driver).

YARN is designed to manage clusters running many different jobs at the time, so it will not per default assign all ressources to a single job, unless you force it to by setting the above mentioned setting. Furthermore, the default setting for Spark are also not sufficient for most jobs and you need to set them explicitly. Please have a read through this blog post to get a better understanding of how to tune spark settings for optimal performance.

Title: AWS EMR- Yarn Container

Body:
I was running an application on AWS EMR-Spark. Here, is the spark-submit job;-

Arguments : spark-submit --deploy-mode cluster --class com.amazon.JavaSparkPi s3://spark-config-test/SWALiveOrderModelSpark-1.0.assembly.jar s3://spark-config-test/2017-08-08

AWS uses YARN for resource management. I was looking at the metrics (screenshot below), and have a doubt regarding the YARN 'container' metrics.

Here, the container allocated is shown as 2. However, I was using 4 nodes (3 slave + 1 master),all 8 cores CPU. So, how are only 2 container allocated?

Body:
A couple of thing you need to do. First of all, you need to set the following configuration in capacity-scheduler.xml

"yarn.scheduler.capacity.resource-calculator":"org.apache.hadoop.yarn.util.resource.DominantResourceCalculator"

otherwise YARN will not use all the cores you specify. Secondly, you need to actually specify the number of executors you need, and also the number of cores you need and the amount of memory you want allocated on executors (and possibly on the driver as well, if you either have many shuffle partitions or if you collect data to the driver).

YARN is designed to manage clusters running many different jobs at the time, so it will not per default assign all ressources to a single job, unless you force it to by setting the above mentioned setting. Furthermore, the default setting for Spark are also not sufficient for most jobs and you need to set them explicitly. Please have a read through this blog post to get a better understanding of how to tune spark settings for optimal performance.


问:
Django: Why 'Class' object is not iterable
I built a dictionary list like this

```<code>lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]
</code>```

and I'm using

```<code>for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process
</code>```

The error message is like "Classname" object is not iterable.

答:
Iterating over a dictionary just iterates over the keys, not key-value pairs. So on the line

```<code>for k,v in dic:
</code>```

Python is taking just a key, such as Classobj1, and trying to unpack it to match it to the tuple k,v. Since Classobj1 can't be iterated over, it can't be unpacked to match two items, which is why you get this error.

To iterate over key-value pairs, use items() or iteritems():

```<code>for k,v in dic.items():
</code>```

Body:
I built a dictionary list like this

lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]

and I'm using

for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process

The error message is like "Classname" object is not iterable.

Body:
Iterating over a dictionary just iterates over the keys, not key-value pairs. So on the line

for k,v in dic:

Python is taking just a key, such as Classobj1, and trying to unpack it to match it to the tuple k,v. Since Classobj1 can't be iterated over, it can't be unpacked to match two items, which is why you get this error.

To iterate over key-value pairs, use items() or iteritems():

for k,v in dic.items():


问:
How to Round to the nearest whole number in C#
How can I round values to nearest integer?

For example:

```<code>1.1 => 1
1.5 => 2
1.9 => 2
</code>```

"Math.Ceiling()" is not helping me. Any ideas?

答: Using Math.Round(number) rounds to the nearest whole number.

ContentLicense: CC BY-SA 4.0

Body:
How can I round values to nearest integer?

For example:

1.1 => 1
1.5 => 2
1.9 => 2

"Math.Ceiling()" is not helping me. Any ideas?


问:
python cgitb is not functioning through a browser
I can't seem to get the python module cgitb to output the stack trace in a browser. I have no problems in a shell environment. I'm running Centos 6 with python 2.6.

Here is an example simple code that I am using:

```<code>import cgitb; cgitb.enable()

print "Content-type: text/html"
print

print 1/0
</code>```

I get an Internal Server error instead of the printed detailed report. I have tried different error types, different browsers, etc.

When I don't have an error, of course python works fine. It will print the error in a shell fine. The point of cgitb is to print the error instead of returning an "Internal Server Error" in the browser for most error exceptions. Basically I'm just trying to get cgitb to work in a browser environment.

Any Suggestions?

Body:
I can't seem to get the python module cgitb to output the stack trace in a browser. I have no problems in a shell environment. I'm running Centos 6 with python 2.6.

Here is an example simple code that I am using:

import cgitb; cgitb.enable()

print "Content-type: text/html"
print

print 1/0

I get an Internal Server error instead of the printed detailed report. I have tried different error types, different browsers, etc.

When I don't have an error, of course python works fine. It will print the error in a shell fine. The point of cgitb is to print the error instead of returning an "Internal Server Error" in the browser for most error exceptions. Basically I'm just trying to get cgitb to work in a browser environment.

Any Suggestions?

Body:
Okay, I got my problem fixed and the OP brought me to it: Even tho cgitb will output HTML by default, it will not output a header! And Apache does not like that and might give you some stupid error like:

<...blablabla>: Response header name '<!--' contains invalid characters, aborting request

It indicates, that Apache was still working its way through the headers when it already encountered some HTML. Look at what the OP prints before the error is triggered. That is a header and you need that. Including the empty line.


问:
Making modular VBA function (MS Access)
I am writing up a simple multi-condition search form.
The Access VBA function set for the first toggle button looks like this:

```<code>Private Sub ToggleQ1_Click()
Select Case ToggleQ1.Value
    Case True
        CondQ1 = "AND"
        ToggleQ1.Caption = CondQ1
    Case False
        CondQ1 = "OR"
        ToggleQ1.Caption = CondQ1
End Select
End Sub
</code>```

ToggleQ1 = button's name

CondQ1 = variable to be used with a string to create conditional search.

It would likely be absurd to create 50 more of the same button code, differ only in its name (ex. "ToggleQ50" and "CondQ50")

Is there any way to make it modular and reusable?
Thank you very much in advance.

答:
Use WithEvents. That takes a little code when loading and unloading the form, but zero code for each button.

A similar example with full code, which you should be able to adapt, can be found here:

Create Windows Phone Colour Palette and Selector using WithEvents

and at GitHub:
VBA.ModernTheme

Code snippet:

```<code>Private ControlCollection   As Collection

Private Sub Form_Load()

    ' Load events for all colour value textboxes.

    Dim EventProcedure  As ClassTextboxSelect
    Dim Control         As Access.Control

    Set ControlCollection = New Collection

    For Each Control In Me.Controls
        If Control.ControlType = acTextBox Then
            Set EventProcedure = New ClassTextboxSelect
            EventProcedure.Initialize Control
            ControlCollection.Add EventProcedure, Control.Name
        End If
    Next

    Set EventProcedure = Nothing
    Set Control = Nothing

End Sub

Private Sub Form_Open(Cancel As Integer)

    Dim Index   As Integer

    ' Set colour palette.
    For Index = 0 To 20
        Me("Box" & CStr(Index + 1)).BackColor = PaletteColor(Index)
        Me("Name" & CStr(Index + 1)).Value = LiteralWpThemeColor(PaletteColor(Index))
        Me("Css" & CStr(Index + 1)).Value = RGBHex(PaletteColor(Index))
        Me("Vba" & CStr(Index + 1)).Value = PaletteColor(Index)
        Me("Hex" & CStr(Index + 1)).Value = "&H" & Hex(PaletteColor(Index))
    Next

End Sub

Private Sub Form_Unload(Cancel As Integer)

    ' Unload events for all colour value textboxes.

    Dim EventProcedure  As ClassTextboxSelect

    For Each EventProcedure In ControlCollection
        EventProcedure.Terminate
    Next

    Set EventProcedure = Nothing
    Set ControlCollection = Nothing

End Sub
</code>```

Title: Making modular VBA function (MS Access)

Body:
I am writing up a simple multi-condition search form.
The Access VBA function set for the first toggle button looks like this:

Private Sub ToggleQ1_Click()
Select Case ToggleQ1.Value
    Case True
        CondQ1 = "AND"
        ToggleQ1.Caption = CondQ1
    Case False
        CondQ1 = "OR"
        ToggleQ1.Caption = CondQ1
End Select
End Sub

ToggleQ1 = button's name

CondQ1 = variable to be used with a string to create conditional search.

It would likely be absurd to create 50 more of the same button code, differ only in its name (ex. "ToggleQ50" and "CondQ50")

Is there any way to make it modular and reusable?
Thank you very much in advance.

Body:
Use WithEvents. That takes a little code when loading and unloading the form, but zero code for each button.

A similar example with full code, which you should be able to adapt, can be found here:

Create Windows Phone Colour Palette and Selector using WithEvents

and at GitHub:
VBA.ModernTheme

Code snippet:

Private ControlCollection   As Collection

Private Sub Form_Load()

    ' Load events for all colour value textboxes.

    Dim EventProcedure  As ClassTextboxSelect
    Dim Control         As Access.Control

    Set ControlCollection = New Collection

    For Each Control In Me.Controls
        If Control.ControlType = acTextBox Then
            Set EventProcedure = New ClassTextboxSelect
            EventProcedure.Initialize Control
            ControlCollection.Add EventProcedure, Control.Name
        End If
    Next

    Set EventProcedure = Nothing
    Set Control = Nothing

End Sub

Private Sub Form_Open(Cancel As Integer)

    Dim Index   As Integer

    ' Set colour palette.
    For Index = 0 To 20
        Me("Box" & CStr(Index + 1)).BackColor = PaletteColor(Index)
        Me("Name" & CStr(Index + 1)).Value = LiteralWpThemeColor(PaletteColor(Index))
        Me("Css" & CStr(Index + 1)).Value = RGBHex(PaletteColor(Index))
        Me("Vba" & CStr(Index + 1)).Value = PaletteColor(Index)
        Me("Hex" & CStr(Index + 1)).Value = "&H" & Hex(PaletteColor(Index))
    Next

End Sub

Private Sub Form_Unload(Cancel As Integer)

    ' Unload events for all colour value textboxes.

    Dim EventProcedure  As ClassTextboxSelect

    For Each EventProcedure In ControlCollection
        EventProcedure.Terminate
    Next

    Set EventProcedure = Nothing
    Set ControlCollection = Nothing

End Sub


问:
GraphQL - fetch a field conditionally
Imagine that I have a following query (I am using Apollo):

```<code>const userQuery = gql`
    query {
      user {
        id
        name
      }
    }
  `;
</code>```

I want to fetch name field only if some condition is met (let's say variable shouldFetchName is true). How should I approach this and what is the best practice?

答:
You can pass a variable to your query and use a Directive to fetch a field conditionally, like name @include(if: $shouldFetchName).

See the docs for Directives.

Title: GraphQL - fetch a field conditionally

Body:
Imagine that I have a following query (I am using Apollo):

const userQuery = gql`
    query {
      user {
        id
        name
      }
    }
  `;

I want to fetch name field only if some condition is met (let's say variable shouldFetchName is true). How should I approach this and what is the best practice?


问:
Changing structure of WooCommerce shortcode
I have installed WooCommerce on my page, and I'm displaying features posts using shortcode inside of a php file.

```<code><?php echo do_shortcode('[featured_products per_page="3" columns="3"]'); ?>
</code>```

It displays features products, but the problem is that its displaying them in UL and LI elements. Is there a way I can change how its displayed(for example displaying them inside of a bootstrap row and columns), so it can match the structure of my front end.

答:
Yes you can easily do it. Please follow the below instructions

Create a folder named "woocommerce" in your theme folder.

Copy template files in directory wp-content/plugins/woocommerce/templates from woocommerce plugin folder and paste these files in the woocommerce folder of your theme.

Now you can modify WooCommerce templates from your theme.

Open loop folder and edit loop-start.php and loop-end.php remove
 and place your bootstrap divs here.

Open content-product.php to change the
 to your bootstrap columns.

Body:
I have installed WooCommerce on my page, and I'm displaying features posts using shortcode inside of a php file.

<?php echo do_shortcode('[featured_products per_page="3" columns="3"]'); ?>

It displays features products, but the problem is that its displaying them in UL and LI elements. Is there a way I can change how its displayed(for example displaying them inside of a bootstrap row and columns), so it can match the structure of my front end.

Body:
Yes you can easily do it. Please follow the below instructions

Create a folder named "woocommerce" in your theme folder.

Copy template files in directory wp-content/plugins/woocommerce/templates from woocommerce plugin folder and paste these files in the woocommerce folder of your theme.

Now you can modify WooCommerce templates from your theme.

Open loop folder and edit loop-start.php and loop-end.php remove <ul> and place your bootstrap divs here.

Open content-product.php to change the <li> to your bootstrap columns.


问:
What is happening when docker-maven plugin tries to build image?
I am running Jenkins in a docker container and Jenkins tries to run my maven build. As part of the build, the docker maven plugin instructs it to build a docker image.

That part of the POM is below.

```<code><plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.3.8</version>
    <configuration>
        <imageName>example</imageName>
        <baseImage>java:latest</baseImage>
        <skipDockerBuild>false</skipDockerBuild>
        <cmd>["java", "-jar", "myLogThread-jar-with-dependencies.jar"]</cmd>
        <resources>
            <resource>
                <directory>target/</directory>
                <include>config.properties</include>
            </resource>
            <resource>
                <directory>${project.build.directory}</directory>
                <include>myLogThread-jar-with-dependencies.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>
</code>```

The maven build runs until it attempts to build the image, at which point the following error message is spat out:

```<code>[INFO] Building image example
[INFO] I/O exception (java.io.IOException) caught when processing request to {}->unix://localhost:80: Permission denied
</code>```

I can go into the correct directory and the Dockerfile is there.

I can also run sudo docker build . and it will build the image with no issues.

Why is the maven build failing? What request is being made to localhost:80? How can I correct this so that maven can build my image?

Note: I have mounted the docker socket and binary in this container

答:
I had the same problem, but in my local machine.

I've got it after reading this comment in Github thread: https://github.com/docker/compose/issues/1214#issuecomment-256774629

It says:

Solution (from
  https://docs.docker.com/engine/installation/linux/debian/, does not
  only work with Debian):

Add the docker group if it doesn't already exist.

sudo groupadd docker

Add the connected user "${USER}" to the docker group. Change the user
  name to match your preferred user. You may have to logout and log back
  in again for this to take effect.

sudo gpasswd -a ${USER} docker

Restart the Docker daemon.

sudo service docker restart

Body:
I am running Jenkins in a docker container and Jenkins tries to run my maven build. As part of the build, the docker maven plugin instructs it to build a docker image.

That part of the POM is below.

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.3.8</version>
    <configuration>
        <imageName>example</imageName>
        <baseImage>java:latest</baseImage>
        <skipDockerBuild>false</skipDockerBuild>
        <cmd>["java", "-jar", "myLogThread-jar-with-dependencies.jar"]</cmd>
        <resources>
            <resource>
                <directory>target/</directory>
                <include>config.properties</include>
            </resource>
            <resource>
                <directory>${project.build.directory}</directory>
                <include>myLogThread-jar-with-dependencies.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>

The maven build runs until it attempts to build the image, at which point the following error message is spat out:

[INFO] Building image example
[INFO] I/O exception (java.io.IOException) caught when processing request to {}->unix://localhost:80: Permission denied

I can go into the correct directory and the Dockerfile is there.

I can also run sudo docker build . and it will build the image with no issues.

Why is the maven build failing? What request is being made to localhost:80? How can I correct this so that maven can build my image?

Note: I have mounted the docker socket and binary in this container


问:
How to hide Tablix in RDLC C#
I have two tablix in RDLC report,

Tablix2

Tablix3

Tablix2 have 3 rows

Row 1 is used to Show Tablix Header

Row 2 is used to Show Data

Row 3 Containing Tablix3

Here is Design of both Tablixs

My Aim is hidden Tablix3 when there is no data passed to tablix.

Here is Runtime Image without hiding Tablix3

In above Image There is only one detail record for first Purchase no so it will display in RDLC but other purchase No have not details so that will be hidden.

To Hiding Tablix 3 I am using below code in Tablix3 Properties ==> Visibility ==> Show or hide base on an expression Section.

```<code>=IIF(IsNothing(Fields!DataColumn9.Value),"False","True")
</code>```

but when I run RDLC it's giving me Error

the hidden expression for the tablix ‘tablix3’ returned a data type
  that is not valid

I also tried

```<code>=IIF(Len(Fields!DataColumn9.Value) > 0 ,"True","False")
</code>```

as well as also changed values "True","False" to 0 and 1, but still same Error
I tried a lot but failed to find out where I am wrong

答:
using this I solved my problem

```<code>=IIF(IsNothing(Fields!DataColumn9.Value),True,False)
</code>```

In visibility Property it needs boolean value and I was passing string values so that was a Error

Title: How to hide Tablix in RDLC C#

Body:
I have two tablix in RDLC report,

Tablix2

Tablix3

Tablix2 have 3 rows

Row 1 is used to Show Tablix Header

Row 2 is used to Show Data

Row 3 Containing Tablix3

Here is Design of both Tablixs

My Aim is hidden Tablix3 when there is no data passed to tablix.

Here is Runtime Image without hiding Tablix3

In above Image There is only one detail record for first Purchase no so it will display in RDLC but other purchase No have not details so that will be hidden.

To Hiding Tablix 3 I am using below code in Tablix3 Properties ==> Visibility ==> Show or hide base on an expression Section.

=IIF(IsNothing(Fields!DataColumn9.Value),"False","True")

but when I run RDLC it's giving me Error

the hidden expression for the tablix ‘tablix3’ returned a data type
  that is not valid

I also tried

=IIF(Len(Fields!DataColumn9.Value) > 0 ,"True","False")

as well as also changed values "True","False" to 0 and 1, but still same Error
I tried a lot but failed to find out where I am wrong

Body:
using this I solved my problem

=IIF(IsNothing(Fields!DataColumn9.Value),True,False)

In visibility Property it needs boolean value and I was passing string values so that was a Error


问:
Google Analytics event tracking code breaks wordpress site when added to functions.php
I've added a global button via functions.php that shows on my product pages using the following code:

```<code>function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a"><img src="sample-image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
</code>```

Upon adding the following Google Analytics event tracking code to the above code the site breaks.

```<code>function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a" onClick="ga('send', 'event', 'social', 'line-button-click', 'line-button');"><img src="sample-image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
</code>```

I've successfully tested the tracking code by putting it directly in a page

```<code><a href="website.com" onClick="ga('send', 'event', 'social', 'line-button-
click', 'line-button');">anchor text</a>
</code>```

What am I doing wrong?

答:
If you open code with single quote and use them in code you want to echo, you need to escape it, like this:

```<code>function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a" onClick="ga(\'send\', \'event\',
\'social\', \'line-button-click\', \'line-button\');"><img src="sample-
image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}
</code>```

Even if you open echo with " doublequotes it will break since there are double quostes in code you are echoing. I advise you to use some text editor with php syntax highlighting to see where it breaks.

Try the code i gave you,
Regards

Body:
I've added a global button via functions.php that shows on my product pages using the following code:

function add_content_after_addtocart_button_func() {
echo '

';
}

Upon adding the following Google Analytics event tracking code to the above code the site breaks.

function add_content_after_addtocart_button_func() {
echo '

';
}

I've successfully tested the tracking code by putting it directly in a page

anchor text

What am I doing wrong?

Body:
If you open code with single quote and use them in code you want to echo, you need to escape it, like this:

function add_content_after_addtocart_button_func() {
echo '
<div class="wsbl_line"><a href="http://line.me/R/msg/text/website.com"
title="share using Line" rel="nofollow"
class="wp_social_bookmarking_light_a" onClick="ga(\'send\', \'event\',
\'social\', \'line-button-click\', \'line-button\');"><img src="sample-
image.png"
width="135" height="30" class="wp_social_bookmarking_light_img"></a></div>';
}

Even if you open echo with " doublequotes it will break since there are double quostes in code you are echoing. I advise you to use some text editor with php syntax highlighting to see where it breaks.

Try the code i gave you,
Regards


问:
POST versus Ajax call
Now that most modern browsers support AJAX and client-side requests without performing a POST, what is the role of POST (form post)?

Are there situations or general rules when a POST will always be preferred to a XmlHttpRequest?

All that POST is doing is placing variable key value pairs inside the server head. The advantages of POST I can think of are large amounts of data and mobile browsers. Are there many others I'm missing?

N.B. I know you can perform POSTs with AJAX calls, I'm talking primarily about with a <form> tag

答: If you need to refresh the entire page, a post would probably be easier.  </p>

OwnerDisplayName: Chris

Title: POST versus Ajax call

OwnerDisplayName: Kevin


问:
Coldfusion Server: Issues when an email is generated that does not get sent
Basically when an email is generated in our ColdFusion application sometimes an email gets hung in the system because of some error, maybe an email address wasn't specified or something like that. So my boss is having me check the ColdFusion8\Mail\Spool directory every morning for a email(s) if they exist, restart the ColdFusion8 Application Server service then delete the emails.

Issue: System gets email that hangs up, system stops sending emails all together for every email form.

Is there a automated way to handle this?

答:
The Undelivernator project on RIAForge.org is what you're looking for.

http://undelivrnator.riaforge.org/


问:
How send data from fragment in TabLayout to MainActivity?
I have a TabLayout with two tabs and a MainActivity.
 How can I send data from fragment1 which placed in tab1 to MainActivity?

答:
You can create one interface for that. Please check code snippet.

Fragment

```<code>public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
          someEventListener = (onSomeEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
        }
  }

  final String LOG_TAG = "myLogs";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment2, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

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

Activity

```<code>public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}
</code>```

Body:
You can create one interface for that. Please check code snippet.

Fragment

public class Fragment2 extends Fragment {

  public interface onSomeEventListener {
    public void someEvent(String s);
  }

  onSomeEventListener someEventListener;

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
        try {
          someEventListener = (onSomeEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement onSomeEventListener");
        }
  }

  final String LOG_TAG = "myLogs";

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment2, null);

    Button button = (Button) v.findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        someEventListener.someEvent("Test text to Fragment1");
      }
    });

    return v;
  }
}

Activity

public class MainActivity extends Activity implements onSomeEventListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Fragment frag2 = new Fragment2();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment2, frag2);
        ft.commit();
    }

  @Override
  public void someEvent(String s) {
      Fragment frag1 = getFragmentManager().findFragmentById(R.id.fragment1);
      ((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
  }
}


问:
Copy cell value if next cell matchs
I'd like to copy the longitude/latitude value to between 2 list of countries, but not all countries name matches. I was able to use conditional format to fix some of the names. What formula can I use to copy the lon/lat value from column E/F to B/C if value in A matches D.

Link: My sheet on gDoc

答:
```<code>=IF(COUNTIF($D:$D, A2)=0,"",VLOOKUP(A2,$D:$F,2,FALSE))
</code>```

<p>is able to solve this problem after some try and error. </p>

Title: Copy cell value if next cell matchs

Body:
=IF(COUNTIF($D:$D, A2)=0,"",VLOOKUP(A2,$D:$F,2,FALSE))

is able to solve this problem after some try and error.


问:
Apples SinglePing app doesn't call delegate methods
I am trying SimplePing app from Apple. But delegate methods aren't called. I am trying to find solution, but I am also asking here for help.

Thank you.

Here is complete MainViewController class to look at.

```<code>import UIKit

class MainViewController: UITableViewController, SimplePingDelegate {

    let hostName = "www.apple.com"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = self.hostName
    }

    var pinger: SimplePing?
    var sendTimer: Timer?

    func start(forceIPv4: Bool, forceIPv6: Bool) {
        self.pingerWillStart()

        NSLog("start")

        let pinger = SimplePing(hostName: self.hostName)
        self.pinger = pinger

        if (forceIPv4 && !forceIPv6) {
            pinger.addressStyle = .icmPv4
        } else if (forceIPv6 && !forceIPv4) {
            pinger.addressStyle = .icmPv6
        }

        pinger.delegate = self
        pinger.start()
    }

    func stop() {
        NSLog("stop")
        self.pinger?.stop()
        self.pinger = nil

        self.sendTimer?.invalidate()
        self.sendTimer = nil

        self.pingerDidStop()
    }

    func sendPing() {
        self.pinger!.send(with: nil)
    }

    // MARK: pinger delegate callback

    private func simplePing(pinger: SimplePing, didStartWithAddress address: NSData) {
        NSLog("pinging %@", MainViewController.displayAddressForAddress(address: address))

        self.sendPing()

        assert(self.sendTimer == nil)
        self.sendTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MainViewController.sendPing), userInfo: nil, repeats: true)
    }

    private func simplePing(pinger: SimplePing, didFailWithError error: NSError) {
        NSLog("failed: %@", MainViewController.shortErrorFromError(error: error))

        self.stop()
    }

    private func simplePing(pinger: SimplePing, didSendPacket packet: NSData, sequenceNumber: UInt16) {
        NSLog("#%u sent", sequenceNumber)
    }

    private func simplePing(pinger: SimplePing, didFailToSendPacket packet: NSData, sequenceNumber: UInt16, error: NSError) {
        NSLog("#%u send failed: %@", sequenceNumber, MainViewController.shortErrorFromError(error: error))
    }

    private func simplePing(pinger: SimplePing, didReceivePingResponsePacket packet: NSData, sequenceNumber: UInt16) {
        NSLog("#%u received, size=%zu", sequenceNumber, packet.length)
    }

    private func simplePing(pinger: SimplePing, didReceiveUnexpectedPacket packet: NSData) {
        NSLog("unexpected packet, size=%zu", packet.length)
    }

    // MARK: utilities

    static func displayAddressForAddress(address: NSData) -> String {
        var hostStr = [Int8](repeating: 0, count: Int(NI_MAXHOST))

        let success = getnameinfo(
            address.bytes.assumingMemoryBound(to: sockaddr.self),
            //UnsafePointer(address.bytes),
            socklen_t(address.length),
            &hostStr,
            socklen_t(hostStr.count),
            nil,
            0,
            NI_NUMERICHOST
        ) == 0
        let result: String
        if success {
            result = String(cString: hostStr)
        } else {
            result = "?"
        }
        return result
    }

    /// Returns a short error string for the supplied error.
    ///
    /// - parameter error: The error to render.
    ///
    /// - returns: A short string representing that error.

    static func shortErrorFromError(error: NSError) -> String {
        if error.domain == kCFErrorDomainCFNetwork as String && error.code == Int(CFNetworkErrors.cfHostErrorUnknown.rawValue) {
            if let failureObj = error.userInfo[kCFGetAddrInfoFailureKey] {
                if let failureNum = failureObj as? NSNumber {
                    if failureNum.intValue != 0 {
                        let f = gai_strerror(Int32(failureNum.intValue))
                        if f != nil {
                            return String(cString: f!)
                        }
                    }
                }
            }
        }
        if let result = error.localizedFailureReason {
            return result
        }
        return error.localizedDescription
    }

    // MARK: table view delegate callback

    @IBOutlet var forceIPv4Cell: UITableViewCell!
    @IBOutlet var forceIPv6Cell: UITableViewCell!
    @IBOutlet var startStopCell: UITableViewCell!

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = self.tableView.cellForRow(at: indexPath as IndexPath)!
        switch cell {
        case forceIPv4Cell, forceIPv6Cell:
            cell.accessoryType = cell.accessoryType == .none ? .checkmark : .none
        case startStopCell:
            if self.pinger == nil {
                let forceIPv4 = self.forceIPv4Cell.accessoryType != .none
                let forceIPv6 = self.forceIPv6Cell.accessoryType != .none
                self.start(forceIPv4: forceIPv4, forceIPv6: forceIPv6)
            } else {
                self.stop()
            }
        default:
            fatalError()
        }
        self.tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    }

    func pingerWillStart() {
        self.startStopCell.textLabel!.text = "Stop…"
    }

    func pingerDidStop() {
        self.startStopCell.textLabel!.text = "Start…"
    }
}
</code>```

I've converted it to Swift 4 syntax, but nothing works on Simulator or real device. I tap on IPv4 or IPv6 and then start, but nothing happens.

答:
I downloaded the project from Apple and tried it myself. You probably have the wrong method signature for the didSelect event of the table view.

Make sure to change

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

 to

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)

inside the MainViewController.swift.

I hope this fixes your issue.

Edit: You also need to change the signature of all delegate methods in your MainViewController.swift. For example func simplePing(pinger: SimplePing, didFailWithError error: NSError) should become func simplePing(_ pinger: SimplePing, didFailWithError error: Error).

Body:
I am trying SimplePing app from Apple. But delegate methods aren't called. I am trying to find solution, but I am also asking here for help.

Thank you.

Here is complete MainViewController class to look at.

import UIKit

class MainViewController: UITableViewController, SimplePingDelegate {

    let hostName = "www.apple.com"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = self.hostName
    }

    var pinger: SimplePing?
    var sendTimer: Timer?

    func start(forceIPv4: Bool, forceIPv6: Bool) {
        self.pingerWillStart()

        NSLog("start")

        let pinger = SimplePing(hostName: self.hostName)
        self.pinger = pinger

        if (forceIPv4 && !forceIPv6) {
            pinger.addressStyle = .icmPv4
        } else if (forceIPv6 && !forceIPv4) {
            pinger.addressStyle = .icmPv6
        }

        pinger.delegate = self
        pinger.start()
    }

    func stop() {
        NSLog("stop")
        self.pinger?.stop()
        self.pinger = nil

        self.sendTimer?.invalidate()
        self.sendTimer = nil

        self.pingerDidStop()
    }

    func sendPing() {
        self.pinger!.send(with: nil)
    }

    // MARK: pinger delegate callback

    private func simplePing(pinger: SimplePing, didStartWithAddress address: NSData) {
        NSLog("pinging %@", MainViewController.displayAddressForAddress(address: address))

        self.sendPing()

        assert(self.sendTimer == nil)
        self.sendTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MainViewController.sendPing), userInfo: nil, repeats: true)
    }

    private func simplePing(pinger: SimplePing, didFailWithError error: NSError) {
        NSLog("failed: %@", MainViewController.shortErrorFromError(error: error))

        self.stop()
    }

    private func simplePing(pinger: SimplePing, didSendPacket packet: NSData, sequenceNumber: UInt16) {
        NSLog("#%u sent", sequenceNumber)
    }

    private func simplePing(pinger: SimplePing, didFailToSendPacket packet: NSData, sequenceNumber: UInt16, error: NSError) {
        NSLog("#%u send failed: %@", sequenceNumber, MainViewController.shortErrorFromError(error: error))
    }

    private func simplePing(pinger: SimplePing, didReceivePingResponsePacket packet: NSData, sequenceNumber: UInt16) {
        NSLog("#%u received, size=%zu", sequenceNumber, packet.length)
    }

    private func simplePing(pinger: SimplePing, didReceiveUnexpectedPacket packet: NSData) {
        NSLog("unexpected packet, size=%zu", packet.length)
    }

    // MARK: utilities

    static func displayAddressForAddress(address: NSData) -> String {
        var hostStr = [Int8](repeating: 0, count: Int(NI_MAXHOST))

        let success = getnameinfo(
            address.bytes.assumingMemoryBound(to: sockaddr.self),
            //UnsafePointer(address.bytes),
            socklen_t(address.length),
            &hostStr,
            socklen_t(hostStr.count),
            nil,
            0,
            NI_NUMERICHOST
        ) == 0
        let result: String
        if success {
            result = String(cString: hostStr)
        } else {
            result = "?"
        }
        return result
    }

    /// Returns a short error string for the supplied error.
    ///
    /// - parameter error: The error to render.
    ///
    /// - returns: A short string representing that error.

    static func shortErrorFromError(error: NSError) -> String {
        if error.domain == kCFErrorDomainCFNetwork as String && error.code == Int(CFNetworkErrors.cfHostErrorUnknown.rawValue) {
            if let failureObj = error.userInfo[kCFGetAddrInfoFailureKey] {
                if let failureNum = failureObj as? NSNumber {
                    if failureNum.intValue != 0 {
                        let f = gai_strerror(Int32(failureNum.intValue))
                        if f != nil {
                            return String(cString: f!)
                        }
                    }
                }
            }
        }
        if let result = error.localizedFailureReason {
            return result
        }
        return error.localizedDescription
    }

    // MARK: table view delegate callback

    @IBOutlet var forceIPv4Cell: UITableViewCell!
    @IBOutlet var forceIPv6Cell: UITableViewCell!
    @IBOutlet var startStopCell: UITableViewCell!

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = self.tableView.cellForRow(at: indexPath as IndexPath)!
        switch cell {
        case forceIPv4Cell, forceIPv6Cell:
            cell.accessoryType = cell.accessoryType == .none ? .checkmark : .none
        case startStopCell:
            if self.pinger == nil {
                let forceIPv4 = self.forceIPv4Cell.accessoryType != .none
                let forceIPv6 = self.forceIPv6Cell.accessoryType != .none
                self.start(forceIPv4: forceIPv4, forceIPv6: forceIPv6)
            } else {
                self.stop()
            }
        default:
            fatalError()
        }
        self.tableView.deselectRow(at: indexPath as IndexPath, animated: true)
    }

    func pingerWillStart() {
        self.startStopCell.textLabel!.text = "Stop…"
    }

    func pingerDidStop() {
        self.startStopCell.textLabel!.text = "Start…"
    }
}

I've converted it to Swift 4 syntax, but nothing works on Simulator or real device. I tap on IPv4 or IPv6 and then start, but nothing happens.


问:
Use a service for child components without having to inject it in the constructor
I want to use a service for getting information about the current coins the app supports.

Therefore I have created the Service: CoinsService

```<code>import { Injectable } from '@angular/core';

const coins = {
  "btc":"bitcoin",
  "ltc":"litecoin"
};

@Injectable()
export class CoinsService {

  getCoins(){
    return coins;
  }

  getSpecificCoin(coinShortcut: string) {
    return coins[coinShortcut];
  }
}
</code>```

My user class looks like this:

```<code>import { CoinsService } from './coins.service';

export class User {
  constructor(public id: number, public balance: number, public coinsService: CoinsService) {
    console.log(coinsService.getCoins());
  }
}
</code>```

Before the service if I wanted to create a user I did it like this:
let userA = new User('1','200');

Now with the service I need to pass in the coinService at object creation:
let userA = new User('1','200', coinService)

For wholeness I post also the app.component.ts:

```<code>import { Component } from '@angular/core';
import { User } from './user';
import { CoinsService } from './coins.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CoinsService]
})
export class AppComponent {
  title = 'app';

  constructor(private coinsService: CoinsService){
      let userA = new User(1, 200, coinsService);
  }
}
</code>```

Are there any other options to be able to use the service in the User class without
"passing it down" to the component which actually needs it?

I would like to create users without explicitly telling it everytime for every user that it needs a CoinsService.

It should be the standard that every user that gets created has access to it.

Also the service should be able to be used in every component below the App.Component.
That's why I entered the CoinssService in the providers array.

Any help is appreciated.

答:
You can make the method static and call it from everywhere

```<code>@Injectable()
export class CoinsService {

  static getCoins(){
    return coins;
  }

  getSpecificCoin(coinShortcut: string) {
    return coins[coinShortcut];
  }
}
</code>```

```<code>import { CoinsService } from './coins.service';

export class User {
  constructor(public id: number, public balance: number) {
    console.log(CoinsService.getCoins());
  }
}
</code>```

Be careful when using static properties though, they are like a global/shared property. If you change a static property, it will change in all of the instances of that class.

More info: What does the 'static' keyword do in a class?

Body:
I want to use a service for getting information about the current coins the app supports.

Therefore I have created the Service: CoinsService

import { Injectable } from '@angular/core';

const coins = {
  "btc":"bitcoin",
  "ltc":"litecoin"
};

@Injectable()
export class CoinsService {

  getCoins(){
    return coins;
  }

  getSpecificCoin(coinShortcut: string) {
    return coins[coinShortcut];
  }
}

My user class looks like this:

import { CoinsService } from './coins.service';

export class User {
  constructor(public id: number, public balance: number, public coinsService: CoinsService) {
    console.log(coinsService.getCoins());
  }
}

Before the service if I wanted to create a user I did it like this:
let userA = new User('1','200');

Now with the service I need to pass in the coinService at object creation:
let userA = new User('1','200', coinService)

For wholeness I post also the app.component.ts:

import { Component } from '@angular/core';
import { User } from './user';
import { CoinsService } from './coins.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [CoinsService]
})
export class AppComponent {
  title = 'app';

  constructor(private coinsService: CoinsService){
      let userA = new User(1, 200, coinsService);
  }
}

Are there any other options to be able to use the service in the User class without
"passing it down" to the component which actually needs it?

I would like to create users without explicitly telling it everytime for every user that it needs a CoinsService.

It should be the standard that every user that gets created has access to it.

Also the service should be able to be used in every component below the App.Component.
That's why I entered the CoinssService in the providers array.

Any help is appreciated.

Body:
You can make the method static and call it from everywhere

@Injectable()
export class CoinsService {

  static getCoins(){
    return coins;
  }

  getSpecificCoin(coinShortcut: string) {
    return coins[coinShortcut];
  }
}

import { CoinsService } from './coins.service';

export class User {
  constructor(public id: number, public balance: number) {
    console.log(CoinsService.getCoins());
  }
}

Be careful when using static properties though, they are like a global/shared property. If you change a static property, it will change in all of the instances of that class.

More info: What does the 'static' keyword do in a class?


问:
How to get the current database name in Impala? I actually googled a lot for this, but i didn't find anything related
I have a requirement to show the name of the TABLE NAME , DATABASE NAME and ROW COUNT of the given table using IMPALA,
i am able to show the ROW COUNT  and TABLE NAME using below query and got stuck in getting current database name,I actually googled a lot but i didn't find anything related.
any one can help me in this?</p>

```<code>select count(*) as rowcount,'table name' from table1
union
select count(*) as rowcount,'table name' from table2
union
select count(*) as rowcount,'table name' from table3
union
select count(*) as rowcount,'table name' from table4
</code>```

答: From this https://issues.apache.org/jira/browse/IMPALA-675 , you can use select current_database() to get the database name.

Body:
I have a requirement to show the name of the TABLE NAME , DATABASE NAME and ROW COUNT of the given table using IMPALA,
i am able to show the ROW COUNT  and TABLE NAME using below query and got stuck in getting current database name,I actually googled a lot but i didn't find anything related.
any one can help me in this?

select count(*) as rowcount,'table name' from table1
union
select count(*) as rowcount,'table name' from table2
union
select count(*) as rowcount,'table name' from table3
union
select count(*) as rowcount,'table name' from table4


问:
How to ignore javascript timezone to send a datetime to server
I am building a web app with c# and angular to store event schedule. The user will input a date time which is in UTC and I want to save that time in db exactly as inputted. And then show exactly same time when a user will view this information. And this should not depend on user's timezone, and I am telling the user that time is in UTC.

But the problem is browser send time information with timezone info when ajax post to server and server saves a different time (by converting its own timezone) in db as the server is in a different timezone.

How to prevent this?

答:
So if you are using html5 datetime,then you can change it to datetime-local

```<code><input type="datetime-local">
</code>```

This will give you datetime without the timezone info.

Here is an example.

var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';

let btn = document.getElementById('btns');
let inp = document.getElementById('party');
let dv = document.getElementById('displayValue');
btn.addEventListener('click', ()=>{
  dv.innerText = inp.value;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label for="party">Enter a date and time for your party booking:</label>
<input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30">

<button type="submit" id="btns">Check Value</button>

<div id="displayValue">

</div></code>```

Code snippet is just to give you an idea on how to use datetime-local.
If you are using angular 2/4, then you can directly bind ngModel to a variable as you would do generally to get the value.

Body:
So if you are using html5 datetime,then you can change it to datetime-local

<input type="datetime-local">

This will give you datetime without the timezone info.

Here is an example.

var dateControl = document.querySelector('input[type="datetime-local"]');
dateControl.value = '2017-06-01T08:30';

let btn = document.getElementById('btns');
let inp = document.getElementById('party');
let dv = document.getElementById('displayValue');
btn.addEventListener('click', ()=>{
  dv.innerText = inp.value;
});

<label for="party">Enter a date and time for your party booking:</label>
<input id="party" type="datetime-local" name="partydate" value="2017-06-01T08:30">

<button type="submit" id="btns">Check Value</button>

<div id="displayValue">

</div>

Code snippet is just to give you an idea on how to use datetime-local.
If you are using angular 2/4, then you can directly bind ngModel to a variable as you would do generally to get the value.


问:
How to extract apple's 1 billion countdown?
I've been trying to figure it out for hours and i didn't success, This Counter from Apple 1 billion downloads prize. doesn't use flash at all, only javascript and 0-9 images, which makes it really cool. Now after stackoverflow successed to extract google's pacman, can we do that?

P.S I can't even know if this is using prototype or scriptaculous since they're both included.

答:
The hearth of the whole script is this single image: http://images.apple.com/itunes/10-billion-app-countdown/images/filmstrip.png

Now everything should be obvious.

HTML placeholder for a single digit:

```<code><div class="digit-placeholder"></div>
</code>```

CSS that styles that placeholder:

```<code>.digit-placeholder {
     /* Dimensions of a single "frame" */
     width: 50px;
     height: 75px;

     background-image: url(...);
     background-position: 0 0;
}
</code>```

To display digit 7 you just have to move background (background-positon property) to the following coordinates: 0 -2800px (that's only an example). To display 8 move it to 0 -3400px.

To create an animation (change from 7 to 8) you just have to move background from -2800 to -3400 with a step of 60 in some period of time (let's say 0.5 second).

All you have to do is to clone that several times (10 times for one billion) and compute that period of time for each digit.

Body:
The hearth of the whole script is this single image: http://images.apple.com/itunes/10-billion-app-countdown/images/filmstrip.png

Now everything should be obvious.

HTML placeholder for a single digit:

<div class="digit-placeholder"></div>

CSS that styles that placeholder:

.digit-placeholder {
     /* Dimensions of a single "frame" */
     width: 50px;
     height: 75px;

     background-image: url(...);
     background-position: 0 0;
}

To display digit 7 you just have to move background (background-positon property) to the following coordinates: 0 -2800px (that's only an example). To display 8 move it to 0 -3400px.

To create an animation (change from 7 to 8) you just have to move background from -2800 to -3400 with a step of 60 in some period of time (let's say 0.5 second).

All you have to do is to clone that several times (10 times for one billion) and compute that period of time for each digit.


问:
Stuck with my query
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

```<code>select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;
</code>```

Where am I making the mistake?

Thanks in advance!

答:
You can use an analytic function to find the maximum salary - this negates the need to query the table twice:

```<code>select ename,
       sal,
       max(sal) over () max_overall_sal,
       max(sal) over (partition by deptno) max_sal_per_dept
from   emp;
</code>```

I've given you two ways to find the max salary - one across the whole data set (over ()) and one per department (over (partition by deptno)) since I wasn't sure which you wanted.

If you are unfamiliar with analytic functions, I highly recommend you look them up. In their basic form, they're similar to how aggregate functions work, except instead of collapsing the rows, they report the value for each row. The partition by clause groups the data in the same way as the group by does in an aggregate query.

Title: Stuck with my query

Body:
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;

Where am I making the mistake?

Thanks in advance!

Body:
You can use an analytic function to find the maximum salary - this negates the need to query the table twice:

select ename,
       sal,
       max(sal) over () max_overall_sal,
       max(sal) over (partition by deptno) max_sal_per_dept
from   emp;

I've given you two ways to find the max salary - one across the whole data set (over ()) and one per department (over (partition by deptno)) since I wasn't sure which you wanted.

If you are unfamiliar with analytic functions, I highly recommend you look them up. In their basic form, they're similar to how aggregate functions work, except instead of collapsing the rows, they report the value for each row. The partition by clause groups the data in the same way as the group by does in an aggregate query.


问:
PostgreSQL: append elements to jsonb array only if element is unique
I created a PostgreSQL (v10.0) table with a jsonb-array column as follows:

```<code>CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')
</code>```

Then I want add new animals to the first row as follows:

```<code>UPDATE test
SET animals = animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb
WHERE id = 1;
</code>```

However, I want to append only those elements that are not yet in the array. In this case only [chicken, 2].

答:
probably simplest would be:</p>

```<code>t=# with c as (select distinct e,min(o) over (partition by e) o from test, jsonb_array_elements(animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb) with ordinality t(e,o) where id =1)
, r as (select jsonb_agg(e order by o) z from c)
t-# update test set animals = z from r where id = 1;
UPDATE 1
t=# select * from test;
 id |                             animals
----+------------------------------------------------------------------
  2 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]
  1 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]", "[chicken, 2]"]
(2 rows)
</code>```

Body:
I created a PostgreSQL (v10.0) table with a jsonb-array column as follows:

CREATE TABLE test (id INT, animals jsonb)

INSERT INTO test VALUES
   (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'),
   (2, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]')

Then I want add new animals to the first row as follows:

UPDATE test
SET animals = animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb
WHERE id = 1;

However, I want to append only those elements that are not yet in the array. In this case only [chicken, 2].

Body:
probably simplest would be:

t=# with c as (select distinct e,min(o) over (partition by e) o from test, jsonb_array_elements(animals || '["[hamsters, 7]", "[chicken, 2]"]'::jsonb) with ordinality t(e,o) where id =1)
, r as (select jsonb_agg(e order by o) z from c)
t-# update test set animals = z from r where id = 1;
UPDATE 1
t=# select * from test;
 id |                             animals
----+------------------------------------------------------------------
  2 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]
  1 | ["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]", "[chicken, 2]"]
(2 rows)


答:
Don't pass the service itself, pass the url or the method to call in the coinService like "dollarUrl" "euroUrl" which can be used in your URL or function call. 'this.coinService.' + coinMethod + '(params)...

If you need coinService for every user, then use coinService in your userService constructor and call it from here..

Title: Use a service for child components without having to inject it in the constructor


答:
Before I go to bed:

```<code>var number = '';
$('.digitImage').each(function(i) {
    number += Math.abs($(this).position().top) / 618;
});
console.log(+number);
</code>```

Now how long did that take? 3 minutes trying to figure out how do install a bookmarklet in chrome for injecting jQuery... 5 more minutes to get it working.

Title: How to extract apple's 1 billion countdown?

Body:
I've been trying to figure it out for hours and i didn't success, This Counter from Apple 1 billion downloads prize. doesn't use flash at all, only javascript and 0-9 images, which makes it really cool. Now after stackoverflow successed to extract google's pacman, can we do that?

P.S I can't even know if this is using prototype or scriptaculous since they're both included.

Body:
Before I go to bed:

var number = '';
$('.digitImage').each(function(i) {
    number += Math.abs($(this).position().top) / 618;
});
console.log(+number);

Now how long did that take? 3 minutes trying to figure out how do install a bookmarklet in chrome for injecting jQuery... 5 more minutes to get it working.