问:
Conditional validation in a JavaScript web form
I am working on a web form using JavaScript for validation.  This is only one section of a much larger form.

The form has a question that asks the user if they have a Social Security Number. (SocialSecurity field)  It has two radio buttons, one yes and one no.  IF the user answers yes, then another field (SSN) becomes visible.  Otherwise, it stays hidden.   This part is actually working. (the show/hide of the SSN field)

The JS needs to do two things.  IF the user answers yes, then the SSN field becomes required, and must validate that it has 9 integers.   BUT, if the user answers no, then SSN field, which will stay hidden must no longer be required.

What I am having difficulty with, is getting the SSN to be required only if the user answers yes, and validate it correctly under that circumstance.

Online Demo

Here is the code:

```<code><div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>

</div></div>

<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" maxlength="9" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div> </div>

$('.field.SocialSecurity input[type=radio]').on("change", function() {
  switch ($(this).val()) {
    case 'As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.':
      $('.field.SSN').show();
      $('.field.SSN input').focus();
      break;

    case 'Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.':
      $('.field.SSN').hide();
      break;
  }
});

//Here is the SS format validation section

function validateSSN() {
  if (!validateRequiredTextField('SSN', 'Social Security Number'))
    return false;

  var value = $('.field.SSN input').val();

  if (!isInteger(value) ||
    (value.length != 9) ||
    (value == '000000000') ||
    (value == '111111111') ||
    (value == '222222222') ||
    (value == '333333333') ||
    (value == '444444444') ||
    (value == '555555555') ||
    (value == '666666666') ||
    (value == '777777777') ||
    (value == '888888888') ||
    (value == '999999999') ||
    (value == '123456789')) {
    $('.field.SSN input').focus();
    alert("Invalid: Social Security Number");
    return false;
  }

  return true;
}

//overall form validation - section on SSN
function validateForm()

if (!validateSSN())
  return false;
</code>```

答:
Your sample code is way to messy to work with. I've created this demo to show you the basics of how I think you should go about this. Note that I have simplified your code and changed both field names and classnames for the purpose of this demo. If you choose to implement a solution such as this you will need to update code to use your own values accordingly. (see second snippet.)

Solution:

Use the browser's native validation by adding required and pattern attributes to the fields. A simple Rx pattern=[0-9]{9} will take care of your 9 integer validation requirement. Remember to re-validate server-side after the form has been submitted.

Using JavaScript (/jQuery) listen for changes on the SocialSecurity field then set the SSN field's disabled attribute to true or false to enable or disable it depending on the chosen SocialSecurity value. If you don't want the disabled SSN field to be visible you can have the JS hide its parent container. Note that so long as the field is given the disabled property it won't be validated or submitted regardless of whether its visible or not.

Woking demo:

$(function() {
  var $ssn = $(".SSN");
  //add and enable and disable custom event:
  $ssn.on("enable", function() {
    $(this).show().find("input").attr("disabled", false);
  }).on("disable", function() {
    $(this).hide().find("input").attr("disabled", true);
  })
  //set initial state to disabled:
  $ssn.trigger("disable");
  //listen for changes and change the $ssn state accordingly
  $("input[name='havessn']").on("change", function() {
    var val = $(this).val();
    if (val === 'nope') {
      $(".SSN").trigger("disable");
    } else {
      $(".SSN").trigger("enable");
    }
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input:required:valid {
  border: green solid 3px;
}</code>```

<form>

    Do you have a Social Security Number?

      <input type="radio" name="havessn" value="yup" required="required" />As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.

      <input type="radio" name="havessn" value="nope" required="required" />Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.

      Social Security Number <input name="ssn" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" />

    <input type="submit" />
</form>```
</div>
</div>
</p>

<p><strong>Demo for your specific use-case with unwieldy classnames intact:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
  var $ssn = $(".SSN");
  //add and enable and disable custom event:
  $ssn.on("enable", function() {
    $(this).show().find("input").attr("disabled", false);
  }).on("disable", function() {
    $(this).hide().find("input").attr("disabled", true);
  })
  //set initial state to disabled:
  $ssn.trigger("disable");
  //listen for changes and change the $ssn state accordingly
  $("input[name='p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list']").on("change", function() {
    var val = $(this).val();
    if (val === "Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.") {
      $(".SSN").trigger("disable");
    } else {
      $(".SSN").trigger("enable");
    }
  })
});</code>```

input:required:valid {
  border: green solid 3px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>

</div></div>

<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div></div></code>```

Body:
I am working on a web form using JavaScript for validation.  This is only one section of a much larger form.

The form has a question that asks the user if they have a Social Security Number. (SocialSecurity field)  It has two radio buttons, one yes and one no.  IF the user answers yes, then another field (SSN) becomes visible.  Otherwise, it stays hidden.   This part is actually working. (the show/hide of the SSN field)

The JS needs to do two things.  IF the user answers yes, then the SSN field becomes required, and must validate that it has 9 integers.   BUT, if the user answers no, then SSN field, which will stay hidden must no longer be required.

What I am having difficulty with, is getting the SSN to be required only if the user answers yes, and validate it correctly under that circumstance.

Online Demo

Here is the code:

Do you have a Social Security Number?

<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.

<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.

Social Security Number

<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" maxlength="9" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />

$('.field.SocialSecurity input[type=radio]').on("change", function() {
  switch ($(this).val()) {
    case 'As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.':
      $('.field.SSN').show();
      $('.field.SSN input').focus();
      break;

    case 'Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.':
      $('.field.SSN').hide();
      break;
  }
});

//Here is the SS format validation section

function validateSSN() {
  if (!validateRequiredTextField('SSN', 'Social Security Number'))
    return false;

  var value = $('.field.SSN input').val();

  if (!isInteger(value) ||
    (value.length != 9) ||
    (value == '000000000') ||
    (value == '111111111') ||
    (value == '222222222') ||
    (value == '333333333') ||
    (value == '444444444') ||
    (value == '555555555') ||
    (value == '666666666') ||
    (value == '777777777') ||
    (value == '888888888') ||
    (value == '999999999') ||
    (value == '123456789')) {
    $('.field.SSN input').focus();
    alert("Invalid: Social Security Number");
    return false;
  }

  return true;
}

//overall form validation - section on SSN
function validateForm()

if (!validateSSN())
  return false;

Body:
Your sample code is way to messy to work with. I've created this demo to show you the basics of how I think you should go about this. Note that I have simplified your code and changed both field names and classnames for the purpose of this demo. If you choose to implement a solution such as this you will need to update code to use your own values accordingly. (see second snippet.)

Solution:

Use the browser's native validation by adding required and pattern attributes to the fields. A simple Rx pattern=[0-9]{9} will take care of your 9 integer validation requirement. Remember to re-validate server-side after the form has been submitted.

Using JavaScript (/jQuery) listen for changes on the SocialSecurity field then set the SSN field's disabled attribute to true or false to enable or disable it depending on the chosen SocialSecurity value. If you don't want the disabled SSN field to be visible you can have the JS hide its parent container. Note that so long as the field is given the disabled property it won't be validated or submitted regardless of whether its visible or not.

Woking demo:

$(function() {
  var $ssn = $(".SSN");
  //add and enable and disable custom event:
  $ssn.on("enable", function() {
    $(this).show().find("input").attr("disabled", false);
  }).on("disable", function() {
    $(this).hide().find("input").attr("disabled", true);
  })
  //set initial state to disabled:
  $ssn.trigger("disable");
  //listen for changes and change the $ssn state accordingly
  $("input[name='havessn']").on("change", function() {
    var val = $(this).val();
    if (val === 'nope') {
      $(".SSN").trigger("disable");
    } else {
      $(".SSN").trigger("enable");
    }
  })
});

input:required:valid {
  border: green solid 3px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="field SocialSecurity">
    <span>Do you have a Social Security Number?</span>
    <div>
      <label><input type="radio" name="havessn" value="yup" required="required" />As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
      <label><input type="radio" name="havessn" value="nope" required="required" />Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
    </div>

    <div class="field SSN">
      <label>Social Security Number <input name="ssn" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" />
</label>
    </div>
    <input type="submit" />
</form>

Demo for your specific use-case with unwieldy classnames intact:

$(function() {
  var $ssn = $(".SSN");
  //add and enable and disable custom event:
  $ssn.on("enable", function() {
    $(this).show().find("input").attr("disabled", false);
  }).on("disable", function() {
    $(this).hide().find("input").attr("disabled", true);
  })
  //set initial state to disabled:
  $ssn.trigger("disable");
  //listen for changes and change the $ssn state accordingly
  $("input[name='p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list']").on("change", function() {
    var val = $(this).val();
    if (val === "Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.") {
      $(".SSN").trigger("disable");
    } else {
      $(".SSN").trigger("enable");
    }
  })
});

input:required:valid {
  border: green solid 3px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="field SocialSecurity">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_lb" class="EditingFormLabel">Do you have a Social Security Number?</span>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpsocialsecurity" class="EditingFormControlNestedControl editing-form-control-nested-control">
<span id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list" class="radio radio-list-vertical">
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_0">As a U.S. Citizen, permanent resident, or temporary working resident, I have a Social Security Number.</label><br />
<input id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1" type="radio" name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SocialSecurity$list" required="required" value="Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number." />
<label for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SocialSecurity_list_1">Due to my international student status, my residency status, or my specific visa type, I do not have a Social Security Number.</label>
</span>

</div></div>

<div class="field SSN">
<label id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_lb" class="EditingFormLabel" for="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText">Social Security Number</label>
<div id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_ncpssn" class="EditingFormControlNestedControl editing-form-control-nested-control">
<input name="p$lt$ctl03$pageplaceholder$p$lt$ctl00$On_lineForm$viewBiz$SSN$txtText" type="text" required="required" length="9" pattern="[0-9]{9}" title="Please provide a 9 digit SSN" id="p_lt_ctl03_pageplaceholder_p_lt_ctl00_On_lineForm_viewBiz_SSN_txtText" class="form-control" />
</div></div>


来源: stackexchange

问:
React fragment shorthand failing to compile
The project in question is using React-16.2.0 which has the capability to use Fragments and the Fragment shorthand.

https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

While the full-length syntax works fine...

```<code>import React, { Fragment, Component } from 'react';

class TestingFragment extends Component {
    render() {
        return (
            <Fragment>
                <span>This is a fragment of text </span>
                <div>Another part of the fragment</div>
            </Fragment>
        )
    }
};

export default TestingFragment
</code>```

The shorthand fails to compile and I am at a loss as to why this is. Fore example...

```<code>import React, { Component } from 'react';

class TestingFragment extends Component {
    render() {
        return (
            <>
                <span>This is a fragment of text </span>
                <div>Another part of the fragment</div>
            </>
        )
    }
};

export default TestingFragment
</code>```

Which fails to compile as follows...

```<code>Failed to compile
./src/testingFragments.js
Syntax error: Unexpected token (6:4)

  4 |   render() {
  5 |       return (
> 6 |           <>
    |            ^
  7 |               <span>This is a fragment of text </span>
  8 |               <div>Another part of the fragment</div>
  9 |           </>
This error occurred during the build time and cannot be dismissed.
</code>```

Is there something here I am missing about the Fragment shorthand syntax?

答:
You can use the poor man's fragment shorthand as a quick fix: [ , ]

```<code>render(){
  return [
    <div key="f">foo</div>,
    <div key="b">bar</div>
  ]
}
</code>```

as array of nodes is a valid jsx element. You need to add a key prop to each of them manually though as Anarno pointed out.

ContentLicense: CC BY-SA 3.0

Body:
The project in question is using React-16.2.0 which has the capability to use Fragments and the Fragment shorthand.

https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html

While the full-length syntax works fine...

import React, { Fragment, Component } from 'react';

class TestingFragment extends Component {
    render() {
        return (
            <Fragment>
                This is a fragment of text

Another part of the fragment

            </Fragment>
        )
    }
};

export default TestingFragment

The shorthand fails to compile and I am at a loss as to why this is. Fore example...

import React, { Component } from 'react';

class TestingFragment extends Component {
    render() {
        return (
            <>
                This is a fragment of text

Another part of the fragment

            </>
        )
    }
};

export default TestingFragment

Which fails to compile as follows...

Failed to compile
./src/testingFragments.js
Syntax error: Unexpected token (6:4)

  4 |   render() {
  5 |       return (
> 6 |           <>
    |            ^
  7 |               This is a fragment of text
  8 |
Another part of the fragment

  9 |           </>
This error occurred during the build time and cannot be dismissed.

Is there something here I am missing about the Fragment shorthand syntax?

Body:
You can use the poor man's fragment shorthand as a quick fix: [ , ]

render(){
  return [
    <div key="f">foo</div>,
    <div key="b">bar</div>
  ]
}

as array of nodes is a valid jsx element. You need to add a key prop to each of them manually though as Anarno pointed out.

ContentLicense: CC BY-SA 4.0


问:
Having difficulties in understanding Regexp in TCL Language
I am new to TCL language. I am having difficulties to catch data in myFile.txt.

MyFile.txt

```<code>set obj "{Hello}"
set obj "{Bye}"
set obj "{Nice}"
set obj "{Yoh}"
</code>```

I want to catch words inside the curly bracket as shown below.

```<code>Hello, Bye, Nice, Yoh
</code>```

How to do it with regexp in TCL.

答:
The first thing to try would be this simple thing:

```<code>regexp {\{(\w+)\}} $obj -> word
</code>```

The key points:

{ and } are metacharacters inside Tcl's RE language variant, so they need to be escaped.

The bit we want to extract (“non-empty word character sequence”, so \w+) needs to be captured and matched with a capture variable that comes afterwards: the -> is just a dummy variable for a capture that we want to ignore.

Always put REs in Tcl inside curly braces unless you know exactly what you're doing. (When you know what you're doing, you'll know to put them in braces virtually always anyway.) This allows us to write REs without an inflammation of backslashes.

Body:
I am new to TCL language. I am having difficulties to catch data in myFile.txt.

MyFile.txt

set obj "{Hello}"
set obj "{Bye}"
set obj "{Nice}"
set obj "{Yoh}"

I want to catch words inside the curly bracket as shown below.

Hello, Bye, Nice, Yoh

How to do it with regexp in TCL.

Body:
The first thing to try would be this simple thing:

regexp {\{(\w+)\}} $obj -> word

The key points:

{ and } are metacharacters inside Tcl's RE language variant, so they need to be escaped.

The bit we want to extract (“non-empty word character sequence”, so \w+) needs to be captured and matched with a capture variable that comes afterwards: the -> is just a dummy variable for a capture that we want to ignore.

Always put REs in Tcl inside curly braces unless you know exactly what you're doing. (When you know what you're doing, you'll know to put them in braces virtually always anyway.) This allows us to write REs without an inflammation of backslashes.


问:
Pop art effect in iphone
Thanks in advance.

I want to get a pop art effect on a image (pop art effect means in photoshop we will get 4 photos with different effects of same photo) in iphone using objective c. Actually i dodn't know is it possible or not , if possible how to proceed. If any one know please help me.

答:
Yes, it's possible with, for example, Apple's CoreImage framework, the algorithm should be easy to write, but harded to adjust:

Pseudocode:

```<code>image = loadImageFromFile("your image file");
popArt = createImage(/*width:*/ image.width * 2,
                     /*height:*/ image.height * 2);

subdivisions = [ [ 0, image.width, 0, image.height ],
                 [ image.width, image.width, 0, image.height ],
                 [ 0, image.width, image.height, image.height ],
                 [ image.width, image.width,  image.height, image.height ] ];

blendFunctions = [ boost_red, boost_blue, boost_yellow, boost_green ];

for(i=0;i<4;++i) {
   fillRectangle(rectangle[i], /*dest. image:*/popArt,
                            /*source image:*/image,
                            blendFunctions[i]);
}
</code>```

Title: Pop art effect in iphone

Body:
Yes, it's possible with, for example, Apple's CoreImage framework, the algorithm should be easy to write, but harded to adjust:

Pseudocode:

image = loadImageFromFile("your image file");
popArt = createImage(/*width:*/ image.width * 2,
                     /*height:*/ image.height * 2);

subdivisions = [ [ 0, image.width, 0, image.height ],
                 [ image.width, image.width, 0, image.height ],
                 [ 0, image.width, image.height, image.height ],
                 [ image.width, image.width,  image.height, image.height ] ];

blendFunctions = [ boost_red, boost_blue, boost_yellow, boost_green ];

for(i=0;i<4;++i) {
   fillRectangle(rectangle[i], /*dest. image:*/popArt,
                            /*source image:*/image,
                            blendFunctions[i]);
}


问:
How to update nested mongo object
I am trying to make a report function for my app

in the front end I make a put request :

```<code>.put(`http://localhost:3000/api/posts/report`, {
                        params: {
                            id: mongoId,
                            reportInfo: {
                                reported: true,
                                reportingUser: id
                            }
                        }
                    })

</code>```

to this backend route

```<code>router.put('/report', (req, res, next) => {
    postModel.findOneAndUpdate(
        { _id: mongoose.Types.ObjectId(req.query.id) },
        req.query,
        { new: true, useFindAndModify: false },
        (error, returnedDocuments) => {
            if (error) return next(error);
            res.json(returnedDocuments);
        }
    );
});
</code>```

for this model

```<code>const postSchema = new mongoose.Schema(
    {
        title: { type: String },
        description: { type: String },
        image: { type: String },
        price: { type: String },
        location: { type: String },
        image: { type: Array },
        author: {
            type: String,
            ref: 'User'
        },
        reportInfo: {
            reported:{
                type: Boolean,
                default: false
            },

            reportingUser:{
            type: String
            }

        }
    },
    {
        timestamps: true
    }
);
</code>```

any ideas why it is not updating the reportInfo object , do I need to do something if there are some nested objects contained?

thanks

答:
Your code tries to replace entires MongoDB document. Try to use $set instead of passing req.query directly:

```<code>{ $set: { reportInfo: req.query.reportInfo } }
</code>```

I would also check if there should be req.query or req.body so just print the value to make sure that it gets deserialized properly.

Title: How to update nested mongo object

Body:
I am trying to make a report function for my app

in the front end I make a put request :

.put(`http://localhost:3000/api/posts/report`, {
                        params: {
                            id: mongoId,
                            reportInfo: {
                                reported: true,
                                reportingUser: id
                            }
                        }
                    })

to this backend route

router.put('/report', (req, res, next) => {
    postModel.findOneAndUpdate(
        { _id: mongoose.Types.ObjectId(req.query.id) },
        req.query,
        { new: true, useFindAndModify: false },
        (error, returnedDocuments) => {
            if (error) return next(error);
            res.json(returnedDocuments);
        }
    );
});

for this model

const postSchema = new mongoose.Schema(
    {
        title: { type: String },
        description: { type: String },
        image: { type: String },
        price: { type: String },
        location: { type: String },
        image: { type: Array },
        author: {
            type: String,
            ref: 'User'
        },
        reportInfo: {
            reported:{
                type: Boolean,
                default: false
            },

            reportingUser:{
            type: String
            }

        }
    },
    {
        timestamps: true
    }
);

any ideas why it is not updating the reportInfo object , do I need to do something if there are some nested objects contained?

thanks

Body:
Your code tries to replace entires MongoDB document. Try to use $set instead of passing req.query directly:

{ $set: { reportInfo: req.query.reportInfo } }

I would also check if there should be req.query or req.body so just print the value to make sure that it gets deserialized properly.


问:
How can I use onClick on stateless component in React?
I want to use onClick on a stateless compoenent but it's reject an error like : onClick listener to be a function, instead got a value of object type.

I need to show and hide component on click.
Example when I click on the <ResultCard/> component I want to hide him and show <ResultDetail/>

State React Component :

```<code>import React, { Component } from "react";
import ResultCard from "./ResultCard";
import "../../assets/css/Result.css";
import Spinner from "../Spinner";
import { getApiToken, getParisByPrice } from "../../services/api";
import Modal from "../Modal";
import "../../assets/css/BudgetEntry.css";
import modify from "../../assets/images/modify.png";
import ResultDetail from "./ResultDetail";

class Results extends Component {
  state = {
    priceValue: "",
    showResult: true
  };

  showResultDetail = () => {

    this.setState({ showResult: false });
  };

  closeResultDetails = () => {

    this.setState({ showResult: true });
  };

  render() {
    return (
      <div className="results-container">

        {this.state.loading ? (
          <Spinner />
        ) : (
          <div className={"row"}>
            {this.state.showResult ?
            (
              this.state.paris.map(details => (
                <ResultCard
                  key={details.id}
                  id={details.id}
                  showResultDetail={this.showResultDetail}
                  prefix={details.prefix}
                  costPerDay={details.average_cost_per_day}
                  logoSports={details.infrastructure.map(home =>
                    home.logo_path.map(path_image => (
                      <img
                        src={path_image}
                        alt="icon-sports"
                        style={{ width: 20 }}
                        key={path_image}
                      />
                    ))
                  )}
                />
              ))
            )
              :
            (
              <ResultDetail closeResultDetail={this.closeResultDetails}/>
            )
            }
          </div>
        )}
      </div>
    );
  }
}

export default Results;

</code>```

ResultCard (who is stateless component):

```<code>import React from 'react';
import '../../assets/css/ResultCard.css';

const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id}) => {

  return (
    <div className="card" onClick={showResultDetail} id={id}>
      <p style={{margin:5}}>{prefix}</p>
      <p style={{margin:1}}>arrondissement</p>
      <p>{costPerDay} $</p>
      {logoSports}
    </div>
  )

};

export default ResultCard;
</code>```

ResultDetail (who is stateless component):

```<code>import React from 'react';

const ResultDetail = (closeResultDetail) => (

      <div onClick={closeResultDetail}>
        <p>Result detail</p>
      </div>
)

export default ResultDetail;
</code>```

thank for your help

答:
in your state component

```<code>  showResultDetail = () => {

    this.setState({ showResult: false });
  };

   render() {

        ....
        <ResultCard
        ....
        show={this.state.showResult}
         //defer the execution of the method
        onClick={(e) => this.showResultDetail(e)}/>

    }

</code>```

resultCard.js

```<code>const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id, show}) => {

  if(show)
     return (
    <div className="card" onClick={showResultDetail} id={id}>
      <p style={{margin:5}}>{prefix}</p>
      <p style={{margin:1}}>arrondissement</p>
      <p>{costPerDay} $</p>
      {logoSports}
    </div>
  );

};

</code>```

Body:
I want to use onClick on a stateless compoenent but it's reject an error like : onClick listener to be a function, instead got a value of object type.

I need to show and hide component on click.
Example when I click on the <ResultCard/> component I want to hide him and show <ResultDetail/>

State React Component :

import React, { Component } from "react";
import ResultCard from "./ResultCard";
import "../../assets/css/Result.css";
import Spinner from "../Spinner";
import { getApiToken, getParisByPrice } from "../../services/api";
import Modal from "../Modal";
import "../../assets/css/BudgetEntry.css";
import modify from "../../assets/images/modify.png";
import ResultDetail from "./ResultDetail";

class Results extends Component {
  state = {
    priceValue: "",
    showResult: true
  };

  showResultDetail = () => {

    this.setState({ showResult: false });
  };

  closeResultDetails = () => {

    this.setState({ showResult: true });
  };

  render() {
    return (

        {this.state.loading ? (
          <Spinner />
        ) : (

            {this.state.showResult ?
            (
              this.state.paris.map(details => (
                <ResultCard
                  key={details.id}
                  id={details.id}
                  showResultDetail={this.showResultDetail}
                  prefix={details.prefix}
                  costPerDay={details.average_cost_per_day}
                  logoSports={details.infrastructure.map(home =>
                    home.logo_path.map(path_image => (

                    ))
                  )}
                />
              ))
            )
              :
            (
              <ResultDetail closeResultDetail={this.closeResultDetails}/>
            )
            }

        )}

    );
  }
}

export default Results;

ResultCard (who is stateless component):

import React from 'react';
import '../../assets/css/ResultCard.css';

const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id}) => {

  return (

{prefix}

arrondissement

{costPerDay} $

      {logoSports}

  )

};

export default ResultCard;

ResultDetail (who is stateless component):

import React from 'react';

const ResultDetail = (closeResultDetail) => (

Result detail

)

export default ResultDetail;

thank for your help

Body:
in your state component

  showResultDetail = () => {

    this.setState({ showResult: false });
  };

   render() {

        ....
        <ResultCard
        ....
        show={this.state.showResult}
         //defer the execution of the method
        onClick={(e) => this.showResultDetail(e)}/>

    }

resultCard.js

const ResultCard = ({prefix, costPerDay, logoSports, showResultDetail, id, show}) => {

  if(show)
     return (
    <div className="card" onClick={showResultDetail} id={id}>
      <p style={{margin:5}}>{prefix}</p>
      <p style={{margin:1}}>arrondissement</p>
      <p>{costPerDay} $</p>
      {logoSports}
    </div>
  );

};


问:
Possible to send an email from SendGrid & React.js without a back-end?
I have a React.js app that I am hosting on a cPanel that does not allow a back-end within the application.  Wondering if I can get sendgrid to work without the back-end?  Has anyone gotten this to work previously?

I currently get the following error:

```<code>Access to fetch at 'https://api.sendgrid.com/v3/mail/send' from origin '
    https://angelospizzaharvard.com' has been blocked by CORS policy: Response
    to preflight request doesn't pass access control check: The 'Access-Control-
    Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not
    equal to the supplied origin.

Have the server send the header with a valid
    value, or, if an opaque response serves your needs, set the request's mode
    to 'no-cors' to fetch the resource with CORS disabled.
    Navbar.js:427 TypeError: Failed to fetch
</code>```

答: From this link sendgrid docs, it seems that it could only be called from a back-end server. </p>

Body:
I have a React.js app that I am hosting on a cPanel that does not allow a back-end within the application.  Wondering if I can get sendgrid to work without the back-end?  Has anyone gotten this to work previously?

I currently get the following error:

Access to fetch at 'https://api.sendgrid.com/v3/mail/send' from origin '
    https://angelospizzaharvard.com' has been blocked by CORS policy: Response
    to preflight request doesn't pass access control check: The 'Access-Control-
    Allow-Origin' header has a value 'https://sendgrid.api-docs.io' that is not
    equal to the supplied origin.

Have the server send the header with a valid
    value, or, if an opaque response serves your needs, set the request's mode
    to 'no-cors' to fetch the resource with CORS disabled.
    Navbar.js:427 TypeError: Failed to fetch


问:
Only print specific information to String
I have a firebase app where I am able to use a datasnapshot to return a users UID and Score from my Firebase realtime database.

When I run this code:

package com.example.securityapp;

import androidx.appcompat.app.AppCompatActivity;

import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import static java.lang.System.in;

public class leaderboard extends AppCompatActivity {

    DatabaseReference databaseUsers;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    FirebaseAuth mAuth;
    TextView score;
    private static final String TAG = "leaderboard";
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leaderboard);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();
        score = (TextView) findViewById(R.id.tableText);

        leaderBoard();

    }

    public void leaderBoard(){
        database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    System.out.println("The score is: " + snapshot.toString());
                    s = s + snapshot.toString() + "\n";
                    score.setText(s);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

            }

        });

    }

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

<p>I get this as a result:
<img src="https://i.stack.imgur.com/cKAeA.png" alt="enter image description here"></p>

<p>Is there anyway to only have the key value and points value returned as opposed to all of the other information that comes along with it?</p>

<p>The current state of the leaderboard screen:
<img src="https://i.stack.imgur.com/qvjGJ.png" alt="enter image description here"></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".leaderboard">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.38">

            <TextView
                android:layout_width="420dp"
                android:layout_height="150dp"
                android:gravity="center"
                android:text="Leaderboard!"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textColor="#0C40F1"
                android:textSize="50dp"
                android:textStyle="bold">

            </TextView>
        </RelativeLayout>

        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            <TableRow>
                <TextView
                    android:text="User ID"
                    android:padding="3dip"
                    android:layout_gravity="center"
                    android:textSize="20dp"/>
                <TextView
                    android:text="Points"
                    android:layout_gravity="center"
                    android:gravity="right"
                    android:textSize="20dp"/>
            </TableRow>
            <TableRow>
                <TextView
                    />
            </TableRow>
            <TableRow>
                <TextView
                    android:id="@+id/tableText"
                    android:layout_weight="1"/>
            </TableRow>
        </TableLayout>
    </LinearLayout>

</ScrollView></code>```

Thanks

答:
You're loading the entire Scores node, but apparently only want to show the value of a single property of each child. In that case you can look up the value of that property with something like:

```<code>database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            System.out.println("The score is: " + snapshot.child("Points").getValue());
            s = s + snapshot.toString() + "\n";
            score.setText(s);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "onCancelled", databaseError.toException());
    }
});
</code>```

Body:
I have a firebase app where I am able to use a datasnapshot to return a users UID and Score from my Firebase realtime database.

When I run this code:

package com.example.securityapp;

import androidx.appcompat.app.AppCompatActivity;

import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import static java.lang.System.in;

public class leaderboard extends AppCompatActivity {

    DatabaseReference databaseUsers;
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    FirebaseAuth mAuth;
    TextView score;
    private static final String TAG = "leaderboard";
    String s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leaderboard);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();
        score = (TextView) findViewById(R.id.tableText);

        leaderBoard();

    }

    public void leaderBoard(){
        database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    System.out.println("The score is: " + snapshot.toString());
                    s = s + snapshot.toString() + "\n";
                    score.setText(s);
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                // Getting Post failed, log a message
                Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

            }

        });

    }

}

I get this as a result:

Is there anyway to only have the key value and points value returned as opposed to all of the other information that comes along with it?

The current state of the leaderboard screen:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context=".leaderboard">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="0.38">

            <TextView
                android:layout_width="420dp"
                android:layout_height="150dp"
                android:gravity="center"
                android:text="Leaderboard!"
                android:textAppearance="@style/TextAppearance.AppCompat.Body1"
                android:textColor="#0C40F1"
                android:textSize="50dp"
                android:textStyle="bold">

            </TextView>
        </RelativeLayout>

        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            >
            <TableRow>
                <TextView
                    android:text="User ID"
                    android:padding="3dip"
                    android:layout_gravity="center"
                    android:textSize="20dp"/>
                <TextView
                    android:text="Points"
                    android:layout_gravity="center"
                    android:gravity="right"
                    android:textSize="20dp"/>
            </TableRow>
            <TableRow>
                <TextView
                    />
            </TableRow>
            <TableRow>
                <TextView
                    android:id="@+id/tableText"
                    android:layout_weight="1"/>
            </TableRow>
        </TableLayout>
    </LinearLayout>

</ScrollView>

Thanks

Body:
You're loading the entire Scores node, but apparently only want to show the value of a single property of each child. In that case you can look up the value of that property with something like:

database.getReference().child("Scores").addValueEventListener(new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            System.out.println("The score is: " + snapshot.child("Points").getValue());
            s = s + snapshot.toString() + "\n";
            score.setText(s);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.w(TAG, "onCancelled", databaseError.toException());
    }
});


问:
Solving a closure pattern with TypeScript?
I have a class containing two methods. The first takes a callback function and loops over a set of values,  and for each that satisfies a condition it executes the callback with two parameters:

```<code>...
public mapShapeMatrix(callback): void {
    let row = 0, col = 0;

    for (let bit = 0x8000; bit > 0; bit = bit >> 1) {
        if (this.dirs[this.currentDir] & bit) {
            callback(col, row);
        }
        if (++col === 4) {
            col = 0;
            ++row;
        }
    }
}
...
</code>```

I then have another method which calls the first and passes it a callback:

```<code>...
private collide(boardMatrix): boolean {
    this.mapShapeMatrix(
        (col: number, row: number) => {
            if ((boardMatrix[row + this.offset.y] &&
                boardMatrix[row + this.offset.y][col + this.offset.x]) !== 0) {
                return true;
            }
        }
    )
    return false;
}
...
</code>```

Then later on I am calling the collide function to check whether it returned true or false:

```<code>if (this.collide(boardMatrix)) {
    // do stuff
}
</code>```

The problem is, as expected, that the callback returns true within its own scope, and does not return from the collide function. Normally I would solve this with a closure pattern, but it's not so easy with TypeScript. Storing the call to this.mapShapeMatrix in a variable means that the collide function is not returning a boolean, and if its return type is not a boolean then the call to this.collide complains about checking for truthiness against the wrong type.

Essentially I'm looking to find out if there is a way in TypeScript to write this kind of pattern, and if not, is there a different solution?

答:
If I've understood the question correctly, you need to change the methods to return booleans as mapShapeMatrix doesn't return anything. You can then check the returned values, something like:</p>

```<code>type CB = (x: number, y: number) => boolean

public mapShapeMatrix(callback: CB): boolean {
    let row = 0, col = 0

    for (let bit = 0x8000; bit > 0; bit = bit >> 1) {
        if (this.dirs[this.currentDir] & bit) {
            if (callback(col, row)) {
                return true
            }
        }

        if (++col === 4) {
            col = 0
            ++row
        }
    }

    return false
}

private collide(boardMatrix): boolean {
    return this.mapShapeMatrix(
        (col: number, row: number) => {
            if ((boardMatrix[row + this.offset.y] &&
                boardMatrix[row + this.offset.y][col + this.offset.x]) !== 0) {
                return true
            } else {
                return false
            }
        }
    )
    return false
}
</code>```

Body:
I have a class containing two methods. The first takes a callback function and loops over a set of values,  and for each that satisfies a condition it executes the callback with two parameters:

...
public mapShapeMatrix(callback): void {
    let row = 0, col = 0;

    for (let bit = 0x8000; bit > 0; bit = bit >> 1) {
        if (this.dirs[this.currentDir] & bit) {
            callback(col, row);
        }
        if (++col === 4) {
            col = 0;
            ++row;
        }
    }
}
...

I then have another method which calls the first and passes it a callback:

...
private collide(boardMatrix): boolean {
    this.mapShapeMatrix(
        (col: number, row: number) => {
            if ((boardMatrix[row + this.offset.y] &&
                boardMatrix[row + this.offset.y][col + this.offset.x]) !== 0) {
                return true;
            }
        }
    )
    return false;
}
...

Then later on I am calling the collide function to check whether it returned true or false:

if (this.collide(boardMatrix)) {
    // do stuff
}

The problem is, as expected, that the callback returns true within its own scope, and does not return from the collide function. Normally I would solve this with a closure pattern, but it's not so easy with TypeScript. Storing the call to this.mapShapeMatrix in a variable means that the collide function is not returning a boolean, and if its return type is not a boolean then the call to this.collide complains about checking for truthiness against the wrong type.

Essentially I'm looking to find out if there is a way in TypeScript to write this kind of pattern, and if not, is there a different solution?

Body:
If I've understood the question correctly, you need to change the methods to return booleans as mapShapeMatrix doesn't return anything. You can then check the returned values, something like:

type CB = (x: number, y: number) => boolean

public mapShapeMatrix(callback: CB): boolean {
    let row = 0, col = 0

    for (let bit = 0x8000; bit > 0; bit = bit >> 1) {
        if (this.dirs[this.currentDir] & bit) {
            if (callback(col, row)) {
                return true
            }
        }

        if (++col === 4) {
            col = 0
            ++row
        }
    }

    return false
}

private collide(boardMatrix): boolean {
    return this.mapShapeMatrix(
        (col: number, row: number) => {
            if ((boardMatrix[row + this.offset.y] &&
                boardMatrix[row + this.offset.y][col + this.offset.x]) !== 0) {
                return true
            } else {
                return false
            }
        }
    )
    return false
}


问:
Catch array combine warning and print own error message?
I read some csv file and map the contents to the field names using array_combine:

```<code>$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);
</code>```

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

答:
According to the docs if either array is empty or if they are of different lengths, array_combine will return false.

So you should be able to do something like:

```<code>if($b = array_combine($a, $csv)) {

} else {
   ... the warning occurred ...
}
</code>```

Body:
I read some csv file and map the contents to the field names using array_combine:

$csv = array();
$a = array('some fields');
$b = array_combine($a, $csv);

However if the field names in $a are different from what I specified in my csv file the method will fails with a warning

array_combine()
  [function.array-combine]: Both
  parameters should have an equal number
  of elements

I tried using try and catch but this does not work. As a note, I am working with zend framework.

Any ideas how to catch the warning?

Body:
According to the docs if either array is empty or if they are of different lengths, array_combine will return false.

So you should be able to do something like:

if($b = array_combine($a, $csv)) {

} else {
   ... the warning occurred ...
}


问:
Confluent Kafka Streams - Could not find class io.confluent.connect.avro.ConnectDefault
I am using a jdbc source connector with query mode, and it seems that without a specified table name, the schemas registered in the schema-registry for the record key and record value have empty schema names and are being assigned the default name "ConnectDefault" as defined in Confluent's AvroData class https://github.com/confluentinc/schema-registry/blob/master/avro-converter/src/main/java/io/confluent/connect/avro/AvroData.java

When running a Kafka Streams application using generated avro sources and  SpecificAvroSerde, I am getting the error:

```<code>Exception in thread "streams-app-6e39ebfd-db14-49bc-834f-afaf108a6d25-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Failed to deserialize value for record. topic=topic-name, partition=0, offset=0
  at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:46)
  at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
  at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
  at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
  at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
  at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
  at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing Avro message for id 2
Caused by: org.apache.kafka.common.errors.SerializationException: Could not find class io.confluent.connect.avro.ConnectDefault specified in writer's schema whilst finding reader's schema for a SpecificRecord.
</code>```

I have tried to POST a new version of both the key and value schemas from the topic with a table name as the schema name and DELETE the original versions that had the \"name\":\"ConnectDefault\",\"namespace\":\"io.confluent.connect.avro\" properties with no luck. Am I missing a class named ConnectDefault or can I specify somewhere in the source connector a schema name without the namespace?

My Kafka Streams configuration:

```<code>streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-app");
streamsConfig.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
streamsConfig.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081");
streamsConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
</code>```

My Kafka Connect configuration:

```<code>name=source
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=1
connection.url=jdbc:oracle:thin:
mode=incrementing
incrementing.column.name=id
query=QUERY
topic.prefix=topic-name

transforms=InsertKey, ExtractId
transforms.InsertKey.type=org.apache.kafka.connect.transforms.ValueToKey
transforms.InsertKey.fields=id
transforms.ExtractId.type=org.apache.kafka.connect.transforms.ExtractField$Key
transforms.ExtractId.field=id
key.converter=org.apache.kafka.connect.storage.StringConverter
key.converter.schemas.enable=false

value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schemas.enable=true
value.converter.schema.registry.url=http://localhost:8081
</code>```

答:
By default kafka will search for key schema in ConnectDefault. </p>

<p>Just create the key schema class with name as "ConnectDefault" and keep that class inside package "io.confluent.connect.avro". </p>

Body:
I am using a jdbc source connector with query mode, and it seems that without a specified table name, the schemas registered in the schema-registry for the record key and record value have empty schema names and are being assigned the default name "ConnectDefault" as defined in Confluent's AvroData class https://github.com/confluentinc/schema-registry/blob/master/avro-converter/src/main/java/io/confluent/connect/avro/AvroData.java

When running a Kafka Streams application using generated avro sources and  SpecificAvroSerde, I am getting the error:

Exception in thread "streams-app-6e39ebfd-db14-49bc-834f-afaf108a6d25-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Failed to deserialize value for record. topic=topic-name, partition=0, offset=0
  at org.apache.kafka.streams.processor.internals.SourceNodeRecordDeserializer.deserialize(SourceNodeRecordDeserializer.java:46)
  at org.apache.kafka.streams.processor.internals.RecordQueue.addRawRecords(RecordQueue.java:84)
  at org.apache.kafka.streams.processor.internals.PartitionGroup.addRawRecords(PartitionGroup.java:117)
  at org.apache.kafka.streams.processor.internals.StreamTask.addRecords(StreamTask.java:474)
  at org.apache.kafka.streams.processor.internals.StreamThread.addRecordsToTasks(StreamThread.java:642)
  at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:548)
  at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:519)
Caused by: org.apache.kafka.common.errors.SerializationException: Error deserializing Avro message for id 2
Caused by: org.apache.kafka.common.errors.SerializationException: Could not find class io.confluent.connect.avro.ConnectDefault specified in writer's schema whilst finding reader's schema for a SpecificRecord.

I have tried to POST a new version of both the key and value schemas from the topic with a table name as the schema name and DELETE the original versions that had the \"name\":\"ConnectDefault\",\"namespace\":\"io.confluent.connect.avro\" properties with no luck. Am I missing a class named ConnectDefault or can I specify somewhere in the source connector a schema name without the namespace?

My Kafka Streams configuration:

streamsConfig.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-app");
streamsConfig.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
streamsConfig.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, "http://localhost:8081");
streamsConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

My Kafka Connect configuration:

name=source
connector.class=io.confluent.connect.jdbc.JdbcSourceConnector
tasks.max=1
connection.url=jdbc:oracle:thin:
mode=incrementing
incrementing.column.name=id
query=QUERY
topic.prefix=topic-name

transforms=InsertKey, ExtractId
transforms.InsertKey.type=org.apache.kafka.connect.transforms.ValueToKey
transforms.InsertKey.fields=id
transforms.ExtractId.type=org.apache.kafka.connect.transforms.ExtractField$Key
transforms.ExtractId.field=id
key.converter=org.apache.kafka.connect.storage.StringConverter
key.converter.schemas.enable=false

value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schemas.enable=true
value.converter.schema.registry.url=http://localhost:8081

Body:
By default kafka will search for key schema in ConnectDefault.

Just create the key schema class with name as "ConnectDefault" and keep that class inside package "io.confluent.connect.avro".


问:
How to Add XLSX to server side Node JS
I want it to read XLSX Excel file on server side

I try to install with "node install xlsx"

```<code>var XLSX = require('xlsx');

        var XLSdata = null;
        const fs = require('fs');
        // First I want to read the file
        //console.log("ovde", fs);
        fs.readFile('/roster.xls', function (err, data) {
          ///console.log("dir", __dirname);
          console.log("error", err);
          //console.log("ovde",data);
          XLSdata = data;
        });
      try {
        var workbook = XLSX.read(XLSdata, {type: 'binary'});
      }

      catch(err) {
          console.log("error",err.message);
        return;
      }
</code>```

When I compile code I got the error:

"Error: Cannot find module 'xlsx'"

答:
To install it:

npm i xlsx

To use it:

```<code>const XLSX = require("xlsx");

let workbook = XLSX.readFile("./test.xlsx");

console.log(workbook);
</code>```

(You can use var here instead of const and let)

Title: How to Add XLSX to server side Node JS

Body:
I want it to read XLSX Excel file on server side

I try to install with "node install xlsx"

var XLSX = require('xlsx');

        var XLSdata = null;
        const fs = require('fs');
        // First I want to read the file
        //console.log("ovde", fs);
        fs.readFile('/roster.xls', function (err, data) {
          ///console.log("dir", __dirname);
          console.log("error", err);
          //console.log("ovde",data);
          XLSdata = data;
        });
      try {
        var workbook = XLSX.read(XLSdata, {type: 'binary'});
      }

      catch(err) {
          console.log("error",err.message);
        return;
      }

When I compile code I got the error:

"Error: Cannot find module 'xlsx'"

Body:
To install it:

npm i xlsx

To use it:

const XLSX = require("xlsx");

let workbook = XLSX.readFile("./test.xlsx");

console.log(workbook);

(You can use var here instead of const and let)


问:
Sheets IF Function setup and/or formatting errors
Cell C5 on the Trip Assignment Form tab is a dropdown selection list of destinations.  I am trying to make sheets automatically fill in the C6 cell with the matching address (coming from a tab called Schools).  When I put the below formula in I get an error or FALSE but I cannot figure out why.

=if(C5=Schools!A1, C6=Schools!B1, "Other Error")

I need to make the formula work for any destination selected so that the appropriate address is inserted into the cell.  Can I do this like the way I am thinking or would Apps Script be better and if so how would I go about that?

"Trip Assignment Form"

"Schools" data sheet

Link to copy of my sheet:

https://docs.google.com/spreadsheets/d/1Xkwxjtf6syEd-zGaPUVsyE2_6Kfczu8c-8W3RuRg9CY/edit?usp=sharing

答:
It is possible to do with Google Apps Script but it's probably not the easiest way to go

You can use the onEdit trigger and this sort of code:

```<code>function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='Sheet12' && e.range.columnStart==1 && e.range.rowStart==1 & e.value!='') {
    var ss=SpreadsheetApp.getActive();
    var sh1=ss.getSheetByName('Sheet12');
    var v1=sh1.getRange(1,1).getValue();
    var sh2=ss.getSheetByName('Sheet13');
    var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues();
    for(var i=0;i<v2.length;i++) {
      if(v2[i][0]==v1) {
        sh1.getRange(2,1).setValue(v2[i][1]);
      }
    }
  }
}
</code>```

Animation:

Your setup:

```<code>function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='assignment sheet name' && e.range.columnStart==3 && e.range.rowStart==5 & e.value!='') {
    var ss=SpreadsheetApp.getActive();
    var sh1=ss.getSheetByName('assignment sheet name');//assignment sheet name
    var v1=sh1.getRange(e.range.rowStart,e.range.columnStart).getValue();
    var sh2=ss.getSheetByName('schools sheet name');//schools sheet name
    var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues();
    for(var i=0;i<v2.length;i++) {
      if(v2[i][0]==v1) {
        sh1.getRange(6,3).setValue(v2[i][1]);
      }
    }
  }
}
</code>```

Body:
It is possible to do with Google Apps Script but it's probably not the easiest way to go

You can use the onEdit trigger and this sort of code:

function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='Sheet12' && e.range.columnStart==1 && e.range.rowStart==1 & e.value!='') {
    var ss=SpreadsheetApp.getActive();
    var sh1=ss.getSheetByName('Sheet12');
    var v1=sh1.getRange(1,1).getValue();
    var sh2=ss.getSheetByName('Sheet13');
    var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues();
    for(var i=0;i<v2.length;i++) {
      if(v2[i][0]==v1) {
        sh1.getRange(2,1).setValue(v2[i][1]);
      }
    }
  }
}

Animation:

Your setup:

function onEdit(e) {
  var sh=e.range.getSheet();
  if(sh.getName()=='assignment sheet name' && e.range.columnStart==3 && e.range.rowStart==5 & e.value!='') {
    var ss=SpreadsheetApp.getActive();
    var sh1=ss.getSheetByName('assignment sheet name');//assignment sheet name
    var v1=sh1.getRange(e.range.rowStart,e.range.columnStart).getValue();
    var sh2=ss.getSheetByName('schools sheet name');//schools sheet name
    var v2=sh2.getRange(1,1,sh2.getLastRow(),2).getValues();
    for(var i=0;i<v2.length;i++) {
      if(v2[i][0]==v1) {
        sh1.getRange(6,3).setValue(v2[i][1]);
      }
    }
  }
}


问:
Cannot add hostPath to under volumes in custom SCC
I have an OpenShift custom SCC which I have deployed.
I want to add hostPath to the volumes section.
I use the following command:

```<code>$ oc edit scc custom-scc
</code>```

Add line

```<code>- hostPath
</code>```

Save and exit

Upon returning to edit I see that nothing my addition was removed.

I don't have this problem with other edits such as capabilities.

答:
I needed to also add:</p>

```<code>allowHostDirVolumePlugin: true
</code>```

Body:
I have an OpenShift custom SCC which I have deployed.
I want to add hostPath to the volumes section.
I use the following command:

$ oc edit scc custom-scc

Add line

- hostPath

Save and exit

Upon returning to edit I see that nothing my addition was removed.

I don't have this problem with other edits such as capabilities.

Body:
I needed to also add:

allowHostDirVolumePlugin: true


问:
Perform a lookup between C# Lists and return matched where value is minimum
I have two lists:

```<code>var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}
</code>```

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

```<code>    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }
</code>```

Example data:

qtys

```<code>WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0
</code>```

times

```<code>WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5
</code>```

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

答:
What you want is a group join:

Functional Syntax

```<code>var query1 = qtys.Where(q => q.QuantityInWarehouse > 0)
                 .GroupJoin(times, q => q.WarehouseId, t => t.WarehouseId, (q, t) => new { q.WarehouseId, TransitDays = t.DefaultIfEmpty().Min(grp => grp?.TransitDays) })
                 .OrderBy(g => g.TransitDays)
                 .FirstOrDefault();
</code>```

Query Syntax

```<code>var query2 = from q in qtys
             join t in times on q.WarehouseId equals t.WarehouseId into grp
             where q.QuantityInWarehouse > 0
             select new
             {
                 q.WarehouseId,
                 TransitDays = grp.DefaultIfEmpty().Min(g => g?.TransitDays)
             };

var result = query2.OrderBy(g => g.TransitDays)
                   .FirstOrDefault();
</code>```

A group join will join two lists together on their corresponding keys--similar to a database join--and the associated values to those keys will be grouped into an enumerable. From that enumerable, you can derive the minimum value that you care about, TransitDays in this case.

There is no equivalent to "first or default" in query syntax. The easiest approach is just to apply the same OrderBy and FirstOrDefault against the query variable, as demonstrated above.

Body:
I have two lists:

var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }

Example data:

qtys

WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0

times

WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

Body:
What you want is a group join:

Functional Syntax

var query1 = qtys.Where(q => q.QuantityInWarehouse > 0)
                 .GroupJoin(times, q => q.WarehouseId, t => t.WarehouseId, (q, t) => new { q.WarehouseId, TransitDays = t.DefaultIfEmpty().Min(grp => grp?.TransitDays) })
                 .OrderBy(g => g.TransitDays)
                 .FirstOrDefault();

Query Syntax

var query2 = from q in qtys
             join t in times on q.WarehouseId equals t.WarehouseId into grp
             where q.QuantityInWarehouse > 0
             select new
             {
                 q.WarehouseId,
                 TransitDays = grp.DefaultIfEmpty().Min(g => g?.TransitDays)
             };

var result = query2.OrderBy(g => g.TransitDays)
                   .FirstOrDefault();

A group join will join two lists together on their corresponding keys--similar to a database join--and the associated values to those keys will be grouped into an enumerable. From that enumerable, you can derive the minimum value that you care about, TransitDays in this case.

There is no equivalent to "first or default" in query syntax. The easiest approach is just to apply the same OrderBy and FirstOrDefault against the query variable, as demonstrated above.


问:
rcpp compiling error when installing R 3.5 packages (ubuntu 16.04)
I'm unable to install tidyverse or devtools, and I'm getting this error:

```<code>/usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
make: *** [RcppExports.o] Error 1
</code>```

For example, these are the results for install.packages("tidyverse", dependencies = TRUE):

```<code> ^
/usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
make: *** [RcppExports.o] Error 1
ERROR: compilation failed for package ‘xml2’
* removing ‘/usr/local/lib/R/site-library/xml2’
ERROR: dependency ‘xml2’ is not available for package ‘rvest’
* removing ‘/usr/local/lib/R/site-library/rvest’
ERROR: dependencies ‘rvest’, ‘xml2’ are not available for package ‘tidyverse’
* removing ‘/usr/local/lib/R/site-library/tidyverse’
</code>```

My R version:

```<code>platform       x86_64-pc-linux-gnu
arch           x86_64
os             linux-gnu
system         x86_64, linux-gnu
status
major          3
minor          5.3
year           2019
month          03
day            11
svn rev        76217
language       R
version.string R version 3.5.3 (2019-03-11)
nickname       Great Truth
</code>```

I've tried installing each individual dependency, but get the same error each time (sometimes with a  different constellation of dependencies: rvest,roxygen2,rversions,lintr,etc.). I've also tried uninstalling Rcpp and reinstalling it. I've tried updating my packages (update.packages(checkBuilt=TRUE, ask=FALSE). I haven't messed with any other settings. This is running on Ubuntu 16.04 with 2GB of RAM. Could it be a memory issue? Do I need to start from scratch and reinstall?

```<code>Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial
</code>```

```<code>              total        used        free      shared  buff/cache   available
Mem:           1971         932         653          16         385         830
Swap:           999         518         481
</code>```

ADDED INFO: I saw it suggested elsewhere to try installing the latest version of xml2 from github: remotes::install_github("hadley/xml2")

This is the error (similar to the one before) I got when doing that:

```<code>  ^
   /usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
   make: *** [RcppExports.o] Error 1
   ERROR: compilation failed for package ‘xml2’
─  removing ‘/tmp/RtmpNcUpLL/Rinst1bbc679e28bc/xml2’
         -----------------------------------
   ERROR: package installation failed
Error: Failed to install 'xml2' from GitHub:
  System command 'R' failed, exit status: 1, stdout + stderr (last 10 lines):
>                  from RcppExports.cpp:4:
> /usr/include/unicode/ucnv.h:585:1: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type
>  U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterPointer, UConverter, ucnv_close);
>  ^
> /usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
> make: *** [RcppExports.o] Error 1
> ERROR: compilation failed for package ‘xml2’
> * removing ‘/tmp/RtmpNcUpLL/Rinst1bbc679e28bc/xml2’
>       -----------------------------------
> ERROR: package installation failed
>

</code>```

Results from R CMD config --all

```<code>
CC = gcc -std=gnu99
CFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CPICFLAGS = -fpic
CPP = gcc -std=gnu99 -E
CPPFLAGS =
CXX = g++
CXXCPP = g++ -E
CXXFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXXPICFLAGS = -fpic
CXX11 = g++
CXX11STD = -std=gnu++11
CXX11FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX11PICFLAGS = -fpic
CXX14 = g++
CXX14STD = -std=gnu++14
CXX14FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX14PICFLAGS = -fpic
CXX98 = g++
CXX98STD = -std=gnu++98
CXX98FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX98PICFLAGS = -fpic
CXX17 =
CXX17STD =
CXX17FLAGS =
CXX17PICFLAGS =
CXX1X = g++
CXX1XSTD = -std=gnu++11
CXX1XFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX1XPICFLAGS = -fpic
DYLIB_EXT = .so
DYLIB_LD = gcc -std=gnu99
DYLIB_LDFLAGS = -shared -fopenmp
F77 = gfortran
FFLAGS = -g -O2 -fstack-protector-strong
FPICFLAGS = -fpic
FLIBS = -lgfortran -lm -lquadmath
SAFE_FFLAGS = -g -O2 -fstack-protector-strong -msse2 -mfpmath=sse
FC = gfortran
FCFLAGS = -g -O2 -fstack-protector-strong
FCPICFLAGS = -fpic
OBJC =
OBJCFLAGS =
JAVA = /usr/lib/jvm/default-java/jre/bin/java
JAVAC = /usr/lib/jvm/default-java/bin/javac
JAVAH = /usr/lib/jvm/default-java/bin/javah
JAR = /usr/lib/jvm/default-java/bin/jar
JAVA_HOME = /usr/lib/jvm/default-java
JAVA_LIBS = -L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm
JAVA_CPPFLAGS = -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux
LDFLAGS = -Wl,-Bsymbolic-functions -Wl,-z,relro
SHLIB_CFLAGS =
SHLIB_CXXLD = g++
SHLIB_CXXLDFLAGS = -shared
SHLIB_CXX98LD = g++ -std=gnu++98
SHLIB_CXX98LDFLAGS = -shared
SHLIB_CXX11LD = g++ -std=gnu++11
SHLIB_CXX11LDFLAGS = -shared
SHLIB_CXX14LD = g++ -std=gnu++14
SHLIB_CXX14LDFLAGS = -shared
SHLIB_CXX17LD =
SHLIB_CXX17LDFLAGS = -shared
SHLIB_EXT = .so
SHLIB_FFLAGS =
SHLIB_LD = gcc -std=gnu99
SHLIB_LDFLAGS = -shared
SHLIB_FCLD = gfortran
SHLIB_FCLDFLAGS = -shared
SHLIB_CXX1XLD = g++ -std=gnu++11
SHLIB_CXX1XLDFLAGS = -shared
TCLTK_CPPFLAGS = -I/usr/include/tcl8.6 -I/usr/include/tcl8.6
TCLTK_LIBS = -L/usr/lib/x86_64-linux-gnu -ltcl8.6 -L/usr/lib/x86_64-linux-gnu -ltk8.6 -lX11 -lXss -lXext
BLAS_LIBS = -lblas
LAPACK_LIBS = -llapack
MAKE = make
LIBnn = lib
LOCAL_SOFT =
COMPILED_BY =
</code>```

答:
I was eventually able to install xml2 into a different library directory by doing this at the command line:

```<code>sudo apt-get install r-cran-xml2
</code>```

This installed xml2 into the /usr/lib/R/site-library directory, whereas using R and install.packages installs by default into the /usr/local/lib/R/site-library directory, which is what wasn't working.

Once xml2 was installed, it allowed me to install devtools and kinda-sorta solved my issue for the moment, but I still get the rcpp error if I try to install tidyverse or several other packages using sudo R-->install.packages("xml2"). I'd be interested in finding out what's going on if anyone ever happens upon this and has any insight!

Body:
I'm unable to install tidyverse or devtools, and I'm getting this error:

/usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
make: *** [RcppExports.o] Error 1

For example, these are the results for install.packages("tidyverse", dependencies = TRUE):

 ^
/usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
make: *** [RcppExports.o] Error 1
ERROR: compilation failed for package ‘xml2’
* removing ‘/usr/local/lib/R/site-library/xml2’
ERROR: dependency ‘xml2’ is not available for package ‘rvest’
* removing ‘/usr/local/lib/R/site-library/rvest’
ERROR: dependencies ‘rvest’, ‘xml2’ are not available for package ‘tidyverse’
* removing ‘/usr/local/lib/R/site-library/tidyverse’

My R version:

platform       x86_64-pc-linux-gnu
arch           x86_64
os             linux-gnu
system         x86_64, linux-gnu
status
major          3
minor          5.3
year           2019
month          03
day            11
svn rev        76217
language       R
version.string R version 3.5.3 (2019-03-11)
nickname       Great Truth

I've tried installing each individual dependency, but get the same error each time (sometimes with a  different constellation of dependencies: rvest,roxygen2,rversions,lintr,etc.). I've also tried uninstalling Rcpp and reinstalling it. I've tried updating my packages (update.packages(checkBuilt=TRUE, ask=FALSE). I haven't messed with any other settings. This is running on Ubuntu 16.04 with 2GB of RAM. Could it be a memory issue? Do I need to start from scratch and reinstall?

Distributor ID: Ubuntu
Description:    Ubuntu 16.04.6 LTS
Release:    16.04
Codename:   xenial

              total        used        free      shared  buff/cache   available
Mem:           1971         932         653          16         385         830
Swap:           999         518         481

ADDED INFO: I saw it suggested elsewhere to try installing the latest version of xml2 from github: remotes::install_github("hadley/xml2")

This is the error (similar to the one before) I got when doing that:

  ^
   /usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
   make: *** [RcppExports.o] Error 1
   ERROR: compilation failed for package ‘xml2’
─  removing ‘/tmp/RtmpNcUpLL/Rinst1bbc679e28bc/xml2’
         -----------------------------------
   ERROR: package installation failed
Error: Failed to install 'xml2' from GitHub:
  System command 'R' failed, exit status: 1, stdout + stderr (last 10 lines):
>                  from RcppExports.cpp:4:
> /usr/include/unicode/ucnv.h:585:1: error: ‘unique_ptr’ in namespace ‘std’ does not name a template type
>  U_DEFINE_LOCAL_OPEN_POINTER(LocalUConverterPointer, UConverter, ucnv_close);
>  ^
> /usr/lib/R/etc/Makeconf:172: recipe for target 'RcppExports.o' failed
> make: *** [RcppExports.o] Error 1
> ERROR: compilation failed for package ‘xml2’
> * removing ‘/tmp/RtmpNcUpLL/Rinst1bbc679e28bc/xml2’
>       -----------------------------------
> ERROR: package installation failed
>

Results from R CMD config --all

CC = gcc -std=gnu99
CFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CPICFLAGS = -fpic
CPP = gcc -std=gnu99 -E
CPPFLAGS =
CXX = g++
CXXCPP = g++ -E
CXXFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXXPICFLAGS = -fpic
CXX11 = g++
CXX11STD = -std=gnu++11
CXX11FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX11PICFLAGS = -fpic
CXX14 = g++
CXX14STD = -std=gnu++14
CXX14FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX14PICFLAGS = -fpic
CXX98 = g++
CXX98STD = -std=gnu++98
CXX98FLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX98PICFLAGS = -fpic
CXX17 =
CXX17STD =
CXX17FLAGS =
CXX17PICFLAGS =
CXX1X = g++
CXX1XSTD = -std=gnu++11
CXX1XFLAGS = -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g
CXX1XPICFLAGS = -fpic
DYLIB_EXT = .so
DYLIB_LD = gcc -std=gnu99
DYLIB_LDFLAGS = -shared -fopenmp
F77 = gfortran
FFLAGS = -g -O2 -fstack-protector-strong
FPICFLAGS = -fpic
FLIBS = -lgfortran -lm -lquadmath
SAFE_FFLAGS = -g -O2 -fstack-protector-strong -msse2 -mfpmath=sse
FC = gfortran
FCFLAGS = -g -O2 -fstack-protector-strong
FCPICFLAGS = -fpic
OBJC =
OBJCFLAGS =
JAVA = /usr/lib/jvm/default-java/jre/bin/java
JAVAC = /usr/lib/jvm/default-java/bin/javac
JAVAH = /usr/lib/jvm/default-java/bin/javah
JAR = /usr/lib/jvm/default-java/bin/jar
JAVA_HOME = /usr/lib/jvm/default-java
JAVA_LIBS = -L/usr/lib/jvm/default-java/jre/lib/amd64/server -ljvm
JAVA_CPPFLAGS = -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux
LDFLAGS = -Wl,-Bsymbolic-functions -Wl,-z,relro
SHLIB_CFLAGS =
SHLIB_CXXLD = g++
SHLIB_CXXLDFLAGS = -shared
SHLIB_CXX98LD = g++ -std=gnu++98
SHLIB_CXX98LDFLAGS = -shared
SHLIB_CXX11LD = g++ -std=gnu++11
SHLIB_CXX11LDFLAGS = -shared
SHLIB_CXX14LD = g++ -std=gnu++14
SHLIB_CXX14LDFLAGS = -shared
SHLIB_CXX17LD =
SHLIB_CXX17LDFLAGS = -shared
SHLIB_EXT = .so
SHLIB_FFLAGS =
SHLIB_LD = gcc -std=gnu99
SHLIB_LDFLAGS = -shared
SHLIB_FCLD = gfortran
SHLIB_FCLDFLAGS = -shared
SHLIB_CXX1XLD = g++ -std=gnu++11
SHLIB_CXX1XLDFLAGS = -shared
TCLTK_CPPFLAGS = -I/usr/include/tcl8.6 -I/usr/include/tcl8.6
TCLTK_LIBS = -L/usr/lib/x86_64-linux-gnu -ltcl8.6 -L/usr/lib/x86_64-linux-gnu -ltk8.6 -lX11 -lXss -lXext
BLAS_LIBS = -lblas
LAPACK_LIBS = -llapack
MAKE = make
LIBnn = lib
LOCAL_SOFT =
COMPILED_BY =

Body:
I was eventually able to install xml2 into a different library directory by doing this at the command line:

sudo apt-get install r-cran-xml2

This installed xml2 into the /usr/lib/R/site-library directory, whereas using R and install.packages installs by default into the /usr/local/lib/R/site-library directory, which is what wasn't working.

Once xml2 was installed, it allowed me to install devtools and kinda-sorta solved my issue for the moment, but I still get the rcpp error if I try to install tidyverse or several other packages using sudo R-->install.packages("xml2"). I'd be interested in finding out what's going on if anyone ever happens upon this and has any insight!


问:
How to calculate the difference between two cumsum columns using Pandas
I have the following data frame:

```<code>         duid start_date   end_date
0   b2919f1eb 2019-08-26 2019-09-05
1   e372dedd4 2019-08-26        NaT
2   ba8147ce9 2019-09-09 2019-11-05
3   902c56036 2019-09-13 2019-10-01
4   16ec096a7 2019-09-17 2019-10-02
5   1faac1a15 2019-09-17        NaT
6   319fb59f5 2019-09-24 2020-01-20
7   2a3f1dac5 2019-10-01        NaT
8   aecbcf0c5 2019-10-01 2019-11-05
9   0ee088b63 2019-10-08 2019-10-03
10  c0c02fa4c 2019-10-31 2019-10-31
12  aac5fbc7d 2019-11-05 2019-11-05
11  c76bc248a 2019-11-05 2019-11-29
13  20dcef410 2019-11-12        NaT
14  bc7ea631d 2019-11-12        NaT
15  786af275b 2019-11-12 2019-11-12
16  005ec00c8 2019-11-15        NaT
17  482462695 2019-11-19        NaT
18  ecba54e5d 2019-11-26        NaT
19  28490c52f 2019-12-17        NaT
20  02f2f7f4b 2020-01-15        NaT
21  0ea659d1a 2020-01-29        NaT
22  0b78caca1 2020-01-29        NaT
23  368cc8744 2020-01-29 2020-01-29
</code>```

This table describes staff hired and left dates.  So far I've managed to calculate the count per month:

df.groupby(df['start_date'].dt.strftime('%Y %B')) \
   .agg(hired=('start_date', 'size'), left=('end_date', 'count')) \
   .reset_index()
```

```       start_date  hired  left
0     2019 August      2     1
1   2019 December      1     0
2   2019 November      8     3
3    2019 October      4     3
4  2019 September      5     4
5    2020 January      4     1
```

<p>Also, I've tried to calculate the cumulative sum of each date, but it returns weird results</p>

<pre class="lang-py prettyprint-override"><code>ds = df.groupby(df['start_date'].dt.strftime('%Y %B'))
ds.size().cumsum()
</code>```

```<code>start_date
2019 August        2
2019 December      3
2019 November     11
2019 October      15
2019 September    20
2020 January      24
dtype: int64
</code>```

And the cumulative lefts...

de = df.groupby(df['end_date'].dt.strftime('%Y %B'))
de.size().cumsum()
```

```end_date
2019 November      5
2019 October       9
2019 September    10
2020 January      12
dtype: int64
```

<p>There's a sort thing, I don't know why the table doesn't take the sort order by <code>start_date</code>, but that issue is not as relevant as to calculate the difference between the two values i.e.:</p>

```df = df.sort_values('start_date')
```

<p>How can I sum the cumulative of two columns, <code>start_date</code> and <code>end_date</code> to get the following result</p>

```       start_date  hired  left  rooster
0     2019 August      2     1        1
1  2019 September      5     4        2
2    2019 October      4     3        3
3   2019 November      8     3        8
4   2019 December      1     0        9
5    2020 January      4     1       12
```

答:
You'll probably find it easier to leave the grouping key as a datetime like object and then just reformat it at the end so sorting works correctly. (So pd.Grouper with a freq or .to_period(...) etc...)

Start with getting your initial aggregate figures and sort by the grouped index so your data is guaranteed to be in sorted order:

```<code>agg = (
    df.groupby(pd.Grouper(key='start_date', freq='M'))['end_date']
    .agg(hired='size', left='count')
    .sort_index()
)
</code>```

Then assign a new column for the running total of the roster...

```<code>agg['roster'] = agg['hired'].cumsum() - agg['left'].cumsum()
</code>```

Then reformat your index and reset it, eg:

```<code>agg = agg.set_index(agg.index.strftime('%Y %B')).reset_index()
</code>```

Will give you:

```<code>       start_date  hired  left  roster
0     2019 August      2     1       1
1  2019 September      5     4       2
2    2019 October      4     3       3
3   2019 November      8     3       8
4   2019 December      1     0       9
5    2020 January      4     1      12
</code>```

Body:
I have the following data frame:

         duid start_date   end_date
0   b2919f1eb 2019-08-26 2019-09-05
1   e372dedd4 2019-08-26        NaT
2   ba8147ce9 2019-09-09 2019-11-05
3   902c56036 2019-09-13 2019-10-01
4   16ec096a7 2019-09-17 2019-10-02
5   1faac1a15 2019-09-17        NaT
6   319fb59f5 2019-09-24 2020-01-20
7   2a3f1dac5 2019-10-01        NaT
8   aecbcf0c5 2019-10-01 2019-11-05
9   0ee088b63 2019-10-08 2019-10-03
10  c0c02fa4c 2019-10-31 2019-10-31
12  aac5fbc7d 2019-11-05 2019-11-05
11  c76bc248a 2019-11-05 2019-11-29
13  20dcef410 2019-11-12        NaT
14  bc7ea631d 2019-11-12        NaT
15  786af275b 2019-11-12 2019-11-12
16  005ec00c8 2019-11-15        NaT
17  482462695 2019-11-19        NaT
18  ecba54e5d 2019-11-26        NaT
19  28490c52f 2019-12-17        NaT
20  02f2f7f4b 2020-01-15        NaT
21  0ea659d1a 2020-01-29        NaT
22  0b78caca1 2020-01-29        NaT
23  368cc8744 2020-01-29 2020-01-29

This table describes staff hired and left dates.  So far I've managed to calculate the count per month:

df.groupby(df['start_date'].dt.strftime('%Y %B')) \
   .agg(hired=('start_date', 'size'), left=('end_date', 'count')) \
   .reset_index()

       start_date  hired  left
0     2019 August      2     1
1   2019 December      1     0
2   2019 November      8     3
3    2019 October      4     3
4  2019 September      5     4
5    2020 January      4     1

Also, I've tried to calculate the cumulative sum of each date, but it returns weird results

ds = df.groupby(df['start_date'].dt.strftime('%Y %B'))
ds.size().cumsum()

start_date
2019 August        2
2019 December      3
2019 November     11
2019 October      15
2019 September    20
2020 January      24
dtype: int64

And the cumulative lefts...

de = df.groupby(df['end_date'].dt.strftime('%Y %B'))
de.size().cumsum()

end_date
2019 November      5
2019 October       9
2019 September    10
2020 January      12
dtype: int64

There's a sort thing, I don't know why the table doesn't take the sort order by start_date, but that issue is not as relevant as to calculate the difference between the two values i.e.:

df = df.sort_values('start_date')

How can I sum the cumulative of two columns, start_date and end_date to get the following result

       start_date  hired  left  rooster
0     2019 August      2     1        1
1  2019 September      5     4        2
2    2019 October      4     3        3
3   2019 November      8     3        8
4   2019 December      1     0        9
5    2020 January      4     1       12

Body:
You'll probably find it easier to leave the grouping key as a datetime like object and then just reformat it at the end so sorting works correctly. (So pd.Grouper with a freq or .to_period(...) etc...)

Start with getting your initial aggregate figures and sort by the grouped index so your data is guaranteed to be in sorted order:

agg = (
    df.groupby(pd.Grouper(key='start_date', freq='M'))['end_date']
    .agg(hired='size', left='count')
    .sort_index()
)

Then assign a new column for the running total of the roster...

agg['roster'] = agg['hired'].cumsum() - agg['left'].cumsum()

Then reformat your index and reset it, eg:

agg = agg.set_index(agg.index.strftime('%Y %B')).reset_index()

Will give you:

       start_date  hired  left  roster
0     2019 August      2     1       1
1  2019 September      5     4       2
2    2019 October      4     3       3
3   2019 November      8     3       8
4   2019 December      1     0       9
5    2020 January      4     1      12


问:
Artifact has not been packaged yet
I am letting Maven copy some dependency files into a specific location for a GWT project. The maven-dependency-plugin does the job and so far it works. The only Problem is that I'm getting an error from Eclipse that says:

Artifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187.

I have tried to change the <phase> but that did not work. How can I get rid of that error and why is it there because Maven builds as intended.

<plugins>
  <plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <phase>install</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <outputDirectory>${project.basedir}/war/WEB-INF/lib</outputDirectory>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>
```

答:
For those returning to this question, it may be useful to report seeing the same problem in Eclipse against maven-dependency-plugin version 2.8.  This was in the package phase:

Artifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187. (org.apache.maven.plugins:maven-dependency-plugin:2.8:copy:copy-proguard:package)

In this case upgrading to 3.1.1 solved the problem:

```<code><plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
        <execution>
            <id>copy-proguard</id>
            <phase>package</phase>
            <goals>
                <goal>copy</goal>
            </goals>
            ...
</code>```

Title: Artifact has not been packaged yet

Body:
For those returning to this question, it may be useful to report seeing the same problem in Eclipse against maven-dependency-plugin version 2.8.  This was in the package phase:

Artifact has not been packaged yet. When used on reactor artifact, copy should be executed after packaging: see MDEP-187. (org.apache.maven.plugins:maven-dependency-plugin:2.8:copy:copy-proguard:package)

In this case upgrading to 3.1.1 solved the problem:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <version>3.1.1</version>
    <executions>
        <execution>
            <id>copy-proguard</id>
            <phase>package</phase>
            <goals>
                <goal>copy</goal>
            </goals>
            ...