text:
Q: How to customize a .bst file I want to customize this .bst file.
Now, when I compile a reference it gives me (For an entry of type @article):

Author1, Author2, "Title," Journal Volume (Year) pages, arxiv:0208157.

But I want to make the comma appear after the quotation mark, and I want to replace arxiv:0208157 with [hep-ph/0208157]:

Author1, Author2, "Title", Journal Volume (Year) pages
  [hep-ph/0208157].

Here is an MWE:
  \documentclass{article}
   \usepackage{filecontents}
   \begin{filecontents*}{test.bib}
      @article{AA,
      archivePrefix = {arXiv},
      arxivId = {hep-th/9605032},
      primaryClass = {hep-th},
      author = {AuthorI, A. and AuthorII, B. and AuthorIII, C.},
      eprint = {9605032},
      journal = {Journal},
      pages = {pages},
      title = {{Title with ?}},
      volume = {Volume},
      year = {Year}
      }
  \end{filecontents*}
  \begin{document}

  \nocite{*}

  %Bibloography

 \bibliographystyle{utphys}
 \bibliography{test}
 \end{document}

Update: Concerning the arxiv problem, you have to replace, in the FUNCTION {format.primaryClass} of .bst file, the code "{ " [" primaryClass * "]" *} by  { "" primaryClass *}. And in the function FUNCTION {format.eprint} you should replace "{{\ttfamily " * format.archive * eprint * format.primaryClass * "}}" *} by "{{" * " [" * format.primaryClass * "/" * eprint * "]" * "}}" * }
Now, I have a new problem: when the arxivId does not contains a category e.g. hep-th,in primaryClass = {hep-th}, the citation printed as [/9605032]. So, my new question is how to write it in this case just [Arxiv:9605032]?.
Update II: The solution is so easy!, I have just to type "Arxiv" instead of "" after primaryClass empty$

A: You need to apply minor modifications to the following two functions, starting on l. 519, in the file utphys.bst:
FUNCTION {format.title}
{ title empty$
    { "" }
    { "``" title "t" change.case$ * ",''" * }
  if$
}

FUNCTION {format.title.p}
{ title empty$
    { "" }
    { "``" title "t" change.case$ * ".''" * }
  if$
}

Specifically, change ,'' to '', in format.title, and change .'' to ''. in format.title.p.
Note that you shouldn't edit and change an original file from the TeX distribution directly. Instead, make a copy of the file utphys.bst and apply the two suggestions given above to the copy.

A: To fix the problem of arxiv papers, first, you have to replace, in the utphys.bst file, the code
FUNCTION {format.primaryClass}
{
  primaryClass empty$
      { "" }
      { " [" primaryClass * "]" *}
  if$
}

FUNCTION {format.eprint}
{ eprint empty$
     { ""}
     { archive empty$
          {"\href{http://arxiv.org/abs/" eprint * "}" *
             "{{\ttfamily " * format.archive * eprint *
              format.primaryClass * "}}" *}
          {"\href{" archive *  "/" * eprint * "}" *
             "{{\ttfamily " * format.archive * eprint *
              format.primaryClass * "}}" *}
       if$
     }
     if$
}

by the following code:
FUNCTION {format.primaryClass}
{
  primaryClass empty$
      { "Arxiv:" } %
     { "" primaryClass * "/" *}        %Vall { " [" primaryClass * "]" *}
  if$
}

FUNCTION {format.eprint} % eprint:9605032, http://arxiv.org/abs/hep-th/9605023
{ eprint empty$
     { "" }
     {  archive empty$
          {"\href{http://arxiv.org/abs/"  format.primaryClass *  eprint * "}" *
             "{{" * " [" * format.primaryClass *                              % vall "{{\ttfamily " * format.archive * eprint *
               eprint * "]" * "}}" * }

          {"\href{http://arxiv.org/abs/"  "}" *
             "{{" * " [" * format.primaryClass *
              eprint * "]" * "}}" *}
       if$
        }
     if$
}

Explication:
I) in  format.primaryClass { "" primaryClass * "/" *} instead of { " [" primaryClass * "]" *}  will replace  [hep-th] by hep-th/. So it will print primaryClass/ (printClass is
the catagory of the paper e.g. hep-th ) when it is defined, else (some of arxiv papers do not have a primaryClass) it would print Arxiv: (If$ will check that).
II) in  format.eprint:
A): \href{http://arxiv.org/abs/"  format.primaryClass *  eprint * "}": this useful only when you use the hyperref package,
 it produces the hyperlink http://arxiv.org/abs/primerClass/eprint e.g. if  primaryClass = {hep-th} and eprint = {9605032} it will produce
http://arxiv.org/abs/hep-th/9605032. The code "{{" * " [" * format.primaryClass * eprint * "]" * "}}" * } is the hyperlinked printed text which is
[format.primaryClass eprint] i.e. in my previous example [hep-th/9605032].  Remark: If you do not use the hyperref package this will just print
 [hep-th/9605032].
B) : Now, you can guess what the code "\href{http://arxiv.org/abs/"  "}" does ?. When the arxiv paper does not have a primaryClass the case
A) is omitted and the program will excute this code, so  this is nothing but \href{http://arxiv.org/abs/format.primaryClass eprint } and since there is no primaryClass the format.primaryClass is just Arxiv:. e.g. if  eprint = {1512.00704} this will give the hyperlink http://arxiv.org/abs/Arxiv:1512.00704 and you will automatically redirected
to the link http://arxiv.org/abs/1512.00704. Finally, the code "{{" * " [" * format.primaryClass *  eprint * "]" * "}}" * will print the hyperlinked
text [format.primaryClass eprint] which is in our last example [Arxiv:1512.00704].
To remove the comma before Arxiv you must replace the following code (as in this answer):
FUNCTION {article}
{ output.bibitem
  format.collaboration output
  format.authors "author" output.check
  format.title "title" output.check
  blank.sep
  crossref missing$
  { journal missing$
        {}
        { format.journal add.doi "journal" output.check}
      if$
    report missing$
        {format.eprint output}
        {blank.sep format.report output format.eprint output}
      if$
    }
    { format.article.crossref output.nonnull
      format.pages output
      format.eprint output
    }
  if$
  new.sentence
  format.url output
  new.sentence
  note output
  new.sentence
  format.SLACcitation output
  fin.entry
}

by the code:
FUNCTION {article}
{ output.bibitem
  format.collaboration output
  format.authors "author" output.check
  format.title "title" output.check
  blank.sep
  crossref missing$
  { journal missing$
        {}
        { format.journal add.doi "journal" output.check}
      if$
    report missing$
         {before.all 'output.state := %% added
         format.eprint output}
        {blank.sep format.report output format.eprint output}
      if$
    }
    { format.article.crossref output.nonnull
      format.pages output
      format.eprint output
    }
  if$
  new.sentence
  format.url output
  new.sentence
  note output
  new.sentence
  format.SLACcitation output
  fin.entry
}

A MWE:
  \documentclass{article}
   \begin{filecontents*}{test.bib}
     @article{A,
      archivePrefix = {arXiv},
      arxivId = {hep-th/9605032},
      author = {AuthorI, A. and AuthorII, B. and AuthorIII, C.},
      eprint = {9605032},
      journal = {Journal of Bla bla},
      pages = {12},
      primaryClass = {hep-th},
      title = {{Title of the paper A}},
      volume = {123},
      year = {2016}
        }
     @article{B,
      archivePrefix = {arXiv},
      author = {AuthorA, A. and AuthorB, B. and AuthorC, C.},
      arxivId = {1512.00704},
      eprint = {1512.00704},
      journal = {Journal of bla bla},
      pages = {1233},
      title = {{Title of the paper B}},
      volume = {567},
      year = {2016}
        }
  \end{filecontents*}
  \begin{document}

   ~\nocite{*}

 %Bibleography

 \bibliographystyle{Vall}
 \bibliography{test}
 \end{document}

The result:


text:
Q: Angular: Cannot retrieve function parameter value as an object property selector I have an issue trying to retrieve a function parameter value as an object property selector into a .filter() method.
This is my code:
myFunction(property, value) {
    function myFilter(obj) {
        return obj.details.name == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(myFilter));
}

I want to replace return obj.details.name == value; by return obj.property == value;.
obj.property is the parameter of my function myFunction(property, value). The value parameter value works fine and is well retrieved.
This is what I want:
getFilteredFMsBy(property, value) {
    function specificFilter(obj) {
        return obj.property == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}

If I define the value of property in the function, same case. It doesn't work:
getFilteredFMsBy(property, value) {
    property = "details.name";
    function specificFilter(obj) {
        return obj.property == value;
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}

Any idea?

A: Seems like you need to access object[prop][prop2] given the object and the string "prop.prop2"
from this answer: Javascript: Get deep value from object by passing path to it as string you can do deepFind:
function deepFind(obj, path) {
  var paths = path.split('.')
    , current = obj
    , i;

  for (i = 0; i < paths.length; ++i) {
    if (current[paths[i]] == undefined) {
      return undefined;
    } else {
      current = current[paths[i]];
    }
  }
  return current;
}

then do
getFilteredFMsBy(property, value) {
    property = "details.name";
    function specificFilter(obj) {
        return deepFind(obj, property) == value; // <-- use it here
    }
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter));
}

A: How about this?
getFilteredFMsBy(property: string, value:any) {
    return this._http.get(this.Url).map((response: Response) => response.json().filter((obj) => { return obj[property] == value; }));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function similar to x * Gaussian function, but with equal areas bounded by positive and negative sides I would like to find a function which graphically resembles $xe^{-x^2}$, or similarly the $\psi_{1}$ eigenfunction of the Schrodinger equation, and has the following properties:
It is continuous and differentiable. Also, the value at which the function converges to near-$0$ with a near-$0$ slope on the left and the right are fixed (say, to $x = 0$ and $x = 1$), and within the domain $[0,1]$, the area enclosed by each hump separated by the point m at which the function crosses the x-axis is equal. Since the area outside of the bounds is negligible, the domain restriction for area is not important. I am hoping to easily toggle where the point m lies, and even when it is closer to the left or right bound, still maintain the property that their areas are equal. Attached is a demos sketch that has disproportionate humps (move s to change the crossing point): https://www.desmos.com/calculator/0fnj3yxeru
and here is a partial solution, which is not differentiable at m: https://www.desmos.com/calculator/ywxezwhpk6?fbclid=IwAR0iWXLgRXcbz3swvUGjR8jUk847o0IlVPFb1v_07ENgXTW7hfB8Hf_Zl0E


text:
Q: [].slice.call(arguments) не копирует значение в массив Имеется простой пример работы функции логирования:
function work(a) {
  /* ... */ // work - произвольная функция
}
function makeLogging(f, log) {
    return function(){
        log.push(arguments[0]);
        f.apply(this,arguments);
    }
}
var log = [];
work = makeLogging(work, log);
work(1); // 1, добавлено в log
work(5); // 5, добавлено в log
for (var i = 0; i < log.length; i++) {
  alert( 'Лог:' + log[i] ); // "Лог:1", затем "Лог:5"
}

При таком коде все успешно работает, согласно комментариям. Изначально, я попробовал иначе:
function makeLogging(f, log) {
    return function(){
        log=[].slice.call(arguments);// изменения тут
        f.apply(this,arguments);
    }
}

По понятным причинам это не сработало так, как планировалось по заданию, но я ожидал от данного кода, что массив log всегда будет иметь значение аргумента последней вызванной функции, однако, если после вызова work(1) посмотреть содержимое log, он окажется пустым. Я не до конца понимаю почему.

A: Из-за того, что локальной переменной присваивается новое значение, никакого отображения на глобальной переменной нет.
Проблема скорее в неверном именовании, если немного переименовать, станет понятнее:
var log = [];
function makeLogging(f, logArr) {
    return function(){
        logArr=[].slice.call(arguments);// изменения тут
        f.apply(this,arguments);
    }
}

Теперь видно, что изменения происходят именно с локальной переменной, а не глобальной, значение которой проверяется после выполнения функции.
Для решения достаточно менять не всю ссылку, а один элемент, либо делать push/shift, которые меняют сам переданный массив.
Например:

function work(a) {
  console.log('work', a);
}

function makeLogging(f, log) {
  return function() {
    log[0] = [].slice.call(arguments); // изменения тут
    f.apply(this, arguments);
  }
}

var log = [];
work = makeLogging(work, log);
work(1); // 1, добавлено в log
console.log(log)


text:
Q: How to array the numbers like a bowtie shape in c
I'm trying to arrange numbers in a nxn(n is odd number) matrix with bow tie shapes. (like fig.)
Trying to 5x5 matrix set coordinates but no result.
my code:
bowtie {
  int a[5][5] = {{
                     0,
                 },
                 {
                     0,
                 },
                 {
                     0,
                 },
                 {
                     0,
                 },
                 {
                     0,
                 }};

  int i, j;
  int num = 1;

  for (i = 0; i < 5; i++) {
    if (i <= 2)  // y>=0 - coordinate(2d)
    {
      for (j = i; j <= 2; j++)  // x<=0, y>=0 Quadrant 2
      {
        a[i][j] = num;
        num++;
      }
      for (j = 4 - i; j > i; j++)  // Quadrant 1

      {
        a[i][j] = num;
        num++;
      }
    } else                              // y<0
      for (j = 4 - i; j <= 4 - i; j++)  // Quadrant 3
      {
        a[i][j] = num;
        num++;
      }

    for (j = i; j >= i; j++)  // Quadrant 2
    {
      a[i][j] = num;
      num++;
    }
  }

  for (i = 0; i < 5; j++) {
    for (j = 0; j < 5; j++) {
      printf("%d\t", a[i][j]);
    }
    printf("\n");
  }
}

A: The loop

       for (j = 4 - i; j > i; j++)  // Quadrant 1

is wrong because j starts at 4 (i valuing 0) being the last valid index then never stop to grow producing an undefined behavior when you go out of the array
The loop

       for (j = 4 - i; j <= 4 - i; j++)  // Quadrant 3

is strange because the last possible value is the first one, so this is not a loop but just its body executed with j = 4 - i
The loop

    for (j = i; j >= i; j++)  // Quadrant 2

is like the first and makes j incompatible with the array dimensions

A proposal where the size in given in argument and can be odd or even :
#include <stdio.h>

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage %s <size>\n", *argv);
  else {
    int n;

    if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1))
      fprintf(stderr, "invalid size %s\n", argv[1]);
    else {
      int a[n][n];
      int v = 0; /* the value 1.. to put in the cells */
      int empty; /* the empty height */
      int i,j;

      /* first half and may be center */
      empty = -1;

      for (j = 0; j <= (n-1)/2; ++j) {
        empty += 1;

        for (i = 0; i != empty; ++i)
          a[i][j] = a[n - i - 1][j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++][j] = ++v;
      }

      if ((n & 1) == 0)
        empty += 1;

      /* second half */
      for (; j < n; ++j) {
        empty -= 1;

        for (i = 0; i != empty; ++i)
          a[i][j] = a[n - i - 1][j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++][j] = ++v;
      }

      /* show result */
      for (i = 0; i != n; ++i) {
        for (j = 0; j != n; ++j) {
          if (a[i][j] == 0)
            fputs("    ", stdout); /* witdh = 4 compatible with a size up to 43 */
          else
            printf("% 4d", a[i][j]); /* width = 4 compatible with a size up to 43 */
        }
        putchar('\n');
      }
    }
  }

  return 0;
}

Compilation and executions :
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall b.c
pi@raspberrypi:/tmp $ ./a.out 1
   1
pi@raspberrypi:/tmp $ ./a.out 2
   1   3
   2   4
pi@raspberrypi:/tmp $ ./a.out 3
   1       5
   2   4   6
   3       7
pi@raspberrypi:/tmp $ ./a.out 4
   1           9
   2   5   7  10
   3   6   8  11
   4          12
pi@raspberrypi:/tmp $ ./a.out 5
   1              13
   2   6      10  14
   3   7   9  11  15
   4   8      12  16
   5              17
pi@raspberrypi:/tmp $ ./a.out 6
   1                  19
   2   7          15  20
   3   8  11  13  16  21
   4   9  12  14  17  22
   5  10          18  23
   6                  24
pi@raspberrypi:/tmp $ ./a.out 7
   1                      25
   2   8              20  26
   3   9  13      17  21  27
   4  10  14  16  18  22  28
   5  11  15      19  23  29
   6  12              24  30
   7                      31

If you do not accept even size
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage %s <size>\n", *argv);
  else {
    int n;

    if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1) || ((n & 1) == 0))
      fprintf(stderr, "invalid size %s\n", argv[1]);
    else {
      int a[n][n];
      int v = 1; /* the value 1.. to put in the cells */
      int empty; /* the empty height */

      /* first half more center */
      empty = -1;

      for (int j = 0; j <= n/2; ++j) {
        int i;

        empty += 1;

        for (i = 0; i != empty; ++i)
          a[i][j] = a[n - i - 1][j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++][j] = v++;
      }

      /* second half */
      for (int j = n/2 + 1; j < n; ++j) {
        int i;

        empty -= 1;

        for (i = 0; i != empty; ++i)
          a[i][j] = a[n - i - 1][j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++][j] = v++;
      }

      /* show result */
      for (int i = 0; i != n; ++i) {
        for (int j = 0; j != n; ++j) {
          if (a[i][j] == 0)
            fputs("    ", stdout);
          else
            printf("% 4d", a[i][j]);
        }
        putchar('\n');
      }
    }
  }

  return 0;
}

Compilation and executions :
pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -Wall o.c
pi@raspberrypi:/tmp $ ./a.out
Usage ./a.out <size>
pi@raspberrypi:/tmp $ ./a.out 1
   1
pi@raspberrypi:/tmp $ ./a.out 2
invalid size 2
pi@raspberrypi:/tmp $ ./a.out 3
   1       5
   2   4   6
   3       7
pi@raspberrypi:/tmp $ ./a.out 5
   1              13
   2   6      10  14
   3   7   9  11  15
   4   8      12  16
   5              17
pi@raspberrypi:/tmp $ ./a.out 17
   1                                                             145
   2  18                                                     130 146
   3  19  33                                             117 131 147
   4  20  34  46                                     106 118 132 148
   5  21  35  47  57                              97 107 119 133 149
   6  22  36  48  58  66                      90  98 108 120 134 150
   7  23  37  49  59  67  73              85  91  99 109 121 135 151
   8  24  38  50  60  68  74  78      82  86  92 100 110 122 136 152
   9  25  39  51  61  69  75  79  81  83  87  93 101 111 123 137 153
  10  26  40  52  62  70  76  80      84  88  94 102 112 124 138 154
  11  27  41  53  63  71  77              89  95 103 113 125 139 155
  12  28  42  54  64  72                      96 104 114 126 140 156
  13  29  43  55  65                             105 115 127 141 157
  14  30  44  56                                     116 128 142 158
  15  31  45                                             129 143 159
  16  32                                                     144 160
  17                                                             161
pi@raspberrypi:/tmp $

From you remark

'int a[n][n];' has problem.

probably you compiled in C++ rather than C, but it is easy to change that :

*

*replace int a[n][n]; by int * a = malloc(n*n*sizeof(int));

*replace each form a[x][y] by a[(x)*n+y]

*add a free(a); at the end

For instance if I do that on the proposal only accepting odd size :
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char ** argv)
{
  if (argc != 2)
    printf("Usage %s <size>\n", *argv);
  else {
    int n;

    if ((sscanf(argv[1], "%d", &n) != 1) || (n < 1) || ((n & 1) == 0))
      fprintf(stderr, "invalid size %s\n", argv[1]);
    else {
      int * a = malloc(n*n*sizeof(int));
      int v = 1; /* the value 1.. to put in the cells */
      int empty; /* the empty height */

      /* first half more center */
      empty = -1;

      for (int j = 0; j <= n/2; ++j) {
        int i;

        empty += 1;

        for (i = 0; i != empty; ++i)
          a[i*n+j] = a[(n - i - 1)*n+j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++*n+j] = v++;
      }

      /* second half */
      for (int j = n/2 + 1; j < n; ++j) {
        int i;

        empty -= 1;

        for (i = 0; i != empty; ++i)
          a[i*n+j] = a[(n - i - 1)*n+j] = 0;
        for (int k = n - empty*2; k; --k)
          a[i++*n+j] = v++;
      }

      /* show result */
      for (int i = 0; i != n; ++i) {
        for (int j = 0; j != n; ++j) {
          if (a[i*n+j] == 0)
            fputs("    ", stdout);
          else
            printf("% 4d", a[i*n+j]);
        }
        putchar('\n');
      }

      free(a);
    }
  }

  return 0;
}


text:
Q: How to get the text enclosed within a tag, which contains multiple sub-tags, with beautifulsoup? I am trying to scrape a webpage which has the following tag:

            Pick me please.

 Do not pick me please!

I want to scrape the "pick me please" string but don't want to scrape the "Do not pick me please!" string. Any idea how?
EDIT : I would appreciate a more generic solution, where I always wish to get the text under a particular tag, which is not inside any sub-tag

A: You can also use get_text() method.  It returns all the text in a document or beneath a tag, as a single Unicode string. Here i used regular expression re.compile to get the text.
import re
from bs4 import BeautifulSoup
html= """

            Pick me please.

 Do not pick me please!

"""

soup = BeautifulSoup(html, 'lxml')
print(soup.find(text=re.compile("Pick me please.")).strip())

A: Edit
A more "generic" solution to find() the non empty text node in the div:
parent = soup.select_one('div')
parent.find(text=lambda text: text and text.strip(), recursive=False).strip()

To get the text node use previous_sibling and to avoid spaces,... strip() the result.
soup.select_one('div p').previous_sibling.strip()

or use get_text() and strip:
soup.select_one('div').get_text('|', strip=True).split('|')[0]

Minimal example
from bs4 import BeautifulSoup

html = '''

            Pick me please.

 Do not pick me please!

'''
soup = BeautifulSoup(html, 'lxml')

soup.select_one('div p').previous_sibling.strip()

Output

Pick me please.

A: You can search for a
 tag, then call the find_next() method which will return the first match.
soup = BeautifulSoup(html, "html.parser")

print(soup.select_one('div br').find_next(text=True).strip())

Output:
Pick me please.


text:
Q: Is it possible to create red/blue 3d color in LaTeX? Is it possible to create a red/blue 3d effect in LaTeX using a preexisting package? If not, would anybody have any insight into how to go about this?
I am planning to make a beamer presentation on 3d effects, and the ability to have a 3d(even if it is gimickey) would be fun.
Link on red/blue 3d http://en.wikipedia.org/wiki/Anaglyph_3D


text:
Q: Angular 4 Empty Div Element Before a Form Submit In the following HTML content, I have a form. I can submit this form to the server which calls a REST API to return some results. The results that I return are paginated using the infinite scroller.

Search

        <form class="row" name="powerPlantSearchForm" (ngSubmit)="f.valid && searchPowerPlants()" #f="ngForm" novalidate>

            PowerPlant Name
            <input type="text" class="form-control-small" [ngClass]="{ 'has-error': f.submitted && !powerPlantName.valid }" name="powerPlantName" [(ngModel)]="model.powerPlantName" #powerPlantName="ngModel" />

            PowerPlant Type
            <select class="form-control" [(ngModel)]="model.powerPlantType" name="powerPlantType">
              <option value="" disabled>--Select Type--</option>
              <option [ngValue]="powerPlantType" *ngFor="let powerPlantType of powerPlantTypes">
                {{ powerPlantType }}
              </option>
            </select>

            Organization Name
            <input type="text" class="form-control-small" name="powerPlantOrganization" [(ngModel)]="model.powerPlantOrg" #organizationName="ngModel" />

            PowerPlant Active Status
            <select class="form-control" [(ngModel)]="model.powerPlantStatus" name="powerPlantStatus">
              <option value="" disabled>--Select Status--</option>
              <option [ngValue]="powerPlantStatus" *ngFor="let powerPlantStatus of powerPlantStatuses">
                {{ powerPlantStatus }}
              </option>
            </select>

            <button [disabled]="loading" class="btn btn-primary">Search</button>
            <img *ngIf="loading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA==" />
            <button type="button" (click)="resetForm()" class="btn btn-primary">Reset</button>

        </form>

{{powerPlant.powerPlantName}}

Now when the user scrolls after loading the first set of results clicking the search button, the calls are made to the server's REST API to fetch additional results. So far so good!
What I want is the following:
The user could enter some other search criteria and click Search button again. Now this time I want to clear the already populated results and show the newly fetched results. When the user scrolls again, I will fetch additional data for the given search criteria and continue hence forth.
Here is my current Typescript!
import { Component, OnInit } from '@angular/core';

import { PowerPlantService, UserService } from '../shared';
import { User } from '../shared/models/user.model';
import { PowerPlant } from '../shared/models/powerplant.model';
import {PowerPlantSearchParams} from '../shared/models/powerplantsearchparams.model';

@Component({
  selector: 'app-home-page',
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  // Represents the PowerPlantTypes
  powerPlantTypes = ['RampUpType', 'OnOffType'];
  // Represents the status of a PowerPlant
  powerPlantStatuses = ['Active & Disabled', 'Active', 'Disabled'];
  // Represents the search form
  model: any = {};
  // represents the list of PowerPlant data
  powerPlants: PowerPlant[] = [];
  scrollCallback;

  currentPage = 1;

  constructor(private powerPlantService: PowerPlantService) {
    // this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
    // Set the initial values for the drop down fields in the UI
    this.resetForm();

    this.scrollCallback = this.searchPowerPlants.bind(this);
  }

  ngOnInit() {}

  resetForm() {
    this.model.powerPlantOrg = '';
    this.model.powerPlantName = '';
    this.model.powerPlantType = '';
    this.model.powerPlantStatus = '';
  }

  searchPowerPlants() {
    const powerPlantSearchParams = new PowerPlantSearchParams(
      this.model.powerPlantType,
      this.model.powerPlantOrg,
      this.model.powerPlantName,
      this.model.powerPlantStatus);
/*
    this.powerPlantService.searchPowerPlants(powerPlantSearchParams).subscribe(result => {
      this.powerPlants = <PowerPlant[]> result;
    }); */
    // this.scrollCallback = this.searchPowerPlants.bind(this);
    // const something = this.powerPlantService.searchPowerPlants(powerPlantSearchParams, this.currentPage);
    return this.powerPlantService.searchPowerPlants(powerPlantSearchParams, this.currentPage).do(this.processData);
  }

  private processData = (newPowerPlants) => {
    alert(newPowerPlants);
    this.currentPage++;
    // this.powerPlants = this.powerPlants.concat(newPowerPlants.json());
    this.powerPlants = this.powerPlants.concat(newPowerPlants);
  }

  allPowerPlants(onlyActive: boolean = false, page: number = 1): void {
    this.powerPlantService.allPowerPlants(onlyActive, page).subscribe(result => {
      this.powerPlants = <PowerPlant[]> result;
    });
  }
}

Any suggestions on how to approach this?
EDIT: I tried a different approach, but still could not solve it. What I did is to add another method in the onClick of the search button like this:

And in my Typescript, I empty this array (everything else in my Typescript stays the same):
emptyAndBindNew() {
    this.powerPlants = [];
    alert('In empty method');
  }

With this approach I get an error:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]'.
    at viewDebugError (core.es5.js:8421)
    at expressionChangedAfterItHasBeenCheckedError (core.es5.js:8399)
    at checkBindingNoChanges (core.es5.js:8563)
    at checkNoChangesNodeInline (core.es5.js:12430)
    at checkNoChangesNode (core.es5.js:12404)
    at debugCheckNoChangesNode (core.es5.js:13181)
    at debugCheckDirectivesFn (core.es5.js:13083)
    at Object.View_HomeComponent_0._co [as updateDirectives] (HomeComponent.html:45)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13065)
    at checkNoChangesView (core.es5.js:12224)


text:
Q: Is the locatation of channel file location specific? Does the channel file need to be in the root of the site or may it reside in the directory that contains my canvas app pages?

A: It can reside in the directory as long as you set the location correctly when you fb.init
http://developers.facebook.com/docs/reference/javascript/FB.init/


text:
Q: Web-Service retornando máxima cota excedida. Como resolver? Estou consumindo um web-service de terceiros.
Quando recebo o retorno do serviço a seguinte mensagem é exibida:

A cota máxima de tamanho de mensagens de entrada (65536) foi excedida

Já pesquisei em fóruns por uma solução, mas não obtive sucesso com nenhum...
Deixo abaixo meu app.config para verificação.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <diagnostics>
            <messageLogging maxSizeOfMessageToLog="2147483647" />
        </diagnostics>
        <bindings>
            <basicHttpBinding>
                <binding name="WorkflowWebServiceSoap" maxBufferPoolSize="2147483647"
                    maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
            </basicHttpBinding>
            <customBinding>
                <binding name="WorkflowWebServiceSoap12">
                    <textMessageEncoding messageVersion="Soap12" />
                    <httpTransport maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647"
                        maxBufferSize="2147483647" />
                </binding>
            </customBinding>
        </bindings>
        <client>
            <endpoint address="URL DO WEB SERVICE"
                binding="customBinding" bindingConfiguration="WorkflowWebServiceSoap12"
                contract="ServiceReference1.WorkflowWebServiceSoap" name="WorkflowWebServiceSoap12" />
        </client>
    </system.serviceModel>
</configuration>

Alguém teria alguma proposta de solução?

A: Tive erro desse, porém o problema estava no lado client, e foi só alterar o security mode do basicHttpBinding:
<basicHttpBinding>
    <binding name="WServicoSoapBinding">
        <security mode="Transport" />
    </binding>
</basicHttpBinding>

Também pode ser feito ao instanciar o objeto:
objWS = new NS.WServicoClient(new BasicHttpBinding(BasicHttpSecurityMode.Transport), new EndpointAddress(this.UrlWS));


text:
Q: Python last match How do I grab the "california" part in the following string?
http://states.com/_states/united_states/50/california

I'm trying the following but don't' know how to match the last /.
match = re.search(r'\/(.*)$', state_url)

A: Are you sure you need regular expressions for this? What about the following?
In [66]: url = 'http://states.com/_states/united_states/50/california'

In [67]: url.split('/')[-1]
Out[67]: 'california'

But this depends on whether you always want to extract the last word in a URL, of course. I just wanted to mention it.

A: Use
r'[^/]*$'

which matches any number of characters except '/' before the end of input
or ideally, for a URL,
r'[^/#?]*(?:$|[#?])'

which matches any number of characters that are non-special in a URL path part up to the end of input ($) or the end of the path part [#?].  The (?:...) is just a parenthetical group that does not capture the contents.

Btw, appendix B of RFC 3986 is a great reference for parsing URIs with regular expressions.

Appendix B.  Parsing a URI Reference with a Regular Expression
As the "first-match-wins" algorithm is identical to the "greedy"
    disambiguation method used by POSIX regular expressions, it is
    natural and commonplace to use a regular expression for parsing the
    potential five components of a URI reference.
The following line is the regular expression for breaking-down a
    well-formed URI reference into its components.
 ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
  12            3  4          5       6  7        8 9

...


text:
Q: How does g++ align memory to make sure the alignment starts at the beginning of a cacheline? I read that in g++ we can do :
struct foo {
    int a, b, c;
} __attribute__((__aligned__(64)));

so that the struct foo is of size 64 --- which is normally the size of a cache line. when we need to access this cache line, cpu can load foo in one go.
Does this mean that CPU can load foo from L2 at any memory address --- not necessarily a round number of 64?
imaging that foo 's address in memory is something like 0xFFFF3, does CPU need to read TWO cache lines to load foo?
Can anybody clarify this for me?
PS: I am using g++ 6.2 on CentOS 64bit

A: Aligned is related with where start the address of the structure in memory. If the size of your structure is less or equals to 64 bytes, then you are right and your structure will fit in one line cache, but if the structure is bigger than 64 bytes that is always false.
Aligned is only related with where will start a local or global variable of that type. When you are writing algorithms that try to explode the power of the processor is good optimise the data access aligned to 64 bytes so that you can process 64 continuous bytes without any cache fault. By the way the optimiser of the compiler create more optimal code when data are aligned to 64 bytes.
A quick test is to create a small program, and generate the assembler code with aligned and without aligned, and compare the assembler that you get. (A small loop that access local vectors for example), enabling the optimiser (-O2 or -O3).
PS: When using the heap, you can do it by yourself allocating
struct foo *myFoo = (malloc(size(struct foo)+15) + 15) & (~ 0x0f);

A: There seems to be two questions masked as one. I will try to answer them.
First, alignment question. Generally speaking, C++ compiler knows nothing (or pretends to know nothing) of the cache lines and such. Instead, it simply makes sure that all objects of this type are aligned to 64 byte boundaries (provided they are natively smaller or equal in size to 64). This is where compiler job is done.
Now, we need to focus on CPU behavior. Since cache line size is 64 bytes, when the object is aligned on 64 byte boundary, we are certain that the whole object is going to be in the cache when we load it. As a result, access to object members is guaranteed to be served by L1 cache rather than more expensive ways (L2, for example).
Since L2 is a much bigger cache, there is no reason to try to align code to adhere to L2 boundaries.


text:
Q: Unknown argument on field of type "Mutation" I am working on laravel, magento and graphql. I am trying use mutation to grab a data and send to api. But
I am getting below errors -
{#321
  +"errors": array:8 [
    0 => {#301
      +"message": "Unknown argument "card_num" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#304
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#307
          +"line": 2
          +"column": 25
        }
      ]
    }
    1 => {#305
      +"message": "Unknown argument "nme_card" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#259
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#302
          +"line": 2
          +"column": 46
        }
      ]
    }
    2 => {#292
      +"message": "Unknown argument "ex_mnth" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#291
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#294
          +"line": 2
          +"column": 67
        }
      ]
    }
    3 => {#306
      +"message": "Unknown argument "ex_yr" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#299
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#308
          +"line": 2
          +"column": 86
        }
      ]
    }
    4 => {#309
      +"message": "Unknown argument "cvc2" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#310
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#311
          +"line": 2
          +"column": 101
        }
      ]
    }
    5 => {#312
      +"message": "Unknown argument "action" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#313
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#314
          +"line": 2
          +"column": 114
        }
      ]
    }
    6 => {#315
      +"message": "Unknown argument "dps_px_pay" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#316
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#317
          +"line": 2
          +"column": 131
        }
      ]
    }
    7 => {#318
      +"message": "Unknown argument "session_id" on field "pxFusionPostRequest" of type "Mutation"."
      +"extensions": {#319
        +"category": "graphql"
      }
      +"locations": array:1 [
        0 => {#320
          +"line": 2
          +"column": 156
        }
      ]
    }
  ]
}

Here is my graphql in magento -
type Mutation {

    pxFusionPostRequest(input: PxFusionRequestData): String @resolver(class: "Limesharp\\Windcave\\Model\\Resolver\\PxFusionPostRequest")

}

input PxFusionRequestData {
    card_num: String!
    nme_card: String!
    ex_mnth: String!
    ex_yr: String!
    cvc2: String!
    action: String!
    dps_px_pay: String!
    session_id: String!
}

And I calling it using laravel like -
public function pxFusionPostRequest($input){
        try {
            $response = $this->sendGraphQL('post', 'queries/payment/px-fusion-post-request.graphql', [
                'card_num'      =>  $input['cardNum'],
                'nme_card'      =>  $input['nmeCard'],
                'ex_mnth'       =>  $input['exMnth'],
                'ex_yr'         =>  $input['exYr'],
                'cvc2'          =>  $input['cvc2'],
                'action'        =>  $input['action'],
                'dps_px_pay'    =>  $input['dpsPxPay'],
                'session_id'    =>  $input['sessionId']
            ]);

            dd($response);

            if ($response->data->pxFusionPostRequest == null) {
                throw new GraphQlLogicException($response->errors[0]->message);
            }

            $data = $response->data->pxFusionPostRequest;
            return response()->json($data);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()])->setStatusCode(400);
        }
    }

And this px-fusion-post-request.graphql
mutation ($card_num: String!, $nme_card: String!, $ex_mnth: String!, $ex_yr: String!, $cvc2: String!, $action: String!, $dps_px_pay: String!, $session_id: String!) {
    pxFusionPostRequest(card_num: $card_num, nme_card: $nme_card, ex_mnth: $ex_mnth, ex_yr: $ex_yr, cvc2: $cvc2, action: $action, dps_px_pay: $dps_px_pay, session_id: $session_id)
}

Basically, I am passing user card details to magento and creating a post request. But, I am not sure why it is saying unknown argument as I am passing it.

A: Your mutation is expecting one argument with name input and type PxFusionRequestData, but you are trying to pass all the subfields as parameters. Try this:
mutation ($input: PxFusionRequestData) {
    pxFusionPostRequest(input: $input)
}


text:
Q: Having identified a variable significant in a count glm, how does one determine if it is associated with higher or lower count? I have a dataset of counts of four different metadata factors associated with a gene and two experimental groups, FGT and free, with 52 and 40 unique genes respectively. The first 100 rows can be found here: https://pastebin.com/PAG5pCDh (I can provide more)
Having performed a poisson distributed glm on count data and identifying the variable origin as a significant predictor, as originfree is significant (I think I am under standing that correctly?), how do I determine if origin free is associated with a  higher or lower count.
A truncated output of coefficients for the glm looks like this:
Coefficients:
                       Estimate Std. Error z value Pr(>|z|)
(Intercept)          -7.100e-01  5.827e-01  -1.218 0.223062
originfree           -2.921e-01  8.830e-02  -3.308 0.000939 ***
variableDuplication   1.427e-01  1.116e-01   1.279 0.201013
variableKnown_target -1.609e+00  2.000e-01  -8.047 8.47e-16 ***
variablePhylogeny     1.310e-01  1.119e-01   1.171 0.241491
geneGrpE              1.792e+00  6.236e-01   2.873 0.004063 **
genePGK              -4.455e-15  8.165e-01   0.000 1.000000
geneRibosomal_S14     6.931e-01  7.071e-01   0.980 0.326959
geneSHMT              2.079e+00  6.124e-01   3.396 0.000684 ***
geneTIGR00009         9.758e-15  8.165e-01   0.000 1.000000
geneTIGR00057         6.931e-01  7.071e-01   0.980 0.326959
geneTIGR00069        -6.149e-15  8.165e-01   0.000 1.000000
geneTIGR00079         1.386e+00  6.455e-01   2.148 0.031743 *
geneTIGR00105         1.386e+00  6.455e-01   2.148 0.031743 *

I see that originfree is significant, which I understand to mean it the fact of something being originfree or not significantly affects the models ability to predict count )please correct me if I am wrong)
Now how do I find out if originfree is associated with an increase or decrease in the count of the four metadata factors? Would I have to run separate glms on subset dataframe for each metadata factor in order to work this out?
My alternative hypothesis is that it would lead to a decrease

A: You exponentiate the estimation of the coefficient and this gives you a multiplicative factor by which you can see the effect of the coefficient.
In R this can be done by:
exp(estimation)

As highlighted by @Whuber and directed to an answer by @Stephen G and also a very good answer can be found here


text:
Q: Detect Swipe without affecting click event I did some researches on other posts related to swipe functionality and found a useful function however it also affects click events.
Here is the link I found that is swipe function useful:
http://www.javascriptkit.com/javatutors/touchevents2.shtml
Is there a way to tweak it and to make click event work.
Here is the sample fiddle http://jsfiddle.net/8rscLo1z/4/ (P.S. Use toggle device toolbar in chrome to work)
Swipe trigger:
var el = document.getElementById('testing_area');
swipedetect(el, function(swipedir){
    // swipedir contains either "none", "left", "right", "top", or "down"
    if (swipedir =='left'){
        $('#testing_area').html('Swipe LEFT detected');
    } else if (swipedir == 'right'){
        $('#testing_area').html('Swipe RIGHT detected');
    } else {
        $('#testing_area').html('Swipe UNRECOGNIZED');
    }
});

Click event
$('#testing_area').click(function(){
    alert('test click');
});

A: On your touchend event listener, var distX pertains to the distance travelled by the touch (swipe). You can add additional if condition wherein it will check if distX is equal to 0.
Update you code from:
touchsurface.addEventListener('touchend', function(e){
        var touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX
        distY = touchobj.pageY - startY
        elapsedTime = new Date().getTime() - startTime
        if (elapsedTime <= allowedTime){
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
                swipedir = (distX < 0)? 'left' : 'right'
            }
            else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
                swipedir = (distY < 0)? 'up' : 'down'
            }
        }
        handleswipe(swipedir)
        e.preventDefault()
    }, false)

Into this
touchsurface.addEventListener('touchend', function(e){
        var touchobj = e.changedTouches[0]
        distX = touchobj.pageX - startX
        distY = touchobj.pageY - startY
        elapsedTime = new Date().getTime() - startTime
        if(distX == 0){
            alert('test click'); //this is where click event is detected
        } else if (elapsedTime <= allowedTime){
            if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
                swipedir = (distX < 0)? 'left' : 'right'
            }
            else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
                swipedir = (distY < 0)? 'up' : '
            }
        }
        handleswipe(swipedir)
        e.preventDefault()
    }, false)

Here is the working fiddle: http://jsfiddle.net/8rscLo1z/14/show


text:
Q: In Apache Spark Sql Context how to delete rows with same ID but different row values In Spark I have DataFrame like this
ID  AGE INFO
2    21  123
2    21  245
3    24  125
3    24  55
3    24  256
4    26  245
5    21  22

As you can see first two rows share same ID "2" but have different INFO. Same thing with row3,4 and 5.(They share ID 3 but contain different INFO) What I want is only keep the row with Unique ID and smallest INFO number. So the output should be like this
ID  AGE INFO
2    21  123
3    24  55
4    26  245
5    21  22

I think it can be easier to do it with SQL Context, however, if you have solution to do this directly with DataFrame, it will also be helpful! Thanks! (I asked this as a SQl question first, and someone suggest me to ask it with Spark tag. So I modify my question and hope it will be a more clear one) Thanks

A: You can simply group and aggregate:
import org.apache.spark.sql.functions.min

val df = sc.parallelize(Seq(
    (2, 21,  123), (2, 21,  245), (3, 24,  125),
    (3, 24,  55), (3, 24,  256),(4, 26,  245), (5, 21,  22)
)).toDF("ID", "AGE", "INFO")

val transformed1 = df.groupBy($"ID", $"AGE").agg(min($"INFO").alias("INFO"))

Using raw SQL:
df.registerTempTable("df")
val transformed2 = sqlContext.sql(
  "SELECT id, age, min(info) info FROM df GROUP BY id, age")


text:
Q: Dias úteis e API Java 8, como verificar? Como verificar se um dia é útil utilizando a API do Java 8?
É possível verificar se é sábado ou domingo, mas como verificar por exemplo feriado como 7 de Setembro (Independência do Brasil) ou Sexta-Feira Santa?
int ano = 2014;
int mes = 5;
YearMonth anoMes = YearMonth.of(ano, mes);

List<LocalDate> listaDosDiasUteisDoMes = new ArrayList<>();

for(int dia=1; dia <= anoMes.lengthOfMonth(); dia++){
  LocalDate data = anoMes.atDay(dia);

  if(!data.getDayOfWeek().equals(DayOfWeek.SATURDAY) &&
    !data.getDayOfWeek().equals(DayOfWeek.SUNDAY)){

      listaDosDiasUteisDoMes.add(data);
  }
}

A: Para isso você precisa definir a sua própria lista de feriados. Existem várias APIs que fornecem este tipo de informação, como a Jollyday (tem um exemplo no final), e várias outras listadas neste link.
Caso você não queira usar uma API, pode ter seu próprio cadastro também (e neste caso, é algo que você terá que fazer manualmente).
Outro problema dos feriados é que nem todos possuem datas fixas (como a Páscoa, Carnaval, etc, que todo ano caem em datas diferentes), e devem ser calculados de acordo com o ano. Além disso, há os feriados nacionais, estaduais e municipais, e você deve decidir se vai incluí-los ou não na sua lista.
De qualquer forma, independente da solução escolhida (usar uma API externa, cadastrar manualmente, incluir somente feriados nacionais, etc), basta que você guarde todos os feriados em um java.util.Set, e em seguida verifique se a data está no Set (usando o método contains), mais ou menos assim:
Set<LocalDate> feriados = // feriados, ver mais abaixo como montar este Set
for (int dia = 1; dia <= anoMes.lengthOfMonth(); dia++) {
    LocalDate data = anoMes.atDay(dia);

    if (data.getDayOfWeek() != DayOfWeek.SATURDAY
        && data.getDayOfWeek() != DayOfWeek.SUNDAY
        && !feriados.contains(data)) {
        listaDosDiasUteisDoMes.add(data);
    }
}

Como java.time.DayOfWeek é um enum, posso compará-los usando == e != (não precisa usar equals).

Para montar o Set com os feriados, eu sugiro separar em 2 métodos: um para os feriados fixos (que é mais fácil, já que sempre caem no mesmo dia todo ano) e outro para os feriados móveis.
Eu sugiro que você passe o ano como parâmetro para estes métodos, assim você consegue construir uma lista de java.time.LocalDate, que é o que você precisa.
// feriados que acontecem todo ano na mesma data, gerar lista para o ano específico
public Set<LocalDate> getFeriadosFixos(int year) {
    Set<LocalDate> dates = new HashSet<>();

    // 7 de setembro
    dates.add(LocalDate.of(year, 9, 7));
    // natal
    dates.add(LocalDate.of(year, 12, 25));
    // ... adicione todos os outros

    return dates;
}

Este método não considera as "emendas" de feriados (se cai na terça, emenda a segunda, então esses dois dias não são úteis). Se quiser, basta verificar se o feriado é uma terça ou quinta (comparando o DayOfWeek):
// 7 de setembro
LocalDate seteSetembro = LocalDate.of(year, 9, 7);
dates.add(seteSetembro);
// se cai na terça, inclui a segunda ("emenda" de feriado)
if (seteSetembro.getDayOfWeek() == DayOfWeek.TUESDAY) {
    dates.add(seteSetembro.minusDays(1));
}
// se cai na quinta, inclui a sexta ("emenda" de feriado)
if (seteSetembro.getDayOfWeek() == DayOfWeek.THURSDAY) {
    dates.add(seteSetembro.plusDays(1));
}

Faça isso para todos os feriados que podem ser "emendados".
Para os feriados móveis, há uma fórmula para calculá-los (procure no Google e encontrará vários sites explicando). Vou usar uma que achei:
// calcula páscoa, carnaval, corpus christi e sexta-feira santa
public Set<LocalDate> getFeriadosMoveis(int year) {
    Set<LocalDate> dates = new HashSet<>();

    LocalDate pascoa;
    LocalDate carnaval;
    LocalDate corpusChristi;
    LocalDate sextaFeiraSanta;

    int a = year % 19;
    int b = year / 100;
    int c = year % 100;
    int d = b / 4;
    int e = b % 4;
    int f = (b + 8) / 25;
    int g = (b - f + 1) / 3;
    int h = (19 * a + b - d - g + 15) % 30;
    int i = c / 4;
    int k = c % 4;
    int l = (32 + 2 * e + 2 * i - h - k) % 7;
    int m = (a + 11 * h + 22 * l) / 451;
    int month = (h + l - 7 * m + 114) / 31;
    int day = ((h + l - 7 * m + 114) % 31) + 1;

    pascoa = LocalDate.of(year, month, day);

    // Carnaval 47 dias antes da pascoa (sempre cai na terça)
    carnaval = pascoa.minusDays(47);

    // CorpusChristi 60 dias apos a pascoa
    corpusChristi = pascoa.plusDays(60);

    sextaFeiraSanta = pascoa.minusDays(2);

    // páscoa cai sempre no domingo, entao não precisaria adicionar como feriado
    // dates.add(pascoa);

    // carnaval: adicionar um dia antes e depois (emenda de segunda e quarta-feira de cinzas)
    dates.add(carnaval);
    dates.add(carnaval.minusDays(1)); // emenda a segunda-feira
    dates.add(carnaval.plusDays(1)); // quarta-feira de cinzas

    // corpus christi, emendar (adicionar a sexta)
    dates.add(corpusChristi);
    // if apenas para confirmar se é quinta-feira
    if (corpusChristi.getDayOfWeek() == DayOfWeek.THURSDAY) {
        dates.add(corpusChristi.plusDays(1)); // adicionar a sexta-feira
    }

    dates.add(sextaFeiraSanta);

    return dates;
}

Repare que incluí também as "emendas" de feriados. Se não quiser, basta remover as respectivas linhas.
Para criar o Set com todos os feriados, basta usar os dois métodos acima e juntar tudo em um único Set:
Set<LocalDate> feriados = new HashSet<>();
feriados.addAll(getFeriadosFixos(year));
feriados.addAll(getFeriadosMoveis(year));

O parâmetro year pode ser o ano que você está usando (anoMes.getYear()), por exemplo.

Apenas como complemento, é possível encapsular a lógica de verificação em um java.time.temporal.TemporalQuery. A diferença é que esta interface trabalha com um java.time.temporal.TemporalAccessor (ao invés de um tipo específico como LocalDate), então o código para verificar o dia da semana é um pouco diferente:
public class VerificaDiaUtil implements TemporalQuery<Boolean> {

    private Set<LocalDate> feriados = new HashSet<>();

    public VerificaDiaUtil() {
        this.feriados = // constrói a lista de feriados
    }

    @Override
    public Boolean queryFrom(TemporalAccessor temporal) {
        // obter o dia da semana
        DayOfWeek dow = DayOfWeek.from(temporal);
        return dow != DayOfWeek.SATURDAY && dow != DayOfWeek.SUNDAY
               // extrair o LocalDate e verificar se está no Set de feriados
               && !feriados.contains(LocalDate.from(temporal));
    }
}

Com isso a classe VerificaDiaUtil fica responsável por manter a lista de feriados. Se quiser, você pode alterar o construtor para receber o ano como parâmetro (e aí ela constrói apenas os feriados daquele ano), ou então ela já carrega os feriados de vários anos de uma só vez. Fica a seu critério.
Para usar esta classe, basta usar o método query de LocalDate:
VerificaDiaUtil diaUtil = new VerificaDiaUtil();
for (int dia = 1; dia <= anoMes.lengthOfMonth(); dia++) {
    LocalDate data = anoMes.atDay(dia);
    if (data.query(diaUtil)) {
        listaDosDiasUteisDoMes.add(data);
    }
}

Como TemporalQuery recebe um java.time.temporal.TemporalAccessor, ele funciona com outras classes também (desde que estas tenham dia, mês e ano - e consequentemente, um dia da semana), como LocalDateTime ou ZonedDateTime. Se você passar uma classe que não possui dia da semana (como LocalTime, por exemplo, que só possui as horas), este código lancará uma exceção.

Apenas para citar um exemplo com uma API, segue uma solução com Jollyday. Fica bem similar ao código acima, a única diferença é que você não precisa mais calcular os feriados manualmente, podendo delegar esta tarefa para a API:
import de.jollyday.HolidayCalendar;
import de.jollyday.HolidayManager;
import de.jollyday.ManagerParameters;

public class VerificaDiaUtil implements TemporalQuery<Boolean> {
    private HolidayManager manager;
    public VerificaDiaUtil() {
        // usa os feriados do Jollyday, em vez de calcular manualmente
        this.manager = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.BRAZIL));
    }
    @Override
    public Boolean queryFrom(TemporalAccessor temporal) {
        // obter o dia da semana
        DayOfWeek dow = DayOfWeek.from(temporal);
        return dow != DayOfWeek.SATURDAY && dow != DayOfWeek.SUNDAY
                // extrair o LocalDate e verificar se é feriado
                && !this.manager.isHoliday(LocalDate.from(temporal));
    }
}

// A forma de usar é a mesma do código anterior
VerificaDiaUtil diaUtil = new VerificaDiaUtil();
for (int dia = 1; dia <= anoMes.lengthOfMonth(); dia++) {
    LocalDate data = anoMes.atDay(dia);
    if (data.query(diaUtil)) {
        listaDosDiasUteisDoMes.add(data);
    }
}

No caso do Jollyday, ainda dá para verificar feriados estaduais, municipais, etc, ou ainda criar sua própria lista. Para mais detalhes, consulte a documentação.

A: Você pode utilizar a Google Calendar API da seguinte forma proposta pela documentação:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class CalendarQuickstart {
    private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
    * Global instance of the scopes required by this quickstart.
    * If modifying these scopes, delete your previously saved credentials/ folder.
    */
    private static final List<String> SCOPES = Collections.singletonList(CalendarScopes.CALENDAR_READONLY);
    private static final String CREDENTIALS_FILE_PATH = "credentials.json";

    /**
    * Creates an authorized Credential object.
    * @param HTTP_TRANSPORT The network HTTP Transport.
    * @return An authorized Credential object.
    * @throws IOException If the credentials.json file cannot be found.
    */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // Load client secrets.
        InputStream in = CalendarQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
        return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();

        // List the next 10 events from the primary calendar.
        DateTime now = new DateTime(System.currentTimeMillis());
        Events events = service.events().list("primary")
                .setMaxResults(10)
                .setTimeMin(now)
                .setOrderBy("startTime")
                .setSingleEvents(true)
                .execute();
        List<Event> items = events.getItems();
        if (items.isEmpty()) {
            System.out.println("No upcoming events found.");
        } else {
            System.out.println("Upcoming events");
            for (Event event : items) {
                DateTime start = event.getStart().getDateTime();
                if (start == null) {
                    start = event.getStart().getDate();
                }
                System.out.printf("%s (%s)\n", event.getSummary(), start);
            }
        }
    }
}

A: No meu caso eu tenho uma tabela de feriados e com ela eu utilizado as rotinas abaixo:
private LocalDate calculaDia(LocalDate data, int diaMesSemanaAno, boolean trataFinalDeSemana, boolean trataFeriado) {
    int maisOuMenosUm = 1;
    // trata quando quiser subtrair uma data
    if (diaMesSemanaAno < 0) {
        diaMesSemanaAno = diaMesSemanaAno * -1;
        maisOuMenosUm = -1;
    }
    while (diaMesSemanaAno > 0) {
        data = data.plusDays(maisOuMenosUm);
        // quando for final de semana
        if (trataFinalDeSemana) {
            // verifica se e final de semana...
            data = eFinalSemana(data, maisOuMenosUm);
        }

        // quando tem feriado
        if (trataFeriado) {
            data = eFeriado(data, maisOuMenosUm);
        }

        diaMesSemanaAno--;
    }
    return data;
}

private LocalDate eFeriado(LocalDate data, int somaSubtraiUm) {
    String feriado = DateUtil.getData(data, DateUtil.DATA_BR_PADRAO_BARRAS);
    TwebferiadosTO twebferiadosTO = new TwebferiadosTO();
    twebferiadosTO.setDataFormatada(feriado);
    twebferiadosTO = consultar(twebferiadosTO);
    if (twebferiadosTO != null) {
        data = data.plusDays(somaSubtraiUm);
        data = eFeriado(data, somaSubtraiUm);
        //verifica se nao e final de semana
        data = eFinalSemana(data, somaSubtraiUm);
    }
    return data;
}

private LocalDate eFinalSemana(LocalDate data, int somaSubtraiUm) {
    if (data.getDayOfWeek() == DayOfWeek.SATURDAY
            || data.getDayOfWeek() == DayOfWeek.SUNDAY) {
        data = data.plusDays(somaSubtraiUm);
        data = eFinalSemana(data, somaSubtraiUm);
    }
    return data;
}

*

*Valida feriado em sequencia. Ex. Carnaval

*Valida feriado que cai no final de semana


text:
Q: The Hammerpede scene -- what was the purpose of going into Millburn's throat? Of course, knowing what we do now of facehuggers and also the Engineer and the giant octopus, we might assume it intended to impregnate Millburn but as far as I know, it just kills him while his buddy gets mutated. Is there a deleted scene that indicates or does the novelization indicate something further happens to Millburn? It is not clear to me what causes the other guy's mutation since all that happens to him is that he is sprayed with acid -- there does not seem to be direct contact with the hammerpede in his case.

A: This early draft of the script indicates that Milburn was simply killed by the Hammerpede (or centipede, as it's referred to in this version of the script). There's no indication that there was any other reason for the creature going inside him.

INT. CATACOMBS - INSECT CHAMBER
Milburn writhes on the ground, heels drumming frantically against the deck. Excruciating screams.
Fifield kneels over him, helplessly pulling at the tail of the centipede - which has all but vanished into Milburn's suit. A trickle of scarlet from the hole.
Fifield is delirious with horror. He clutches at the centipede in vain. It slips through his gloves.
Milburn claws at Fifield, wild-eyed.
MILBURN: Cut off my arm. Cut off my -
He convulses. Spits blood. The head of the centipede emerges between his teeth. He seizes. Choking and dying.
FIFIELD: Jesus Christ!
He leaps up. Backs away. Runs into the dark.
Prometheus script (early draft)

When the rest of the crew discovers Milburn's body, it's explicitly stated that he's dead.

CATACOMBS - MILBURN'S RESTING PLACE
Janek and Stillwell stand aghast. Their flashlights illuminate a hideous sight:
Milburn lies dead on the deck. His body contorted in agony. His head inside his helmet is gnawed down to the bone.
Prometheus script (early draft)

As for Fifield, in this version of the script, he doesn't get sprayed by the centipede's blood, and runs off instead. He then stops to rest in another room, and ends up getting bitten on the cheek by a flying insect, which was presumably mutated by the black goo. The bite transmits foreign DNA into his bloodstream, which causes his transformation.

INT. CATACOMBS - LONELY PASSAGE - NIGHT
Fifield stumbles along. Exhausted. Pouring sweat inside his suit. He is hopelessly lost. He slams into a resinous structure that topples to the floor. Things break.
He whips his light around in jittery paranoia. Taps at his comm controls, getting only static.
In Fifield's headlamp beam, the blackness is filling with motes of light. A blizzard of tiny flying insects.
SCARABS.
FIFIELD: Fifield to Magellan. Come on, come on. Anybody, seriously! God damn it!
Scarabs flit through the darkness around him. They alight on his shoulders. Crawl over his visor. Obscuring his vision.
FIFIELD: Get off!
He swats at his visor, killing some. The crushed insects produce acid that eats into the plexiglass in seconds.
FIFIELD: Shit.
He twists, craning with his flashlight to inspect himself. Brushes scarabs away right and left.
Acid opens a hole in his visor. Scarabs are inside. Buzzing around his head. Fifield freaks out, clawing at his helmet.
A scarab bites his cheek.
FLASH ON:
The microscopic world - as strange DNA invades Fifield's bloodstream. Virulent strands of protein attack the native DNA, transforming...
FIFIELD
As his pupils dilate, breath hissing into his nostrils. His expanding body stiffens as if shocked by a powerful electric current. He screams. Falls, convulsing.
Prometheus script (early draft)

Within the actual film, Fifield instead falls face first into a puddle of the black goo, right after his helmet is sprayed with the acidic blood from the Hammerpede. He then lifts his head up, and the front part of his helmet collapses onto his face with the black goo all over it.


text:
Q: UITabBarController to UIViewController with inner UITableView I apologize in advance for being a total noob with this question, but at least I'm trying right?
Here's my current setup. I have a storyboard setup with the following
UITabBarController -> UIViewController -> TableView -> Cell
I have a Class that is of type UITableViewController setup to feed some static data to the TableView. What I'm getting hung up on is how I can hook up the first view of the UITabBarController to point to the UIViewController that then pulls in the data of the TableViews and it's sells.
Here is the tutorial I've been following. My code is basically the same except my storyboard is different(my way is explained above).
http://www.appcoda.com/ios-programming-customize-uitableview-storyboard/
Any ideas on what I'm doing wrong or need to do in order to hook this up correct?! All help is greatly appreciated!!!

A: Create the following view hierarchy
UITabBarController - > UINavigationController - > UITableviewcontroller -> UIViewController
create tabbar as rootview for application then create navigation controller with tableview as topviewcontroller for that navigationController and then add that navigation controller as view to the tabbar. now to load data in view on selection of cell in tabview use
didSelectRowAtIndexPath method of tableview controller  to call view using push segue with data which you want to show on that view.
// Try this one it will work.


text:
Q: how to split one column into multiple variable columns in parse.com I have the following records in my data base
fields:   brand |model |attributes
          ----------------------------
record 1) apple |iPhone|6s space grey sprint
record 2) audi  | a6   |quattro coupe

How can I store the attributes into different column names, with  version/color/carrier columns for the first record and engine/type as the different columns for second record. The table should have 5 total columns for 1st record and 4 columns for the second record.
How do I achieve this? Should I split the table? If there are million products and each have varied length attributes then the number of columns in the table will be long. Whats the efficient way of doing this?

A: You can store the related attributes in a second table.

record|attribute|value
------+---------+-----
1     |version  |6s
1     |color    |space grey
1     |carrier  |sprint
2     |engine   |quattro
2     |type     |coupe

This would allow for an item to have any number of (optional) attributes.


text:
Q: Choosing ArcMap Network Analyst Tool I have two polygon layers, and a roads layer that I've made into a network dataset. My goal is to find the closest polygon in one layer to each polygon in the other layer, but instead of just calculating the distance to find the closest I need to use the roads ND to see which of the polygons from the first layer is closest to the polygon from the second layer.
What tool can I use to do this?
I've assumed I can do it with something in the Network Analyst toolset, but I can't figure out what.
From the picture, I want to find the closest green polygon to both of the red polygons using the yellow roads.
I'm still relatively new to this, in my first course on the subject.

Edit: I received this solution on GeoNet, the Esri forum:

*

*Convert the vertices of your polygon features to points (Feature Vertices To Points-Data Management toolbox).

*Do this twice: once for the green polygons and once for the red polygons

*Calculate an OD cost matrix with the Network Analyst (OD cost matrix analysis layer-ArcGIS Pro).

*Load the vertices from the red polygons as origins and the vertices from the green polygons as destinations (or vice-versa).

*Use the OD cost matrix to find out the shortest path between any vertex of a green polygon and any vertex of a red polygon.

*Use these vertices geographic positions to determine to which green or red polygon the vertices belong.

A: I think an issue you may run into is that polygons can not be used as Facilities when using Network Analyst. I came across this post which is similar to the issue you are having.
https://community.esri.com/thread/28048
From what I read, it seems like an alternative process would be to use the "Feature Vertices To Points" tool to create a series of individual points to replace your polygons.  From there you can use the points as Facilities in order to run the "New Closest Facility" tool through Network Analyst. This would give you more accurate results than just using a centroid point of each polygon.


text:
Q: Create ID with data of other fields I'm new to mongodb, and I'm using mongoose to validate and order the data (I'm open to change it to MySQL if this doesn't work).
The app will be an e-shop, to buy merchandising related to movies, games, ext.
My schema is as follows:
var productSchema = {
    id: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    img: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    stock: {
        type: Number,
        required: true
    },
    category: {
        object: {
            type: String,
            required: true
        },
        group: {
            type: String,
            required: true
        },
        name: {
            type: String,
            required: true
        }
    }
};

This is what I would like to do:
If I have the following data in category:

*

*category.object = "ring"

*category.group = "movies"

*category.name= "lord of the rings"

I want the id to be made of the first letters of every field in category and a number (the number of the last item added plus 1). In this case, It would be RMLOTR1.
What I'm doing right now
I'm adding a lot of data at the same time, so every time I do it, I made a function that iterates through all the items added and does what I want but...
My question is
Is there a built-in way to do this with mongodb or mongoose, adding the data and creating the id at the same time? I know I can do a virtual, but I want the data to be stored.
Extras

*

*If it's not posible to do this with mongodb, is there a way to do this with MySQL?

*Is doing this kind of thing considered a correct/wrong approach?

A: You are basically looking for a "pre" middleware hook on the "save" event fired by creating new documents in the collection. This will inspect the current document content and extract the "strings" from values in order to create your "prefix" value for _id.
There is also another part, where the "prefix" needs the addition of the numeric counter when there is already a value present for that particular "prefix" to make it distinct. There is a common technique in MongoDB used to "Generate an auto-incrementing sequence field", which basically involves keeping a "counters" collection and incrementing the value each time you access it.
As a complete and self contained demonstration, you combine the techniques as follows:
var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/warehouse');

var counterSchema = new Schema({
  "type": { "type": String, "required": true },
  "prefix": { "type": String, "required": true },
  "counter": Number
});

counterSchema.index({ "type": 1, "prefix": 1 },{ "unique": true });

counterSchema.virtual('nextId').get(function() {
  return this.prefix + this.counter;
});

var productSchema = new Schema({
  "_id": "String",
  "category": {
    "object": { "type": String, "required": true },
    "group": { "type": String, "required": true },
    "name": { "type": String, "required": true }
  }
},{ "_id": false });

productSchema.pre('save', function(next) {
  var self = this;

  if ( !self.hasOwnProperty("_id") ) {

    var prefix = self.category.object.substr(0,1).toUpperCase()
      + self.category.group.substr(0,1).toUpperCase()
      + self.category.name.split(" ").map(function(word) {
        return word.substr(0,1).toUpperCase();
      }).join("");

    mongoose.model('Counter').findOneAndUpdate(
      { "type": "product", "prefix": prefix },
      { "$inc": { "counter": 1 } },
      { "new": true, "upsert": true },
      function(err,counter) {
        self._id = counter.nextId;
        next(err);
      }
    );
  } else  {
    next();  // Just skip when _id is already there
  }
});

var Product = mongoose.model('Product',productSchema),
    Counter = mongoose.model('Counter', counterSchema);

async.series(
  [
    // Clean data
    function(callback) {
      async.each([Product,Counter],function(model,callback) {
        model.remove({},callback);
      },callback);
    },
    function(callback) {
      async.each(
        [
          {
            "category": {
              "object": "ring",
              "group": "movies",
              "name": "lord of the rings"
            }
          },
          {
            "category": {
              "object": "ring",
              "group": "movies",
              "name": "four weddings and a funeral"
            }
          },
          {
            "category": {
              "object": "ring",
              "group": "movies",
              "name": "lord of the rings"
            }
          }
        ],
        function(data,callback) {
          Product.create(data,callback)
        },
        callback
      )
    },
    function(callback) {
      Product.find().exec(function(err,products) {
        console.log(products);
        callback(err);
      });
    },
    function(callback) {
      Counter.find().exec(function(err,counters) {
        console.log(counters);
        callback(err);
      });
    }
  ],
  function(err) {
    if (err) throw err;
    mongoose.disconnect();
  }
)

This gives you output like:
[ { category: { name: 'lord of the rings', group: 'movies', object: 'ring' },
    __v: 0,
    _id: 'RMLOTR1' },
  { category:
     { name: 'four weddings and a funeral',
       group: 'movies',
       object: 'ring' },
    __v: 0,
    _id: 'RMFWAAF1' },
  { category: { name: 'lord of the rings', group: 'movies', object: 'ring' },
    __v: 0,
    _id: 'RMLOTR2' } ]
[ { __v: 0,
    counter: 2,
    type: 'product',
    prefix: 'RMLOTR',
    _id: 57104cdaa774fcc73c1df0e8 },
  { __v: 0,
    counter: 1,
    type: 'product',
    prefix: 'RMFWAAF',
    _id: 57104cdaa774fcc73c1df0e9 } ]

To first understand the Counter schema and model, you are basically defining something where you are going to look up a "unique" key and also attach a numeric field to "increment" on match. For convenience this just has a two fields making up the unique combination and a compound index defined. This could just also be a compound _id if so wanted.
The other convenience is the virtual method of nextId, which just does a concatenation of the "prefix" and "counter" values. It's also best practice here to include something like "type" here since your Counter model can be used to service "counters" for use in more than one collection source. So here we are using "product" whenever accessing in the context of the Product model to differentiate it from other models where you might also keep a similar sequence counter. Just a design point that is worthwhile following.
For the actual Product model itself, we want to attach "pre save" middleware hook in order to fill the _id content. So after determining the character portion of the "prefix", the operation then goes off and looks for that "prefix" with the "product" type data in combination in the Counter model collection.
The function of .findOneAndUpdate() is to look for a document matching the criteria in the "counters" collection and then where a document is found already it will "increment" the current counter value by use of the $inc update operator. If the document was not found, then the "upsert" option means that a new document will be created, and at any rate the same "increment" will happen in the new document as well.
The "new" option here means that we want the "modified" document to be returned ( either new or changed ) rather than what the document looked like before the $inc was applied. The result is that "counter" value will always increase on every access.
Once that is complete and a document for Counter is either incremented or created for it's matching keys, then you now have something you can use to assign to the _id in the Product model. As mentioned earlier you can use the virtual here for convenience to get the prefix with the appended counter value.
So as long as your documents are always created by either the .create() method from the model or by using new Product() and then the .save() method, then the methods attached to your "model" in your code are always executed.
Note here that since you want this in _id, then as a primary key this is "immutable" and cannot change. So even if the content in the fields referenced was later altered, the value in _id cannot be changed, and therefore why the code here makes no attempt when an _id value is already set.


text:
Q: Cascaded flip-flops and shift register timing In the D-flip flop at the edge triggering of the clock, \$Q(t+1)=D\$.
In the figure below, shift-register using cascaded flip flops, why don't we assume that at clock edge triggering
\$Q_1(t+1)=D_1\$ and \$Q_2(t+1)=D_2=Q_1(t+1)\$...etc.
so \$Q_4(t+1)=Q_3(t+1)=Q_2(t+1)=Q_1(t+1)=D_1\$?
Is the propagation delay what makes the schematic below a shift register?
How can I put that into consideration?

A: Edge triggered FFs have set-up and hold time requirements. Only data that was present before the clock triggered, will have satisfied the set-up time, and thus be "registered". Since (if well designed) the FFs have their clocks triggered at the same time, or nearly the same time, data that is "registered" at the input of one FF will appear at that FF's output too late to be registered by the next FF. That is why changes that happen in one FF don't just ripple down the entire shift register in one clock cycle.
Addendum:
The design of an edge triggered D-Flip-Flop used in another answer (by Paul Ghobril), and shown here, may work in an integrated circuit, but relies upon careful control of propagation delays. That is, it is susceptible to race conditions. (Sadly it is found all over the internet).

A edge triggered D-Flip-Flop that does not depend upon careful control of propagation delays is this:

Copied from PlayHookey.com

A: To understand it, consider first a gated D-Latch which is level sensitive which means that the input is applied to the output as long as the gate (E) is active, otherwise the last state is maintained:

Now one way to implement an edge triggered D-FlipFlop is by using two D-Latches in a master-slave configuration:

When the clock is low the first latch (the master) is activated and its output follows the D input but the second latch (slave) retains its last state.
When the clock switches to 1, the master holds the state available at the rising edge and then the slave will be active and its output follows the maintained output of the master. This value will remian until the next clock edge.
Now if you consider the successive D-FlipFlops of your circuit:

*

*Before the clock rising edge, the master of each Flipflop is connected to the state held by the slave of the previous Flipflop at the previous clock edge .

*At the rising edge of the clock, it is this maintained value that will be latched by the master of each Flipflop which is the status at the previous clock edge. this maintained value will be applied to the output of the D-Flipflop after the rising edge.


text:
Q: Refreshing UI after deleting item in React I'm new to React and I have the issue that my UI ain't refreshing once I send a delete fetch in my React app. I tried to use a useEffect on my deleteTaskHandler but it broke my code. Any ideas how to accomplish this refresh?
This is my Task.js file, which is receiving props from a TaskList.js file, and TaskList.js file sends a component to App.js:
import React, { useState } from 'react';
import classes from './Task.module.css';

const Task = (props) => {
    const [isCompleted, setIsCompleted] = useState(props.isCompleted);
    const changeCompleteStatus = () => {
        setIsCompleted(!isCompleted);
    }

const deleteTaskHandler = async () => {
    try {
        const key = props.id
        const response = await fetch('http://localhost:5050/delete-task/' + key, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error('Something went wrong!');
        };

        const data = await response.json();
        console.log(data);

    } catch (error) {
        console.log(error);
    }

};

const updateTaskHandler = async () => {
    const id = props.id
    const taskData = {
        id: id,
        content: props.content,
        isCompleted: !props.isCompleted,
        dateCreation: props.dateCreation,
    };

    try {
        const response = await fetch('http://localhost:5050/edit-task/' + id, {
            method: 'PATCH',
            body: JSON.stringify(taskData),
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error('Something went wrong!');
        };

        const data = await response.json();
        console.log(data);

    } catch (error) {
        console.log(error);
    }

};

let task;
if (props.isAllView) {
    task =

        <input type="checkbox" onClick={updateTaskHandler} onChange={changeCompleteStatus} checked={isCompleted} />

{props.content}

{props.dateCreation}

        <button onClick={deleteTaskHandler}>X</button>

} else {
    task =

{props.content}

{props.dateCreation}

}

return (

{task}

);
};

export default Task;

This is TaskList.js:
import React, { useState } from 'react';
import classes from './TaskList.module.css';
import Task from './Task';

const TaskList = (props) => {
    const [taskView, setTaskView] = useState('all');

    const getCompleteURL = () => {
        setTaskView('complete')
        props.onChangeTaskURL('http://localhost:5050/completed');
    };
    const getAllURL = () => {
        setTaskView('all')
        props.onChangeTaskURL('http://localhost:5050/');
    };
    const getPendingURL = () => {
        setTaskView('pending')
        props.onChangeTaskURL('http://localhost:5050/pending');
    };

    let taskList;

    if (taskView != 'all') {
        taskList = props.taskData.map((task) => (
            <Task
                key={task.id}
                content={task.content}
                dateCreation={task.dateCreation}
                isCompleted={task.isCompleted}
                isAllView={false}
            />
        ));
    } else {
        taskList = props.taskData.map((task) => (
            <Task
                key={task.id}
                id={task.id}
                content={task.content}
                dateCreation={task.dateCreation}
                isCompleted={task.isCompleted}
                isAllView={true}
            />
        ));
    }

    return (

                {taskList}

            <button onClick={getCompleteURL}>Completed</button>
            <button onClick={getAllURL}>All</button>
            <button onClick={getPendingURL}>Pending</button>

    );
};

export default TaskList;

This is App.js:
import React, { useState, useEffect, useCallback } from 'react';
import './App.css';
import TaskList from './components/Tasks/TaskList';
import NewTask from './components/NewTask/NewTask';

function App() {
  const [tasks, setTasks] = useState([]);
  const [taskURL, setTaskURL] = useState('http://localhost:5050/');

  const fetchTasksHandler = useCallback(async (url) => {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error('Something went wrong!');
      }

      const data = await response.json();

      const loadedTasks = [];

      for (const key in data) {
        loadedTasks.push({
          id: data[key]._id,
          content: data[key].content,
          isCompleted: data[key].isCompleted,
          dateCreation: data[key].dateCreation
        });
      }
      console.log(loadedTasks)
      setTasks(loadedTasks);
    } catch (error) {
      // throw new Error('Something went wrong!');
      console.log(error)
    }

  }, []);

  useEffect(() => {
    fetchTasksHandler(taskURL);
  }, [fetchTasksHandler, taskURL]);

  const changeTaskURL = url => {
    console.log(url)
    setTaskURL(url);
  };

  return (
    <React.Fragment>
      <TaskList taskData={tasks} onChangeTaskURL={changeTaskURL}></TaskList>
      <NewTask></NewTask>
    </React.Fragment>
  );
}

export default App;

A: Extract deleteTaskHandler and updateTaskHandler in your App.js and pass them down to the TaskList => Task. In both methods, on successful operation update the tasks state array (for delete - filter out the deleted task, for update - swap the old task with the updated one). This way, the Task component will call the relevant handler which will update the parent tasks state, which in turn will spill down to the TaskList and Task and everything will get updated automatically.
Here is a sample. Consider it more as a pseudo code as you'll have to modify some of the parts to handle your case appropriately.
Your Task.js:
import React, { useState } from 'react';
import classes from './Task.module.css';

const Task = (props) => {
    const {
        updateTaskHandler,
        deleteTaskHandler
    } = props;

    const [isCompleted, setIsCompleted] = useState(props.isCompleted);

    const changeCompleteStatus = () => {
        setIsCompleted(!isCompleted);
    }

    const updateHandler = () => {
        const taskData = {
            id: id,
            content: props.content,
            isCompleted: !props.isCompleted,
            dateCreation: props.dateCreation,
        };

        updateTaskHandler(props.id, taskData);
    };

    const deleteHandler = () => {
        deleteTaskHandler(props.id);
    };

    let task;

    if (props.isAllView) {
        task =

            <input type="checkbox" onClick={updateHandler} onChange={changeCompleteStatus} checked={isCompleted} />

{props.content}

{props.dateCreation}

            <button onClick={deleteHandler}>X</button>

    } else {
        task =

{props.content}

{props.dateCreation}

    }

    return (

{task}

    );
};

export default Task;

TaskList.js:
import React, { useState } from 'react';
import classes from './TaskList.module.css';
import Task from './Task';

const TaskList = (props) => {
    const [taskView, setTaskView] = useState('all');

    const getCompleteURL = () => {
        setTaskView('complete')
        props.onChangeTaskURL('http://localhost:5050/completed');
    };

    const getAllURL = () => {
        setTaskView('all')
        props.onChangeTaskURL('http://localhost:5050/');
    };

    const getPendingURL = () => {
        setTaskView('pending')
        props.onChangeTaskURL('http://localhost:5050/pending');
    };

    let taskList;

    if (taskView != 'all') {
        taskList = props.taskData.map((task) => (
            <Task
                key={task.id}
                content={task.content}
                dateCreation={task.dateCreation}
                isCompleted={task.isCompleted}
                isAllView={false}
                updateTaskHandler={props.updateTaskHandler}
                deleteTaskHandler={props.deleteTaskHandler}
            />
        ));
    } else {
        taskList = props.taskData.map((task) => (
            <Task
                key={task.id}
                id={task.id}
                content={task.content}
                dateCreation={task.dateCreation}
                isCompleted={task.isCompleted}
                isAllView={true}
                updateTaskHandler={props.updateTaskHandler}
                deleteTaskHandler={props.deleteTaskHandler}
            />
        ));
    }

    return (

                {taskList}

            <button onClick={getCompleteURL}>Completed</button>
            <button onClick={getAllURL}>All</button>
            <button onClick={getPendingURL}>Pending</button>

    );
};

export default TaskList;

And App.js:
import React, { useState, useEffect, useCallback } from 'react';
import './App.css';
import TaskList from './components/Tasks/TaskList';
import NewTask from './components/NewTask/NewTask';

function App() {
    const [tasks, setTasks] = useState([]);
    const [taskURL, setTaskURL] = useState('http://localhost:5050/');

    const fetchTasksHandler = useCallback(async (url) => {
        try {
            const response = await fetch(url);

            if (!response.ok) {
                throw new Error('Something went wrong!');
            }

            const data = await response.json();

            const loadedTasks = [];

            for (const key in data) {
                loadedTasks.push({
                    id: data[key]._id,
                    content: data[key].content,
                    isCompleted: data[key].isCompleted,
                    dateCreation: data[key].dateCreation
                });
            }

            setTasks(loadedTasks);
        }
        catch (error) {
            // throw new Error('Something went wrong!');
            console.log(error)
        }

    }, []);

    const deleteTaskHandler = async (taskID) => {
        try {
            const response = await fetch(`http://localhost:5050/delete-task/${taskID}`, {
                method: 'DELETE'
            });

            if (!response.ok) {
                throw new Error('Something went wrong!');
            };

            const data = await response.json();

            setTasks(tasks => {
                return tasks.filter(task => task.id !== taskID)
            });
        }
        catch (error) {
            console.log(error);
        }
    };

    const updateTaskHandler = async (taskID, taskData) => {
        const id = props.id
        const taskData = {
            id: id,
            content: props.content,
            isCompleted: !props.isCompleted,
            dateCreation: props.dateCreation,
        };

        try {
            const response = await fetch(`http://localhost:5050/edit-task/${taskID}`, {
                method: 'PATCH',
                body: JSON.stringify(taskData),
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) {
                throw new Error('Something went wrong!');
            };

            const data = await response.json();

            setTasks(tasks => {
                return tasks.map(task => {
                    if (task.id !== taskID) {
                        return task;
                    }
                    else {
                        return data; // The updated task
                    }
                })
            });
        }
        catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        fetchTasksHandler(taskURL);
    }, [fetchTasksHandler, taskURL]);

    const changeTaskURL = url => {
        console.log(url)
        setTaskURL(url);
    };

    return (
        <React.Fragment>
            <TaskList
                taskData={tasks}
                onChangeTaskURL={changeTaskURL}
                deleteTaskHandler={deleteTaskHandler}
                updateTaskHandler={updateTaskHandler}
            />
            <NewTask />
        </React.Fragment>
    );
}

export default App;

A: You have to pass a callback that removes a task and pass it as a prop to the Task component.
In your App.js:
function deleteTask(id) {
  setTasks(loadedTasks.filter(x => x.id !== id);
}

// ...

<TaskList taskData={tasks} onDelete={deleteTask}></TaskList>

In your TaskList.js:
tasks.map(task => <Task id={task.id} key={task.id} onDelete={props.deleteTask}></Task>)

In the Task.js call props.deleteTask(props.id) whenever you need to.
Note that passing a prop through two components or more is called "prop drilling" and should be avoided (by keeping the state in TaskList.js for example).

A: you can use
window.location.reload();

to refresh the page or
this.setState({});

to refresh the component or
  const [value,setValue] = useState();

  const refresh = ()=>{
   setValue({});
  }

to refresh the component using hooks
i hope you found this answer helpful


text:
Q: Webdriver and push button i try to make in webdriver a test.

*

*go to http://programyedukacyjne.pl/konkurs/galeria-prac.html

*click for example first vote "GŁOSUJ [star]"
and should appear a box to put email.
But nothing happend just add to url in browser "#vote_box_22"
I tryed use click(), Action and javascript click but still there no appear a form...
here is begine:
driver.get("http://programyedukacyjne.pl/konkurs/galeria-prac.html");
    WebElement location = driver.findElement(By.name("filter_miejscowosc"));
    location.sendKeys("nowy sącz", Keys.ENTER);

here is where I have problem
WebElement voteBtn = driver.findElement(By.xpath("html/body/div[4]/div/div[3]/div/div[4]/div/div[1]/div[2]/div[2]/div[1]/a"));
    voteBtn.click();

my secound solution
new Actions(driver).moveToElement(voteBtn).click().perform();

A: Try using a more specific selector that pinpoints the link more accurately in a less brittle way. The following CSS selector should select the vote link for the first result shown in the list:
WebElement voteBtn = driver.findElement(By.cssSelector("div.praca:nth-of-type(1) a[href*='vote_box']"));
voteBtn.click();


text:
Q: Android - Starting Thread from Synchronized Block Any ideas, why this part of code is locking the UI Thread?
synchronized (executionMonitor) {
    thread = new Thread(asyncCommand);
    thread.setPriority(Thread.MIN_PRIORITY);
    thread.setName(command.getClass().getSimpleName());
    thread.start();
    return;
}

I'm starting the thread from the UI block. During debuging I found, that UI thread is in MONITOR state. But I don't understand why?
executionMonitor is defined only as object:
private Object executionMonitor = new Object();

and not used in other places.

A: Try returning outside the synchronized block.
Update:
Confirmed as not the solution - Java will automatically release the lock even if the return statement is inside the synchronized block

A: Ok.. I found, thank you all for replies, the problem was another stupid synchronization block - but in the command. Whole command was synchronized using the instance of DBHelper.