Show/hide fields in a form based on the value of a checkbox

Question: Is there a way to hide a specific or specifics fields in Drupal when you create content until you checked a checkbox?
Now it looks like this:

I need something like this:

But I need some checkboxes to decide if I have a certain field to show or not. Like this:
(Fieldcollection item 'some information' is showing up now because I checked the checkbox before the label)
Is there a module for this?
What would be nice is if all fields only become mandatory if you checked a checkbox.
Answer: In Drupal 7 you can use $form #states instead of custom jQuery script. Example:
<code>  $form['student_type'] = array(
    '#type' => 'radios',
    '#options' => array(
      'high_school'   => t('High School'),
      'undergraduate' => t('Undergraduate'),
      'graduate'      => t('Graduate'),
    ),
    '#title' => t('What type of student are you?')
  );

  // High school information.
  $form['high_school']['tests_taken'] = array(
    '#type' => 'checkboxes',
    '#options' => drupal_map_assoc(array(t('SAT'), t('ACT'))),
    '#title' => t('What standardized tests did you take?'),
    // This #states rule says that this checkboxes array will be visible only
    // when $form['student_type'] is set to t('High School').
    // It uses the jQuery selector :input[name=student_type] to choose the
    // element which triggers the behavior, and then defines the "High School"
    // value as the one that triggers visibility.
    '#states' => array(
      'visible' => array(   // action to take.
        ':input[name="student_type"]' => array('value' => 'high_school'),
      ),
    ),
  );
</code>
Answer: Drupal 8 has a very well structured system to show hide fields based on values of other fields. It is called the Form API #states system. You can see drupal.org documentation on #states.
While defining the form you can map the visible and invisible states of the form element based on the value of another form element.
This is an example from the documentation above
<code>$form['toggle_me'] = array(
  '#type' => 'checkbox',
  '#title' => t('Tick this box to type'),
);
$form['settings'] = array(
  '#type' => 'textfield',
  '#states' => array(
    // Only show this field when the 'toggle_me' checkbox is enabled.
    'visible' => array(
      ':input[name="toggle_me"]' => array(
        'checked' => TRUE,
      ),
    ),
  ),
);
</code>
There are other states besides visible and invisible that can be controlled through the same mechanism. Lullabot has a good article on Form API #states
Other states including making a field required is available. The full list is as follows.
<code>enabled
disabled
required
optional
visible
invisible
checked
unchecked
expanded
collapsed
</code>
Answer: You can use module conditional fields if you want to do this node form


Make Parent div draggable with Child div

Question: How can I make a parent div draggable with a child div?
I'm using the jquery-ui draggable function for this. I cannot find anything regarding my problem on the site, so I'm asking here.
The whole div should only be draggable with it's header and not the whole div.
http://api.jqueryui.com/draggable/
My Example:
https://jsfiddle.net/3xdLtask/1/

      child header

    content

Comment: DO NOT share to external sites. but instead create a working snippet
( or fiddle ) to reproduce your problem
Comment: you want to drag this modal box layout  only with header?
Answer: You have to use the handle event for getting the desired result. Check the api documentation here.
http://jqueryui.com/demos/draggable/#handle

Here is an working example below:

$("#MainDiv").draggable({
  handle: "#header"
});
* {
  margin: 0px;
  padding: 0px;
  font-family: arial;
  text-align: center;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

.ModalBox {
  border: 2px solid #000;
  width: 200px;
  background: red;
}

.Modal-header {
  background: #7bd4ff;
  width: 100$;
  height: 40px;
  border-bottom: 2px solid #000;
  color: #fff;
  padding: 10px;
}

.Modal-Body {
  height: 260px;
  background: #ffadc9;
  color: #fff;
  padding: 10px;
}

I am Dragabble header !

    I am child ! I am Child ! I am Child ! I am child ! I am Child ! I am Child ! I am child ! I am Child ! I am Child ! I am child ! I am Child ! I am Child ! I am child ! I am Child ! I am Child ! I am child ! I am Child ! I am Child ! I am child ! I am    Child ! I am Child ! I am child !


Programmatically set latitude and longitude exposed input

Question: I've been using geolocation 8.x-1.12 for a while now. I have a REST route that gets a view with my exposed form and returns the results.
Previously I did:
<code>$plugin = \Drupal::service('plugin.manager.geolocation.geocoder');
$geocoder = $plugin->getGeocoder('google_geocoding_api');
$geocode = $geocoder->geocode($zip_code);

$view = Views::getView('local_pharmacies');
$view->setDisplay('block_1');
$exposed = [
  'field_geolocation_proximity-lat' => $geocode['location']['lat'], // No longer exists in 3.x
  'field_geolocation_proximity-lng' => $geocode['location']['lng'], // No longer exists in 3.x
  'field_geolocation_proximity' => "50",
];
$view->setExposedInput($exposed);
$view->preExecute();
$view->execute();
</code>
I updated to 8.x-3.7 because I plan to upgrade to D9 soon. The above is no longer working. I think because field_geolocation_proximity-lat and field_geolocation_proximity-lng no longer exist. I tried diving into the source as well as kinting form alters to figure out how to properly set the coordinates but I cannot figure it out. Any ideas?
Answer: I finally figured out how its supposed to be formatted. Kinting after the view execute rather than before exposed the field names.
<code>$exposed = [
  'center' => [
    'coordinates' => [
      'lat' => $geocode['location']['lat'],
      'lng' => $geocode['location']['lng'],
    ],
  ],
  'field_geolocation_proximity' => "50",
];
</code>


Couldn't load the category php and ajax

Question: I am creating an e-commerce website. I completed the design part. While writing the coding part I ran in to the problem on couldn't display the categories inside the

I attached the code below what tried so far. there is no error displayed how to display the categories inside the div tag.
All categories display inside to this Div like order list

Jquery
 function getCategory(){
        $.ajax({
            type: 'GET',
            url: 'all_category.php' ,
            dataType: 'JSON',
            success: function (data) {
             console.log(data);

                $("categories").html(data.catname);

            },
            error: function (xhr, status, error) {
                alert(xhr.responseText);
//
            }

        });
    }

Database all_category.php
<?php
include("db.php");

$stmt = $conn->prepare("select id,catname,status from category order by id DESC ");
$stmt->bind_result($id,$catname,$status);

if ($stmt->execute()) {
    while ( $stmt->fetch() ) {
        $output[] = array ("id"=>$id, "catname"=>$catname,"status"=>$status);
    }

    echo json_encode( $output );
}
$stmt->close();

?>

Comment: In ajax you will get the response. Parse the response and make a string variable and then append to the required DOM element
Answer: Your jQuery syntax is slightly off - minor spelling issue;
 $("categories").html(data.catname);

should be
 $("#categories").html(data.catname);

Edit: to address the issue of the items not being added to your list, you'll need to append the element inside of your ajax's success handler:
$.each(data.catname, function(key, value) {
    $("#categories").append('
'+ value +'
');
});

Comment: My answer addresses one of your problems. When you run this, you're still unlikely to get the results you're looking for in the `` tags. If you can edit the question with what a `var_dump()` of `$output` looks like, then I can address the second problem.
Comment: sir i did it what the answer you posted but didn't work sir.
Comment:  tag how can i call in to ajex to display the output
Comment: Read my above comment, I'd need to know the output of `$output` in all_category.php
Comment: yes sir. $output  this is a  output in all_category.php
Comment: Obviously... again, I'd need to know what a `var_dump()` of `$output` looks like.
Comment: i made the output as json type sir . data will be success fully display on page. i tested using console.log(data). but how to pass it  tage inside the
Comment: I've told you what is needed, I don't know how to explain it any other way. Go back through my responses and see if you can help us help you :)
Comment: 0: {id: 55, catname: "Mobilenew", status: 1}
1: {id: 52, catname: "TV", status: 1}     this is $output i am getting how to pass this output into li tag    i did it like this $("#categories li").html(data.catname); no output displayed
Comment: Let me know if that helps you out, if not, print the console error logs if there are any.
Comment: Uncaught SyntaxError: missing ) after argument list  this error shown on the console.
Comment: Just posted a final update - but it seems like you could do a little bit of investigate debugging on your end at this point. Hopefully you get the problems resolved.

Couldn't load the category php and ajax


How do i shorten a pandas data frame based by the dates in one column

Question: So I have this data frame that has many columns, but I'm only interested in the data spanning from say 01/01/2009-01/01/2019 so I want to keep all the data in that range and get rid of everything else
Answer: Assuming date column name as date_column
df_new = df[(df['date_column'] > '01/01/2009') & (df['date_column'] <= '01/01/2019')]
print(df_new)

Comment: This also assumes that the column is already converted to datetime type. If not, you have to use "to_datetime" function from pandas.
Comment: yes, True!.....
Answer: If they're correctly formatted:
df_new = df[df['date_col'].between('2009-01-01', '2019-01-01')]

Answer: this will work no for any date format, dd-mm-yyyy or yyyy-mm-dd
df[(pd.to_datetime(df['Date']).dt.year >= 2009) & (pd.to_datetime(df['Date']).dt.year <= 2019)]

Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Randomisation for 2 site clinical study

Question: If I want to conduct a randomised study in 2 sites comparing two clinical treatment arms, and every site is expected to include 60-80 patients, is it acceptable to randomise every new patient with simple coin toss (one centralised scheme for all patients, regardless of site) or is some stratified randomisation more appropriate (stratified per center)? I have tried to understand urn randomisation and wonder if it would be a better model. If so, can you suggest an easy way of doing so? I have found RANDI3 online (http://dschrimpf.github.com/randi3/) but I have no idea whether I can 'trust' its output. Any advice welcome
Answer: Stratification is used to balance treatments within important subgroups. By "important" I mean related to the primary outcome. Trial site (centre) is often thought to be important because patients at different centres are likely to differ in severity of illness or socio-economic background, and so may well have different average risks of poor outcome. However, you should consider whether this is likely to be the case in your trial before automatically stratifying by centre.
The most popular method of balancing treatments within strata is random permuted blocks. This is easy to understand and you can create stratified blocked lists yourself so you don't need to trust a "black box" like RANDI3.

Randomisation for 2 site clinical study


Techniques for "Dynamics" with Distortion on Electric Guitar

Question: Recently I went to a workshop on electric guitar. Between several subjects, the presenter talked about dynamics with distortion.
He said that you can use palm mute to create the effect of a "growing melody". For example, you start your song with a full palm mute, and you keep going slowly releasing your hand from the strings during the time until you achieve a "full open sound" (just before a chorus, for example).
I understand that maybe with heavy distortion it's not really dynamics in terms of "amplitude" that we're talking about, but I couldn't think of any other techniques that could have a similar effect of dynamics. The subjects in the workshop changed and I forgot to ask my question:
What other techniques you can use on electric guitar with distortion to bring something similar to "dynamics" to your sound?
Answer: It's true that distortion, especially heavy distortion causes a lot of compression and evens out most of the dynamics. But a softly picked note is not only quieter, it's also duller, that is, it contains less high frequency, even after distortion. Since we are more sensitive to high frequencies, some dynamics can be achieved just by picking softer or harder. It's not drastic, but it's audible. It's mostly a change in timbre but there is some difference in perceived loudness too. So one way of achieving (at least some) dynamics is to just pick softly.
Palm muting decreases the high frequency content even further. So a palm muted note will be perceived as being softer than a non-palm muted note even though the peak to peak amplitudes don't change much.
You can extend this idea to the other end of the spectrum by applying a little bit of pick harmonics, i.e. "digging in" for accent because harmonics add more high frequency content.
The volume controls on the guitar and amp or a volume pedal before or after the preamp is yet another way to control the dynamics for a heavily distorted electric guitar.
Comment: I also considered mentioning picking position (brighter when closer to bridge, mellower when closer to neck). But picking closer to the bridge also decreases the volume, negating the perceived loudness increase. It is nevertheless an often neglected way of changing the timbre. Heavily distorted electric guitar is not the most expressive instrument in terms of dynamics. So I tend to try to get as much timbral variation as I can get as a substitute. Picking angle is another good variable most people tend to forget.
Comment: As another way of broadening the timbre range, consider putting away the pick sometimes! Fingerstyle is mostly associated with clean/acoustic guitar, but guitarists like Jeff Beck (who's also master of volume- & tone-pot dynamic play) demonstrate how much extra possibilities it offers in distorted sounds.
Comment: Thanks for the nice answer. So it's like stop thinking of amplitude and start thinking on spectrum and tone. The idea of using volume (or even expression pedals) is nice, but I was more focused on "bare hands" techniques, as the harmonics you mentioned. If you have any other examples of more "bare hands" techniques, please add them to your answer. Thanks again!
Answer: Controlled feedback is a useful technique although it's as old as Hendrix.  I like to use high gain and distortion and a wah so that I can hit a single note and control its feedback crescendo and decrescendo with careful muting. When I do this, I put the wah between the distortion pedal and the guitar.

What are some techniques to control feedback in a musical setting?
Comment: I didn't know what was the "controlled feedback", so I got this video https://www.youtube.com/watch?v=-YpUVsCbrEE which shows what it is :) The feedback is a good idea as well. And I'd say it's "bare hands" in someway.
Comment: This question explains a little bit more about how to do it: http://music.stackexchange.com/questions/2518/what-are-some-techniques-to-control-feedback-in-a-musical-setting
Answer: Playing through a wah wah, and gradually increasing the resonant frequence (creating more "open" vowel sounds) can lend a dynamic effect.
Answer: One important observation in the perception of loudness is that our ears perceive single-frequency sounds as louder than more spread-spectrum sounds. Loudness is also associated with the duration of a tone.
Therefore, when a guitar tone is heavily distorted, a single, clear, held-out note will sound much louder than the momentary crunch of a palm-muted power chord.
Answer: When it comes to dynamics one of the best things you can do is to listen to a lot of musicians and analyse what they are doing. In a three-piece band each instrument has to carry a lot of musical weight, and for me the classic case study in basic guitar dynamics is probably Nirvana- listen to Nevermind and pay attention to the changes between light and heavy distortion ( the guitar is almost always at least a little distorted ) and the movement from picked notes and drones to full on heavy chords.
Also listen for the way that the whole band will cut out leaving just one instrument for a moment and then come crashing back in- often creating spaces and playing with listener expectation is as important as the actual notes you play.
When you are working with a lot of distortion, you might also want to be careful of how fast you play - once you hit a certain speed it's very hard for the listener to pick out the notes or rhythm you are playing with the distortion around them. It can be much more effective to hold off a little and give each note or chord enough space to have rhythmic or melodic impact.
Answer: As the great Australian recording engineer, John L.Sayers is fond of saying, 'If you want a good guitar sound, get a good guitarist'. If you dial up the dirt you're dialling down the dynamics, but if you back off the drive a little and gradually wean yourself off full-gain distortion what you lose in the easy playability of max distortion you will gain in dynamic control.


Seeking help to evaluate an integration

Question: Let Say, $G \left(x \right)$ is the Cumulative distribution function of a random variable $X$ which is continuous, now consider below integral
$\int_{0}^{\alpha} 1 \left(G \leq u \right)du$, where $1 \left( x \right)$ is equal to 1 if $x$ is true and 0 otherwise.
The answer I obtain for above integration is $\left( \alpha -G \right) 1 \left( G \leq \alpha\right)$.
How can I obtain this answer using fundamentals of integration?
Comment: A specific example would help make it clearer.
Answer: Within the integral, $0 \leq u \leq \alpha$. Suppose $\alpha < G$. Then $u < G$ throughout the integral, and so $1 \left(G \leq u \right) = 0$ throughout. The integral then evaluates to $0$.
If $\alpha > G$, and since $G$ must be $\geq 0$, then $0 \leq G < \alpha$. So $1 \left(G \leq u \right) = 0$ for $0 \leq u < G$, and $1 \left(G \leq u \right) = 1$ for $G \leq u \leq \alpha$. The integral then evaluates to $\alpha -G$.
The $\alpha = G$ case is similar to the $\alpha < G$, since the integral is non-zero only at a single (finite number) point, and so the integral is still $0$.
$\left( \alpha -G \right) 1 \left( G \leq \alpha\right)$ then represents the three cases through a single expression.

Seeking help to evaluate an integration


Can't call functions in parent from iframe

Question: I'm trying to make a call to 2 functions setListener(); and addNewBox(); from within an iframe.
I've looked everywhere and tried everything and I can't get it to work.
I don't have access to the head of the parent because it is being constructed in chunks through php require.
This is a rough mockup of what the parent file looks like.

<?php require "head.html" ?>

<?php require "content.html" ?>

content.html mockup:

image_editor.html mockup:

<form id="image_form">
<input type="submit" value="Submit"/>
</form>

I have tried every solution I could find online, from using top, to re-declaring the functions in parent in public format (window.myFunction = function() { };).
I would appreciate any advice.
Thanks
UPDATE:
After some debugging it seems that the reason the calls aren't working is because execution stop one line before them. Somehow this line "$(".new", window.parent.document).remove();" breaks everything. I now have to figure that one out. I appreciate all your help.
Answer: This happens at least because setListener() and addNewBox() are not in the global scope of window.parent. To fix this you need to move them out of $(document).ready(function(e) {...}()).
Comment: Nope, none that are related.
Comment: If one of them cuts the execution before it gets to this part of the code?
Comment: No, its just warning about fb button not loading.
Comment: No, but you were right. The line right before, "$(".new", window.parent.document).remove();" is preventing anything further from being executed for whatever reason.
Answer: This is because they are in $(document).ready(function(){});
You can fix it like this:
$(window.parent).bind(setListener);
$(window.parent).bind(addNewBox);

Hope it helps!


How to enable authenticated access to Windows NFS shares from Solaris 5.10?

Question: We're serving some NFS shares from a Windows Server 2008 R2 x64 machine, that are accessed by Solaris 5.10 clients. How do we configure authentication so that a certain group have write permission to the shares from Solaris? Thanks for any help! :)
Answer:
We're serving some NFS shares from a Windows Server 2008 R2 x64 machine,

There's your problem right there.
All kidding aside, setting up proper authentication isn't too bad with Services for NFS on Windows. Here's a guide from microsoft with all the relevant details: http://technet.microsoft.com/en-us/library/dd758767%28WS.10%29.aspx
Comment: Having experimented a bit, it doesn't seem like giving RW access to my netgroup makes any difference though? So long as all machines were given RW access, I could write to the mounted share if and only if I had Unix-level write access on the client. When I tried taking away write access from all machines on the server, I couldn't write even if my netgroup had write access. Could you provide some instructions on how to mount a Windows NFS share correctly from a Solaris client?
Comment: I'm not following what you're asking. When you mount an NFS share, you're going to be passing your current user information, which should be mapped to a username on the Windows server. Information about advanced mapping on Windows is here: http://go.microsoft.com/fwlink/?LinkId=127917
Comment: Thanks for the user name mapping info. Part of the problem, though, is that we can't see any way to specify whom to mount as on Solaris. Are you sure user name mapping, as described in that article, is still available in 2008 R2 though? I suspect it's been removed.
Comment: It appears I should actually use Active Directory user lookup, in order to map the Unix user who's mounted a share to an AD account.
Comment: I'm 99% sure that the user that is accessing the data is what the permissions are based on. The link that I provided is what is linked off the answer's Technet article, which applies to 2008 R2. It should still be applicable. I apologize though, the comment link was for simple mapping. A more complete guide is here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=5f4c294c-8692-4235-8236-8ea809ae71f7
Comment: Thanks. Do you know how to specify user to mount as in /etc/vfstab on Solaris 5.10, though?
Comment: It's not set in the vfstab. That just creates the mount, but the effective user permissions depend on the logged in user interacting with the mounted file system. There's a more in-depth guide about Solaris 10 NFS usage here: http://www.scribd.com/doc/3469690/Solaris-10-NFS
Comment: So given that there's a Unix group "build"; how can "build" members get write permission to a mounted Windows NFS share? Will "build" have write permission on the Unix client if mapped (via AD lookup) to a group on the server with write permission?


D3 - display x value data ticks as percentages

Question: Have a line graph shown as here: https://i.stack.imgur.com/V54Wu.jpg
Would love the x-axis to display a & sign after each tick, 10%, 20%, etc. How does one accomplish this?
I've read up on a format method one can use, as well as saw people using Math and actually doing a conversion, but figure there must be a quick way to add a string % after each tick, surely!
Using V4 of D3 here
<code>
    <script>
        // set the dimensions and margins of the graph
        const formatPercent = d3.format(".0%")
        const margin = {top: 20, right: 30, bottom: 60, left: 250},
            width = 1000 - margin.left - margin.right,
            height = 300 - margin.top - margin.bottom;

        // append the svg object to the body of the page
        const svg = d3.select(".line")
          .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
          .append("g")
            .attr("transform",
                  "translate(" + margin.left + "," + margin.top + ")");

        // Parse the Data
        d3.json("./data/linedata.json", function(data) {

          // Add X axis
          const x = d3.scaleLinear()
            .domain([0, 100])
            .range([ 0, width]);
          svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x))
            .selectAll("text").attr('class', 'xaxis')
              .attr("transform", "translate(0,0 )")

              .style("text-anchor", "end");

          // Y axis
          const y = d3.scaleBand()
            .range([ 0, height ])
            .domain(data.map(function(d) { return d.desc; }))
            .padding(.1)
          svg.append("g").attr('class', 'xaxis')
            .call(d3.axisLeft(y))

          //Bars
          svg.selectAll("myRect")
            .data(data)
            .enter()
            .append("rect")
            .attr("x", x(0) )
            .attr("y", function(d) { return y(d.desc); })
            .attr("width", function(d) { return x(d.total); })
            .attr("height", y.bandwidth() )
            .attr("fill", "#008080")

        })

        </script>
</code>
Answer: Have you tried using the tickFormat function?
Something like this should work:

.tickFormat(d => d + "%")


Could someone help me understand a little about sound/tone? Beginner/intermediate guidance perhaps

Question: I've been playing guitar for a couple of years now. I always hear someone in the band mention something like, 'that tone needs to have low-mids', terms like 'gain..feedback'(just saying). I would like visualize(not literally) sound wave/tone just enough to understand and be able to make informed decisions while setting the knobs on my amp or working on my tone instead of having to always experiment to get the 'right' sound. The 'why/how' of it.
A general overview and then a guitarist's perspective perhaps.
Comment: I don't think you mean literally visualise, but that may suggest a technological approach:  an outboard analyser can show you your spectral peaks, then the rest of the band as a whole.  If they are saying your tone is getting buried, an analyser might help you pull your tone out of the mud.  If they are simply suggesting as a matter of taste, then experimentation & experience may be your best (slow) approach.
Comment: @commonhare No not visualize visualize. I guess I need to edit that, little misleading. More like 'see'(auditorily I guess) what happens when I change the 'highs' knob on the amp, say. Etc etc,.
Comment: Nevertheless, it can be instructive.  (I'm no professional but) I've been home-recording for years, and sometimes I can't figure out what is happening with a particular tone until I look at its spectrum.  Most recording software has this capability...if you route your output to it, bring up an analyser, and sit there and move knobs, you might find it very interesting...
Answer: Difficult question, but a very worthwhile thing to try to "visualize." I agree with @commonhare 's comments on your question: trial and error using a spectral analyzer would be an effective way to increase your understanding as well as your aural intuition. A similar procedure with your guitar and amp could also be helpful:
Try setting all of your tone knobs to a neutral position, and, for now, use all of your pickups, or at least both the bridge and neck pickups. Strum a few chords, play a few melodic lines. Now turn the low tone way down and the high tone way up. Strum the same chords and play the same melodies, and really intently try to listen to the sound as if it were a landscape spread out before you. Try to "hear" the lack of lower frequencies; try to hear the increased presence of high frequencies. How would you describe the "terrain?" A lot of people would describe the sound as tinny, or at least fairly edgy. If you turn on some distortion in this setting it can have a particularly buzzsaw, grating quality. A lot of the Dead Kennedy's guitar sound involves this sort of high-frequency enhanced distortion.
Now go for the opposite: a lot of low tone, and very little high. Play the same chords and melodies. I wouldn't be surprised if the chords sound like mush in this environment. It's a sound that tends to be very muddy and almost "underwater." This isn't surprising since low frequencies travel through water, but high frequencies don't.  Although the chords are probably unusably muddy in this environment, the melodies might have a cool, muted quality that works in low registers. Distortion in this soundworld is a relatively muted effect, because a lot of the sound of distortion lives in the higher frequencies.
You get the idea. Try cutting out only the mids and listen for a "hollow" character. Switch between the neck and bridge pickups; the former should be much mellower, tending to favor mids and lows, while the latter will be substantially more nasal and tinny, favoring the highs. If you have a wah pedal, play around with very slow movements of the pedal. As you open up the wah filter, listen for high frequencies emerging and as you close it, listen to how they're attenuated and your focus shifts to the muddier lows.
Build some strange "soundscapes" with your guitar, and try to predict what they will sound like—at least broadly—before you play any notes. The more you listen three dimensionally, the better you'll get at recognizing what's missing or overabundant in a variety of playing situations.
Comment: A way of visualising what you're "doing to the sound" would be to use a graphic equaliser, maybe 7-band, where each slider affects a certain frequency range- from bass/low on left to treble/high on right. If you have it set flat (all sliders in the middle) then it's doing nothing; a smiley face shape (up at each end) enhances bass and treble, and sad face diminishes bass and treble. With guitars, a lot of fun can be had around the middle giving different characteristics. This is like 7 bass/middle/treble tone conrols in a row, using sliders instead of rotary knobs but it helps visualise it.
Comment: The alternative would be a parametric Eq (aka "sweepable middle" range) where you have one knob to determine the frequency range you want to affect (low ->high) and another knob to say what you want to do to it - make louder of quieter. This is quite surprisingly useful, and is almost standard setup on mixers, but quite rare on guitar amps which is a shame. If you can get a chance to play with one, even just for half an hour, on any guitar music (for familiarity) you'll learn a lot about the resulting sounds.


How have Red Bull and Ferrari managed to overcome the 2022 car problems but not Mercedes?

Question: It seems like a major issue of 2022 Formula 1 cars is porpoising but what is more interesting is, how have Red Bull and Ferrari managed to overcome this problem, and what have they done differently from Mercedes who are still struggling with this?
Answer: The current theory is that this is a fundamental problem with the "no sidepods" design that Mercedes have pioneered this season - namely, it leaves much more of the floor exposed compared to the more conventional designs of Red Bull and Ferrari. That exposed floor is then flexing due to the aerodynamic loads being placed on it, and this is what triggers the porpoising.
As explained by Autosport, Red Bull and Ferrari have also been able to mitigate the flexing by using "stays" - metal rods hidden in the sidepod that attach to the floor and help support it. Because Mercedes' sidepods are so minimal, they can't use these internal stays, and only one pair of external stays are permitted - not enough to prevent the flexing.
As per BBC Sport:

Mercedes' problems are caused by their car's floor. It is flexing in an uncontrolled way, and this is triggering the aerodynamic instability - "porpoising" or bouncing - that is forcing them to run it in a set-up they don't want to, to keep it under some form of control.
[...]
Questions are being asked about the overall concept of Mercedes' car. It is dramatically different from the rest, with pared-back sidepods and much more exposed upper floor area at the rear than any other car.
Many outside the team suspect this is the root of the problem and that Mercedes will have to abandon it for next year.


Persisting Client IP address in rest apis deployed in AKS

Question: Persisting Client IP address in rest apis deployed in AKS.
Is there any setup to be done at AKS level to persist client IP address?
Currently AKS cluster ip is assigned to client IP address in meta data info of header.
Answer: If you are trying to preserve the client IP for incoming requests, have you tried setting the externalTrafficPolicy to Local on the Service?
Here is a walkthrough of that type of setup.
https://techcommunity.microsoft.com/t5/fasttrack-for-azure/how-client-source-ip-preservation-works-for-loadbalancer/ba-p/3033722
Comment: Yes paul i tried that approach already & it didnt help me.
Comment: The blog explains to set it to Local on application level, but the IP Address is already obscured by ingress controller, so it shows the IP of LoadBalancer service in ingress controller. Also Local can cause imbalance in traffic, thats what I have read. Did you find some other solution to it?


Percentage question. People voting in an election.

Question:
In an election, $10\%$ voters did not participate and $1200$ votes are found invalid. The winner gets $68\%$ of total voting list and he won by $56400$ votes. Find the votes polled in favor of losing candidate.

I can't understand what should I do with the number of invalid votes.

Edit:

Can anybody tell why 1200 has been subtracted from 56400 in
$$46units=56400-1200$$
Shouldn't $$46 units =56400$$
Because 1200 votes are not counted in voting, how can it be a part of the votes by which the candidate won?
Answer: Let total number of voters be $x$. Then, we have:
Total votes = $\frac{9x}{10}$ and total number of valid votes = $\frac{9x}{10}-1200$
Because, the winner got $68\%$ votes of total list, the number of votes he got =  $\frac{34x}{50}$ and thus, number of votes the loser got = $\frac{34x}{50}-56400$
Thus, $$\text{ Total valid votes } = \text{ Votes secured by winner } + \text{ Votes secured by loser } $$ $$\implies \frac{9x}{10}-1200=\frac{34x}{50}+\frac{34x}{50}-56400$$ $$\implies x= \, ?$$
Comment: Hi, can you explain why 1200 has been subtracted from 56400 in the solution that I have posted above...
Comment: @Soumee See they have first assumed 100 votes total and they have done the calculations. Then, difference between the winner and loser was found to be 46 units (their sense). But, it is **actually** 56400 (the difference). So, they subtracted 1200 from it (the invalid votes).
Comment: @Soumee Note that the invalid votes were never ever taken into consideration before that point.
Comment: But isn't 1200 a separate entity? Why has it been taken into account in the 56400 votes?
Comment: @Soumee See my second last equation. On rearranging the terms, $$\frac{9x}{10}=… - 56400+1200$$ = Winner + Loser - (56400-1200) They have simplified it like that!
Answer: Let $x$ be the number of voters on the list.  The total number of votes is equal to the number of votes received by the winner plus the number of votes received by the loser plus the number of voters who did participate in the election plus the number of voters whose votes were invalidated.
The winner receives $0.68x$.
Since the loser receives $56~400$ fewer votes, the loser receives $0.68x - 56~400$.
The number of voters who did participate in the election is $0.1x$.
There were $1200$ invalid votes.
Hence,
\begin{align*}
0.68x + 0.68x - 56~400 + 0.1x + 1200 & = x\\
1.46x - 55~200 & = x\\
0.46x & = 55~200\\
46x & = 5~520~000\\
x & = 120~000
\end{align*}
Therefore, the loser receives
$$0.68(120~000) - 56~400 = 81~600 - 56~400 = 25~200$$
votes.


Jackson upgrade causing deserialization error with Kotlin

Question: Upgraded to jackson 2.12.x and it's been failing my builds in Kotlin 1.3.x which seemingly for a method not being available. I'm unable to figure out if this is breaking change coming from Jackson.
 Caused by: java.lang.NoSuchMethodError: kotlin.reflect.KClass.getSealedSubclasses()Ljava/util/List;
|   at com.fasterxml.jackson.module.kotlin.KotlinAnnotationIntrospector.findSubtypes(KotlinAnnotationIntrospector.kt:72)
|   at com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair.findSubtypes(AnnotationIntrospectorPair.java:263)
|   at com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair.findSubtypes(AnnotationIntrospectorPair.java:263)
|   at com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver._collectAndResolveByTypeId(StdSubtypeResolver.java:288)
... jackson internals omitted ...
|   at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3601)
|   at com.xxxxxxx.util.JacksonSerializationHelper.deserialize(JacksonSerializationHelper.kt:94)

Answer: Looks like some things have been depreciated in the upgrade.
You need to look at the upgrade notes, because this method doesn't exist anymore getSealedSubclasses()
You might find the answer here: https://github.com/FasterXML/jackson/wiki/Jackson-Releases
If you cant find it here, you will need to create a bug report
Comment: `getSealedSubclasses()` is a kotlin API. This is a jackson upgrade. Or do you mean a jackson function is now usinng something else that isn't in Kotlin 1.3?
Comment: Yes i think upgrade both


Why is linux kernel coded using non-standard C (gcc specific features)?

Question: Linux kernel code uses "statement-expression" and typeof extension that makes it only compilable under gcc.
More I think about it, more it doesn't make sense.
It defeats the purpose of portability and standard C.
(now linux kernel code needs a specific compiler that supports gcc extensions).
Was it a bad design choice or was there a specific reason for making linux kernel code specific to gcc?
EDIT: When I said it defeats portability, I used it in different context. I was thinking, by conforming to standard C, it would be accepted to ANY compiler that supports standard C (which is exactly the purpose of creating a standard -- to unify all different dialects of C), hence being more portable. Of course, since gcc is so popular, and gcc supports zillion architectures, this line is almost meaningless. I am just asking if there was a specific rationale behind not conforming to standard C.
Comment: @OliCharlesworth The Linux kernel isn't GNU/Linux, GNU/Linux specifies that the core utilities included in a distribution are the GNU implementations.  It should be possible to use a Linux kernel with another implementation of the core utilities, e.g. BSD, and that would not be GNU/Linux.
Comment: Why is it strange that GNU Linux is written to be compiled with the GNU Compiler?  Who said that Linux was designed to be ported to other compilers?
Comment: Linux is not about code quality or portability. It's about world domination.
Comment: This doesn't sound like it's on-topic for SO.  I don't know enough about the scope of [Programmers](http://programmers.stackexchange.com/) to say whether it should be moved there or not.
Comment: @SHH Once that happens, they're no longer "gcc extensions". They're "stuff needed by some people, implemented by some compilers". Many former gcc extensions are now standard C99 features.
Comment: @cnicutar isn't it because intel c compilers had to put extra efforts to implement gcc extension?
Comment: @Oli Charlesworth [clang](http://clang.llvm.org/) is able to  compile a working Linux kernel, and clang isn't a GNU compiler, but I do agree. :)
Comment: So, linux was written to be compiled with the GNU compiler because it just wanted people to use GNU compilers? I am just wondering if there was any other performance issues rather than political or social issues. I just thought it would make everything much eaiser if it sticked to standard C (if there is no performance issue).
Comment: The Intel C compiler also compiles the Linux kernel.
Comment: @WTP I thought clang was all about unimpeachable standards conformance?
Comment: @Seth Carnegie may be, but it has some (if not all) GCC extensions. You can disable them, though.
Comment: @SHH: care to explain how using a compiler that runs and generates code for a zillion architectures (approximately) "defeats portability"?
Comment: @ninjalj when I said defeats portability, I used it in different context. I was thinking, by conforming to standard C, it would be accepted to ANY compiler that supports standard C (which is exactly the purpose of creating a standard -- to unify all different dialects of C), hence being more portability. Of course, since gcc is so popular and and gcc support zillion architectures, this context is almost meaningless. I am just asking was there a specific rationale behind not conforming to standard C.
Answer: Why would the Linux kernel developers worry about making their code work on say Microsoft Visual Studio compiler or the IBM xlC compilers?
When you're writing a kernel, you need very precise control over a lot more stuff, like exact memory layout, than you do (generally) in userspace. Such controls are not really accounted for in the C standard (left as implementation defined characteristics for instance), so either some extensions are necessary, or you need to rely on the compiler's quirks.
Sticking with one specific compiler, taking advantage of its extensions, is a rational decision. The code doesn't need to be portable across compilers - it needs to be efficient and portable across different hardware platforms.
Comment: Lastly, and this is _very_ important: the Linux kernel doesn't care about portability _at all_ in the way ordinary applications do. They write the environment they run in and provide to userspace. The portability the kernel cares about is _entirely different_ from the portability of "ordinary" applications.
Comment: I don't know what gcc-extension features allow you to precisely control over a lot more stuff like memory layouts or maximizes efficiencies. Isn't that the job of assemly language specific to architecture? I mean if kernel developers wanted maximum efficiencies, why didn't they use assembly languages instead? It looks like any gcc extensions used in kernel could have been replaced by Standard C (correct me if I am wrong).
Comment: Writing assembly is much more time-consuming and difficult than writing C. Even in the kernel, it's limited to the areas where either a) it's simply not possible to express in C, or b) for very specific, performance critical pieces of code that the C compiler doesn't get "perfect". Some of the extension used could probably be replaced by standard C, but what would be the point? If it's easier to write with exts, why bother? Also remember that the C standard evolves. Some extensions get implemented by many compilers over time because they are _useful_. Then, eventually, they can become standard
Comment: Being limited to gcc is probably a feature rather than a bug, if they had supported other compilers, people will try to compile the kernel under those compilers, and that will exponentially multiply the number of different configurations the kernel can be compiled as as well as other use space programs. The support nightmare probably wouldn't be worth it.
Comment: @Mat: the Linux kernel sure cares about portability, that's why it uses a compiler that has been ported and generates code for a zillion architectures.
Comment: @ssh, simplest examples would be the `__attribute__`s which don't have a standard equivalent.
Comment: @SHH: If an extended version of C allows one piece of source code to perform a task on many different architectures that would otherwise require a separate piece of assembly language code for each architecture, why should programmers have to use assembly?  I've observed some people who seem reflexively opposed to the use of C for such purposes, but I see no good justification for such opposition.
Answer: Here's some good background on the specific extensions used. It's not really written from the perspective of "why?", but it should give you some good background on the reasons for choosing this approach:
https://developer.ibm.com/tutorials/l-gcc-hacks/
Answer: Once the kernel is compiled, it doesn't leave "traces" of its compilation environment around to taint the running kernel experience.
I'd say it's just a matter of expedience.  The kernel also contains bits of assembly, and assembly isn't exactly portable either.  Perhaps if the "mission" of the kernel was to write a kernel which could be compiled on multiple C compilers, the complaint would fall on more attentive ears.
Answer: The Linux Kernel code is a complicated piece of software. The more facilities gcc provides them with, they happier the coders would be.
Why would they care about portability? gcc compiles code under virtually every hardware configuration PLUS it provides them with good features. Why would they care if Linux could or could not be compiled with another compiler?
Today, portable code is such a common concept for us that we believe it should be existent everywhere. But that is not the case. For example, if a compiler provides real-time extensions to C, NASA would use it without care for portability. The important point being the features are too good to sacrifice for a portability that is never used (I mean, who would compile the kernel with MS Visual Studio for example?)
Comment: not every hardware supported by gcc is provided with good features from gcc.
Comment: What do you mean? The features I had in mind were of the type `"statement-expression" and typeof` as the OP had asked.
Comment: I mean that gcc don't give good performance to every supported platform.


Como ao clicar numa ImageView não interfierir na aplicação?

Question: Tenho um Linear Layout
               <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/linear"
                android:orientation="horizontal"
                android:onClick="onClickAcao">

               </LinearLayout>

      public void image(ImageView image,int rid,LinearLayout linear )
    {
        image.setBackgroundResource(rid);

        linear.addView(image);
    }

E nesse Linear layout vai uma ImagemView criada via código, com a imagemView criada no Linear Layout como imagem que pega todo o Linear Layout ao clicar nele não executa ação do linear Layout, Tem como fazer a ImagemView não interferir na ação?.
Comment: Poste o código da criação da *ImageView*.
Comment: Se o imageView vai ocupar todo o espaço você poderia setar o click no imageView ou isso atrapalharia?
Comment: @ramaral tá lá o código
Comment: @CaiqueOliveira isso atrapalharia
Comment: Se o código é só esse não vejo razão para que `onClickAcao` do *LinearLayout* não seja chamado.
Comment: @ramaral realmente a função está sendo chamado, o erro esta na comparação de imagem `R.drawable.image`
Comment: Necessariamente tenque adicionar uma ImageView? Não poderia trabalhar com o próprio background do LinearLayout?
Comment: Não entendi. O que quer dizer com: *"o erro esta na comparação de imagem...."*?
Comment: @ramaral já resolvi é o seguinte tinha  armazenado o id das figura em um vetor de inteiros ao comparar não está identificando que era iguais, que eu fiz converti para `String` e fiz a comparação usando `.equals()` e deu certo
Answer: Realmente a ImagemView não atrapalhou para chamar a função onClickAcaodo Linear Layout


Is there any function to find second minimum or maximum number in 2D array?

Question: I have an 2D array,
a= [[ 1  5  9]
 [ 5  8  9]
 [-9  6  2]]

I want to find the second minimum or maximum number in this array. for example pad = -9 which is lowest value in this array, I want to get minimum value = 1.
Ex.
if(np.amin(a)== pad):
      min = 1

I am looking for one line function which returns the second minimum value.
It should also be able to find answer in below case:
k = [-999. -999. -999. -999.   43.   40. -999.   14.   15.]

In this case, when we sort
k = [-999. -999. -999. -999. -999. 14.   15. 40. 43.]
min = 14

Update 1
nodatavalue = -999.0
if(np.amin(k) == nodatavalue):
      np.amin(np.array(a)[a != np.amin(a)])
else:
       np.amin(k)

Answer: Since you're using numpy: a != np.amin(a) will give you an index-array of all elements which aren't equal to the minimum. You can use that to mask out the min-values and then call amin on the masked array to get your answer:
np.amin(np.array(a)[a != np.amin(a)])

Note that if your input is a numpy array (and not a python list) you don't need the extra call to np.array, making it just:
np.amin(a[a != np.amin(a)])

EDIT: If you want to find the minimum while disregarding a specific value, you can just use that value to generate the index array:
np.amin(a[a != nodatavalue])

Note that it helps if you ask what you actually need the first time around in your question. See How to Ask for tips on writing useful and clear questions!
Comment: @AN_SH yw! Note that if your original array is already a Numpy array (and not a vanilla python list) then you can omit the extra call to `np.array`
Comment: one more question- how do compare minimum value with given value. for example consider array k in question. here min = -999.0 but what I want is getting the second minimum value, if nodatavalue = -999.0. the code works great for this condition, but I will look for second minimum value only if amin(k)== nodatavalue.
Comment: This miht help understanding,
    if(np.amin(k) == nodatavalue):
           np.amin(np.array(a)[a != np.amin(a)])
    else:
           np.amin(k)
Please check update 1
Comment: I think i asnwered my own question
Comment: You could just use `np.amin(a[a != nodatavalue])`
Comment: its giving min value as nodatavalue.


Finding closure/interior of subset of function space

Question: Consider the subset $$A=\left\{f\in C(\Bbb R): |f(x)|< \frac{1}{1+|x|} \, \text{for all } x\in \Bbb R\right\}\subset \left\{f\in C(\Bbb R): \lim_{|x|\to \infty}f(x)=0 \right\}=X.$$
where $X$ is equipped with the operator norm. What is the closure and interior of $A$?

My guess is that the closure of $A$ is the set $$B=\left\{f\in C(\Bbb R): |f(x)|\leqslant \frac{1}{1+|x|} \, \text{for all } x\in \Bbb R\right\}$$
  and the interior is the set
  $$C=\left\{f\in C(\Bbb R): \exists\epsilon>0 \text{ such that }|f(x)|< \frac{1}{1+|x|}-\epsilon \, \text{for all } x\in \Bbb R\right\}.$$

I'm fairly certain I got the closure right, but I'm unsure about the inerior.
Certainly $C$ is open and a subset of $A$, therefore, $C\subset \operatorname{int}A$. Does $\operatorname{int A}\subset C$ also hold?
Are my guesses correct?
Comment: $B$ is correct, $C$ is not. Indeed your $C$ is not well-defined: If $|x|$ is large, then $\frac{1}{1+|x|} -\epsilon <0$, so what can $|f(x)|$ be? (Instead, try to show that $A$ is open).
Answer: I suppose you mean that $X$ is equipped with the $\sup$ norm $\Vert \cdot \Vert$ and define
$\mathcal{B}_r(g)=\{f \in X : \Vert f - g \Vert < r\}$ to be the open ball with center $g \in X$ and radius $r>0$.
The interior of $A$ is empty, because for every $g \in A$ there exists for every $r>0$ a function $f$ in $\mathcal{B}_r(g) \setminus A$.
Indeed, without loss of generality, we suppose $r < 1$ and define $x_r$, $\delta_{+}$ respectively $\delta_{-}$ by $\frac{1}{1+ x_r } = \frac{r}{2}$, $\delta_{+} = \frac{r}{2} - g(x_r)$ respectively $\delta_{-} = \frac{r}{2} - g(-x_r) $. It is then easy to check that the function $f$, defined by,
$f(x)=
\begin{cases}
\frac{c_{-}}{1 - x / 2} & \text{if $  x < - x_r$}, \\
g(x) -  \frac{x}{x_r} \delta_{-} & \text{if $ - x_r \leq x \leq 0 $},\\
g(x) +  \frac{x}{x_r} \delta_{+} & \text{if $0 \leq x < x_r$},\\
\frac{c_{+}}{1+ x / 2} & \text{if $  x_r \leq x$},
\end{cases}
$
satisfies the required properties, were $c_{+}$ is defined by $\frac{c_{+}}{1+ x_r /2}=\frac{1}{1+ x_r }$ and $c_{-}$ by $\frac{c_{-}}{1 - x_r /2}=\frac{1}{1- x_r }$to keep $f$ continuous.
Concerning the closure of $\bar{A}$ of $A$, as you say, it is given by the set $B$. Indeed,
$B \subset \bar{A}$ : let $b \in B$. Then, for every neighborhood $V$ of $b$ there exists $\epsilon >0$ such that $\mathcal{B}_{\epsilon}(b) \subset V$. Let $k \in (\max(1- \epsilon,0), 1)$. Then $kb \in \mathcal{B}_{\epsilon}(b) \cap A$, because
$\Vert kb - b \Vert = (1-k) \Vert b \Vert < \epsilon \Vert b \Vert  \leq \epsilon \,\,$ and $\,\, \vert kb(x) \vert = k \vert b(x) \vert < \frac{1}{1+\vert x \vert}$ for all $x \in \mathbb{R}$. This shows that $b \in \bar{A}$.
$\bar{A} \subset B$ : let $a \in X \setminus B$. We need to show that $a \notin \bar{A}$. There exists $y \in \mathbb{R}$ such that $ \vert a(y) \vert > \frac{1}{1+\vert y \vert}$. Let $r=\frac{1}{2}  \left( \vert a(y) \vert - \frac{1}{1+\vert y \vert} \right)$. Then $\mathcal{B}_r(a)$ does not intersect $A$, because for all $g \in \mathcal{B}_r(a)$ it is easily verified that $\vert g(y) \vert > \frac{1}{1+\vert y \vert}$. This shows that $a \notin \bar{A}$.
Answer: According to your definition of $C$, $A\cap C =\emptyset$ ( if $f\in A$, $|f|$ eventually becomes smaller than $\epsilon$.)
Perhaps it makes more sense to consider the set:
$
C=\left\{ f\in A\,\,\, |\,\,\, \exists M>0 \,\,\,s.t.\,\,\, f(x)=0\,\,\, \forall |x| \geq M \right\}.
$


Fiber Channel SAN hooked up to 2 ESXi Hosts

Question: I have a PowerVault with 4 FC modules at 8gb/s. I don't want to jack the SAN into our 10/100/1000 switch because of the max 1gb/s speed.
My question is can I jack both ESXi host's FC into the SAN's FCs and have HV and vMotion?
Comment: Standard Fibre Channel (it's "Fibre" in FC, a proper name) uses a completely different medium from Ethernet. You can not plug the 8gbFC modules into your 1gbE switch. Perhaps you should read up on FC and become acquainted with the technology *before* planning or deploying anything.
Comment: What's "HV"? Did you mean "HA"?
Comment: @Frank, you're Ethernet Switch has Fibre Channel ports? I don't think so. The slowest FC AL or SW Switch is 1Gb, there's no such thing as a 10/100/1000 port in FC. Something's not making sense.
Comment: I don't want to plug it into my switch (which has 4 1000base FC ports). I was asking if I will have HV and vMotion if my 2 ESX host's 8gbFC where plugged into my 8gbFC SAN.
Answer: The SAN itself doesn't need an Ethernet connection in this case, all it needs is FC to the ESXi hosts. The ESXi hosts will need GigE Ethernet. During VMotion, the source ESXi starts sending machine-state to the target ESXi host over the VMKernel connection in the virtual-switch. That's actually a connection between the two ESXi hosts over your physical Ethernet switch. Meanwhile, when state is fully transferred control of the VMDK files is passed over to the target server it it goes live. So, vMotion requires both FC and Ethernet.
HA (what I presume you meant by HV) requires vMotion to work, so should be available if vMotion is working.
Unless you meant Hardware Virtualization, or direct LUN presentation. That can also work, but is trickier. The same volume needs to be presented to both ESXi hosts using exactly the same LUN number, if it doesn't have the same LUN number that volume won't be visible when the VM is on one or the other ESXi host.
Answer: As long as both your ESXi hosts can see the same shared storage, HA, vMotion, Storage vMotion, etc. should all work. It doesn't matter how these systems see the storage - you could have one host attached via FC and one via iSCSI. As long as they have consistent access to the same VMFS volume(s), you should have no problems.


Who is run out if both batsmen are out of their ground?

Question:
Who is out in the attached picture, assuming non of the batters stop running or turn back to their original grounds? At the time of wicket is broken, both were out of their ground but they had not crossed.
Comment: This question is identical to one asked three years ago, and answered successfully. It even uses the exact same picture to demonstrate the situation.
Comment: Thanks @Nij. I was sure I'd seen this one before, but couldn't find the duplicate.
Comment: The identical question was difficult to locate as it was very poorly titled. I've edited the title to make it easier to find in future.
Answer: This is covered by Law 38, Section 3. It states that the person run out shall be the one whose ground is closest to the end where the wicket is put down.
Both batsmen have left their ground, so Law 29 section 2, clause C states that "each ground belongs to whichever batsman is nearer to it" hence batsman B is out.


Bash - While loop doesn't stop

Question: I've written a script where I have a while loop. I've tried two similar looking conditions but for some weird reason one of the condition works but the other doesn't.
Works, the loop stops as expected.
function finder {
    # it prints an integer
}

for ((current = 1; current <= $total_lines; current++)); do
    foo=$(( current - 1 ))
    while [ "$(finder $foo)" = "0" ]; do
        (( foo-- ))
    done
done

Doesn't work, the while loop never stops.
function finder {
    # it prints an integer
}

for ((current = 1; current <= $total_lines; current++)); do
    foo=$(( current - 1 ))
    while [[ $(finder $foo) -eq 0 ]]; do
        (( foo-- ))
    done
done

My actual question is what are the differences between these conditions? I want the 2nd condition to work somehow.
while [ "$(finder $foo)" = "0" ];
# versus
while [[ $(finder $foo) -eq 0 ]];

Comment: `foo=((` is invalid. Don't you get a syntax error? `it returns an integer` does the function __return__ an integer or prints an integer? Your code checks If it prints an integer.
Comment: @KamilCuk Typing mistakes sorry. Forgot to add ```$```.
Comment: @KamilCuk it prints an integer
Comment: Are you asking XY question?
Comment: @KamilCuk yeah, it's an XY question.
Comment: Are you *sure* that `finder` is printing an integer? What exactly is it printing when the loop should stop but doesn't? Putting `set -x` before the problem section may clarify what's going on here.
Comment: @Arghadip : From looking at your code, it's the other way round: the second one looks more reasonable than the first, although I had written it still differently: `while (( $(finder $foo) == 0 ))`. Of course, if `finder` returns garbage, than - depending on the kind of garbage - it may well be that the real problem is in your `finder` function.
Answer:
My actual question is what's the difference between these conditions?
while [ "$(finder $foo)" = "0" ];
# versus
while [[ $(finder $foo) -eq 0 ]];

To summarize:

[ "$(finder $foo)" = "0" ];
[[ $(finder $foo) -eq 0 ]]

portable and POSIX compatible
bash specific

calls a [ or test command
calls a bash (very) special builtin [[

compares the strings as they are
does arithmetic expansion before comparing

does string comparison
does arithmetic comparison

uses quoting " to disable word splitting and filename expansion
special semantics of [[ disable word splitting and filename expansion
Comment: So In sort, can I use ```[[ $(finder $foo) -eq 0 ]]``` for my current purpose? What I'm doing wrong?
Comment: Yes. No idea - present an [MCVE]. Please see [ask].

Bash - While loop doesn't stop


Column not found in laravel polymorphic relationship

Question: developers :)
I'm made a relationship (many-to-many polymorphic) in laravel
between :

 users
 clothes , shoes , ...ect (each one is a model on it's own )

hint: the user can favorite any one he like (clothes or shoes ...etc)
user model :
class User extends Authenticatable
{
public  function  clothes()
    {

        return $this->morphToMany('Etrade\clothes\Clothes' ,'favoritable' )
       ->withTimestamps('created_at','updated_at');

    }
}

clothes model :
class Clothes extends Model
{

 // relationship with user
    public  function  user()
    {
        return $this->morphToMany('Etrade\Users\User' ,'favoritable')
       ->withTimestamps('created_at','updated_at');
    }

}

favoritable model :
class Favriable extends Model
{
    protected $table = 'favoritables';

    public function favoritable()
    {
        return $this->morphTo();
    }
}

fetching the data using relationship :
- get all users for given clothes :
$clo= Etrade\clothes\Clothes::find(35);

$clo->user; // fetch the relation

=> Illuminate\Database\Eloquent\Collection {#760
     all: [
       Etrade\Users\User {#761
         id: 4,
         name: "Reta Paucek",
         email: "email@example.com",
         gender: 0,
         mobile: "",
         city_id: 0,
         active: 0,
         friend_status: 1,
         created_at: "2016-12-26 18:53:51",
         updated_at: "2016-12-26 18:53:51",
         pivot: Illuminate\Database\Eloquent\Relations\MorphPivot {#213
           favoritable_id: 35,
           user_id: 4,
           created_at: "2016-12-30 03:34:58",
           updated_at: "2016-12-30 03:34:58",
         },
       },
     ],
   }

- get all clothes for given user:
 $user = Etrade\Users\User::find(4);

 $user->clothes; // fetch the relationship

Getting error :
Column not found: 1054 Unknown column 'favoritables.clothes_id' in 'field list' (SQL: select
`clothes`.*, `favoritables`.`favoritable_id` as `pivot_favoritable_id`, `favoritables`.`clothes_id` as `pivot_clothes_id`, `favoritables`.`created_at` as `pivo
t_created_at`, `favoritables`.`updated_at` as `pivot_updated_at` from `clothes` inner join `favoritables` on `clothes`.`id` = `favoritables`.`clothes_id` where
 `favoritables`.`favoritable_id` = 4 and `favoritables`.`favoritable_type` = Etrade\Users\User)'

My question : how to fix this error ,,, the relationship work in one direction not for both ??
Comment: Did you find the issue?
Answer: I'm thinking that you copy the code correctly, if yes, then I can see spelling mistake there, sorry but I'm underlevel to use 'comment'.
//Favriable, or Favoritable
class Favriable extends Model
{
    protected $table = 'favoritables';

    public function favoritable()
    {
        return $this->morphTo();
    }
}

Please note that Laravel's Eloquent use 'snake-case' to define a vocabs or something, check this out:
https://laravel.com/docs/5.3/eloquent#defining-models
I can say you must be careful with Laravel's Eloquent when it comes to spelling. She's strict and straight.
Plus, if your table is called "favorites", the model should be "Favorite".
If the table in the database is called "stars", the model should be "Star", just to name few examples.
Hope this enlighten something.


Assistance with combo box using lookup table - MS Access

Question: Basically what I have is a Customer Table which contains information about our customers.  One of the fields in this table is Customer.CustomerTypeID.
I have a CustomerType Table as well that is basically a lookup table.
I want the CustomerType.CustomerTypeName field to populate my combo box, then when I go to save my record I want the CustomerType.CustomerTypeID for the CustomerType.CustomerTypeName I chose to be updated in the Customer.CustomerTypeID field.
Am I overcomplicating this?  Should I just change it so I'm storing the CustomerName in the Customer table instead of the ID?
Thanks in advance.
Answer: No, store the ID.
Set your combo like so:
Row Source: SELECT CustomerTypeID, CustomerTypeName FROM CustomerType
Control Source : CustomerTypeID
Bound Column : 1
Column Count : 2
Column widthes : 0, 2

The control source + bound column means that the data will be stored to a field called CustomerTypeID in the table the form is based on, the column widths means that the ID column is hidden and the description is displayed.


Correlation between combinations of uncorrelated variables

Question: If I have uncorrelated variables X,Y,Z how do I find the correlation between (X+Y) & (Y+Z)?
Ps. It's a theory question: ie, I can't compute the correlation from observed instances of X,Y & Z. What I can do is assume these variables have a standard deviation of a,b & c, and figure out the correlation of M & N (where M=X+Y & N=Y+Z) from there.
Comment: Hint: Covariance is a _bilinear_ function meaning that \begin{align}\operatorname{cov}(aW+bX,cY+dZ) &= (ac)\cdot\operatorname{cov}(W,Y)+(bd)\cdot\operatorname{cov}(X,Z)\\& ~~+(ad)\cdot\operatorname{cov}(W,Z)+(bc)\cdot\operatorname{cov}(X,Y)\end{align} unless, of course, those $\&$'s mean something else.
Comment: Coul you specify in your question what you mean by "and so on"? + maybe you could first simply compute the covariance between $X+Y$ and $Y+Z$ and see where it goes...
Comment: Edited the question. Essentially, I need to know how to compute covariance between (X+Y) & (Y+Z) given sd of X,Y & Z.
Comment: Ok, I did not mean "compute" with a calculator, I meant: write down the definition of the correlation, or maybe first of the covariance, expand and simplify the terms that go away thanks to your hypotheses, and see what is left.
Comment: @DilipSarwate. Thanks! I had forgotten that property, and it is definitely what I needed.
Comment: @VincentGuillemot Thanks Vincent. While I'd tried the expansion (16 terms), it has left me with terms I was unable to resolve.
Answer: Use bilinearity and calculate
$$ \DeclareMathOperator{\cov}{\mathbb{C}ov}
   \DeclareMathOperator{\var}{\mathbb{V}ar}
   \DeclareMathOperator{\cor}{corr}
\cov(X+Y,Y+Z) =\cov(X,Y)+\cov(X,Z)+\cov(Y,Y)+\cov(Y,Z) =0+0+\var(Y)+0
$$
so
$$
 \cor(X+Y,Y+Z)=\frac{\cov(X+Y,Y+Z)}{\sqrt{\var(X+Y) \var(Y+Z)}} = \\
\frac{\var(Y)}{\sqrt{(\var(X)+\var(Y))(\var(Y)+\var(Z))}}
$$
and you can take it from there.


How to load different textboxes based on url and database data?

Question: I'm trying to control the loading of different textboxes according to the url of the page and prior settings in the database.
For example: I have a database table that looks like this:

And I'd like my page to look like that when browsing www.mysite.com/us/mypage

like that when browsing www.mysite.com/canada/mypage

like that when browsing www.mysite.com/italy/mypage

So I'm trying to understand how to design my code. Should it be addressed only on the client side, with javascript on the page load or should it be handled with the controller on the server side.
Thanks!
Comment: Can you share with us what you have tried?
Answer: First off, since you already have the rules. Set it up first. Second, you need to parse the url (get the country and treat it like a slug) and feed it into the rules. Third, then just use a normal foreach loop and a condition inside (1/0 or true/false) if it needs to be printed or not. Consider this example:
<?php

// $current_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url1 = 'www.mysite.com/us/mypage';
$url2 = 'www.mysite.com/canada/mypage';
$url3 = 'www.mysite.com/italy/mypage';
// dummy values

// setup the rules
$rules = array(
    'us' => array(
        'textbox1' => 1,
        'textbox2' => 1,
        'textbox3' => 1,
        'textbox4' => 1,
    ),
    'canada' => array(
        'textbox1' => 1,
        'textbox2' => 1,
        'textbox3' => 0,
        'textbox4' => 0,
    ),
    'italy' => array(
        'textbox1' => 1,
        'textbox2' => 0,
        'textbox3' => 1,
        'textbox4' => 0,
    ),
);

// properly parse the url
$current_url = $url2; // i just chosen canada for this example
if (!preg_match("~^(?:f|ht)tps?://~i", $current_url)) {
    $current_url = "http://" . $current_url;
}
$current_url = array_filter(explode('/', parse_url($current_url, PHP_URL_PATH)));
$country = reset($current_url);

?>

<form method="POST" action="">
<?php foreach($rules[$country] as $key => $value): ?>
    <?php if($value == 1): ?>
        <?php echo $key; ?>
        <input type="text" name="<?php echo $key; ?>" />

    <?php endif; ?>
<?php endforeach; ?>
    <input type="submit" name="submit" />
</form>

Answer: You have to set condition and check the value
if($isset($textbox) && $textbox==1)
{
//print the label and text box
}

Answer: Best thing is try to achive the output at server side.
I think the following code will be useful for you.
Try to get the country code from url and get the database values into $textboxA array, and run the following code.
$textboxA = array(1,1,0,1);
foreach($textboxA as $key => $value){
    switch($key){
        case 0: if($value) print $textbox1;
        break;
        case 1: if($value) print $textbox2;
        break;
        case 2: if($value) print $textbox3;
        break;
        case 3: if($value) print $textbox4;
        break;
        default: print "";
    }
}


Showing that $x^4 + x^3 + 31x^2 + 130x + 107$ is irreducible

Question: I need to prove that
$$x^4 + x^3 + 31x^2 + 130x + 107$$
is irreducible in $\mathbb Z[x]$ using the Eisenstein criterion for $p=7$ and that $f(x)$ is irreducible if $f(x+c)$ is irreducible. I have tried some values for $c=1,2,3,4$, but that doesnt seem to work since $c^4+c^3+31c^2+130c+107$ is not divisible by $7$. My approach was just to try out some values for $c$. Is there a better way to look for values for $c$ that work?
Comment: How can you use Eisenstein for $p=7$? None of the coefficient is divisible by $7$.
Comment: We are to use Eisenstein on f(x+c) not f(x)
Answer: If positive doesn't work try negative. $c=-2\implies f(-2)=-21.$ And
$$
f(x-2)=x^4-7x^3+49x^2-14x-21
$$
Comment: Thanks. I think I actually tried c=-2. Probably messed up my calculation


How to migrate Clickhouse's Zookeeper to new instances?

Question: I'm hosting ClickHouse (v22.214.171.124) in 2 replicas on Kubernetes and it makes use of Zookeeper (v3.5.5) in 3 replicas (also hosted on the same Kubernetes cluster).
I would need to migrate the Zookeeper used by ClickHouse with another installation, still 3 replicas but v3.6.2.
What I tried to do was the following:

I stopped all instances of ClickHouse in order to freeze Zookeeper nodes.
Using zk-shell, I mirrored all znodes from /clickhouse of the old ZK cluster to the new one (it took some time but it was completed without problems)
I restarted all instances of ClickHouse, one at a time, now attached to the new instance of Zookeeper.
Both the ClickHouse instances started correctly, without any errors, but all the times I try (or someone tries) to add rows to a table with an insert, ClickHouse logs something like the following:

<code>2021.01.13 13:03:36.454415 [ 135 ] {885576c1-832e-4ac6-82d8-45fbf33b7790} <Warning> default.check_in_availability: Tried to add obsolete part 202101_0_0_0 covered by 202101_0_1159_290 (state Committed)
</code>
and the new data is never inserted.
I've read all the info about Data Replication and Deduplication, but I am sure I'm adding new data in the insert, plus all tables make use of temporal fields (event_time or update_timestamp and so on) but it simply doesn't work.
Attaching ClickHouse back to the old Zookeeper, the problem is not happening with the same data inserted.
Is there something which needs to be done prior to change Zookeeper endpoints? Am I missing something obvious?
Answer:
Using zk-shell, I

You cannot use this method because it does not copy autoincrement values which are used for part block numbers.
There are much simpler way. You can migrate ZK cluster by adding new ZK nodes as followers.

Here is a plan for ZK 3.4.9 (no dynamic reconfiguration):
1. Configure the 3 new ZK nodes as a cluster of 6 nodes (3 old + 3 new), start them. No changes needed for the 3 old ZK nodes at this time.
    The new server would not connect and download a snapshot, so I had to start one of them in the cluster of 4 nodes first.
2. Make sure the 3 new ZK nodes connected to the old ZK cluster as followers (run echo stat | nc localhost 2181 on the 3 new ZK nodes)
3. Confirm that the leader has 5 synced followers (run echo mntr | nc localhost 2181 on the leader, look for zk_synced_followers)
7. Remove the 3 old ZK nodes from zoo.cfg on the 3 new ZK nodes.
8. Stop data loading in CH (this is to minimize errors when CH loses ZK).
4. Change the zookeeper section in the configs on the CH nodes (remove the 3 old ZK servers, add the 3 new ZK servers)
5. Restart all CH nodes (CH must restart to connect to different ZK servers)
6. Make sure there are no connections from CH to the 3 old ZK nodes (run echo stat | nc localhost 2181 on the 3 old nodes, check their Client ssection).
11. Turn off the 3 old ZK nodes
9. Restart the 3 new ZK nodes. They should form a cluster of 3 nodes.
10. When CH reconnects to ZK, start data loading.

Altinity KB
Comment: Thanks for the answer! I can't exactly increase the number of ZK nodes and then split them from the cluster that way because I'm excuting ZK on Kubernetes. I was thinking of increasing the number of nodes.. but then, instead of splitting them, doing a backup and restore on the real new nodes (changing the myid)
Comment: >because I'm excuting ZK on Kubernetes.
You probably wrong. Ask this question with k8s tags
Comment: You can simply copy snapshots and logs from the old ZK server to the new you are able to stop CH for 5 minutes.
Comment: Yeah I just did that, was unsure on how to copy them since I was also upgrading version of ZK but I made it work
Comment: And yeah I was wrong, I could have used dynamic reconfiguration to link the two clusters together, most probably, but I found out only after I was done with the other method.


Add datepicker to view exposed filter

Question: I have a view and an exposed filter with a date field, I want to make this filter as a date picker, not a text field, I've used Better Exposed Filters but didn't find anything in view, I had used it much time in D7 but In D8 cannot find it in the view exposed form style. So what should I do to use this module
Answer: You can add the jquery date picker in for that page as dependency.
your_theme.libraries.yml
date-picker:
  js:
    script/site-datepicker.js : {}
  dependencies:
    - core/jquery
    - core/jquery.ui.datepicker

site-datepicker.js
Drupal.behaviors.customDatepicker = {
  attach: function (context, settings) {
    jQuery(function () {
      jQuery("#datepicker").datepicker({
        dateFormat: "dd-mm-yy",
        altField: "input[data-drupal-selector=edit-created]",
        altFormat: "yy/mm/dd 23:59:59"
      });
    });
  }
};

views-exposed-form--views-block-name.html.twig
{% if q is not empty %}
  {#
    This ensures that, if clean URLs are off, the 'q' is added first,
    as a hidden form element, so that it shows up first in the POST URL.
  #}
  {{ q }}
{% endif %}

<input id="datepicker" type="text">
<input data-drupal-selector="edit-created" data-msg-maxlength="This field field has a maximum length of 128." name="created" size="30" maxlength="128" aria-invalid="false" type="hidden">
{{ form|without('created') }}

There is also the Date Popup module, for Drupal 8. You can use that module and implement this functionality.
Comment: How to add month and date selector to the calendar? @Himanshu

Add datepicker to view exposed filter


left outer join 2 shell output on a common key column using bash

Question: Is there a way I can do a "left outer join" for bash output from 2 different commands based on a common key column (ip address)? For various reasons, I would like to avoid saving the output from either commands into a file and using the filename as inputs into awk/join.
These are the 2 outputs I would like to merge together:
output1=$(oc get pod -lname=elasticsearch -o wide)
output2=$(curl -ks https://elasticsearch.apps.ocp.domain.com/_cat/allocation?v)

Here's the disk utilization of my elasticsearch pods
$ echo "$output1"
shards disk.indices disk.used disk.avail disk.total disk.percent host          ip            node
   347        1.5tb     1.5tb      4.2tb      5.8tb           27 10.1.1.1      10.1.1.1      jxAuPMt
   335        1.7tb     1.7tb        4tb      5.8tb           30 10.2.2.2      10.2.2.2      bwYW1cg
   341        1.3tb     1.9tb    959.7gb      2.9tb           67 10.3.3.3      10.3.3.3      69O4sR-
   343        1.6tb     1.7tb      1.1tb      2.9tb           59 10.4.4.4      10.4.4.4      zCVUS05
   346        1.4tb     1.9tb   1000.6gb      2.9tb           66 10.5.5.5      10.5.5.5      AlvtEtf
   345        1.6tb     1.6tb      1.2tb      2.9tb           57 10.6.6.6      10.6.6.6      pmObkSm
   248          1tb       1tb    374.9gb      1.4tb           74 10.7.7.7      10.7.7.7      OSzB5J1
   332        1.4tb     1.9tb    952.1gb      2.9tb           68 10.8.8.8      10.8.8.8      EShhlrb
   218     1011.8gb       1tb    418.2gb      1.4tb           71 10.9.9.9      10.9.9.9      1rQ7PXD
   329        1.7tb     1.8tb        1tb      2.9tb           63 10.10.10.10   10.10.10.10   73TfUnn
    15                                                                                UNASSIGNED

Here are the running elasticsearch pods in my environment
$ echo "$output2"
NAME                              READY     STATUS    RESTARTS   AGE       IP              NODE
elasticsearch-4-40700             1/1       Running   0          4d        10.1.1.1        server1b.ocp.domain.com
elasticsearch-4-6m2p1             1/1       Running   0          4d        10.2.2.2        server2b.ocp.domain.com
elasticsearch-4-8n8v5             1/1       Running   0          7d        10.3.3.3        server3b.ocp.domain.com
elasticsearch-4-ffnk0             1/1       Running   0          4d        10.4.4.4        server4b.ocp.domain.com
elasticsearch-4-h5xr6             1/1       Running   0          7d        10.5.5.5        server5b.ocp.domain.com
elasticsearch-4-h6c15             1/1       Running   0          7d        10.6.6.6        server6b.ocp.domain.com
elasticsearch-4-j7cv5             1/1       Running   0          7d        10.7.7.7        server7b.ocp.domain.com
elasticsearch-4-nn3pc             1/1       Running   0          5d        10.8.8.8        server8b.ocp.domain.com
elasticsearch-4-sq5hr             1/1       Running   0          7d        10.9.9.9        server9b.ocp.domain.com
elasticsearch-4-zj7tq             1/1       Running   0          7d        10.10.10.10     server10b.ocp.domain.com
elasticsearch-4-az9sp             1/1       Running   0          7d        10.10.10.11     server11b.ocp.domain.com
elasticsearch-4-bi2c7             1/1       Running   0          7d        10.10.10.12     server12b.ocp.domain.com

Expected results after doing a "left outer join" from output1 and output2 based on the IP address
NAME                              READY     STATUS    RESTARTS   AGE       IP              NODE                      shards disk.indices disk.used disk.avail disk.total disk.percent node
elasticsearch-4-40700             1/1       Running   0          4d        10.1.1.1        server1b.ocp.domain.com      347        1.5tb     1.5tb      4.2tb      5.8tb           27 jxAuPMt
elasticsearch-4-6m2p1             1/1       Running   0          4d        10.2.2.2        server2b.ocp.domain.com      335        1.7tb     1.7tb        4tb      5.8tb           30 bwYW1cg
elasticsearch-4-8n8v5             1/1       Running   0          7d        10.3.3.3        server3b.ocp.domain.com      341        1.3tb     1.9tb    959.7gb      2.9tb           67 69O4sR-
elasticsearch-4-ffnk0             1/1       Running   0          4d        10.4.4.4        server4b.ocp.domain.com      343        1.6tb     1.7tb      1.1tb      2.9tb           59 zCVUS05
elasticsearch-4-h5xr6             1/1       Running   0          7d        10.5.5.5        server5b.ocp.domain.com      346        1.4tb     1.9tb   1000.6gb      2.9tb           66 AlvtEtf
elasticsearch-4-h6c15             1/1       Running   0          7d        10.6.6.6        server6b.ocp.domain.com      345        1.6tb     1.6tb      1.2tb      2.9tb           57 pmObkSm
elasticsearch-4-j7cv5             1/1       Running   0          7d        10.7.7.7        server7b.ocp.domain.com      248          1tb       1tb    374.9gb      1.4tb           74 OSzB5J1
elasticsearch-4-nn3pc             1/1       Running   0          5d        10.8.8.8        server8b.ocp.domain.com      332        1.4tb     1.9tb    952.1gb      2.9tb           68 EShhlrb
elasticsearch-4-sq5hr             1/1       Running   0          7d        10.9.9.9        server9b.ocp.domain.com      218     1011.8gb       1tb    418.2gb      1.4tb           71 1rQ7PXD
elasticsearch-4-zj7tq             1/1       Running   0          7d        10.10.10.10     server10b.ocp.domain.com     329        1.7tb     1.8tb        1tb      2.9tb           63 73TfUnn
elasticsearch-4-az9sp             1/1       Running   0          7d        10.10.10.11     server11b.ocp.domain.com
elasticsearch-4-bi2c7             1/1       Running   0          7d        10.10.10.12     server12b.ocp.domain.com

Answer: The below produces your desired output, but without headers:
awk 'NR==FNR{a[$8]=$0}FILENAME==ARGV[1]{b[$6]=$2} FILENAME==ARGV[2]{print $0,a[$6]}' <(oc get pod -lname=elasticsearch -o wide) <(curl -ks https://elasticsearch.apps.ocp.domain.com/_cat/allocation?v) | awk 'NR>1' | awk '!($14=$15="")'

The part, wich is a little bit unclean is how this removes the duplicate ip address columns with 'awk '!($14=$15="")''
You might be better off with a little multiline script instead of a one liner to make this process cleaner.


MCMC Metropolis-Hastings' jumping distribution for non-negative parameters

Question: The Metropolis-Hastings algorithm is Markov Chain Monte Carlo technique for sampling from some distribution $f(x)$ by constructing a Markov Chain whose equilibrium distribution is equal to $f(x)$. Essentially given the current state of the Markov Chain a new state is proposed and it is either accepted or rejected. This new state $X_\text{new}$ is given by:
$$X_\text{new} = X_\text{old} + \lambda$$
Let us call the distribution of $\lambda$ the `jumping distribution'. Typically $\lambda$ is taken to be a mean-zero normal random variable :
$$\lambda \sim \mathcal{N}(0,\sigma^2)$$
Usually the variance $\sigma^2$ is fine-tuned to alter the acceptance rate $\alpha$ of of new moves. My question regards sampling from a non-negative distribution $f(x)$. For instance this may arise from sampling from the Bayesian posterior distribution of the variance parameter of some model. My intial approach was to keep $\lambda$ normal however if the proposed new value is negative I set it to zero instead. However this does not seem like a particularly intelligent or efficient approach. Can you propose a better jumping distribution for non-negative $f(x)$?
Comment: You could try using a truncated normal?
Answer: Let $q(x^*|x_{old})$ be your proposal (jumping) distribution and let $x^*$ be a proposed value from this distribution. Then the Metropolis-Hastings acceptance probability is
$$
\rho = \min \left\{ a, \frac{f(x^*)}{f(x_{old})} \frac{q(x_{old}|x^*)}{q(x^*|x_{old})} \right\}
$$
and set $x_{new} = x^*$ with probability $\rho$ and otherwise $x_{new} = x_{old}$.
The Metropolis-Hastings algorithm is appealing because you have a wide range of flexibility in specifying $q$. For example, you can use $N(x_{old},\sigma^2)$ in which case you have to remember that the target $f$ for a non-negative parameter includes an indicator function that indicates the parameter must be positive. Thus any negative values for $x^*$ are rejected because $f(x^*)$ will be zero and you set $x_{new} = x_{old}$. This proposal is convenient because it is symmetric, i.e. $q(x_{old}|x^*)= q(x^*|x_{old})$ for all $x^*, x_{old}$. Thus, you never need to calculate the last ratio in the acceptance probability.
Alternatively (as suggested in the comments), you can use a truncated normal, e.g. $N(x_{old},\sigma^2)\mathrm{I}(x^*>0).$ But note that the normalizing constant for this truncated normal depends on $x_{old}$ and thus this proposal is not a symmetric proposal and thus you will need to calculate the last ratio in the acceptance probability.
The choice of setting any proposed value to zero doesn't gain you anything since (I'm guessing) either your data will indicate that the parameter cannot actually be zero and thus $f(x^*)$ will be zero when $x^*=0$. Even if this isn't the case, evaluation of the proposal distribution will be a bit annoying since it is now a mixture of a continuous distribution and a point mass at zero.
There are many other choices for the proposal distribution including independent proposals, i.e. those that do not depend on $x_{old}$. You have not provided enough information for us to give a "better" proposal distribution because this will depend on the target distribution. If this target distribution doesn't have too much mass near zero, then the normal random-walk proposal, i.e. $N(x_{old},\sigma^2)$, will likely work well even though it occasionally will reject a negative proposed value.
Comment: How do you calculate the "the last ratio in the acceptance probability" in the case of the truncated normal?
Comment: @Giorgetto Feel free to post a new question.


How can I track repeated visitors using cookies

Question: I want to track repeated user for our web site to show others by using cookies. It can be either java or javascript.
Answer: If you want a very simple system, you can write a cookie with a GUID-type value when the user first visits.  Then you'll get this cookie back on every request.  When you handle the request, log the info you want to track, along with the GUID from the cookie, in your data base.
Slice and dice as needed.
You'll find it's easy to say but hard to do and get any meaningful data.


MPI for the D programming language

Question: This question is related to this question: MPI and D: Linker Options
I am trying to get MPI working from D. There are several posts to be found in the net, but none I found did actually work... So here is what I did so far:
I took the mpi.d from here https://github.com/1100110/OpenMPI/blob/master/mpi.d and set up a minimal program:
import mpi;
import std.stdio;

void* MPI_COMM_WORLD = cast(void*)0;

int main(string[] args)
{

  int rank, size;
  int argc = cast(int)args.length;
  char *** argv = cast(char***)&args;

  MPI_Init (&argc, argv);   /* starts MPI */
  MPI_Comm_rank (MPI_COMM_WORLD, &rank);    /* get current process id */
  MPI_Comm_size (MPI_COMM_WORLD, &size);    /* get number of processes */
  writefln( "Hello world from process %d of %d", rank, size );
  MPI_Finalize();

  return 0;
}

I compile with
dmd test_mpi.d -L-L/usr/lib/openmpi -L-lmpi -L-ldl -L-lhwloc

or
gdc test_mpi.d -pthread -L/usr/lib/openmpi -lmpi -ldl -lhwloc -o test_mpi

and run with
mpirun -n 2 ./test_mpi

This is the error I get:
[box:1871] *** An error occurred in MPI_Comm_rank
[box:1871] *** on communicator MPI_COMM_WORLD
[box:1871] *** MPI_ERR_COMM: invalid communicator
[box:1871] *** MPI_ERRORS_ARE_FATAL: your MPI job will now abort
--------------------------------------------------------------------------
mpirun has exited due to process rank 0 with PID 1870 on
node bermuda-iii exiting improperly. There are two reasons this could occur:

1. this process did not call "init" before exiting, but others in
the job did. This can cause a job to hang indefinitely while it waits
for all processes to call "init". By rule, if one process calls "init",
then ALL processes must call "init" prior to termination.

2. this process called "init", but exited without calling "finalize".
By rule, all processes that call "init" MUST call "finalize" prior to
exiting or it will be considered an "abnormal termination"

This may have caused other processes in the application to be
terminated by signals sent by mpirun (as reported here).
--------------------------------------------------------------------------
[box:01869] 1 more process has sent help message help-mpi-errors.txt / mpi_errors_are_fatal
[box:01869] Set MCA parameter "orte_base_help_aggregate" to 0 to see all help / error messages

Obviously I do call MPI_Init and MPI_Finalize. So what am I missing?
Comment: Sooo...  Is it still working from when I left it there?  I do accept pull requests!
Comment: I am still testing... so far this simple example wroks, but more complex stuff doesn't so I am trying to figure out why...
Comment: If it's easy for you, pull anyways and let me take a look.  Maybe I'll be able to spot it.   (if it's not don't worry about it.  I'll update that at some point.)
Comment: ping, maybe?  Got an update for me?
Comment: @0b1100110: I didn't work on this for a while as you might have noticed ;) Anyways, I would like to pull and see if some afternoon I play with it. I'll send you an Email
Answer: In Open MPI C communicator handles are pointers to the real communicator structures. MPI_COMM_WORLD is a pointer to the precreated world communicator structure and not a NULL pointer as you define it. That's why Open MPI aborts in the call to MPI_COMM_RANK - it is equivalent to calling MPI_Comm_rank(NULL, &rank) in C.
If you take a look at line 808 of mpi.d, you would notice that MPI_COMM_WORLD is already defined as:
MPI_COMM_WORLD      = cast(void*) &(ompi_mpi_comm_world),

So your code should work if you remove the line where you redefine MPI_COMM_WORLD.
Comment: Doh! I put that to compile with another version of mpi.d and forgot to delete it! Thanks.
Answer: You are not casting string[] to char*** right. You should do this instead:
import std.string, std.algorithm, std.array;

char** argv = cast(char**)map!(toStringz)(args).array.ptr;
MPI_Init (&argc, &argv);

Here's how it works:

Maps toStringz on each args element.
Because map returns range, we use array to have array of it.
Getting array pointer.
Comment: there is a parenthesis missing. Before map?
Comment: ok, thanks for pointing that out. But unfortunately it doesn't fix the issue... :(

MPI for the D programming language


How to Display NSSet value in UItableView Using NSmutableArray

Question: I'm having an array of elements like this
150,
150,
150,
571,
571,
571,
692,
692,
692,
123,
123,
123,
144,
144,
144,
147,
147,
147,
155,
155,
155,
542,
542,
542,
548,
548,
548,
551,
551,
551
I used to display my array elements in tableviewcell where i used code like this
<code>NSArray *array=[jsonarray valueForKey:@"ID"];
mySet = [NSSet setWithArray:array] ;

NSLog(@"%@",mySet);
</code>
now i got my all elements which is not repeated as 11 elements in myset but if i printed myset value i got like this
2012-08-01 12:49:53.049 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.050 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.050 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.051 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.051 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.052 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.052 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.053 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.053 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.054 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
2012-08-01 12:49:53.054 jothi R&D[3647:f803] {(
    551,
    548,
    692,
    150,
    155,
    147,
    542,
    571,
    123,
    144
)}
and if i tried to print that in UItableviewcell i got BAD ACCESS issue at return[myset count];.My table view cell contains
<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return  [myset count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

{        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

}
// Configure the cell...

cell.textLabel.text=[myset objectAtIndex:indexPath.row];

return cell;
}
</code>
Here jsonarray is NSMutableArray,myset is NSSet..Guidance please..
Answer: the reason is that the NSSet does not accept duplicates, so you 'have more elements in your NSMutablearray
so you must chose to use one of them in all you dataSource methodes


Prove convexity of set

Question: I've had a hard time proving this statement. The objective is to prove that the set $M$ is convex where $f(y)$ can be any function. The task is to prove it using triangle inequality. I've looked at threads like Proving Convexity of an Open Disk but i still can't wrap my head around it. If anyone could give me a hint in the right direction i would be very grateful.
$$M = \{\, x\,\big| \, ||x-y|| \leq f(y) \, \text{ for all } y \in S\,\} \quad \text{where } S \subseteq \mathbb{R}^n$$
Best Regards
Answer: Hint: If $x_1, x_2 \in M$ and $0 < \lambda < 1$ then for all $y \in S$
$$
 |\lambda x_1 + (1-\lambda) x_2 - y| = |\lambda(x_1-y) + (1-\lambda)(x_2 - y)|
 \, .
$$
Now use the triangle inequality to conclude that this is
$$
 \le \lambda| x_1-y| + (1-\lambda)|x_2 - y| \le \lambda f(y) + (1-\lambda) f(y) = f(y) \, ,
$$
which means that $\lambda x_1 + (1-\lambda) x_2 \in M$.
Comment: Seems to me that one can conclude that  $|x_1-y|$ and $|x_2-y|$are both $\leq f(y)$ as that's stated in the original formula. Then one should be able to rewrite it all:

$|\lambda( x_1 - y) + (1- \lambda) (x_2 - y)| \leq \lambda |x_1-y| + (\lambda - 1) |x_2-y| \leq f(y)$
Comment: @PontusS: Correct.
Comment: A short final question to make sure i understand this correctly. For a convex set a line between two points in the set must be contained within the set. Two arbitrary points $x_1$ and $x_2$ are contained in the set.

The equation

$\lambda | x_1 - y| + (1- \lambda) |x_2 -y| \leq f(y)$ Proves that all the points on the line connecting the points $x_1$ and $x_2$ are also contained within the set.

Sorry for any inconvenience just want to make sure i get this stuff :) You have been very helpful thanks!
Comment: @PontusS: $|(\lambda x_1 + (1-\lambda) x_2) - y| \le \ldots \le f(y)$ for all $y \in S$ shows that $\lambda x_1 + (1-\lambda) x_2$ is in the set.
Answer: Another hint:  $M$ is the intersection of a certain collection of closed balls.

Prove convexity of set