问:
"Undefined class" as argument for is_base_of
```<code>class Base {};

template <class T, typename = typename std::enable_if<std::is_base_of<Base, T>::value>::type>
class B {};                                                ^^^^^^^^^^ error C2139: 'A': an undefined class is not allowed as an argument to compiler intrinsic type trait '__is_base_of'

class A : public Base
{
    B<A> b;
};
</code>```

Apparently this is not allowed. Is there a workaround, or something I'm forgetting?

答:
Here's the output for GCC:

```<code>type_traits:1302:66: error: incomplete type 'A' used in type trait expression
    : public integral_constant<bool, __is_base_of(_Base, _Derived)>
                                                                 ^
<source>:5:51: note: in instantiation of template class 'std::is_base_of<Base, A>' requested here
template <class T, typename = std::enable_if<std::is_base_of<Base, T>::value>>
                                                  ^
<source>:10:5: note: in instantiation of default argument for 'B<A>' required here
    B<A> b;
    ^~~~

<source>:8:7: note: definition of 'A' is not complete until the closing '}'
class A : public Base
      ^
</code>```

Indeed, A is incomplete until the closing } has been reached. You use A in the type traits while instantiating B inside A, so you're out of luck there.

What you can do instead is to enforce it with a static_assert in a member function of B:

```<code>template <class T>
class B {
public:
    B() {
        static_assert(std::is_base_of<Base, T>::value, "T must inherit from base");
    }
};
</code>```

Inside member functions, all types are complete.

Body:
class Base {};

template <class T, typename = typename std::enable_if<std::is_base_of<Base, T>::value>::type>
class B {};                                                ^^^^^^^^^^ error C2139: 'A': an undefined class is not allowed as an argument to compiler intrinsic type trait '__is_base_of'

class A : public Base
{
    B b;
};

Apparently this is not allowed. Is there a workaround, or something I'm forgetting?

Body:
Here's the output for GCC:

type_traits:1302:66: error: incomplete type 'A' used in type trait expression
    : public integral_constant<bool, __is_base_of(_Base, _Derived)>
                                                                 ^
<source>:5:51: note: in instantiation of template class 'std::is_base_of<Base, A>' requested here
template <class T, typename = std::enable_if<std::is_base_of<Base, T>::value>>
                                                  ^
<source>:10:5: note: in instantiation of default argument for 'B<A>' required here
    B<A> b;
    ^~~~

<source>:8:7: note: definition of 'A' is not complete until the closing '}'
class A : public Base
      ^

Indeed, A is incomplete until the closing } has been reached. You use A in the type traits while instantiating B<A> inside A, so you're out of luck there.

What you can do instead is to enforce it with a static_assert in a member function of B:

template <class T>
class B {
public:
    B() {
        static_assert(std::is_base_of<Base, T>::value, "T must inherit from base");
    }
};

Inside member functions, all types are complete.


来源: stackexchange

问:
Google Apps Script - TypeError: Cannot read property 'length' of undefined
I have a Google Sheets script that is supposed to grab data from an API but I am getting the error

TypeError: Cannot read property 'length' of undefined (line 5, file "draftOrder")

How can I fix this error? I haven't touched this script in years, so I'm not sure what broke.

```<code>  function draftOrder(ownerRange, numRounds) {
  var output = [];
  var owners = [];

  for (var i = 0; i < ownerRange.length; i++) {
    if (ownerRange[i][0] !== '') {
      owners.push(ownerRange[i][0]);
    }
  }

  for (var i = 0; i < numRounds; i++) {
    if (i % 2 == 0) {
      output = output.concat(owners);
    } else {
      output = output.concat([].concat(owners).reverse());
    }

  }
  return output;
}
</code>```

Thanks in advance for any help that you can provide. Cheers!

答:
```<code>function draftOrder(ownerRange, numRounds) {
  var output = [];
  var owners = [];
  if(ownerRange && numRounds) {//checking for valid inputs

    for (var i = 0; i < ownerRange.length; i++) {
      if (ownerRange[i][0] !== '') {
        owners.push(ownerRange[i][0]);
      }
    }

    for (var i = 0; i < numRounds; i++) {
      if (i % 2 == 0) {
        output = output.concat(owners);
      } else {
        output = output.concat([].concat(owners).reverse());
      }

    }
    return output;
  }else{
    SpreadsheetApp.getUi().alert('Invalid Inputs')
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Google Sheets script that is supposed to grab data from an API but I am getting the error

TypeError: Cannot read property 'length' of undefined (line 5, file "draftOrder")

How can I fix this error? I haven't touched this script in years, so I'm not sure what broke.

  function draftOrder(ownerRange, numRounds) {
  var output = [];
  var owners = [];

  for (var i = 0; i < ownerRange.length; i++) {
    if (ownerRange[i][0] !== '') {
      owners.push(ownerRange[i][0]);
    }
  }

  for (var i = 0; i < numRounds; i++) {
    if (i % 2 == 0) {
      output = output.concat(owners);
    } else {
      output = output.concat([].concat(owners).reverse());
    }

  }
  return output;
}

Thanks in advance for any help that you can provide. Cheers!


问:
How do I create Sharebar like this sample URL?
I have to create a social sharing sidebar similar to this website. Can you suggest how it can be implemented? using Jquery OR anything?

ref. this page, http://www.chow.com/recipes/25677-beef-kalbi

look at the left side SHARE BAR

答:
Their's specifically is via Gigya.

I think Gigya charge for what they offer but you can get something similar using free sharing services such as AddThis or ShareThis, both of which offer sharing stats. From there it's just a matter of fixing a
 containing their "copy & paste" code to the top left of the page and you're sorted. Here's an example using code from ShareThis:

HTML:

```<code><div id="sharebar">
    <span class="btn st_facebook_vcount" displayText="Facebook"></span>
    <span class="btn st_twitter_vcount" displayText="Tweet"></span>
    <span class="btn st_email_vcount" displayText="Email"></span>
</div>
<script>var switchTo5x=true;</script>
<script src="//w.sharethis.com/button/buttons.js"></script>
</code>```

CSS:

```<code>#sharebar {
    top:10%;
    left:-65px;
    width:66px;
    position:fixed;
    background:#35a731;
    border-radius:10px;
    padding:5px 5px 10px 15px;
}
#sharebar:hover { left:-10px; }
#sharebar .btn { display:block; margin-left:-15px; }
#sharebar:hover .btn { margin-left:0; }
</code>```

Add a little CSS3 transition for effect and even a label and it starts looking a bit more respectable.

View demo: jsfiddle.net/kUTWc/show (or edit it)

Body:
Their's specifically is via Gigya.

I think Gigya charge for what they offer but you can get something similar using free sharing services such as AddThis or ShareThis, both of which offer sharing stats. From there it's just a matter of fixing a <div> containing their "copy & paste" code to the top left of the page and you're sorted. Here's an example using code from ShareThis:

HTML:

<div id="sharebar">
    <span class="btn st_facebook_vcount" displayText="Facebook"></span>
    <span class="btn st_twitter_vcount" displayText="Tweet"></span>
    <span class="btn st_email_vcount" displayText="Email"></span>
</div>
<script>var switchTo5x=true;</script>
<script src="//w.sharethis.com/button/buttons.js"></script>

CSS:

#sharebar {
    top:10%;
    left:-65px;
    width:66px;
    position:fixed;
    background:#35a731;
    border-radius:10px;
    padding:5px 5px 10px 15px;
}
#sharebar:hover { left:-10px; }
#sharebar .btn { display:block; margin-left:-15px; }
#sharebar:hover .btn { margin-left:0; }

Add a little CSS3 transition for effect and even a label and it starts looking a bit more respectable.

View demo: jsfiddle.net/kUTWc/show (or edit it)

ContentLicense: CC BY-SA 3.0


问:
Replace strings with longest string in group
Consider this dataframe

```<code>df <- data.frame(name = c("Dirk Nowitzki", "Dirk Nowitzki", "LeBron James", "Lebron James", "Kobe Bryant", "Kobe Bryant"),
                 team = c("Mavericks", "Mavs", "Cavs", "Cavaliers", "Lakers", "Lakers"))
           name      team
1 Dirk Nowitzki Mavericks
2 Dirk Nowitzki      Mavs
3  LeBron James      Cavs
4  Lebron James Cavaliers
5   Kobe Bryant    Lakers
6   Kobe Bryant    Lakers
</code>```

I'd like to replace the shortened team names with their longer counterparts and get this

```<code>           name      team
1 Dirk Nowitzki Mavericks
2 Dirk Nowitzki Mavericks
3  LeBron James Cavaliers
4  Lebron James Cavaliers
5   Kobe Bryant    Lakers
6   Kobe Bryant    Lakers
</code>```

It's easy enough to use gsub or str_replace to do this one by one in a toy example, but the actual dataset has thousands of incomplete strings.

I can group by name, and determine which team name is longest, but then I get stuck

```<code>df %>%
  group_by(name) %>%
  mutate(str_len = str_length(team))
</code>```

答:
Some of the 'name's differ by case, so it is better to change it to a common case while grouping, and then get the index of max length with which.max and replace the 'team' with that corresponding value for 'team'

```<code>library(stringr)
library(dplyr)
df %>%
   group_by(name2 = toupper(name)) %>%
   mutate(team = team[which.max(str_length(team))]) %>%
   ungroup  %>%
   select(-name2)
# A tibble: 6 x 2
#  name          team
#  <fct>         <fct>
#1 Dirk Nowitzki Mavericks
#2 Dirk Nowitzki Mavericks
#3 LeBron James  Cavaliers
#4 Lebron James  Cavaliers
#5 Kobe Bryant   Lakers
#6 Kobe Bryant   Lakers
</code>```

Body:
Consider this dataframe

df <- data.frame(name = c("Dirk Nowitzki", "Dirk Nowitzki", "LeBron James", "Lebron James", "Kobe Bryant", "Kobe Bryant"),
                 team = c("Mavericks", "Mavs", "Cavs", "Cavaliers", "Lakers", "Lakers"))
           name      team
1 Dirk Nowitzki Mavericks
2 Dirk Nowitzki      Mavs
3  LeBron James      Cavs
4  Lebron James Cavaliers
5   Kobe Bryant    Lakers
6   Kobe Bryant    Lakers

I'd like to replace the shortened team names with their longer counterparts and get this

           name      team
1 Dirk Nowitzki Mavericks
2 Dirk Nowitzki Mavericks
3  LeBron James Cavaliers
4  Lebron James Cavaliers
5   Kobe Bryant    Lakers
6   Kobe Bryant    Lakers

It's easy enough to use gsub or str_replace to do this one by one in a toy example, but the actual dataset has thousands of incomplete strings.

I can group by name, and determine which team name is longest, but then I get stuck

df %>%
  group_by(name) %>%
  mutate(str_len = str_length(team))

Body:
Some of the 'name's differ by case, so it is better to change it to a common case while grouping, and then get the index of max length with which.max and replace the 'team' with that corresponding value for 'team'

library(stringr)
library(dplyr)
df %>%
   group_by(name2 = toupper(name)) %>%
   mutate(team = team[which.max(str_length(team))]) %>%
   ungroup  %>%
   select(-name2)
# A tibble: 6 x 2
#  name          team
#  <fct>         <fct>
#1 Dirk Nowitzki Mavericks
#2 Dirk Nowitzki Mavericks
#3 LeBron James  Cavaliers
#4 Lebron James  Cavaliers
#5 Kobe Bryant   Lakers
#6 Kobe Bryant   Lakers


问:
Gridstack.js Delete Widget using Jquery
Below is the Jquery Function I am using I have no idea how to use remove_widget please help:
I am not able to find any help on deleting widget whereas the Knockout.js is not of my use as I am not using it.</p>

```<code>$(function () {
var options = {resizable: {
handles: 'e, se, s, sw, w'
}
};

$('.grid-stack').gridstack(options);

        new function () {
            this.serialized_data = [
                {x: 0, y: 0, width: 2, height: 2},
                {x: 3, y: 1, width: 1, height: 2},
                {x: 4, y: 1, width: 1, height: 1},
                {x: 2, y: 3, width: 3, height: 1},
                {x: 1, y: 4, width: 1, height: 1},
                {x: 1, y: 3, width: 1, height: 1},
                {x: 2, y: 4, width: 1, height: 1},
                {x: 2, y: 5, width: 1, height: 1}
            ];

            this.grid = $('.grid-stack').data('gridstack');

            this.load_grid = function () {
                this.grid.remove_all();
                var items = GridStackUI.Utils.sort(this.serialized_data);
                _.each(items, function (node) {
                    this.grid.add_widget($('<div><div class="grid-stack-item-content" /><div/>'),
                        node.x, node.y, node.width, node.height);
                }, this);
            }.bind(this);

            this.save_grid = function () {
                this.serialized_data = _.map($('.grid-stack > .grid-stack-item:visible'), function (el) {
                    el = $(el);
                    var node = el.data('_gridstack_node');
                    return {
                        x: node.x,
                        y: node.y,
                        width: node.width,
                        height: node.height
                    };
                }, this);
                $('#saved-data').val(JSON.stringify(this.serialized_data, null, '    '));
            }.bind(this);

            this.clear_grid = function () {
                this.grid.remove_all();
            }.bind(this);
            this.add_grid = function(){
                this.grid.add_widget($('<div><div class="grid-stack-item-content" /><i class=" fa fa-remove"></><div/>'), 0, 0, 3, 2, true);
                $('.fa-remove').click(this.remove_grid);
            }.bind(this);
            this.remove_grid = function(){
                this.grid.remove_widget("What should I use Here", true);
            }.bind(this);
            $('#save-grid').click(this.save_grid);
            $('#load-grid').click(this.load_grid);
            $('#clear-grid').click(this.clear_grid);
            $('#add-grid').click(this.add_grid);
            $('.fa-remove').click($(this).remove_grid);
            this.load_grid();
        };
    });
</code>```

答:
Removing widget after click checkbox</p>

```<code>$("#mycheckbox").click(function () {if (document.getElementById('mycheckbox').checked == false)
                    {
                        $("#myblockContent").insertAfter("#spantrash");
                        var grid = $('.grid-stack').data('gridstack');
                        el=$('#divGridstackContent').closest('.grid-stack-item');
                        grid.removeWidget(el);
                    }
                    else{
                        var grid = $('.grid-stack').data('gridstack');
                        grid.addWidget($('<div><div class="grid-stack-item-content divscroll" id="divGridstackContent" ><span id="spanContent"></span></div></div>'), {id: "Content", x: "0", y: "6", width: "6", height: "6"});
                        $( "#blockContent" ).insertAfter( "#spanContent" );

                    }
                    });
</code>```

Title: Gridstack.js Delete Widget using Jquery

Body:
Below is the Jquery Function I am using I have no idea how to use remove_widget please help:
I am not able to find any help on deleting widget whereas the Knockout.js is not of my use as I am not using it.

$(function () {
var options = {resizable: {
handles: 'e, se, s, sw, w'
}
};

$('.grid-stack').gridstack(options);

        new function () {
            this.serialized_data = [
                {x: 0, y: 0, width: 2, height: 2},
                {x: 3, y: 1, width: 1, height: 2},
                {x: 4, y: 1, width: 1, height: 1},
                {x: 2, y: 3, width: 3, height: 1},
                {x: 1, y: 4, width: 1, height: 1},
                {x: 1, y: 3, width: 1, height: 1},
                {x: 2, y: 4, width: 1, height: 1},
                {x: 2, y: 5, width: 1, height: 1}
            ];

            this.grid = $('.grid-stack').data('gridstack');

            this.load_grid = function () {
                this.grid.remove_all();
                var items = GridStackUI.Utils.sort(this.serialized_data);
                _.each(items, function (node) {
                    this.grid.add_widget($('

'),
                        node.x, node.y, node.width, node.height);
                }, this);
            }.bind(this);

            this.save_grid = function () {
                this.serialized_data = _.map($('.grid-stack > .grid-stack-item:visible'), function (el) {
                    el = $(el);
                    var node = el.data('_gridstack_node');
                    return {
                        x: node.x,
                        y: node.y,
                        width: node.width,
                        height: node.height
                    };
                }, this);
                $('#saved-data').val(JSON.stringify(this.serialized_data, null, '    '));
            }.bind(this);

            this.clear_grid = function () {
                this.grid.remove_all();
            }.bind(this);
            this.add_grid = function(){
                this.grid.add_widget($('

</>
'), 0, 0, 3, 2, true);
                $('.fa-remove').click(this.remove_grid);
            }.bind(this);
            this.remove_grid = function(){
                this.grid.remove_widget("What should I use Here", true);
            }.bind(this);
            $('#save-grid').click(this.save_grid);
            $('#load-grid').click(this.load_grid);
            $('#clear-grid').click(this.clear_grid);
            $('#add-grid').click(this.add_grid);
            $('.fa-remove').click($(this).remove_grid);
            this.load_grid();
        };
    });

Body:
Removing widget after click checkbox

$("#mycheckbox").click(function () {if (document.getElementById('mycheckbox').checked == false)
                    {
                        $("#myblockContent").insertAfter("#spantrash");
                        var grid = $('.grid-stack').data('gridstack');
                        el=$('#divGridstackContent').closest('.grid-stack-item');
                        grid.removeWidget(el);
                    }
                    else{
                        var grid = $('.grid-stack').data('gridstack');
                        grid.addWidget($('<div><div class="grid-stack-item-content divscroll" id="divGridstackContent" ><span id="spanContent"></span></div></div>'), {id: "Content", x: "0", y: "6", width: "6", height: "6"});
                        $( "#blockContent" ).insertAfter( "#spanContent" );

                    }
                    });


问:
Could not increase number of max_open_files to more than 4096 (request: 4214)
I have MariaDB + Nginx on Linux Debian 9(stretch).
After installing MariaDB it and trying to start it, I got the error saying:
[Warning] Could not increase number of max_open_files to more than 4096 (request: 4214).
So I googled it and it told me that I should change LimiNOFILE to 10000 in /etc/systemd/system/mysql.service. I did that, did deamon-reload and it did absolutely nothing. I am still getting the same error message. I tried reinstalling MariaDB but that didn't help either. I also added LimitMEMLOCK=10000 at the very end of my file, that didn't change anything.

Full traceback:

Link

Thank you in advance

答:
I solved it by reinstalling MariaDB with

$ sudo apt-get purge mariadb-server

And you should check if it's still on the system with:

$ sudo dpkg -l | grep mariadb

And if it is, do:

$ sudo apt-get purge mariadb-common

But before doing that I killed everything that had to do with MariaDB/MySQL via htop.
And then the standart procedure with installing it:

$ sudo apt update

$ sudo apt install mariadb-server

$ sudo mysql_secure_installation


问:
How to validate data so no incorrect data is saved to the database, using javascript
I would like to validate my code for adding a product to sqlite database, but dont know how I do that in the best way. I have been using this:

routes.post('/product/', async (req, res)

and await for adding a product to the sqlite database, which was successful.
What I would like to accomplish is to check so the same product can't be added twice. Do you have any tips for how I can do that?
I was thinking if I could use an if statement to check that..

答:
When you create your sqlite table, add a statement something like this to create a unique index (an index that prohibits duplicate values) on your table.

You can also add this index onto an existing table.

```<code> CREATE UNIQUE INDEX product_indx ON yourtable(product);
</code>```

Then, attempts to insert duplicate values of product will fail and throw an error.

You can catch the error and use it to whine at your user, or present whatever error message is appropriate

Body:
When you create your sqlite table, add a statement something like this to create a unique index (an index that prohibits duplicate values) on your table.

You can also add this index onto an existing table.

 CREATE UNIQUE INDEX product_indx ON yourtable(product);

Then, attempts to insert duplicate values of product will fail and throw an error.

You can catch the error and use it to whine at your user, or present whatever error message is appropriate


问:
Functional Programming: Having a very difficult time understanding how this function lazily evaluates
I'm working through the Functional Programming in Scala book, and am on the section about lazy evaluation.  There is an exercise to implement a takeWhile function using foldRight.  I was able to complete it successfully, but when I added print statements I saw that it seems to be doing processing I wouldn't expect.  I am very confused by this.

Here is the code:

```<code>trait McStream[+A] {
    def uncons: Option[(A, McStream[A])]

    def isEmpty: Boolean = uncons.isEmpty

    def toList: List[A] = {
      uncons match {
        case Some(head -> tail) => head :: tail.toList
        case None => Nil
      }
    }

    def foldRight[B](z: => B)(f: (A, => B) => B): B = {
      uncons match {
        case Some(head -> tail) =>
          println(s"Inside foldRight, head is $head")
          f(head, tail.foldRight(z)(f))
        case None => z
      }
    }

    // TODO how does evaluate?  Trace steps
    // TODO it seems to be storing a deferred takeWhile in the `b` variable that evaluates during the cons
    def takeWhile(p: A => Boolean): McStream[A] = {
      foldRight(McStream.empty[A]) { (a, b) =>
        println(s"a is $a, b is $b")
        if (p(a)) {
          McStream.cons(a, b)
        } else {
          McStream.empty
        }
      }
    }
}
</code>```

With a helper object for constructors:

```<code>object McStream {
    def empty[A]: McStream[A] = new McStream[A] {
      override def uncons: Option[(A, McStream[A])] = None
    }

    def cons[A](hd: => A, tl: => McStream[A]): McStream[A] = {
      new McStream[A] {
        lazy val uncons = Some((hd, tl))
      }
    }

    def apply[A](as: A*): McStream[A] = {
      if (as.isEmpty) empty
      else cons(as.head, apply(as.tail: _*))
    }
  }
}
</code>```

Here is the test I'm running:

```<code>"take while a predicate is matched" in {
      val stream = McStream(1, 2)
      stream.takeWhile(_ < 2).toList shouldEqual List(1)
    }
</code>```

And here is the output I get:

```<code>Inside foldRight, head is 1
Inside foldRight, head is 2
a is 2, b is McStream(None)
a is 1, b is McStream(None)
Inside foldRight, head is 2
a is 2, b is McStream(None)
</code>```

I'm confused about the last two lines, to me it seems like it should recurse all the way to the end of the list, and then either connect the currently processed tail to the next element if the predicate matches, or replace it with an empty McStream otherwise.  At that point, it should just be returning the list, and not doing the additional foldRight and evaluation.

Here is the evaluation order as far as I can understand it:

```<code>Stream(1, Stream(2, Stream.empty)).takeWhile(_ < 2)
should print Inside foldRight, head is 1
Stream(2, Stream.empty).takeWhile(_ < 2)
should print Inside foldRight, head is 2
Stream.empty.takeWhile(_ < 2)
End of recursion, starts to return
Stream(2, Stream.empty).takeWhile(_ < 2)
should print a is 2, b is Stream.empty
Stream(1, Stream.empty).takeWhile(_ < 2)
should print a is 1, b is Stream.empty
1 #:: Stream.empty
</code>```

Thanks in advance!

答:
Turns out that the very mechanisms I was using to try to understand the evaluation (println statements), were forcing evaluation and causing the above issues.  When I remove the print statements it evaluates like it should.

Don't use println in your lazy evaluations!

Body:
I'm working through the Functional Programming in Scala book, and am on the section about lazy evaluation.  There is an exercise to implement a takeWhile function using foldRight.  I was able to complete it successfully, but when I added print statements I saw that it seems to be doing processing I wouldn't expect.  I am very confused by this.

Here is the code:

trait McStream[+A] {
    def uncons: Option[(A, McStream[A])]

    def isEmpty: Boolean = uncons.isEmpty

    def toList: List[A] = {
      uncons match {
        case Some(head -> tail) => head :: tail.toList
        case None => Nil
      }
    }

    def foldRight[B](z: => B)(f: (A, => B) => B): B = {
      uncons match {
        case Some(head -> tail) =>
          println(s"Inside foldRight, head is $head")
          f(head, tail.foldRight(z)(f))
        case None => z
      }
    }

    // TODO how does evaluate?  Trace steps
    // TODO it seems to be storing a deferred takeWhile in the `b` variable that evaluates during the cons
    def takeWhile(p: A => Boolean): McStream[A] = {
      foldRight(McStream.empty[A]) { (a, b) =>
        println(s"a is $a, b is $b")
        if (p(a)) {
          McStream.cons(a, b)
        } else {
          McStream.empty
        }
      }
    }
}

With a helper object for constructors:

object McStream {
    def empty[A]: McStream[A] = new McStream[A] {
      override def uncons: Option[(A, McStream[A])] = None
    }

    def cons[A](hd: => A, tl: => McStream[A]): McStream[A] = {
      new McStream[A] {
        lazy val uncons = Some((hd, tl))
      }
    }

    def apply[A](as: A*): McStream[A] = {
      if (as.isEmpty) empty
      else cons(as.head, apply(as.tail: _*))
    }
  }
}

Here is the test I'm running:

"take while a predicate is matched" in {
      val stream = McStream(1, 2)
      stream.takeWhile(_ < 2).toList shouldEqual List(1)
    }

And here is the output I get:

Inside foldRight, head is 1
Inside foldRight, head is 2
a is 2, b is McStream(None)
a is 1, b is McStream(None)
Inside foldRight, head is 2
a is 2, b is McStream(None)

I'm confused about the last two lines, to me it seems like it should recurse all the way to the end of the list, and then either connect the currently processed tail to the next element if the predicate matches, or replace it with an empty McStream otherwise.  At that point, it should just be returning the list, and not doing the additional foldRight and evaluation.

Here is the evaluation order as far as I can understand it:

Stream(1, Stream(2, Stream.empty)).takeWhile(_ < 2)
should print Inside foldRight, head is 1
Stream(2, Stream.empty).takeWhile(_ < 2)
should print Inside foldRight, head is 2
Stream.empty.takeWhile(_ < 2)
End of recursion, starts to return
Stream(2, Stream.empty).takeWhile(_ < 2)
should print a is 2, b is Stream.empty
Stream(1, Stream.empty).takeWhile(_ < 2)
should print a is 1, b is Stream.empty
1 #:: Stream.empty

Thanks in advance!


问:
Crontab and testing a command to be executed
I'm quite new to cron and crontab.

I've edited the crontab file and I need to execute manually one of commands so I can try it and test it beforehand. How do I do that? If it fails, is there a mode that shows the errors?

答:
Write a shell script that you can test.

Execute that shell script from the crontab.

Remember that cron provides barely any environment - so your script may have to fix that.  In particular, your profile will not be used.

Do not get fancy with what you put in the crontab.

Build a debug mode into your shell script.

No, there isn't specifically a mode that shows errors.  Usually, if the cron job witters, the output is emailed to you.  That is, it sends standard output and standard error information to you if the executed command writes anything to either standard output or standard error.

On MacOS X (10.6.7), the environment I got was (via a crontab entry like 12 37 17 5 * env >/tmp/cron.env):

```<code>SHELL=/bin/sh
USER=jleffler
PATH=/usr/bin:/bin
PWD=/Users/jleffler
SHLVL=1
HOME=/Users/jleffler
LOGNAME=jleffler
_=/usr/bin/env
</code>```

Of those, PWD, _ and SHLVL are handled by the shell.  So, to test your script reliably in a cron-like environment, use:

```<code>(cd $HOME
 env -i \
    SHELL=/bin/sh \
    USER=$USER \
    PATH=/usr/bin:/bin \
    HOME=$HOME \
    LOGNAME=$LOGNAME \
    /path/to/script/you/execute ...
)
</code>```

The -i option to env means 'ignore all inherited enviroment'; the script will see exactly the five values specified plus anything the shell specifies automatically.  With no arguments, env reports on the environment; with arguments, it adjusts the environment and executes a command.

Body:
Write a shell script that you can test.

Execute that shell script from the crontab.

Remember that cron provides barely any environment - so your script may have to fix that.  In particular, your profile will not be used.

Do not get fancy with what you put in the crontab.

Build a debug mode into your shell script.

No, there isn't specifically a mode that shows errors.  Usually, if the cron job witters, the output is emailed to you.  That is, it sends standard output and standard error information to you if the executed command writes anything to either standard output or standard error.

On MacOS X (10.6.7), the environment I got was (via a crontab entry like 12 37 17 5 * env >/tmp/cron.env):

SHELL=/bin/sh
USER=jleffler
PATH=/usr/bin:/bin
PWD=/Users/jleffler
SHLVL=1
HOME=/Users/jleffler
LOGNAME=jleffler
_=/usr/bin/env

Of those, PWD, _ and SHLVL are handled by the shell.  So, to test your script reliably in a cron-like environment, use:

(cd $HOME
 env -i \
    SHELL=/bin/sh \
    USER=$USER \
    PATH=/usr/bin:/bin \
    HOME=$HOME \
    LOGNAME=$LOGNAME \
    /path/to/script/you/execute ...
)

The -i option to env means 'ignore all inherited enviroment'; the script will see exactly the five values specified plus anything the shell specifies automatically.  With no arguments, env reports on the environment; with arguments, it adjusts the environment and executes a command.


答:
```<code>df <- df %>%
  mutate(team_full = case_when(
     team == 'Cavs' ~ 'Cavaliers',
     team == 'Mavs' ~ 'Mavericks',
     TRUE ~ team))
</code>```

<p>*Note the lists can be more inclusive for multiple values like...</p>

```<code>team %in% c('Mavs', 'mavs', 'Mavrix') ~ 'Mavericks,
</code>```

Title: Replace strings with longest string in group

Body:
df <- df %>%
  mutate(team_full = case_when(
     team == 'Cavs' ~ 'Cavaliers',
     team == 'Mavs' ~ 'Mavericks',
     TRUE ~ team))

*Note the lists can be more inclusive for multiple values like...

team %in% c('Mavs', 'mavs', 'Mavrix') ~ 'Mavericks,


问:
Query for text and return corresponding value, within a date range
Working on moving an excel sheet to google sheets.
One of the areas I have working quite nicely in excel is finding a paycheck value out of a list of transactions.
The transactions list is a running sheet from 2018.  The current tab has cells A1 and A2 specifying the beginning and end days, ie 7/1/19 7/31/19.
The formula takes those two dates and searches for the keywords, returns the first, second or third instance (for this formula it's the first)

Trying to figure out how to best move this type of query over to google sheets.
Any advise?

```<code>=IFERROR(INDEX([Transactions.xlsx]Transactions!$D$2:$D$8996,SMALL(IF(([Transactions.xlsx]Transactions!$B$2:$B$8996="DFAS-CLEVELAND   FED SALARY ***********xxxx")+([Transactions.xlsx]Transactions!$A$2:$A$8996>=$A$1)+([Transactions.xlsx]Transactions!$A$2:$A$8996<=$A$2)=3,ROW([Transactions.xlsx]Transactions!$B$2:$B$8996)-ROW(INDEX([Transactions.xlsx]Transactions!$B$2:$B$8996,1,1))+1),1)),"None")
</code>```

答:
try something like:</p>

```<code>=QUERY(2018!A:B,
 "select B
  where A >= date '"&TEXT(A1, "yyyy-mm-dd")&"'
    and A <= date '"&TEXT(A2, "yyyy-mm-dd")&"'
  limit 3", 0)
</code>```

Body:
Working on moving an excel sheet to google sheets.
One of the areas I have working quite nicely in excel is finding a paycheck value out of a list of transactions.
The transactions list is a running sheet from 2018.  The current tab has cells A1 and A2 specifying the beginning and end days, ie 7/1/19 7/31/19.
The formula takes those two dates and searches for the keywords, returns the first, second or third instance (for this formula it's the first)

Trying to figure out how to best move this type of query over to google sheets.
Any advise?

=IFERROR(INDEX([Transactions.xlsx]Transactions!$D$2:$D$8996,SMALL(IF(([Transactions.xlsx]Transactions!$B$2:$B$8996="DFAS-CLEVELAND   FED SALARY ***********xxxx")+([Transactions.xlsx]Transactions!$A$2:$A$8996>=$A$1)+([Transactions.xlsx]Transactions!$A$2:$A$8996<=$A$2)=3,ROW([Transactions.xlsx]Transactions!$B$2:$B$8996)-ROW(INDEX([Transactions.xlsx]Transactions!$B$2:$B$8996,1,1))+1),1)),"None")

Body:
try something like:

=QUERY(2018!A:B,
 "select B
  where A >= date '"&TEXT(A1, "yyyy-mm-dd")&"'
    and A <= date '"&TEXT(A2, "yyyy-mm-dd")&"'
  limit 3", 0)


问:
How can I compile c++ to multiple files?
I have a program (cpp) with many classes. Every class is in separate source file (.h + .cpp).

How can I split the compiled program into multiple files (instead of one big executable file)?

Let's say, one file for every class (same as the code structure).

So that every time there is change in a specific class, I compile only that class, and replace the specific compiled file related to that class.

(Something similar to .DLL files in Windows.)

Example from real life:

I am making TUI interface for managing mysql.

I would like to create mysql text editor (TUI) with ncurses.

the code (class) for creating and managing single window object is in
'textWin.cpp' + 'textWin.h'

the code (class) for managing multiple windows, by creating windows objects from previous class is in winMan.cpp winMan.h

the code (class) for managing mysql database is in :
mysql.cpp mysql.h

and so on...

so, I have the following files:

MyProgram.cpp

- winMan.cpp + winMan.h

- textWin.cpp + textWin.h

- mysql.cpp + mysql.h

- ..

- ..

After g++ compilation, I get one executable file, './MyProgram' (size about 15Mb.) which I deliver to all my customers (1000's of them).

I Just found a typo in textWin.cpp, I fixed it, and I told to all customers that there is an update... all of them need to download one big 15Mb file, this consumes allot of bandwidth and server resources, for just a small update.

Is there a way to send to all my customers smaller file, that contains only the compiled code for textWin class ?

I use g++ on Centos7

答:
As suggested in the comments by @RSahu

Shared Libraries (.so files) is the way to split your compiled code.

here is a small example:

https://www.cprogramming.com/tutorial/shared-libraries-linux-gcc.html


问:
Query for similar phrases
Is there any way to match 'United States of America' with 'United States' in SQL?

I have the country with the name 'United States' stored in the database.
The query below should retrieve the item from the database with the name 'United States'.

```<code>SELECT * FROM `countries` WHERE `name` LIKE '%United States of America%'
</code>```

Thank you!

答:
For this case, you should look into an elastic search database. It has the functionality for partial filters.

Otherwise you could do the following via dynamic sql:

Split the string by spaces/delimiter

Using joins, (1 is match, 0 is not match) for a given word

Total the number of matches (you can pivot or target the columns via a sum operand, but its probably simpler to just sum the values in the target named columns since you're already going to use dynamic sql)

if the total number of matches = word count, you have an absolute match (100% match, possible mis-order)

For non-absolute matches, calculate the certainty by dividing the sum / number of words (absolute is 100%)

Select the top (1) for this list, group by the original word, and order by the certainty.

Alternatively, you can do a what @Gordon said for a simpler, one time solution

Title: Query for similar phrases

Body:
Is there any way to match 'United States of America' with 'United States' in SQL?

I have the country with the name 'United States' stored in the database.
The query below should retrieve the item from the database with the name 'United States'.

SELECT * FROM `countries` WHERE `name` LIKE '%United States of America%'

Thank you!


问:
Optimizing R objective function with Rcpp slower, why?
I am currently working on a Bayesian method that requires multiple steps of optimisation of a multinomial logit model per iteration. I am using optim() to perform those optimisations, and an objective function written in R. A profiling revealed that optim() is the main bottleneck.

After digging around, I found this question in which they suggest that recoding the objective function with Rcpp could speed up the process. I followed the suggestion and recoded my objective function with Rcpp, but it ended up being slower (about two times slower!).

This was my first time with Rcpp (or anything related to C++) and I was not able to find a way of vectorising the code. Any idea how to make it faster?

Tl;dr: Current implementation of function in Rcpp is not as fast as vectorised R; how to make it faster?

A reproducible example:

Define objective functions in R and Rcpp: log-likelihood of an intercept only multinomial model

```<code>library(Rcpp)
library(microbenchmark)

llmnl_int <- function(beta, Obs, n_cat) {
  n_Obs     <- length(Obs)
  Xint      <- matrix(c(0, beta), byrow = T, ncol = n_cat, nrow = n_Obs)
  ind       <- cbind(c(1:n_Obs), Obs)
  Xby       <- Xint[ind]
  Xint      <- exp(Xint)
  iota      <- c(rep(1, (n_cat)))
  denom     <- log(Xint %*% iota)
  return(sum(Xby - denom))
}

cppFunction('double llmnl_int_C(NumericVector beta, NumericVector Obs, int n_cat) {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };

    NumericVector Xby = (n_Obs);
    NumericMatrix Xint(n_Obs, n_cat);
    NumericVector denom = (n_Obs);
    for (int i = 0; i < Xby.size(); i++) {
        Xint(i,_) = betas;
        Xby[i] = Xint(i,Obs[i]-1.0);
        Xint(i,_) = exp(Xint(i,_));
        denom[i] = log(sum(Xint(i,_)));
    };

    return sum(Xby - denom);
}')

</code>```

Compare their efficiency:

```<code>## Draw sample from a multinomial distribution
set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

## Benchmarking
microbenchmark("llmml_int" = llmnl_int(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               "llmml_int_C" = llmnl_int_C(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               times = 100)
## Results
# Unit: microseconds
#         expr     min       lq     mean   median       uq     max neval
#    llmnl_int  76.809  78.6615  81.9677  79.7485  82.8495 124.295   100
#  llmnl_int_C 155.405 157.7790 161.7677 159.2200 161.5805 201.655   100

</code>```

Now calling them in optim:

```<code>## Benchmarking with optim
microbenchmark("llmnl_int" = optim(c(4,2,1), llmnl_int, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               "llmnl_int_C" = optim(c(4,2,1), llmnl_int_C, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               times = 100)
## Results
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval
#    llmnl_int 12.49163 13.26338 15.74517 14.12413 18.35461 26.58235   100
#  llmnl_int_C 25.57419 25.97413 28.05984 26.34231 30.44012 37.13442   100

</code>```

I was somewhat surprised that the vectorised implementation in R was faster. Implementing a more efficient version in Rcpp (say, with RcppArmadillo?) can produce any gains? Is it a better idea to recode everything in Rcpp using a C++ optimiser?

答:
I can think of four potential optimizations over Ralf's and Olivers answers.

(You should accept their answers, but I just wanted to add my 2 cents).

1) Use // [[Rcpp::export(rng = false)]] as a comment header to the function in a seperate C++ file.  This leads to a ~80% speed up on my machine.  (This is the most important suggestion out of the 4).

2) Prefer cmath when possible. (In this case, it doesn't seem to make a difference).

3) Avoid allocation whenever possible, e.g. don't shift beta into a new vector.

4) Stretch goal: use SEXP parameters rather than Rcpp vectors.  (Left as an exercise to the reader).  Rcpp vectors are very thin wrappers, but they're still wrappers and there is a small overhead.

These suggestions wouldn't be important, if not for the fact that you're calling the function in a tight loop in optim.  So any overhead is very important.

Bench:

```<code>microbenchmark("llmnl_int_R_v1" = optim(beta, llmnl_int, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_R_v2" = optim(beta, llmnl_int_R_v2, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v2" = optim(beta, llmnl_int_C_v2, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v3" = optim(beta, llmnl_int_C_v3, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v4" = optim(beta, llmnl_int_C_v4, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             times = 1000)

Unit: microseconds
expr      min         lq       mean     median         uq        max neval cld
llmnl_int_R_v1 9480.780 10662.3530 14126.6399 11359.8460 18505.6280 146823.430  1000   c
llmnl_int_R_v2  697.276   735.7735  1015.8217   768.5735   810.6235  11095.924  1000  b
llmnl_int_C_v2  997.828  1021.4720  1106.0968  1031.7905  1078.2835  11222.803  1000  b
llmnl_int_C_v3  284.519   295.7825   328.5890   304.0325   328.2015   9647.417  1000 a
llmnl_int_C_v4  245.650   256.9760   283.9071   266.3985   299.2090   1156.448  1000 a
</code>```

v3 is Oliver's answer with rng=false.  v4 is with Suggestions #2 and #3 included.

The function:

```<code>#include <Rcpp.h>
#include <cmath>
using namespace Rcpp;

// [[Rcpp::export(rng = false)]]
double llmnl_int_C_v4(NumericVector beta, IntegerVector Obs, int n_cat) {

  int n_Obs = Obs.size();
  //2: Calculate log sum only once:
  // double expBetas_log_sum = log(sum(exp(betas)));
  double expBetas_log_sum = 1.0; // std::exp(0)
  for (int i = 1; i < n_cat; i++) {
    expBetas_log_sum += std::exp(beta[i-1]);
  };
  expBetas_log_sum = std::log(expBetas_log_sum);

  double ll_sum = 0;
  //3: Use n_Obs, to avoid calling Xby.size() every time
  for (int i = 0; i < n_Obs; i++) {
    if(Obs[i] == 1L) continue;
    ll_sum += beta[Obs[i]-2L];
  };
  //4: Use that we know denom is the same for all I:
  ll_sum = ll_sum - expBetas_log_sum * n_Obs;
  return ll_sum;
}
</code>```

Body:
I am currently working on a Bayesian method that requires multiple steps of optimisation of a multinomial logit model per iteration. I am using optim() to perform those optimisations, and an objective function written in R. A profiling revealed that optim() is the main bottleneck.

After digging around, I found this question in which they suggest that recoding the objective function with Rcpp could speed up the process. I followed the suggestion and recoded my objective function with Rcpp, but it ended up being slower (about two times slower!).

This was my first time with Rcpp (or anything related to C++) and I was not able to find a way of vectorising the code. Any idea how to make it faster?

Tl;dr: Current implementation of function in Rcpp is not as fast as vectorised R; how to make it faster?

A reproducible example:

Define objective functions in R and Rcpp: log-likelihood of an intercept only multinomial model

library(Rcpp)
library(microbenchmark)

llmnl_int <- function(beta, Obs, n_cat) {
  n_Obs     <- length(Obs)
  Xint      <- matrix(c(0, beta), byrow = T, ncol = n_cat, nrow = n_Obs)
  ind       <- cbind(c(1:n_Obs), Obs)
  Xby       <- Xint[ind]
  Xint      <- exp(Xint)
  iota      <- c(rep(1, (n_cat)))
  denom     <- log(Xint %*% iota)
  return(sum(Xby - denom))
}

cppFunction('double llmnl_int_C(NumericVector beta, NumericVector Obs, int n_cat) {

    int n_Obs = Obs.size();

    NumericVector betas = (beta.size()+1);
    for (int i = 1; i < n_cat; i++) {
        betas[i] = beta[i-1];
    };

    NumericVector Xby = (n_Obs);
    NumericMatrix Xint(n_Obs, n_cat);
    NumericVector denom = (n_Obs);
    for (int i = 0; i < Xby.size(); i++) {
        Xint(i,_) = betas;
        Xby[i] = Xint(i,Obs[i]-1.0);
        Xint(i,_) = exp(Xint(i,_));
        denom[i] = log(sum(Xint(i,_)));
    };

    return sum(Xby - denom);
}')

Compare their efficiency:

## Draw sample from a multinomial distribution
set.seed(2020)
mnl_sample <- t(rmultinom(n = 1000,size = 1,prob = c(0.3, 0.4, 0.2, 0.1)))
mnl_sample <- apply(mnl_sample,1,function(r) which(r == 1))

## Benchmarking
microbenchmark("llmml_int" = llmnl_int(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               "llmml_int_C" = llmnl_int_C(beta = c(4,2,1), Obs = mnl_sample, n_cat = 4),
               times = 100)
## Results
# Unit: microseconds
#         expr     min       lq     mean   median       uq     max neval
#    llmnl_int  76.809  78.6615  81.9677  79.7485  82.8495 124.295   100
#  llmnl_int_C 155.405 157.7790 161.7677 159.2200 161.5805 201.655   100

Now calling them in optim:

## Benchmarking with optim
microbenchmark("llmnl_int" = optim(c(4,2,1), llmnl_int, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               "llmnl_int_C" = optim(c(4,2,1), llmnl_int_C, Obs = mnl_sample, n_cat = 4, method = "BFGS", hessian = T, control = list(fnscale = -1)),
               times = 100)
## Results
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval
#    llmnl_int 12.49163 13.26338 15.74517 14.12413 18.35461 26.58235   100
#  llmnl_int_C 25.57419 25.97413 28.05984 26.34231 30.44012 37.13442   100

I was somewhat surprised that the vectorised implementation in R was faster. Implementing a more efficient version in Rcpp (say, with RcppArmadillo?) can produce any gains? Is it a better idea to recode everything in Rcpp using a C++ optimiser?

Body:
I can think of four potential optimizations over Ralf's and Olivers answers.

(You should accept their answers, but I just wanted to add my 2 cents).

1) Use // [[Rcpp::export(rng = false)]] as a comment header to the function in a seperate C++ file.  This leads to a ~80% speed up on my machine.  (This is the most important suggestion out of the 4).

2) Prefer cmath when possible. (In this case, it doesn't seem to make a difference).

3) Avoid allocation whenever possible, e.g. don't shift beta into a new vector.

4) Stretch goal: use SEXP parameters rather than Rcpp vectors.  (Left as an exercise to the reader).  Rcpp vectors are very thin wrappers, but they're still wrappers and there is a small overhead.

These suggestions wouldn't be important, if not for the fact that you're calling the function in a tight loop in optim.  So any overhead is very important.

Bench:

microbenchmark("llmnl_int_R_v1" = optim(beta, llmnl_int, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_R_v2" = optim(beta, llmnl_int_R_v2, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v2" = optim(beta, llmnl_int_C_v2, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v3" = optim(beta, llmnl_int_C_v3, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             "llmnl_int_C_v4" = optim(beta, llmnl_int_C_v4, Obs = mnl_sample,
                                      n_cat = n_cat, method = "BFGS", hessian = F,
                                      control = list(fnscale = -1)),
             times = 1000)

Unit: microseconds
expr      min         lq       mean     median         uq        max neval cld
llmnl_int_R_v1 9480.780 10662.3530 14126.6399 11359.8460 18505.6280 146823.430  1000   c
llmnl_int_R_v2  697.276   735.7735  1015.8217   768.5735   810.6235  11095.924  1000  b
llmnl_int_C_v2  997.828  1021.4720  1106.0968  1031.7905  1078.2835  11222.803  1000  b
llmnl_int_C_v3  284.519   295.7825   328.5890   304.0325   328.2015   9647.417  1000 a
llmnl_int_C_v4  245.650   256.9760   283.9071   266.3985   299.2090   1156.448  1000 a

v3 is Oliver's answer with rng=false.  v4 is with Suggestions #2 and #3 included.

The function:

#include <Rcpp.h>
#include <cmath>
using namespace Rcpp;

// [[Rcpp::export(rng = false)]]
double llmnl_int_C_v4(NumericVector beta, IntegerVector Obs, int n_cat) {

  int n_Obs = Obs.size();
  //2: Calculate log sum only once:
  // double expBetas_log_sum = log(sum(exp(betas)));
  double expBetas_log_sum = 1.0; // std::exp(0)
  for (int i = 1; i < n_cat; i++) {
    expBetas_log_sum += std::exp(beta[i-1]);
  };
  expBetas_log_sum = std::log(expBetas_log_sum);

  double ll_sum = 0;
  //3: Use n_Obs, to avoid calling Xby.size() every time
  for (int i = 0; i < n_Obs; i++) {
    if(Obs[i] == 1L) continue;
    ll_sum += beta[Obs[i]-2L];
  };
  //4: Use that we know denom is the same for all I:
  ll_sum = ll_sum - expBetas_log_sum * n_Obs;
  return ll_sum;
}


问:
MS Access Dropdown List/Combo Box
This should probably be pretty simple but my Google-Fu is as yet unable to find an answer. I simply want to create a dropdown list in Access so that upon selection I can perform some action based on the value of the selection. For instance, I have a list of people and I would like to populate the combo box so that their names appear in the list but the "value" is set to their ID (the primary key).</p>

答: It sounds like you might be asking how to display something in the dropdown other than the ID while keeping the ID as the returned data from the dropdown. If that's the case set the Bound Column to the ID field (usually 1) and (assuming the name field is next) set the Column Count to be 2 and the Column Widths to be 0";1" or 0";[whatever width you need]. </p>

OwnerDisplayName: noblethrasher

ContentLicense: CC BY-SA 2.5

Title: MS Access Dropdown List/Combo Box

LastEditorDisplayName: Chris Ballance

OwnerDisplayName: Scott Konkle


问:
How to use UTF-8 in resource properties with ResourceBundle
I need to use UTF-8 in my resource properties using Java's ResourceBundle. When I enter the text directly into the properties file, it displays as mojibake.

My app runs on Google App Engine.

Can anyone give me an example? I can't get this work.

答:
```<code>package com.varaneckas.utils;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * UTF-8 friendly ResourceBundle support
 *
 * Utility that allows having multi-byte characters inside java .property files.
 * It removes the need for Sun's native2ascii application, you can simply have
 * UTF-8 encoded editable .property files.
 *
 * Use:
 * ResourceBundle bundle = Utf8ResourceBundle.getBundle("bundle_name");
 *
 * @author Tomas Varaneckas <tomas.varaneckas@gmail.com>
 */
public abstract class Utf8ResourceBundle {

    /**
     * Gets the unicode friendly resource bundle
     *
     * @param baseName
     * @see ResourceBundle#getBundle(String)
     * @return Unicode friendly resource bundle
     */
    public static final ResourceBundle getBundle(final String baseName) {
        return createUtf8PropertyResourceBundle(
                ResourceBundle.getBundle(baseName));
    }

    /**
     * Creates unicode friendly {@link PropertyResourceBundle} if possible.
     *
     * @param bundle
     * @return Unicode friendly property resource bundle
     */
    private static ResourceBundle createUtf8PropertyResourceBundle(
            final ResourceBundle bundle) {
        if (!(bundle instanceof PropertyResourceBundle)) {
            return bundle;
        }
        return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);
    }

    /**
     * Resource Bundle that does the hard work
     */
    private static class Utf8PropertyResourceBundle extends ResourceBundle {

        /**
         * Bundle with unicode data
         */
        private final PropertyResourceBundle bundle;

        /**
         * Initializing constructor
         *
         * @param bundle
         */
        private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {
            this.bundle = bundle;
        }

        @Override
        @SuppressWarnings("unchecked")
        public Enumeration getKeys() {
            return bundle.getKeys();
        }

        @Override
        protected Object handleGetObject(final String key) {
            final String value = bundle.getString(key);
            if (value == null)
                return null;
            try {
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");
            } catch (final UnsupportedEncodingException e) {
                throw new RuntimeException("Encoding not supported", e);
            }
        }
    }
}
</code>```


问:
SQLAlchemy .contains case insensitive and_ query
I am currently trying to get a query to work as case insensitive.  The query currently works as case sensitive like this:

```<code>and_(db.data.contains({'collections': [{'idType': id_type, 'InternalId': internal_id}]}))
</code>```

The goal of this is to create N number of search filters to query against the DB.  This one being a check for a certain collection containing the data provided to the function.  When I have tried ilike or func.lower inside the contains it gives me the error of keys must be str, int, float, bool or None, not Function sqlalchemy or similar.  There also does not seem to be a .icontains function and all the similar .filter stackoverflow questions don't fit with my problem.

My question is:  Can the .contains check the db for values regardless of case. so that querying for

```<code>{'collections': [{'idType': 'Foo', 'InternalId': 'Bar'}]}
</code>```

would return any DB values with a collection.idType of (Foo, FOO, foo, etc) and a collection.externalId of (Bar, BAR, bar, etc)

答:
The solution is to unnest the array using json(b)_array_elements and then use an EXISTS subquery expression. Given a model

```<code>class Foo(Base):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    data = Column(JSONB)
</code>```

and

```<code>session.add(Foo(data={'collections': [{'idType': 'Foo', 'InternalId': 'Bar'}]}))
session.commit()
</code>```

The query would be

```<code>from sqlalchemy import column, exists, func

cs = func.jsonb_array_elements(Foo.data["collections"]).alias("cs")
id_type = column("cs", type_=JSONB)["idType"].astext
internal_id = column("cs", type_=JSONB)["InternalId"].astext

session.query(Foo).\
    filter(exists().select_from(cs).where(and_(
        func.lower(id_type) == "foo",
        func.lower(internal_id) == "bar"))).\
    all()
</code>```

The same in raw SQL is a bit more easier on the eyes in this case:

SELECT *
FROM foo
WHERE EXISTS (
    SELECT *
    FROM jsonb_array_elements(foo.data -> 'collections') cs
    WHERE lower(cs ->> 'idType') = 'foo'
      AND lower(cs ->> 'InternalId') = 'bar'
)
```

Body:
I am currently trying to get a query to work as case insensitive.  The query currently works as case sensitive like this:

and_(db.data.contains({'collections': [{'idType': id_type, 'InternalId': internal_id}]}))

The goal of this is to create N number of search filters to query against the DB.  This one being a check for a certain collection containing the data provided to the function.  When I have tried ilike or func.lower inside the contains it gives me the error of keys must be str, int, float, bool or None, not Function sqlalchemy or similar.  There also does not seem to be a .icontains function and all the similar .filter stackoverflow questions don't fit with my problem.

My question is:  Can the .contains check the db for values regardless of case. so that querying for

{'collections': [{'idType': 'Foo', 'InternalId': 'Bar'}]}

would return any DB values with a collection.idType of (Foo, FOO, foo, etc) and a collection.externalId of (Bar, BAR, bar, etc)

Body:
The solution is to unnest the array using json(b)_array_elements and then use an EXISTS subquery expression. Given a model

class Foo(Base):
    __tablename__ = 'foo'
    id = Column(Integer, primary_key=True)
    data = Column(JSONB)

and

session.add(Foo(data={'collections': [{'idType': 'Foo', 'InternalId': 'Bar'}]}))
session.commit()

The query would be

from sqlalchemy import column, exists, func

cs = func.jsonb_array_elements(Foo.data["collections"]).alias("cs")
id_type = column("cs", type_=JSONB)["idType"].astext
internal_id = column("cs", type_=JSONB)["InternalId"].astext

session.query(Foo).\
    filter(exists().select_from(cs).where(and_(
        func.lower(id_type) == "foo",
        func.lower(internal_id) == "bar"))).\
    all()

The same in raw SQL is a bit more easier on the eyes in this case:

SELECT *
FROM foo
WHERE EXISTS (
    SELECT *
    FROM jsonb_array_elements(foo.data -> 'collections') cs
    WHERE lower(cs ->> 'idType') = 'foo'
      AND lower(cs ->> 'InternalId') = 'bar'
)


问:
Query other fields in tables referenced by FK in junction table
I have a "junction" table (recipe_ingredients) that I'm using to handle a many-to-many relationship in my database. Each field in that table is a reference to the PK of another table: recipe_id, ingredient_id, quantity_id, and measure_id. These are the PKs of the metadata, ingredients, quantities, and measurements tables. With the exception of the metadata table, all these tables have only two fields: the PK, and a name or number associated with that PK.

I'm trying to query recipe_ingredients for all rows that have a given recipe_id... but instead of displaying the PKs in each row with that recipe_id, I want to display the name/number associated with that PK in that table.

So instead of a query that returns this:

```<code>recipe_id | ingredient_id | quantity_id | measure_id
----------+---------------+-------------+-----------
1         | 10            | 2           | 3
----------+---------------+-------------+-----------
1         | 12            | 2           | 3
----------+---------------+-------------+-----------
1         | 13            | 5           | 6
----------+---------------+-------------+-----------
...
</code>```

I'm looking for a query that returns something like this:

```<code>recipe_id | ingredient_name | quantity_num | measure_num
----------+-----------------+--------------+------------
1         | Ground cayenne  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Ground paprika  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Olive oil       | 1            | tbsp
----------+-----------------+--------------+------------
...
</code>```

I just started learning SQL, so I only know how to make simple queries to a single table. I don't even know where to begin with this query, except that I may need a kind of join statement. What query could I write to achieve this?

I'm using sqlite3 on Debian.

The recipe_ingredients "junction" table:

```<code>CREATE TABLE recipe_ingredients (
    recipe_id               int,
    ingredient_id           int,
    quantity_id             int,
    measure_id              int,
    primary key (recipe_id, ingredient_id),
    foreign key (recipe_id)
            references metadata (recipe_id)
                    on update restrict
                    on delete restrict,
    foreign key (ingredient_id)
            references ingredients (ingredient_id)
                    on update restrict
                    on delete restrict,
    foreign key (quantity_id)
            references quantities (quantity_id)
                    on update restrict
                    on delete restrict,
    foreign key (measure_id)
            references measurements (measure_id)
                    on update restrict
                    on delete restrict
);
</code>```

These are the foreign tables referenced by the junction table:

```<code>create table if not exists ingredients (
    ingredient_id           integer         primary key,
    ingredient_name         text            not null
);

create table if not exists quantities (
    quantity_id             integer         primary key,
    quantity_num            int             not null
);

create table if not exists measurements (
    measure_id              integer         primary key,
    measure_name            text            not null
);

create table if not exists metadata (
    recipe_id               integer         primary key,
    recipe_name             text            not null,
    course_id               int,
    cuisine_id              int,
    servings                int,
    prep_time               int,
    cook_time               int,
    total_time              int,
    foreign key (course_id)
            references courses (course_id)
                    on update restrict
                    on delete restrict,
    foreign key (cuisine_id)
            references cuisine (cuisine_id)
                    on update cascade
                    on delete cascade
);
</code>```

答:
You can join the junction table with each of the related tables like so:

```<code>select
    ri.recipe_id,
    i.ingredient_name,
    q.quantity_num,
    m.measure_num
from recipe_ingredients ri
inner join ingredients i  on i.ingredient_id = ri.ingredient_id
inner join quantities q   on q.quantity_id = ri.quantity_id
inner noin measurements m on m.measure_id = ri.measure_id
where ri.recipe_id = ?
</code>```

The question mark (?) stands for the recipe_id that you are looking for.

Body:
I have a "junction" table (recipe_ingredients) that I'm using to handle a many-to-many relationship in my database. Each field in that table is a reference to the PK of another table: recipe_id, ingredient_id, quantity_id, and measure_id. These are the PKs of the metadata, ingredients, quantities, and measurements tables. With the exception of the metadata table, all these tables have only two fields: the PK, and a name or number associated with that PK.

I'm trying to query recipe_ingredients for all rows that have a given recipe_id... but instead of displaying the PKs in each row with that recipe_id, I want to display the name/number associated with that PK in that table.

So instead of a query that returns this:

recipe_id | ingredient_id | quantity_id | measure_id
----------+---------------+-------------+-----------
1         | 10            | 2           | 3
----------+---------------+-------------+-----------
1         | 12            | 2           | 3
----------+---------------+-------------+-----------
1         | 13            | 5           | 6
----------+---------------+-------------+-----------
...

I'm looking for a query that returns something like this:

recipe_id | ingredient_name | quantity_num | measure_num
----------+-----------------+--------------+------------
1         | Ground cayenne  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Ground paprika  | 1/2          | tsp
----------+-----------------+--------------+------------
1         | Olive oil       | 1            | tbsp
----------+-----------------+--------------+------------
...

I just started learning SQL, so I only know how to make simple queries to a single table. I don't even know where to begin with this query, except that I may need a kind of join statement. What query could I write to achieve this?

I'm using sqlite3 on Debian.

The recipe_ingredients "junction" table:

CREATE TABLE recipe_ingredients (
    recipe_id               int,
    ingredient_id           int,
    quantity_id             int,
    measure_id              int,
    primary key (recipe_id, ingredient_id),
    foreign key (recipe_id)
            references metadata (recipe_id)
                    on update restrict
                    on delete restrict,
    foreign key (ingredient_id)
            references ingredients (ingredient_id)
                    on update restrict
                    on delete restrict,
    foreign key (quantity_id)
            references quantities (quantity_id)
                    on update restrict
                    on delete restrict,
    foreign key (measure_id)
            references measurements (measure_id)
                    on update restrict
                    on delete restrict
);

These are the foreign tables referenced by the junction table:

create table if not exists ingredients (
    ingredient_id           integer         primary key,
    ingredient_name         text            not null
);

create table if not exists quantities (
    quantity_id             integer         primary key,
    quantity_num            int             not null
);

create table if not exists measurements (
    measure_id              integer         primary key,
    measure_name            text            not null
);

create table if not exists metadata (
    recipe_id               integer         primary key,
    recipe_name             text            not null,
    course_id               int,
    cuisine_id              int,
    servings                int,
    prep_time               int,
    cook_time               int,
    total_time              int,
    foreign key (course_id)
            references courses (course_id)
                    on update restrict
                    on delete restrict,
    foreign key (cuisine_id)
            references cuisine (cuisine_id)
                    on update cascade
                    on delete cascade
);

Body:
You can join the junction table with each of the related tables like so:

select
    ri.recipe_id,
    i.ingredient_name,
    q.quantity_num,
    m.measure_num
from recipe_ingredients ri
inner join ingredients i  on i.ingredient_id = ri.ingredient_id
inner join quantities q   on q.quantity_id = ri.quantity_id
inner noin measurements m on m.measure_id = ri.measure_id
where ri.recipe_id = ?

The question mark (?) stands for the recipe_id that you are looking for.


问:
Excel VBA Textfile to 2d array
I am new to excel vba. I want to read a textfile that contains text like this:

```<code>John Smith Engineer Chicago
Bob Alice Doctor New York
Jane Smith Teacher St. Louis
</code>```

So, I want to convert this into a 2D array so if I do print(3,3), it should return 'Teacher'.
I am able to read entire file contents into one string but am having difficulty in converting it to
a 2d array like above. Please advice on how to proceed. Thanks

答:
unless the text file has some specific structure to it, you're going to struggle a bit. Things that might make it easier are:

Does the text file contain line breaks at the end of each line?

Are all the names in [FirstName][LastName] format as per your example
or might some have more/less words?

Does the Occupation always come directly after the name?

Are there a (very) limited number of Occupations?

Title: Excel VBA Textfile to 2d array

Body:
I am new to excel vba. I want to read a textfile that contains text like this:

John Smith Engineer Chicago
Bob Alice Doctor New York
Jane Smith Teacher St. Louis

So, I want to convert this into a 2D array so if I do print(3,3), it should return 'Teacher'.
I am able to read entire file contents into one string but am having difficulty in converting it to
a 2d array like above. Please advice on how to proceed. Thanks


问:
React TS - Can you assign default values to a map()?
I currently have a component that maps through an array of data. I'd like to be able to set default values for some of the attributes.

My current Link component:

```<code>const Link: React.FC<ILink> = ({ icons }) => {
  return (
    <div>
      {icons.map(item => (
        <a href={item.href} target={item.target} rel={item.rel}>
          {/* Some element */}
        </a>
      ))}
    </div>
  );
};
</code>```

Typically using TypeScript, I would destructure the props like so, and then add my defaults:

```<code>const Link: React.FC<ILink> = ({
  href,
  target = "_blank",
  rel = "noreferrer noopener"
}) => {}
</code>```

How can I do this for my map though?

答:
You can destructure and assign defaults the same way in your map callback:

```<code>const Link: React.FC<ILink> = ({ icons }) => {
  return (
    <div>
      {icons.map(({ href, target = "_blank", rel = "noreferrer noopener" }) => (
        <a href={href} target={target} rel={rel}>
          {/* Some element */}
        </a>
      ))}
    </div>
  );
};
</code>```

Alternately, you can simply use the or-operator to define fallbacks inline if you only expect string values to be passed:

```<code>const Link: React.FC<ILink> = ({ icons }) => {
  return (
    <div>
      {icons.map(item => (
        <a href={item.href} target={item.target || "_blank"} rel={item.rel || "noopener noreferrer"}>
          {/* Some element */}
        </a>
      ))}
    </div>
  );
};
</code>```

Body:
I currently have a component that maps through an array of data. I'd like to be able to set default values for some of the attributes.

My current Link component:

const Link: React.FC<ILink> = ({ icons }) => {
  return (

      {icons.map(item => (

          {/* Some element */}

      ))}

  );
};

Typically using TypeScript, I would destructure the props like so, and then add my defaults:

const Link: React.FC<ILink> = ({
  href,
  target = "_blank",
  rel = "noreferrer noopener"
}) => {}

How can I do this for my map though?

Body:
You can destructure and assign defaults the same way in your map callback:

const Link: React.FC<ILink> = ({ icons }) => {
  return (
    <div>
      {icons.map(({ href, target = "_blank", rel = "noreferrer noopener" }) => (
        <a href={href} target={target} rel={rel}>
          {/* Some element */}
        </a>
      ))}
    </div>
  );
};

Alternately, you can simply use the or-operator to define fallbacks inline if you only expect string values to be passed:

const Link: React.FC<ILink> = ({ icons }) => {
  return (
    <div>
      {icons.map(item => (
        <a href={item.href} target={item.target || "_blank"} rel={item.rel || "noopener noreferrer"}>
          {/* Some element */}
        </a>
      ))}
    </div>
  );
};


问:
How to see data from .RData file?
I have to load a isfar.RData file to use it in other computation (which are not important to describe here). And I would like to simply see how looks data in this isfar.RData file e.g. what numbers, columns, rows it carries.

First I load my file:

```<code>isfar<-load("C:/Users/isfar.RData")
</code>```

When I try to obtain this information (I'm using Rcmdr) by ls() function or marking isfar at the beginning after loading I get in the output window: [1] "isfar" instead of the table. Why?

Thanks a lot, I appreciate all of the answers! Hope it's comprehensible what I wrote, Im not a native speaker.

答:
If you have a lot of variables in your Rdata file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.

```<code>load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )

# Access individual variables in the RData file using '$' operator
isfar_env$var_name

# List all of the variable names in RData:
ls(isfar_env)
</code>```

Title: How to see data from .RData file?

Body:
I have to load a isfar.RData file to use it in other computation (which are not important to describe here). And I would like to simply see how looks data in this isfar.RData file e.g. what numbers, columns, rows it carries.

First I load my file:

isfar<-load("C:/Users/isfar.RData")

When I try to obtain this information (I'm using Rcmdr) by ls() function or marking isfar at the beginning after loading I get in the output window: [1] "isfar" instead of the table. Why?

Thanks a lot, I appreciate all of the answers! Hope it's comprehensible what I wrote, Im not a native speaker.

Body:
If you have a lot of variables in your Rdata file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.

load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )

# Access individual variables in the RData file using '$' operator
isfar_env$var_name

# List all of the variable names in RData:
ls(isfar_env)


问:
Excel Vlookup Formula
Hello Excel Vlookup Experts,

I am trying to get a VLOOKUP formula to do the following.  Using the columns E, F, and G as references, I am trying to populate data to column C. Column A and B must match column E and F to populate column C.  Notice that column B has hours with the Date.  I just want the data from column C to populate regardless of the hour, if it matches(Column A and B must match column E and F).

End result as shown:

答:
You can try following formulas -

SUMPRODUCT- if combination of Well_Id and Date is unique:

```<code>=SUMPRODUCT((A2=$E$2:$E$21)*(INT(B2)=$F$2:$F$21)*$G$2:$G$21)
</code>```

INDEX/MATCHarray formula - if not unique, it returns first match:

```<code>{=INDEX($G$2:$G$21,MATCH(1,(A2=$E$2:$E$21)*(INT(B2)=$F$2:$F$21),0))}
</code>```

Array formula after editing is confirmed by pressing ctrl + shift + enter

Title: Excel Vlookup Formula

Body:
You can try following formulas -

SUMPRODUCT- if combination of Well_Id and Date is unique:

=SUMPRODUCT((A2=$E$2:$E$21)*(INT(B2)=$F$2:$F$21)*$G$2:$G$21)

INDEX/MATCHarray formula - if not unique, it returns first match:

{=INDEX($G$2:$G$21,MATCH(1,(A2=$E$2:$E$21)*(INT(B2)=$F$2:$F$21),0))}

Array formula after editing is confirmed by pressing ctrl + shift + enter


问:
How do I create Sharebar like this sample URL?
I have to create a social sharing sidebar similar to this website. Can you suggest how it can be implemented? using Jquery OR anything?

ref. this page, http://www.chow.com/recipes/25677-beef-kalbi

look at the left side SHARE BAR

答: Look at the APIs for each site you want to deal with, then write code to talk to that API, then link that code to some buttons that you arrange with CSS.</p>


问:
Add ACF admin column to custom post type
I'm trying to add a new admin column to my custom post type using the content of a custom field (ACF). The field I want to add is a 'post object' field, but it just displays the post title instead of the linked post from the ACF. I added a screenshot.

This is what I have so far:

```<code>function add_new_realisaties_column($columns) {
    $columns['realisatie_line'] = 'Line';
    return $columns;
}
add_filter('manage_realisaties_posts_columns', 'add_new_realisaties_column');

function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
if ($column == 'realisatie_line') {
    $post_object = get_field('realisatie_line');

    if( $post_object ):
        // override $post
        $post = $post_object;
        setup_postdata( $post );

        $evdate = the_title();

        wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;

    echo $evdate;
    }
}
add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);

/* Make the column sortable */
function set_custom_realisaties_sortable_columns( $columns ) {
    $columns['realisatie_line'] = 'realisatie_line';
    return $columns;
}
add_filter( 'manage_edit-realisaties_sortable_columns', 'set_custom_realisaties_sortable_columns' );

function realisaties_custom_orderby( $query ) {
    if ( ! is_admin() )
        return;
        $orderby = $query->get('orderby');

        if ( 'realisatie_line' == $orderby ) {
            $query->set( 'meta_key', 'realisatie_line' );
            $query->set( 'orderby', 'meta_value' );
        }
    }
add_action( 'pre_get_posts', 'realisaties_custom_orderby' );
</code>```

答:
Try changing your add_new_realisaties_admin_column_show_value function to the code below. If the ACF field name is realisatie_line you are going to need to also pass a $post_id to get the specific meta data back for each particular post.

```<code>function add_new_realisaties_admin_column_show_value( $column, $post_id ) {

    //Try using a switch/case for the column name
    switch ( $column ) {
       case 'realisatie_line': //Name of new column from add_new_realisaties_column function
          echo get_the_title( get_post_meta( $post_id, 'realisatie_line', true ) ); //Getting the ACF post meta using the $post_id, passing it through the get_the_title function to get title of attached post
          break;

       default:
          break;

    }
}
</code>```

Body:
I'm trying to add a new admin column to my custom post type using the content of a custom field (ACF). The field I want to add is a 'post object' field, but it just displays the post title instead of the linked post from the ACF. I added a screenshot.

This is what I have so far:

function add_new_realisaties_column($columns) {
    $columns['realisatie_line'] = 'Line';
    return $columns;
}
add_filter('manage_realisaties_posts_columns', 'add_new_realisaties_column');

function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
if ($column == 'realisatie_line') {
    $post_object = get_field('realisatie_line');

    if( $post_object ):
        // override $post
        $post = $post_object;
        setup_postdata( $post );

        $evdate = the_title();

        wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif;

    echo $evdate;
    }
}
add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);

/* Make the column sortable */
function set_custom_realisaties_sortable_columns( $columns ) {
    $columns['realisatie_line'] = 'realisatie_line';
    return $columns;
}
add_filter( 'manage_edit-realisaties_sortable_columns', 'set_custom_realisaties_sortable_columns' );

function realisaties_custom_orderby( $query ) {
    if ( ! is_admin() )
        return;
        $orderby = $query->get('orderby');

        if ( 'realisatie_line' == $orderby ) {
            $query->set( 'meta_key', 'realisatie_line' );
            $query->set( 'orderby', 'meta_value' );
        }
    }
add_action( 'pre_get_posts', 'realisaties_custom_orderby' );

Body:
Try changing your add_new_realisaties_admin_column_show_value function to the code below. If the ACF field name is realisatie_line you are going to need to also pass a $post_id to get the specific meta data back for each particular post.

function add_new_realisaties_admin_column_show_value( $column, $post_id ) {

    //Try using a switch/case for the column name
    switch ( $column ) {
       case 'realisatie_line': //Name of new column from add_new_realisaties_column function
          echo get_the_title( get_post_meta( $post_id, 'realisatie_line', true ) ); //Getting the ACF post meta using the $post_id, passing it through the get_the_title function to get title of attached post
          break;

       default:
          break;

    }
}


问:
Terraform error "Your query returned no results"
I have below bom-asg.tf file.

```<code>data "aws_ami" "bom-ami" {
most_recent = true

  filter {
    name   = "tag:ami_name"
    values = ["${var.environment}-bom-ami"]
  }

  owners = ["****"]
}

resource "aws_security_group" "bom-sg" {
  name_prefix = "${var.environment}-bom-asg-sg"
  vpc_id      = "${var.vpc_id}"
  .....
</code>```

I am unable to successfully execute refresh and plan commands. I am getting below errors.

```<code>terraform plan --var-file=environment-parity.tfvars -target=bom-asg.tf --out apply.out
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.
</code>```

But when I run refresh. I am getting below error.

```<code>terraform refresh --var-file=environment-parity.tfvars
data.template_file.es_access_policy_search: Refreshing state...
data.aws_ami.nginx-ami: Refreshing state...
data.aws_ami.php-search-ami: Refreshing state...
data.aws_ami.ng-ami: Refreshing state...
data.aws_ami.mysql-ami: Refreshing state...
data.aws_ami.frontend-search-ami: Refreshing state...
data.aws_ami.bom-ami: Refreshing state...
data.aws_ami.lg-ami: Refreshing state...
data.aws_ami.rabbitmq-search-ami: Refreshing state...
data.aws_ami.ngas-ng-drupal-ami: Refreshing state...
data.aws_ami.mongodb-ami: Refreshing state...

Error: Error refreshing state: 1 error(s) occurred:

* data.aws_ami.bom-ami: 1 error(s) occurred:

* data.aws_ami.bom-ami: data.aws_ami.bom-ami: Your query returned no results. Please change your search criteria and try again.
</code>```

Can you please help?

答:
Terraform data source is to access an existing resource, not to create one.

```<code>data "aws_ami" "bom-ami"
</code>```

As in the documentation, the AMI needs to exist already.

Data Source: aws_ami

Use this data source to get the ID of a registered AMI for use in other resources.

If you are creating an AMI from an EBS snapshot taken from an EC2 instance (e.g. Amazon Linux EC2), then:

Resource: aws_ami

Please note the difference between data and resource.

To create a custom AMI image, please also consider Hashicorp packer.

Body:
I have below bom-asg.tf file.

data "aws_ami" "bom-ami" {
most_recent = true

  filter {
    name   = "tag:ami_name"
    values = ["${var.environment}-bom-ami"]
  }

  owners = ["****"]
}

resource "aws_security_group" "bom-sg" {
  name_prefix = "${var.environment}-bom-asg-sg"
  vpc_id      = "${var.vpc_id}"
  .....

I am unable to successfully execute refresh and plan commands. I am getting below errors.

terraform plan --var-file=environment-parity.tfvars -target=bom-asg.tf --out apply.out
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

------------------------------------------------------------------------

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.

But when I run refresh. I am getting below error.

terraform refresh --var-file=environment-parity.tfvars
data.template_file.es_access_policy_search: Refreshing state...
data.aws_ami.nginx-ami: Refreshing state...
data.aws_ami.php-search-ami: Refreshing state...
data.aws_ami.ng-ami: Refreshing state...
data.aws_ami.mysql-ami: Refreshing state...
data.aws_ami.frontend-search-ami: Refreshing state...
data.aws_ami.bom-ami: Refreshing state...
data.aws_ami.lg-ami: Refreshing state...
data.aws_ami.rabbitmq-search-ami: Refreshing state...
data.aws_ami.ngas-ng-drupal-ami: Refreshing state...
data.aws_ami.mongodb-ami: Refreshing state...

Error: Error refreshing state: 1 error(s) occurred:

* data.aws_ami.bom-ami: 1 error(s) occurred:

* data.aws_ami.bom-ami: data.aws_ami.bom-ami: Your query returned no results. Please change your search criteria and try again.

Can you please help?

Body:
Terraform data source is to access an existing resource, not to create one.

data "aws_ami" "bom-ami"

As in the documentation, the AMI needs to exist already.

Data Source: aws_ami

Use this data source to get the ID of a registered AMI for use in other resources.

If you are creating an AMI from an EBS snapshot taken from an EC2 instance (e.g. Amazon Linux EC2), then:

Resource: aws_ami

Please note the difference between data and resource.

To create a custom AMI image, please also consider Hashicorp packer.


问:
Effect Certain Column/column ranges in a VBA Code
I am working on the VBA code down below to change the color of a cell based on the text specified in the certain cell. I have gotten the code to work inside the active sheet, but when I run my code it erases all colors that I had in my original spreadsheet(Not Sure Why). I would like to just apply this code to certain columns in my table.
EX only change the colors for these values in columns P and Y between rows 12- 1000...

Here is the code I am using:

```<code>Sub changeColor()

    Dim itm As Range

    Application.ScreenUpdating = False
    ActiveSheet.UsedRange.Offset(1).Interior.ColorIndex = xlColorIndexNone

    For Each itm In ActiveSheet.UsedRange.Offset(1)
        If Not IsError(itm) Then
            With itm
                Select Case .Value2
                    Case "GREEN", "green", "Green"
                        .Interior.Color = XlRgbColor.rgbLightGreen
                    Case "RED", "red", "Red"
                        .Interior.Color = XlRgbColor.rgbRed
                    Case "Yellow", "yellow", "Yellow"
                        .Interior.Color = XlRgbColor.rgbYellow
                End Select
            End With
        End If
    Next
    Application.ScreenUpdating = True

End Sub
</code>```

答:
@ "but when I run my code it erases all colors that I had in my original spreadsheet(Not Sure Why)."

This line is saying, every cell in the used range, erase that color:

```<code>ActiveSheet.UsedRange.Offset(1).Interior.ColorIndex = xlColorIndexNone
</code>```

Then use what Tim Williams said above in comment, to specify what range of cells to loop through.

Body:
I am working on the VBA code down below to change the color of a cell based on the text specified in the certain cell. I have gotten the code to work inside the active sheet, but when I run my code it erases all colors that I had in my original spreadsheet(Not Sure Why). I would like to just apply this code to certain columns in my table.
EX only change the colors for these values in columns P and Y between rows 12- 1000...

Here is the code I am using:

Sub changeColor()

    Dim itm As Range

    Application.ScreenUpdating = False
    ActiveSheet.UsedRange.Offset(1).Interior.ColorIndex = xlColorIndexNone

    For Each itm In ActiveSheet.UsedRange.Offset(1)
        If Not IsError(itm) Then
            With itm
                Select Case .Value2
                    Case "GREEN", "green", "Green"
                        .Interior.Color = XlRgbColor.rgbLightGreen
                    Case "RED", "red", "Red"
                        .Interior.Color = XlRgbColor.rgbRed
                    Case "Yellow", "yellow", "Yellow"
                        .Interior.Color = XlRgbColor.rgbYellow
                End Select
            End With
        End If
    Next
    Application.ScreenUpdating = True

End Sub

Body:
@ "but when I run my code it erases all colors that I had in my original spreadsheet(Not Sure Why)."

This line is saying, every cell in the used range, erase that color:

ActiveSheet.UsedRange.Offset(1).Interior.ColorIndex = xlColorIndexNone

Then use what Tim Williams said above in comment, to specify what range of cells to loop through.


问:
Requesting for user_friends
How do I show a screencast showing the end to end user experience if I'm requesting for the scope user_friends?

I would like to use scope to allow my game to send and receive diamonds from friends. However, I would need to pull the data, to see which of their friends has already download the game, and to send and request diamonds to each other. Please advise. Thanks!

答:
Found out that I could do so using the test app.
https://developers.facebook.com/docs/apps/test-apps</p>

Title: Requesting for user_friends


问:
Reactjs Router is causing Array to become undefined
So I am trying to fetch JSON data from server running on another port in my pc using axios and renders it on homepage. I want to setup Router to components. But whenever I wrap Router around my components It causes Array recipeslists to become undefined (see below console output) and hence I can not map that Array in my Allrecipes Component But without any Router it works fine.

App.js's code is as follows

import React, { useState , useEffect} from 'react'
import { BrowserRouter as Router, Route } from "react-router-dom"
import "bootstrap/dist/css/bootstrap.min.css"

import Navbar from './components/Navbar'
import Allrecipes from './components/Allrecipes'
import Createrecipe from './components/Createrecipe'
import axios from 'axios'

const App = () => {
    const [recipeslists,setRecipes] = useState([])
    const [filterRecipe,setFilterRecipe] = useState([])
    const [search,setSearch] = useState('')
    console.log("in app")

    useEffect(()=>{
        console.log("useEffect")
        axios.get('http://localhost:3001/api/recipes')
        .then(response => {
            console.log(response.data)
            return response.data
        })
        .then( recipeslist => {
            console.log(recipeslist,"recipes")
            setRecipes(recipeslist)
            setFilterRecipe(recipeslist)
        })
        .catch((err) => console.log(err))
    },[])

    function handlechange(event){
        var query = event.target.value.toLowerCase()
        setSearch(query)

        var filter_recipes = filterRecipe.filter((recipe) =>
            recipe.dish_name.toLowerCase().includes(query)
        )

        setRecipes(filter_recipes)
    }

    return (
        <Router>

                <Navbar handlechange={handlechange}  search={search}/>
                <Allrecipes recipeslists={recipeslists} />

            <Route path="/" exact component={Allrecipes} />
            <Route path="/recipes/create" exact component={Createrecipe} />
        </Router>
    )

}
export default App

```

<p><code>Allrecipes.js</code> code is as follow</p>

<pre class="lang-js prettyprint-override"><code>import React from "react"
import Recipe from './Recipe'

const Allrecipes = (props) => {
    const {recipeslists} = props
    console.log(recipeslists,"*** recipes array in Allrecipes***")

    return (
        <div className="recipecontainer">
               {recipeslists.map( recipeitem => <Recipe key={recipeitem.id} recipeitem={recipeitem} />)}
        </div>
    )
}

export default Allrecipes
</code>```

Output of above code in console:

Output in console without using Router:

Explain me,

why Router is causing Array to become undefined? or it is another bug I am unknown of?

If this is wrong implementation or method of using Router in Reactjs , then what is the correct way to do it?

Thank You. I would appreciate your any help!

答:
Simple, when you use the router you don't pass the list and your component get the list from the props. in your code it looks like that:

When you are not using the Router

```<code><Allrecipes recipeslists={recipeslists} />
</code>```

When you are using the Router

```<code><Route path="/" exact component={Allrecipes} />
</code>```

You should query the data inside your component and not get it as a prop.

Body:
So I am trying to fetch JSON data from server running on another port in my pc using axios and renders it on homepage. I want to setup Router to components. But whenever I wrap Router around my components It causes Array recipeslists to become undefined (see below console output) and hence I can not map that Array in my Allrecipes Component But without any Router it works fine.

App.js's code is as follows

import React, { useState , useEffect} from 'react'
import { BrowserRouter as Router, Route } from "react-router-dom"
import "bootstrap/dist/css/bootstrap.min.css"

import Navbar from './components/Navbar'
import Allrecipes from './components/Allrecipes'
import Createrecipe from './components/Createrecipe'
import axios from 'axios'

const App = () => {
    const [recipeslists,setRecipes] = useState([])
    const [filterRecipe,setFilterRecipe] = useState([])
    const [search,setSearch] = useState('')
    console.log("in app")

    useEffect(()=>{
        console.log("useEffect")
        axios.get('http://localhost:3001/api/recipes')
        .then(response => {
            console.log(response.data)
            return response.data
        })
        .then( recipeslist => {
            console.log(recipeslist,"recipes")
            setRecipes(recipeslist)
            setFilterRecipe(recipeslist)
        })
        .catch((err) => console.log(err))
    },[])

    function handlechange(event){
        var query = event.target.value.toLowerCase()
        setSearch(query)

        var filter_recipes = filterRecipe.filter((recipe) =>
            recipe.dish_name.toLowerCase().includes(query)
        )

        setRecipes(filter_recipes)
    }

    return (
        <Router>

                <Navbar handlechange={handlechange}  search={search}/>
                <Allrecipes recipeslists={recipeslists} />

            <Route path="/" exact component={Allrecipes} />
            <Route path="/recipes/create" exact component={Createrecipe} />
        </Router>
    )

}
export default App

Allrecipes.js code is as follow

import React from "react"
import Recipe from './Recipe'

const Allrecipes = (props) => {
    const {recipeslists} = props
    console.log(recipeslists,"*** recipes array in Allrecipes***")

    return (

               {recipeslists.map( recipeitem => <Recipe key={recipeitem.id} recipeitem={recipeitem} />)}

    )
}

export default Allrecipes

Output of above code in console:

Output in console without using Router:

Explain me,

why Router is causing Array to become undefined? or it is another bug I am unknown of?

If this is wrong implementation or method of using Router in Reactjs , then what is the correct way to do it?

Thank You. I would appreciate your any help!

Body:
Simple, when you use the router you don't pass the list and your component get the list from the props. in your code it looks like that:

When you are not using the Router

<Allrecipes recipeslists={recipeslists} />

When you are using the Router

<Route path="/" exact component={Allrecipes} />

You should query the data inside your component and not get it as a prop.