问:
Custom v-on:click.prevent functionality
I've no idea what to call this so I don't know what to search for. I've looked around the directives but not sure this is what it is either, basically, I want to be able to do:

```<code>v-on:click.validate="runCode"
</code>```

Where validate is a custom method that runs before runCode is called (much in the same way .prevent works.

Can someone point me to some docs / an example?

More Context: I've written some custom form components that feed validation data into my state. These form components can be used as and when i.e

```<code><msp-input
          v-model="form.username"
          :validation="{ required, email }"
          float-label="Email Address"
          type="email"
        />
</code>```

I want to be able to write a button on any of the forms that causes the validation popup to show if the state shows some validation has failed. I could have an <msp-button> component to do it but thought it would be nice to have an inline .validate.

答: why not just do v-on:click="validate" then put runCode at the last line of your validate method.</p>

Title: Custom v-on:click.prevent functionality

Body:
I've no idea what to call this so I don't know what to search for. I've looked around the directives but not sure this is what it is either, basically, I want to be able to do:

v-on:click.validate="runCode"

Where validate is a custom method that runs before runCode is called (much in the same way .prevent works.

Can someone point me to some docs / an example?

More Context: I've written some custom form components that feed validation data into my state. These form components can be used as and when i.e

<msp-input
          v-model="form.username"
          :validation="{ required, email }"
          float-label="Email Address"
          type="email"
        />

I want to be able to write a button on any of the forms that causes the validation popup to show if the state shows some validation has failed. I could have an <msp-button> component to do it but thought it would be nice to have an inline .validate.


来源: stackexchange

问:
How to succinctly write a formula with many variables from a data frame?
Suppose I have a response variable and a data containing three covariates (as a toy example):

```<code>y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))
</code>```

I want to fit a linear regression to the data:

```<code>fit = lm(y ~ d$x1 + d$x2 + d$y2)
</code>```

Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like

```<code>fit = lm(y ~ d)
</code>```

(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.

答:
I build this solution, reformulate does not take care if variable names have white spaces.

```<code>add_backticks = function(x) {
    paste0("`", x, "`")
}

x_lm_formula = function(x) {
    paste(add_backticks(x), collapse = " + ")
}

build_lm_formula = function(x, y){
    if (length(y)>1){
        stop("y needs to be just one variable")
    }
    as.formula(
        paste0("`",y,"`", " ~ ", x_lm_formula(x))
    )
}

# Example
df <- data.frame(
    y = c(1,4,6),
    x1 = c(4,-1,3),
    x2 = c(3,9,8),
    x3 = c(4,-4,-2)
    )

# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"

# Run Model
lm(formula = formula, data = df)
# output
Call:
    lm(formula = formula, data = df)

Coefficients:
    (Intercept)           x1           x2           x3
        -5.6316       0.7895       1.1579           NA
</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
Suppose I have a response variable and a data containing three covariates (as a toy example):

y = c(1,4,6)
d = data.frame(x1 = c(4,-1,3), x2 = c(3,9,8), x3 = c(4,-4,-2))

I want to fit a linear regression to the data:

fit = lm(y ~ d$x1 + d$x2 + d$y2)

Is there a way to write the formula, so that I don't have to write out each individual covariate? For example, something like

fit = lm(y ~ d)

(I want each variable in the data frame to be a covariate.) I'm asking because I actually have 50 variables in my data frame, so I want to avoid writing out x1 + x2 + x3 + etc.

Body:
I build this solution, reformulate does not take care if variable names have white spaces.

add_backticks = function(x) {
    paste0("`", x, "`")
}

x_lm_formula = function(x) {
    paste(add_backticks(x), collapse = " + ")
}

build_lm_formula = function(x, y){
    if (length(y)>1){
        stop("y needs to be just one variable")
    }
    as.formula(
        paste0("`",y,"`", " ~ ", x_lm_formula(x))
    )
}

# Example
df <- data.frame(
    y = c(1,4,6),
    x1 = c(4,-1,3),
    x2 = c(3,9,8),
    x3 = c(4,-4,-2)
    )

# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"

# Run Model
lm(formula = formula, data = df)
# output
Call:
    lm(formula = formula, data = df)

Coefficients:
    (Intercept)           x1           x2           x3
        -5.6316       0.7895       1.1579           NA

```


问:
Tomcat randomly invalidating Sessions
My tomcat application randomly invalidates the session information and the user if forced to log back in again. This only happens when the webapp is deployed with other specific web applications. When it is run by itself with no other app running, it works fine. There is a conflict somewhere, but I am unable to find it.

The webapp in question uses both the Spring and Hibernate frameworks. The other webapps do as well. Here is an example of what happens.

When I first log on, everything is fine.

JSESSIONID Matches

The JSESSONID matches in both the cookie and the management console. However, when using the application, it randomly terminates the session.

Session gone in Tomcat Console

When I another web request, the login page is shown and a new JSESSIONID has been generated.

From the research I have done, the JSESSIONID is generated whenever a JSP file is called and there is no current session. I don't understand why the session is being invalidated, but only when it is run alongside other applications. I have checked the memory usage, and I didn't notice a correlation between a memory drop and the sessions being invalidated. I guess that means that Tomcat isn't clearing sessions to free up memory.

Any help is much appreciated

答:
Check that session.setMaxInactiveInterval() is not programmatically configured in the other web applications.  This would elicit the behavior you describe.

This method is slightly different from the session timeout value that you would find in your web.xml files.  (Here's a good rundown.)

Title: Tomcat randomly invalidating Sessions


问:
How can I make an iteration then iterate the same object again after a break in Blade PHP (Laravel)
In my controller, I'm passing a Collection of 8 items:

```<code>$data['items'] = Item::orderBy('id','desc')->take(8)->get();
</code>```

to the view. Using Blade, I want to break the collection in half and render each half in different positions:

@foreach($items as $item)
  // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items as $item)
  // iterate the rest 4 items from the same object $items
@endforeach
```

How can I do this?

答:
Slice your $items collection in half:

// Slice collection from the 0 index for a length of 4 (the first 4 items)
@foreach($items->slice(0, 4) as $item)
  // ...
@endforeach

// Iterate over the rest from th 4 index.
// By passing the second parameter you can restrain the length.
@foreach($items->slice(4) as $item)
  // ...
@endforeach
```

Or chunk it into two collections.

Body:
In my controller, I'm passing a Collection of 8 items:

$data['items'] = Item::orderBy('id','desc')->take(8)->get();

to the view. Using Blade, I want to break the collection in half and render each half in different positions:

@foreach($items as $item)
  // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items as $item)
  // iterate the rest 4 items from the same object $items
@endforeach

How can I do this?

Body:
Slice your $items collection in half:

// Slice collection from the 0 index for a length of 4 (the first 4 items)
@foreach($items->slice(0, 4) as $item)
  // ...
@endforeach

// Iterate over the rest from th 4 index.
// By passing the second parameter you can restrain the length.
@foreach($items->slice(4) as $item)
  // ...
@endforeach

Or chunk it into two collections.


问:
How do I make the UI in IE 8 update as lines of JavaScript are executed in a function, rather than at the end of of the function?
I'm trying to display a progress bar while ajax calls populate a form. I have a function called LOADFORM(). It launches a jquery dialog box, displays a progress bar, calles a few other non-async ajax calls to get data. With each data call complete it advances the progress bar and at the end it hides the progressbar and displays the form. This works perfecly in Firfox, but in IE, it just shows the completed form. I doesn't update the UI until the function is done running and by that time everything is complete, but the user has to sit at a uneventful screen for several seconds. How do I make the UI in IE 8 update as lines of JavaScript are executed in a function?

Example:

```<code>ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    this.ShowError(false, "");

    //SHOW PROGRESS BAR
    this.ShowProgress(true, 30, "loading...");

    this.ShowDialogBox();

    //POPULATE FIELDS
    this.GetAccountName(constId);
    this.ShowProgress(true, 60, "loading...proposals");
    this.GetProposlas(constId);
    this.ShowProgress(true, 90, "loading...action types");
    this.GetActionTypes();
    this.ShowProgress(true, 100, "loading...complete");
    this.ConstituentID = constId;
    $("#" + this.CONSTITUENTID_ID + ":input").val("");
    $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + this.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (formType != "") {
        ToggleForms(formType);
    }

    //HIDE PROGRESS BAR
    this.ShowProgress(false, 0, "");

}
</code>```

Thanks,
T

答:
Chaining via callbacks. Its all about the callbacks. I've been avoiding them because they're ugly and hard to read, but they allow you update the DOM while the rest of your code runs, IN IE. This is un</p>

```<code>function LoadFormCall(constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();
    arfObj.hiddenStuff1 = constId;
    arfObj.hiddenStuff2 = formType;
    //CLEAR FIELDS
    arfObj.ClearFormFields();

    //HIDE ERRORS
    arfObj.ShowError(false, "");

    //SHOW PROGRESS BAR
    arfObj.ShowProgress(true, 30, "loading...");

    //OPEN DIALOG
    ShowDialogBox();

    //POPULATE FIELDS
    //THIS CALLS A JQUERY $.ajax call with a callback execute in the success function
    //AND SO BEGINS THE CHAIN.
    arfObj.GetAccountName1(constId, LoadFormCall2);
};

function LoadFormCall2() {
    constId = arfObj.hiddenStuff1;
    arfObj.ShowProgress(true, 60, "loading...proposals");
    arfObj.GetProposals1(constId, LoadFormCall3);
};

function LoadFormCall3() {
    arfObj.ShowProgress(true, 90, "loading...action types");
    arfObj.GetActionTypes1(LoadFormCall4);
}

function LoadFormCall4(){
    arfObj.ShowProgress(true, 100, "loading...complete");
    arfObj.ConstituentID = constId;

    $("#" + arfObj.CONSTITUENTID_ID + ":input").val("");
    $("#" + arfObj.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + arfObj.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + arfObj.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (arfObj.hiddenStuff2 != "") {
        ToggleForms(arfObj.hiddenStuff2);
    }

    //HIDE PROGRESS BAR
    arfObj.ShowProgress(false, 0, "");
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to display a progress bar while ajax calls populate a form. I have a function called LOADFORM(). It launches a jquery dialog box, displays a progress bar, calles a few other non-async ajax calls to get data. With each data call complete it advances the progress bar and at the end it hides the progressbar and displays the form. This works perfecly in Firfox, but in IE, it just shows the completed form. I doesn't update the UI until the function is done running and by that time everything is complete, but the user has to sit at a uneventful screen for several seconds. How do I make the UI in IE 8 update as lines of JavaScript are executed in a function?

Example:

ActionReportForms.prototype.LoadFormData = function (constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();

    //CLEAR FIELDS
    this.ClearFormFields();

    //HIDE ERRORS
    this.ShowError(false, "");

    //SHOW PROGRESS BAR
    this.ShowProgress(true, 30, "loading...");

    this.ShowDialogBox();

    //POPULATE FIELDS
    this.GetAccountName(constId);
    this.ShowProgress(true, 60, "loading...proposals");
    this.GetProposlas(constId);
    this.ShowProgress(true, 90, "loading...action types");
    this.GetActionTypes();
    this.ShowProgress(true, 100, "loading...complete");
    this.ConstituentID = constId;
    $("#" + this.CONSTITUENTID_ID + ":input").val("");
    $("#" + this.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + this.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + this.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (formType != "") {
        ToggleForms(formType);
    }

    //HIDE PROGRESS BAR
    this.ShowProgress(false, 0, "");

}

Thanks,
T

Body:
Chaining via callbacks. Its all about the callbacks. I've been avoiding them because they're ugly and hard to read, but they allow you update the DOM while the rest of your code runs, IN IE. This is un

function LoadFormCall(constId, formType) {
    //HOOK UP DATE PICKER
    $('#' + this.TPLDATEFIELD_ID).datepicker();
    $('#' + this.CRDATEFIELD_ID).datepicker();
    arfObj.hiddenStuff1 = constId;
    arfObj.hiddenStuff2 = formType;
    //CLEAR FIELDS
    arfObj.ClearFormFields();

    //HIDE ERRORS
    arfObj.ShowError(false, "");

    //SHOW PROGRESS BAR
    arfObj.ShowProgress(true, 30, "loading...");

    //OPEN DIALOG
    ShowDialogBox();

    //POPULATE FIELDS
    //THIS CALLS A JQUERY $.ajax call with a callback execute in the success function
    //AND SO BEGINS THE CHAIN.
    arfObj.GetAccountName1(constId, LoadFormCall2);
};

function LoadFormCall2() {
    constId = arfObj.hiddenStuff1;
    arfObj.ShowProgress(true, 60, "loading...proposals");
    arfObj.GetProposals1(constId, LoadFormCall3);
};

function LoadFormCall3() {
    arfObj.ShowProgress(true, 90, "loading...action types");
    arfObj.GetActionTypes1(LoadFormCall4);
}

function LoadFormCall4(){
    arfObj.ShowProgress(true, 100, "loading...complete");
    arfObj.ConstituentID = constId;

    $("#" + arfObj.CONSTITUENTID_ID + ":input").val("");
    $("#" + arfObj.CONSTITUENTID_ID + ":input").val(constId);

    //HIDE
    $('#' + arfObj.TPLDATEFIELD_ID).datepicker("hide");
    $('#' + arfObj.CRDATEFIELD_ID).datepicker("hide");

    //TOGGLE FORM
    if (arfObj.hiddenStuff2 != "") {
        ToggleForms(arfObj.hiddenStuff2);
    }

    //HIDE PROGRESS BAR
    arfObj.ShowProgress(false, 0, "");
}


问:
How to filter an array inside of an array of objects?
I have this array that I want to check the days that has the job done inside.(In this case Monday)</p>

```<code>const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?
</code>```

答:
First of all, as I said in the comments, event.job is an Array so doing === 'done' will never evaluate to true.

What you need is to apply .every() filter on the array rather than ===.

```<code>const freeTime = done.filter((event) => event.job.every(isDone) )

function isDone(status){
  return status == "done";
}
</code>```

This is of course assuming that all three values in jobs property must be 'done'.

JSFiddle

If your structure of those object is that each value in days corresponds to each value in jobs (i.e. index 0 in days is assigned to index 0 of jobs), then you need to design your objects more efficiently. The current design not efficient nor practical.

Body:
I have this array that I want to check the days that has the job done inside.(In this case Monday)

const done = [
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "done", "done"]},
 {days:["Monday", "Tuesday", "Friday"] ,job: ["done", "not yet", "not yet"]},
]

 const freeTime = done
  .filter((event) => event.job === 'done')
console.log(freeTime) // I get nothing here?

Body:
First of all, as I said in the comments, event.job is an Array so doing === 'done' will never evaluate to true.

What you need is to apply .every() filter on the array rather than ===.

const freeTime = done.filter((event) => event.job.every(isDone) )

function isDone(status){
  return status == "done";
}

This is of course assuming that all three values in jobs property must be 'done'.

JSFiddle

If your structure of those object is that each value in days corresponds to each value in jobs (i.e. index 0 in days is assigned to index 0 of jobs), then you need to design your objects more efficiently. The current design not efficient nor practical.


问:
Loop through words in a string
I've seen a lot of javascript stack questions around this, but nothing specifically related to SQL Server.

What I need to do is accept a string value and do a loop over the string multiple times to get back all the individual words so I can do calculations on them.

A rough idea is shown below. Anyone know how this can be achieved?

```<code>Declare @String nvarchar(50) = 'Mary had a little lamb'
Declare @word nvarchar(50)

Start Loop 1 to 5
    Set @word = 'Mary' (1)
    Set @word = 'had' (2)
    Set @word = 'a' (3)
    Set @word = 'little' (4)
    Set @word = 'lamb' (5)
End Loop
</code>```

答:
You can split the parameter and write it in a temp table, and then use the values from the temp table. Using loops in SQL is not the best idea as they really affects your query performance.</p>

```<code>Declare @String nvarchar(50) = 'Mary had a little lamb'

INSERT INTO #tempTable(colName)
SELECT colName
FROM dbo.Split(@String , ' ')
</code>```

Title: Loop through words in a string

Body:
I've seen a lot of javascript stack questions around this, but nothing specifically related to SQL Server.

What I need to do is accept a string value and do a loop over the string multiple times to get back all the individual words so I can do calculations on them.

A rough idea is shown below. Anyone know how this can be achieved?

Declare @String nvarchar(50) = 'Mary had a little lamb'
Declare @word nvarchar(50)

Start Loop 1 to 5
    Set @word = 'Mary' (1)
    Set @word = 'had' (2)
    Set @word = 'a' (3)
    Set @word = 'little' (4)
    Set @word = 'lamb' (5)
End Loop

Body:
You can split the parameter and write it in a temp table, and then use the values from the temp table. Using loops in SQL is not the best idea as they really affects your query performance.

Declare @String nvarchar(50) = 'Mary had a little lamb'

INSERT INTO #tempTable(colName)
SELECT colName
FROM dbo.Split(@String , ' ')


问:
JSON_NUMERIC_CHECK and phone numbers
Our PHP API outputs results using json_encode with JSON_NUMERIC_CHECK enabled, which is important for financial figures, binary values etc.. but we have recently introduced a phone number field, and it is removing zeros from the beginning of the number when it casts it as an integer.

I've tried to force "(string)" type on the value before it goes to json_encode, but it looks like the function is overriding it. eg:

```<code>$output = array(
    'is_bool' => 1,
    'total_amount' => '431.65',
    'phone_number' => (string) '0272561313'
);
echo json_encode($output,JSON_NUMERIC_CHECK);
</code>```

Produces:

```<code>{"is_bool":1,"total_amount":431.65,"phone_number":272561313}
</code>```

Any suggestions on how to best handle this would be much appreciated. I really don't want to have to resort to adding trailing spaces at the end of the phone number when it's output just to get it through as a string.

Thanks!

答:
You can try this:

```<code>{
  "is_bool": 1,
  "total_amount": 431.65,
  "phone_number": "xn#0272561313"
}
</code>```

as example in mysql:
SELECT CONCAT('xn#', phone_number) as phone_number...

If you used json_encode(), replace the string like this:

```<code>echo str_replace('xn#','',$your_encoded_json);
</code>```

Title: JSON_NUMERIC_CHECK and phone numbers

Body:
Our PHP API outputs results using json_encode with JSON_NUMERIC_CHECK enabled, which is important for financial figures, binary values etc.. but we have recently introduced a phone number field, and it is removing zeros from the beginning of the number when it casts it as an integer.

I've tried to force "(string)" type on the value before it goes to json_encode, but it looks like the function is overriding it. eg:

$output = array(
    'is_bool' => 1,
    'total_amount' => '431.65',
    'phone_number' => (string) '0272561313'
);
echo json_encode($output,JSON_NUMERIC_CHECK);

Produces:

{"is_bool":1,"total_amount":431.65,"phone_number":272561313}

Any suggestions on how to best handle this would be much appreciated. I really don't want to have to resort to adding trailing spaces at the end of the phone number when it's output just to get it through as a string.

Thanks!

Body:
You can try this:

{
  "is_bool": 1,
  "total_amount": 431.65,
  "phone_number": "xn#0272561313"
}

as example in mysql:
SELECT CONCAT('xn#', phone_number) as phone_number...

If you used json_encode(), replace the string like this:

echo str_replace('xn#','',$your_encoded_json);


问:
Extract Array (Data) Field from PHP CURL Response (Response in HTML format)
I am using PHP CURL in response i get the data in html format.

The data is coming in array format how can i extract the data from that array.

ihave to got response in $response variable.

$response = curl_exec($curl);

below is the response format

```<code><html><div id="form_section">

        <span class="select_dele">/ / User <strong>Details</strong><a class="close" href="https://www.example.com"><img src="/img/close.png" alt="close" /></a>
        </span>

        <form action="#" style="width:55.5%;margin:2% 4% 0 0">
        <div class="comn_box info">
        <div class="detail_row">
        <label>User Number:</label>
        <span class="detail">1234567890</span>
        </div>
         <div class="detail_row">
        <label>Username Name:</label>
        <span class="detail">Jhon</span>
        </div>
        <div class="detail_row">
        <label>Post: </label>
          <span class="detail">Teacher</span>
        </div>
        </div>
        </form>

   </html>
</code>```

i want to display in echo only the User Number and the Username Name field data.

Thanks

答:
use DOMDocument.

```<code>$data=array();
foreach((@DOMDocument::loadHTML($response))->getElementsByTagName("label") as $label){
    $data[trim($label->textContent)]=trim($label->nextSibling->nextSibling->textContent);
}
print_r($data);
</code>```

output:

```<code>Array
(
    [User Number:] => 1234567890
    [Username Name:] => Jhon
    [Post:] => Teacher
)
</code>```

Body:
I am using PHP CURL in response i get the data in html format.

The data is coming in array format how can i extract the data from that array.

ihave to got response in $response variable.

$response = curl_exec($curl);

below is the response format

        / / User Details

        <form action="#" style="width:55.5%;margin:2% 4% 0 0">

        User Number:
        1234567890

        Username Name:
        Jhon

        Post:
          Teacher

        </form>

i want to display in echo only the User Number and the Username Name field data.

Thanks

Body:
use DOMDocument.

$data=array();
foreach((@DOMDocument::loadHTML($response))->getElementsByTagName("label") as $label){
    $data[trim($label->textContent)]=trim($label->nextSibling->nextSibling->textContent);
}
print_r($data);

output:

Array
(
    [User Number:] => 1234567890
    [Username Name:] => Jhon
    [Post:] => Teacher
)


问:
Why does "npm install" rewrite package-lock.json?
I just recently upgraded to npm@5.  I now have a package-lock.json file with everything from package.json.  I would expect that, when I run npm install that the dependency versions would be pulled from the lock file to determine what should be installed in my node_modules directory.  What's strange is that it actually ends up modifying and rewriting my package-lock.json file.

For example, the lock file had typescript specified to be at version 2.1.6.  Then, after the npm install command, the version was changed to 2.4.1.  That seems to defeat the whole purpose of a lock file.

What am I missing?  How do I get npm to actually respect my lock file?

答:
EDIT: the name "lock" is a tricky one, its NPM trying to catch up with Yarn. It isn't a locked file whatsoever. package.json is a user-fixed file, that once "installed" will generate node_modules folder tree and that tree will then be written in package-lock.json. So you see, its the other way around - dependency versions will be pulled from package.json as always, and package-lock.json should be called package-tree.json

(hope this made my answer clearer, after so many downvotes)

A simplistic answer: package.json have your dependencies as usual, while package-lock.json is "an exact, and more importantly reproducible node_modules tree" (taken from npm docs itself).

As for the tricky name, its NPM trying to catch up with Yarn.

ContentLicense: CC BY-SA 4.0


问:
Instruction error while learning assembly
So I'm trying to learn some x86 assembly, I'm using NASM as my complier. I have this code that I'm working on, but when I compile, I get an error.

```<code>$ nasm -f bin -o myfirst.bin myfirst.asm
myfirst.asm:46: error: parser: instruction expected
</code>```

Any idea whats wrong? Thanks!

答: you typed 'mv' instead of 'mov' on line 46</p>

Body:
So I'm trying to learn some x86 assembly, I'm using NASM as my complier. I have this code that I'm working on, but when I compile, I get an error.

$ nasm -f bin -o myfirst.bin myfirst.asm
myfirst.asm:46: error: parser: instruction expected

Any idea whats wrong? Thanks!


答:
You can use The split method to break a collection into the given number of groups:

Example:

```<code>$collection = collect([1, 2, 3, 4, 5, 6, 7, 8]);

$groups = $collection->split(2);

$groups->toArray(); // [[1, 2, 3, 4], [5, 6, 7, 8]]
</code>```

In your controller:

```<code>$data['items'] = Item::orderBy('id','desc')->take(8)->get()->split(2);
</code>```

Blade:

```<code>@foreach($items[0] as $item)
    // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items[1] as $item)
    // iterate the rest 4 items from the same object $items
@endforeach
</code>```

Title: How can I make an iteration then iterate the same object again after a break in Blade PHP (Laravel)

Body:
You can use The split method to break a collection into the given number of groups:

Example:

$collection = collect([1, 2, 3, 4, 5, 6, 7, 8]);

$groups = $collection->split(2);

$groups->toArray(); // [[1, 2, 3, 4], [5, 6, 7, 8]]

In your controller:

$data['items'] = Item::orderBy('id','desc')->take(8)->get()->split(2);

Blade:

@foreach($items[0] as $item)
    // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items[1] as $item)
    // iterate the rest 4 items from the same object $items
@endforeach


问:
equals vs Arrays.equals in Java
When comparing arrays in Java, are there any differences between the following 2 statements?

```<code>Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);
</code>```

And if so, what are they?

答:
```<code>import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {
   // initializing three object arrays
   Object[] array1 = new Object[] { 1, 123 };
   Object[] array2 = new Object[] { 1, 123, 22, 4 };
   Object[] array3 = new Object[] { 1, 123 };

   // comparing array1 and array2
   boolean retval=Arrays.equals(array1, array2);
   System.out.println("array1 and array2 equal: " + retval);
   System.out.println("array1 and array2 equal: " + array1.equals(array2));

   // comparing array1 and array3
   boolean retval2=Arrays.equals(array1, array3);
   System.out.println("array1 and array3 equal: " + retval2);
   System.out.println("array1 and array3 equal: " + array1.equals(array3));

   }
}
</code>```

Here is the output:

```<code>    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false
</code>```

Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.

Title: equals vs Arrays.equals in Java

Body:
When comparing arrays in Java, are there any differences between the following 2 statements?

Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);

And if so, what are they?

Body:
import java.util.Arrays;
public class ArrayDemo {
   public static void main(String[] args) {
   // initializing three object arrays
   Object[] array1 = new Object[] { 1, 123 };
   Object[] array2 = new Object[] { 1, 123, 22, 4 };
   Object[] array3 = new Object[] { 1, 123 };

   // comparing array1 and array2
   boolean retval=Arrays.equals(array1, array2);
   System.out.println("array1 and array2 equal: " + retval);
   System.out.println("array1 and array2 equal: " + array1.equals(array2));

   // comparing array1 and array3
   boolean retval2=Arrays.equals(array1, array3);
   System.out.println("array1 and array3 equal: " + retval2);
   System.out.println("array1 and array3 equal: " + array1.equals(array3));

   }
}

Here is the output:

    array1 and array2 equal: false
    array1 and array2 equal: false

    array1 and array3 equal: true
    array1 and array3 equal: false

Seeing this kind of problem I would personally go for Arrays.equals(array1, array2) as per your question to avoid confusion.


问:
Localizing strings in iOS: default (fallback) language?
Is there a way to set a default language to be used when the device UI language is not supported by an app?

Example:
My app is localized into English and German:

```<code>// en.lproj:
"POWER_TO_THE_PEOPLE_BTN" = "Power";
"POWER_PLUG_BTN" = "Power";

// de.lproj:
"POWER_TO_THE_PEOPLE_BTN"  = "Macht";
"POWER_PLUG_BTN" = "Spannung";
</code>```

Now, if I run the app on a device with UI language set to Italian the app will use the key strings POWER_TO_THE_PEOPLE_BTN and POWER_PLUG_BTN.

There must be a way to specify a default (fallback) language to be used by the application in such a case.

From the above example it should be clear that using the English string as a key will not work.

The only option I see right now is to use NSLocalizedStringWithDefaultValue instead of NSLocalizedString.

答:
Based on Bodus solution (thx btw.) I created this category because you need the "fallbackString" too. So I have to check the current selected language of the device and compare it with my languages I want to support. Just import the header and you can use apples default macro

```<code>NSString *myString = NSLocalizedString(@"My Ub0rstring", nil);
</code>```

Works fine on iOS 9.x and 11.1.

NSString+Helper.h

```<code>#import <Foundation/Foundation.h>

#undef NSLocalizedString
#define NSLocalizedString(key, comment) [NSString localizedStringForKey:(key) replaceValue:(comment)]

@interface NSString (Helper)

+ (NSString *)localizedStringForKey:(NSString *)key replaceValue:(NSString *)comment;

@end
</code>```

NSString+Helper.m

```<code>#import "NSString+Helper.h"

@implementation NSString (Helper)

+ (NSString *)localizedStringForKey:(NSString *)key replaceValue:(NSString *)comment
{
    NSString *fallbackLanguage      = @"en";
    NSString *fallbackBundlePath    = [[NSBundle mainBundle] pathForResource:fallbackLanguage ofType:@"lproj"];
    NSBundle *fallbackBundle        = [NSBundle bundleWithPath:fallbackBundlePath];
    NSString *fallbackString        = [fallbackBundle localizedStringForKey:key value:comment table:nil];
    NSString *localizedString       = [[NSBundle mainBundle] localizedStringForKey:key value:fallbackString table:nil];

    NSString *language              = [[NSLocale preferredLanguages] firstObject];
    NSDictionary *languageDic       = [NSLocale componentsFromLocaleIdentifier:language];
    NSString *languageCode          = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

    if ([languageCode isEqualToString:@"de"] || [languageCode isEqualToString:@"en"]) {
        return localizedString;
    }
    else {
        return fallbackString;
    }
}

@end
</code>```

Body:
Is there a way to set a default language to be used when the device UI language is not supported by an app?

Example:
My app is localized into English and German:

// en.lproj:
"POWER_TO_THE_PEOPLE_BTN" = "Power";
"POWER_PLUG_BTN" = "Power";

// de.lproj:
"POWER_TO_THE_PEOPLE_BTN"  = "Macht";
"POWER_PLUG_BTN" = "Spannung";

Now, if I run the app on a device with UI language set to Italian the app will use the key strings POWER_TO_THE_PEOPLE_BTN and POWER_PLUG_BTN.

There must be a way to specify a default (fallback) language to be used by the application in such a case.

From the above example it should be clear that using the English string as a key will not work.

The only option I see right now is to use NSLocalizedStringWithDefaultValue instead of NSLocalizedString.

Body:
Based on Bodus solution (thx btw.) I created this category because you need the "fallbackString" too. So I have to check the current selected language of the device and compare it with my languages I want to support. Just import the header and you can use apples default macro

NSString *myString = NSLocalizedString(@"My Ub0rstring", nil);

Works fine on iOS 9.x and 11.1.

NSString+Helper.h

#import <Foundation/Foundation.h>

#undef NSLocalizedString
#define NSLocalizedString(key, comment) [NSString localizedStringForKey:(key) replaceValue:(comment)]

@interface NSString (Helper)

+ (NSString *)localizedStringForKey:(NSString *)key replaceValue:(NSString *)comment;

@end

NSString+Helper.m

#import "NSString+Helper.h"

@implementation NSString (Helper)

+ (NSString *)localizedStringForKey:(NSString *)key replaceValue:(NSString *)comment
{
    NSString *fallbackLanguage      = @"en";
    NSString *fallbackBundlePath    = [[NSBundle mainBundle] pathForResource:fallbackLanguage ofType:@"lproj"];
    NSBundle *fallbackBundle        = [NSBundle bundleWithPath:fallbackBundlePath];
    NSString *fallbackString        = [fallbackBundle localizedStringForKey:key value:comment table:nil];
    NSString *localizedString       = [[NSBundle mainBundle] localizedStringForKey:key value:fallbackString table:nil];

    NSString *language              = [[NSLocale preferredLanguages] firstObject];
    NSDictionary *languageDic       = [NSLocale componentsFromLocaleIdentifier:language];
    NSString *languageCode          = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"];

    if ([languageCode isEqualToString:@"de"] || [languageCode isEqualToString:@"en"]) {
        return localizedString;
    }
    else {
        return fallbackString;
    }
}

@end


问:
AnyLogic: Improving computational performance of a network model
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

```<code>int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;
</code>```

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?

答:
Your result that things bog down somewhere between 1000 and 5000 is pretty common with the agent-based models I've seen.  It's a basic computational complexity issue.  With N agents, the number of 2-way interactions is N.choose.2, which is O(N^2).  5000 agents is approximately 25 times as much work as 1000 agents.

You can pull some stunts with localization.  Basically, divide your sandbox into different playing areas based on the fact that agents in a particular area can't interact with agents in other areas, so you only need to check for a subset of the interactions.  Dividing the N agents into k independent groupings, if possible, will yield an O(k)-fold improvement in run times.

Another alternative might be to move away from a time-step framework and work out an event-based design for your problem. You can find an example of this approach in this paper.

Body:
I'm working with an agent-based model of an epidemic. The idea is that individual agents make decisions based on what they observe in their networks (distance-based). I have several functions within each agent that dynamically update counts of infected contacts, contacts showing a particular behaviour etc.

The code below is for counting infected contacts within an agent's network.

int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;

There will be at least 3 more such functions that keep counts of other agents expressing other features within an agent's network. Now, this seems to run Okay when I have <500 agents, but when I increase the agent population to about 1,000 or so, the model becomes extremely slow. I'm looking to simulate at least 5,000 agents, and at this point, the model doesn't even initialise.

Is there a more computationally efficient way to track network statistics in Anylogic for larger populations?


问:
Java Webstart not working offline (NoRouteToHostException/UnknownHostException)
I want to configure my webstart app/jnlp so that if no internet connection is available, it would start from cache. Nevertheless, when I disconnect from the internet, I always get a NoRouteToHostException or UnknownHostException exception, despite the configuration below.

I've set the offline-allowed and update tags/attributes properly I think; I cannot find the reason why webstart is still trying to lookup the host.
I definitely do have the app cached from my previous start when I was connected.

```<code><?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="6.0+" codebase="http://cms.mydomain.com/sync/" href="myAppSync.jnlp">

<information>
    <title>My App Sync</title>
    <vendor>My Company</vendor>
    <homepage href="http://www.myapp.com/"/>
    <description>Sync application for My App</description>
    <icon href="ATTico.png"/>

    <!-- allow app to run without Internet access -->
    <offline-allowed/>

    <shortcut online="true">
      <desktop/>
      <!-- create menu item for this app under the major heading 'My App' -->
      <menu submenu="My App"/>
    </shortcut>

</information>

<security>
    <all-permissions/>
</security>

<update check="timeout" policy="always" />

<resources>
    <java version="1.6*" href="http://java.sun.com/products/autodl/j2se"/>
    <jar href="lib/myAppSync.jar" />
    <jar href="lib/apache-mime4j-0.6.jar" />
    <jar href="lib/commons-logging-1.1.1.jar" />
    <jar href="lib/commons-codec-1.3.jar" />
    <jar href="lib/httpclient-4.0.1.jar" />
    <jar href="lib/httpcore-4.0.1.jar" />
    <jar href="lib/httpmime-4.0.1.jar" />
    <jar href="lib/swingx-1.6.jar" />
    <jar href="lib/swingx-beaninfo-1.6.jar" />
</resources>

<application-desc main-class="com.myapp.sync.forms.Main"/>

</jnlp>
</code>```

Error log:

```<code>java.net.NoRouteToHostException: No route to host: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doGetRequestEX(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.launch(Unknown Source)
at com.sun.javaws.Main.launchApp(Unknown Source)
at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
at com.sun.javaws.Main$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

java.net.UnknownHostException: cms.mydomain.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doGetRequestEX(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.launch(Unknown Source)
at com.sun.javaws.Main.launchApp(Unknown Source)
at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
at com.sun.javaws.Main$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
</code>```

答:
This can be achieved by using <update check="background"/>, but updates are no longer immediately downloaded when available, it requires a second start which is annoying.

This really feels like a Java Web Start bug, <update check="timeout"/> shouldn't prevent the application from starting if the connection to the server times out.

Body:
I want to configure my webstart app/jnlp so that if no internet connection is available, it would start from cache. Nevertheless, when I disconnect from the internet, I always get a NoRouteToHostException or UnknownHostException exception, despite the configuration below.

I've set the offline-allowed and update tags/attributes properly I think; I cannot find the reason why webstart is still trying to lookup the host.
I definitely do have the app cached from my previous start when I was connected.

<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="6.0+" codebase="http://cms.mydomain.com/sync/" href="myAppSync.jnlp">

<information>
    <title>My App Sync</title>
    <vendor>My Company</vendor>
    <homepage href="http://www.myapp.com/"/>
    <description>Sync application for My App</description>
    <icon href="ATTico.png"/>

    <offline-allowed/>

    <shortcut online="true">
      <desktop/>

      <menu submenu="My App"/>
    </shortcut>

</information>

<security>
    <all-permissions/>
</security>

<update check="timeout" policy="always" />

<resources>
    <java version="1.6*" href="http://java.sun.com/products/autodl/j2se"/>
    <jar href="lib/myAppSync.jar" />
    <jar href="lib/apache-mime4j-0.6.jar" />
    <jar href="lib/commons-logging-1.1.1.jar" />
    <jar href="lib/commons-codec-1.3.jar" />
    <jar href="lib/httpclient-4.0.1.jar" />
    <jar href="lib/httpcore-4.0.1.jar" />
    <jar href="lib/httpmime-4.0.1.jar" />
    <jar href="lib/swingx-1.6.jar" />
    <jar href="lib/swingx-beaninfo-1.6.jar" />
</resources>

<application-desc main-class="com.myapp.sync.forms.Main"/>

</jnlp>

Error log:

java.net.NoRouteToHostException: No route to host: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doGetRequestEX(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.launch(Unknown Source)
at com.sun.javaws.Main.launchApp(Unknown Source)
at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
at com.sun.javaws.Main$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

java.net.UnknownHostException: cms.mydomain.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doRequest(Unknown Source)
at com.sun.deploy.net.BasicHttpRequest.doGetRequestEX(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.isUpdateAvailable(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResourceCacheEntry(Unknown Source)
at com.sun.deploy.net.DownloadEngine.getResource(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadJarFiles(Unknown Source)
at com.sun.javaws.LaunchDownload.downloadEagerorAll(Unknown Source)
at com.sun.javaws.Launcher.downloadResources(Unknown Source)
at com.sun.javaws.Launcher.prepareLaunchFile(Unknown Source)
at com.sun.javaws.Launcher.prepareToLaunch(Unknown Source)
at com.sun.javaws.Launcher.launch(Unknown Source)
at com.sun.javaws.Main.launchApp(Unknown Source)
at com.sun.javaws.Main.continueInSecureThread(Unknown Source)
at com.sun.javaws.Main$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)


问:
Building a Transition Matrix using words in Python/Numpy
Im trying to build a 3x3 transition matrix with this data

```<code>days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']
</code>```

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

```<code>self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix
</code>```

for every type of weather I need to calculate the probability for the next day

答:
It seems you want to create a matrix of the probability of rain coming after sun or clouds coming after sun (or etc).  You can spit out the probability matrix (not a math term) like so:

```<code>def probabilityMatrix():
    tomorrowsProbability=np.zeros((3,3))
    occurancesOfEach = Counter(data)
    myMatrix = Counter(zip(data, data[1:]))
    probabilityMatrix = {key : myMatrix[key] / occurancesOfEach[key[0]] for key in myMatrix}
    return probabilityMatrix

print(probabilityMatrix())
</code>```

However, you probably want to spit out the probability for every type of weather based on today's weather:

```<code>def getTomorrowsProbability(weather):
    probMatrix = probabilityMatrix()
    return {key[1] : probMatrix[key]  for key in probMatrix if key[0] == weather}

print(getTomorrowsProbability('sun'))
</code>```

Body:
Im trying to build a 3x3 transition matrix with this data

days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix

for every type of weather I need to calculate the probability for the next day

Body:
It seems you want to create a matrix of the probability of rain coming after sun or clouds coming after sun (or etc).  You can spit out the probability matrix (not a math term) like so:

def probabilityMatrix():
    tomorrowsProbability=np.zeros((3,3))
    occurancesOfEach = Counter(data)
    myMatrix = Counter(zip(data, data[1:]))
    probabilityMatrix = {key : myMatrix[key] / occurancesOfEach[key[0]] for key in myMatrix}
    return probabilityMatrix

print(probabilityMatrix())

However, you probably want to spit out the probability for every type of weather based on today's weather:

def getTomorrowsProbability(weather):
    probMatrix = probabilityMatrix()
    return {key[1] : probMatrix[key]  for key in probMatrix if key[0] == weather}

print(getTomorrowsProbability('sun'))


问:
Position elements on webpage via CSS or Bootstrap

What is the best way or how do I position elements as shown in the diagram on a webpage to look like this. I tried absolute positioning but I dont know if that would work in a responsive environment and bootstrap seems not able to do this. Any ideas on how to do this positioning and layout?

答: Have you tried using CSS padding’s or margins? W3Schools has great tutorials on how to position elements. Here’s one about using margins and padding is on the next page. https://www.w3schools.com/css/css_margin.asp</p>


问:
connecting to PostgreSQL over a network
I have a pgsql server running on windows 7. I can remotely connect to it within the network using the computer name, so i know that there are no issues with config etc. I have disabled firewall. I have a static ip and have tried to connect to the database from another network but i get the error: server does not listen. What am i doing wrong? I know small amounts about ip addresses so any help will be appreciated. thanks in advance!

EDIT:
A little more information, i have set up a home network, i have two computers networked together that can both access the pgsql server that resides on one of the computers. I am based in the uk and get my internet from plusnet, config is all done on the thompson gateway. The third computer is a remote computer not on the same network, i was just testing to see whether or not i could "host" a pgsql database for several, not networked computers. Its more of a hobbiest thing really, although would be could if i could do it for work reasons too. Thanks for you help. (sorry if i sound dumb but this really isnt my subject-yet!)

答:
Configure the pg_hba.conf file to add the line

```<code>host all all 192.168.0.1/24 trust
</code>```

that IP 192.168.0.1 is just for the sake of example, you'll put there your IP
then edit the postgresql.conf to reflect these settings

```<code>tcpip_socket = true
</code>```

i think this  ^^ is only required for older versions, but add it there anyway

listen_addresses='*'

by default it's localhost, put * to listen to all addresses, or just your IP to tighten up the security

Title: connecting to PostgreSQL over a network

Body:
Configure the pg_hba.conf file to add the line

host all all 192.168.0.1/24 trust

that IP 192.168.0.1 is just for the sake of example, you'll put there your IP
then edit the postgresql.conf to reflect these settings

tcpip_socket = true

i think this  ^^ is only required for older versions, but add it there anyway

listen_addresses='*'

by default it's localhost, put * to listen to all addresses, or just your IP to tighten up the security


问:
OWASP ZAP false positive on X-Frame-Options and non-existing html file
I am using OWASP ZAP to test my application for vulnerabilities.

I am using the quick start Attack with the URL of my login page.

I am running the application on Tomcat from Eclipse.

Currently there are 2 problems:

ZAP finds an html page that I deleted. It does not exist anywhere in my project and yet ZAP generates an alert on it. It did exist at the time of first run.

ZAP generates an alert about X-Frame-Content header although this header exists and can be seen in Firefox F12 Tools. I even wrote a simple simulator that attempts to IFrame my application login page and the browser blocks it.

I am guessing ZAP has some kind of cache and I did Exit and Delete Session but it did not change anything.

Any advice will be appreciated.

Kirill.

答:
This was covered in a User Group thread: https://groups.google.com/forum/m/?pli=1#!topic/zaproxy-users/e764_WPWCRc

The URL clicked in the alert tree and displayed in the alert panel is the URL the alert applies to. Which is not necessarily the URL entered in the quick start tab.
The response an alert pertains to can be seen by selecting the alert and then going to the response tab (behind the quick start tab).

Once the user properly identified which urls/resour as were impacted they "... added security headers generation in Tomcat configuration and now there are no alerts."


问:
handling notification time with sensu
I'm using Sensu for alerting. If anything goes wrong with any of service then it would trigger the alert and send us notification mail.

I've just come across one document where I can change the notification time outside business hours, this is the document I was referring to.

I've created filter rule, /etc/sensu/conf.d/filters/nine_to_fiver.json

```<code>{
    "filters": {
      "nine_to_fiver": {
        "negate": false,
        "attributes": {
          "timestamp": "eval: [1,2,3,4,5].include?(Time.at(value).wday) && Time.at(value).hour.between?(9,17)"
        }
     }
  }
}
</code>```

After making this change, I reloaded sensu-client deamon on client side but I'm still getting notification on mail ID. Is there anything wrong with filter rules ? Or Am I missing anything ?

Any help would be appreciated.

答:
Filters must be applied on the Sensu Server, not the Sensu Client. Furthermore, the filter must reside server-side and the handler must be configured to apply the filter.

Alternatively, you might be able to get a little fancy with the when filter field.

Title: handling notification time with sensu

Body:
I'm using Sensu for alerting. If anything goes wrong with any of service then it would trigger the alert and send us notification mail.

I've just come across one document where I can change the notification time outside business hours, this is the document I was referring to.

I've created filter rule, /etc/sensu/conf.d/filters/nine_to_fiver.json

{
    "filters": {
      "nine_to_fiver": {
        "negate": false,
        "attributes": {
          "timestamp": "eval: [1,2,3,4,5].include?(Time.at(value).wday) && Time.at(value).hour.between?(9,17)"
        }
     }
  }
}

After making this change, I reloaded sensu-client deamon on client side but I'm still getting notification on mail ID. Is there anything wrong with filter rules ? Or Am I missing anything ?

Any help would be appreciated.


问:
How do I import a certificate to the Certstore on remote systems when WinRM is disabled with powershell
How do I import a certificate with Powershell to the Certstore on remote systems when WinRM is disabled in the environment due to security. I have attempted a few work around and all have failed. Please be easy I'm a novice.

I have tried this as a work around and yes I know its the untrusted store.

```<code>$cert = getchilditem -path "SharePath.cer"
$server = Get-content ".\servers.txt"
$server | foreach { $cert | import-certificate -CertStoreLocation Cert:LocalMachine\Disallowed
</code>```

答:
Deploying certificates to computers is probably best accomplished via Group Policy as it is a far more robust and easy to use process.

That being said if you cannot use Group Policy you may be able to use one of several other solutions depending on your target System's OS.

Boe Prox wrote an Import-Certificate function and explanation that uses .Net under the covers to allow imports on remote computers without WinRM or older than Windows 10. Using his solution you can do the following:

```<code>$File = "C:\temp\SomeRootCA.cer"
$Computername = 'Server1','Server2','Client1','Client2'
Import-Certificate -Certificate $File -StoreName Disallowed -StoreLocation LocalMachine -ComputerName $Computername
</code>```

If you are on Windows 10 you can use the built in Import-Certificate but this only works for the local system. So you will need to wrap it with Invoke-Command (which requires WinRM) or you can fallback to Invoke-WMIMethod. It's  not nearly as friendly to use or work with output, but it will work. This is a working example of executing a function on a remote computer without WinRM. For complex commands you will want to use the -EncodedCommand parameter of powershell.exe.

Copy cert to the remote system to avoid 2 hop issues

```<code>Copy-Item "C:\temp\SomeRootCa.cer" "\\Computer1\C$\temp\"
</code>```

Encode the command we want to use

```<code>$encoded = [Convert]::ToBase64String(
               [System.Text.Encoding]::Unicode.GetBytes(
                   {Import-Certificate -FilePath C:\temp\somerootca.cer -CertStoreLocation cert:\localmachine\disallowed}
               )
           )
</code>```

Spawn a process on the remote computer

```<code>Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "powershell.exe -encodedcommand $encoded" -ComputerName Computer1
</code>```

You will get output similar to the following on your computer

```<code>__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 2
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ProcessId        : 8748
ReturnValue      : 0
PSComputerName   :
</code>```

Note that the return value of 0 indicating success only indicates that powershell was spawned, not that the commands you executed were successful. If you want some logging you will need to bake it into the command you encode

EDIT: Foreach-Object and Get-Content

```<code>Get-Content C:\some\file\name\here.txt | Foreach-Object -begin {
    $encoded = [Convert]::ToBase64String(
               [System.Text.Encoding]::Unicode.GetBytes(
                   {Import-Certificate -FilePath C:\temp\somerootca.cer -CertStoreLocation cert:\localmachine\disallowed}
               )
           )
} -process {
    if(Test-Connection $_ -quiet){
        Copy-Item "C:\temp\SomeRootCa.cer" "\\$_\C$\temp\"
        Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "powershell.exe -encodedcommand $encoded" -ComputerName $_
    }
}
</code>```

Please do not copy/pasta this into a production environment. Read it and understand what is happening. Use the ISE to debug portions of the functions and piece it together bit by bit.

Body:
How do I import a certificate with Powershell to the Certstore on remote systems when WinRM is disabled in the environment due to security. I have attempted a few work around and all have failed. Please be easy I'm a novice.

I have tried this as a work around and yes I know its the untrusted store.

$cert = getchilditem -path "SharePath.cer"
$server = Get-content ".\servers.txt"
$server | foreach { $cert | import-certificate -CertStoreLocation Cert:LocalMachine\Disallowed

Body:
Deploying certificates to computers is probably best accomplished via Group Policy as it is a far more robust and easy to use process.

That being said if you cannot use Group Policy you may be able to use one of several other solutions depending on your target System's OS.

Boe Prox wrote an Import-Certificate function and explanation that uses .Net under the covers to allow imports on remote computers without WinRM or older than Windows 10. Using his solution you can do the following:

$File = "C:\temp\SomeRootCA.cer"
$Computername = 'Server1','Server2','Client1','Client2'
Import-Certificate -Certificate $File -StoreName Disallowed -StoreLocation LocalMachine -ComputerName $Computername

If you are on Windows 10 you can use the built in Import-Certificate but this only works for the local system. So you will need to wrap it with Invoke-Command (which requires WinRM) or you can fallback to Invoke-WMIMethod. It's  not nearly as friendly to use or work with output, but it will work. This is a working example of executing a function on a remote computer without WinRM. For complex commands you will want to use the -EncodedCommand parameter of powershell.exe.

Copy cert to the remote system to avoid 2 hop issues

Copy-Item "C:\temp\SomeRootCa.cer" "\\Computer1\C$\temp\"

Encode the command we want to use

$encoded = [Convert]::ToBase64String(
               [System.Text.Encoding]::Unicode.GetBytes(
                   {Import-Certificate -FilePath C:\temp\somerootca.cer -CertStoreLocation cert:\localmachine\disallowed}
               )
           )

Spawn a process on the remote computer

Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "powershell.exe -encodedcommand $encoded" -ComputerName Computer1

You will get output similar to the following on your computer

__GENUS          : 2
__CLASS          : __PARAMETERS
__SUPERCLASS     :
__DYNASTY        : __PARAMETERS
__RELPATH        :
__PROPERTY_COUNT : 2
__DERIVATION     : {}
__SERVER         :
__NAMESPACE      :
__PATH           :
ProcessId        : 8748
ReturnValue      : 0
PSComputerName   :

Note that the return value of 0 indicating success only indicates that powershell was spawned, not that the commands you executed were successful. If you want some logging you will need to bake it into the command you encode

EDIT: Foreach-Object and Get-Content

Get-Content C:\some\file\name\here.txt | Foreach-Object -begin {
    $encoded = [Convert]::ToBase64String(
               [System.Text.Encoding]::Unicode.GetBytes(
                   {Import-Certificate -FilePath C:\temp\somerootca.cer -CertStoreLocation cert:\localmachine\disallowed}
               )
           )
} -process {
    if(Test-Connection $_ -quiet){
        Copy-Item "C:\temp\SomeRootCa.cer" "\\$_\C$\temp\"
        Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList "powershell.exe -encodedcommand $encoded" -ComputerName $_
    }
}

Please do not copy/pasta this into a production environment. Read it and understand what is happening. Use the ISE to debug portions of the functions and piece it together bit by bit.


问:
Calling an ActionResult in a controller that isn't Home
I have a bit of javascript that is trying to POST to an ActionResult in a controller called Tables.  For some reason the routing isn't working.

My Javascript (in script tags at the top of my view):

```<code>$(document).ready(function () {
    $('#somevalue').autocomplete({
        source: '@Url.Action("Tables/GetExpenseTypes")'
    });
})
</code>```

My Controller:

```<code>public class TablesController : Controller
{
    public ActionResult GetExpenseTypes(string term)
    {
        return Json(Blah);
    }
}
</code>```

Whenever I execute the call, it returns a 404 Not Found error.  When I look at the request, it looks like this:

```<code>http://localhost:56569/Home/Tables/GetExpenseTypes
</code>```

If it matters, this is my RouteConfig.cs:

```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id =
    UrlParameter.Optional }
);
</code>```

Why does my request want to go to the Home controller no matter what?  If I precede the controller/Action with a forward slash:

```<code>$('#somevalue').autocomplete({
    source: '@Url.Action("/Tables/GetExpenseTypes")'
});
</code>```

It makes no difference, the request is still routed to the Home controller

答:
Because you are using the Url.Action helper incorrectly

Your current code is calling this overload

```<code>public virtual string Action(
    string actionName
)
</code>```

and you are passing Tables/GetExpenseTypes as the value of the actionName parameter. The helper method will use the current controller as the controller when building the url to this action method, hence you are getting /Home/Tables/GetExpenseTypes

You should use this overload

```<code>public virtual string Action(
    string actionName,
    string controllerName
)
</code>```

where you pass the action name and controller name as separate parameters

```<code>source: '@Url.Action("GetExpenseTypes","Tables")'
</code>```

This will generate the correct url.

Body:
I have a bit of javascript that is trying to POST to an ActionResult in a controller called Tables.  For some reason the routing isn't working.

My Javascript (in script tags at the top of my view):

$(document).ready(function () {
    $('#somevalue').autocomplete({
        source: '@Url.Action("Tables/GetExpenseTypes")'
    });
})

My Controller:

public class TablesController : Controller
{
    public ActionResult GetExpenseTypes(string term)
    {
        return Json(Blah);
    }
}

Whenever I execute the call, it returns a 404 Not Found error.  When I look at the request, it looks like this:

http://localhost:56569/Home/Tables/GetExpenseTypes

If it matters, this is my RouteConfig.cs:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id =
    UrlParameter.Optional }
);

Why does my request want to go to the Home controller no matter what?  If I precede the controller/Action with a forward slash:

$('#somevalue').autocomplete({
    source: '@Url.Action("/Tables/GetExpenseTypes")'
});

It makes no difference, the request is still routed to the Home controller

Body:
Because you are using the Url.Action helper incorrectly

Your current code is calling this overload

public virtual string Action(
    string actionName
)

and you are passing Tables/GetExpenseTypes as the value of the actionName parameter. The helper method will use the current controller as the controller when building the url to this action method, hence you are getting /Home/Tables/GetExpenseTypes

You should use this overload

public virtual string Action(
    string actionName,
    string controllerName
)

where you pass the action name and controller name as separate parameters

source: '@Url.Action("GetExpenseTypes","Tables")'

This will generate the correct url.


问:
How to search for a letter in a user generated word
Would like the code in choice 2 to search for a letter in the word created from choice 1. I can not seem to find a solution to this.</p>

```<code>if choice==1:
    print ("Enter a Word")
    minput= input()

    wordList= list (minput)
    print (wordList)

    mainMenu()

if choice==2:
    letter=['a,b,c,d, e, f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z']
    counter=0
    searchletter=input('Enter letter to search\t')

    while counter<len(letter) and searchletter!=letter[counter]:
        counter+=1
    if counter <len(letter):
        print(searchletter,'found')
    else:
        print(searchletter, ' Not found')
        mainMenu()
</code>```

答:
Your problem is in the while loop. Currently, when searching, your loop exits at the first character that isn't your search letter. Instead, you could simply use

```<code>print("found" if searchletter in word else "not found")
</code>```

and put the variable name for your word in word.

```<code>>>> word = "testme"
>>> searchletter = "t"
>>> print("found" if searchletter in word else "not found")
found
>>> searchletter = "f"
>>> print("found" if searchletter in word else "not found")
not found
</code>```

Body:
Would like the code in choice 2 to search for a letter in the word created from choice 1. I can not seem to find a solution to this.

if choice==1:
    print ("Enter a Word")
    minput= input()

    wordList= list (minput)
    print (wordList)

    mainMenu()

if choice==2:
    letter=['a,b,c,d, e, f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z']
    counter=0
    searchletter=input('Enter letter to search\t')

    while counter<len(letter) and searchletter!=letter[counter]:
        counter+=1
    if counter <len(letter):
        print(searchletter,'found')
    else:
        print(searchletter, ' Not found')
        mainMenu()

Body:
Your problem is in the while loop. Currently, when searching, your loop exits at the first character that isn't your search letter. Instead, you could simply use

print("found" if searchletter in word else "not found")

and put the variable name for your word in word.

>>> word = "testme"
>>> searchletter = "t"
>>> print("found" if searchletter in word else "not found")
found
>>> searchletter = "f"
>>> print("found" if searchletter in word else "not found")
not found


问:
Correctly passing parameters to setTimeout
I am working on a Node.js project, and I am having issues wrapping a Promise function with a setTimeout function.

My original Promise function:

I want to wrap this function in a call to setTimeout() but am having trouble passing in the Promise object. I need the Promise object and the data object available inside the setTimeout() function, but when I pass them into setTimeout() as parameters i still get the following error:

TypeError: Cannot read property 'then' of undefined

My code:

```<code>return Promise.props(data).then(function (data) {
    data.companies = data.order && data.order.companies;
    if (!data.companies) {
        data.companies = {};
        data.companies[data.company.id] = data.company;
    }

    if (data.order) {
        if (data.order.contactentry) {
            data.order.pointofcontact = data.order.contactentry + ' ' + phone(data.order.contactentryphone);
        } else if (data.order.borrowername) {
            data.order.pointofcontact = data.order.borrowername + ' ' + phone(data.order.borrowerphone);
        } else if (data.order.lockboxcode) {
            data.order.pointofcontact = 'Lockbox ' + data.order.lockboxcode
        }
    }

    if (data.part && data.order && data.part.vendor) {
        var oid = data.order && data.order.id;
        var vid = data.part && data.part.vendor && data.part.vendor.id;
        if (!oid || !vid) {
            var e = new Error('Could not assemble vendor accept url, order id or part vendor id are missing')
            log.error({
                error: e,
                data,
            }, e.message);
            throw e;
        }
    }

    return data;
});
</code>```

The data object is available inside the function when passed in as a parameter, but the Promise object is not.
How can I properly pass in the Promise object to make it available inside setTimeout()?

答:
You're approaching this inside-out. When you want to incorporate non-promise async code (such as setTimeout) into your promise-based code, you should isolate the wrapped non-promise part instead of getting it mixed too deep in the rest of your promise code.

Promise wrapper for setTimeout:

```<code>function delay(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}
</code>```

Then you can use it:

```<code>return Promise.props(data)
    .then(function (result) {
      return delay(1000).return(result);
    });
</code>```

Since you appear to be using Bluebird, you can also skip all the setTimeout stuff and use the built-in .delay method:

```<code>return Promise.props(data).delay(1000);
</code>```

Note that either of the above will add an additional 1 second delay to the time it takes to resolve all of the promises in data. If your goal is to just make it so that the minimum total time is 1 second, then you can use my approach from this question:

```<code>return Promise.delay(1000).return(Promise.props(data));
</code>```

Body:
I am working on a Node.js project, and I am having issues wrapping a Promise function with a setTimeout function.

My original Promise function:

I want to wrap this function in a call to setTimeout() but am having trouble passing in the Promise object. I need the Promise object and the data object available inside the setTimeout() function, but when I pass them into setTimeout() as parameters i still get the following error:

TypeError: Cannot read property 'then' of undefined

My code:

return Promise.props(data).then(function (data) {
    data.companies = data.order && data.order.companies;
    if (!data.companies) {
        data.companies = {};
        data.companies[data.company.id] = data.company;
    }

    if (data.order) {
        if (data.order.contactentry) {
            data.order.pointofcontact = data.order.contactentry + ' ' + phone(data.order.contactentryphone);
        } else if (data.order.borrowername) {
            data.order.pointofcontact = data.order.borrowername + ' ' + phone(data.order.borrowerphone);
        } else if (data.order.lockboxcode) {
            data.order.pointofcontact = 'Lockbox ' + data.order.lockboxcode
        }
    }

    if (data.part && data.order && data.part.vendor) {
        var oid = data.order && data.order.id;
        var vid = data.part && data.part.vendor && data.part.vendor.id;
        if (!oid || !vid) {
            var e = new Error('Could not assemble vendor accept url, order id or part vendor id are missing')
            log.error({
                error: e,
                data,
            }, e.message);
            throw e;
        }
    }

    return data;
});

The data object is available inside the function when passed in as a parameter, but the Promise object is not.
How can I properly pass in the Promise object to make it available inside setTimeout()?

Body:
You're approaching this inside-out. When you want to incorporate non-promise async code (such as setTimeout) into your promise-based code, you should isolate the wrapped non-promise part instead of getting it mixed too deep in the rest of your promise code.

Promise wrapper for setTimeout:

function delay(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}

Then you can use it:

return Promise.props(data)
    .then(function (result) {
      return delay(1000).return(result);
    });

Since you appear to be using Bluebird, you can also skip all the setTimeout stuff and use the built-in .delay method:

return Promise.props(data).delay(1000);

Note that either of the above will add an additional 1 second delay to the time it takes to resolve all of the promises in data. If your goal is to just make it so that the minimum total time is 1 second, then you can use my approach from this question:

return Promise.delay(1000).return(Promise.props(data));


问:
How can I combine chai-things and chai-like?
I want to write a NodeJS chai test which checks that the result of some service-call (which is an array) contains an object which is equal to what I expect. There might be some more fields in the result which I don't want to check.

There are two chai plugins which can solve this problem: chai-things (which allows you to use a syntax like expect(i).to.include.something.that.deep.equals) and chai-like (which allows you to use a syntax like expect(i).to.be.like).

But, in combination they don't work.

See this minimal working example:

```<code>const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-things'))
chai.use(require('chai-like'))

describe('the chai setup', function() {
  it('should work', function(done) {
    const i = [{
      name: 'Name A',
      age: 1
    }, {
      name: 'Name B',
      age: 2
    }]

    // Works
    expect(i).to.include.something.that.deep.equals({
      name: 'Name B',
      age: 2
    })

    // Works
    expect(i[1]).to.be.like({
      name: 'Name B'
    })

    // Doesn't work
    expect(i).to.include.something.that.like({
      name: 'Name B'
    })
    done()
  })
})
</code>```

This doesn't work and throws an error message:

AssertionError: expected { name: 'Name B', age: 2 } to like { name:
  'Name B' }

How can this be fixed?

答:
Load chai-like before loading chai-things to make them work together:

```<code>chai.use(require('chai-like'))
chai.use(require('chai-things'))
</code>```

Body:
I want to write a NodeJS chai test which checks that the result of some service-call (which is an array) contains an object which is equal to what I expect. There might be some more fields in the result which I don't want to check.

There are two chai plugins which can solve this problem: chai-things (which allows you to use a syntax like expect(i).to.include.something.that.deep.equals) and chai-like (which allows you to use a syntax like expect(i).to.be.like).

But, in combination they don't work.

See this minimal working example:

const chai = require('chai')
const expect = chai.expect
chai.use(require('chai-things'))
chai.use(require('chai-like'))

describe('the chai setup', function() {
  it('should work', function(done) {
    const i = [{
      name: 'Name A',
      age: 1
    }, {
      name: 'Name B',
      age: 2
    }]

    // Works
    expect(i).to.include.something.that.deep.equals({
      name: 'Name B',
      age: 2
    })

    // Works
    expect(i[1]).to.be.like({
      name: 'Name B'
    })

    // Doesn't work
    expect(i).to.include.something.that.like({
      name: 'Name B'
    })
    done()
  })
})

This doesn't work and throws an error message:

AssertionError: expected { name: 'Name B', age: 2 } to like { name:
  'Name B' }

How can this be fixed?

Body:
Load chai-like before loading chai-things to make them work together:

chai.use(require('chai-like'))
chai.use(require('chai-things'))


问:
What does testing if a variable is not equal to nothing do?
I came across SAS code recently that looks something like this:

```<code>%if var_name ~= %then %do;
    flag = 1;
%end;
</code>```

I understand that ~= means "not equal", but there appears to be nothing here for the variable to be compared to. Can someone shed any light on this syntax?

I've ruled out the possibility that this is shorthand for identifying missing observations: the flag is generated regardless of whether var_name contains any missing observations. That being said, it does the exact same thing as the code that you would think would actually do this:

```<code>%if var_name ~= . %then %do;
    flag = 1;
%end;
</code>```

The above also generates a flag with value 1 for all observations.

Any help on this greatly appreciated as I am quite new to SAS!

答:
Bestimate: The macro expression is emitting flag=1; as an unconditional DATA step statement .

"Coming across SAS code" can be anywhere on the continuum of a singularly rewarding experience to a journey into a deep dark place.

The snippet

```<code>%if var_name ~= . %then %do;
    flag = 1;
%end;
</code>```

is construct consistent with someone who is learning macro and does not yet grok the scopes and environments within a SAS session.  Macro variables and statements do not mingle with running data step variables and statements.  Macro programming typically controls what is eventually seen as the DATA or PROC step source code that needs to be run.

There can be legitimate reasons for the snippet and therein starts your journey.

%IF expression %THEN statement; involves the resolution of a macro logical expression.

The expression is implicitly resolved and evaluated to be zero (false) or non-zero (true).  Expressions that can not be resolved down to a non-missing numeric value at macro evaluation time will log an ERROR:

NOTE: Macro evaluation time is long gone by the time the SAS executor has compiled and is executing the DATA Step. SAS Documentation is pretty awesome, use it!.

Your var_name ~= expression is always true.

```<code>%put NOTE: %nrstr(%eval(var_name ~=)) resolves to %eval(var_name ~=);
----
NOTE: %eval(var_name ~=) resolves to 1
</code>```

Because the %IF expression always resolves to true the %THEN statement is always resolved and emitted as source code to be consumed by the SAS executor.

So in your case the source code flag = 1; is emitted, ostensibly as part of a DATA step in which the flag assignment is unconditional.

Many times the statement is another macro expression that does not emit anything and instead performs an action that affects the macro state at the current macro scope -- For example %IF &variable=&target %THEN %let target_met=1;.

The statements around the one you noticed are really clues to whether the %IF is correct and what it should be.  What could it be?

Does the data set be processed actually have a column named var_name ?
Maybe you are dealing with metadata output by Proc CONTENTS, SQL DICTIONARY.COLUMNS or working in a framework that uses control data for generating statements.

A goofup wherein the %if - %then should really be a data step if -then and the var_name should have been replaced with an actual variable name found in the data set being processed.

Working in a code generating framework where non-empty symbols representing data step variables are used to generate data step if-then statements

The code is the work of a madman, mad genius, or village idiot.

Happy coding!

Body:
I came across SAS code recently that looks something like this:

%if var_name ~= %then %do;
    flag = 1;
%end;

I understand that ~= means "not equal", but there appears to be nothing here for the variable to be compared to. Can someone shed any light on this syntax?

I've ruled out the possibility that this is shorthand for identifying missing observations: the flag is generated regardless of whether var_name contains any missing observations. That being said, it does the exact same thing as the code that you would think would actually do this:

%if var_name ~= . %then %do;
    flag = 1;
%end;

The above also generates a flag with value 1 for all observations.

Any help on this greatly appreciated as I am quite new to SAS!

Body:
Bestimate: The macro expression is emitting flag=1; as an unconditional DATA step statement .

"Coming across SAS code" can be anywhere on the continuum of a singularly rewarding experience to a journey into a deep dark place.

The snippet

%if var_name ~= . %then %do;
    flag = 1;
%end;

is construct consistent with someone who is learning macro and does not yet grok the scopes and environments within a SAS session.  Macro variables and statements do not mingle with running data step variables and statements.  Macro programming typically controls what is eventually seen as the DATA or PROC step source code that needs to be run.

There can be legitimate reasons for the snippet and therein starts your journey.

%IF expression %THEN statement; involves the resolution of a macro logical expression.

The expression is implicitly resolved and evaluated to be zero (false) or non-zero (true).  Expressions that can not be resolved down to a non-missing numeric value at macro evaluation time will log an ERROR:

NOTE: Macro evaluation time is long gone by the time the SAS executor has compiled and is executing the DATA Step. SAS Documentation is pretty awesome, use it!.

Your var_name ~= expression is always true.

%put NOTE: %nrstr(%eval(var_name ~=)) resolves to %eval(var_name ~=);
----
NOTE: %eval(var_name ~=) resolves to 1

Because the %IF expression always resolves to true the %THEN statement is always resolved and emitted as source code to be consumed by the SAS executor.

So in your case the source code flag = 1; is emitted, ostensibly as part of a DATA step in which the flag assignment is unconditional.

Many times the statement is another macro expression that does not emit anything and instead performs an action that affects the macro state at the current macro scope -- For example %IF &variable=&target %THEN %let target_met=1;.

The statements around the one you noticed are really clues to whether the %IF is correct and what it should be.  What could it be?

Does the data set be processed actually have a column named var_name ?
Maybe you are dealing with metadata output by Proc CONTENTS, SQL DICTIONARY.COLUMNS or working in a framework that uses control data for generating statements.

A goofup wherein the %if - %then should really be a data step if -then and the var_name should have been replaced with an actual variable name found in the data set being processed.

Working in a code generating framework where non-empty symbols representing data step variables are used to generate data step if-then statements

The code is the work of a madman, mad genius, or village idiot.

Happy coding!