text:
Q: Optimal message length and cross entropy When it comes to cross entropy, the assumption is that an optimal encoding would use $\log(\frac{1}{p_i})$ bits for a symbol with probability $p_i$.  While I understand this from a theoretical standpoint, and this definition is of course useful for optimization & learning, I am hoping to:

*

*See a formal derivation of this intuitive result. That is, we should be able to conclude that $\sum_ip_i\log(1/p_i)$ (i.e. the expected message length) is optimal across all possible encodings for any messages drawn from the underlying distribution.

*See a practical example of this type of encoding (perhaps Huffman coding?)

For #2, for example, consider the following symbols and probabilities:

*

*p(A) = 0.8. requires 0.32 bits

*p(B) = 0.1. requires 2.32 bits

*p(C) = 0.1, requires 2.32 bits

What would the optimal encoding of a message here actually look like in practice?
Related threads for reference:

*

*Qualitively what is Cross Entropy

*What is the role of the logarithm in Shannon's entropy?

A:
See a formal derivation of this intuitive result

This is shown very nicely in the first few chapters of Thomas & Cover's Elements of Information Theory.
The proof is too long for an answer, but it generally goes as follows. First, by definition, a code must be uniquely decodable, meaning that there is only one way to decode it. Then, they show that prefix-free codes, a strict subset of uniquely-decodable codes, are just as efficient. Prefix-tree codes can be represented by trees, and the Kraft Inequality can be used to complete the average $\log\left(\frac{1}{p_i}\right)$ bits proof.
If you are willing to settle for a less rigorous proof, it can be shown through the Asymptotic Equipartition Property. Assume symbol $i$ is generated with probability $p_i$. Then taking the negative log of the probabilities, and noting that the log of a product is the product of a log, the law of large numbers says that there is a set of size $e^{n H}$ containing nearly all the probabilities of sets generated by this process.
Thus a code of average per-bit length $H$ is about as efficient as you can get. This is what you'd get if you'd assign length $-\log\left( \frac{1}{p_i} \right)$ to symbol $i$. You cannot assign a better length based on $-\log\left( \frac{1}{p_i} \right)$. The $q_i$ would have to be a distribution as well (if not, either the code could be made more efficient, or it would violate Kraft). Using Gibb's Inequality, since
$$
\ln x \leq x-1
$$
(formally, by derivation and checking $x = 1$), then
$$
- \sum_i \left[ p_i \ln\left(\frac{q_i}{p_i}\right) \right] \leq
- \sum_i \left[ p_i \left(\frac{q_i}{p_i} - 1\right) \right] =
- \sum_i \left[ q_i - p_i \right].
$$
The right hand side, however, is 0, as $p$ and $q$ are probability distributions.

See a practical example

Given a set of probabilities, you can construct a concrete code using Arithmetic Coding.

Looking back at the answer, it seems to me a bit long and rambling. Again, I suggest you go over the first chapters of Cover & Thomas.


text:
Q: Non conjugate points on a Riemannian manifold with two connecting minimizing geodesics We know that for a point $q$ in the cut locus of a point $p$ in a complete Riemannian manifold there are two possibilities: the point $q$ is conjugate to $p$ or they are connected by (at least) two minimizing geodesics.
I have been told that there is an example of two conjugate points with a unique minimizing geodesic, and, conversely, of two non conjugate points connected by two minimizing geodesics.
Can someone provide me some hints about the latter? I suspect that something on the torus can help me, but I can't say anything precise.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use PHP to send email on mobile device I need some direction on the following:
I developed a contact form using AngularJS and PHP. I am hosting the website on GoDaddy. When I access the website on a computer and send a message from the contact form to the specified email address, it works fine; I receive the email. However, if I access the website from a mobile device and use the contact form to send an email, the email is never received. Below is my code.
<?php
$contactFormData = file_get_contents( 'php://input' );
$data = json_decode($contactFormData);
if ($data) {
    $sendername = $data->contactname;
    $sendersubject = $data->subject;
    $senderemail = $data->email;
    $message = $data->message;

    if ( $sendername != '') {
        $mailTo = 'contact@me.com';
        $subject = 'New contact form submission';
        $body  .= 'From: ' . $sendername . "\n";
        $body  .= 'Subject: ' . $sendersubject . "\n";
        $body .= 'Email: ' . $senderemail . "\n";
        $body .= "Message:\n" . $message . "\n\n";

        $sent = mail( $mailTo, $subject, $body );

    }
}
?>


text:
Q: Partial update into large document I'm facing the problem about performance. My application is about chatting.
I designed mapping index with nested object like below.
{
  "conversation_id-v1": {
    "mappings": {
      "stream": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "message": {
            "type": "text",
            "fields": {
              "analyzerName": {
                "type": "text",
                "term_vector": "with_positions_offsets",
                "analyzer": "analyzerName"
              },
              "language": {
                "type": "langdetect",
                "analyzer": "_keyword",
                languages: ["en", "ko", "ja"]
              }
            }
          },
          "comments": {
            "type": "nested",
            "properties": {
            "id": {
              "type": "keyword"
            },
            "message": {
              "type": "text",
              "fields": {
                "analyzerName": {
                  "type": "text",
                  "term_vector": "with_positions_offsets",
                  "analyzer": "analyzerName"
                },
                "language": {
                  "type": "langdetect",
                  "analyzer": "_keyword",
                  languages: ["en", "ko", "ja"]
                }
              }
            }
            }
          }
        }
      }
    }
  }
}

** actually have a lot of fields
A document has around 4,000 nested objects. When I upsert data into document, It peak the cpu to 100% also disk i/o in case write. Input ratio around 1000/s.
How can I tuning to improve performance?
Hardware
3x 2vCPUs 13GB on GCP

A: 4000 nested fields sounds like a lot - if I were you, I would look long and hard at your mapping design to be very certain you actually need that many nested fields.
Quoting from the docs:
Internally, nested objects index each object in the array as a separate hidden document.

Since a document has to be fully reindexed on update, you're indexing 4000 documents with a single update.
Why so many fields?
The reason you gave in the comments for needing so many fields
I'd like to search comments in nested and come with their parent stream for display.

makes me think that you may be mixing two concerns here.
ElasticSearch is meant for search, and your mapping should be optimized for search. If your mapping shape is dictated by the way you want to display information, then something is wrong.
Design your index around search
Note that by "search" I mean both indexing and querying.
For the use case you have, it seems like you could:

*

*Index only the comments, with a reference (some id) to the parent stream in the indexed comment document.

*After you get the search results (a list of comments) back from the search index, you can retrieve each comment along with its parent stream from some other data source (e.g. a relational database).

The point is, it may be much more efficient to re-retrieve the comment along with whatever else you want from some other source that is more better than ElasticSearch at joining data.


text:
Q: Finding values in JSON type response (HTTP) in python I have a json response
{"length": 2, "chain": [{"index": 0, "transactions": [], "timestamp": 0, "previous_hash": "0", "nonce": 0, "hash": "6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9"}, {"index"
: 1, "transactions": [{"test": "test2.m4a", "ipfs_hash": "QmaQgbSbgZdAfdiHmnfD9PevwpYSepytvA5G6agupqjVA3", "timestamp": 1610467381.102983, "Mac_ADD": "e0:94:67:bc:17:f9", "signature": "b'AQAgIQgAAD'"}], "timestamp":1610467386.9993732,"previous_hash":"6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9", "nonce": 214, "hash": "00a92715e60f577a57165b52c02e2b6bbef1ba60a3a27ead16e4d6a7a0a9d3d2"}], "peers": []}

I want to find the corresponding "ipfs_hash" using the "test" value. How do I achieve this in python?

A: You can use the Python standard library module json to convert JSON strings into dictionaries by using the json.loads(json_string) function.
For example:
import json
my_dictionary = json.loads("""{"length": 2, "chain": [{"index": 0, "transactions": [], "timestamp": 0, "previous_hash": "0", "nonce": 0, "hash": "6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9"}, {"index" : 1, "transactions": [{"test": "test2.m4a", "ipfs_hash": "QmaQgbSbgZdAfdiHmnfD9PevwpYSepytvA5G6agupqjVA3", "timestamp": 1610467381.102983, "Mac_ADD": "e0:94:67:bc:17:f9", "signature": "b'AQAgIQgAAD'"}], "timestamp":1610467386.9993732,"previous_hash":"6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9", "nonce": 214, "hash": "00a92715e60f577a57165b52c02e2b6bbef1ba60a3a27ead16e4d6a7a0a9d3d2"}], "peers": []}""")

Once you have it as a dictionary, you can access any of the elements by indexing with the key like so:
print(my_dictionary["length"])
print(my_dictionary["transactions"])

A: As the others have mentioned, you can use json to load your string into a python object, e.g., a dictionary.
s = '''{"length": 2, "chain": [{"index": 0, "transactions": [], "timestamp": 0, "previous_hash": "0", "nonce": 0, "hash": "6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9"}, {"index"
: 1, "transactions": [{"test": "test2.m4a", "ipfs_hash": "QmaQgbSbgZdAfdiHmnfD9PevwpYSepytvA5G6agupqjVA3", "timestamp": 1610467381.102983, "Mac_ADD": "e0:94:67:bc:17:f9", "signature": "b'AQAgIQgAAD'"}], "timestamp":1610467386.9993732,"previous_hash":"6dbf23122cb5046cc5c0c1b245c75f8e43c59ca8ffeac292715e5078e631d0c9", "nonce": 214, "hash": "00a92715e60f577a57165b52c02e2b6bbef1ba60a3a27ead16e4d6a7a0a9d3d2"}], "peers": []}'''

import json

d = json.loads(s)

test = 'test2.m4a'
for c in d['chain']:
    for t in c['transactions']:
        if t['test'] == test:
            print(t['ipfs_hash'])


text:
Q: .htaccess to redirect from http to https I have a website on shared host, the hosting default root directory is /public_html, but I place my website at /pulbic_html/web for file organizing purpose
I have registered for HTTPS from cloudflare
I wish for 2 results

*

*visitors can type https://example.com, https://www.example.com

*visitors can type http://example.com, http://www.example.com then redirect to either https://example.com or https://www.example.com
My current .htaccess
RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L,QSA]

Using the current .htaccess

*

*typing http://example.com -> working

*typing http://www.example.com -> working

*typing https://example.com -> working

*typing https://www.example.com -> working but redirect to http://example.com with connection not secure warning on the browser

I have googled and came up with
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L,QSA]

with this .htaccess all testing result

please help to achieve these

*

*typing https://example.com, https://www.example.com -> working

*typing http://example.com, http://www.example.com -> redirect to either https://example.com or https://www.example.com
thanks all

A: This might help.. Update your current rule with this:
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

A: RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


text:
Q: Dropdown menu not being displayed on clicking I have a website and the HomePage is working perfectly, but the dropdown menu which should get displayed on mobiles/small screens on clicking the down pointing triangle, next to the "Links", is not displaying/showing the top navbar links on any other webpage, for example Corns. I have tried a lot of things and given up! Somebody please help!

A: I solved it. I had missed a bracket in the Javascript!


text:
Q: openssl EC_KEY_new_by_curve_name crashed with no information In my get_keypair function,I want to create an EC_KEY structure by EC_KEY_new_by_curve_name(NID_secp256k1) .By doing so,I got a crash on my vs2019 with no details.Below comes my code.
bool get_keypair(EC_KEY** key, bool getcompressed,uint8_t* rawprikey,  uint8_t rawprikeylen) {
    BIGNUM* priv; //prikey bignum
    BN_CTX* ctx; //hold the operation
    const EC_GROUP* group;
    EC_POINT* pub; //pubkey point st
    *key = EC_KEY_new_by_curve_name(NID_secp256k1); //secp256k1, !!!crashed here
    if (*key == 0) {
        printf("new ec key failed");
        exit(-1);
    }
    priv = BN_new(); //create bignum
    BN_bin2bn(rawprikey, 32, priv); //fill the bigbum with prikey
    EC_KEY_set_private_key(*key, priv); //put prikey bignum to key pair

    ctx = BN_CTX_new(); //create context
    BN_CTX_start(ctx); //init context
    group = EC_KEY_get0_group(*key); //G
    pub = EC_POINT_new(group); //create pub st
    EC_POINT_mul(group, pub, priv, NULL, NULL, ctx); //P = n * G
    EC_KEY_set_public_key(*key, pub); //fill the key pair, !!!crashed here
    EC_KEY_set_conv_form(*key, getcompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED); //compressd or not
    uint64_t pubkeylen = i2o_ECPublicKey(*key, NULL);
    uint8_t *pubkey = calloc(pubkeylen, sizeof(uint8_t));

    uint8_t* pub_copy = pubkey;
    if (i2o_ECPublicKey(*key, &pub_copy) != pubkeylen) {
        puts("Unable to decode public key");
        return false;
    }

    /*for (int i = 0; i < *pubkeylen; i++) {
        printf("%02X", (*pubkey)[i]);
    }*/

    EC_POINT_free(pub);//free all
    BN_CTX_end(ctx);
    BN_CTX_free(ctx);
    BN_clear_free(priv);
    return true;
}

Just a proof of work,No checks was added.
And I keet rerun the program many times,saw that the program will crash at different code.
Below are some pictures captured when the program crashed.
crashed at EC_KEY_new_by_curve_name
crashed at EC_KEY_set_public_key
crashed on main exit
linked librares

A: You need to allocate "EC_KEY** key" variable before call get_keypair() function.


text:
Q: How to change the color of a glyph using callback? I've tried around using Bokeh, and now I want to search a word and change the color of its glyph. My code looks like that:
import bokeh.plotting as bp
from bokeh.models import HoverTool, CustomJS
from bokeh.models.widgets import TextInput
from bokeh.io import vform

words = ["werner", "herbert", "klaus"]
x=[1,2,3]
y=[1,2,3]
color = ['green', 'blue', 'red']
word_input= TextInput(value="word", title="Point out a word")

source = bp.ColumnDataSource(data= dict(x=x,y=y,words=words, color='color'))
hover= HoverTool(tooltips=[("word", "@words")])

# output to static HTML file (with CDN resources)
bp.output_file("plot.html", mode="cdn")

# create a new plot with the tools above, and explicit ranges
p = bp.figure(plot_height = 600, plot_width = 800, title="word2vec", tools=[hover], logo =None)
# add a circle renderer with vectorized colors and sizes
p.circle('x','y', radius= 0.1, color = color, source=source, line_color=None)
callback= CustomJS(args=dict(source=source), code ="""
    var data = source.get('data');
    var glyph = cb_obj.get('value')
    words = data['words']
    colors=data['color']
    for (i=0; i< words.length;i++){
        if(glyph==words[i]){colors[i]='yellow'}
    }
    source.trigger('change');
""")
layout = vform(word_input, p)
# show the results
bp.show(layout)

This code just doesn't work, and I can't figure out why not.
What am I doing wrong? I've posted an other question earlier that day and this is kind of a first step solving it.

A: there are a couple of problems you have:

*

*you create the CallbackJS but never set is as the callback property of the TextInput

*you set the color key of data dict to the string "color" not to the list of colors

*you passed the actual list of colors as the color argument to figure (it should be the string name of the data source column you want to use, e.g. "color")

Here is a version that works:
from bokeh.io import vform
from bokeh.models import HoverTool, CustomJS
from bokeh.models.widgets import TextInput
from bokeh.plotting import output_file, figure, show, ColumnDataSource

output_file("plot.html")

words = ["werner", "herbert", "klaus"]
x, y = [1,2,3], [1,2,3]
color = ['green', 'blue', 'red']

source = ColumnDataSource(data=dict(x=x, y=y, words=words, color=color))

hover = HoverTool(tooltips=[("word", "@words")])

p = figure(plot_height=600, plot_width=800, title="word2vec", tools=[hover])
p.circle('x','y', radius=0.1, fill_color='color', source=source, line_color=None)

callback = CustomJS(args=dict(source=source), code="""
    var data = source.get('data')
    var value = cb_obj.get('value')
    var words = data['words']
    for (i=0; i < words.length; i++) {
        if ( words[i]==value ) { data.color[i]='yellow' }
    }
    source.trigger('change')
""")

word_input = TextInput(value="word", title="Point out a word", callback=callback)

layout = vform(word_input, p)

show(layout)

A: Updated @bigreddot's solution to work under Bokeh 2.2.3 if others come along similar tasks.
from bokeh.layouts import column
from bokeh.models import HoverTool, CustomJS
from bokeh.models.widgets import TextInput
from bokeh.plotting import output_file, figure, show, ColumnDataSource

output_file("plot.html")

words = ["werner", "herbert", "klaus"]
x, y = [1,2,3], [1,2,3]
color = ['green', 'blue', 'red']

source = ColumnDataSource(data=dict(x=x, y=y, words=words, color=color))

hover = HoverTool(tooltips=[("word", "@words")])

p = figure(plot_height=600, plot_width=800, title="word2vec", tools=[hover])
p.circle('x','y', radius=0.1, fill_color='color', source=source, line_color=None)

callback = CustomJS(args=dict(source=source), code="""
    var data = source.data;
    var value = cb_obj.value;
    var words = data['words'];
    for (var i=0; i < words.length; i++) {
        if ( words[i]==value ) { data.color[i]='yellow' }
    }
    source.change.emit();
""")

word_input = TextInput(value="word", title="Point out a word")

word_input.js_on_change('value', callback)

layout = column(word_input, p)

show(layout)


text:
Q: From drop-list lists show only the selected list and its subcategories I want to show only the entire dropdown list, but when you select an option, the remaining list is removed and remains only selected is displayed. I'll show you the current code, all I want is when I click on "Main Item One", the "Main Item Two" option disappears and show only "Main Item One" with options. Or when I click on "Main Item Two" show only "Main Item Two" with subcategory.

var allHasChildren = document.querySelectorAll(".item-has-children a");
for (var x = 0; x < allHasChildren.length; x++) {
  allHasChildren[x].onclick = function() {
    // get the first submenu and toggle using classes
    var subMenu = this.parentNode.getElementsByClassName("sub-menu")[0];
    if (subMenu.classList.contains('selected')) {
      subMenu.classList.remove("selected");
    } else {
      subMenu.classList.add("selected");
    }
  }
}
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown .dropbtn {
  background-color: blue;
  color: #fff;
  font-size: 17px;
  font-weight: 600;
  border: none;
  cursor: pointer;
  height: 55px;
  background: #153161;
  border-bottom-left-radius: 7px;
  border-bottom-right-radius: 7px;
  padding: 12px 50px;
}

.dropdown .dropbtn i {
  margin-left: 30px;
  color: #8391ab;
}

.dropdown .dropbtn .arrow {
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #8191aa;
  margin: 100%;
  padding-top: 4px;
}

.dropdown .dropbtn-two {
  background: red;
}

.dropdown .dropbtn-three {
  background: yellow;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  width: 330px;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 25px;
  text-decoration: none;
  display: flex;
  justify-content: flex-start;
}

.dropdown-content a:hover {
  background-color: #F8F8F8;
}

.dropdown:hover .dropdown-content {
  display: block;
  background: white;
  opacity: 0.8;
  width: 100%;
}

.sub-menu {
  display: none;
}

.sub-menu.selected {
  display: block;
  transition: transform 0.6s;
}

ul {
  list-style: none;
}

  <button class="dropbtn dropbtn-one">
            DropDown

        </button>

        Main Item One

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six

        Main Item Two

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six

        Main Item Two

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six

A: Inside the click event handler you can get a reference to the parent li element of the selected option using
e.target.parentNode

Now if you loop over the complete list of options
document.querySelectorAll(".item-has-children")

and compare it to the reference you can hide the remaining options.
Here's some code:

var clicked = false;
var allHasChildren = document.querySelectorAll(".item-has-children a");
for (var x = 0; x < allHasChildren.length; x++) {
  allHasChildren[x].onclick = function(e) {

    var subMenu = this.parentNode.getElementsByClassName("sub-menu")[0];
    if (subMenu.classList.contains('selected')) {
      subMenu.classList.remove("selected");
    } else {
      subMenu.classList.add("selected");
    }
    var allOptions = document.querySelectorAll(".item-has-children");
    if (!clicked) {
      clicked = true;
      var currentOption = e.target.parentNode;

      for (var a = 0; a < allOptions.length; a++) {
        if (allOptions[a] != currentOption) {
          allOptions[a].style.display = "none";
        }
      }
    } else {
      clicked = false;
      for (var a = 0; a < allOptions.length; a++) {
        allOptions[a].style.display = "block";
      }
    }
  }
}

document.getElementsByClassName("dropdown")[0].onmouseout = function() {
  if (clicked && window.getComputedStyle(document.getElementsByClassName("dropdown-content")[0], null).getPropertyValue("display") == "none") {
    var allOptions = document.querySelectorAll(".item-has-children");
    for (var a = 0; a < allOptions.length; a++) {
      allOptions[a].style.display = "block";
    }

    var subMenu = document.getElementsByClassName("sub-menu");
    for (var a = 0; a < subMenu.length; a++) {
      subMenu[a].classList.remove("selected");
    }
    clicked = false;
  }
}
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown .dropbtn {
  background-color: blue;
  color: #fff;
  font-size: 17px;
  font-weight: 600;
  border: none;
  cursor: pointer;
  height: 55px;
  background: #153161;
  border-bottom-left-radius: 7px;
  border-bottom-right-radius: 7px;
  padding: 12px 50px;
}

.dropdown .dropbtn i {
  margin-left: 30px;
  color: #8391ab;
}

.dropdown .dropbtn .arrow {
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-right: 6px solid transparent;
  border-top: 6px solid #8191aa;
  margin: 100%;
  padding-top: 4px;
}

.dropdown .dropbtn-two {
  background: red;
}

.dropdown .dropbtn-three {
  background: yellow;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  width: 330px;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 25px;
  text-decoration: none;
  display: flex;
  justify-content: flex-start;
}

.dropdown-content a:hover {
  background-color: #F8F8F8;
}

.dropdown:hover .dropdown-content {
  display: block;
  background: white;
  opacity: 0.8;
  width: 100%;
}

.sub-menu {
  display: none;
}

.sub-menu.selected {
  display: block;
  transition: transform 0.6s;
}

ul {
  list-style: none;
}

  <button class="dropbtn dropbtn-one">
            DropDown

        </button>

        Main Item One

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six

        Main Item Two

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six

        Main Item Two

Sub Item One

Sub Item Two

Sub Item Three

Sub Item Four

Sub Item Five

Sub Item Six


text:
Q: Cherenkov light and refractive index LHCb's Ring Imaging CHerenkov detector (RICH) is aimed at telling different charged particles apart by measuring their velocity, which, together with an independent measurement of their momentum, is enough to derive their masses. It has been built in order to achieve a minimum angular acceptance of $10$ mrad and its medium has refractive index $n=1.0014$. As far as I know there is also RICH2, with a lower refractive index $n=1.0005$, to measure high energy particles, since it postpones the saturation effect.
The problem is that I don't really understand what "postpones the saturation effect" really means. The lower refraction index is supposed to allow me to distinguish between particles at higher energies, but I don't really understand why the lower index should help here.
Can somebody maybe explain this, or make an example that illustrates how the refractive index helps to distinguish particles with higher energy?

A: I am not entirely sure what ``saturation effect''  means in this case.
But let us go back to the expression for the Cherenkov angle:
$$
\cos\theta = \frac{1}{n \beta}
$$
we can obtain two limits:

*

*first, on the minimum $\beta$ to have Cherenkov effect:
$$
\beta_{\rm th} = \frac{1}{n},
$$
and - as you noticed - the smaller $n$, the lower the velocity of the particle we can detect;

*but also on the maximum aperture angle of the Cherenkov cone, in case the particle is ultrarelativistic $\beta \rightarrow 1$:
$$
\cos\theta_{\rm max} = \frac{1}{n}.
$$
I thought the ``saturation'' might be related to this second point, the fastest particles will generate cones with apertures:
\begin{equation}
\begin{split}
\theta_{\rm max}^{\rm RICH} &= \arccos \left( \frac{1}{1.0014} \right) \approx 3.03^{\circ}, \\
\theta_{\rm max}^{\rm RICH2} &= \arccos \left( \frac{1}{1.0005} \right) \approx 1.81^{\circ},
\end{split}
\end{equation}
In the two different detectors. For ultra-relativistic particles you will have smaller rings in the detector with the smaller $n$. If you receive many particles it would be easier to ``saturate'' (to create more overlapping rings, maybe?) the detector with the larger $n$.
Just my speculation though!

EDIT
After the useful suggestions of @dukwon I understood the saturation was not due to the number of particles hitting the detector but by the impossibility to distinguish their momentum when their $\beta \rightarrow 1$. Therefore I created this plot. Here I show the values of $\theta_{\rm C}$, i.e. the Cherenkov angle for different values of the particle energy. I consider three particles (kaon, pion and muon) and two mediums with the indexes, $n_1=1.0014$ and $n_2=1.0005$ as in @Sito's original question.

I placed the vertical dashed line by eye at the point where I am not capable of distinguishing anymore kaons and pions angles. As you can see in the material with the worst (higher) refraction index this happens already at $80\,{\rm GeV}$. In the material with the better (lower) refraction index you can push the indistinguishability of kaons and pions at $E > 100\,{\rm GeV}$. and that's exactly why $n_2=1.0005$

postpones the saturation effect
  .

Thanks @dukwon!
@Sito, here the snippet if you want to reproduce the figure
import numpy as np
import matplotlib.pyplot as plt

def beta(E, mec2):
    gamma = E / mec2
    return np.sqrt(1 - 1 / np.power(gamma, 2))

def theta(beta, n):
    return np.arccos(1 / (beta * n))

mec2_kaon = 493.68  # MeV / c^2
mec2_pion = 139.57  # MeV / c^2
mec2_muon = 105.65  # MeV / c^2

E = np.logspace(np.log10(5e3), 6, 100) # MeV

beta_pion = beta(E, mec2_pion)
beta_kaon = beta(E, mec2_kaon)
beta_muon = beta(E, mec2_muon)

n_1 = 1.0014
n_2 = 1.0005

fig, ax = plt.subplots()

plt.semilogx(E, theta(beta_kaon, n_1), color="crimson", ls="-", label=r"$K, n_1=1.0014$")
plt.semilogx(E, theta(beta_pion, n_1), color="crimson", ls="--", label=r"$\pi, n_1=1.0014$")
plt.semilogx(E, theta(beta_muon, n_1), color="crimson", ls="-.", label=r"$\mu, n_1=1.0014$")

plt.semilogx(E, theta(beta_kaon, n_2), color="k", ls="-", label=r"$K, n_2=1.0005$")
plt.semilogx(E, theta(beta_pion, n_2), color="k", ls="--", label=r"$\pi, n_2=1.0005$")
plt.semilogx(E, theta(beta_muon, n_2), color="k", ls="-.", label=r"$\mu, n_2=1.0005$")

plt.axvline(8e4, color="crimson", ls=":")
plt.axvline(1.1e5, color="k", ls=":")

plt.xlabel("E / MeV")
plt.ylabel(r"$\theta_{\rm C}\,/\,rad$")
plt.legend()
plt.show()
fig.savefig("cherenkov_angles.png")


text:
Q: SQL Server return one row with columns with the minimum and maximum data I have a dataset like this
Id  name  StartTime   EndTime
-----------------------------
1   aa    12:00       13:00
2   aa    13:30       15:00
3   aa    15:00       19:00

I need a query to return
aa,12:00,19:00

I want to return record having same name and a column with minimum time and the next one a maximum column

A: I suspect a simple aggregation and group by should do the trick
Select Name
      ,StartTime = min(StartTime)
      ,EndTime   = max(EndTime)
 From  YourTable
 Group By Name


text:
Q: Extjs 5 - How to add routes on init I have some routes in my App.controller which i like to extend on init (I get the routes from server). What is the method or function to append the routes?
I am looking for something like this
this.application.addRoute({
  route: 'new-page',
  action: 'showNewPage'
});

Lets say i have this setup below to clarify my questions:
Ext.define('APP.controller.AppController',{
    extend: 'Ext.app.Controller',
    alias: 'appcontroller',
    config : {
        routes : {
            'page'          : {
                action: 'showPage'
            }
      },
      init: function() {

       // How to add new route which will be added to config.routes of this controller?
       this.addRoute({
           route: 'new-page',
           action: 'showNewPage'
       });

      },
      showPage: function(){
      },
      showNewPage: function(){
      }
});

A: Turns out there is a setRoutes() method :)
Ext.define('APP.controller.AppController',{
    extend: 'Ext.app.Controller',
    alias: 'appcontroller',
    config : {
        routes : {
            'page'          : {
                action: 'showPage'
            }
      },
      init: function() {

       // Adding the routes
       this.setRoutes({
           'page'          : {
                action: 'showPage'
            },
            'new-page'          : {
                action: 'showNewPage'
            }
       });

      },
      showPage: function(){
      },
      showNewPage: function(){
      }
});


text:
Q: Conexões de rede entre processos dentro de uma máquina ao dar o comando netstat -na no cmd do windows aparecem as conexões de rede que estão em andamento na máquina.
Na minha apareceram diversas conexões tendo como IP de origem e destino o "127.0.0.1" que é o endereço "interno", ou seja, comunicação da própria máquina com ela mesma.
Alguém sabe porque o Windows faz isso? Ao invés de usar simplesmente (e somente) a comunicação entre processos? (Pipes, fifos, mensagens, sinais...)

A: Imagine que você precise testar sua aplicação cliente-servidor ou peer-to-peer consigo mesmo, sua máquina não está conectada na Internet, nem tem um IP real, e o protocolo de rede é o TCP/IP. Que endereço você usaria para se conectar consigo mesmo?
Bem, a IETF escreveu há muito a RFC 5735, que, entre outras coisas, define endereços IP especiais, como este, o 127.0.0.1, chamado loopback. É um endereço fixo que aponta sempre para a própria máquina. Utilizar o domínio localhost resulta no mesmo, porque no arquivo hosts do sistema operacional localhostestá mapeado para 127.0.0.1.
A aplicação nunca se encarrega da rede. Para ela não faz diferença se você está rodando o cliente e o servidor na mesma máquina ou em máquinas diferentes. Ela apenas vai obter a configuração de IP e porta que lhe for passada e pedir ao sistema operacional enviar a comunicação. Mas, quando se envia algo para 127.0.0.1, o sistema operacional nem se dá ao trabalho de enviar para além da placa de rede. O driver de rede TCP/IP passa direto para a porta da aplicação.
Existem outras utilidades menores deste endereço. Como por exemplo testar se o protocolo de comunição de rede instalado é o TCP/IP versão IPv4, com o comando $ ping 127.0.0.1. O sistema operacional precisa entender este endereço.

A:
Alguém sabe porque o Windows faz isso? Ao invés de usar simplesmente (e somente) a comunicação entre processos? (Pipes, fifos, mensagens, sinais...)

Não é bem o windows que faz isso, há sim alguns serviços nele que fazem isso, mas a maioria são de outros programas que deve ter instalado no seu computador.
Imagine um servidor de banco de dados, toda a comunicação é feita por TCP/IP, porque ele deve funcionar via rede. E para a comunicação local, ele continua a utilizar o TCP/IP, porém com o endereço loopback.
Imagine a complicação para desenvolver uma comunicação de rede e uma local (entre processos, mensagens, pipes, etc) apenas para não gerar essas conexões em loopback. Totalmente desnecessário.
Utilize netstat -a -b para ver quais são os executáveis que estão escutando ou comunicando com essas portas, ou então um software tcpview.exe da Sysinternals que mostra detalhada todas as comunicações do SO.
Download tcpview: https://docs.microsoft.com/en-us/sysinternals/downloads/tcpview


text:
Q: How to retrieve object from query params in url in Angular 8 I was wondering if there is a way how I can retrieve an array of objects from the queryParams in a url.
The objects that I want to retrieve should look like this.
events: [
 {
   locations: ['123456789', '987654321']
   period: {
     from: '2019-11-19',
     to: '2019-11-27'
   }
 },
 {
   locations: ['123456789']
   period: {
     from: '2018-01-23',
     to: '2018-01-25'
   }
 }
],
days: [0, 1, 2, 3],
groupBy: 'days',
extraSeries: ['visits']

So I was wondering how the queryparams in the url should look like and how I should retrieve them from the url. For example how do I get queryParam events which return the array of objects?
The reason why I need this is in the queryParams is because I want to be able to share a url with other users where the filter is set based on the queryParams.

A: You can use queryParams
Look out this demo it helps you
import { ActivatedRoute } from '@angular/router';

 constructor( private route: ActivatedRoute) { }

 ngOnInit() {
     this.route.queryParams.subscribe(params => {
        let event = params['events'];
      });
  }

A: I wouldn't share the params as is. You can base64 encrypt and decrypt the params for sharing. Your example data encrypted:
ZXZlbnRzOiBbDQogew0KICAgbG9jYXRpb25zOiBbJzEyMzQ1Njc4OScsICc5ODc2NTQzMjEnXQ0KICAgcGVyaW9kOiB7DQogICAgIGZyb206ICcyMDE5LTExLTE5JywNCiAgICAgdG86ICcyMDE5LTExLTI3Jw0KICAgfQ0KIH0sDQogew0KICAgbG9jYXRpb25zOiBbJzEyMzQ1Njc4OSddDQogICBwZXJpb2Q6IHsNCiAgICAgZnJvbTogJzIwMTgtMDEtMjMnLA0KICAgICB0bzogJzIwMTgtMDEtMjUnDQogICB9DQogfQ0KXSwNCmRheXM6IFswLCAxLCAyLCAzXSwNCmdyb3VwQnk6ICdkYXlzJywNCmV4dHJhU2VyaWVzOiBbJ3Zpc2l0cydd
The encrypted data is not shorter, but it has url-friendly characters

A: It may help to you try below code:
import { ActivatedRoute } from '@angular/router';

constructor( private route: ActivatedRoute) { }

ngOnInit() {
  this.route.queryParams.subscribe(
  params => {
    let event = params['events'];
  });
}


text:
Q: Communication between sibling components in angular I have two sibling components and one needs to send data to the other one. The communication should happen between the heroes component and encounters component:

 <app-heroes></app-heroes>

 <app-monsters></app-monsters>

 <app-encounters></app-encounters>

I have uploaded the UI to imgur to clarify the issue. When someone clicks on one of the heroes, the hero that has been clicked should be added to "Heroes" in the encounter component.
I created a shareservice:
import { Injectable } from '@angular/core';
import {Subject} from 'rxjs';
import {Hero} from '../model/hero';

@Injectable({
providedIn: 'root'
})
export class SharedHeroService {
 private hero = new Subject<Hero>();
 public  hero$ = this.hero.asObservable();

 publishHero(heroToPublish: Hero){
  this.hero.next((heroToPublish));
 }
}

for which I created the following method in my heroes component:
addToEncounter(hero){
this.sharedService.publishHero(hero);
}

and added the following in my Encounters component:
@Input() public heroesAdded = [];
@Input() hero: Hero;
private subscriber: Subscription;

constructor(private sharedHeroService: SharedHeroService) {}

ngOnInit() {
this.subscriber = this.sharedHeroService.hero$.subscribe(hero =>{this.hero =
hero; this.monstersAdded.push(hero)});
}

The html for the Heroes component is:

  {{hero.name}}
Hitpoints: {{hero.hitPoints}} Armor: {{hero.armor}}

But when I click on the badge, I get the following error:
Uncaught ReferenceError: addToEncounter is not defined
    at HTMLSpanElement.onclick
I googled this and people are saying the onclick() should never be used, but I don't really get the alternatives?

A: You should use (click) instead of onClick

  {{hero.name}}
Hitpoints: {{hero.hitPoints}} Armor: {{hero.armor}}


text:
Q: creating xpi does not work I have been trying to learn about Add On Development for Firefox.  I am hitting a snag and I am not too sure what the issue is?  I have tried installing the SDK and Python on two different machines Python 2.5 (on a win server 2008) and python 2.6 (on windows 7) successfully. I installed the Add On SDK with no problems.  Followed this tutorial to a TEE. https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Getting_Started_With_cfx the test runs perfectly using cfx run on both machines and setups.  Looks great.  My issue is when I do cfx xpi to create the xpi file.  It creates the file no problem and I can install this no problem on a Mac FireFox browser and it all works like a charm. However, when I try to install this on any Windows Firefox browser in the Add-Ons manager it installs perfectly but the icon that is supposed to be in the add-on toolbar never shows up.  Why would this example xpi not work on Windows Firefox?
This is the code in my lib/main.js file
var widgets = require("sdk/widget");
var tabs = require("sdk/tabs");
var widget = widgets.Widget({
  id: "jquery-link",
  label: "jQuery website",
  contentURL: "http://www.jquery.com/favicon.ico",
  onClick: function() {
    tabs.open("http://www.jquery.com/");
  }
});

Exactly like the tutorial.  I don't believe its a code issue more than a setup issue? Or maybe there is another step that is missing for Windows Firefox (maybe a setting in options? Security? or maybe some file needs to be registered in the registry?).  The strangest part about this is that it works no problem with cfx run, I see the jQuery icon in the add-on bar. When I create the xpi file and install it into the same Firefox browser I just tested it with it doesn't work?  Any clue why?


text:
Q: how to make a function for validating TextInputLayout kotlin I want to make a function for validation of text inputs(material design) and use it multiple times
I have a working code but I know it is dirty
how to optimize it?
this is my onClick method
 fun addItems(view: View) {

        val name1 = etName.text.toString().trim()
        val quantity1 = etQuantity.text.toString()
        val gst1 = etGst.text.toString()
        val amount1 = etAmount.text.toString()
        fun showToast() {
            runOnUiThread(kotlinx.coroutines.Runnable {
                Toast.makeText(this, "$name1 Added", Toast.LENGTH_LONG).show()
            }) // runnable is used because activity is immediately killed and toast cannot be sowed hence it is to be done on ui tread
            finish()
        }

        if (name1.isNotBlank() && quantity1.isNotBlank() && amount1.isNotBlank()) {

            if (quantity1.toInt() != 0) {
                if (amount1.toInt() != 0) {
                    Thread {
                        val db = Room.databaseBuilder(this, AppDb::class.java, "BookDB")
                            .build()
                        val item = ItemEntity()
                        item.itemName = name1
                        item.quantity = quantity1
                        item.amount = amount1
                        if (boolProcessWithGST) {
                            if (gst1.isNotBlank()) {
                                if (gst1.toInt() != 0) {
                                    // process with GST
                                    item.gst = gst1
                                    db.abstractItemDao().saveItems(item)
                                    showToast()

                                } else runOnUiThread {
                                    tilGST.error = "Tax can't be 0%"
                                    etGst.requestFocus()
                                } // ui operation only works on main/ui thread
                            } else runOnUiThread {
                                tilGST.error = "Disable toggle if no TAX"
                                etGst.requestFocus()
                            }
                        } else {
                            // process without gst
                            db.abstractItemDao().saveItems(item)
                            showToast()
                        }
                    }.start()
                } else {
                    tilAmount.error = "Amount can't be 0"
                    etAmount.requestFocus()
                }
            } else {
                tilQuantity.error = "Quantity can't be 0"
                etQuantity.requestFocus()
            }
        } else Toast.makeText(this, "please fill the required fields", Toast.LENGTH_LONG).show()
    }

I want to use the same validation for another onClick in the same activity
I tried making a function but the android studio suggests -> Cascade if should be replaced with when. how to do so?
function I made
private fun isValidInput(): Boolean {
        var isValid = true
        val name1 = etName.text.toString().trim()
        val quantity1 = etQuantity.text.toString()
        val gst1 = etGst.text.toString()
        val amount1 = etAmount.text.toString()

        TransitionManager.beginDelayedTransition(root_layout)
        if (name1.isEmpty()) {
            tilName.isErrorEnabled = true
            tilName.error = "Required"
            isValid = false
        } else tilName.isErrorEnabled = false

        if (quantity1.isEmpty()) {
            tilQuantity.isErrorEnabled = true
            tilQuantity.error = "Required"
            isValid = false
        } else if (quantity1.toInt() == 0) {
            tilQuantity.isErrorEnabled = true
            tilQuantity.error = "can't be 0"
        } else tilQuantity.isErrorEnabled = false

        if (amount1.isEmpty()) {
            tilAmount.isErrorEnabled = true
            tilAmount.error = "Required"
            isValid = false
        }else if (amount1.toInt() == 0) {
            tilAmount.isErrorEnabled = true
            tilAmount.error = "can't be 0"
        } else tilAmount.isErrorEnabled = false

        if (gst1.isEmpty()) {
            tilGST.isErrorEnabled = true
            tilGST.error = "Required"
            isValid = false
        }else if (gst1.toInt() == 0) {
            tilGST.isErrorEnabled = true
            tilGST.error = "can't be 0"
        } else tilGST.isErrorEnabled = false

        return isValid
    }

A: first I recommend using MVVM or any other architectural pattern(MVC, MVP, MVI ... ) to clean your code and achieve separation of concerns principle. in short, you should have a separate class for your application logic(in MVVM its called ViewModel) and repository class for accessing and saving your data like database or API call, and your activity is only responsible for the views. this will make your code much cleaner.
for starter, you can use this guide : Guide to app architecture
but there are tons of other resources out there which you can learn from
for your warning "Cascade if should be replaced with when" you can just hit Alt+enter and let the android studio do it for you. if it's not working you can do it yourself. it means something like this
with if:
if (num == 0) {
        //do something
    } else if (num < 5) {
        //do something
    } else {
        //do something
    }

convert to when looks like this:
 when {
        num == 0 -> {
            //do something
        }
        num < 5 -> {
            //do something
        }
        else -> {
            //do something
        }
    }

when is called switch/case in other programming languages.


text:
Q: Random WinError 10060 when trying to connect to websocket Background - using a windows machine, Windows 10/11, connected to the internet through ethernet cable. Using python's websocket-client module, on pycharm.
Problem - one fine day, out of the blue, I am no longer able to connect to FTX's websocket wss://ftx.com/ws/ on my local windows machine and kept getting the error [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
I tried on my VPS, a linux machine, with the same exact code and it works fine.
Attempts to fix the problem were:

*

*A full reformat of computer, windows 10 > windows 10, and reinstall python 3.10 and pycharm.

*Then upgrading windows 10 > windows 11.

*Made sure all drivers are up to date, and also reinstalling them.

*Resetting network settings from Windows

*Tested the websocket connection with other end point and it worked fine. eg wss://api.gemini.com/v1/marketdata/BTCUSD
None of the above worked.
My websocket connection is in a while loop something like this
while True:
         try:
              ws.run_forever()
              time.sleep(0.2)
         except:
              pass

So it would keep retrying.
There was a weird behavior when, from windows, I disable, and re-enable the network adapter, the websocket connection would suddenly be successful. And if I were to disable and re-enable the network adapter again; sometimes it would continue to fail, or sometimes the connection would be successful again. Note this is while the code is still executing in the while loop.
And, if I were to stop and re-run the code, it would never work, and the error WinError 10060 would arise.
At this point I am stumped and have no clue how to solve this problem as it was totally random and out of the blue. Looking for help and advise please..!


text:
Q: Oracle database rollback after update After upgrading from 11g to 12c, we noticed a weird behaviour. When we update a table, the data is rolled back though we issued commit and there was no error.
Anyone with similar experience?

A: This is never supposed to happen: once the database receives a COMMIT request, it must either (1) fulfill the COMMIT request or (2) return an error AND roll back the transaction.  Oracle (version 12C) has an API called "Transaction Guard" that is supposed to notify you if a commit is successful.  Here is the URL for that API:
https://docs.oracle.com/database/121/CNCPT/transact.htm#CNCPT89217
Even if you are Not using this API, if the transaction reaches the ORACLE database, it should
either succeed or you should receive a listener or ORA- error.
Are you sure that:

You are using a client that does not roll back if part of the data for a transaction (E.G. one field in a data grid) is not filled out
Is your ORACLE client compatible with 12C?


text:
Q: C++ member function callback and object lifetime I have a zeromq subscriber class that handles events from any of my connectes publisher services. This works well but now I want class member function callbacks. The specific class which contains all the member functions has the subscriber class as a member but how to manage object lifetime when registering member functions in the subscriber class.
I do not know exactly how to name this problem but imagine the following situation:

*

*The subscriber class has a data structure that holds all callbacks. This is quite easy to implement using lambdas and std::function for binding to class members.

*The class containing the subscriber class is destructed and goes into the destructor. After the destructor, all members (including the subscriber) are destroyed. This is the situation which is critical because the server is still able to send some data and the subscriber is still alive after the destructor has been called but calling a member function after the destructor might be dangerous.
How would you handle this situation?
Edit 1:
Here is some mockup.
class Subscriber {
public:
  Subscriber(const std::string &server);

  void subscribe(const std::string &topic,
    std function);

}

class SomeClass {
public:
  SomeClass();
  virtual ~SomeClass();

private:
  Subscriber sub;
}

SomeClass may do whatever it wants and register some handlers.


text:
Q: Hide tab markers in Ace editor Ace editor shows tab markers.  Tabs are marked by dots.  Is there a way to hide them?
Here is the code I'm using to load the editor:
var themeCssAceEditor = ace.edit("themeCssAceEditor");
baseCssAceEditor.setTheme("ace/theme/monokai");
themeCssAceEditor.getSession().setMode("ace/mode/css");
themeCssAceEditor.on("change", function test() { });

Also, can anyone explain the meaning of the following line?                  themeCssAceEditor.getSession().setUseSoftTabs(true);

A: themeCssAceEditor.setDisplayIndentGuides(false) (see kitchen-sink demo)
useSoftTabs means tabs are expanded to spaces


text:
Q: Non-Zero Metrics-FileBeat I am using elasic.co/filebeat:6.3.1 and ELK elastic.co:6.3.0 in ubuntu as docker, while running filebeat facing this issue,
https://i.stack.imgur.com/9rZjt.png
And my filebeat.yml is
filebeat.inputs:

    # Each - is an input. Most options can be set at the input level, so
    # you can use different inputs for various configurations.
    # Below are the input specific configurations.

  - type: log

   # Change to true to enable this input configuration.
  enabled: false

   # Paths that should be crawled and fetched. Glob based paths.
 paths:
     - /usr/local/java/ABC_LOGS/*/*.log
     #- c:\programdata\elasticsearch\logs\*
     #============================= Filebeat modules ===============================

       filebeat.config.modules:
         # Glob pattern for configuration loading
        path: ${path.config}/modules.d/*.yml

             # Set to true to enable config reloading
       reload.enabled: false

          #==================== Elasticsearch template setting ==========================

       setup.template.settings:
       index.number_of_shards: 3
       #index.codec: best_compression
       #_source.enabled: false

              #============================== Dashboards =====================================
          setup.dashboards.enabled: true

      #============================== Kibana =====================================

         setup.kibana:
            host: "10.0.0.0:5601"

       #-------------------------- Elasticsearch output ------------------------------
          output.elasticsearch:
            hosts: ["10.0.0.0:9200"]

Please help me,Thanks in advance


text:
Q: If $P(G)>0$, then $\int_GX\ dP<0$ where $G:=\{X<0\}$?
Let $(\Omega,\Sigma,P)$ be a probability space and $X:\Omega\to\mathbb{R}$ be a random variable. Let $G:=\{X<0\}$. If $P(G)>0$, then $\int_GX\ dP<0$.

I came up with this exercise in measure theory when I tried to recover the proof of a property of conditional expectations: if $X\leq Y$ a.s., then
$
E(X|\Sigma)\leq E(Y|\Sigma)
$
a.s.
One can get immediately "$\int_G X\leq 0 $" by the property of integral. But I don't see how to get rid of the equal sign.
I'm quite sure that I have seen similar questions here before but I can't find one.

A: Hint: One of the sets $\{X < -1/n\}, n = 1,2,\dots $ has positive measure.


text:
Q: Using multiple strategies in Passport, how can I find the strategy being used? I've got a REST API built with Node.js/Express, and my endpoints are protected using either a username/password combination (HTTP Basic Authentication, with passport-http) or bearer token (HTTP Bearer Authentication, with passport-http-bearer).
This is how I use passport.authenticate in my router:
passport.authenticate(['basic', 'bearer'], { session: false });

I'd like to be able to determine which strategy was used for the request from within my routes (so I could, for example, limit the access of token requests).
Does Passport provide a way to do this? If not, is there a workaround?
Thank you.


text:
Q: Why can a closed, bounded interval be uncountable? From what I have read, all finite sets are countable but not all countable sets are finite. As I understand it,

*

*Countably Finite --- a one to one map onto $\Bbb{N}$ with a limited number of members

*Countably Infinite --- a one to one map onto $\Bbb{N}$ with an unlimited number of members but that you can count in principle if given an infinite amount of time

*Uncountably Infinite --- there is no one to one mapping onto $\Bbb{N}$. Even if you count, you will miss some of the members. And it is infinite.

From this I gather that countable is not the same as finite. Countable is the one to one property with $\Bbb{N}$. Finite just means a limited number of elements.
Now consider $[0,1]$ which is closed and bounded.

*

*Bounded --- $\forall k \in [0,1]$ we have $k \leq 1$. Similarly all $k\geq0$.

*Closed --- it contains the endpoints $0$ and $1$

Yet I read $[0,1]$ is uncountably infinite. So clearly, neither closure nor boundedness implies finiteness or countability.
Question:
Why can a closed, bounded interval be uncountable?
It just seems like something that is bounded would be "more finite" than something that isn't.

A: I suspect you're conflating two meanings of "finite". Some sets are finite, meaning they have only finitely many elements.  An interval like $[0,1]$ is not such a set.  On the other hand, $[0,1]$ has finite length, which is a quite different matter.  As the other answers have explained, finite length does not imply finiteness (or even countability) in terms of the number of elements.

A: Certainly the interval $[0,1]$ is uncountably infinite; it has the same cardinality as $(0,1)$ and $\mathbb{R}$ and $\mathcal{P}(\mathbb{N})$ and many other sets which are commonly used in mathematics.
However, closed and bounded intervals such as $[0,1]$ do have a nice finiteness property called compactness: that is, if $\{ U_i \mid i \in I \}$ is any collection of open intervals such that $\bigcup_{i \in I} U_i = [0,1]$, then there is a finite subset $J \subseteq I$ such that $\bigcup_{i \in J} U_j = [0,1]$.
This is not true of $(0,1)$, since for instance if we define $U_i = (\frac{1}{i}, 1-\frac{1}{i})$ then $\bigcup_{i \in I} U_i = (0,1)$ but no finite subset $J \subseteq I$ has $\bigcup_{i \in J} U_i = (0,1)$.

A: Well, in some sense you are right. If a set is bounded, that means it has finite volume. If it is not bounded, it means it cannot be contained in any ball of finite volume (does not mean it has infinite volume though, e.g. consider the set of all $(k,0)$ for integer $k$ in $\mathbb{R}^2$).
Note that both finite and countable sets have 0 volume in real space...

A: Why would you expect otherwise, when $[0,1]$ contains $0$ and $\frac{1}{a}$ for every $a\in[1,\infty)$? Your intuition probably tells you there are plenty of real numbers bigger than $1$. $[0,1]$ includes a variety of things, like
$$\begin{align*}
0&.10000000000000000\ldots\\
0&.01000000000000000\ldots\\
0&.00100000000000000\ldots\\
&\;\vdots\\
0&.012345678910111213\ldots\\
&\;\vdots\\
&\;\text{random numbers like}\\
0&.235672352435943092\ldots\\
0&.594368239803409420\ldots\\
0&.234796028543203921\ldots\\
0&.824875320985230387\ldots\\
0&.314654363453498344\ldots\\
0&.348657378634864915\ldots\\
0&.120490320289123526\ldots\\
\end{align*}$$
and even if you listed a countably infinite number of such elements, you still wouldn't have gotten them all.

A: In the sense of cardinality, $[0,1]$ and $\mathbb R$ are the same (ie they have the same cardinality) because you can find a bijection from $[0,1]$ to $\mathbb R$.
As you've noted, this has nothing to do with a set being closed or bounded

A: Let $[a,b]\subset\mathbb R$ be a closed interval-segment. What would happen if it were countable?
(source: https://web.math.pmf.unizg.hr/~guljas/skripte/MATANALuR.pdf)
Then there would exist a bijection $f:\mathbb N\to[a,b]$. For the sake of understanding, let's treat it like a sequence, just like others have already suggested, and look it as nothing but points. I'll state we want to come to a contradiction according to the axiom of completeness and Cantor's axiom. We're dealing with nested-intervals.
Range/image of $f$: $$\mathcal R_f=[a,b]=\{f(n):n\in\mathbb N\}$$
Next step: $a=a_1,b=b_1$
$$\frac{a+b}{2}=\frac{a_1+b_1}{2}=\frac{2a_1+2b_2}{4}$$
Two cases:
$(i)$ $f(1)\leq\frac{a_1+b_1}{2}$ & $(ii)$ $f(1)\geq\frac{a_1+b_1}{2}$
Technical computations:
$a_1,b_1\in\mathbb R,a_1<b_1\implies$
$$\frac{a_1+b_1}{2}=\frac{a_1+a_1+2b_1}{4}<\frac{a_1+b_1+2b_1}{4}=\frac{a_1+3b_1}{4}\;\;\;\;\;(1)$$
$$\frac{a_1+b_1}{2}=\frac{2a_1+b_1+b_1}{4}>\frac{2a_1+a_1+b_1}{4}=\frac{3a_1+b_1}{4}\;\;\;\;\;(2)$$
Now we manipulate with this arbitrary function so as to get nonsense:
$(i)\;\&\;(1),\;\;a_2=\frac{a_1+3b_1}{4},\;b_2=b_1$ $$f(1)\leq\frac{a_1+b_1}{2}\implies f(1)\notin[a_2,b_2]$$
$(ii)\;\&\;(2),\;\;a_2=a_1,\;b_2=\frac{3a_1+b_1}{4}$ $$f(1)\geq\frac{a_1+b_1}{2}\implies f(1)\notin[a_2,b_2]$$
We managed to construct $[a,b]$ s.t. $f(1)\notin[a,b]$ neither in $(i)$ or $(ii)$.
We iterate this for $n\in\mathbb N$ and $$a_{n+1}=a_n\underline{\lor} b_{n+1}=b_n$$ and$$[a_{n+1},b_{n+1}]\subset[a_n,b_n],f(n)\notin [a_{n+1},b_{n+1}]\;\forall n\in\mathbb N$$
But$$\text{axiom of completeness}\implies\;\;\exists x\in[a,b]\cap[a_n,b_n]=[a_n,b_n]\;\forall n\in\mathbb N$$
and
$$f:\mathbb N\to[a,b]\;\text{is bijective}\implies\;\exists m\in\mathbb N\;s.t.\;f(m)=x$$
But (again) $$f(m)\notin[a_{m+1},b_{m+1}]\Rightarrow\Leftarrow$$


text:
Q: what is the correct place to put code that reoccurs on every page in MVC In my mvc solution I was originally using a viewModel to hold an IEnumerable of SelectListItems. These would be used to populate a dropdownfor element like below
 @Html.DropDownListFor(model => model.Type, Model.PrimaryTypeList, new { data_acc_type = "account", data_old = Model.Type, @class = "js-primary-account-type" })

the problem being that whenever I had to return this view, the list would need re-populating with something pretty heavy like the following:
if(!ModelState.IsValid){
 using (var typeRepo = new AccountTypeRepository())
            {

                var primTypes = typeRepo.GetAccountTypes();
                var primtype = primTypes.SingleOrDefault(type => type.Text == model.Type);
                model.PrimaryTypeList =
                    primTypes
                    .Select(type => new SelectListItem()
                    {
                        Value = type.Text,
                        Text = type.Text
                    }).ToList();

                }
  return View(model);
}

It seemed silly to me to have to rewrite - or even re-call (if put into a method) the same code every postback. - the same applies for the ViewBag as i have about 6 controllers that call this same view due to inheritance and the layout of my page.
At the moment i'm opting to put the call actually in my razor. but this feels wrong and more like old-school asp. like below
@{
ViewBag.Title = "Edit Account " + Model.Name;

List<SelectListItem> primaryTypes = null;
using (var typeRepo = new AccountTypeRepository())
{
    primaryTypes =
        typeRepo.GetAccountTypes()
        .Select(t => new SelectListItem()
        {
            Value = t.Text,
            Text = t.Text
        }).ToList();
}
 @Html.DropDownListFor(model => model.Type, primaryTypes, new { data_acc_type = "account", data_old = Model.Type, @class = "js-primary-account-type" })

Without using something completely bizarre. would there be a better way to go about this situation?
UPDATE: While semi-taking onboard the answer from @Dawood Awan below. my code is somewhat better, still in the view though and i'm 100% still open to other peoples ideas or answers.
Current code (Razor and Controller)
  public static List<SelectListItem> GetPrimaryListItems(List<AccountType> types)
    {
        return types.Select(t => new SelectListItem() { Text = t.Text, Value = t.Text }).ToList();
    }
    public static List<SelectListItem> GetSecondaryListItems(AccountType type)
    {
        return type == null?new List<SelectListItem>(): type.AccountSubTypes.Select(t => new SelectListItem() { Text = t.Text, Value = t.Text }).ToList();
    }

@{
    ViewBag.Title = "Add New Account";
    List<SelectListItem> secondaryTypes = null;
    List<SelectListItem> primaryTypes = null;
    using (var typeRepo = new AccountTypeRepository())
    {
        var primTypes = typeRepo.GetAccountTypes();
        primaryTypes = AccountController.GetPrimaryListItems(primTypes);
        secondaryTypes = AccountController.GetSecondaryListItems(primTypes.SingleOrDefault(t => t.Text == Model.Type));
    }

}

A: In practice, you need to analyse where you app is running slow and speed up those parts first.
For starters, take any code like that out of the view and put it back in the controller. The overhead of using a ViewModel is negligible (speed-wise). Better to have all decision/data-fetching code in the controller and not pollute the view (Views should only know how to render a particular "shape" of data, not where it comes from).
Your "Something pretty heavy" comment is pretty arbitary. If that query was, for instance, running across the 1Gb connections on an Azure hosted website, you would not notice or care that much. Database caching would kick in too to give it a boost.
Having said that, this really is just a caching issue and deciding where to cache it. If the data is common to all users, a static property (e.g. in the controller, or stored globally) will provide fast in-memory reuse of that static list.
If the data changes frequently, you will need to provide for refreshing that in-memory cache.
If you used IOC/injection you can specific a single static instance shared across all requests.
Don't use per-session data to store static information. That will slow down the system and run you out of memory with loads of users (i.e. it will not scale well).

A: If the DropDown Values don't change it is better to save in Session[""], then you can access in you View, controller etc.
Create a class in a Helpers Folder:
public class CommonDropDown
{

    public string key = "DropDown";

    public List<SelectListItem> myDropDownItems
    {
        get { return HttpContext.Current.Session[key] == null ? GetDropDown() : (List<SelectListItem>)HttpContext.Current.Session[key]; }
        set { HttpContext.Current.Session[key] = value; }
    }

    public List<SelectListItem> GetDropDown()
    {

        // Implement Dropdown Logic here
        // And set like this:
       this.myDropDownItems = DropdownValues;
    }
}

Create a Partial View in Shared Folder ("_dropDown.cshtml"):
With something like this:
@{
    // Add Reference to this Folder
    var items = Helpers.CommonDropDown.myDropDownItems;
}

@Html.DropDownList("ITems", items, "Select")

And then at the top of each page:
@Html.Partial("_dropDown.cshtml")


text:
Q: How can you extract the currently-selected range of cells in LibreOffice calc via pyuno? When using pyuno in a LibreOffice / OpenOffice calc python macro, I would like simply to be able to select a range of cells, and when the macro is run, for all of the cell data (e.g. as some iterable object) to be able to be retrieved within the python script, so that it can be manipulated.  I have found hardly any documentation on this, and would welcome some example code that demonstrates how to do this.

A: After a very painful time of trial and error (thanks to the scant documentation and examples on pyuno usage anywhere -- please correct me if I've overlooked something), I ended up with the following code that seems to do what I'm after:
import uno
doc = XSCRIPTCONTEXT.getDocument()

def mymodule():
    ctrlr = doc.CurrentController
    sel = ctrlr.getSelection()
    x = sel.getDataArray()
    # now the data is available as nested tuples in x, so do something with it
    file('/tmp/out', 'w').write(repr(x))

This can be put into a python file, and stored (at least with Ubuntu 14.04) in the ~/.config/libreoffice/4/user/Scripts/python directory, and then as long as the libreoffice-script-provider-python package is installed, it can be run from within LibreOffice Calc via the Tools->Macros->Run Macro menu option.  Or it can be bound to a keyboard shortcut using the Tools->Customize->Keyboard dialog.
For a more complete example that allows one to load data from LibreOffice Calc into Octave for further analysis, see this pyuno script.

A: Or you could try something like this, which I think is more easily understood.
    desktop = XSCRIPTCONTEXT.getDesktop()
    model = desktop.getCurrentComponent()
    try:
        sheets = model.getSheets()
    except AttributeError:
        raise Exception("This script is for Calc Spreadsheets only")
    #sheet = sheets.getByName('Sheet1')
    sheet = model.CurrentController.getActiveSheet()
    oSelection = model.getCurrentSelection()
    oArea = oSelection.getRangeAddress()
    first_row = oArea.StartRow
    last_row = oArea.EndRow
    first_col = oArea.StartColumn
    last_col = oArea.EndColumn


text:
Q: как проверить какой стандарт С99 или С11 использует интегрированнная среда разработки В общем пользуюсь QtCreator-ом, и хотел бы в виде кода вывести какой стандарт СИ использует мой gcc.
Хотел бы в виде кода запустить, а терминал вывел.

A: Использование стандарта зависит от флагов gcc на этапе компиляции.
gcc -std=

Доступны такие значения:
'c90'
'c89'
'iso9899:1990'
'iso9899:199409'
'c99'
'c9x'
'iso9899:1999'
'iso9899:199x'
'c11'
'c1x'
'iso9899:2011'
'c17'
'c18'
'iso9899:2017'

По умолчанию при отсутсвии флагов используется
-std=gnu11

Подробнее Параметры управления диалектом C и Языковые стандарты, поддерживаемые GCC
Конкретно для Qt creator это регулируется в .pro файле добавлением флагов
 QMAKE_CFLAGS += -std=c99

A: Спасибо @Fat-Zer  , надо использовать макрос __STDC_VERSION__
Вот код:
    printf(" используем версию языка %d\n", __STDC_VERSION__);

выводит :
используем версию языка 201112
что означает 2011 год 12 месяц (также сюда не добавили 20 день :3 )
вот ссылка на сам архив:
https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg23572.html


text:
Q: How to check if records related to fields in custom metadata are changed I have a scenario where I need to check in opportunity update if particular field values of opportunity which are mentioned in metadata are changed or not, if these values are changed meaning that that record would be considered for update. I have done this with field sets but not sure how we can achieve the same using custom metadata. Attaching the code used for field sets here
Public static boolean isValuesChanged(List<Opportunity> newOpportunitiesList, Map<id,Opportunity> oldOpportunityMap)
{
    for(Opportunity oppRecord : newOpportunitiesList)
    {

            for(Schema.FieldSetMember fieldSetMemberObj : SObjectType.Opportunity.FieldSets.Opportunity_Comparision_FieldSet.getFields())
            {
                if(oppRecord.get(fieldSetMemberObj.getFieldPath()) != oldOpportunityMap.get(oppRecord.id).get(fieldSetMemberObj.getFieldPath()) && oppRecord.Amount > 0)
                {
                    return true;
                }
            }

    }
    return false;
}

This is what I have done when I used field sets. The same I want to do using custom metadata.How can I check changes in Apex ?
Thanks in Advance

A: Cut it into 2 problems.

*

*Given a set of strings with field api names - how to detect changes

Set<String> fields = new Set<String>{'Name', 'CloseDate', 'StageName'};
Set<Id> oppsToProcess = new Set<Id>();

for(Opportunity opp: newList){
    Opportunity old = oldMap.get(opp.Id);
    for(String field : fields){
        if(opp.get(field) != old.get(field)){
            oppsToProcess.add(opp.Id);
            break;
        }
    }
}

*Given a custom metadata with field names - how do I make a set of strings out of it.

Solution for this one depends what exactly you have in custom meta:

*

*list with multiple records, each with single field's name?

*1 record with field names saved in columns like Field1__c, Field2__c, Field3__c

*1 record with list of fields stored comma-separated, like Fields__c = 'Name,CloseDate,StageName'
You'll have to do it yourself, query and loop through first one or call String.split(','); on the last one or...


text:
Q: scroll bug of suggest box in gwt I am creating Suggestbox in my gwt project.I used the css trick to add a scrollbar on my suggest popup like below,
.suggestPopupContent{
 height: 183px;
overflow-y: scroll;
text-align                   :    left;
cursor                       :    pointer;
cursor                       :    hand ;

}
it works, but there's a bug : if you use the arrow keys to navigate through choices, the scrolling does not follow.
Please help me to sort out this bug.
Thanks Rahul

A: See this other Question/Answer (https://stackoverflow.com/a/24235088/1357094) for a solution that uses the same CSS you already have, but doesn't have to hack into SuggestBox like @DonX 's Answer here:  It extends SuggestBox instead, and relatively simply.


text:
Q: Runnable in Handler not run when posted from inside a push notification IntentService In my app when I receive a push notification I want to fire a web request to the server to update some data. This is my implementation of IntentService.onHandleIntent(), which is called when I receive a push:
@Override protected void onHandleIntent(Intent intent) {

    final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    // ... notification setup
    notificationManager.notify(Integer.parseInt(intent.getStringExtra("id")), notificationBuilder.build());

    // Web request to the server to update data
    syncData(this);

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    PushNotificationsReceiver.completeWakefulIntent(intent);

}

public static void syncData(final Context content) {
    new Handler().post(new Runnable() {
        @Override public void run() {
            // ... my web request
        }
    });
}

There's no reason in wrapping the request in a Runnable run by an Handler, but the fact is that the runnable is not run. I even checked the return value of post(), and it's true. If I call syncData() from inside an activity, or a fragment, etc, it works as expected, but not in this IntentService. Why is that?
If do this instead, everything works correctly:
public static void syncData(final Context content) {
    // ... my web request
}

A: In an IntentService, onHandleIntent() will be called on a separate thread created by the IntentService. So when you call new Handler(), a handler instance will be created for that new thread. When you post a runnable using that handler, it will be posted on the new thread's handler and thread's onHandleMessage will be called which is implemented by IntentService and it is ignored.
If you modify the above code as below it will work
public static void syncData(final Context content) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override public void run() {
        // ... my web request
    }
});
}

but in the above Runable will be called on main thread where you should not perform network operation


text:
Q: TCP connection reset in linux(strange packet loss) but not on windows It is all good on windows, but on linux when I try to retrieve a specific web page, I get a long wait and then a "connection reset by peer"
Pinging destination IP works fine.
I tried to reduce interface MTU to 1476(found using "ping -c1 -M do -s") and even lower values but it did not solve the problem.
On another linux PC near the destination host, there is no problem, so i suspect some router in the path.
These are wireshark and tshark output:
Linux with connection reset: http://pastebin.com/tpjS5qZc
Windows with no problem: http://pastebin.com/iyN1GDxT
It seems that third packet gets lost in the path to destination host and destination sends back several duplicate ack packets, but i can not see any relevant difference in windows and linux packets.

A: In your capture both servers are setting "Do not fragment bit". This means that both ends are trying to do Path MTU Discovery.
It seems that there is a firewall that blocks ICMP Fragmentation Needed form your Linux server towards the remote server. As a workaround enable MSS clamping with:
iptables -A OUTPUT -p tcp --tcp-flags SYN,RST SYN -j TCPMSS  --clamp-mss-to-pmtu

You can also try to disable P MTU Discovery in Linux:
echo  1  |sudo tee /proc/sys/net/ipv4/ip_no_pmtu_disc

From the iptables man page:

TCPMSS
         This  target allows to alter the MSS value of TCP SYN packets, to control the maximum size for that connection (usually limiting it
         to your outgoing interface's MTU minus 40 for IPv4 or 60 for IPv6, respectively).  Of course, it can only be  used  in  conjunction
         with -p tcp.

   This  target is used to overcome criminally braindead ISPs or servers which block "ICMP Fragmentation Needed" or "ICMPv6 Packet Too
   Big" packets.  The symptoms of this problem are that everything works fine from your Linux firewall/router, but machines behind  it
   can never exchange large packets:
    1) Web browsers connect, then hang with no data received.
    2) Small mail works fine, but large emails hang.
    3) ssh works fine, but scp hangs after initial handshaking.
   Workaround: activate this option and add a rule to your firewall configuration like:

           iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN
                       -j TCPMSS --clamp-mss-to-pmtu

   --set-mss value
          Explicitly  sets  MSS  option  to  specified  value.  If  the  MSS of the packet is already lower than value, it will not be
          increased (from Linux 2.6.25 onwards) to avoid more problems with hosts relying on a proper MSS.

   --clamp-mss-to-pmtu
          Automatically clamp MSS value to (path_MTU - 40 for IPv4; -60 for IPv6).  This may not function as desired where  asymmetric
          routes  with  differing  path MTU exist — the kernel uses the path MTU which it would use to send packets from itself to the
          source and destination IP addresses. Prior to Linux 2.6.25, only the path MTU to the destination IP address  was  considered
          by this option; subsequent kernels also consider the path MTU to the source IP address.

   These options are mutually exclusive.

See: http://lartc.org/howto/lartc.cookbook.mtu-mss.html
Edit: After I've take a closer look on the captures, I've discovered that there is a broken firewall along the path that is filtering all IP packets that use TCP Timestamp option. Just run on the Linux box: echo 0 | sudo tee /proc/sys/net/ipv4/tcp_timestamps


text:
Q: Excel VBA. How to check if a sub is called anywhere in a Workbook (eg what buttons) How do you check where an Excel VBA Sub is called from? It's easy enough to hit CTRL+F to find where in the code it may be called, but suppose there's an obscure hidden button that calls the Sub. How would you know?

A: Kindly install the addin mztools. It has an option Procedure Callers which list down all the places from where the procedure is called.
The below image shows all the procedure callers for procedure a.

A: Even if you use CTRL+F in IDE you won't find the situation when standard form button is set to run that macro on action. Moreover, any of shape within your Workbook could have on action set to your sub. You would then need to check each of it.
But if you need to check such situation during compilation you could use something like:
Debug.Print Application.Caller

If your sub would be started from standard button then you get information Button 1 or shape name if was start from any other shape. Important! You would require error handling procedure if you use that check syntax for situation when your sub is called from other sub.
For other check Santosh idea, yours, and finally you could write some code which search all modules to find your sub and list it.


text:
Q: Nginx PHP MySQL ROR setup on Ubuntu Server How would I go about installing and setting up nginx, PHP, MySQL and RoR on a Ubuntu Server 10.04.2 machine?
I have been through a few tutorials but have never found one which integrates ruby on rails. Is this not possible?
Cheers, Dean

A: Here is a short Tutorial. But nginx is used to proxy and balance the connections to the Mongrel cluster. A real integration of rails in nginx is not possible.
But you can look into the tutorial there is a cool way to set up a Mongrel cluster and proxy the connections with nginx this is the common way i know and what i use.


text:
Q: Как создать массив из схожих ключей с индексами в квадратных скобках? В post-запросе приходит примерно следующее:
[question-preptime-2] => 110
[question-anstime-2] => 33
[question-subquest-2[1]] => cv
[question-subquest-2[2]] => sdf
[question-subquest-2[3]] => sdfsd
[question-subquest-2[4]] => 345dh

Как из ключей содержащих question-subquest создать отдельный массив, где ключ будет цифра в квадратных сбоках, т.е. в итоге получить:
[question-subquest-2] => Array
        (
            [1] => cv
            [2] => sdf
            [3] => sdfsd
            [4] => 345dh
        )

A: Само собой $post поменять на $_POST.
<?php
$post = [ 'question-preptime-2' => 110,
          'question-anstime-2' => 33,
          'question-subquest-2[1]' => 'cv',
          'question-subquest-2[2]' => 'sdf',
          'question-subquest-2[3]' => 'sdfsd',
          'question-subquest-2[4]' => '345dh'
        ];

$outArray = [];

foreach( $post as $key => $value ) {
    preg_match_all("/(\S+)\[(\d+)\]$/", $key, $matches);
    if ( is_array( $matches ) && count( $matches ) >= 3 && is_array( $matches[1] ) && count( $matches[1] ) > 0 && is_array( $matches[2] ) && count( $matches[2] ) > 0 ) {
        if ( !isset( $outArray[ trim( $matches[1][0] ) ] ) )  {
            $outArray[ trim( $matches[1][0] ) ] = [];
        }
        $outArray[ trim( $matches[1][0] ) ][ trim( $matches[2][0] ) ] = $value;
    }
}

var_dump( $outArray );

Результат:
array(1) {'question-subquest-2' => array(4) { [1] => "cv",
                                              [2] => "sdf",
                                              [3] => "sdfsd",
                                              [4] => "345dh"
                                            }
}


text:
Q: Finite-dimensional Hilbert $C^*$-modules Does there exist a classification, or characterization, of finite-dimensional Hilbert $C^*$-modules? More generally, does there exist a characterization of countable direct sums of finite-dimensional Hilbert $C^*$-modules
Edit: By finite dimensional I mean that the $C^*$-module is finite dimensional as a vector space.

A: As a vector space, okay.  Let $A$ be a C*-algebra and $E$ a Hilbert module over $A$ which is finite dimensional as a vector space. Then $A$ acts by left multiplication on $E$, i.e., we have a bounded homomorphism from $A$ into $B(E) \cong M_n$. Letting $I$ be the kernel of this homomorphism, this shows that $A$ has a finite codimension closed ideal $I$ (which is automatically self-adjoint) and $E$ is a Hilbert module over $A/I$ (exercise).
So we have to classify finite dimensional Hilbert modules over finite dimensional C*-algebras. Any finite dimensional C*-algebra is a direct sum of matrix algebras, and any Hilbert module over such a direct sum decomposes as a direct sum of Hilbert modules over the summand matrix algebras. So we only have to classify the finite dimensional Hilbert modules over $M_n$. But again, left multiplication gives a homomorphism from $M_n$ into $B(E)$, and this $*$-homomorphism must be unital (exercise), which by the answer to this question means that $E \cong \mathbb{C}^n\otimes \mathbb{C}^k$ for some $k$, with the action being $a(v\otimes w) = av\otimes w$. So $E$ is a direct sum of finitely many copies of $\mathbb{C}^n$ as a module over $M_n$ in the natural way. The inner product is described in Matthew's answer.

A: Let $E$ be a Hilbert $C^*$-module over a $C^\ast$-algebra $A$.  (I'll use the right module convention, which basically just makes life difficult for myself.)  Then $I$, the closure of $\newcommand{\lin}{\operatorname{lin}} \lin \{ (x|y):x,t\in E \}$ is a (two-sided) closed ideal in $A$.  (Because, for example $(x|y)a = (x|y\cdot a)\in I$).  Recall that $E$ is full when $A=I$.
Now suppose that $E$ is a finite-dimensional vector space.  Then $\lin \{ (x|y):x,y\in E \}$ is finite-dimensional, so equals $I$.  As $I$ is itself a $C^\ast$-algebra, and is finite-dimensional, it in particular has a unit $e$.  Then $I = eA = Ae = AeA$ and $A\rightarrow I, a\mapsto ae = eae = ea$ is a $*$-homomorphism which is the identity on $I$.  It follows that $A \cong I \oplus B$ for some $C^\ast$-algebra $B$.
We know that $E = E\cdot I$ and so $x = x\cdot e$ for each $x\in E$.  We can hence treat $E$ is a full Hilbert $C^\ast$-module over $I$.  We now use that $I$ is a direct sum of matrix algebras, say $I = \sum_{k=1}^N M_{n_k}$.  Let $1_k$ be the unit of $M_{n_k}$ so $x = x\cdot e = x\cdot(\sum 1_k) = \sum_k x\cdot 1_k$ for $x\in E$, and so $E = \sum_{k=1}^N E_k$ where $E_k = E\cdot 1_k$ is a full module over $M_{n_k}$.
Finally, we classify modules $F$ over $M_n$.  One can show (I do not know a fast way to show this) that if $F$ is a finite-dimensional vector space with a (left) action of $M_n$ then $F \cong \mathbb C^n \otimes F'$ where $M_n$ acts on $\mathbb C^n$ in the usual way (treat $\mathbb C^n$ as column vectors) and the action on $F$ is as $a\otimes 1$.  As $F$ is a right module over $M_n$, we have that $(\xi\otimes x')\cdot a = a^\top\xi \otimes x'$ where $a^\top$ is the transpose of $a\in M_n$.  Let $\delta=\delta_1$ be the first unit vector in the standard basis of $\mathbb C^n$, so $a^\top\delta\otimes x'$ is a typical elementary vector in $F$.
Now consider the $M_n$-valued inner-product on $F$ which is
$$
(a^\top\delta\otimes x'|b^\top\delta\otimes y') = a^\ast (\delta\otimes x'|
\delta\otimes y') b = a^\ast \theta(x'|y')b
$$
say, for some sesquilinear $\theta:F\times F\rightarrow M_n$.  However, notice that if $a^\top\delta=0$ or $b^\top\delta=0$ then $a^*\theta(x'|y')b=0$ for any $x',y'$.  Let $\theta_{\xi,\eta}\in M_n$ be the rank-one operator $\alpha\mapsto \xi(\eta|\alpha)$.  Further let $J:\mathbb C^n\rightarrow \mathbb C^n$ be the anti-linear operator given by pointwise complex conjugation.  Then $a^\top = Ja^\ast J$.  Thus, if $(\xi|\delta)=0$ or $(\eta|\delta)=0$, then $\theta_{\xi,\alpha}^\ast \theta(x',y') \theta_{\eta,\beta}=0$ for any $\alpha,\beta$, so $(\xi|\theta(x',y')\eta)=0$.  It follows that $\theta(x',y') \in \mathbb C \theta_{\delta,\delta}$.  So, there is a Hilbert space structure on $F'$ with $\theta(x',y') = (x'|y') \theta_{\delta,\delta}$.  We conclude that the $M_n$-valued inner-product on $F=\mathbb C^n\otimes F'$ is
$$ (\xi\otimes x'|\eta\otimes y') = (x'|y') \theta_{\eta,\xi} \in M_n. $$
So, this completely answers the case of a finite-dimensional module over $A$.  There was also the question of countable direct sums of such things.  I'm not sure what is meant here.  If you know that $E$ is a countable direct sum $E\cong \oplus E_n$ each $E_n$ finite-dimensional, then you can piece together the structure for each $E_n$.  However, if you want to know which $E$ can occur in this way, then that seems more complicated.


text:
Q: Backoff strategy for producers/consumers when a lock-free queue is full/empty? Assume a producer-consumer scenario. I have used a lock-free implementation of a fixed-capacity queue, so that:

*

*The number of items that can be held in the queue is limited.

*Producers/consumers can push/pop items to/from the queue directly without holding any lock.

Now, I'm considering how to synchronize the producers and consumers, so that producers are not busy try-pushing to a full queue, and consumers are not busy try-popping from an empty queue.
I thought about condition variable at first. But it seems to destroy the whole purpose of using a lock-free queue implementation.
Is polling (with interval) the only sensible way to go with a lock-free queue?


text:
Q: How to get users email from MobileServiceClient? i am using:
private MobileServiceClient mClient;

    private void authenticate() {

        mClient.login("windowsazureactivedirectory", "Scheme", LOGIN_REQUEST_CODE);
    }

I just can use getUserId()

A: You can send an authenticated GET request to https://{your-appname}.azurewebsites.net/.auth/me endpoint for retrieving more detailed information about the logged user. You could leverage invokeApi for retrieving the json data as follows:

You need to parse the response and retrieve user's email under user_claims.


text:
Q: call converter in XAML if property of a object in the observable collection changes I have a converter that accepts an ObservableCollection as a parameter, and I'd like to re-evaluate it whenever a specific property on any item in the collection changes
For example: lets say I have bound a label to a collection of Person objects with a converter. The job of the converter is to count the number of Persons in the list that are female, and return "valid" for 1 female or "accepted" for 2. I'd like the converter to get called again anytime the Gender property on any Person object gets changed.
How can I accomplish this?

A: That's a classic problem you end up having if you play around WPF long enough.
I've tried various solutions, but the one that works best is to use a BindingList like so:
public class WorldViewModel : INotifyPropertyChanged
{
   private BindingList<Person> m_People;
   public BindingList<Person> People
   {
      get { return m_People; }
      set
      {
         if(value != m_People)
         {
            m_People = value;
            if(m_People != null)
            {
               m_People.ListChanged += delegate(object sender, ListChangedEventArgs args)
               {
                  OnPeopleListChanged(this);
               };
            }
            RaisePropertyChanged("People");
         }
      }
   }

   private static void OnPeopleListChanged(WorldViewModel vm)
   {
      vm.RaisePropertyChanged("People");
   }

   public event PropertyChangedEventHandler PropertyChanged;
   void RaisePropertyChanged(String prop)
   {
      PropertyChangedEventHandler handler = this.PropertyChanged;
      if (handler != null)
      {
          handler(this, new PropertyChangedEventArgs(prop));
      }
   }
}

Then just bind to the People collection like you would do with an ObservableCollection, except bindings will be re-evaluated when any property in its items change.
Also, please note that OnPeopleListChanged is static, so no memory leaks.
And Person should implement INotifyPropertyChanged.

A: A CollectionChanged event is only thrown when an item is added or removed from the collection (not when an item in the collection is changed).  So the converter is not called when an item is changed.
One option:
In the Gender Property Set include logic to evaluate the collection and set a string Property that you bind the label to.
Wrote generic version of the answer from Baboon
public class ObservalbeList<T>: INotifyPropertyChanged
{
    private BindingList<T> ts = new BindingList<T>();

    public event PropertyChangedEventHandler PropertyChanged;

    // This method is called by the Set accessor of each property.
    // The CallerMemberName attribute that is applied to the optional propertyName
    // parameter causes the property name of the caller to be substituted as an argument.
    private void NotifyPropertyChanged( String propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public BindingList<T> Ts
    {
        get { return ts; }
        set
        {
            if (value != ts)
            {
                Ts = value;
                if (Ts != null)
                {
                    ts.ListChanged += delegate(object sender, ListChangedEventArgs args)
                    {
                        OnListChanged(this);
                    };
                }
                NotifyPropertyChanged("Ts");
            }
        }
    }

    private static void OnListChanged(ObservalbeList<T> vm)
    {
        vm.NotifyPropertyChanged("Ts");
    }

    public ObservalbeList()
    {
        ts.ListChanged += delegate(object sender, ListChangedEventArgs args)
        {
            OnListChanged(this);
        };
    }
}


text:
Q: Construct a (non-measurable) function $f: R\to R$ with the following property any function $g:R \to R$ such that $|g(x)-f(x)|<1$ for all $x \in R$ is non-measurable.
I am thinking about the function $f$ being $f=2\chi_N$, $N$ is a non-measurable set in [0,1]. Thus, $m(x\in R, 1<g(x)<3)=N$. I did it this way in the exam, but I am not sure whether it is right or not...If it is wrong, could you please construct an example function? Thank you!

A: Your construction is correct. Let $U=\{x\in \mathbb{R}|g(x)>1\}$. $U$ is equal to $N$ since if $x\in N$, then by definition $f(x)=2$, so since $|2-g(x)|<1$ we have $g(x)>1$, and if $x\notin N$ then $f(x)=0$, so $|g(x)-0|<1$ so $g(x)<1$. $U$ is the inverse image of the measurable set $(1,\infty)$ under $g$, so $g$ is not measurable.


text:
Q: Binomial histogram with ggplot2 function Suppose I have a data set consisting of values of a statistic which theoretically follows Binomial distribution with some specified parameter (say size=30, prob=0.5). Suppose my dataset is represented by r which is given below:-
 dput(r)
c(16L, 7L, 12L, 19L, 15L, 11L, 13L, 16L, 14L, 15L, 11L, 12L,
18L, 18L, 12L, 14L, 13L, 13L, 18L, 20L, 13L, 19L, 14L, 17L, 16L,
19L, 14L, 12L, 14L, 12L, 16L, 13L, 16L, 15L, 18L, 17L, 12L, 16L,
15L, 14L, 16L, 11L, 13L, 12L, 14L, 17L, 17L, 18L, 15L, 18L, 15L,
13L, 12L, 13L, 16L, 13L, 13L, 12L, 18L, 11L, 16L, 16L, 13L, 18L,
15L, 9L, 14L, 17L, 14L, 11L, 17L, 15L, 13L, 14L, 18L, 16L, 11L,
13L, 13L, 11L, 21L, 11L, 17L, 7L, 15L, 15L, 16L, 16L, 13L, 10L,
12L, 17L, 13L, 14L, 12L, 19L, 12L, 12L, 14L, 16L)

I want to see whether this observations are from binomial distribution with size=30, and prob=0.5. I want to do these using histogram. I tried the following codes :-
x<-data.frame(obs=dbinom(0:50, 50, 0.5))
y<-data.frame(obs=r)
x$type<-'bin1'
y$type<-'bin2'
data<-rbind(x,y)
library(devtools)
library(easyGgplot2)
ggplot2.histogram(data=data, xName='obs',
                  groupName='type', legendPosition="top",
                  alpha=0.2 )

This is the plot I get. But I think I have done mistake, because the histogram for x should have been symmetric, but it shows only one bar. Could anyone tell me where I have mistaken?

I tried to use the following references while writing the codes:- 1)http://www.sthda.com/english/wiki/ggplot2-histogram-easy-histogram-graph-with-ggplot2-r-package
2)How to plot two histograms together in R?

A: I assume you rather wanted to use rbinom - so, would this be closer to the result you want to achieve?
x<-data.frame(obs=rbinom(30, 30, 0.5))
y<-data.frame(obs=r)
x$type<-'bin1'
y$type<-'bin2'
data<-rbind(x,y)

ggplot(data, aes(obs, fill = type)) + geom_histogram(position = "dodge", alpha = 0.8)


text:
Q: How to add new field in result query Laravel So I have  model request:
$genres = Genre::all();

It gives me reuslt object:
"id" => 32
"name" => "Rock"
"position" => null
"updated_at" => "2017-02-07 06:16:46"
"created_at" => "2017-02-07 06:16:46"

How can I add new element list = [] in this object?

A: You can use map(), refer to this post.
->map(function ($item) {
  $item['test'] = ['123', '345'];
  return $item;
});


text:
Q: Setting value on array, it is not updating child component - Angular I'm trying to prevent triplicate values and handling the logic in parent component. However, it successfully prevents 3rd value once, but not subsequent times. The problem is when setting value on array, it is not updating child component. I'm trying to understand why it is not behaving the same way on subsequent times...
Reproduces here

A: The problem is that there is no change in the Input property the second time onwards.
You are reassiging the same value (i.e., empty string literal oValues[oNumber] = '';) to the property in your array.
e.g. for oValues[3]

First change: Previous value = '2', new value = ' '

Here Angular change detection detects the change on the Input property.

Second change: Previous value = ' ', New value = ' '

Here Angular change detection does not detect a change in the value of the Input property.
So basically Angular change detection triggers only if it finds a change in the Input property's value.


text:
Q: Lock screen option disappeared from Debian 9 and can't lock the OS I have tried the answers to this question, Ubuntu 17.10 Screen lock not working and grey and tried installing sudo apt-get install gnome-screensaver.
However, the problem is that I can't lock the computer anyway since there isn't any lock option in the menu nor does gnome-screensaver-command -l work properly.
It is the exact same problem discussed in this thread on Reddit, Lock screen doesn't work.

A: Once my "Lock" menu item disappeared and at the same moment I couldn't lock the screen either. Then I checked the Gnome settings:
gsettings list-recursively | grep lockdown

and I found that somehow option "disable-lock-screen" was set to true, which hides the menu item and prevents the screen from locking. Then I set it to false again:
gsettings set org.gnome.desktop.lockdown disable-lock-screen 'false'

and the "Lock" item is immediately returned and Super + L starts working again.

A: The problem was with the display manager. I was using sddm and it was resolved after switching to gdm3 package.
You can see the current display manager using this command:
cat /etc/X11/default-display-manager

For switching display manager to gdm3 you can simply run the following commands and select it as the default display manager:
sudo apt-get install gdm3
sudo dpkg-reconfigure gdm3

After all it is needed to rebooting the system.
Now you can lock the system either with the lock button or with the following command:
sudo apt-get install gnome-screensaver
gnome-screensaver-command -l

P.S I have read somewhere that someone had the same issue with lightdm display manager package.


text:
Q: Conclusively Detect a Process losing Focus How do you conclusively detect when the whole application (all process HWND's and child HWND's) have lost focus. I need to know this so I can hide my main HWND. I cant just make the main HWND handle WM_KILLFOCUS because child windows could have the focus prior to losing it (am I making sense?).
I could subclass every child's window procedure and handle WM_KILLFOCUS but that seems like overkill. And a hook also seems like overkill - seems like you only use hooks when completely necessary otherwise your application gets flagged as suspicious.


text:
Q: html2canvas plugin not capturing image This question has been asked before but I can't seem to get it to work. Hopefully you can see the error of my ways. The code below will capture the text and gray div but not the image.

THIS IS A TEXT TEST

$("#myBtn").click ->
    html2canvas $("#snapshot"),
      background: "red"
      onrendered: (canvas) ->
        imgSrc = canvas.toDataURL()
        popup = window.open(imgSrc)
        return

    return

<button id="myBtn">Click Me</button>

Here's the fiddle
jsfiddle

A: OK, well I figured out what the problem is. html2canvas can't capture an image if it's not from the same origin. My images are coming from a CDN.
html2canvas docs