Monitor unix process with Nagios Core

Question: I'm begginer with Nagios and i'm trying to monitor if a specific process on my unix machine is up or not.
Server and client are on the same machine : Trying to monitor that machine from a Nagios runing on it.
I've installed Nagios Core 4, nrpe and it's plugins. After looking on the web, I found an answer of how to monitor process using check_procs plugin (up or down) and that's what I actually have in my files :
1- in /etc/nagios/nrpe.cfg
server_address=127.0.0.1
command[check_service]=/usr/lib/nagios/plugins/check_procs -c 1: -C $ARG1$

2- I created a file called "ubunutu_host.cfg" in /usr/local/nagios/etc/servers/ :
# Ubuntu Host configuration file
    define host {
            use                          linux-server
            host_name                    ubuntu_host
            alias                        Ubuntu Host
            address                      127.0.0.1
            register                     1
    }

    define service {
          host_name                       ubuntu_host
          service_description             check_apache2
          check_command                   check_service!apache2
          max_check_attempts              2
          check_interval                  2
          retry_interval                  2
          check_period                    24x7
          check_freshness                 1
          contact_groups                  admins
          notification_interval           2
          notification_period             24x7
          notifications_enabled           1
          register                        1
    }

3- In /etc/nagios-plugins/configp/rocs.cfg :
define command{
command_name check_service
command_line /usr/lib/nagios/plugins/check_procs -c 1: -C '$ARG1$'
}

My probelm is :
when runing this command :
/usr/lib/nagios/plugins/check_procs -c 1: -C apache2

that's what I'm having as a result
PROCS OK: 7 processes with command name 'apache2' | procs=7;;1:;0;

BUT In Nagios, below what I'm having (apache2 is always critical) :
Problem proc apache2 is always shown critical
Comment: Help guys! Thanks
Comment: https://serverfault.com/ or https://askubuntu.com/ are better forums for this question.  StackOverflow is meant for programming questions while ServerFault covers admin questions and AskUbuntu covers general questions.
Comment: Try run this command `/usr/lib/nagios/plugins/check_procs -c 1: -C apache2` as Nagios user and also try replace `'$ARG1$'` to `"$ARG1$"`, just for the case...
Answer: First of all, NRPE is used to make and receive remote plugin calls. You don't specify which server you are modifying /etc/nagios/nrpe.cfg on, but your check command is /usr/lib/nagios/plugins/check_procs which means that Nagios is running this plugin locally, and perhaps that is what you want, I don't know, but in that case there is no point in involving NRPE at all.
Since you mention that you get the output you want when "running" the command (you don't specify as what user):
/usr/lib/nagios/plugins/check_procs -c 1: -C apache2

I'm guessing that the user that you are running this as actually can see your apache2 processes, while the user running the actual Nagios check cannot. Try using su to change into your Nagios user and see if there's a difference in output.

Monitor unix process with Nagios Core


Tool or Package For Designing Site For a Small Non-Profit Accepting Donations

Question: I deal primarily with custom .net WebForms and MVC based applications, but someone came to me and asked for help with creating a small website for their non-profit organization for which they will need to be able to accept donations.
My preference would be to use a simple CMS, and I have heard of Shopify and the Shop Plugin for WordPress, but they really don't need that level of e-commerce. Basically what I am looking for is some advice for using a simple mini-CMS, be it WordPress, Squarespace, etc, and integrating some method for accepting and keeping track of donations.
My initial thought was to use WordPress and then link to Paypal.
Comment: Ended up initially going with squarespace... then moved to Orchard...
Answer: Note: WordPress has grown up since a few years ago. It can easily be used as a full-on CMS serving hundreds of pages based on custom data types.
As far as collecting donations, any ecommerce/shopping cart solution is massive overkill for accepting donations. A PayPal link is definitely the fastest way to go. Here is a step-by-step tutorial on how to do it.
Note: some people do not like PayPal, so consider adding multiple buttons. Here is the Google Checkout version. Or 2co looks like they will support it now (or Real Soon Now).
Comment: Looking into. Thanks for the recommendations.
Answer: Squarespace - an alternative to wordpress. Get the complete guide - https://support.squarespace.com/hc/en-us/articles/206796007-Templates-and-design
After your setup the website - Find the step-by-step guide on how to accept recurring donations on Squarespace website for your non-profit websites.
https://donorbox.org/nonprofit-blog/squarespace-embedding/


Hat and River Problem

Question: Below is the story problem:

A person dives from a bridge into a river and swims upstream through the water for 1 hour at constant speed. She then turns around and swims downstream through the water at the same rate of speed.
As the swimmer passes under the bridge, a bystander tells the swimmer that her hat fell into the river when she originally dove. The swimmer continues downstream at the same rate of speed, catching up with the hat at another bridge exactly 1 mile downstream from the first one. What is the speed of the current in miles per hour?

The answer given was 1/2 mile per hour and the author concluded it took 2 hours - "The whole thing took 2 hours, during which the hat traveled
1 mile downstream."
How did he come to the conclusion that it took 2 hours for the "whole thing"?
Answer: Give the provided information, we can't know the speed of the swimmer, but let's suppose the swimmer swims at a speed of $v$ miles per hour. That is, if the water would not flow, she swims at $v$ miles per hour. Since the hat flows with the water, that means that as the swimmer swims upstream, the distance between the hat and the swimmer increases at exactly that $v$ miles per hour. So, swimming back, the swimmer decreases the distance with exactly $v$ miles per hour as well. So, if she swam upstream for one hour, it'll take that one hour to catch back up.
The key to solving this puzzle is therefore to look at the movement of the swimmer relative to the river as a 'whole'. That is, if we look at the movement of the swimmer relative to all of space, the swimmer goes through space at an enormous speed, since the swimmer is located n planet Earth, which hurtles through space at a good clip ... and our solar system moves at great speed relative to the center of our galaxy, etc. etc.  So thinking about these kinds of things, we recognize that 'speed' is always relative to something. Now, here on Earth, and for day to day purposes, most of the time we think of and measure speed relative to the 'surface' of the Earth. Indeed, that's is exactly the perspective you are asked to take when asked the speed of the river: that's relative to the river bank, or bridge, or river bed, or anything that's in a 'fixed' position as far as the earth surface goes.
OK, but for solving this puzzle, it is better to take think about the movement of the hat and swimmer relative to the river as a whole. That is, we can think of the river as a kind of 'snake' that moves, as a whole, relative to the Earth's surface. However, how does the hat and swimmer move relative to this 'snake'?  Well, relative to the river, the hat remains at a fixed position; it's as if it is 'attached' to the snake.  The swimmer, however, moves with a certain speed relative to this river; think of it as 'crawling' along the skin of the snake. And we can assume that is the same relative speed as if the swimmer is in standing water, i.e. in a lake or pool. And, when the swimmer turns around, the swimmer moves at exactly that same speed relative to the river again, just in the opposite direction. So, thinking about it that way, it really is analogous to the situation where she would dive in a lake, lose the hat right where she dove in, swim for an hour into the lake, and then turns around: how long does it take to get back to the hat? An hour of course!
Comment: @youcanlearnanything There are typically two phases to solving mathematical problems:  First, put the problem into symbols. Second, figure out something by manipulating those symbols.  For the second part we often use algebra, yes.  But the first part is part and parcel of the mathematical solving process as well. In my Answer, I effectively did all the analysis to get it ready for symbolization. I'll do that symbolization now: We know that two hours past between the moment the swimmer lost her hat when diving in, and the moment the swimmer caught up with her hat. ... (continued)
Comment: @youcanlearnanything During this time, the hat flowed down 1 mile. So, if we set the speed of the current to $v$ miles per hour, we have as an equation: $2v=1$.  OK, we are now ready to do part two, which is using algebra to solve this equation: $v = \frac{1}{2}$. OK. Done with part two.  The moral is: spending a bit of time doing part I, and thinking about how best to represent the problem can really pay off!
Comment: are you assuming that the speed remains the same for upstream and downstream?
Comment: @youcanlearnanything I am assuming the swimmer swims with the same 'intensity', yes. Of course, from the point of view of someone standing on the riverbank, she goes faster downstream than upstream, but relative to 'the water' (imagine an individual water molecule flowing down, and how the swimmer 'swims away from it first, and then catches back) she swims with the same speed. Yes,  that's what I assume. I also assume it takes $0$ seconds to turn around, and she is not slowed up talking to the person back at the bridge.
Comment: @Bram27 can you explain how would you resolve it using algebra?
Comment: I am confused over the 3rd variable, which is the current. Thank you for your clear explanation!
Answer: Work in the frame of reference of the hat (i.e., the surface of the river).  The swimmer swims away from the hat for one hour and then swims toward the hat until she gets back to it--which clearly also takes one hour.
Answer:
$s$ - speed of swimmer, positive
$r$ - speed of river, positive
$p_1$ - position the swimmer goes upstream, positive
$p_2$ - position the swimmer goes downstream, positive
$t$ - the time it takes to go from $p_1$ to $p_2$

A person dives from a bridge into a river and swims upstream through the water for 1 hour at constant speed.

$$p_1 = (s - r)\cdot 1$$

As the swimmer passes under the bridge, a bystander tells the swimmer that her hat fell into the river when she originally dove.

$$p_2 = r\cdot (t + 1)$$

The swimmer continues downstream at the same rate of speed, catching up with the hat at another bridge

$$p_1 + p_2 = (s + r) \cdot t$$

exactly 1 mile downstream from the first one.

$$p_2 = 1$$

$$(s - r)\cdot 1 + r\cdot (t + 1) = (s + r)\cdot t$$
$$s - r + r\cdot t + r = s\cdot t + r \cdot t$$
$$s = s\cdot t$$
$$s = 0 \text{ or } t = 1$$
Since "catching up with the hat" wouldn't make sense if $s=0$, it must be that $t=1$.
$$p_2 = r\cdot(t+1)$$
$$1 = r\cdot(1+1)$$
$$\frac12 = r$$

Hat and River Problem


How to change views exposed filter default value

Question: So I have this view with exposed filter of taxonomy terms with depth, I had selected some of the terms to limit the selection.
everything works just fine but the issue is that the default value of the exposed filter (combo-box) is set to the latest entry (taxonomy term), and I want to set it to that -All- thing.
I know that if I don't select any of the terms to limit the selection, it'll be set on -All- as default value for the exposed filter, but I don't wanna do that!
the question seems quite simple but I couldn't figure this out! thanks.
Answer: in template.php:
<code>function MY_THEME_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EXPOSED_FORM_ID') {
    // Modifications go here.
    // example: (change the field name to yours)
    // $form['field_adv_cat_1_tid']['#default_value'] = 'All';
  }
}
</code>
then clear the cache.
Comment: @Sohail 1. This function is a hook_form_FORM_ID_alter() function. You can read about it by this link: https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_FORM_ID_alter/7. 2. open template.php file and paste above code into it, and change MY_THEME to your theme name. Clear cache and use dpm($form) to find the id of your form. Then change MY_EXPOSED_FORM_ID to your form's id.
Comment: @Sohail, By default, `Drupal` replace underscore (`_`) in `form id` of the form into dash(`-`) when render HTML of the form. You should use `views_exposed_form_resellers_page` or check with `dpm()` function or `print_r` or `var_dump`.
Comment: @xurshid29, I have checked `views_exposed_form` and found that `#id` attribute of `form` and `#form_id` is different. I think, as all exposed form has same `form id (views_exposed_form)`, so `views` module is setting different `#id` attribute of the form for each different form.  In `drupal_prepare_form()` in `form.inc`, then if `#id` attribute is not set, its converting `form_id` and setting to `#id` attribute of form.
Comment: Thanks xurshid for answer but the thing is I rather to fix it via views itself, if it's not possible I try template.php thing, btw I tried your approach and couldn't make it work, maybe I did sth wrong there, should I replace the ID of my select field in $form['field_adv_cat_1_tid']['#default_value'] = 'All'; instead of field_adv_cat_1_tid ?
Comment: @Sohail here is a nice tutorial (unfortunately in russian) - http://xandeadx.ru/blog/drupal/304, shows how to work with Devel
Comment: thanks, the thing is I still couldn't make it work! By the way we can just inspect the form and use the form ID in HTML (easier than devel). I used the below code:

function stme_form_views_exposed_form_alter(&$form, &$form_state) {
   dpm($form);
  if ($form['#id'] == 'views-exposed-form-resellers-page') {
    // Modifications go here.
    // example: (change the field name to yours)
    $form['views-exposed-form-resellers-page']['#default_value'] = 'All';
  }
}
Comment: @Sohail `views-exposed-form-resellers-page` ( `$form['views-exposed-form-resellers-page']`) - is a name of an element? You need to find your desired element's name... Use devel's `dpm($form)` or php's built-in `print_r($form)` or `var_dump($form)` to find it..
Comment: Oh sry I pasted the wrong thing, here's the code:
function stme_form_views_exposed_form_alter(&$form, &$form_state) {
   dpm($form);
  if ($form['#id'] == 'views-exposed-form-resellers-page') {
    $form['term_node_tid_depth_i18n']['#default_value'] = 'All';
  }
}

but it works! but just based on devel it says that term_node_tid_depth_i18n #default_value is All, but it still shows the last term of mine which is a city name! it must be overriden somewhere, right? is it even possbile? I cleared cache btw
Comment: @Sohail Does 'All' value exist in the options array?
Comment: Jayendra, Thanks for the hint, I fixed that.
xurshid, Yea it does, if I say resellers?term_node_tid_depth_i18n=All in URL it works the way that it should
Comment: @JayendraKainthola in my project `if ($form['#id'] == 'views-exposed-form-adverts-advert-term-display') {...}` works fine:) It's a strange..
Comment: @xurshid29, Yes, its strange. As I know that Drupal replace `form id` when render the html of the form.
Comment: @JayendraKainthola I just tested this and found that if I change dashes to underscores, it won't work.. `$form['#id']` only receives dashes..
Comment: @xurshid29, `id` in HMTL form is `views-exposed-form-adverts-advert-term-display`?
Comment: @JayendraKainthola yes. Here you can see it: ``
Comment: @xurshid29, It's interesting. I also need to check this . But, I am sure, if you will check with another form like creating custom form in custom module, it will not work.
Comment: @JayendraKainthola Thanks for the clarification, I didn't know about it..
Comment: @xurshid29, I also do not know about this _why `views_exposed_form` working differently_.
Comment: hey -- does anyone know if it's possible to have the default values affect the results from the view? I've followed the steps to create the default values, which works, but the form must be submitted before the results are filtered, which can be confusing to the user. Is it possible to force the "apply" step on initial page load? I'd rather avoid using a javascript solution so if there's a drupal way to do this that would be great. Thanks


Ajax request not working on datatable pagination

Question: In my Laravel web application I am using datatable to show data. My table has 3 actions to view, edit and delete.
For edit and view I am using Bootstrap 4 modal.
Here is a view of data table..

Here is my ajax request code to edit on modal:
$.ajax({
      type:'GET',
      url:"{{route('user.edit')}}",
      data:{'id':user_id},
      success:function(data){
        var role;
        if(data.role_id == 1){
            role = 'Admin';
        }else if(data.role_id == 2){
            role = 'Seller';
        }else{
            role = 'Publisher';
        }
        $(header).empty();
        $(header).append('
'+data.details.name+'\'s details
');
        $('#name').empty();
        $('#name').val(data.details.name);
        $('#email').empty();
        $('#email').val(data.details.email);
        $('#contact').empty();
        $('#contact').val(data.details.contact);
        $('#address').empty();
        $('#address').val(data.details.address);
        $('#user_id').empty();
        $('#user_id').val(data.details.id);
        $.each(data.roles, function(index,val){
            if(data.details.role_id == val.id)
                var selected = 'selected';
            $('#role').append('<option '+selected+' value="'+val.id+'">'+val.role_name+'</option>');

        });
    }
});

Now everything works fine for the first page. But when I search something in datatable or go to another page through pagination, my ajax request does not work. I am using class to call the ajax request. When I go to another page or search a data and click on edit, Only the modal opens the ajax request does not initiate and it shows empty modal.
How can I solve this issue?
Comment: Does it say anything in the console? Also, remove the `empty()` calls. They are redundant.
Comment: are you doing this in a blade?  a Vue front end?  Laravel actually has a datatable package that is super simple/easy.  http://yajrabox.com/docs/laravel-datatables/master/installation . If you are in a blade just send all the data back from the controller attached to a blade, loop through it build a table that call jQuery on it.
Comment: @Mark Walet Console is clean. When I go to other page the ajax just does not activate....
Comment: @Brad I am using Blade. Thanks a lot for your suggestion. But is there any fix for my problem.
Answer: $(document).on('click', '.your_button', function(){
   //code for action
});

event handler only handle to those elements which exists in the dom when the code was executed so need to use delegation based event handler. try this
Comment: Thank you very very much for the solution! It worked perfectly. That is really nice of you to even explain the situation. Perfect answer.


Bernoulli distribution/ SOME probability/conjugate prior

Question: I would like to know what "SOME probability of seeing tail" means in the second answer here. I.e. how much is it?
EDIT: I do not understand how can I see that there is SOME probability of seeing Tail just from the shape of the 4th picture. Can someone elaborate on this? May the word "SOME" be made precise in the sense of magnitude of that quantity?
Comment: "Some" means greater then zero. What is unclear for you?
Comment: Thank you for your reply. What I do not understand is **how** to read "SOME" **from** the 4th picture.
Comment: What do you mean by "how to read"? You mean English pronunciation?
Comment: No :-) How do I understand or read off from the 4th picture that there is SOME probability of seeing Tail. It is somehow because that it is curved towards the 0 at the r.h.s.?
Comment: @Tim I did my best, please see EDIT.
Answer: I would try running the commands below:
print(dbeta(seq(0,1,0.01),3,2))
plot(dbeta(seq(0,1,0.01),3,2),type='l')

the plot should be the same as the one in the link (see below for reference).
the print statement prints the probabilities of the dbeta:

  [1] 0.000000 0.001188 0.004704 0.010476 0.018432 0.028500 0.040608 0.054684
  [9] 0.070656 0.088452 0.108000 0.129228 0.152064 0.176436 0.202272 0.229500
 [17] 0.258048 0.287844 0.318816 0.350892 0.384000 0.418068 0.453024 0.488796
 [25] 0.525312 0.562500 0.600288 0.638604 0.677376 0.716532 0.756000 0.795708
 [33] 0.835584 0.875556 0.915552 0.955500 0.995328 1.034964 1.074336 1.113372
 [41] 1.152000 1.190148 1.227744 1.264716 1.300992 1.336500 1.371168 1.404924
 [49] 1.437696 1.469412 1.500000 1.529388 1.557504 1.584276 1.609632 1.633500
 [57] 1.655808 1.676484 1.695456 1.712652 1.728000 1.741428 1.752864 1.762236
 [65] 1.769472 1.774500 1.777248 1.777644 1.775616 1.771092 1.764000 1.754268
 [73] 1.741824 1.726596 1.708512 1.687500 1.663488 1.636404 1.606176 1.572732
 [81] 1.536000 1.495908 1.452384 1.405356 1.354752 1.300500 1.242528 1.180764
 [89] 1.115136 1.045572 0.972000 0.894348 0.812544 0.726516 0.636192 0.541500
 [97] 0.442368 0.338724 0.230496 0.117612 0.000000

The value at p=1 with index 100 is 0.0 which means that there is some probability that you will see a tail. This can be inferred from the sharp dip of the curve.
When the toss was heads, the probability at 1 kept going up, indicating a completely head biased coin, but as soon as you saw the tail the probability at 1 went down showing that it not completely head biased, because a tail was observed.
It might be interesting to observe that the value at p=0 is also zero, meaning that the coin is neither completely head nor completely tail biased.
Hope this helps.


Table dynamic created with tha data

Question: I have this script on php and i need to create table automatcally from that
<code>foreach ( $GetJobResult->Components->Component as $component_index => $component ) {
    $quote_title = ($component_index + 1) . ') ' . $component->Title . "-Machine :\r\n";
    if (isset ( $component->Paper->Family )) {
        if (isset ( $component->Paper->Type ) && isset ( $component->Paper->Color )) {
            if ($component->Ink->FrontColors == '0') {
                $quote_impression = "sans impression\r\n";
            }
            $getPaperInfoResult = $ws->getPaperInfo ( $component->Paper->Family, $component->Paper->Type );
            foreach ( $getPaperInfoResult->PapFamType as $paper_index => $paperinfo ) {
                if (($paperinfo->Ccoul == $component->Paper->Color) && ($paperinfo->Gramm == $component->Paper->Weight)) {
                    $quote_support = $paperinfo->Lfam . ' - ' . $paperinfo->Lcoul . ' - ' . $paperinfo->Gramm . ' g/m2' . "\n";
                    $quote_impression = $component->Ink->FrontColors . ' Couleur(s) ( ' . $component->Ink->FrontColorDesc . ') au recto / ' . $component->Ink->BackColors . ' Couleur(s)' . ' ( ' . $component->Ink->BackColorDesc . ' ) ' . "\n";
                    break;
                }
                // $quote_desc[]= $getPaperInfoResult->PapFamType [$component_index + 1]->Lfam . ' - ' . $getPaperInfoResult->PapFamType [$component_index + 1]->Lcoul . ' - ' . $getPaperInfoResult->PapFamType [$component_index + 1]->Gramm . ' g/m2' . "\n";
            }
        }
        $row++; $col++;
        $tbl = $p->add_table_cell($tbl, $col, $row, $quote_title, $opttitrecontact);
        $imp_text_element1.=$quote_title."-Support : ".$quote_support."-Impression : ".$quote_impression;
    }
 }
</code>
It's done table in each cell the data and skip the one cell on put the data so i need just table contains the data how can i do that.
Comment: Welcome to Stack Overflow. Your question could use a bit more detail. Please edit it and include any errors you see or maybe some examples of the resulting data you are getting versus what you're trying to get.
Comment: i do my script  but the result not table contains the data in different cellul
Answer: I see a possible problem, by the way you increase the variables for
<code>$row++; $col++;
</code>
That means, for each additional content, you increase the row and the cell.
I would expect, the row should only increased as soon you need a new row.
I guess you want not only add one cell for each run in you foreach-loop:
    $tbl = $p->add_table_cell($tbl, $col, $row, $quote_title, $opttitrecontact);
Maybe you want to add more cells, if so, you should add multiple add_table_cell() calls with the data you want to place.
However as Twisty already mentioned, you might describe your problem more precise. Also, the support team from PDFlib might give you further help.
Comment: Thanks @Rainer but how can i creat table with the data Thanks in advance
Comment: @test, I'm sorry, but I don't understand the background of the question. What do you mean with "data"? Just add table cells with the content you want place. Straight forward. You might check the samples in the PDFlib cookbook (cool resource) http://www.pdflib.com/pdflib-cookbook/tables/
Comment: Thanks @Rainer i need on cell retour the line but not do i do \r\n that $tbl = $p->add_table_cell($tbl, $col, $row, $quote_title."\r\n".$quote_support, $opttitrecontact);
Comment: so you want a have a multi line text in this cell? if so, you have to add the content in a two steps: create a textflow which contains the text, then apply this textflow to the cell. As a sample, you might check the starter_table.php sample. Per default, a text cell is a textline, which is always a single line. I'm sure, in the meanwhile you have read this in detail within the PDFlib Tutorial.
Comment: how do you think you might get help, when you don't share error messages?

Table dynamic created with tha data


Cross-sectional SUR in R

Question: Is there a package in R that can estimate panel data with cross-sectional seemingly unrelated regression generalized least squares weights (like in EViews)?
Comment: UCLA has a tutorial on how to implement an SUR in R with `systemfit` here: http://stats.idre.ucla.edu/r/faq/how-can-i-perform-seemingly-unrelated-regression-in-r/
Answer: Yes, the "systemfit" package does that.

Cross-sectional SUR in R


How to pass data in react js inside a file

Question: I have the next component in ReactJs:

function App() {
function handleClick(e) {
    console.log('click ', e);
    localStorage.setItem('my-item', e.key);
    console.log(localStorage.getItem('my-item'))
  }
  return (

      <Menu
        selectedKeys={e.key}
        style={{ width: 500px}}
        onClick={handleClick}
      >
      ...another code

}

There i used AntDesign. The function handleClick write in my localstorage the key of an item. It works, but i want to pass in selectedKeys the key that i passed in the localstorage, so i want to do this selectedKeys={e.key}, but i can't do this. How to pass the data e.key from the function to<Menu> tag?
Answer: What about using a state :
With the React hook useState :
import React, { useState } from React;

then
const [selectedKeys, setSelectedKeys] = useState([]);

then
function handleClick(key) {
  localStorage.setItem('my-item', key);
  let newKeys = selectedKeys.slice(0); // you may need to clone the array
  newKeys.push(key);
  setSelectedKeys(newKeys); // or push it into an array if there is many.
}

your Menu component would then look like :
<Menu
 mode="inline"
 selectedKeys={selectedKeys}
 openKeys={openKeys}
 onOpenChange={onOpenChange}
 style={{ width: 500px}}
 onClick={() => handleClick(e.key)}>

All together :
import React, { useState } from React;

const App = () => {
  const [selectedKeys, setSelectedKeys] = useState([]);

  const handleClick = (key) => {
    localStorage.setItem('my-item', key);
    let newKeys = selectedKeys.slice(0); // you may need to clone the array
    newKeys.push(key);
    setSelectedKeys(newKeys); // or push it into an array if there is many.
  }

  return {
    <Menu
     mode="inline"
     selectedKeys={selectedKeys}
     openKeys={openKeys}
     onOpenChange={onOpenChange}
     style={{ width: 500px}}
     onClick={() => handleClick(e.key)}>
  }
}

Answer: Make it a class component and in the state make an attribute of selected key and in the handleClick do set the state and assign the selectedKey value from the state in the Menu tag. Thats the proper way of doing it.

import React, { Component } from 'react';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
        selectedKey: null
    };
  }
  handleClick = (e) => {
    console.log('click ', e);
    this.setState({
       selectedKey: e.key
    });
    localStorage.setItem('my-item', e.key);
    console.log(localStorage.getItem('my-item'));
  }
  render () {
    return (

        <Menu
          selectedKeys={this.state.selectedKey}
          style={{ width: 500px}}
          onClick={handleClick}
        >
        ...another code
  }
}
Comment: Thank you @Mteuahasan did it in haste. appreciate it
Answer: Use an arrow function:
onClick={() => handleClick(e.key)}

In your code:
  handleClick = key => {
    console.log("the key is:", key);
    localStorage.setItem('my-item', key);
    console.log(localStorage.getItem('my-item'))
  }

  <Menu
    selectedKeys={e.key}
    style={{ width: 500px}}
    onClick={() => handleClick(e.key)}>


Logging long tensor values in tensorflow estimator

Question: I have built a classification model using tensorflow estimator API. I am trying to get tensor outputs from hidden layes printed in logs while prediction using below code.
model = tf.estimator.DNNLinearCombinedClassifier(
        model_dir=model_dir,
        linear_feature_columns=wide_columns,
        dnn_feature_columns=deep_columns,
        dnn_hidden_units=hidden_units,
        config=run_config)
tensors_to_log = {"DenseOut": "dnn/logits/BiasAdd"}
logging_hook = tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=1)
predictions = model.predict(train_input_fn, hooks=[logging_hook])

When i run the code I am able to get the tensors logged in output but since the value is very long it is truncated and i can only see few numbers in begining and end.
INFO:tensorflow:DenseOut = [[ 0.61572325 -0.44044942 -0.19232166 ...  0.04 0.605 0.15]]

How can I specify tensorflow to log the complete output?
Answer: So interesting, I found that the solution was to set np.set_printoptions.
import numpy as np

np.set_printoptions(threshold=np.nan)

It seems that tensorflow and numpy are closely integrated.
Comment: That worked perfectly. Makes sense as tensors are also based on top of numpy array. Thanks alot.
Answer: Try this:
    import sys
    import numpy as np
    np.set_printoptions(threshold= sys.maxsize)


Replacing a specific character if it is inside a string that matches a pattern in Python

Question: Is it possible to use regex to replace a specific character inside a string if it matches a pattern?
For example I want to replace \ with X if it is inside two $ characters, otherwise it should remain unchanged.
 $some\string here inside$ and [some here \out side]

and what I expect to have in output is
$someXstring here inside$ and [some here \out side]

re.sub(r'\$*\\*\$', 'X', b) replaces $ with X. How should I do this with one re.sub command?
Answer: You can use a lambda with re.sub using str.replace to replace any \\ that matches your pattern
s = "$some\string here inside$ and [some here \out side]"
import re

print(re.sub(r"\$.*\\.*\$",lambda  x: x.group().replace("\\","X"),s))
$someXstring here inside$ and [some here \out side]

Comment: Appreciated :) Thanks
Answer: Regexless solution:
s = r'$some\string here inside$ and [some here \out side]'

def solution(s):
    inside = False
    for c in s:
        if c == '$':
            inside = not inside
            yield c
        elif inside and c == '\\':
            yield 'X'
        else:
            yield c

print(''.join(solution(s)))

I know some explanation would be welcome, but at the moment I have no idea what could I explain.


Does restricting the frames/s of a game engine (via vertical sync or common throttling), inflict latencies also on audio and input subsystems?

Question: I was contemplating the fact that inflicting frame per second restrictions is not ideal in regards to latency and performance since a monitor still has a chance to show something sooner (assuming no vertical sync which is mainly for stability).
However, it occurred to me that process might have ramifications on audio subsystems (or also input devices), assuming frames per second also governs the global loop of the engine itself (the case in almost all 3D accelerated applications).
Do audio cards/audio devices on an operating system have a concept of "Hertz" that might be related? Do we assume the faster the global loop of the application the better the latency for the audio subsystems?
Answer: Audio is not typically affected at all. The audio has a separate buffer which you fill up in advance, maybe a hundred milliseconds or more, and the sound card plays back from that regardless of what your game loop is doing.
It is possible, if you fill that buffer in your game loop, that taking too long to get back to the game loop will result in the sound buffer being empty and a looping sound being heard. To avoid this, developers will either use a big buffer or fill the buffer from a background thread.
As you might guess, audio is already running at some sort of latency, proportional to the amount of data in the buffer that the game attempts to keep in there at all times. This is usually not so noticeable since sound takes a non-negligible time to travel in real life anyway. Pro audio applications have to keep this buffer small for low latency and responsiveness, but they don't have graphical frames to worry about...
As far as input, yes, it is often affected. If a game does not decouple the rendering rate from the input handling rate, then there will be some additional latency on the way in. There will always be some additional perceived latency on the way out too, if you consider input latency as the length of time between performing an action and seeing it take effect. But that perceived latency may well be larger than the simulation latency, since the affected entity may have been altered at an earlier timestep than the one displayed in the next frame.
Answer: Typically the game processing and the display aren't coupled, so reducing the FPS of the display won't affect the central game processing, which would include things like input (and presumably audio).
This article explains it pretty well, including different options for having FPS linked to game speed or not.
Comment: This is an amazing Article. It's not what I asked at all but it's better.
Comment: Uhm, I think I spotted a potential loohole in the article. He dismisses the very 1st case as something simplistic and wrong while he could have had timing implementation on the gameplay() itself and avoid any throttling whatsoever.
Comment: Good article, though I think he's one of those guy who likes it that the game eats every bit of CPU it can get, just for more FPS. But he's correct, interpolation is the only way to do it right, especially when it comes to multiplayer/online games where you might have to deal with the fact that certain objects only get updated a few times per second. But keep in mind that prediction and interpolation can get fairly complicated in such cases.
Comment: @Lela Dax - I wouldn't say he dismisses it, just points out some pretty serious problems.  One of the problems with having FPS and gameplay linked in that case is if the machine is struggling, everything will slow down together, so things like how far a character moves according to input will also change.  It usually gives a better experience to have the game speed constant, with the FPS getting worse if the machine is slow.
Comment: @Ivo Yeah, to be honest I've never done this, I used something like option 3, which is fine for a lot of cases.
Comment: Yes but, if one thinks CPU power has to be throttled to save power or be comfortable with other processes, that's a different subject which he does not cover since he assumes it's either a fast machine or a slow machine (with efficiency of the engine being needed). If the problem he sees on the first case is timing then he can simply do timing on the game logic and leave everything else unthrottled (not even the loop of the game logic, since it would be covered explicitly by its timing considerations). If the problem is power saving, it can be done explicitly elsewhere.
Comment: What could make it more efficient is throttling either game logic or rendering merely for giving more 'powah' to the other. This can be done in cases where e.g. 'audio calc needs better latency, take more from rendering'. etc.
Comment: True, throttling the processor to let other processes work isn't really considered, but I think in most cases it's assumed that people are using only the game and that the game should use all resources available.  This seems to be the case he's addressing, anyway - although option 1 does allow for other processes while the game loop is sleeping.  And timing the game and leaving the display to run is what he describes in the 3rd option.
Comment: Also consider that there may well be a GPU for graphics, so 'routing' processing power around may not be feasible, regardless of whether it was possible or a good idea.
Comment: On 'GPU for graphics'; well I meant even with a GPU one can simply delay it with timers to give more CPU time to game logic, if that is desired (I had a GPU in mind actually).


Como manter página atualizada sem refresh?

Question: Estou tentando criar uma página que fique sempre atualizada, sem ter que dar refresh.
Criei uma função em Javascript que fica buscando um select e while de outra página, mas isso esta gerando alto consumo no CPU e os caras do servidor já reclamaram. Como faço para sempre dar select em Javascript sem ter esse problema?

Chama a página busca_p.php que tem um select e while  e carrega dentro da div (msg_porto).
Funciona bem, mas fica processando o tempo todo e já reclamaram de alto uso de CPU por parte do servidor.
Comment: Pessoal talvez baguncei um pouco o que tentei passar, mas o que tento fazer é ter minha pagina atualizada sempre sem precisar atualizar a pagina, então fiz uma função que chama uma pagina onde esta consultando o banco e dando um while . Assim traz o resultado e carrega na div (msg_porto).  E ate funciona mas consome muito cpu do servidor porque coloquei a função window.setInterval(busca,1000); para chamar a função que solicita a pagina de consulta a cada 1 segundo.
Comment: O javascript faz a função de solicitar ao servidor às informações que serão retornadas pelo PHP sem ter que atualizar a página inteira. Dá uma conferida neste link
http://www.mauricioprogramador.com.br/posts/atualizar-parte-do-site-sem-refresh-na-pagina-inteira-com-javascript espero ter ajudado.
Comment: Dario me ajudou sim , conhecimento é sempre bem vindo, mas preciso que minha pagina se atualize sem a necessidade da ação do usuario, e consegui isso apenas usando a função window.setInterval(busca,1000) , mas isso faz o servidor processar muito , pensei se poderia ter isto sem ter que acessar uma pagina off , mas posso estar falando bobeira, mas obrigado por tentar me ajudar
Comment: Qual é o código que estás a correr no servidor? podes colocar aqui? e qual é o HTML que está a retornar? Sem essa informação não podemos ajudar muito mais.
Comment: ...   //A div que retorna com o resultado
Comment: Usando o framework angular, talvez resolva seu problema, já que ele é dinâmico. Não sei usá-lo, mas quem conhece pode até te orientar melhor.
Comment: @AndréNascimento, acredito que o Angular por si só não resolva o problema dele, afinal ele ainda vai precisar consultar o servidor para atualizar o modelo. por um outro lado, pode ser que exista algo em PHP que faça o que o MeteorJS faz, um bind do Model ligando o client ao server.
Comment: @CesarLimaPaulo, O conteudo novo é criado pela sua aplicação? digo, um outro usuario acessa uma outra pagina do sistema de insere os dados novos? se sim, você pode usar Web Sockets para notificar todos os clientes que precisam desta informação nova.
Comment: Use Web Socket para isso, aparentemente o que você quer é ter um real-time em sua aplicação e Web Socket ajuda a resolver justamente esse problema e com um consumo bem menor de CPU, segue uma boa introdução: http://www.html5rocks.com/pt/tutorials/websockets/basics/
Answer: A sua actualização de página nada tem de mal, o problema está no lado do servidor. Claro que pode ser melhorado, mas o principio é o que usa.
A chamada de Ajax está bem realizada e serve o propósito. No lado do servidor a única coisa que pode falhar são os consequentes requests, muito em especial as consultas à base de dados. Um problema recorrente.
É comum muitos ambientes disporem apenas de um servidor, onde o mesmo serve de  Http Server e Sql Server, mas dependendo do projecto e da base de dados isto pode ser um problema (o que normalmente é).
Nesse princípio, cada request HTTP pode utilizar muitos recursos do servidor, conforme a sua implementação parece fazer. Para minimizar este problema, aconselho-o a recorrer à utilização de cache. Seja ela mediante software próprio ou um esquema por si idealizado que possa guardar o resultado do seu último SELECT à base de dados.

Algo a evitar são comandos SELECT generalistas '*' no SQL, limitando ao máximo o número de registos a retornar.

Na programação não basta apenas colocar uns comandos, temos de pensar a implementação como um todo, mas muito em especial o fim a que se destina e a quantidade de dados que o mesmo vai gerir e movimentar em cada request.
Para finalizar, vale dizer que do lado do cliente você pode fazer e refazer seguindo inúmeras recomendações... mas enquanto do lado do servidor as coisas não estejam preparadas para a realidade do projecto, nada irá ser solução.
Answer: Provavelmente não é uma consulta muito levo no lado do servidor, as tabelas onde são realizadas a consulta é alimentada a cada segundo?
Primeiro seria bom aumentar o tempo de consulta, invés de 1 seg coloque 10 ou 5 ou até 1 min, isto depende da periodicidade que as tabelas são atualizadas.
Web Sockets é  uma boa, caso não precise funcionar em navegadores antigos (principalmente nos IEs antigos).
Algo que iria te ajudar bastante seria criar uma outra tabela que armazena a data e hora da ultima atualização das tabelas que fazem parte desta consulta, dai ao invés de a cada 1 seg efetuar a consulta, você consulta primeiro nesta tabela e se houver alguma atualização dai sim você consulta realiza esta sua consulta, isto vai diminuir bastante o processamento do servidor.


Memory Management : character arrays and = operator

Question: Memory Management : character arrays and = operator
Q.  In terms of Memory Management, What error would you have with the following code?
<code>class String
{
public:
 String(const char right[]);
 String& operator= (const String& right);
 int length() const;
private:
 char* buffer;
 int len;
};

int String::length() const {return len;}

String::String(const char right[])
{
  len = 0;
  while (right[len] != '\0')
    len++;
  buffer = new char[len+1];
  for (int i = 0; i < len; i++)
    buffer[i] = right[i];
  buffer[len] = '\0';
}

String& String::operator= (const String& right)
{
  int n = right.length();
  for (int i = 0; i <= n; i++)
    buffer[i] = right.buffer[i];
  return *this;
}
</code>
Answer.
I have no clue... Could you help me?
The array size seems okay... new operator...
is it because of the dangling pointer because there is no delete operator?
Or rule of three?
I would appreciate your help!
Please let me know.
Thanks,
Comment: It does not implement the [Rule of Three](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)), which means its a seg-fault waiting to happen. The assignment operator is also quite moronic in its implementation. The constructor, not quite as bad, but still no gem. Finally, no destructor, which means its a memory leak factory on top of everything else wrong with it.
Comment: The `operator=` is a buffer overflow just begging to happen, and there is no destructor nor copy assignment operator...
Comment: Besides the obvious really bad things, there's no need for the manual calculation of the string length in the constructor, or for the manual copying.
Answer: Is all I can suggest
<code>~String()
{
    if(buffer)
        delete [] buffer;
    len = 0;
}

String(int length)
{
  buffer = new char[length];
  len = length;
}

String String::operator = (String rhs)
{
    if(this != &rhs)
    {
        delete [] buffer;
        buffer = new char[strlen(rhs.m_str) + 1];
        strcpy(buffer, rhs.buffer);
    }

    return *this;
}
</code>
If you don't have a destructor, every time you new the buffer in your class, it will be a memory leak because your code has no way of getting rid of it.
Comment: You don't need to check for `NULL` when using `delete`. Your `operator=` should take a `const String&` and return a `String&`. For exception safety, always allocate new space before you `delete` (as `new` can throw - this will leave the objects in a consistent state if it does).


SQL Output Multiple Local Variables into one Column

Question: Is it possible, using SQL, to output multiple separately defined local variables into one column as separate rows? Eg.
DECLARE var1 INT = 4
DECLARE var2 INT = 5
DECLARE var3 INT = 6

And then select the variables in some manner like
SELECT (var1, var2, var3) AS UserIDs,
       ('u1', 'u2', 'u3') AS Names

Which would produce the following table:
UserIDs | Names
   4    |  u1
   5    |  u2
   6    |  u3

Comment: @MatBailie OP said SSMS, so SQL server is implied
Comment: @MatBailie a_horse_with_no_name has updated the tags
Answer: Use Table valued constructor
SELECT *
FROM   (VALUES (@var1,'u1'),
               (@var2,'u2'),
               (@var3,'u3')) tc (UserIDs, Names)

Comment: That's a neat approach. I found more info [here](http://blog.sqlauthority.com/2014/10/30/sql-server-beginning-table-valued-constructors-notes-from-the-field-052/)
Answer: select var1 as UserID, 'u1' as Name
union all
select var2, 'u2'
union all
etc
etc

Comment: @PM77-1 Muchos gracias
Comment: This did the job however, I'm going to accept @Prdp's Answer
Comment: @Xynos to be fair, prdp's is a better answer


What are the main differences between regulations of the NFL and the CFL?

Question: What are the main differences between regulations of the NFL and the CFL?
I live in Canada and follow the NFL, but also watch CFL games once in a while. I know a few differences; for example in the NFL each team gets 4 tries to carry the ball 10 yards, but that is only 3 tries in the CFL. Also I have noticed that the field is bigger under CFL regulations.
I'm wondering what are the major differences between the rules in these two leagues, specially when it comes to fouls.
Answer: Here is site that covers a lot of differences. http://www.13thman.com/cflvsnfl.html
Specifically to penalties is the Fair catch (NFL) vs. No Yards rule (CFL) on kick returns, but in general some of the bigger differences include:

Field length and upright position
Number of players on the field
Number of downs
Scoring rules on kicking plays
Fair catch (NFL) vs. No Yards rule (CFL) on kick returns
Length of play clock
Players in motion prior to the snap

Another rule I didn't see mentioned but is fairly significant is that CFL only requires one foot in play for a catch to be considered complete.
I'm sure there are other rule differences as well this is just a start.
Comment: Interesting site.  It's not entirely accurate, though; for example, in the US game, a missed FG can be returned if it doesn't hit the ground (is caught in the air), and the clock doesn't run continuously except for the ball to be replaced - there are all sorts of times when the clock stops.
Answer: At times it may appear that an offensive player in motion is treated the same in both leagues, but the rules are drastically different in both leagues.  In the CFL any eligible receiver not on the line of scrimmage can be moving towards the line of scrimmage at the the snap of the ball.  RB, FB, & WR can all be moving at the same time.  Additionally in the CFL eligible receivers on the line of scrimmage before the snap of the ball can only move along the line of scrimmage, perpendicular to the sideline and the ball.  In the NFL only one player can be in motion at a time and he is a player not on the line of scrimmage.  Players off the line of scrimmage can go in motion sequentially with a one second pause between motions. There are times when it appears that more than one eligible player is moving, but this considered a shift.  The players break the huddle and line up in a formation.  Any combination of eligible receivers can move to another position on the field and have to come to rest in that position for a one second before the ball can be snapped otherwise it is a penalty for illegal motion.


How to duplicate strings in each line using bash?

Question: I have a text file containing strings in each line like this:
'abc',
'dog',
'zebra',

I want to make it like:
'abc', 'abc',
'dog', 'dog',
'zebra', 'zebra',

How best to do it in bash?
Comment: This could work too...`paste -d " " dupcol.csv dupcol.csv`
Comment: Possible duplicate of [How to duplicate string in Bash?](https://stackoverflow.com/q/16484887/608639)
Answer: You could call sed:
sed -r 's/(.*)/\1 \1/' dupcol.csv

The .* says to match any character on a line, repeatedly. The ( ) around it says to store the match in the first register (\1). Then the full match is output twice.
I just usually default to using sed's -r option to make for cleaner (extended) regexes. However, omitting the -r enables & to match the full pattern. So a simpler version of this special case where you want to keep the full match is:
sed -r 's/.*/& &/' dupcol.csv

If you want to change the file in-place, add the -i option.
Comment: Worked like a charm. Thanks. Would be more informative  if you also explain what `\1 \1` does.
Comment: As you are using everything matched you can just use `&` without any capture groups or need for `-r`. `sed 's/.*/& &/'`
Comment: Awesome tip on &. I had originally tried that but now see that it does not work with -r. I've added this into the answer. Thanks!


What should be the optimum number of features for 10 million observations for kmeans clustering?

Question: I have a dataset of 10 million observations and 100 million features. I have to perform kmeans clustering on that dataset. The approx value of k is 30000
Is it advisable to perform clustering with such huge number of features? What are the problems I may face using such huge number of features? (Currently, I am facing OutofMemory in Spark mllib kmeans)
Wouldn't it be better to perform PCA reduce the number of features or feature-vectors are re-engineered in such a way that it contains less number of features? What should be the ideal number of features? Is there any doc on high dimensionality and kmeans?
Comment: Just to know: how much is your k?
Answer: Any algorithm that relies on a distance metric in a high-dimensional space will suffer from the curse of dimensionality. In effect, all your observations are going to appear "far" from one another, with relatively little variation in the distance measurement, making the clustering very weak. You'd be much better off selecting informative features, and using only those to construct your distance metric for k-means. The ideal number of features is very much problem dependent, so there's no set guideline on a pre-defined number.
Answer: Performing PCA before Kmeans clustering is an acceptable practice. The number of features for your number of samples is quite high and I guess many of them are correlated.
I would give PCA a try.
Just change your number of PCA components and see how much of the variance is explained (maybe try n_components = [100,1000,10000]). Once you are happy with the number of components, experiment with the number of kmeans clusters and draw the entropy plot and find the elbow point.
Kmeans and PCA are both unsupervised and need manual experimentation.


How can I filter nodes by term (entity reference) with jsonapi?

Question: My nodes contain an entity reference field, Ref Term.  I want to fetch a list of nodes that have a specific term with jsonapi.
In jsonapi, when I fetch nodes, the field with the taxonomy term reference is returned like this:
"field_ref_term": {
"type": "taxonomy_term--my_vocabulary",
"id": "b1a97358-9834-499d-aee0-ebb0302fb2c3"
},

So, first, I tried this:
/jsonapi/node/my_content_type?filter[field_ref_term]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

However, that gave me an error:
"title": "Bad Request",
"status": "400",
"detail": "Invalid nested filtering. The field `field_ref_term`, given in the path `field_ref_term` is incomplete, it must end with one of the following specifiers: `id`.",

So I tried adding [id]:
/jsonapi/node/my_content_type?filter[field_ref_term][id]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

That gave me a different error:
"detail": "You must provide a valid filter condition. Check that you have set the required keys for your filter.",

So I tried a longer version:
/jsonapi/node/my_content_type?&filter[term-filter][condition][path]=field_ref_term&filter[term-filter][condition][id]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

That gave me the first error again.  I read the documentation on filtering.
How can I filter my nodes based on which are tagged with a specific taxonomy term?  (In my case, each node has one and only one taxonomy term in its entity reference field.)
Answer: You were close, but your syntax was off. This is documented further down in your linked page, in the Filter Examples > Get nodes by a value of a entity reference section.
SHORT
filter[uid.id][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

NORMAL
filter[author-filter][condition][path]=uid.id
filter[author-filter][condition][value]=BB09E2CD-9487-44BC-B219-3DC03D6820CD

So, in your example, you'd need to use:
SHORT
/jsonapi/node/my_content_type?filter[field_ref_term.id][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749

LONG
/jsonapi/node/my_content_type?filter[term-filter][condition][path]=field_ref_term.id&filter[term-filter][condition][value]=f9c171db-1a1d-4d9a-bb55-5b0f8b033749


Propriedade col-xs não funciona

Question: Estou desenvolvendo um website utilizando Bootstrap e HTML, cujo vou deixá-lo flexível para a plataforma desktop e mobile. Porém, não consigo entender o porque da propriedade  col-xs(phones) não funcionar.
Segue o trecho de código:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>test-Col.xs.md.lg</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">

  <link href="css/sb-admin-2.min.css" rel="stylesheet">

              <form class="user">

                    <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password">

                    <input type="password" class="form-control form-contr   pleRepeatPassword" placeholder="Repeat Password">

                  Cadastrar

              </form>

Os anexos abaixo demonstram o comportamento da aplicação nas seguintes dimensões: lg(larger desktops), md(desktops), xs(phones).
Adaptação em lg:

Adaptação em md:

Adaptação em xs:

Por colocar em ambos os campos o código col-xs-3 acredito que na terceira imagem, os campos deveriam ficar lateralmente posicinados.
Palpite: Acredito que o motivo do comportamento em "xs" não estar acontecendo, deve ser por conta dos testes que estou executando, simplesmente reduzindo o tamanho do navegazor clicando e arrastando na vertice do navegador.
Answer: Seu problema é mais simples do que parece, pelo que vc vc está indexando no seu documento o /bootstrap/4.3.1/. E o motivo para não funcionar é que o tamanho XS só existe no Bootstrap 3, no Bootstrap 4 ele não existe e deve ser substituído apenas por col-n°.
Então veja que seu grid deveria ficar apenas com col-3 sem o xs
Bootstrap 3: col-xs-3
Bootstrap 4: col-3

Opções de tamanho do Grid do Bootstrap 4

No seu caso com vc declarou a div assim, sem um tamanho para -sm-:

O grid a partir do tamanho de tela médio -md- muda o grid para col-3, se vc quiser controlar o tamanho entre 768px e 576px vc precisa colocar por exemplo col-sm-4, ou então a partir de -md- o grid já aplica o col-3 abaixo de 768px

Veja a documentação oficial do grid do Bootstrap 4 https://getbootstrap.com/docs/4.0/layout/grid/#grid-options
Segue o código ajustado.

<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.0/css/bootstrap.min.css" />

              <form class="user">

                    <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password">

                    <input type="password" class="form-control form-contr   pleRepeatPassword" placeholder="Repeat Password">

                  Cadastrar

              </form>

Comment: Mas vale-se a pena implementar, agradeço!
Comment: Valeu hugo, apesar de já ter visto esse col-nº, não imaginava que ele veio para substituir o `xs`, valeu pela dica do uso do médio `md`, porém, a aplicação só vai ser utilizada por notebook e celular em alguns casos. Acredito que não seria necessário em meu cenário.
Comment: @AndréFilipe talvez sim, talvez não, tem dentro que olha o celular em landscape, tem celular com tela de tamanho de tablet, etc... não sei se vale a pena arriscar só por meia dúzia de caracteres... é só uma opinião, mas faça uma pesquisa com seus usuários para ter certeza ;)
Comment: Na verdade é um único usuário, o *cliente*, que vai usar a aplicação em notebook e mobile, no formato *portrait* apenas.

Propriedade col-xs não funciona


Eigenvalues and inverse of a Toeplitz matrix

Question: Given the Toeplitz matrix
$$X = \begin{pmatrix}
  ~~~~\textbf{1} ~~~~\textbf{c} ~~~~\textbf{d} ~~~~0 ~~~~0 ~~~~0 ~~~~\textbf{d}~~~~ \\
  ~~~~\textbf{c} ~~~~\textbf{1} ~~~~\textbf{c} ~~~~\textbf{d} ~~~~0 ~~~~0 ~~~~0~~~~ \\
  ~~~~\textbf{d} ~~~~\textbf{c} ~~~~\textbf{1} ~~~~\textbf{c} ~~~~\textbf{d} ~~~~0 ~~~~0~~~~ \\
  ~~~~0 ~~~~\textbf{d} ~~~~\textbf{c} ~~~~\textbf{1} ~~~~\textbf{c} ~~~~\textbf{d} ~~~~0~~~~ \\
  ~~~~0 ~~~~0 ~~~~\textbf{d} ~~~~\textbf{c} ~~~~\textbf{1} ~~~~\textbf{c} ~~~~\textbf{d}~~~~ \\
  ~~~~0 ~~~~0 ~~~~0 ~~~~\textbf{d} ~~~~\textbf{c} ~~~~\textbf{1} ~~~\textbf{c}~~~~ \\
  ~~~~\textbf{d} ~~~~0 ~~~~0 ~~~~0 ~~~~\textbf{d} ~~~~\textbf{c} ~~~~\textbf{1}~~~~ \\
 \end{pmatrix}$$
where $d$ and $c$ are different values between $-1$ and $0$. Furthermore,
$$2c + 2d = -1$$
My questions are to find expressions for

Second largest eigenvalue modulus (SLEM) or eigenvalues
Inverse of $X$

Thanks
Comment: $c$ and $d$ will have to be in the interval $[-\frac{1}{2}, 0]$ in order the have the relation $2c+2d=-1$.
Answer: $1-\sqrt{2} c$ is the second largest eigenvalue. For $c=-\frac{1}{2}$ it gives the second largest modulus.
According to maple this is the determinant:
$$ (2d-1)(-1+2c^2)(2c^4-4c^2+2dc^2-4d^3+2d-2d^2+1) . $$


How to export the contents of nodes in a view

Question: I have a view that displays content based on some criteria. I would like to export all of the content of the results of the view into a text document or Excel spreadsheet, as I am intending to edit them for a book. Any idea how to do this?
Answer: The module I use for this is http://drupal.org/project/views_data_export
You create a new style and attach it to your existing page/pane, you can export:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML
Answer: Take look at these modules:
Views Data Export,
Views Excel Export
Here is screencast about Views Data Export
http://www.lullabot.com/articles/module-monday-views-data-export


using REST webservices as a datasource for Lift?

Question: Is there a way to use a webservice (REST in this case) as the data source for a Lift application? I can find a number of tutorials/examples of using Lift to provide the REST API, but in my case the data is hosted elsewhere and exported as a REST webservice. Pointers to doc are greatly appreciated.
Thanks,
Jeff
Answer: This is not related to Lift in fact. There is a lot of different pieces of information already:

HttpClient library as was suggested already,
or Dispatch Scala library for accessing HTTP services
information on how to cache data in Scala in various ways in case you need it

Think about caching thoroughly, it is generally a good choice if your application generates a lot of requests and you can afford caching. Caching will let you achieve many goals:

decrease response time, as you do not depend on the remote service (if you do synchronous data processing)
avoid Denial of Service in case the remote service dies. Otherwise your application will generate many sockets to read data and exhaust resources (either sockets or threads or something else)
do not exceed SLA of the remote service, as many services constrain the number of requests you are allowed to pefrorm per some unit of time.

So you can just sit and put these things together, that's it.
Answer: If you really want to be fancy, you can create a Record implementation for a REST-based data source.  There's already one of these in existence that works with CouchDB.  Using the lift-couchdb module, the interactions with CouchDB are abstracted away and all you deal with is the Scala code.  There is a short wiki page with instructions on how to get started with lift-couchdb here:
http://www.assembla.com/wiki/show/liftweb/CouchDB
The pertinent source code files are available here:
http://github.com/lift/lift/tree/master/framework/lift-persistence/lift-couchdb/src/main/scala/net/liftweb/couchdb/
Using the Record interface gives you access to lots of Traits which you use to provide functionality with minimal code-writing such as creating HTML forms, providing lifecycle based calls, and easy hooks for validation.
Answer: I've put a scala layer over HttpClient and then use that.  I've been meaning to put this on github for some time.
Comment: Then do it. If you add the code I would give you a point here easily!! ;)
Answer: I use Dispatch (which is a wrapper around HttpClient) for making REST calls. Looks nice and simple


Cardinal Inequality without using Choice

Question: Let $k$ be an infinite cardinal (i.e. not in bijection with any natural number), show that
$\mathbb{N} \leq 2^{2^k}$
This is very easy with choice, without it I don't even know where to start.
Answer: HINT:

If $k$ is infinite, then $k$ contains subsets of every finite size.
Of course, there will be many subsets of $k$ of each finite size.
Do you see how to identify a given natural number $n$ with a certain family of subsets of $k$?
Comment: By induction we know that $k$ contains a subset of cardinality $n$ for any natural number $n$. So we can define a function $f:\mathbb{N}−>P(P(k))$ which maps n to the set of subsets of cardinality n. This function is clearly injective. Is this correct?
Comment: @Tim Yup, that's it. By the way, if you play around with this for a while, you'll see that it's very hard to get an injection $\mathbb{N}\rightarrow P(k)$ - it turns out that there need not be one! (Although actually proving possible nonexistence is of course extremely hard, and requires **forcing**.)


My slider's images have larger file-size than their originals

Question: I have a slider in my homepage and this slider has 3 photos named a.jpg, b.jpg, and c.jpg.
The original file's sizes are (respectively), 42kb's, 20kb's, 52kb's. And yet when I download them from my slider (Flexslider) they whey much larger (c for example is 191 kb's).
Answer: Replace image style from the Slider's View (At Views module). I kept it without any style so the image won't be scaled to a larger style (You could scale it yourself with CSS in the relevant Div at the slider and it won't affect size).


Python - How to return a double with eval()

Question: Sorry if this has already been asked, I couldn't find anything on it.
I'm new to python and I'm making a calculator using Tkinter. With the evaluation of the equation entered, it will only return decimals if you use a decimal in the equation. For example, if you type in 3/2 it will return 1. Is there any way to return answers as a double other than creating my own method for each problem type?
code:
def enter(self):
    answer = self.text.get(0.0, END)
    answer = eval(answer)
    self.text.delete(0.0, END)
    self.text.insert(END, answer)

Comment: This is *not* the way to write a calculator. You should be parsing the input string, not using `eval` at all. `eval` is `evil`.
Comment: To be fair, parsing/evaluating arbitrary infix operations yourself is not trivial, and slapping `eval` in there is a one-line implementation.  It's reasonable to put `eval` in, write the rest of your program around it, then swap it out for your own much-safer implementation later.  (then wash your hands because use of `eval` makes you feel *unclean*)
Answer: To get floating-point division for integer inputs in Python 2, use
from __future__ import division

at the top of your code, before everything else. Note that this will affect the whole file, not just the eval.
Answer: In python2, either import __future__, or convert to float first.
Importing __future__:
>>> from __future__ import division
>>> eval('3/2')
1.5
>>>

Or call the numbers with a trailing 0:
>>> eval('3.0/2.0')
1.5
>>>

However, the from __future__ import division is only necessary in python2, because by default the future versions of python call this.
When you import __future__, the division applies for all future equations you work on.
>>> from __future__ import division
>>> 3/2
1.5
>>> 10/9
1.1111111111111112
>>> 1/3
0.3333333333333333
>>> 7/8
0.875
>>> 7/9
0.7777777777777778
>>>

Comment: Importing `__future__` does nothing; only the `from __future__ import whatever` form is magic.
Comment: Edited, you beat me by 27 seconds :)


convert 4.5 to 4 but 4.6 to 5 in javascript

Question: I have to divide n number into 3 parts according to given rule but the divided number should not be a floating-point number if the given n is an odd number.
Example
`const rule = [50,30,20]` . // in percentagee

 const n = 10;

the expected result should // 5,3,2

but if the given number is an odd number then the output should be as given below
 n = 9
 output 4,3,2

when getting the percentage according to rules it comes as follow
4.5,2.7,1.8

Now I want if the fractional part of the number is up to .5, the argument should be rounded to the next lower integer. If the fractional part of the number is greater than .5, the argument is rounded to the next higher integer.
This is NOT asking how to round floating point numbers, as the dupe target says. This is asking how to round DOWN .5 cases.
ANSWER: var result = -Math.round(-num);
Comment: @NinaScholz `Math.round` will round 4.5 to 5 not to 4 per the post.
Comment: @NinaScholz My first try was Math.round but that does fit into the requirement.  I know it can be done in many ways like splitting number and then writing if and else condition. But I am looking for if there is any built-in feature to support this requirement
Answer: You can do this by negating both the result and the argument to Math.round.
E.g. var result = -Math.round(-num);
The only thing this changes is the .5 case, as -4.5 rounds up to -4, then you simply change the sign again.
Comment: Nice! That was easy :)


keep double slashes when working with passenger

Question: I've urls on my site that have nested urls encoded by encodeURI function.
www.site.com/http%3A%2F%2Fwww.site.com%2F

My site is running using nginx 0.8.53
The problem is that when nginx gets such url it decodes the whole url and remove double slashes passing incorrect url down to passenger and then in my ruby code.
Here is my general nginx configuration:
daemon off;

user  www-data;
pid   /var/run/nginx.pid;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/local/rvm/gems/ruby-1.9.2-p136@global/gems/passenger-3.0.2;
    passenger_ruby /email@example.com/ruby;

    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    tcp_nodelay        on;

    gzip  on;

    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        log_format combined-realip '$remote_addr ($http_x_real_ip) - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
        access_log /opt/nginx/logs/access.log combined-realip;

        if (-f /home/site.com/current/maintenance) {
            return 503;
        }

        root /home/site.com/current/public;
        passenger_enabled on;

        rack_env production;
        passenger_set_cgi_param SERVER_NAME $http_host;

        error_page 503 /503.html;
        location = /503.html {
            root   html;
        }

        include /home/site.com/current/*nginx.conf;
    }
}

I tried setting merge_slashes to off in /home/site.com/current/nginx.conf
merge_slashes off;

but it didn't work. I don't have any ideas except start passenger as standalone and use proxy_pass, but another problem is that I'm using cloud service which provides nginx and passenger and I can only edit that /home/site.com/current/nginx.conf and nothing else.
Please help me.
Comment: Are you sure that nginx was restarted so that 'merge_slashes' option  was really applied?
Comment: yes, restarted couple of times, still doesnt work
Answer: merge_slashes only works as a directive in a server block when that server is a default server. Specify it instead in your http block.
Note however that even with merge_slashes off, nginx will still decode the slashes, and Passenger will still merge them. I worked around this on my site by looking for things like "http:/" in my action and modifying them appropriately:
missing_double_slash_match = /\A([a-z]+)\:\/([^\/])/.match(term)
if !missing_double_slash_match.nil?
    term = term.sub(missing_double_slash_match[0], "#{missing_double_slash_match[1]}://#{missing_double_slash_match[2]}")
end


Search bar in react works, but experiencing very strange behaviour

Question: In a component when an input is provided it dispatches the input to a reducer
const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value)
    dispatch(userActions.searchByName(searchTerm));
  }

Then the reducer takes that value and tries to filter the array based on that input
searchByName: (state, action) => {
      state.search = action.payload;

      let newArray = state.users.filter((user) =>
        user.name.toLowerCase().includes(state.search.toLowerCase())
      );

      state.users = newArray;
    },

Then this whole array is displayed in one of the other components. The search bar works to some extent:
When you start typing into the search bar it only starts to work after second input. In console I have noticed that if you type "Timmothy" it will only register "Timmoth" in the state.
Additionaly, if I delete text from the input, the state of the array doesn't update and stays the same even though the input value changes.
So what happens currently is if you start typing in the search bar, it updates the array, but always only registers second to last keystroke. Additionally, if you delete input from the search bar, it doesn't register. The value changes, but the array stays with only few items left.
I have tried to not use the additional variable to store the state and do it like this
state.users.filter((user) =>
       user.name.toLowerCase().includes(state.search.toLowerCase())

But then absolutely nothing happens. Would appreciate if someone could tell me what I'm missing here
EDIT
This is the component that receives that input
<input onChange={changeSearchTerm} type="text" value={searchTerm}></input>

And the searchTerm value is saved in useState - const [searchTerm, setSearchTerm] = useState("");
Comment: Please share your search bar component code/JSX as well. What event handler are you using?
Comment: Apologies, I updated the question and added additional info
Answer: From what I can tell, it only works after the second input because of this block:
const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value)
    dispatch(userActions.searchByName(searchTerm));
  }

State setters like setSearchTerm are actually asynchronous. This means that after you call setSearchTerm, on the next line the value of searchTerm is still the old value.
You can instead do one of the following:
const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value)
    dispatch(userActions.searchByName(e.target.value));
}

const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value, () => {
      // This callback runs only after state has changed
      dispatch(userActions.searchByName(searchTerm));
    });
}

Edit: Sorry I missed that you used useState/functional. You can use useEffect:
const changeSearchTerm = (e) => {
    setSearchTerm(e.target.value);
}

useEffect(() => {
   if (searchTerm.length > 0) {
     dispatch(userActions.searchByName(searchTerm));
   }
}, [searchTerm]);

This way your dispatch will correctly run whenever searchTerm's value changes for sure.
https://reactjs.org/docs/react-component.html#setstate
Comment: Thanks for your reply, unfortunately, first example still returns the same issues, while the second one returns an error and doesn't work :(
Comment: Could you share the error in the second usage?
Comment: Yes its `tate updates from the useState() and useReducer() Hooks don't support the second callback argument.`
Comment: @KivDaor Ah gotcha added an edit using useEffect that should work!
Comment: Thank you, this solved the problem of input "lagging". However, in the actual array that's been displayed it gets updated when you write in the search bar, however, if you delete the input it doesn't update. Do you have any thoughts why would that be?
Comment: Ah get rid of the of "if searchTerm.length > 0" I only added that condition in case it was a required check but if you remove it, your reducer state should update properly when the input is empty
Comment: Yes, I removed that before for it to work properly. I'm realising that my search functionality works properly when you type, but it doesn't when you delete, because updating the input returns a new array, and on deleting it doesn't go back to the previous state of the array. I can't figure out how to solve that though, do you have an idea?
Comment: Could you please share your full component code then as it's not clear how you're rendering things or consuming the array. It'll help to figure things out. Also are you using the useSelector hook?
Comment: I am almost certain that the issue is how I use the reducers to manage the state. I asked another question in https://stackoverflow.com/questions/72164352 to better explain it, if you would like to take a look
Comment: I'll take a look at that and answer. I think I know what the issue might be but since you asked the second part of your question in a separate stackoverflow thread, if this answer solved your first part then please consider marking it accepted!
Comment: My apologies, I marked your answer as accepted :) if you could take a look at the other issue, would be much appreciated
Comment: No worries at all! Posted an answer there


how to use images uploaded to public://

Question: with a form I've got the possibility to upload images, this is the piece of code that says where the files go: '#upload_location' => 'public://',
this is the piece of code which generates the rows in my table view:
$rows[] = array(
        'data' => array(
            l($node->id, 'node/'. $node->id),
            $node->url,
            $node->title,
            $icon = "icon'>",
            $node->created,
            $delete = "id/delete'> " . t('Delete') . " | id/edit'> " . t('Edit') . ""
        )
  );

notice '$icon'. $node->icon returns for example usa.gif. But of course the path is invalid.
The question is: how can I use my images? I cant figure it out
There's probably some drupal way to do this, advice is highly appreciated!
Comment: You can also try file_create_url($uri)
Answer: If $node->icon is the path relative to public://, then you can use the following code.
if ($wrapper = file_stream_wrapper_get_instance_by_uri("public://{$node->icon}")) {
  $url = $wrapper->getExternalUrl();
}

The code works also for stream wrappers that are not local, for which the file is not local to the server running the code.

how to use images uploaded to public://


CakePHP routing - search parms

Question: I need to set up routing based on search parms (I'm using CakeDC search plugin)
URL should look like this: /apartments/studio-apartments

instead of this: /apartments/propertytype_id:1
I've already tried adding routes like this one:
Router::connect('/apartments/studio-apartments', array('controller'=>'apartments', 'action'=>'index'), array('pass'=>array('propertytype_id:1')));

or
Router::connect('/apartments/studio-apartments', array('controller' => 'apartments', 'action' => 'index', 'propertytype_id:1'));

or that one from Cake book
Answer: Try this in your routes.php:
Router::connect('/apartments/studio-apartments',
    array('controller' => 'apartments','action' => 'index'),
    array('propertytype_id' => '[0-9\-]+')
);

CakePHP routing - search parms


Content type creation with table of fields

Question: I want to be able to create a content type with a number of fields (naturally). One section of the content type needs to be like the attached image with the ability to:
 - group items together (e.g. an 'ingredient' in a recipe' - "2 cups flour, sifted"
 - link (via autocomplete) to existing nodes [INGREDIENT NAME field below]
 - add multiple items with a "more" button
Below is a screenshot from the 'Recipe' module. Is it possible to create this structure with CCK and can this be then added in a feature?
Answer: Use field collection to make a group of fields, then set that group to unlimited entries, simple.
Comment: thanks that worked a treat! I also used field_collection_table to make adding content easier
Comment: needed to apply this patch to field_collection_table to make it work correctly - https://www.drupal.org/node/2104475
Comment: Good work! Did you need to add the extra bracket as per comment #12?  If so it would be useful to let others know on that thread that you found the comment to be correct.
Comment: yeah extra bracket is needed.


Spring Cloud Stream Kafka - Serde class not found: org.apache.kafka.common.serialization.Serde$StringSerde

Question: I am trying to build a simple Kafka Streams application using Spring Cloud Stream framework. I can connect to the stream to push raw data for processing. But when I try to process the stream for event counting by key, I get Serde class not found: org.apache.kafka.common.serialization.Serde$StringSerde exception when I run the application. I checked in my project included libraries and I could locate the Serde class, it's not missing. I am not sure why at run time it is not being loaded!
Below are my source files.
com.pgp.learn.kafka.analytics.AnalyticsApplication
package com.pgp.learn.kafka.analytics;

import com.pgp.learn.kafka.analytics.model.PageViewEvent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.kafka.common.serialization.Serde;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.kstream.*;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
@EnableBinding(AnalyticsBinding.class)
public class  AnalyticsApplication {

    public static void main(String[] args) {
        SpringApplication.run(AnalyticsApplication.class, args);
    }

    @Component
    public static class PageViewEventSource implements ApplicationRunner {
        private final MessageChannel pageViewOut;
        private final Log log = LogFactory.getLog(getClass());

        public PageViewEventSource(AnalyticsBinding binding) {
            this.pageViewOut = binding.pageViewsOut();
        }

        @Override
        public void run(ApplicationArguments args) throws Exception {
            List<String> names = Arrays.asList("Peter", "Tom", "Ady", "Nency", "George", "Kevin", "Chelsey", "Thomas");
            List<String> pages = Arrays.asList("About", "Contact", "Blogs", "Gallery", "Music", "Site-map", "News");

            Runnable runner = () -> {
                String rName = names.get(new Random().nextInt(names.size()));
                String rPage = pages.get(new Random().nextInt(pages.size()));

                PageViewEvent event = new PageViewEvent(rName, rPage, Math.random() > .5 ? 10L : 1000L);

                Message<PageViewEvent> message = MessageBuilder
                        .withPayload(event)
                        .setHeader(KafkaHeaders.MESSAGE_KEY, event.getUserId().getBytes())
                        .build();

                try {
                    this.pageViewOut.send(message);
                    log.info("Sent: " + message.toString());
                } catch (Exception e) {
                    log.error(e);
                }
            };

            Executors.newScheduledThreadPool(1).scheduleAtFixedRate(runner, 1, 1, TimeUnit.SECONDS);
        }
    }

    @Component
    public static class PageViewEventProcessor {
        private final Log log = LogFactory.getLog(getClass());

        @StreamListener
        @SendTo(AnalyticsBinding.PAGE_COUNT_OUT)
        public static KStream<String, Long> process(
                @Input(AnalyticsBinding.PAGE_VIEW_IN_CHANNEL) KStream<String, PageViewEvent> events) {
            return events
                    .filter((s, pageViewEvent) -> pageViewEvent.getDuration() > 10)
                    .map((s, pageViewEvent) -> new KeyValue<>(pageViewEvent.getPage(), 0L))
                    .groupByKey()
                    //Also tried using below line, but no luck
//.groupByKey(Serialized.with(Serdes.String(), Serdes.Long()))

.count(Materialized.as(AnalyticsBinding.PAGE_COUNT_MV))
                    .toStream();
        }
    }
}

com.pgp.learn.kafka.analytics.AnalyticsBinding
package com.pgp.learn.kafka.analytics;

import com.pgp.learn.kafka.analytics.model.PageViewEvent;
import org.apache.kafka.streams.kstream.KStream;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

public interface AnalyticsBinding {

    String PAGE_VIEW_OUT_CHANNEL = "pvout";
    String PAGE_VIEW_IN_CHANNEL = "pvin";
    String PAGE_COUNT_MV = "pcmvc";
    String PAGE_COUNT_OUT = "pcout";
    String PAGE_COUNT_IN = "pcin";

    @Input (PAGE_VIEW_IN_CHANNEL)
    KStream<String, PageViewEvent> pageViewsIn();

    @Output (PAGE_VIEW_OUT_CHANNEL)
    MessageChannel pageViewsOut();

    @Output (PAGE_COUNT_OUT)
    KStream<String, Long> pageCountOut();

}

application.properties
# defaults
spring.cloud.stream.kafka.streams.binder.configuration.commit.interval.mms=1000
spring.cloud.stream.kafka.streams.binder.configuration.default.key.serde=org.apache.kafka.common.serialization.Serde$StringSerde
spring.cloud.stream.kafka.streams.binder.configuration.default.value.serde=org.apache.kafka.common.serialization.Serde$StringSerde
spring.cloud.stream.kafka.binder.brokers=220.127.116.11
#
# page views out
spring.cloud.stream.bindings.pvout.destination=pvs
spring.cloud.stream.bindings.pvout.producer.header-mode=raw
#
# page views in
spring.cloud.stream.bindings.pvin.destination=pvs
spring.cloud.stream.bindings.pvin.consumer.header-mode=raw
#
# page count out
spring.cloud.stream.bindings.pcout.destination=pcs
spring.cloud.stream.bindings.pcout.producer.use-native-encoding=true
spring.cloud.stream.kafka.streams.bindings.pcout.producer.keySerde=org.apache.kafka.common.serialization.Serdes$StringSerde
spring.cloud.stream.kafka.streams.bindings.pcout.producer.valueSerde=org.apache.kafka.common.serialization.Serdes$LongSerde

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.pgp.learn.kafka</groupId>
    <artifactId>analytics</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>analytics</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RC2</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-kafka-streams</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-test-support</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>

</project>

Exception while Running
java.lang.IllegalStateException: java.lang.IllegalStateException: Serde class not found:
    at org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.adaptAndRetrieveInboundArguments(KafkaStreamsStreamListenerSetupMethodOrchestrator.java:308) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.orchestrateStreamListenerSetupMethod(KafkaStreamsStreamListenerSetupMethodOrchestrator.java:164) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binding.StreamListenerAnnotationBeanPostProcessor.doPostProcess(StreamListenerAnnotationBeanPostProcessor.java:195) ~[spring-cloud-stream-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binding.StreamListenerAnnotationBeanPostProcessor.lambda$postProcessAfterInitialization$0(StreamListenerAnnotationBeanPostProcessor.java:167) ~[spring-cloud-stream-2.1.0.RC4.jar:2.1.0.RC4]
    at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_161]
    at org.springframework.cloud.stream.binding.StreamListenerAnnotationBeanPostProcessor.injectAndPostProcessDependencies(StreamListenerAnnotationBeanPostProcessor.java:285) ~[spring-cloud-stream-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binding.StreamListenerAnnotationBeanPostProcessor.afterSingletonsInstantiated(StreamListenerAnnotationBeanPostProcessor.java:105) ~[spring-cloud-stream-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:863) ~[spring-beans-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at com.pgp.learn.kafka.analytics.AnalyticsApplication.main(AnalyticsApplication.java:35) [classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_161]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_161]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_161]
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:558) [spring-boot-maven-plugin-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_161]
Caused by: java.lang.IllegalStateException: Serde class not found:
    at org.springframework.cloud.stream.binder.kafka.streams.KeyValueSerdeResolver.getKeySerde(KeyValueSerdeResolver.java:177) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binder.kafka.streams.KeyValueSerdeResolver.getInboundKeySerde(KeyValueSerdeResolver.java:74) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    at org.springframework.cloud.stream.binder.kafka.streams.KafkaStreamsStreamListenerSetupMethodOrchestrator.adaptAndRetrieveInboundArguments(KafkaStreamsStreamListenerSetupMethodOrchestrator.java:246) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    ... 22 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.apache.kafka.common.serialization.Serde$StringSerde
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_161]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_161]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_161]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_161]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_161]
    at org.apache.kafka.common.utils.Utils.loadClass(Utils.java:333) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:322) ~[kafka-clients-2.0.1.jar:na]
    at org.springframework.cloud.stream.binder.kafka.streams.KeyValueSerdeResolver.getKeySerde(KeyValueSerdeResolver.java:171) ~[spring-cloud-stream-binder-kafka-streams-2.1.0.RC4.jar:2.1.0.RC4]
    ... 24 common frames omitted

Any help to find what I am doing wrong here? I am new to Kafka and Stream processing. So, please excuse me if I am doing any silly mistake.
Comment: Try adding the base kafka streams dependencies
Answer: You have a typo in your configuration properties:
spring.cloud.stream.kafka.streams.binder.configuration.default.key.serde=org.apache.kafka.common.serialization.Serde$StringSerde
It is missing 's' in Serde. Should be ...serialization.Serdes$StringSerde
Comment: Thanks for your suggestion. After adding 's' to the Serde in default configuration, I stopped getting the exception as listed above. However, now my program stopped recognizing the broker configuration and takes the default configuration with "localhost". Any help to solve that problem now?
Comment: It is hard to say. Perhaps you can post  sample project that reproduces the issue in the GitHub, so we can look.


ace:chart : how to change size of chart

Question: I am using icefaces 3.2 ace chart and testing on IE8/firefox. I have a BarChart. I want to know how can i set the height and width of my chart. The problem is if the x axis labels length increases , i notice that the chart height decreases. Just to highlight icefaces charts framework is based on jqplot from jquery.
Answer: Add in a css:
<code>.jqplot-target {
    height: HEIGHT px;
    width: WIDTH px;
}
</code>
You can also use the setTickAngle() property to display labels in diagonal
<code>xAxis = new Axis();
xAxis.setAutoscale(true);
xAxis.setTickAngle(-30);
</code>

ace:chart : how to change size of chart


Backpropagation final layer δ term

Question: I'm trying to understand the calculation for the gradient of the blue weight shown in the NN below.

In Andrew Ng's Machine Learning coursera module, the δ term for the final layer of the NN is:

However, in other sources, the δ term for the final layer is:

where the red box has been added to the formula (the derivative of the sigmoid activation function).
Both sources then multply δ by the activation of the previous node to get the gradient:

What is the reason for the discrepancy between these two calculations? Could it be because Andrew assumes the activation function of the final layer is g(z) = z?
Answer: The difference is that in Andrew Ng's video, the Logistic regression cost function is used.

Conversely, the other source uses the Squared Error regression cost function.

The derivation of the delta term using the Logistic regression function is as follows:

Backpropagation final layer δ term