问:
dependency inversion in top class (main)
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

```<code>MainApp - - - > IModel
                  ^
                  |
                  |
                Model
</code>```

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

```<code>MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel
</code>```

Is this the correct approach and does this mean that any start of a well designed app is a factory?

答:
It sounds like you are asking for a way to enable late binding. Programming to an interface is the first step, and you are already doing that.

The next step is to map the interface to a concrete class. The easiest way to do that is with a DI Container. You Main method might now look like this:

```<code>static void Main()
{
    var container = CreateContainer();
    IModel model = container.Resolve<IModel>();
    // use model...
}
</code>```

I omitted the implementation of the CreateContainer helper method on purpose because selecting a DI Container is a different question.

All mainstream DI Containers for .NET support late binding, so this will enable you to implement the IModel in another assembly. The IModel interface should stay with the consumer (Main).

Body:
i want to create an app in which i have these two classes, MainApp and Model (in reality more, but this is the base and the core of the problem). MainApp is also the starting class. I want to apply dependency inversion so mainApp doesn't have to be rebuild each time Model changes (Well, mainly because its good practice). I can't do this:

MainApp - - - > IModel
                  ^
                  |
                  |
                Model

because i'd have to create Model in MainApp anyway because it's the start of my app, it would be redundant.

I was thinking about shifting the contents of MainApp to another class and use MainApp just as factory for MainAppContents and Model, like this:

MainApp -------------> Model
   |                     |
   |                     |
   v                     v
MainAppContents - - - > IModel

Is this the correct approach and does this mean that any start of a well designed app is a factory?

Body:
It sounds like you are asking for a way to enable late binding. Programming to an interface is the first step, and you are already doing that.

The next step is to map the interface to a concrete class. The easiest way to do that is with a DI Container. You Main method might now look like this:

static void Main()
{
    var container = CreateContainer();
    IModel model = container.Resolve<IModel>();
    // use model...
}

I omitted the implementation of the CreateContainer helper method on purpose because selecting a DI Container is a different question.

All mainstream DI Containers for .NET support late binding, so this will enable you to implement the IModel in another assembly. The IModel interface should stay with the consumer (Main).


来源: stackexchange

问:
Write a function ASTERISK in C++ Programming
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

```<code>Please enter a number: 10
* * * * * * * * * *
</code>```

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

```<code>#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}
</code>```

答:
Like others already mentioned the issue is that you output the returnvalue of ASTERISK(i) using cout << ASTERISK(i)

In fact you do not need this returnvalue at all, since your function never uses it (it does not even get initialised, which causes undefined behavior), so it would be best to leave it out all together.

The use of global variables in this use case seem not really necessary either, so I would suggest using local variables, so I would suggest changing to

```<code>void ASTERISK (int number);
int main ()
{
    std::cout << "Enter a number: " ;
    int number;
    std::cin >> number;
    ASTERISK(number);
    return 0;
}

void ASTERISK (int number){
    for (int i=0; i!=number; ++i){
        std::cout << "* ";
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I did a coding that accepts an integer from the user, and output the corresponding number of asterisks. For example:

Please enter a number: 10
* * * * * * * * * *

I must use function concept to complete the coding only. I managed to get the correct number of asterisks but the '0' at the back just won't disappear.

#include<iostream>
using namespace std;

int NUMBER, i;
int ASTERISK (int NUMBER);
int main ()

{
    cout << "Enter a number: " ;
    cin >> i ;
    cout << ASTERISK (i);
    return 0;
}

int ASTERISK (int NUMBER){
    int ANSWER;
    for (NUMBER=1; NUMBER<=i; NUMBER=NUMBER+1){
        cout << "* " ;
    }
    return ANSWER;
}

Body:
Like others already mentioned the issue is that you output the returnvalue of ASTERISK(i) using cout << ASTERISK(i)

In fact you do not need this returnvalue at all, since your function never uses it (it does not even get initialised, which causes undefined behavior), so it would be best to leave it out all together.

The use of global variables in this use case seem not really necessary either, so I would suggest using local variables, so I would suggest changing to

void ASTERISK (int number);
int main ()
{
    std::cout << "Enter a number: " ;
    int number;
    std::cin >> number;
    ASTERISK(number);
    return 0;
}

void ASTERISK (int number){
    for (int i=0; i!=number; ++i){
        std::cout << "* ";
    }
}


问:
By clicking one checkbox other checkbox should be disable
I've 2 columns with checkboxes when one column is checked all respective are checked likewise in 2nd column but the problem is here, client wants when One column of checkbox is checked then 2nd column will be disable or throw alert message to check only one column at a time?

```<code>function SelectAll1(headerchk, gridId) {

        var gvcheck = document.getElementById(gridId);
        var i, j;
        if (headerchk.checked) {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
               for (j = 1; j < inputs.length; j++) {
                 if (inputs[j].type == "checkbox") {
                        inputs[j].checked = true;
                    }
                }
            }
        }
        else {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                 for (j = 1; j < inputs.length; j++) {
                   if (inputs[j].type == "checkbox") {
                        inputs[j].checked = false;
                    }
                }
            }
        }
    }
</code>```

You can ch

答:
I don't really know what you're trying to do without the HTML but here's a start you can build off.

var selected = $('.check:checked').length;

if (selected >= 1) {
  $('.check').prop('disabled', true);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check" checked="checked">
<input type="checkbox" class="check">
<input type="checkbox" class="check"></code>```

Body:
I've 2 columns with checkboxes when one column is checked all respective are checked likewise in 2nd column but the problem is here, client wants when One column of checkbox is checked then 2nd column will be disable or throw alert message to check only one column at a time?

function SelectAll1(headerchk, gridId) {

        var gvcheck = document.getElementById(gridId);
        var i, j;
        if (headerchk.checked) {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
               for (j = 1; j < inputs.length; j++) {
                 if (inputs[j].type == "checkbox") {
                        inputs[j].checked = true;
                    }
                }
            }
        }
        else {
            for (i = 0; i < gvcheck.rows.length - 1; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                 for (j = 1; j < inputs.length; j++) {
                   if (inputs[j].type == "checkbox") {
                        inputs[j].checked = false;
                    }
                }
            }
        }
    }

You can ch

Body:
I don't really know what you're trying to do without the HTML but here's a start you can build off.

var selected = $('.check:checked').length;

if (selected >= 1) {
  $('.check').prop('disabled', true);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="check" checked="checked">
<input type="checkbox" class="check">
<input type="checkbox" class="check">


问:
Unit Test NGRX effect with Marbles for an external URL
When an effect is triggered, i would like to test both observables in unit test, to get a 100% code coverage for this part of code. because a window.location.href is triggered, I can't test it correctly.

```<code>export class RouteHelper {
    static redirectToExternalUrl(url: string): any {
        window.location.href = url;
    }
}
</code>```

Effect

```<code>@Effect()
handleCreatePaymentSuccess$: Observable<
    {} | routerActions.Go
> = this.actions$.pipe(
    ofType(cartConfigActions.CREATE_PAYMENT_SUCCESS),
    switchMap((action: any) => {
        if (action.payload.redirect) {
            /* istanbul ignore next */
            return Observable.create(
                RouteHelper.redirectToExternalUrl(action.payload.redirect),
            );
        } else {
            return of(
                new routerActions.Go({
                    path: [RouteHelper.paths['validate']],
                }),
            );
        }
    }),
);
</code>```

Test working for the else condition

```<code>it('should dispatch router action Go on success if no redirect url is provided', () => {
    const payload = { redirect: null };
    const action = new fromCartConfig.CreatePaymentSuccess(payload);
    const completion = new routeractions.Go({
        path: [RouteHelper.paths['validate']],
    });

    actions$.stream = cold('-a', { a: action });
    const expected = cold('-c', { c: completion });

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});
</code>```

Test not working for the if condition

```<code>it('should redirect to url that is returned from api', () => {
    const payload = { redirect: 'http://www.stackoverflow.com' };
    spyOn(RouteHelper, 'redirectToExternalUrl').withArgs(payload.redirect);

    const action = new fromCartConfig.CreatePaymentSuccess(payload);
    const completion = Observable.create(RouteHelper.redirectToExternalUrl);

    actions$.stream = cold('-a', { a: action });
    const expected = cold('-c', { c: completion });

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});
</code>```

Can someone explain how to test the If condition?

答:
Solution:</p>

```<code>it('should dispatch router action Go on success if redirect url is provided', () => {
    spyOn(RouteHelper, 'redirectToExternalUrl').and.callFake(() => {});
    const payload = { redirect: 'www.buckaroo.nl' };
    const action = new fromCartConfig.CreatePaymentSuccess(payload);

    actions$.stream = cold('-a', { a: action });
    const expected = cold('');

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
    expect(RouteHelper.redirectToExternalUrl).toHaveBeenCalled();
});
</code>```

Body:
When an effect is triggered, i would like to test both observables in unit test, to get a 100% code coverage for this part of code. because a window.location.href is triggered, I can't test it correctly.

export class RouteHelper {
    static redirectToExternalUrl(url: string): any {
        window.location.href = url;
    }
}

Effect

@Effect()
handleCreatePaymentSuccess$: Observable<
    {} | routerActions.Go
> = this.actions$.pipe(
    ofType(cartConfigActions.CREATE_PAYMENT_SUCCESS),
    switchMap((action: any) => {
        if (action.payload.redirect) {
            /* istanbul ignore next */
            return Observable.create(
                RouteHelper.redirectToExternalUrl(action.payload.redirect),
            );
        } else {
            return of(
                new routerActions.Go({
                    path: [RouteHelper.paths['validate']],
                }),
            );
        }
    }),
);

Test working for the else condition

it('should dispatch router action Go on success if no redirect url is provided', () => {
    const payload = { redirect: null };
    const action = new fromCartConfig.CreatePaymentSuccess(payload);
    const completion = new routeractions.Go({
        path: [RouteHelper.paths['validate']],
    });

    actions$.stream = cold('-a', { a: action });
    const expected = cold('-c', { c: completion });

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});

Test not working for the if condition

it('should redirect to url that is returned from api', () => {
    const payload = { redirect: 'http://www.stackoverflow.com' };
    spyOn(RouteHelper, 'redirectToExternalUrl').withArgs(payload.redirect);

    const action = new fromCartConfig.CreatePaymentSuccess(payload);
    const completion = Observable.create(RouteHelper.redirectToExternalUrl);

    actions$.stream = cold('-a', { a: action });
    const expected = cold('-c', { c: completion });

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
});

Can someone explain how to test the If condition?

Body:
Solution:

it('should dispatch router action Go on success if redirect url is provided', () => {
    spyOn(RouteHelper, 'redirectToExternalUrl').and.callFake(() => {});
    const payload = { redirect: 'www.buckaroo.nl' };
    const action = new fromCartConfig.CreatePaymentSuccess(payload);

    actions$.stream = cold('-a', { a: action });
    const expected = cold('');

    expect(effects.handleCreatePaymentSuccess$).toBeObservable(expected);
    expect(RouteHelper.redirectToExternalUrl).toHaveBeenCalled();
});


问:
How do I dynamically assign the number of cores per node?
```<code>#!/bin/bash
#SBATCH --job-name=Parallel# Job name
#SBATCH --output=slurmdiv.out# Output file name
#SBATCH --error=slurmdiv.err # Error file name
#SBATCH --partition=hadoop# Queue
#SBATCH --nodes = 1
#SBATCH --time=01:00:00# Time limit
</code>```

The above script does not work without specifying --ntasks-per-node directive. The number of cores per node depends on the queue being used. I would like to assign the maximum number of cores per node without having to specify it ahead of time in the slurm script. I'm using this to run an R script that uses detectCores() and mclapply.

答: You can try adding the #SBATCH --exclusive  parameter to your submission script so that Slurm will allocate a full node for your job, without the need to specify explicitly a specific number of tasks. Then you can use detectCores() in your script.

Body:
#!/bin/bash
#SBATCH --job-name=Parallel# Job name
#SBATCH --output=slurmdiv.out# Output file name
#SBATCH --error=slurmdiv.err # Error file name
#SBATCH --partition=hadoop# Queue
#SBATCH --nodes = 1
#SBATCH --time=01:00:00# Time limit

The above script does not work without specifying --ntasks-per-node directive. The number of cores per node depends on the queue being used. I would like to assign the maximum number of cores per node without having to specify it ahead of time in the slurm script. I'm using this to run an R script that uses detectCores() and mclapply.


问:
ViewBag values are not displaying in a select box?
list of values in ViewBag and want to display this values in a select box.The values are coming inside of the view.But it isn't displaying .
Codeblock:

```<code> <select name="postoffice">
       <option>-select-</option>
                    @if (ViewBag.s != null)
                    {
                       foreach (var f in ViewBag.s)
                        {
                         <option value="@f.po">@f.po</option>

                        }
                     }
 </select>
</code>```

答: you need to cast ViewBag.s in specific format before implement foreach loop (List) ViewBag.s</p>

Body:
list of values in ViewBag and want to display this values in a select box.The values are coming inside of the view.But it isn't displaying .
Codeblock:

 <select name="postoffice">
       <option>-select-</option>
                    @if (ViewBag.s != null)
                    {
                       foreach (var f in ViewBag.s)
                        {
                         <option value="@f.po">@f.po</option>

                        }
                     }
 </select>


问:
Checking last element of a string in a list
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)
```

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

答:
You need to remove the new line from every line of the file.

Try to replace

```<code>lines=(f.readlines())
</code>```

with

```<code>lines=[l.strip() for l in f.readlines()]
</code>```

Body:
I have got some serial communications logs to analyze regarding time, so I record messages with timestamps in format YYYY-MM-DD HH:MM:SS.ffffff:
So my file looks like this:

YYYY-MM-DD HH:MM:SS.ffffff:

few lines of bytes

YYYY-MM-DD HH:MM:SS.ffffff:

and so on...

I want to extract dates from my file so I could calculate times between messages

I want to operate on dates using datetime module, and for the beginning I wanted to get rid of the colons at the end of each date. I have read my file and saved it in variable which is a list of strings, and each element is a line. Now I want to create a second list of only dates, extracting only those lines that end with colons.

f=open("sniffinglog.txt","r")

lines=(f.readlines())
lines_number=len(lines)
i=0
dates=[]
while i<lines_number:
    if lines[i].endswith(":"):
        dates.append(lines[i])
    i+=1
print (dates)

I checked that lines is created correctly, however there are no elements appended to the list dates. It remains empty. Is there something wrong with my ifcondition? Or is there another way of checking last character of a string if it is a list element?

Body:
You need to remove the new line from every line of the file.

Try to replace

lines=(f.readlines())

with

lines=[l.strip() for l in f.readlines()]


问:
Android: Null Pointer Exception at Text View
Here is a code for which I face the Exception

```<code>public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}
</code>```

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

```<code>**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**
</code>```

Can you help me?

答: Move setContentView(R.layout.main); before doing tv=(TextView)findViewById(R.id.txt1);

ContentLicense: CC BY-SA 3.0

Body:
Here is a code for which I face the Exception

public class SHOSuper extends Activity{

String officerName;
String arr[];
String[] offN;
public void onCreate(Bundle savedInstanceState) {
    try{
        super.onCreate(savedInstanceState);
        final TextView tv;
        tv=(TextView)findViewById(R.id.txt1);
        System.out.println("I AM NEW ACTIVITY");
        arr=Receiver.split(Receiver.orignal, ",");
        String value1= arr[1];
        System.out.println("Array index " + value1);
        String value2=arr[2];
        System.out.println("Array 2nd index " + value2);
        tv.setText(value1 + " At " + value2);
        officerName= arr[5];
        offN =new String[officerName.length()];
        offN=Receiver.split(officerName, "_");
    }
    catch(Exception e){
        e.printStackTrace();
    }

setContentView(R.layout.main);
  }
}

On line tv.setText(value1 + " At " + value2); I face Null pointer Exception like this

**04-12 13:25:18.105: WARN/System.err(527): java.lang.NullPointerException
04-12 13:25:18.265: WARN/System.err(527):     at com.sho.SHOSuper.onCreate(SHOSuper.java:24)**

Can you help me?


答:
I think that this could help:

```<code>library(lattice)
xyplot(
  Arima + BuyHold ~ Date,                                   # here you can add log() to the two ts
  data=plotData,
  superpose=T,
  col=c("#cc0000", "#0073e6"),                              # similar colors
  lwd=2,
  key=list(
     text  = list(c("ARIMA+GARCH log", "Buy & Hold log")),
     lines = list( lwd=2, col=c("#cc0000", "#0073e6"))      # similar colors
  ), type=c("l","g")                                        # lines and grid
)
</code>```

If you want to reduce the number of ticks on the x axis, you'd create your labels, and add them in this way (in this case, one year, you'd calculate your full time series parameters):

```<code>x.tick.number <- 1
at <- seq(1, nrow(d), length.out=x.tick.number)
labels <- round(seq(2001, 2001, length.out=x.tick.number))
</code>```

In the plot:

```<code>xyplot(
  Arima + BuyHold ~ Date,                                   # here you can add log() to the two ts
  data=d,
  superpose=T,
  col=c("#cc0000", "#0073e6"),
  lwd=2,
  key=list(
    text  = list(c("ARIMA+GARCH log", "Buy & Hold log")),
    lines = list( lwd=2, col=c("#cc0000", "#0073e6"))
  ), type=c("l","g"),
  scales = list(at=at, labels=labels, rot=90))
</code>```

Title: How to xyplot multiple lines in R

Body:
I would like to plot graphs with multiple lines in R like this:

2 lines

x axis is date

y axis is the log return

I have data in 3 vectors

print(class(TradeDate))
print(class(ArimaGarchCurve))
print(class(CompareCurve))
---------------------------------------------
[1] "factor"
[1] "numeric"
[1] "numeric"

I search and found that xyplot may be useful, but I don't know how to use it. I have tried.

pdf("Testing.pdf")
plotData <- data.frame(Date=TradeDate,
                       Arima=ArimaGarchCurve,
                       BuyHold=BuyHoldCurve)
print(xyplot(
    Arima ~ Date,
    data=plotData,
    superpose=T,
    col=c("darkred", "darkblue"),
    lwd=2,
    key=list(
        text=list(
            c("ARIMA+GARCH", "Buy & Hold")
        ),
        lines=list(
            lwd=2, col=c("darkred", "darkblue")
        )
    )
))
dev.off()

Here is the result:

Learn from here

Thank you very much.

dput(head(plotData,20))
structure(list(Date = structure(1:20, .Label = c("2001-12-03",
"2001-12-04", "2001-12-05", "2001-12-06", "2001-12-07", "2001-12-10",
"2001-12-11", "2001-12-12", "2001-12-13", "2001-12-14", "2001-12-17",
"2001-12-18", "2001-12-19", "2001-12-20", "2001-12-21", "2001-12-24",
"2001-12-25", "2001-12-26", "2001-12-27", "2001-12-28", "2001-12-31",
"2002-01-01", "2002-01-02", "2002-01-03", "2002-01-04", "2002-01-07",
"2019-05-22", "2019-05-23"), class = "factor"), Arima = c(-0.0134052258713131,
-0.00542641764174324, 0.0128513670753771, 0.0282761455973665,
0.0179931884968989, 0.0281714817318116, 0.0435962602538011, 0.0462004298658309,
0.0194592964361352, 0.0248069155406948, 0.032807001046888, 0.0381120657516546,
0.0381120657516546, 0.030090589527961, -0.0146168717909267, -0.00630652663076437,
-0.00630652663076437, -0.00630652663076437, 0.0100429785563596,
0.0100429785563596), BuyHold = c(-0.0134052258713131, -0.00542641764174324,
0.0128513670753771, 0.0282761455973665, 0.0384544388322794, 0.0281714817318116,
0.0125050470584384, 0.0151092166704679, -0.0116319167592278,
-0.0170082867113405, -0.0090082012051471, -0.00370313650038065,
-0.00370313650038065, -0.0117246127240743, -0.056432074042962,
-0.0481217288827996, -0.0481217288827996, -0.0481217288827996,
-0.0317722236956757, -0.0317722236956757)), row.names = c(NA,
20L), class = "data.frame")

Body:
I think that this could help:

library(lattice)
xyplot(
  Arima + BuyHold ~ Date,                                   # here you can add log() to the two ts
  data=plotData,
  superpose=T,
  col=c("#cc0000", "#0073e6"),                              # similar colors
  lwd=2,
  key=list(
     text  = list(c("ARIMA+GARCH log", "Buy & Hold log")),
     lines = list( lwd=2, col=c("#cc0000", "#0073e6"))      # similar colors
  ), type=c("l","g")                                        # lines and grid
)

If you want to reduce the number of ticks on the x axis, you'd create your labels, and add them in this way (in this case, one year, you'd calculate your full time series parameters):

x.tick.number <- 1
at <- seq(1, nrow(d), length.out=x.tick.number)
labels <- round(seq(2001, 2001, length.out=x.tick.number))

In the plot:

xyplot(
  Arima + BuyHold ~ Date,                                   # here you can add log() to the two ts
  data=d,
  superpose=T,
  col=c("#cc0000", "#0073e6"),
  lwd=2,
  key=list(
    text  = list(c("ARIMA+GARCH log", "Buy & Hold log")),
    lines = list( lwd=2, col=c("#cc0000", "#0073e6"))
  ), type=c("l","g"),
  scales = list(at=at, labels=labels, rot=90))


问:
What is Clock offset in NTP server
Can someone give a clear explanation regarding the Offset of Network Time Protocol(NTP), Because currently I am Try to build two android application which works as Master and Slave?</p>

答:
This all is explained in detail at ntp.org; for example:

5.1.1.4. What happens if the Reference Time changes?

Ideally the reference time is the same everywhere in the world. Once synchronized, there should not be any unexpected changes between the clock of the operating system and the reference clock. Therefore, NTP has no special methods to handle the situation.

Instead, ntpd's reaction will depend on the offset between the local clock and the reference time.

For a tiny offset ntpd will adjust the local clock as usual; for small and larger offsets, ntpd will reject the reference time for a while. In the latter case the operation system's clock will continue with the last corrections effective while the new reference time is being rejected. After some time, small offsets (significantly less than a second) will be slewed (adjusted slowly), while larger offsets will cause the clock to be stepped (set anew). Huge offsets are rejected, and ntpd will terminate itself, believing something very strange must have happened.

Naturally, the algorithm is also applied when ntpd is started for the first time or after reboot.

Title: What is Clock offset in NTP server


问:
request.user.is_authenticated working only in the home page
I am creating a website where a user can upload documents. If user is logged out he can view other's document but not download it
if user is logged in he can download the document from the toolbar in pdf viewer

Even when I am logged out request.user.is_authenticated is false in home page but its true in other pages. So the download button does not hide nor a login button shows up.

I have tried using user.is_authenticated but it was returning true all the time

the if else condition works fine in the index page but not in doc_detail.html

urls.py

re_path(r'^all_files/(?P<doc_id>[0-9]+)/$',views.doc_detail,name = 'doc_detail'),
path('login/',auth_views.LoginView.as_view(template_name='homework/login.html'),name = 'login'),

```

<p>views.py</p>

<pre class="lang-py prettyprint-override"><code>def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))
</code>```

doc_detail.html

{{ doc.user.username }}
{{ doc.title }}
{{ doc.doc_type }}

{% if request.user.is_authenticated %}

{% else %}

    login
{% endif %}
```

<p>index page</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
This is the homework page implement upload-routine explore-routine here
{% if request.user.is_authenticated %}
the user is {{ request.user.email }} {{ request.user.profile.institution }}

{% else %}
user not logged in
{% endif %}

{% if request.user.is_authenticated %}
    logout
    update
    upload
    my uploads<br>
{% else %}
    login<br>
{% endif %}

all files
</body>
</html>
</code>```

答:
views.py

```<code>@login_required
def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))
</code>```

doc_detail.html

```<code>{% if user.is_authenticated %}
    <iframe src="{{ doc.document.url }}#toolbar=1&navpanes=0&scrollbar=1" type="application/pdf" width = "80%" height = "600px" />
{% else %}
    <iframe src="{{ doc.document.url }}#toolbar=0&navpanes=0&scrollbar=0" type="application/pdf" width = "80%" height = "600px"  />
    <a href=" url 'homework:login'">login</a>
{% endif %}
</code>```

Body:
I am creating a website where a user can upload documents. If user is logged out he can view other's document but not download it
if user is logged in he can download the document from the toolbar in pdf viewer

Even when I am logged out request.user.is_authenticated is false in home page but its true in other pages. So the download button does not hide nor a login button shows up.

I have tried using user.is_authenticated but it was returning true all the time

the if else condition works fine in the index page but not in doc_detail.html

urls.py

re_path(r'^all_files/(?P<doc_id>[0-9]+)/$',views.doc_detail,name = 'doc_detail'),
path('login/',auth_views.LoginView.as_view(template_name='homework/login.html'),name = 'login'),

views.py

def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))

doc_detail.html

{{ doc.user.username }}
{{ doc.title }}
{{ doc.doc_type }}

{% if request.user.is_authenticated %}

{% else %}

    login
{% endif %}

index page

<!DOCTYPE html>

    <title></title>

This is the homework page implement upload-routine explore-routine here
{% if request.user.is_authenticated %}
the user is {{ request.user.email }} {{ request.user.profile.institution }}

{% else %}
user not logged in
{% endif %}

{% if request.user.is_authenticated %}
    logout
    update
    upload
    my uploads

{% else %}
    login

{% endif %}

all files

Body:
views.py

@login_required
def doc_detail(request,doc_id):
    template = loader.get_template('homework/doc_detail.html')
    doc = get_object_or_404(Document, pk = doc_id)
    context = {
    'doc':doc
    }
    return HttpResponse(template.render(context,request))

doc_detail.html

{% if user.is_authenticated %}
    <iframe src="{{ doc.document.url }}#toolbar=1&navpanes=0&scrollbar=1" type="application/pdf" width = "80%" height = "600px" />
{% else %}
    <iframe src="{{ doc.document.url }}#toolbar=0&navpanes=0&scrollbar=0" type="application/pdf" width = "80%" height = "600px"  />
    <a href=" url 'homework:login'">login</a>
{% endif %}


答:
Call this function

```<code>setContentView(R.layout.main)
</code>```

before calling

```<code>tv=(TextView)findViewById(R.id.txt1);
</code>```

because findViewById() searches in the view hierarchy set by setContentView()

Title: Android: Null Pointer Exception at Text View

Body:
Call this function

setContentView(R.layout.main)

before calling

tv=(TextView)findViewById(R.id.txt1);

because findViewById() searches in the view hierarchy set by setContentView()


问:
OpenCV-python Train-LBPH recognizer
I'm writing a face recognizer in python but I'm in trouble with the  training part.

```<code>import cv2
import numpy as np
from os import listdir
from os.path import isfile, join

data_path = '/home/pi/Desktop/data'
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))]

Training_Data, Labels = [],[]

for i, files in enumerate(onlyfiles):
        image_path = data_path + onlyfiles[i]
        print(image_path)
        images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
        Training_Data.append(np.asarray(images, dtype=np.uint8))
        Labels.append(i)

Labels = np.asarray(Labels, dtype=np.int32)

model = cv2.createLBPHFaceRecognizer()

model.train( np.asarray(Training_Data) ,np.asarray(Labels) )
print("done")
</code>```

When I run it I get this error:

Traceback (most recent call last):
    File "Train_Model.py", line 17, in
      Training_Data.append(np.asarray(images, dtype=np.uint8))
    File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 460, in asarray
      return array(a, dtype, copy=False, order=order)
  TypeError: long() argument must be a string or a number, not 'NoneType'

Thank you.

答:
Add <code>/</code> in line number 6 of your code. </p>

```<code>(data_path = '/home/pi/Desktop/data/')
</code>```

Title: OpenCV-python Train-LBPH recognizer

Body:
I'm writing a face recognizer in python but I'm in trouble with the  training part.

import cv2
import numpy as np
from os import listdir
from os.path import isfile, join

data_path = '/home/pi/Desktop/data'
onlyfiles = [f for f in listdir(data_path) if isfile(join(data_path, f))]

Training_Data, Labels = [],[]

for i, files in enumerate(onlyfiles):
        image_path = data_path + onlyfiles[i]
        print(image_path)
        images = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
        Training_Data.append(np.asarray(images, dtype=np.uint8))
        Labels.append(i)

Labels = np.asarray(Labels, dtype=np.int32)

model = cv2.createLBPHFaceRecognizer()

model.train( np.asarray(Training_Data) ,np.asarray(Labels) )
print("done")

When I run it I get this error:

Traceback (most recent call last):
    File "Train_Model.py", line 17, in
      Training_Data.append(np.asarray(images, dtype=np.uint8))
    File "/usr/lib/python2.7/dist-packages/numpy/core/numeric.py", line 460, in asarray
      return array(a, dtype, copy=False, order=order)
  TypeError: long() argument must be a string or a number, not 'NoneType'

Thank you.

Body:
Add / in line number 6 of your code.

(data_path = '/home/pi/Desktop/data/')


问:
How to remove the mentioned string in a optimized way?
Hi I have a problem where I have to remove some unwanted characters from the string .
For example if the string is Hi Uim IMAGE [rofl]test then I want it to be like Hi Uim rofl test. I donot want to  hardcode IMAGE[ and than again a closing ] using replace of string. Instead of IMAGE, there can be any word in ALLCAPS.

I have written something like the below but would prefer if this can be done in a better way .

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String test = "";
        String in = "Hi Uim IMAGE [rofl] test IMAGE [rofl] notify the bull";
        String[] split = in.split("IMAGE \\[(.*?)\\]");
        System.out.println(split);
        Pattern p = Pattern.compile("IMAGE \\[(.*?)\\]");
        Matcher m = p.matcher(in);
        int i = 0;
        while (m.find()) {
            String group = m.group(1);
            System.out.println(group);
            test = test + split[i++] + group;
        }
        for (int var = i; var < split.length; var++) {
            test = test + split[var];
        }
        System.out.println(test);
    }

}
</code>```

This has a problem like I have to loop through it. Is there any better way to do this.

答:
You may use

```<code>in = in.replaceAll("\\b[A-Z]+\\s*\\[([^\\]\\[]*)]", "$1");
</code>```

See the regex demo

Regex details

\b[A-Z]+ - a word boundary and 1+ uppercase ASCII letters

\s* - 0+ whitespaces

\[ - a [ char

([^\]\[]*) - Group 1 ($1): any 0+ chars other than [ and ]

] - a ] char.

Body:
Hi I have a problem where I have to remove some unwanted characters from the string .
For example if the string is Hi Uim IMAGE [rofl]test then I want it to be like Hi Uim rofl test. I donot want to  hardcode IMAGE[ and than again a closing ] using replace of string. Instead of IMAGE, there can be any word in ALLCAPS.

I have written something like the below but would prefer if this can be done in a better way .

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {
        String test = "";
        String in = "Hi Uim IMAGE [rofl] test IMAGE [rofl] notify the bull";
        String[] split = in.split("IMAGE \\[(.*?)\\]");
        System.out.println(split);
        Pattern p = Pattern.compile("IMAGE \\[(.*?)\\]");
        Matcher m = p.matcher(in);
        int i = 0;
        while (m.find()) {
            String group = m.group(1);
            System.out.println(group);
            test = test + split[i++] + group;
        }
        for (int var = i; var < split.length; var++) {
            test = test + split[var];
        }
        System.out.println(test);
    }

}

This has a problem like I have to loop through it. Is there any better way to do this.

Body:
You may use

in = in.replaceAll("\\b[A-Z]+\\s*\\[([^\\]\\[]*)]", "$1");

See the regex demo

Regex details

\b[A-Z]+ - a word boundary and 1+ uppercase ASCII letters

\s* - 0+ whitespaces

\[ - a [ char

([^\]\[]*) - Group 1 ($1): any 0+ chars other than [ and ]

] - a ] char.


问:
Android ViewPager get the current View
I have a ViewPager, and I'd like to get the current selected and visible view, not a position.

getChildAt(getCurrentItem) returns wrong View

This works not all the time. Sometimes returns null, sometimes just returns wrong View.

```<code>@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser == true) {
        mFocusedListView = ListView;
    }
}
</code>```

PageListener on ViewPager with getChildAt() also not working, not giving me the correct View every time.

How can i get current visible View?

```<code>View view = MyActivity.mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()).getRootView();
ListView listview = (ListView) view.findViewById(R.id.ListViewItems);
</code>```

答:
I use this method with android.support.v4.view.ViewPager

```<code>View getCurrentView(ViewPager viewPager) {
        try {
            final int currentItem = viewPager.getCurrentItem();
            for (int i = 0; i < viewPager.getChildCount(); i++) {
                final View child = viewPager.getChildAt(i);
                final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();

                Field f = layoutParams.getClass().getDeclaredField("position"); //NoSuchFieldException
                f.setAccessible(true);
                int position = (Integer) f.get(layoutParams); //IllegalAccessException

                if (!layoutParams.isDecor && currentItem == position) {
                    return child;
                }
            }
        } catch (NoSuchFieldException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }
</code>```

Title: Android ViewPager get the current View

Body:
I have a ViewPager, and I'd like to get the current selected and visible view, not a position.

getChildAt(getCurrentItem) returns wrong View

This works not all the time. Sometimes returns null, sometimes just returns wrong View.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser == true) {
        mFocusedListView = ListView;
    }
}

PageListener on ViewPager with getChildAt() also not working, not giving me the correct View every time.

How can i get current visible View?

View view = MyActivity.mViewPager.getChildAt(MyActivity.mViewPager.getCurrentItem()).getRootView();
ListView listview = (ListView) view.findViewById(R.id.ListViewItems);

Body:
I use this method with android.support.v4.view.ViewPager

View getCurrentView(ViewPager viewPager) {
        try {
            final int currentItem = viewPager.getCurrentItem();
            for (int i = 0; i < viewPager.getChildCount(); i++) {
                final View child = viewPager.getChildAt(i);
                final ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) child.getLayoutParams();

                Field f = layoutParams.getClass().getDeclaredField("position"); //NoSuchFieldException
                f.setAccessible(true);
                int position = (Integer) f.get(layoutParams); //IllegalAccessException

                if (!layoutParams.isDecor && currentItem == position) {
                    return child;
                }
            }
        } catch (NoSuchFieldException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalArgumentException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }


问:
Why don't onclick events work on touchscreen but do on desktop?
I checked many posts, but looks all different and none of solutions work for me, the following is an extreme simple example, img1_click works in the newest Chrome with mouse click on desktop, but on touchscreen the img1_clickis never called, and I could see:

uncaught referenceerror img1_click is not defined

I found this post which suggests:

```<code>document.getElementById ('img1').addEventListener ("click", img1_click, false);
</code>```

However, it is still not working!

I define function img1_click in a JavaScript file and it is loaded in this .html file:

```<code> <table >

 <td width="280">
 ...
 </td>
 <td width="280">
 <p id="img1"
 style="width:280px;height:157px;
 background:url(images/1.bmp);background-size: 280px 157px;"onclick="img1_click()">
  </p>
  </td>`
</code>```

There is a link to https://tommcfarlin.com/javascript-reference-error-is-not-defined/ to discuss this, it means sometimes HTML could not recognize or define the function, which is in JavaScript.

答: Are you 100% sure that your img_click1() function is defined? In Chrome developer tools (ctrl+shift+i, F12, or Menu -> More Tools -> Chrome Developer Tools) go to console and run img_click1(); to test that it actually exists. If you run into an undefined issue, then we'll need more code (entire HTML + entire JS file) in order to verify that your code is working correctly.</p>

Body:
I checked many posts, but looks all different and none of solutions work for me, the following is an extreme simple example, img1_click works in the newest Chrome with mouse click on desktop, but on touchscreen the img1_clickis never called, and I could see:

uncaught referenceerror img1_click is not defined

I found this post which suggests:

document.getElementById ('img1').addEventListener ("click", img1_click, false);

However, it is still not working!

I define function img1_click in a JavaScript file and it is loaded in this .html file:

 ...

  	`

There is a link to https://tommcfarlin.com/javascript-reference-error-is-not-defined/ to discuss this, it means sometimes HTML could not recognize or define the function, which is in JavaScript.