答:
You need to look at this way,

your code <------ client code

Client code will be trying to access your code. With Encapsulation, your data will be safe from manipulation that can be done by the client code. It will help in specifying the accessibility limit.

To give an Example,

You are building a game and you wouldn't want someone to increase the health of your character (manipulate the fixed data)

```<code>public class GameCharacter {

public int Health{ get; }

public GameCharacter ()
{
    Health = 100;
}

}
</code>```

No one can change the Health!

Title: What is the purpose of Encapsulation? Does it provide a security layer?

Body: As much as I have studied about encapsulation it is about hiding data to prevent from manipulation. For that we declare the private variables so that couldn't be accessible from out of class. But we can implement or access them out of class using setter getter method. So if we have to implement it using setter getter method than any other person can implement it using setter getter method. . So how we are safe from manipulation??

Body:
You need to look at this way,

your code <------ client code

Client code will be trying to access your code. With Encapsulation, your data will be safe from manipulation that can be done by the client code. It will help in specifying the accessibility limit.

To give an Example,

You are building a game and you wouldn't want someone to increase the health of your character (manipulate the fixed data)

public class GameCharacter {

public int Health{ get; }

public GameCharacter ()
{
    Health = 100;
}

}

No one can change the Health!


来源: stackexchange

问:
how to include custom message in email using google apps script
i've written the following function, which is designed to check the status of a webpage, then email the result to defined recipients (toList).

```<code>function testStatusNotif() {
  var url = hostname + "/monitoring";
  var listTo = listGroup;
  var response = UrlFetchApp.fetch(url, params);
  if(response.getResponseCode() !== 200) {
    var message = 'Failed (test): response ' + response.getResponseCode();
    MailApp.sendEmail(listTo, "check the platform is up and operational", message);
  } else {
    var message = 'Passed (test): response ' + response.getResponseCode();
    MailApp.sendEmail(listTo, "trade platform is ready to open", message);
  }
}
</code>```

while this function works as is, i want to separate the sendMail steps into their own functions. the key driver is because i want to cater for more scenarios as well as have different recipients and messages for each of the scenarios. i also want to reuse the sendMail functions for other tests. however when i separate them out, i get undefined in place of message.

here's an example of the check that returns undefined.

```<code>function testStatusNotif() {
  var url = hostname + "/monitoring";
  var response = UrlFetchApp.fetch(url, params);
  if(response.getResponseCode() !== 200) {
    var message = 'Failed (test): response ' + response.getResponseCode();
    failEmail(message);
  } else {
    var message = 'Passed (test): response ' + response.getResponseCode();
    passEmail(message);
  }
  return message;
}

function failEmail() {
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", sampleCheck.message);
}
</code>```

can anyone tell me where i'm going wrong?

答:
The reason of undefined is that the value is not accepted at the function of failEmail. If you want to give message to failEmail(message) and passEmail(message), please modify as follows.

From:

```<code>function failEmail() {
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", sampleCheck.message);
}
</code>```

To:

```<code>function failEmail(message) { // Modified
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", message); // Modified
}
</code>```

Note:

About the object of sampleCheck, I'm not sure from your script. So I modified to message.

Although I'm not sure about the function of passEmail(message), if the situation is the same with failEmail(message), please modify as the same way.

If I misunderstood your question and this was not the result you want, I apologize.

ContentLicense: CC BY-SA 4.0

Body:
i've written the following function, which is designed to check the status of a webpage, then email the result to defined recipients (toList).

function testStatusNotif() {
  var url = hostname + "/monitoring";
  var listTo = listGroup;
  var response = UrlFetchApp.fetch(url, params);
  if(response.getResponseCode() !== 200) {
    var message = 'Failed (test): response ' + response.getResponseCode();
    MailApp.sendEmail(listTo, "check the platform is up and operational", message);
  } else {
    var message = 'Passed (test): response ' + response.getResponseCode();
    MailApp.sendEmail(listTo, "trade platform is ready to open", message);
  }
}

while this function works as is, i want to separate the sendMail steps into their own functions. the key driver is because i want to cater for more scenarios as well as have different recipients and messages for each of the scenarios. i also want to reuse the sendMail functions for other tests. however when i separate them out, i get undefined in place of message.

here's an example of the check that returns undefined.

function testStatusNotif() {
  var url = hostname + "/monitoring";
  var response = UrlFetchApp.fetch(url, params);
  if(response.getResponseCode() !== 200) {
    var message = 'Failed (test): response ' + response.getResponseCode();
    failEmail(message);
  } else {
    var message = 'Passed (test): response ' + response.getResponseCode();
    passEmail(message);
  }
  return message;
}

function failEmail() {
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", sampleCheck.message);
}

can anyone tell me where i'm going wrong?

Body:
The reason of undefined is that the value is not accepted at the function of failEmail. If you want to give message to failEmail(message) and passEmail(message), please modify as follows.

From:

function failEmail() {
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", sampleCheck.message);
}

To:

function failEmail(message) { // Modified
  var listTo = listFails;
  MailApp.sendEmail(listTo, "check the platform is up and operational", message); // Modified
}

Note:

About the object of sampleCheck, I'm not sure from your script. So I modified to message.

Although I'm not sure about the function of passEmail(message), if the situation is the same with failEmail(message), please modify as the same way.

If I misunderstood your question and this was not the result you want, I apologize.


问:
Dataframe slicing on multiple conditions Python
I have a dataframe with 3 columns:

```<code>df:

x       y      z
334     290    3350.0
334     291    3350.5
334     292    3360.1
335     292    3360.1
335     292    3360.1
335     290    3351.0
335     290    3352.5
335     291    3333.1
335     291    3333.1
.
.
</code>```

I'd like to check and parse values of each row from row = n to row = n+7 into a new dataframe based on a couple of conditions:

df[n] != df[n+1]

df[n] != df[n+3]

df[n] != df[n+5]

df['x'][n] < df['x'][n+2]

df['x'][n] > df['x'][n+3]

If all of these are satisfied I want to write a new dataframe:

```<code>df_new = pd.concat([df[n], df[n+1], df[n+2], df[n+3],
df[n+4], df[n+5], df[n+6], df[n+7]])
</code>```

So the algorithm + output would look like:

```<code>for df[n] = 0:
1) [334     290    3350.0] != [334     291    3350.5]  True
2) [334     290    3350.0] != [335     292    3360.1]  True
3) [334     290    3350.0] != [335     290    3351.0]  True
4) 335 < 334  False
5) 335 > 335  False
</code>```

So in this case it would skip the first iteration until we've gone down the entire length of the dataframe and made matches.

df_new(first iteration) = df_new.concat([....]) = empty row values

Is there an easy way to do this with speed in Pandas?

答:
I changed slightly your sample data, to have one positive result:

```<code>df = pd.DataFrame(data=[
    [ 334, 290, 3350.0 ],
    [ 334, 291, 3350.5 ],
    [ 334, 292, 3360.1 ],
    [ 335, 292, 3360.1 ],
    [ 335, 292, 3360.1 ],
    [ 333, 290, 3351.0 ],
    [ 335, 290, 3352.5 ],
    [ 335, 291, 3333.1 ],
    [ 335, 291, 3333.1 ]], columns=['x', 'y', 'z'])
</code>```

Then, for efficiency reason, I defined the following function:

```<code>def roll_win(a, win):
    shape = (a.shape[0] - win + 1, win, a.shape[1])
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
</code>```

It generates a 3-D table, where 2nd and 3rd dimension are "rolling
windows" from the source Numpy array a. The size of window is win,
sliding vertically.
This way, processing of consecutive windows requires a loop running along
the first axis of the generated table (see below).

Due to usage of as_strided function it runs significantly quicker than
any "ordinary" Python loop (compare execution time with other solutions).

I couldn't use rolling windows provided by Pandas, because they were
created to compute some statistics, not for calling any user function
on the whole content of the current window.

Then I call this function:

```<code>tbl = roll_win(df.values, 7)
</code>```

Note that Numpy array must have a single element type, so this
type is "generalized" to float because one source column is of
float type.

Then we have preparation steps for a loop processing each rolling window:

```<code>res = []    # Result container
idx = 0     # Rolling window index
</code>```

The rest of the program is the loop:

```<code>while idx < len(tbl):
    tt = tbl[idx]  # Get the current rolling window (2-D)
    r0 = tt[0]     # Row 0
    # Condition
    cond = not((r0 == tt[1]).all() and (r0 == tt[3]).all()\
        and (r0 == tt[5]).all()) and tt[0][0] < tt[2][0]\
        and tt[0][0] > tt[3][0]
    if cond:   # OK
        # print(idx)
        # print(tt)
        res.extend(tt)  # Add to result
        idx += 7        # Skip the current result
    else:      # Failed
        idx += 1        # Next loop for the next window
</code>```

In the "positive" case, I decided to start the next loop from the row
following the current match (idx += 7), to avoid possible partially
overlapping sets of source rows.
If you don't want this feature, add 1 do idx in both cases.

For demonstration purpose, you can uncomment test printouts above.

The only remaining thing is to create the target DataFrame, from rows
collected in res:

```<code>df2 = pd.DataFrame(data=res, columns=['x', 'y', 'z'], dtype=int)
</code>```

Note that dtype=int will be obeyed only for x and y columns,
because values in z column have fractional part.

Body:
I have a dataframe with 3 columns:

df:

x       y      z
334     290    3350.0
334     291    3350.5
334     292    3360.1
335     292    3360.1
335     292    3360.1
335     290    3351.0
335     290    3352.5
335     291    3333.1
335     291    3333.1
.
.

I'd like to check and parse values of each row from row = n to row = n+7 into a new dataframe based on a couple of conditions:

df[n] != df[n+1]

df[n] != df[n+3]

df[n] != df[n+5]

df['x'][n] < df['x'][n+2]

df['x'][n] > df['x'][n+3]

If all of these are satisfied I want to write a new dataframe:

df_new = pd.concat([df[n], df[n+1], df[n+2], df[n+3],
df[n+4], df[n+5], df[n+6], df[n+7]])

So the algorithm + output would look like:

for df[n] = 0:
1) [334     290    3350.0] != [334     291    3350.5]  True
2) [334     290    3350.0] != [335     292    3360.1]  True
3) [334     290    3350.0] != [335     290    3351.0]  True
4) 335 < 334  False
5) 335 > 335  False

So in this case it would skip the first iteration until we've gone down the entire length of the dataframe and made matches.

df_new(first iteration) = df_new.concat([....]) = empty row values

Is there an easy way to do this with speed in Pandas?

Body:
I changed slightly your sample data, to have one positive result:

df = pd.DataFrame(data=[
    [ 334, 290, 3350.0 ],
    [ 334, 291, 3350.5 ],
    [ 334, 292, 3360.1 ],
    [ 335, 292, 3360.1 ],
    [ 335, 292, 3360.1 ],
    [ 333, 290, 3351.0 ],
    [ 335, 290, 3352.5 ],
    [ 335, 291, 3333.1 ],
    [ 335, 291, 3333.1 ]], columns=['x', 'y', 'z'])

Then, for efficiency reason, I defined the following function:

def roll_win(a, win):
    shape = (a.shape[0] - win + 1, win, a.shape[1])
    strides = (a.strides[0],) + a.strides
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

It generates a 3-D table, where 2nd and 3rd dimension are "rolling
windows" from the source Numpy array a. The size of window is win,
sliding vertically.
This way, processing of consecutive windows requires a loop running along
the first axis of the generated table (see below).

Due to usage of as_strided function it runs significantly quicker than
any "ordinary" Python loop (compare execution time with other solutions).

I couldn't use rolling windows provided by Pandas, because they were
created to compute some statistics, not for calling any user function
on the whole content of the current window.

Then I call this function:

tbl = roll_win(df.values, 7)

Note that Numpy array must have a single element type, so this
type is "generalized" to float because one source column is of
float type.

Then we have preparation steps for a loop processing each rolling window:

res = []    # Result container
idx = 0     # Rolling window index

The rest of the program is the loop:

while idx < len(tbl):
    tt = tbl[idx]  # Get the current rolling window (2-D)
    r0 = tt[0]     # Row 0
    # Condition
    cond = not((r0 == tt[1]).all() and (r0 == tt[3]).all()\
        and (r0 == tt[5]).all()) and tt[0][0] < tt[2][0]\
        and tt[0][0] > tt[3][0]
    if cond:   # OK
        # print(idx)
        # print(tt)
        res.extend(tt)  # Add to result
        idx += 7        # Skip the current result
    else:      # Failed
        idx += 1        # Next loop for the next window

In the "positive" case, I decided to start the next loop from the row
following the current match (idx += 7), to avoid possible partially
overlapping sets of source rows.
If you don't want this feature, add 1 do idx in both cases.

For demonstration purpose, you can uncomment test printouts above.

The only remaining thing is to create the target DataFrame, from rows
collected in res:

df2 = pd.DataFrame(data=res, columns=['x', 'y', 'z'], dtype=int)

Note that dtype=int will be obeyed only for x and y columns,
because values in z column have fractional part.


问:
ReferenceError while using onclick in codesandbox website
I'm writing a Vanilla JS program in codesandbox environment as shown below:

function Game() {
  alert("hi");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
}

td:first-child {
  border-left-width: 0px;
}

td:last-child {
  border-right-width: 0px;
}

table tr:nth-child(1) td {
  border-top-width: 0px;
}

table tr:nth-child(3) td {
  border-bottom-width: 0px;
}</code>```

<!DOCTYPE html>

    <title>Tic-Tac-Toe</title>
    <meta charset="UTF-8" />

```
</div>
</div>
</p>

<p>When I execute the above code snippet in codesandbox.io then it gives below error:</p>

<blockquote>
  <p>ReferenceError Game is not defined</p>
</blockquote>

<p>Not sure why the execution environment of codesandbox is unable to detect the <code>Game</code> function. If I write the <code>alert</code> statement outside the function then it gets called successfully on page load:</p>

```alert("hi");

function Game() {

}
```

I've linked the external JS and CSS files correctly in the head tag of the HTML page.

答:
You need to define the function as a variable attached to the global window object. Try defining the function like this:

```<code>window.Game = function() {
  alert("hi");
}
</code>```

Alternatively, instead of an inline onclick event handler try giving the table element an id such as game-table and then add an event listener:

```<code>document.querySelector('#game-table').addEventListener('click', Game);
</code>```

Body:
I'm writing a Vanilla JS program in codesandbox environment as shown below:

function Game() {
  alert("hi");
}

body {
  font-family: sans-serif;
}

table {
  border-collapse: collapse;
}

td {
  border: 1px solid black;
}

td:first-child {
  border-left-width: 0px;
}

td:last-child {
  border-right-width: 0px;
}

table tr:nth-child(1) td {
  border-top-width: 0px;
}

table tr:nth-child(3) td {
  border-bottom-width: 0px;
}

<!DOCTYPE html>

    <title>Tic-Tac-Toe</title>
    <meta charset="UTF-8" />

When I execute the above code snippet in codesandbox.io then it gives below error:

ReferenceError Game is not defined

Not sure why the execution environment of codesandbox is unable to detect the Game function. If I write the alert statement outside the function then it gets called successfully on page load:

alert("hi");

function Game() {

}

I've linked the external JS and CSS files correctly in the head tag of the HTML page.

Body:
You need to define the function as a variable attached to the global window object. Try defining the function like this:

window.Game = function() {
  alert("hi");
}

Alternatively, instead of an inline onclick event handler try giving the table element an id such as game-table and then add an event listener:

document.querySelector('#game-table').addEventListener('click', Game);


问:
How to remove several elements of a list by the index which can be changed each time?
I have a list like below:

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

After using enumerate I have the following list:

```<code>A = [(0, 1), (1, 2), (2, 3), (3, 4)]
</code>```

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

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

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

```<code>A_reduced = [2, 4]

</code>```

答:
If you want to read the index from the condA list and create the list of that number, the list of indices of elements to be removed will be like:

```<code>rm_lst = [x[0] for x in condA]
</code>```

Now, to remove the elements from your main list:

```<code>A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]
</code>```

Final Code:

```<code>A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
condA = [(0, ((11), (452))), (2, ((545), (757)))]
rm_lst = [x[0] for x in condA]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]
print(A_reduced)
</code>```

Body:
I have a list like below:

A =  [1, 2, 3, 4]

After using enumerate I have the following list:

A = [(0, 1), (1, 2), (2, 3), (3, 4)]

After checking a condition, I realized that I don't need the elements with index 0 and 2.
It means that my condition returns a list like below which can be different each time:

condA = [(0, 1), (2, 3)]

I know that I can use del or .pop() to remove an element from a list.
However, I was wondering how can I read the numbers like (0) and (2) in my condA list and remove those elements from my original list.
I don't want to enter the 0 and 2 in my code because each time they would be different.

The result would be like this:

A_reduced = [2, 4]

Body:
If you want to read the index from the condA list and create the list of that number, the list of indices of elements to be removed will be like:

rm_lst = [x[0] for x in condA]

Now, to remove the elements from your main list:

A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]

Final Code:

A = [(0, ((11), (12))), (1, ((452), (54))), (2, ((545), (757))), (3, ((42), (37)))]
condA = [(0, ((11), (452))), (2, ((545), (757)))]
rm_lst = [x[0] for x in condA]
A_reduced = [x[1] for x in A if x[0] not in rm_lst]
print(A_reduced)


问:
How to remove all `input` elements which are lager then this one who calls the function?
I'm trying to remove all input element until for loop is reatching the one how trigger the function.

Issues, can i use the remove to delete it from the dom?
second issue it is possible to select the ´class´ so that I can delete/remove it?
They all have the same classname.

I create new INPUT and insert the ID in an ARRAY

```<code>function child_input(element) {
  if (order_input.length-1 == 2) {
    alert("ritch lenght")
    return false;
  }
  if (order_input.length-1 >= 2) {
    alert("Fail!!")
  }
  element = document.createElement('input');
  element.type = "number";
  element.classList.add('dropNew');
  element.id = "input"+counter+"";
  element.onmouseleave = function mouseLeave() {
    if (element.value != "") {
      element.readOnly = true;
      element.classList.add('unWriteable');
      element.onmouseleave = false;
      child_input();
      element.addEventListener('dblclick', function() {
        element.classList.remove('unWriteable');
        element.readOnly = false;
        element.onmouseleave = function() {
          //hier würde ich immer den input(child) vorigen löschen...
          mouseLeave();
          removeChild_input(this.id);
        }
      });
    }
  }
  document.querySelector('.Main_Div').append(element);
  order_input.push(element);
  counter++;
}

</code>```

It can be know a little bit difficult to understand!!
If I now dbclick one of these four input (example the second one) I would like the following input to be deleted. (number 4,3 have be to removed).

```<code>  //hold the oldest, and remove all child
    let delete_item = document.querySelector('#'+ id);
    let num_id = id.replace("input", " ");
    num_id = parseInt(num_id);

    for (var i = order_input.length-1; i >= num_id; i--) {
      order_input.slice(-1);
      order_input.pop();
      document.querySelector(".dropNew")[i].remove();
    }
    console.log(order_input.length-1);
}
</code>```

答:
I had to use document.querySelectorAll('+class+')[i].remove()

whole function..,

to delete until the input which trigger the function.

```<code>for (var i = order_input.length-1; i >= num_id; i--) {
      order_input.slice(-1);
      order_input.pop();
      document.querySelectorAll(".dropNew")[i].remove();
    }
</code>```

wish u guys a good night.
 Thx for the help. refocus ;)

Body:
I'm trying to remove all input element until for loop is reatching the one how trigger the function.

Issues, can i use the remove to delete it from the dom?
second issue it is possible to select the ´class´ so that I can delete/remove it?
They all have the same classname.

I create new INPUT and insert the ID in an ARRAY

function child_input(element) {
  if (order_input.length-1 == 2) {
    alert("ritch lenght")
    return false;
  }
  if (order_input.length-1 >= 2) {
    alert("Fail!!")
  }
  element = document.createElement('input');
  element.type = "number";
  element.classList.add('dropNew');
  element.id = "input"+counter+"";
  element.onmouseleave = function mouseLeave() {
    if (element.value != "") {
      element.readOnly = true;
      element.classList.add('unWriteable');
      element.onmouseleave = false;
      child_input();
      element.addEventListener('dblclick', function() {
        element.classList.remove('unWriteable');
        element.readOnly = false;
        element.onmouseleave = function() {
          //hier würde ich immer den input(child) vorigen löschen...
          mouseLeave();
          removeChild_input(this.id);
        }
      });
    }
  }
  document.querySelector('.Main_Div').append(element);
  order_input.push(element);
  counter++;
}

It can be know a little bit difficult to understand!!
If I now dbclick one of these four input (example the second one) I would like the following input to be deleted. (number 4,3 have be to removed).

  //hold the oldest, and remove all child
    let delete_item = document.querySelector('#'+ id);
    let num_id = id.replace("input", " ");
    num_id = parseInt(num_id);

    for (var i = order_input.length-1; i >= num_id; i--) {
      order_input.slice(-1);
      order_input.pop();
      document.querySelector(".dropNew")[i].remove();
    }
    console.log(order_input.length-1);
}

Body:
I had to use document.querySelectorAll('+class+')[i].remove()

whole function..,

to delete until the input which trigger the function.

for (var i = order_input.length-1; i >= num_id; i--) {
      order_input.slice(-1);
      order_input.pop();
      document.querySelectorAll(".dropNew")[i].remove();
    }

wish u guys a good night.
 Thx for the help. refocus ;)


问:
Core Data Store included in App Bundle
I can't find a clear description of these steps in Apple docs...

I have a xcdatamodeld in my xcode project

At launch time, my app parses a XML (project resource) to fill the Core Data Store (SQLLite)

During lifetime of my app, I add, remove, update data of that Store

Now, I want to stop doing that heavy XML parsing process on device and directly include a Store containing the required data.

I have some questions regarding this :

Can I fill a store with a OS X app and then include this store in my XCode-iOs project ?

My store does not appear in Xcode. In fact it is created at run time. How can I add a store in the project and link it to my xcdatamodeld ?

I have read that doing so will prevent my store from being writable... I guess I have to copy it in the right place at launch time (the Core Data utility Tutorial is a great help for that). Am I right ?

Thanks for your hints. URL or other SO questions would be really appreciate !

Kheraud

答:
You can include the store file (sqlite db most of the time) in your app.
Then in your app delegate edit the persistentStoreCoordinator getter merhod :</p>

```<code>- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CoreDataStore.sqlite"];

    // Check if the store exists in.
    if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) {
        // copy the payload to the store location.
        NSString *bundleStore = [[NSBundle mainBundle] pathForResource:@"YourPayload" ofType:@"sqlite"];

        NSError *error = nil;
        [[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:&error];

        if (error){
            NSLog(@"Error copying payload: %@", error);
        }
    }

    NSError *error = nil;
    NSURL *storeURL = [NSURL fileURLWithPath:storePath];
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator_;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Core Data Store included in App Bundle

Body:
You can include the store file (sqlite db most of the time) in your app.
Then in your app delegate edit the persistentStoreCoordinator getter merhod :

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

    if (persistentStoreCoordinator_ != nil) {
        return persistentStoreCoordinator_;
    }

    NSString *storePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CoreDataStore.sqlite"];

    // Check if the store exists in.
    if (![[NSFileManager defaultManager] fileExistsAtPath:storePath]) {
        // copy the payload to the store location.
        NSString *bundleStore = [[NSBundle mainBundle] pathForResource:@"YourPayload" ofType:@"sqlite"];

        NSError *error = nil;
        [[NSFileManager defaultManager] copyItemAtPath:bundleStore toPath:storePath error:&error];

        if (error){
            NSLog(@"Error copying payload: %@", error);
        }
    }

    NSError *error = nil;
    NSURL *storeURL = [NSURL fileURLWithPath:storePath];
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return persistentStoreCoordinator_;
}


问:
How to show category subcategory based on array
I have an array that consists of some data to show the category and subcategories.

```<code>{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}
</code>```

I want to sort and show this data something like this :

```<code>> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series
</code>```

答:
For a general solution, you can take your data and implement a light tree class where each node has a value and a list of children of the node. Then you can create an iterator or similar function that will do a depth-first traversal of the tree. It can return the depth information which will allow you print the values with the proper indentation.

let data = [{id: "5", parent_id: "0", lable: "Movie"},{id: "20", parent_id: "5", lable: "Action"},{id: "15", parent_id: "43", lable: "J.K Rowling"},{id: "43", parent_id: "0", lable: "Book"},{id: "2", parent_id: "20", lable: "James Bond Series"},{id: "3", parent_id: "0", lable: "Music"},{id: "39", parent_id: "15", lable: "Harry Potter Series"}]

class Node {
  constructor(id, value) {
      this.id = id
      this.value = value
      this.children = []
    }
    * getTree(depth = 0) {  // an iterator that yields itself and chidlren
      yield [this.value, depth]
      for (let child of this.children) {
        yield* child.getTree(depth + 1)
      }
    }
}

// Create the nodes using a helper object to keep track of IDs
// Make sure the parent exists (even without info) before trying to push children

let tree = data.reduce((tree, {id,parent_id, lable}) => {
  if (tree[id] === undefined) tree[id] = new Node(id, lable)
  else Object.assign(tree[id], {id,value: lable})

  if (tree[parent_id] == undefined) tree[parent_id] = new Node()

  tree[parent_id].children.push(tree[id])
  return tree
}, { 0: new Node(0, "root")})

// Root of the tree is at id 0
let root = tree[0]

// now iterate of the children using the depth for layout
for (let [node, depth] of root.getTree()) {
  console.log('>'.repeat(depth), node)
}

// Show only movies by starting at a different node:
console.log("----------- movies -------------")
let start = tree[5]
for (let [node, depth] of start.getTree()) {
  console.log('>'.repeat(depth), node)
}```

Body:
I have an array that consists of some data to show the category and subcategories.

{id: "5", parent_id: "0", lable: "Movie"}
{id: "20", parent_id: "5", lable: "Action"}
{id: "15", parent_id: "43", lable: "J.K Rowling"}
{id: "43", parent_id: "0", lable: "Book"}
{id: "20", parent_id: "2", lable: "James Bond Series"}
{id: "3", parent_id: "0", lable: "Music"}
{id: "39", parent_id: "15", lable: "Harry Potter Series"}

I want to sort and show this data something like this :

> Movie
>> Action
>>>James Bond Series

>Book
>>J.K Rowling
>>>Harry Potter Series


问:
How can I filter data from dropdown list?
I would like to filter state on my graph by dropdown list. For instance, I have density graph and dropdown of state list, when I change state graph should be changed as on state. However, with my code when I change the state, it has not something to happen.

My code :

SERVER

```<code>  output$overat <- renderPlot({
   filtered <-
   Medi_sum_small %>%
   filter(State == input$e1)
  ggplot(Medi_sum_small, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })
</code>```

UI

```<code>box(
              title = "Select State"
              ,width = 3
              ,solidHeader = TRUE
              ,status = "primary"
              ,selectInput(
                'e1', 'State',
                c("All",unique(Medi_sum_small$State))
              )

Graphs should be changed when I change the stage.
</code>```

答:
Now I can do it, I change my code to :

```<code> output$overat <- renderPlot({
    ggplot(filtered <-
             Medi_sum_small %>%
             filter(State == input$e1),
           aes(Hospital_Ownership)) +
      geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
      labs(x="Ownership",
           fill="Overall rating") +
      scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })
</code>```

Thank you so much

Body:
I would like to filter state on my graph by dropdown list. For instance, I have density graph and dropdown of state list, when I change state graph should be changed as on state. However, with my code when I change the state, it has not something to happen.

My code :

SERVER

  output$overat <- renderPlot({
   filtered <-
   Medi_sum_small %>%
   filter(State == input$e1)
  ggplot(Medi_sum_small, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })

UI

box(
              title = "Select State"
              ,width = 3
              ,solidHeader = TRUE
              ,status = "primary"
              ,selectInput(
                'e1', 'State',
                c("All",unique(Medi_sum_small$State))
              )

Graphs should be changed when I change the stage.

Body:
Now I can do it, I change my code to :

 output$overat <- renderPlot({
    ggplot(filtered <-
             Medi_sum_small %>%
             filter(State == input$e1),
           aes(Hospital_Ownership)) +
      geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
      labs(x="Ownership",
           fill="Overall rating") +
      scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })

Thank you so much


问:
Add Start and Stop point parameters to method that adds sums of numbers in a string
I am trying to modify a method from the post marked as duplicate that will allow me to enter a string containing numbers, like "Here are77 with88 monsters" which I adds the sum of the numbers in the string to return 14 and 16 if I evaluated the entire string. How would I enhance this method to evaluate start and stop points in the string? So if I wanted to evaluate position 3 through 10, it would return just 14, since 77 are numbers between positions 3 and 10?

I have done quite a bit of research, but I'm really new to Java, and don't know enough yet to figure this out. The code below is where I'm at now:

```<code>    String s = "Here are77 with 88 monsters";
    String[] st = s.split(" ");
    for (int i=0 ; i<st.length ; i++) {
        if (st[i].matches("[0-9]+")) {
            String[] c = st[i].split("(?=\\d)");
            int sum = 0;
            for(int j=0 ; j<c.length ; j++) {
                sum += Integer.parseInt(c[j]);
            }
          return sum;}
        }
</code>```

I need help to add the two extra position parameters so I can use this code above to calculate the sum of the digits within those margins in a method.

答: wouldn't your loop have dead code on i++? Since you will be returning out as soon as your first iteration is done.</p>

Body:
I am trying to modify a method from the post marked as duplicate that will allow me to enter a string containing numbers, like "Here are77 with88 monsters" which I adds the sum of the numbers in the string to return 14 and 16 if I evaluated the entire string. How would I enhance this method to evaluate start and stop points in the string? So if I wanted to evaluate position 3 through 10, it would return just 14, since 77 are numbers between positions 3 and 10?

I have done quite a bit of research, but I'm really new to Java, and don't know enough yet to figure this out. The code below is where I'm at now:

    String s = "Here are77 with 88 monsters";
    String[] st = s.split(" ");
    for (int i=0 ; i<st.length ; i++) {
        if (st[i].matches("[0-9]+")) {
            String[] c = st[i].split("(?=\\d)");
            int sum = 0;
            for(int j=0 ; j<c.length ; j++) {
                sum += Integer.parseInt(c[j]);
            }
          return sum;}
        }

I need help to add the two extra position parameters so I can use this code above to calculate the sum of the digits within those margins in a method.


问:
How to edit a previous plot in an R graphics device split by mfrow
I have an existing plotting function (perhaps written by someone else) that uses mfrow to plot multiple figures on the same graphics device.  I want to edit figures that have already been plotted (e.g. perhaps add a reference line to figure 1)

```<code>par(mfrow = c(1, 2))
plot(1:10)
hist(1:10)
# Oh no!  I want to add abline(a = 0, b = 1) to the first plot!
</code>```

Assume this code is nested in another plotting function
PlotABunchOfStuff(1:10) that I can't modify.

I don't want to modify PlotABunchOfStuff because someone else owns it, or I'm just debugging and won't need the extra details once the bug is found.

答:
If you are ready to use ggplot I think you can find what you want in the code below :

```<code>df <- data.frame(x = 1:10, y = 1:10)
g1 <- ggplot(df, aes(x = x, y = y)) +
  geom_point()
g2 <- ggplot(df, aes(x = x, y = y)) +
  geom_line()

grid.arrange(g1, g2)

g1 <- g1 + geom_smooth(method='lm',formula=y~x)  # it could be anything else !

grid.arrange(g1, g2)
</code>```

Edit 1

Create a graphical object in windows which will be destroye after dev.off() if filename = "" :

```<code>win.metafile(filename = "")
</code>```

By default inhibit doesn't allow the plot to be recorded so we use enable :

```<code>dev.control('enable')
plot(1:10)
p <- recordPlot()
dev.off()
replayPlot(p)

p
abline(a = 1, b = 1, col = "red")
p <- recordPlot()
dev.off()
replayPlot(p)
</code>```

My inspirations on Stackoverflow :

R plot without showing the graphic window
Save a plot in an object

My inspirations on R :

https://www.rdocumentation.org/packages/grDevices/versions/3.6.0/topics/dev
https://www.rdocumentation.org/packages/grDevices/versions/3.6.0/topics/recordPlot

I hope it helps you ! Good luck.

Body:
I have an existing plotting function (perhaps written by someone else) that uses mfrow to plot multiple figures on the same graphics device.  I want to edit figures that have already been plotted (e.g. perhaps add a reference line to figure 1)

par(mfrow = c(1, 2))
plot(1:10)
hist(1:10)
# Oh no!  I want to add abline(a = 0, b = 1) to the first plot!

Assume this code is nested in another plotting function
PlotABunchOfStuff(1:10) that I can't modify.

I don't want to modify PlotABunchOfStuff because someone else owns it, or I'm just debugging and won't need the extra details once the bug is found.

Body:
If you are ready to use ggplot I think you can find what you want in the code below :

df <- data.frame(x = 1:10, y = 1:10)
g1 <- ggplot(df, aes(x = x, y = y)) +
  geom_point()
g2 <- ggplot(df, aes(x = x, y = y)) +
  geom_line()

grid.arrange(g1, g2)

g1 <- g1 + geom_smooth(method='lm',formula=y~x)  # it could be anything else !

grid.arrange(g1, g2)

Edit 1

Create a graphical object in windows which will be destroye after dev.off() if filename = "" :

win.metafile(filename = "")

By default inhibit doesn't allow the plot to be recorded so we use enable :

dev.control('enable')
plot(1:10)
p <- recordPlot()
dev.off()
replayPlot(p)

p
abline(a = 1, b = 1, col = "red")
p <- recordPlot()
dev.off()
replayPlot(p)

My inspirations on Stackoverflow :

R plot without showing the graphic window
Save a plot in an object

My inspirations on R :

https://www.rdocumentation.org/packages/grDevices/versions/3.6.0/topics/dev
https://www.rdocumentation.org/packages/grDevices/versions/3.6.0/topics/recordPlot

I hope it helps you ! Good luck.


问:
How to link one page to another by hyperlink in Django?
I want to create a Home page through which I could go to the other pages that I have created. Suppose I have a home page in which I have two options:

Now, from this home page by click onto the My work option I want to go to another page where I have the information related to my work, how can I do so?

My home page HTML is:

```<code>{% extends 'base.html' %}
{% block content %} <h1>Home Page</h1>
 <ul>
     <li>My Achievements</li>
     <li> My Work</li> </ul>
{% endblock %}
</code>```

The base.html:

```<code><!DOCTYPE html> <html>
<head> </head>
 <body>
 {% block content %}
 {% endblock %}
 </body> </html>
</code>```

答:
I'd suggest taking a look at one of a number of tutorials for getting started with web development using Django.

https://docs.djangoproject.com/en/2.2/intro/tutorial01/
or
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website These should help you more deeply understand what you're asking as a question, and the technologies you're using. I'd also recommend browsing this link to learn a bit more about HTML itself and the various tags usable in it.

To more directly answer your question, the  tag mentioned by Abhijith is what's used to create a reference between pages.

Body:
I want to create a Home page through which I could go to the other pages that I have created. Suppose I have a home page in which I have two options:

Now, from this home page by click onto the My work option I want to go to another page where I have the information related to my work, how can I do so?

My home page HTML is:

{% extends 'base.html' %}
{% block content %}
Home Page

My Achievements

 My Work

{% endblock %}

The base.html:

<!DOCTYPE html>

 {% block content %}
 {% endblock %}

Body:
I'd suggest taking a look at one of a number of tutorials for getting started with web development using Django.

https://docs.djangoproject.com/en/2.2/intro/tutorial01/
or
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/skeleton_website These should help you more deeply understand what you're asking as a question, and the technologies you're using. I'd also recommend browsing this link to learn a bit more about HTML itself and the various tags usable in it.

To more directly answer your question, the <a> tag mentioned by Abhijith is what's used to create a reference between pages.


问:
Chromium: nvm is not compatible with the "npm_config_prefix" environment variable:
We are moving an Angular (Angular, NgRx and Angular Material Starter) based website from CircleCI to Shippable, and I'm now getting these failures:

```<code>27 05 2019 14:46:00.036:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
27 05 2019 14:46:00.040:INFO [launcher]: Launching browsers ChromeShippable with concurrency unlimited
27 05 2019 14:46:00.071:INFO [launcher]: Starting browser Chrome
27 05 2019 14:46:01.326:ERROR [launcher]: Cannot start Chrome
        nvm is not compatible with the "npm_config_prefix" environment variable: currently set to "/build/versions/node/v10.14.1"
Run `unset npm_config_prefix` to unset it.

27 05 2019 14:46:01.327:ERROR [launcher]: Chrome stdout:
27 05 2019 14:46:01.327:ERROR [launcher]: Chrome stderr: nvm is not compatible with the "npm_config_prefix" environment variable: currently set to "/build/versions/node/v10.14.1"
Run `unset npm_config_prefix` to unset it.
</code>```

I can share more configuration, but the same code built fine in CircleCI and now is failing in Shippable.
I can reproduce locally (on my local Docker) using the drydock/u16nodall image.

We are setting the following env vars prior to running npm:

```<code>export PATH="./node_modules/.bin:$PATH";
export CHROME_BIN=chromium-browser;
export DISPLAY=:99.0;
</code>```

Different NPM or Node versions don't seem to make a difference.

karma.conf.js has this:

```<code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  var isWatch = config.buildWebpack.options.watch;
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-spec-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../shippable/codecoverage'),
      reports: ['cobertura', 'html', 'lcovonly', 'json'],
      fixWebpackSourcePaths: true,
      thresholds: {
        statements: 80,
        lines: 80,
        branches: 72,
        functions: 80
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    customLaunchers: {
      ChromeShippable: {
        base: 'Chrome',
        flags: ['--no-sandbox','--disable-setuid-sandbox']
      }
    },
    browserNoActivityTimeout: 50000,
    singleRun: !isWatch
  });
};
</code>```

All I've been able to find around the _not compatible npm_config_prefix_ error seems to be related to a corrupted node installation. But installing a fresh version with NVM also shows this error.

Any ideas how to get this working?

答:
I finally was able to overcome this issue by updating the customLauchers configuration to base off of ChromeHeadless instead of Chrome.

```<code>customLaunchers: {
  ChromeShippable: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox','--disable-setuid-sandbox']
  }
},
</code>```

I'm not done chasing errors around the shippable migration, but at least this clears the error I was specifically asking about. I have already confirmed this ran fine (didn't crash when firing up Chrome) on the Shippable build boxes too.

EDIT: Most of all the subsequent errors were also related to Chrome needing to be explicitly run as headless.

Added to .pa11yci's defaults:

```<code>"chromeLaunchConfig": {
  "args": ["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"]
}
</code>```

Added to e2e/protractor.conf.js's exported capabilities:

```<code>'chromeOptions': {
  args: [ '--headless', '--disable-gpu', '--no-sandbox','--disable-setuid-sandbox','--disable-dev-shm-usage']
}
</code>```

There were plenty other changes outside the scope of this question.

Body:
We are moving an Angular (Angular, NgRx and Angular Material Starter) based website from CircleCI to Shippable, and I'm now getting these failures:

27 05 2019 14:46:00.036:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
27 05 2019 14:46:00.040:INFO [launcher]: Launching browsers ChromeShippable with concurrency unlimited
27 05 2019 14:46:00.071:INFO [launcher]: Starting browser Chrome
27 05 2019 14:46:01.326:ERROR [launcher]: Cannot start Chrome
        nvm is not compatible with the "npm_config_prefix" environment variable: currently set to "/build/versions/node/v10.14.1"
Run `unset npm_config_prefix` to unset it.

27 05 2019 14:46:01.327:ERROR [launcher]: Chrome stdout:
27 05 2019 14:46:01.327:ERROR [launcher]: Chrome stderr: nvm is not compatible with the "npm_config_prefix" environment variable: currently set to "/build/versions/node/v10.14.1"
Run `unset npm_config_prefix` to unset it.

I can share more configuration, but the same code built fine in CircleCI and now is failing in Shippable.
I can reproduce locally (on my local Docker) using the drydock/u16nodall image.

We are setting the following env vars prior to running npm:

export PATH="./node_modules/.bin:$PATH";
export CHROME_BIN=chromium-browser;
export DISPLAY=:99.0;

Different NPM or Node versions don't seem to make a difference.

karma.conf.js has this:

// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  var isWatch = config.buildWebpack.options.watch;
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-spec-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../shippable/codecoverage'),
      reports: ['cobertura', 'html', 'lcovonly', 'json'],
      fixWebpackSourcePaths: true,
      thresholds: {
        statements: 80,
        lines: 80,
        branches: 72,
        functions: 80
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    customLaunchers: {
      ChromeShippable: {
        base: 'Chrome',
        flags: ['--no-sandbox','--disable-setuid-sandbox']
      }
    },
    browserNoActivityTimeout: 50000,
    singleRun: !isWatch
  });
};

All I've been able to find around the _not compatible npm_config_prefix_ error seems to be related to a corrupted node installation. But installing a fresh version with NVM also shows this error.

Any ideas how to get this working?

Body:
I finally was able to overcome this issue by updating the customLauchers configuration to base off of ChromeHeadless instead of Chrome.

customLaunchers: {
  ChromeShippable: {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox','--disable-setuid-sandbox']
  }
},

I'm not done chasing errors around the shippable migration, but at least this clears the error I was specifically asking about. I have already confirmed this ran fine (didn't crash when firing up Chrome) on the Shippable build boxes too.

EDIT: Most of all the subsequent errors were also related to Chrome needing to be explicitly run as headless.

Added to .pa11yci's defaults:

"chromeLaunchConfig": {
  "args": ["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"]
}

Added to e2e/protractor.conf.js's exported capabilities:

'chromeOptions': {
  args: [ '--headless', '--disable-gpu', '--no-sandbox','--disable-setuid-sandbox','--disable-dev-shm-usage']
}

There were plenty other changes outside the scope of this question.


问:
How can I fill the 2d array in clojure with loop like matrix that we do in JAVA if I have a list of the characters
I want to fill 2d array in clojure like we do in java

I have provided the example of java. I want to do like this in Clojure

Scanner sc=new Scanner(System.in);
Scanner sc1=new Scanner(System.in);
int row=sc.nextInt();
int col=sc.nextInt();
realMatrix=new String[row][col];
String[] in=new String[row];
for(int k=0;k<row;k++) {
    in[k]=sc1.nextLine();
}
for(int i=0;i<row;i++) {
    char[] charArry=in[i].toCharArray();
    for(int j=0;j<col;j++) {
        realMatrix[i][j]=Character.toString(charArry[j]);
    }
}
```

答:
If your input (lines) is valid (it contains the correct number of rows and each row contains the correct number of characters), it can be parsed with

(vec (map #(clojure.string/split % #"") (drop 2 lines)))
```

<p>If your input looks like <code>lines</code> below, you'll want to filter out the <code>!</code>s:</p>

<pre class="lang-clj prettyprint-override"><code>(def lines
  ["3"
   "5"
   "abcde!!!"
   "FGHIJ!!!"
   "klmno!!!"
   "!!!!!!!!"
   "!!!!!!!!"])

(defn split-row [row n-cols]
  (vec (take n-cols (clojure.string/split row #""))))

(defn parse-matrix [lines]
  (let [n-rows (Integer. (first lines))
        n-cols (Integer. (second lines))
        matrix-lines (take n-rows (drop 2 lines))]
    (vec (map #(split-row % n-cols) matrix-lines))))
</code>```

If you really want to parse it as it is read from standard input:

(defn parse-matrix-stdin []
  (let [n-rows (Integer. (read-line))
        n-cols (Integer. (read-line))
        matrix-lines (take n-rows (repeatedly read-line))]
    (vec (map #(split-row % n-cols) matrix-lines))))
```

Body:
If your input (lines) is valid (it contains the correct number of rows and each row contains the correct number of characters), it can be parsed with

(vec (map #(clojure.string/split % #"") (drop 2 lines)))

If your input looks like lines below, you'll want to filter out the !s:

(def lines
  ["3"
   "5"
   "abcde!!!"
   "FGHIJ!!!"
   "klmno!!!"
   "!!!!!!!!"
   "!!!!!!!!"])

(defn split-row [row n-cols]
  (vec (take n-cols (clojure.string/split row #""))))

(defn parse-matrix [lines]
  (let [n-rows (Integer. (first lines))
        n-cols (Integer. (second lines))
        matrix-lines (take n-rows (drop 2 lines))]
    (vec (map #(split-row % n-cols) matrix-lines))))

If you really want to parse it as it is read from standard input:

(defn parse-matrix-stdin []
  (let [n-rows (Integer. (read-line))
        n-cols (Integer. (read-line))
        matrix-lines (take n-rows (repeatedly read-line))]
    (vec (map #(split-row % n-cols) matrix-lines))))


问:
iPhone login screen problem
I have a large application. It has a lot of tables and navigation between them. I started a project as a 'NavigationBasedProject' (xcode template). But now I need to add login at the start of the application. So here what I did so far:
In 'didFinishLaunchingWithOptions' I added:

```<code>loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
</code>```

When user data are valid I dismiss login screen like this:

```<code>[self.loginViewController dismissModalViewControllerAnimated:YES];
</code>```

User can also logout from application. And then I present login screen again like this:

```<code>[self.window.rootViewController presentModalViewController:loginViewController animated:NO];
</code>```

And this works. But text fields on login screen are still filled with data that user enter to login. And I am afraid that I have some memory issue here. How to remove login screen completely from memory when user logs in. I don't use GUI designer I connect everything from code.
Also I wonder is it good idea to make login screen and modal view?

答:
you should use....  (I don't know why you are declaring it loginViewController at class level)

```<code>LoginViewController *loginViewController = [[LoginViewController alloc]init];
            [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
            [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
    [loginViewController release];
</code>```

and for dismissal .....

```<code>[self.window.rootViewController dismissModalViewControllerAnimated:YES];
</code>```

Thanks,

Title: iPhone login screen problem

Body:
I have a large application. It has a lot of tables and navigation between them. I started a project as a 'NavigationBasedProject' (xcode template). But now I need to add login at the start of the application. So here what I did so far:
In 'didFinishLaunchingWithOptions' I added:

loginViewController = [[LoginViewController alloc]init];
        [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
        [self.window.rootViewController presentModalViewController:loginViewController animated:NO];

When user data are valid I dismiss login screen like this:

[self.loginViewController dismissModalViewControllerAnimated:YES];

User can also logout from application. And then I present login screen again like this:

[self.window.rootViewController presentModalViewController:loginViewController animated:NO];

And this works. But text fields on login screen are still filled with data that user enter to login. And I am afraid that I have some memory issue here. How to remove login screen completely from memory when user logs in. I don't use GUI designer I connect everything from code.
Also I wonder is it good idea to make login screen and modal view?

Body:
you should use....  (I don't know why you are declaring it loginViewController at class level)

LoginViewController *loginViewController = [[LoginViewController alloc]init];
            [loginViewController.view setFrame:CGRectMake(0, 0, 320, 480)];
            [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
    [loginViewController release];

and for dismissal .....

[self.window.rootViewController dismissModalViewControllerAnimated:YES];

Thanks,


问:
How to preg_match a PCRE expression?
```<code>$key="`client` asc";
preg_match('
                ~(?J)
                    \s*
                    (?:`(?P<col>(?:[^`\\\\]|\\\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z~Axi', $key, $m);
print_r($m);
</code>```

This regular expression fills the col key when tested here

https://regex101.com/r/i00sEn/1

It does not work correctly on my local PHP 5.6 machine, or this 7.3 interpreter.

http://sandbox.onlinephpfunctions.com/code/915a26b741c6d086f21129f60af2420c74cf9f89

It works everywhere if I remove the backticks, but as the purpose of this code is to parse SQL ORDER BY clauses, I need the backticks.

Why does this work?  How can I get it to match backticks correctly?

答:
The alternative to branch reset is to use a conditional  </p>

```<code> # http://sandbox.onlinephpfunctions.com/code/551b5ecba6d554cdeff616f193fca003cd777014

 (?xis-)
 \A                                    # BOS
 \s*
 (?:
      ( `? )                                # (1), Optional backtick
      (?<col>                               # (2 start), Col body
           (?(?<= ` )                            # Conditional, is backtick behind ?
                (?: [^`\\] | \\ . | `` )*             # yes, match backtick body
             |  \S+                                   # no, match consecutive non-whitespaces
           )
      )                                     # (2 end)
      \1                                    # Backref to optional backtick
 )
 (?:                                   # Optional column direction
      \s+
      (?<dir> asc | desc )                  # (3), ascending or descending
 )?
 \s*
 \z                                    # EOS
</code>```

Title: How to preg_match a PCRE expression?

Body:
$key="`client` asc";
preg_match('
                ~(?J)
                    \s*
                    (?:`(?P<col>(?:[^`\\\\]|\\\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z~Axi', $key, $m);
print_r($m);

This regular expression fills the col key when tested here

https://regex101.com/r/i00sEn/1

It does not work correctly on my local PHP 5.6 machine, or this 7.3 interpreter.

http://sandbox.onlinephpfunctions.com/code/915a26b741c6d086f21129f60af2420c74cf9f89

It works everywhere if I remove the backticks, but as the purpose of this code is to parse SQL ORDER BY clauses, I need the backticks.

Why does this work?  How can I get it to match backticks correctly?

Body:
The alternative to branch reset is to use a conditional

 # http://sandbox.onlinephpfunctions.com/code/551b5ecba6d554cdeff616f193fca003cd777014

 (?xis-)
 \A                                    # BOS
 \s*
 (?:
      ( `? )                                # (1), Optional backtick
      (?<col>                               # (2 start), Col body
           (?(?<= ` )                            # Conditional, is backtick behind ?
                (?: [^`\\] | \\ . | `` )*             # yes, match backtick body
             |  \S+                                   # no, match consecutive non-whitespaces
           )
      )                                     # (2 end)
      \1                                    # Backref to optional backtick
 )
 (?:                                   # Optional column direction
      \s+
      (?<dir> asc | desc )                  # (3), ascending or descending
 )?
 \s*
 \z                                    # EOS


问:
Kubernetes Private Docker Registry not working - Command-Line Alternative working, but k8s unable to pull image
I have following docker-compose.yaml for a private docker registry to be run on minikube:

```<code>version: '3'
services:
  registry:
    restart: always
    image: registry:2
    command: ["/bin/sh", "-ec","sleep 1000"]
    ports:
      - 443:443
    environment:
      REGISTRY_HTTP_TLS_CERTIFICATE: /certs/domain.crt
      REGISTRY_HTTP_TLS_KEY: /certs/domain.key
      REGISTRY_AUTH: htpasswd
      REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
      REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
    volumes:
      - /home/usr/registry/data:/var/lib/registry
      - /home/usr/registry/certs:/certs
      - /home/usr/registry/auth:/auth
</code>```

When I do kompose up, the registry should be up and running. But doing docker login localhost:443 only gives me a connection refused error. If I run

```<code>docker run -d   --restart=always   --name registry   -v `pwd`/auth:/auth   -v `pwd`/certs:/certs   -v `pwd`/certs:/certs   -e REGISTRY_AUTH=htpasswd   -e REGISTRY_AUTH_HTPASSWD_REALM="Registry Realm"   -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd   -e REGISTRY_HTTP_ADDR=0.0.0.0:443   -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt   -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key   -p 443:443   registry:2
</code>```

everything works fine and I can log into my private registry.
The reason this is important is that I have a webapp-image that is in the private registry and should be pulled by kubernetes (minikube) from it. However, I always get a CrashLoopBackoff error which I deem due to the fact that the registry cannot be run from kubernetes and incidentally not be accessed by it. What am I getting wrong?

答: The solution is to set up a registry in minikube and port-forward to from localhost so the image gets pushed onto the minikube regsitry. </p>

Body:
I have following docker-compose.yaml for a private docker registry to be run on minikube:

version: '3'
services:
  registry:
    restart: always
    image: registry:2
    command: ["/bin/sh", "-ec","sleep 1000"]
    ports:
      - 443:443
    environment:
      REGISTRY_HTTP_TLS_CERTIFICATE: /certs/domain.crt
      REGISTRY_HTTP_TLS_KEY: /certs/domain.key
      REGISTRY_AUTH: htpasswd
      REGISTRY_AUTH_HTPASSWD_PATH: /auth/htpasswd
      REGISTRY_AUTH_HTPASSWD_REALM: Registry Realm
    volumes:
      - /home/usr/registry/data:/var/lib/registry
      - /home/usr/registry/certs:/certs
      - /home/usr/registry/auth:/auth

When I do kompose up, the registry should be up and running. But doing docker login localhost:443 only gives me a connection refused error. If I run

docker run -d   --restart=always   --name registry   -v `pwd`/auth:/auth   -v `pwd`/certs:/certs   -v `pwd`/certs:/certs   -e REGISTRY_AUTH=htpasswd   -e REGISTRY_AUTH_HTPASSWD_REALM="Registry Realm"   -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd   -e REGISTRY_HTTP_ADDR=0.0.0.0:443   -e REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt   -e REGISTRY_HTTP_TLS_KEY=/certs/domain.key   -p 443:443   registry:2

everything works fine and I can log into my private registry.
The reason this is important is that I have a webapp-image that is in the private registry and should be pulled by kubernetes (minikube) from it. However, I always get a CrashLoopBackoff error which I deem due to the fact that the registry cannot be run from kubernetes and incidentally not be accessed by it. What am I getting wrong?


问:
How to test for a passed function?
doc is an instance of pdfkit document...

```<code>import PDFDocument from 'pdfkit'
const doc = new PDFDocument()
</code>```

...which gets passed to my function:

```<code>export const outputTitle = (doc, title) => {
  if (!title) return null

  doc
    .fontSize(15)
    .font('Helvetica-Bold')
    .text(title, 380, 160)
}
</code>```

Now I need to write unit tests for this functions using jest.

```<code>describe('outputTitle()', () => {
  const doc = jest.fn()

  test('should return null if parameter title is missing', () => {
    // SETUP
    const title = undefined
    // EXECUTE
    const result = outputTitle(doc, title)
    // VERIFY
    expect(result).toBeNull()
  })

  test('should call doc()', () => {
    // ???
  })
})
</code>```

But how do I test the second part, which is the case of passing a title value?
I think my mock of doc is wrong.

答:
```<code>describe('outputTitle()', () => {
  const textSpy = jest.spyOn(doc, 'text');

  test('should call doc with title', () => {
      outputTitle(doc, 'some title');

      expect(textSpy).toBeCalledWith('some title');
    });
})
</code>```

Reference

Title: How to test for a passed function?

Body:
doc is an instance of pdfkit document...

import PDFDocument from 'pdfkit'
const doc = new PDFDocument()

...which gets passed to my function:

export const outputTitle = (doc, title) => {
  if (!title) return null

  doc
    .fontSize(15)
    .font('Helvetica-Bold')
    .text(title, 380, 160)
}

Now I need to write unit tests for this functions using jest.

describe('outputTitle()', () => {
  const doc = jest.fn()

  test('should return null if parameter title is missing', () => {
    // SETUP
    const title = undefined
    // EXECUTE
    const result = outputTitle(doc, title)
    // VERIFY
    expect(result).toBeNull()
  })

  test('should call doc()', () => {
    // ???
  })
})

But how do I test the second part, which is the case of passing a title value?
I think my mock of doc is wrong.

Body:
describe('outputTitle()', () => {
  const textSpy = jest.spyOn(doc, 'text');

  test('should call doc with title', () => {
      outputTitle(doc, 'some title');

      expect(textSpy).toBeCalledWith('some title');
    });
})

Reference


问:
ReactJS - how change html markup dynamically?
I need a reusable component with any markup type decided inside at the coding time, so hardcoding different component would be a very complicating solution, so handling the markup using a function's style would be just awesome.

Here my sandbox:https://codesandbox.io/s/determined-clarke-gvrzv?fontsize=14

I would modify my html markup dynamically depending on a javascript variable, as following:

```<code>let markup= "li"
function App() {
 return (
    <div className="App">
      <[markup]>Hello World</[markup]>
    </div>
 );
}
</code>```

the console returns me:

```<code>Unexpected token
</code>```

How handle this problem?

Thanks for any hint!

答:
You can do:

```<code>const Markup = "li";

return (
  <div className="app">
    <Markup>Hello World</Markup>
  </div>
)
</code>```

I don't know exactly what you're trying to do, but you might also consider conditionally rendering a different component:

```<code>const temperature = -20;

return (
  temperature < 30 ? <Cold /> : <Warm />
);
</code>```

or conditionally swapping the markup inline:

```<code>const isCold = temp => temp < 30;

const temperature = -12;

return (
  isCold(temperature) ? <div>Brrr!</div> : <span>Sunshine!</span>
);
</code>```

And finally, if you have many possible variants, you can establish a getComponent function to figure out what to render:

```<code>const SeasonalComponents = [
  {
    handles: temp => temp < 0,
    component: () => <div>Brrr!</div>
  },
  {
    handles: temp => temp < 30,
    component: () => <div>Get your coat!</div>
  },
  {
    handles: temp => temp < 50,
    component: () => <div>Just a jacket</div>
  },
  {
    handles: temp => temp < 100,
    component: () => <ImportedSummerComponent />
  }
];

function getComponent (temperature) {
  const seasonal = SeasonalComponents.find(x => x.handles(temperature);
  return seasonal ? seasonal.component : <span>Unseasonable weather!</span>;
}
</code>```

which allows your render method to do a lookup:

```<code>const Component = getComponent(this.props.temp);

return (
  <Component />
);
</code>```

Body:
I need a reusable component with any markup type decided inside at the coding time, so hardcoding different component would be a very complicating solution, so handling the markup using a function's style would be just awesome.

Here my sandbox:https://codesandbox.io/s/determined-clarke-gvrzv?fontsize=14

I would modify my html markup dynamically depending on a javascript variable, as following:

let markup= "li"
function App() {
 return (

      <[markup]>Hello World</[markup]>

 );
}

the console returns me:

Unexpected token

How handle this problem?

Thanks for any hint!

Body:
You can do:

const Markup = "li";

return (
  <div className="app">
    <Markup>Hello World</Markup>
  </div>
)

I don't know exactly what you're trying to do, but you might also consider conditionally rendering a different component:

const temperature = -20;

return (
  temperature < 30 ? <Cold /> : <Warm />
);

or conditionally swapping the markup inline:

const isCold = temp => temp < 30;

const temperature = -12;

return (
  isCold(temperature) ? <div>Brrr!</div> : <span>Sunshine!</span>
);

And finally, if you have many possible variants, you can establish a getComponent function to figure out what to render:

const SeasonalComponents = [
  {
    handles: temp => temp < 0,
    component: () => <div>Brrr!</div>
  },
  {
    handles: temp => temp < 30,
    component: () => <div>Get your coat!</div>
  },
  {
    handles: temp => temp < 50,
    component: () => <div>Just a jacket</div>
  },
  {
    handles: temp => temp < 100,
    component: () => <ImportedSummerComponent />
  }
];

function getComponent (temperature) {
  const seasonal = SeasonalComponents.find(x => x.handles(temperature);
  return seasonal ? seasonal.component : <span>Unseasonable weather!</span>;
}

which allows your render method to do a lookup:

const Component = getComponent(this.props.temp);

return (
  <Component />
);


问:
Follow cloaked link with with chain of numbers to front
I'm building a small cloaking link script but I need to find each one with a different string number eg( 'mylinkname1'-1597). By the way: the number is always integer.

The problem is that I never know the string number so I was thinking to use regex but something is failing.

Here's what I got now:

```<code>$pattern = '/-([0-9]+)/';

$v = $_GET['v']

if ($v == 'mylinkname1'.'-'.$pattern) {$link = 'http://example1.com/';}
if ($v == 'mylinkname2'.'-'.$pattern) {$link = 'http://example2.com/';}
if ($v == 'mylinkname3'.'-'.$pattern) {$link = 'http://example3.com/';}

header("Location: $link") ;
exit();
</code>```

答:
no need for regular expressions here at all just split the string on the hyphen and only match that, also I recommend a case\switch when you 3 or if\eleses:</p>

```<code>$v=explode('-',$_GET['v']);

switch ($v[0]) {
    case "mylinkname1":
        $link = 'http://example1.com/';
        break;
    case "mylinkname2":
        $link = 'http://example2.com/';
        break;
    case "mylinkname3":
        $link = 'http://example3.com/';
        break;
    default:
        echo "something not right";
}

header("Location: $link") ;
exit();
</code>```

Body:
I'm building a small cloaking link script but I need to find each one with a different string number eg( 'mylinkname1'-1597). By the way: the number is always integer.

The problem is that I never know the string number so I was thinking to use regex but something is failing.

Here's what I got now:

$pattern = '/-([0-9]+)/';

$v = $_GET['v']

if ($v == 'mylinkname1'.'-'.$pattern) {$link = 'http://example1.com/';}
if ($v == 'mylinkname2'.'-'.$pattern) {$link = 'http://example2.com/';}
if ($v == 'mylinkname3'.'-'.$pattern) {$link = 'http://example3.com/';}

header("Location: $link") ;
exit();

Body:
no need for regular expressions here at all just split the string on the hyphen and only match that, also I recommend a case\switch when you 3 or if\eleses:

$v=explode('-',$_GET['v']);

switch ($v[0]) {
    case "mylinkname1":
        $link = 'http://example1.com/';
        break;
    case "mylinkname2":
        $link = 'http://example2.com/';
        break;
    case "mylinkname3":
        $link = 'http://example3.com/';
        break;
    default:
        echo "something not right";
}

header("Location: $link") ;
exit();


答:
The dash is already in the pattern so you don't have to add it in the if clause.

You can omit the capturing group around the digits -[0-9]+, and you have to use the pattern with preg_match.

You might update the format of the if statements to:

```<code>$pattern = '-[0-9]+';

if (preg_match("/mylinkname1$pattern/", $v)) {$link = 'http://example1.com/';}
</code>```

To prevent mylinkname1-1597 being part of a larger word, you might surround the pattern with anchors ^ and $ to assert the start and end of the string or word boundaries \b

Title: Follow cloaked link with with chain of numbers to front

Body:
The dash is already in the pattern so you don't have to add it in the if clause.

You can omit the capturing group around the digits -[0-9]+, and you have to use the pattern with preg_match.

You might update the format of the if statements to:

$pattern = '-[0-9]+';

if (preg_match("/mylinkname1$pattern/", $v)) {$link = 'http://example1.com/';}

To prevent mylinkname1-1597 being part of a larger word, you might surround the pattern with anchors ^ and $ to assert the start and end of the string or word boundaries \b


问:
One large Elasticsearch lookup index, or several smaller ones?
I'm creating a lookup index that I'll use solely as a terms filter. So no searching/aggregating, only filtering and GETs.

I'm debating the structure of this lookup index, whether each document should contain all of the fields I want to filter for, or whether I should create an index per field.

For example, let's say each document pertains to a user. Each user has a list of games they've played, books they've read, and movies they've watched. When searching for game/book/movie recommendations, I'll use the term filter to filter out those items they've already interacted with.

I'm wondering if I should have a single lookup index with a document mapping like:
users_index

```<code>{
  'game_ids': [],
  'movie_ids' : [],
  'book_ids': []
}
</code>```

or one index per lookup value, like:
user_games_index

```<code>{
  'game_ids': []
}
</code>```

user_movies_index

```<code>{
  'movie_ids': []
}
</code>```

user_books_index

```<code>{
  'book_ids': []
}
</code>```

Pros for one index:

Each index comes with overhead, so the fewer the better

If I ever want to retrieve all of a user's info, it's all in one index

Pros for multiple indices:

According to the update api docs, updating a document means retrieving the whole thing first. I will be updating each document a lot, and those arrays can become rather large (think thousands of ids). Updating a book id will then retrieve all of the game ids, which takes up memory. If they were in separate indices, I could avoid that.

Just easier to maintain on my end of things

I should note that if I use multiple indices, it'll only be 4 or 5, with about 500k documents per index. Also, only 1 primary shard per index, no replicas, and I'm on a single m5.2xlarge EC2 instance (8 cores, 32G ram).

Are these stats so small that it won't really matter at this point, or should I favor one index or many?

答:
How about a third option?

You have one index and each of your document in the index looks something like this:

```<code>{
    "user_id" : "some_user",
    "document_type" : "movie" or "game" or "book"
    "document_id" : "id of movie, game or book"
}
</code>```

Why? Since you say a user's games, movies or books will be updated often, this approach lets you easily add / delete individual movies, games or books for users.

You also can easily filter the books/movies/games for specific users.

All values are of type "keyword" and filtering should be fast.

PS: A "good" mapping for an ES index will try to minimize the numbers of updates on individual documents and rather work at the level of inserting / deleting documents as ES does this task very well compared to finding & updating documents.

Edit: I have added query examples to illustrate how you can filter out results with bool query.

Example:

I want all movies / games / books a user X has NOT interacted with.

GET _search

```<code>{
  "query": {
    "bool": {
      "must_not":{
        "term" : {
            "user_id" : "user X"
        }
      }
    }
  }
}
</code>```

I want only movies a user X has NOT interacted with.

GET _search

```<code>{
  "query": {
    "bool": {
      "must_not":{
        "term" : {
            "user_id" : "user X"
        }
      },
      "filter":{
        "term" : {
            "document_type" : "movie"
        }
      }
    }
  }
}
</code>```

Body:
I'm creating a lookup index that I'll use solely as a terms filter. So no searching/aggregating, only filtering and GETs.

I'm debating the structure of this lookup index, whether each document should contain all of the fields I want to filter for, or whether I should create an index per field.

For example, let's say each document pertains to a user. Each user has a list of games they've played, books they've read, and movies they've watched. When searching for game/book/movie recommendations, I'll use the term filter to filter out those items they've already interacted with.

I'm wondering if I should have a single lookup index with a document mapping like:
users_index

{
  'game_ids': [],
  'movie_ids' : [],
  'book_ids': []
}

or one index per lookup value, like:
user_games_index

{
  'game_ids': []
}

user_movies_index

{
  'movie_ids': []
}

user_books_index

{
  'book_ids': []
}

Pros for one index:

Each index comes with overhead, so the fewer the better

If I ever want to retrieve all of a user's info, it's all in one index

Pros for multiple indices:

According to the update api docs, updating a document means retrieving the whole thing first. I will be updating each document a lot, and those arrays can become rather large (think thousands of ids). Updating a book id will then retrieve all of the game ids, which takes up memory. If they were in separate indices, I could avoid that.

Just easier to maintain on my end of things

I should note that if I use multiple indices, it'll only be 4 or 5, with about 500k documents per index. Also, only 1 primary shard per index, no replicas, and I'm on a single m5.2xlarge EC2 instance (8 cores, 32G ram).

Are these stats so small that it won't really matter at this point, or should I favor one index or many?

Body:
How about a third option?

You have one index and each of your document in the index looks something like this:

{
    "user_id" : "some_user",
    "document_type" : "movie" or "game" or "book"
    "document_id" : "id of movie, game or book"
}

Why? Since you say a user's games, movies or books will be updated often, this approach lets you easily add / delete individual movies, games or books for users.

You also can easily filter the books/movies/games for specific users.

All values are of type "keyword" and filtering should be fast.

PS: A "good" mapping for an ES index will try to minimize the numbers of updates on individual documents and rather work at the level of inserting / deleting documents as ES does this task very well compared to finding & updating documents.

Edit: I have added query examples to illustrate how you can filter out results with bool query.

Example:

I want all movies / games / books a user X has NOT interacted with.

GET _search

{
  "query": {
    "bool": {
      "must_not":{
        "term" : {
            "user_id" : "user X"
        }
      }
    }
  }
}

I want only movies a user X has NOT interacted with.

GET _search

{
  "query": {
    "bool": {
      "must_not":{
        "term" : {
            "user_id" : "user X"
        }
      },
      "filter":{
        "term" : {
            "document_type" : "movie"
        }
      }
    }
  }
}


问:
Issue sending/Receiving vector of double over TCP socket (missing data)
I am trying to send data from a vector over a TCP socket.
I'm working with a vector that I fill with values from 0 to 4999, and then send it to the socket.

Client side, I'm receiving the data into a vector, then I copy its data to another vector until I received all the data from the server.

The issue I'm facing is that when I receive my data, sometimes I will get all of it, and sometimes I will only receive the correct data from 0 to 1625 and then I get trash data until the end (please see the image below). I even received for example from 0 to 2600 correct data, then from 2601 to 3500 it's trash and finally from 3501 to 4999 it's correct again.

 (left column is line number and right column is the data).

This is the server side :

vector<double> values2;
for(int i=0; i<5000; i++)
    values2.push_back(i);
skt.sendmsg(&values2[0], values2.size()*sizeof(double));
```

<p>The function sendmsg :</p>

<pre class="lang-cpp prettyprint-override"><code>void Socket::sendmsg(const void *buf, size_t len){

    int bytes=-1;

    bytes = send(m_csock, buf, len, MSG_CONFIRM);

    cout << "Bytes sent: " << bytes << endl;

}
</code>```

Client side :

vector<double> final;
vector<double> msgrcvd(4096);

do{

    bytes += recv(sock, &msgrcvd[0], msgrcvd.size()*sizeof(double), 0);
    cout << "Bytes received: " << bytes << endl;

    //Get rid of the trailing zeros
    while(!msgrcvd.empty() && msgrcvd[msgrcvd.size() - 1] == 0){
        msgrcvd.pop_back();

    }

    //Insert buffer content into final vector
    final.insert(final.end(), msgrcvd.begin(), msgrcvd.end());

}while(bytes < sizeof(double)*5000);

//Write the received data in a txt file

for(int i=0; i<final.size(); i++)
    myfile << final[i] << endl;

myfile.close();

```

The outputs of the bytes are correct, the server outputs 40 000 when sending the data and the client also outputs 40 000 when receiving the data.

Removing the trailing zeros and then inserting the content of the buffer into a new vector is not very efficient, but I don't think it's the issue. If you have any clues on how to make it more efficient, it would be great!

I don't really know if the issue is when I send the data or when I receive it, and also I don't really get why sometimes (rarely), I get all the data.

答:
recv receives bytes, and doesn't necessarily wait for all the data that was sent.  So you can be receiving part of a double.

Your code works if you receive complete double values, but will fail when you receive part of a value.  You should receive your data in a char buffer, then unpack it into doubles.  (Possibly converting endianness if the server and client are different.)

```<code>#include <cstring>    // For memcpy

std::array<char, 1024> msgbuf;
double d;
char data[sizeof(double)];
int carryover = 0;

do {
    int b = recv(sock, &msgbuf[carryover], msgbuf.size() * sizeof(msgbuf[0]) - carryover, 0);
    bytes += b;
    b += carryover;
    const char *mp = &msgbuf[0];
    while (b >= sizeof(double)) {
        char *bp = data;
        for (int i = 0; i < sizeof(double); ++i) {
            *bp++ = *mp++;
        }
        std::memcpy(&d, data, sizeof(double));
        final.push_back(d);
        b -= sizeof(double);
    }
    carryover = b % sizeof(double);
    // Take care of the extra bytes.  Copy them down to the start of the buffer
    for (int j = 0; j < carryover; ++j) {
        msgbuf[j] = *mp++;
    }
} while (bytes < sizeof(double) * 5000);
</code>```

This uses type punning from What's a proper way of type-punning a float to an int and vice-versa? to convert the received binary data to a double, and assumes the endianness of the client and server are the same.

Incidentally, how does the receiver know how many values it is receiving?  You have a mix of hard coded values (5000) and dynamic values (.size()) in your server code.

Note: code not compiled or tested

Body:
I am trying to send data from a vector over a TCP socket.
I'm working with a vector that I fill with values from 0 to 4999, and then send it to the socket.

Client side, I'm receiving the data into a vector, then I copy its data to another vector until I received all the data from the server.

The issue I'm facing is that when I receive my data, sometimes I will get all of it, and sometimes I will only receive the correct data from 0 to 1625 and then I get trash data until the end (please see the image below). I even received for example from 0 to 2600 correct data, then from 2601 to 3500 it's trash and finally from 3501 to 4999 it's correct again.

 (left column is line number and right column is the data).

This is the server side :

vector<double> values2;
for(int i=0; i<5000; i++)
    values2.push_back(i);
skt.sendmsg(&values2[0], values2.size()*sizeof(double));

The function sendmsg :

void Socket::sendmsg(const void *buf, size_t len){

    int bytes=-1;

    bytes = send(m_csock, buf, len, MSG_CONFIRM);

    cout << "Bytes sent: " << bytes << endl;

}

Client side :

vector<double> final;
vector<double> msgrcvd(4096);

do{

    bytes += recv(sock, &msgrcvd[0], msgrcvd.size()*sizeof(double), 0);
    cout << "Bytes received: " << bytes << endl;

    //Get rid of the trailing zeros
    while(!msgrcvd.empty() && msgrcvd[msgrcvd.size() - 1] == 0){
        msgrcvd.pop_back();

    }

    //Insert buffer content into final vector
    final.insert(final.end(), msgrcvd.begin(), msgrcvd.end());

}while(bytes < sizeof(double)*5000);

//Write the received data in a txt file

for(int i=0; i<final.size(); i++)
    myfile << final[i] << endl;

myfile.close();

The outputs of the bytes are correct, the server outputs 40 000 when sending the data and the client also outputs 40 000 when receiving the data.

Removing the trailing zeros and then inserting the content of the buffer into a new vector is not very efficient, but I don't think it's the issue. If you have any clues on how to make it more efficient, it would be great!

I don't really know if the issue is when I send the data or when I receive it, and also I don't really get why sometimes (rarely), I get all the data.

Body:
recv receives bytes, and doesn't necessarily wait for all the data that was sent.  So you can be receiving part of a double.

Your code works if you receive complete double values, but will fail when you receive part of a value.  You should receive your data in a char buffer, then unpack it into doubles.  (Possibly converting endianness if the server and client are different.)

#include <cstring>    // For memcpy

std::array<char, 1024> msgbuf;
double d;
char data[sizeof(double)];
int carryover = 0;

do {
    int b = recv(sock, &msgbuf[carryover], msgbuf.size() * sizeof(msgbuf[0]) - carryover, 0);
    bytes += b;
    b += carryover;
    const char *mp = &msgbuf[0];
    while (b >= sizeof(double)) {
        char *bp = data;
        for (int i = 0; i < sizeof(double); ++i) {
            *bp++ = *mp++;
        }
        std::memcpy(&d, data, sizeof(double));
        final.push_back(d);
        b -= sizeof(double);
    }
    carryover = b % sizeof(double);
    // Take care of the extra bytes.  Copy them down to the start of the buffer
    for (int j = 0; j < carryover; ++j) {
        msgbuf[j] = *mp++;
    }
} while (bytes < sizeof(double) * 5000);

This uses type punning from What's a proper way of type-punning a float to an int and vice-versa? to convert the received binary data to a double, and assumes the endianness of the client and server are the same.

Incidentally, how does the receiver know how many values it is receiving?  You have a mix of hard coded values (5000) and dynamic values (.size()) in your server code.

Note: code not compiled or tested


问:
npm install ->Failed at the node-sass@4.5.0 postinstall script
I'm trying to do npm install and an error appears :

```<code>Failed at the node-sass@4.5.0 postinstall script.
</code>```

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0

答: I had the same issue with a new install with Keystone.js. I was able to get pass this issue by removing Node Sass from package.json and running npm install again. Being that the package wasn't listed under node modules. And it worked fine after that. </p>

Body:
I'm trying to do npm install and an error appears :

Failed at the node-sass@4.5.0 postinstall script.

I tried to delete node_modules and then reinstall it, same error appears.
what will be the solution?

node v8.9.3

npm v5.4.2

ionic 3.19.0


问:
zoom into html canvas
I would like show a cutting of a canvas element in another canvas element. For explanation i have the following structure:

Canvas Element which gets filled it's background by an image. On top of this image i draw a arrow and a possible path. The background-image is really big, which means that i can not get that much Information from this big image. This is the reason for point two.

I would like to show a cutting of the canvas element 1. For example like the following image:

Currently i get the coordinate of the red arrow in canvas element 1, now i would like to do something like a cutting of this section with offset like in the image.

How could i solve something like this with JavaScript / JQuery. In summary i have two canvas elements. One of them is showing a big map with a red arrow which represents the current location (this works already), but now i wanna show a second canvas element with the zoom of this section where the red arrow is. Currently i am getting the coordinates, but no idea how i could "zoom" into an canvas element.

Like some of the current answers said, i provide some code:

My HTML Code, there is the mainCanvasMap, which has a Background Image and there is the zoomCanvas, which should display a section of the mainCanvasMap!

Here is a JavaScript snippet, which renders the red arrow on the map and should provide a zoom function (where the red-arrow is located) to the zoomCanvas Element.

var canvas = {}
canvas.canvas = null;
canvas.ctx = null;
canvas.scale = 0;

var zoomCanvas = {}
zoomCanvas.canvas = null;
zoomCanvas.ctx = null;
zoomCanvas.scale = 0;

    $(document).ready(function () {

        canvas.canvas = document.getElementById('mainCanvasMap');
        canvas.ctx = canvas.canvas.getContext('2d');

        zoomCanvas.canvas = document.getElementById('zoomCanvas');
        zoomCanvas.ctx = zoomCanvas.canvas.getContext('2d');

        setInterval(requestTheArrowPosition, 1000);
     });

     function requestTheArrowPosition() {
            renderArrowOnMainCanvasElement();
            renderZoomCanvas();
    }

    function renderArrowOnMainCanvasElement(){
          //ADD ARROW TO MAP AND RENDER THEM
    }

    function renderZoomCanvas() {

        //TRY TO ADD THE ZOOM FUNCTION, I WOULD LIKE TO COPY A SECTION OF THE MAINCANVASMAP
        zoomCanvas.ctx.fillRect(0, 0, zoomCanvas.canvas.width, zoomCanvas.canvas.height);
        zoomCanvas.ctx.drawImage(canvas.canvas, 50, 100, 200, 100, 0, 0, 400, 200);
        zoomCanvas.canvas.style.top = 100 + 10 + "px"
        zoomCanvas.canvas.style.left = 100 + 10 + "px"
        zoomCanvas.canvas.style.display = "block";

    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

    <!--MY MAIN CANVAS ELEMENT, WHICH HAS A BACKGROUND IMAGE AND WHERE THE ARROW IS RENDEREED-->
    <canvas id="mainCanvasMap" style="width:100%; height:100%; background: url('https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg') 0% 0% / 100% 100%;"></canvas>

    <!-- MY ZOOM CANVAS ELEMENT, SHOULD SHOW A CUTTING OF THE MAINCANVASMAP -->
    <canvas id="zoomCanvas" style="height:100%;width:100%"></canvas></code>```

The code is only a pseudo-code, but it shows what i like to do.

答:
Your code is using css for the canvas image, that not always looks the way we think...

I will recommend you to draw everything from scratch, here is a starting point:

canvas = document.getElementById('mainCanvasMap');
ctx = canvas.getContext('2d');

zoomCanvas = document.getElementById('zoomCanvas');
zoomCtx = zoomCanvas.getContext('2d');
var pos = {x:0, y:40}

image = document.getElementById('source');
image.onload = draw;

function draw() {
  ctx.drawImage(image,0,0);
  setInterval(drawZoom, 80);
}

function drawZoom() {
  // simple animation on the x axis
  x = Math.sin(pos.x++/10 % (Math.PI*2)) * 20 + 80
  zoomCtx.drawImage(image, x, pos.y, 200, 100, 0, 0, 400, 200);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="mainCanvasMap"></canvas>
<canvas id="zoomCanvas"></canvas>

<img id="source" src="https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg" style="display:none"></code>```

Title: zoom into html canvas

Body:
I would like show a cutting of a canvas element in another canvas element. For explanation i have the following structure:

Canvas Element which gets filled it's background by an image. On top of this image i draw a arrow and a possible path. The background-image is really big, which means that i can not get that much Information from this big image. This is the reason for point two.

I would like to show a cutting of the canvas element 1. For example like the following image:

Currently i get the coordinate of the red arrow in canvas element 1, now i would like to do something like a cutting of this section with offset like in the image.

How could i solve something like this with JavaScript / JQuery. In summary i have two canvas elements. One of them is showing a big map with a red arrow which represents the current location (this works already), but now i wanna show a second canvas element with the zoom of this section where the red arrow is. Currently i am getting the coordinates, but no idea how i could "zoom" into an canvas element.

Like some of the current answers said, i provide some code:

My HTML Code, there is the mainCanvasMap, which has a Background Image and there is the zoomCanvas, which should display a section of the mainCanvasMap!

Here is a JavaScript snippet, which renders the red arrow on the map and should provide a zoom function (where the red-arrow is located) to the zoomCanvas Element.

var canvas = {}
canvas.canvas = null;
canvas.ctx = null;
canvas.scale = 0;

var zoomCanvas = {}
zoomCanvas.canvas = null;
zoomCanvas.ctx = null;
zoomCanvas.scale = 0;

    $(document).ready(function () {

        canvas.canvas = document.getElementById('mainCanvasMap');
        canvas.ctx = canvas.canvas.getContext('2d');

        zoomCanvas.canvas = document.getElementById('zoomCanvas');
        zoomCanvas.ctx = zoomCanvas.canvas.getContext('2d');

        setInterval(requestTheArrowPosition, 1000);
     });

     function requestTheArrowPosition() {
            renderArrowOnMainCanvasElement();
            renderZoomCanvas();
    }

    function renderArrowOnMainCanvasElement(){
          //ADD ARROW TO MAP AND RENDER THEM
    }

    function renderZoomCanvas() {

        //TRY TO ADD THE ZOOM FUNCTION, I WOULD LIKE TO COPY A SECTION OF THE MAINCANVASMAP
        zoomCanvas.ctx.fillRect(0, 0, zoomCanvas.canvas.width, zoomCanvas.canvas.height);
        zoomCanvas.ctx.drawImage(canvas.canvas, 50, 100, 200, 100, 0, 0, 400, 200);
        zoomCanvas.canvas.style.top = 100 + 10 + "px"
        zoomCanvas.canvas.style.left = 100 + 10 + "px"
        zoomCanvas.canvas.style.display = "block";

    }

    <canvas id="mainCanvasMap" style="width:100%; height:100%; background: url('https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg') 0% 0% / 100% 100%;"></canvas>

    <canvas id="zoomCanvas" style="height:100%;width:100%"></canvas>

The code is only a pseudo-code, but it shows what i like to do.

Body:
Your code is using css for the canvas image, that not always looks the way we think...

I will recommend you to draw everything from scratch, here is a starting point:

canvas = document.getElementById('mainCanvasMap');
ctx = canvas.getContext('2d');

zoomCanvas = document.getElementById('zoomCanvas');
zoomCtx = zoomCanvas.getContext('2d');
var pos = {x:0, y:40}

image = document.getElementById('source');
image.onload = draw;

function draw() {
  ctx.drawImage(image,0,0);
  setInterval(drawZoom, 80);
}

function drawZoom() {
  // simple animation on the x axis
  x = Math.sin(pos.x++/10 % (Math.PI*2)) * 20 + 80
  zoomCtx.drawImage(image, x, pos.y, 200, 100, 0, 0, 400, 200);
}

<canvas id="mainCanvasMap"></canvas>
<canvas id="zoomCanvas"></canvas>

<img id="source" src="https://image.jimcdn.com/app/cms/image/transf/dimension=624x10000:format=jpg/path/s7d1eecaa5cee1012/image/i4484f962de0bf3c2/version/1543751018/image.jpg" style="display:none">