What is a method group in C#?

Question: I have often encountered an error such as "cannot convert from 'method group' to 'string'" in cases like:
var list = new List<string>();
// ... snip
list.Add(someObject.ToString);

of course there was a typo in the last line because I forgot the invocation parentheses after ToString. The correct form would be:
var list = new List<string>();
// ... snip
list.Add(someObject.ToString()); // <- notice the parentheses

However I came to wonder what is a method group. Google isn't much of a help nor MSDN.
Comment: Section 7.1 of the C# 3.0 specification defines "method group".
Comment: I read this error now as *you missed the brackets off when calling a method*.
Comment: If you had had a list of an appropriate delegate type, such as `var list = new List>();`, then the method group would have been usable, and `list.Add(someObject.ToString);` would have worked.
Answer: A method group is the name for a set of methods (that might be just one) - i.e. in theory the ToString method may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc - hence ToString by itself is a "method group".
It can usually convert a method group to a (typed) delegate by using overload resolution - but not to a string etc; it doesn't make sense.
Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.
Comment: It is purely a compiler term for "I know what the method name is, but I don't know the signature"; it has no existence at runtime. AFAIK, the only use of a method-group *by itself* (no brackets etc) is during delegate construction.
Comment: ECMA 334v4 §14.1: A method group can be used in an invocation-expression (§14.5.5), used in a delegate-creation-expression (§188.8.131.52), or implicitly converted to a compatible delegate type. In any other context, an expression classified as a method group causes a compile-time error.
Comment: What would be typical uses of a method group? Since (so I understand) it has the same name the parameter count and/or types will differ. So you cannot invoke more than one method from the method group using the group.
Comment: Covariance and contravariance support for method groups allows for matching method signatures with delegate types. This enables you to assign to delegates not only methods that have matching signatures, but also methods that return more derived types (covariance) or that accept parameters that have less derived types (contravariance) than that specified by the delegate type. For more information, see Variance in Delegates (C#) and Using Variance in Delegates (C#).
Comment: 100% of the time when I get this error, I forgot the brackets on the method call cause I thought it was a property. An error like "did you forget the ()" would actually be useful 99% of the time lol
Answer: Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).
So, for example, I have:
private string DoSomethingToMyString(string input)
{
    // blah
}

Instead of explicitly stating the variable to be used like this:
public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}

I can just omit the name of the var:
public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}

Comment: A ReSharper recommendation is what led me to search for method group.  This is what ReSharper ended up doing to one of my linq expressions.
Comment: @a_hardin: ReSharper FTW! I learned a lot about LINQ thanks to Resharper.
Comment: Reminds me of `return flag == true ? true : false` (facepalm).
Comment: The compiler optimizes nothing. Using ILDASM, you see that the explicit version creates a anonymous method (the lambda implementation) and passes it to Select(). The implicit version passes DoSomethingToMyString directly.
Comment: The "more explicit" version is only making an essentially useless wrapper method. The anonymous wrapper method and DoSomethingToMyString both take a string and return a string. The "str => [...](str)" characters are just cruft which the compiler hopefully optimizes away.
Comment: According to this test (http://vibrantcode.com/2013/02/19/lambdas-vs-method-groups/) lambda appears to be faster, even though it creates an extra wrapper method.
Comment: The [relevant overload](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select#System_Linq_Enumerable_Select__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__) of `Select` wants a delegate of type `Func` for its `selector` argument. This is exactly what method groups can be used for: Conversion into (compatible) delegate types.
Comment: @ErikE, updated link:
[Wayback Archive - vibrantcode.com/2013/02/19/lambdas-vs-method-groups](https://web.archive.org/web/20190301033146/http://vibrantcode.com/2013/02/19/lambdas-vs-method-groups/)
Answer: You can cast a method group into a delegate.
The delegate signature selects 1 method out of the group.
This example picks the ToString() overload which takes a string parameter:
Func<string,string> fn = 123.ToString;
Console.WriteLine(fn("00000000"));

This example picks the ToString() overload which takes no parameters:
Func<string> fn = 123.ToString;
Console.WriteLine(fn);

Answer: The first result in your MSDN search said:

The method group identifies the one
  method to invoke or the set of
  overloaded methods from which to
  choose a specific method to invoke

my understanding is that basically because when you just write someInteger.ToString, it may refer to:
Int32.ToString(IFormatProvider)

or it can refer to:
Int32.ToString()

so it is called a method group.
Answer: The ToString function has many overloads - the method group would be the group consisting of all the different overloads for that function.
Comment: Yes, and the point is that a method group is a compile-time construct. The compiler chooses one method overload according to the context where the message group is used. For example: you cannot write "var x = Foo;" (where Foo is a method group), the compiler rejects this even if there is only one overload.

What is a method group in C#?


$_SESSION['fb_id'] lost while redirecting to a subdomain uri, after a facebook connect

Question: I have several subdomains websites, and I wish to be facebook connected on each.
I've created my fb app for the main domain, and it works for it.
In each subdomains I use this link to connect (wrote by an ajax calling) :
<?php
echo "
    Connect with Facebook
    ";
?>

My fbConnect.php
<?php
    header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); // Hack IE for POST params...
    header("Cache-Control: no-cache");
    header("Pragma: no-cache");

    session_set_cookie_params(0, '/', '.mydomain.com', false); // If session is lost with subdomains...
    session_start();
    require('/home/....../facebook.php');

    $facebook = new Facebook(array(
    'appId' => 'myid',// changed for the example
    'secret' => 'mysecret', // same
    'cookie' => true,
    ));

    $user = null;

    $loginUrl=$facebook->getLoginUrl(
            array(
                  'canvas'    => 0,
                'scope'         => 'email,publish_stream,user_location'
            )
    );
    $logoutUrl  = $facebook->getLogoutUrl();

    $user=$facebook->getUser();

    if(!$user) echo "";

    if ($user) {
        echo "Ok";
        $user_profile = $facebook->api('/me');
        $userInfo = $facebook->api("/$user");
        $_SESSION['fb_id']=$userInfo['id'];
       // Some stuff...
       echo "";
    }
?>

Scopes, connections and redirections are working, but I can't get back the $_SESSION['fb_id'] in the $_GET['ref'] page... however the session_id() is the same !
Comment: Have you tried setting the php.ini before session_start with `ini_set("session.cookie_domain", ".yourDomain.com");`
Comment: Thanks, that was a good solution for the session, but there was another problem with the ref var, not supported in the redirect uri...
Answer: Finaly, there was some mistakes :
1. Sessions
They didn't followed in subdomains, so the trick was to change the php.ini or add ini_set("session.cookie_domain", ".myDomain.com"); (thanks @Tommy Crush)
2. redirect_uri
It seems that, in my case, it was not possible to send vars inside the redirect_uri=http://www.myDomain.com?var1=123&var2=456...
3. API use
I had to read the new beginner panel of the GRAPH API, and I was surprised by the number of changes...
I finaly used the following :
In each subdomains
// Simple link to the connection page
echo "Connect with FB";
// Record the current page whitch called this ajax
$_SESSION['connexion_ref']=$_SERVER['HTTP_REFERER'];

My new fbConnect.php
ini_set("session.cookie_domain", ".myDomain.com");
session_start();

$app_id = "myappid";
$app_secret = "myappsecret";
$my_url = "http://www.mydomain.com/fbConnect.php";

$code = $_REQUEST["code"];

if(empty($code)) {
 $_SESSION['state'] = md5(uniqid(rand(), TRUE)); // CSRF protection
 $dialog_url = "https://www.facebook.com/dialog/oauth?client_id="
   . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
   . $_SESSION['state']. "&scope=email,publish_stream,status_update,offline_access";

 echo("");
}

if($_SESSION['state'] && ($_SESSION['state'] === $_REQUEST['state']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
     . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
     . "&client_secret=" . $app_secret . "&code=" . $code;

    $response = file_get_contents($token_url);
    $params = null;
    parse_str($response, $params);

    $_SESSION['access_token'] = $params['access_token'];

    $graph_url = "https://graph.facebook.com/me?access_token="
     . $params['access_token'];

    $user = json_decode(file_get_contents($graph_url));
    //var_dump($user);

    $_SESSION['id_fb']=$user->id;
   // Some stuff
    // Then redirect to the subdomain page of connection
   echo "";
}

Now it works like a charm.
Comment: You should be able to pass vars in the `redirect_uri` if you encode the entire url first.
Comment: Thanks, but à session var is better in my case.


Is E(Y|X) a function of Y?

Question: I'm slightly confused by a question I have encountered, it's a true or false question stating:
'The expression $E_{(Y|X)} (Y|X)$ is a function of $Y$.'
My automatic instinct was, well yes of course it is.
Assuming that the variables are continuous, I think formally (please correct me if I'm wrong as I'm still getting used to the notation):
$$E_{(Y|X)} (Y|X) = \int_{-\infty}^{\infty} y \ g(y|x) \ dy$$
where
$$g(y|x) =\frac {f_{x,y}(x,y)}{\int_{-\infty}^{\infty}f_{x,y}(x,y)dy}$$
Which I think demonstrates it is a function of $Y$, however the answer was 'false'. Have I made a mistake interpreting the notation? Or is it because the expression is a function of both $Y$ and $X$, something which I was aware of however misinterpreted the question.
**On second thought I just realised I'm doing prep work for econometrics, is it because $Y$ is the dependent variable, $X$ the explanatory and therefore $ Y=\mu(X)$ for some function $\mu$.
Any guidance will be greatly appreciated.
Comment: @Neznajka, to make you comment useful you should provide some explanation, not just a plain, undefended statement.
Comment: Hint: Is $1/2 = \int_0^1 x dx$ a function of x?
Comment: @Student001 - No it's a constant, 1/2? Okay I think I understand, as you've inegrated over y, we're left with just a function of x, as the ys effectively disappear out of the expression?
Comment: $E_{Y|X}(Y|X)$ is a function of $X$. The conditional density function $g(y|x)$ depends on both $y$ and $x$ but then you integrate $yg(y|x)$ over $y$ when taking the expectation.
Comment: @Richard Hardy . I agree. I expanded my comment.
Comment: @Neznajka Thanks for the input greatly appreciated.
Comment: @Nik-D: yes, your understanding is correct.
Comment: The $Y$ (and all notion of $y$) will vanish when the integral is evaluated - however this is a technicality. If you consider expectation as a function (which I try to) it depends on both $X$ and $Y$ - if you're doing it numerically also depends on both. Please don't remember this as some sort of "fact"
Answer: $$g_{Y\mid X = x}(y\mid x) =\frac {f_{X,Y}(x,y)}{\int_{-\infty}^{\infty}f_{X,Y}(x,y)dy} = \frac {f_{X,Y}(x,y)}{f_{X}(x)}$$ and so
$$E[Y\mid X = x] = \int_{-\infty}^{\infty} y g_{Y\mid X = x}(y\mid x) \ dy
= \frac{1}{f_{X}(x)} \int_{-\infty}^{\infty} y f_{X,Y}(x,y) \ dy = h(x)\tag{1}$$
Thus, the number $E[Y\mid X = x]$ depends on your choice of $x$.
It does not depend on $y$ at all; $y$ is just a variable of
integration and disappears when we plug in the limits on that
integral in $(1)$.
We can think of this number as the realization or sample of
a random variable $Z$ where $Z$ has value $E[Y\mid X = x]$ whenever
it so happens that $X$ has value $x$. So, we can think of the random
variable $Z = E[Y \mid X]$ as a function $h(X)$ of $X$
since if we sample
$X$ we can figure out what the sample of $Z$ must be.  $Z$ is not
a function of $Y$ at all!
The law of iterated expectation says that the expected value
of $Z = h(X)$, which is a function of $X$ and not at all of $Y$, quite
by magic, happens to equal $E[Y]$, the expected value of $Y$,
that is,
$$E[Z] = E[h(X)] = E\left[\, E[Y\mid X]\,\right] = E[Y].$$
Comment: @ Nik-D You are correct: it should be $f_{X,Y}(x,y)$ and not $g$ at all.  I have fixed the error.
Comment: Thanks very much!
Quick question, is there a mistype in your answer, on the second line in the third expression,  once factored out $\frac {1}{f_x(x)}$ is there still meant to be the conditional probability $g_{y|x}$ or is it meant to be just the joint distribution $f_{x,y}(x,y)$
Answer: @Neznajka pointed out the formal basis for why $E[Y|X]$ is a function of $X$, not $Y$. At a more abstract level, you can also see this by considering that $E[Y|X]$ takes as input a value of $X$ and maps it to a conditional expected value of $Y$. Therefore, you can write $E[Y|X]$ as a plain old univariate function $f: \mathbb{R} \to \mathbb{R}, x\mapsto E[Y|X=x]$.
So, since the distribution of $Y$ remains fixed, then it has to be a function of $X$.

Is E(Y|X) a function of Y?


How to create a separate gemset in a Middleman project?

Question: Using rbenv for managing my rubies, and wondering what the preferred way was to have a separate gemset for each of my Middleman projects?
Answer: User rbenv-gemset. It's designed to work with rbenv, and you can do everything you need to do gemset-wise.


overloading operators == and != : compiler moans ambiguity

Question: I have the following code:
bool operator==(const Inc::CReminderItem& Item1, const Inc::CReminderItem& Item2)
{
    bool bDate = false, bDesc = false, bInfo = false, bWeekday = false;

    if(Item1.m_Date == Item2.m_Date)
        bDate = true;
    if(Item1.m_strDescription == Item2.m_strDescription)
        bDesc = true;
    if(Item1.m_strInfoShort == Item2.m_strInfoShort)
        bInfo = true;
    if(Item1.m_nWeekday == Item2.m_nWeekday)
        bWeekday = true;

    return(bDate && bDesc && bInfo && bWeekday);
}

bool operator!=(const Inc::CReminderItem& Item1, const Inc::CReminderItem& Item2)
{
    return !(Item1 == Item2);    // <<--- ambiguous here!
}

both operators are declared as friend operators in the class.
the error is:

error C2593: 'operator ==' is
  ambiguous

I am not sure, why it is ambiguous O_o and how to fix this.
Any help is greatly appreciated:)
Comment: The compiler should tell you something like *possible candidates are...*. Otherwise, maybe there exists a member-function, or you have some implicit conversions for `CReminderItem`?
Comment: Does it say which are the possible candidates which are causing ambiguity?
Comment: there are neither possible candidates, nor should there be any imlicit conversions (visual studio 2010)
Answer: First, if it is "ambiguous", I would expect other operator== to be
present somewhere.  But it's hard to say what any particular compiler is
really trying to tell you with it's error messages.
Second, you really don't show enough code for anyone to say what is
wrong.  There are a number of possible errors: the class where the
friend is declared and these definitions are in different namespaces,
the signature of the friend is subtly different, etc.  If Inc is
a namespace, these operators must be in Inc as well.  Otherwise,
you've declared an operator== in Inc in the friend declaration, and
an operator== in global namespace here.  Both are considered, which
results in an ambiguity.
(The way I usually handle this is to define a member function,
isEqual, and have both operator== and operator!= call it.  That
way, there's no need for the friend declaration.)
Answer: Maybe you have defined a operator== within the class scope like
class CReminderItem {
public:
    bool operator==(CReminderItem const&) const;
};

That is ambiguous with the global operator overload.
Comment: -o - my fault. a declaration is enough for compile to moan such an error. I'm wondering why compile consider that as ambiguous, not redefinition.
Comment: Because `bool operator==(CReminderItem const&) const` is not the same as `bool CReminderItem::operator==(CReminderItem const&) const`?


Pegar retorno de autocomplete e colocar em inputs diferentes

Question: Tenho o seguinte script

Que pega o retorno daqui:
$q = strtolower($_GET["q"]);
if (!$q) return;

list($resultados,$quantidade) = $select->selectTable('f_tb_empresas','id_empresa,nm_empresa',NULL,"nm_empresa LIKE '%".$q."%'",NULL);

foreach ($resultados as $row) {
    $linha['value'] = $row['nm_empresa'];
    $linha['id'] = $row['id_empresa'];

}

echo json_encode($linha);

E o resultado vem para o input:
<input type="text" name="course" id="course" />

O resultado vem assim: {"value":"Alameda dos anjos","id":"39"}
, mas queria que o id fosse para um input e o value para outro.
Como faço isso com JQuery?
Obrigada
Comment: o valor de $q está sendo passado diretamente para a query sem tratamento antes? >.<
Comment: @RenatoTavares por enquanto sim
Comment: Onde está o JS que retorna o JSON ?
Comment: @TaoPaiPai Essa é minha dúvida, como retorno esse valor? porque da forma como está no código o source vai direto pro input course
Comment: Esse script que tem a função `autocomplete`, tem o LINK ?
Comment: `
` @TaoPaiPai
Comment: Sim, mas você tem o LINK da documentação desse `jquery.autocomplete.js` ? Se não tiver, tudo bem. Só me explica uma coisa... você disse que quer o `value` em um `input` e o `id` em outro `input`. Em qual momento que você quer isso ? Quando retorna os dados ou quando você escolhe uma opção ? Caso seja a primeira opção não tem que ser os dois no mesmo `input` ?
Comment: @TaoPaiPai quando eu escolho uma opção, gostaria que o um input recebesse o value e o outro o id
Comment: Entendi, para isso você tem que ver os elementos que ele gera embaixo do `input`. Abre o Inspect Element do Chrome e digita algo no campo para rodar o `autocomplete`. No resultado que aparecer clique com o botão direito em cima de um resultado e vai em Inspecionar Elemento. Coloca um print no seu post do que aparece.
Comment: @TaoPaiPai link da imagem: (https://drive.google.com/file/d/0BwH8KrvYWlojV3JSbkN3d2pHbU0/view?usp=sharing)
Answer: Recomendo usar o jQuery UI, pois esse arquivo jquery.autocomplete.js é uma versão desatualizada da função.
Você pode conseguir os valores separados seguindo este exemplo:
$("#course").autocomplete("teste1.php", {
    width: 260,
    matchContains: true,
    select: function( event, ui ) {
       $( "#campoNome" ).val( ui.item.label );
       $( "#campoValor" ).val( ui.item.value );
    }
});

Dê uma olhada na documentação:
https://jqueryui.com/autocomplete/#custom-data


How can I use Puppet to Enforce Local Group Membership?

Question: Cross posting this from Ask@PuppetLabs. (There simply isn't enough traffic there.)
I've seen a number of examples for adding users to %wheel with Augeas. These are all variations of the same thing; inserting a user node at the end.

Quick Tip: Add users to a group with augeas
How to manage configurations in Linux with Puppet and Augeas
Puppet Group Management Module

What I need to do is also remove users that are added outside of configuration management. For Puppet to manage the group, only users defined in my Puppet class should be present and any others removed.
Seems like exec'ing a simple Sed command would be much easier, but so many people say to try to stay away from exec. Is it such a bad solution in this case?
Answer: Defining wheel users this way causes them to be added, but if you remove jane from the class, she will not be removed from the wheel group on the next Puppet run.
class wheel {
  augeas { "wheelgroup":
    context => "/files/etc/group/wheel",
    changes => [
      'set user[1] bob',
      'set user[2] jane',
    ]
  }
}

The only way I have found around this is to purge the wheel group and re-add them each time.
class wheel {
  augeas { "wheelgroup":
    context => "/files/etc/group/wheel",
    changes => [
      'rm user',
      'set user[1] bob',
      'set user[2] jane',
    ]
  }
}

I considered an onlyif to match my defined users to prevent this from running on each Puppet run. However, this is also the only way to remove users added outside of Puppet to ensure that %wheel is managed solely by Puppet.
This solution also doesn't lend well to parametrization for reuse.
Comment: Augeas manipulates a tree representation of the file, not the file itself.  If the tree remains unchanged the file is left unchanged so removing nodes and then re-inserting them isn't so bad.
Comment: The downside is that it still takes about 10x longer to execute and doesn't lend well to parametrization.
Comment: @AaronCopley It shouldn't be slow, unless you're using Puppet < 2.7.19. As for parametrization, I'd encourage you to make a defined resource type around the `augeas` resource.
Comment: We are using 2.7.something (the EPEL build.) So maybe we are subject to what you describe. It's a relief to hear that there is significant performance improvements ahead. (Upgrading to 3.latest is one of about 1,200 tasks on my plate.) Good call on a defined resource type. I am pretty new to Puppet, but I think know what you're getting at. Something like what [Herculesteam](https://forge.puppetlabs.com/herculesteam) has published in the Forge?
Comment: Annnddd I just noticed you are 50% of the Hercules Team. :)
Answer: It might be possible to use the Group members type to specifically set the members of the group. You may need to use the forcelocal option.
Comment: The `manages_members` feature is not available for the `groupadd` provider. You're supposed to set this in the `user` type using the `groups` attribute, which is what OP is trying to avoid here.
Comment: He's not entirely wrong. But, it should be noted that for Linux, this requires a [custom provider](https://github.com/pdxcat/puppet-module-group).


Set keyboard to use only a specific language without let to use change language button. objective c

Question: I try to obligate user to use only a specific language (my device language) and block the keyboard on this specific language. without allow him to change the language with the button.
what I did till now is to add a custom textfield:
<code>@implementation customTextField

- (NSString *)langFromLocale:(NSString *)locale {
   NSRange r = [locale rangeOfString:@"_"];
   if (r.length == 0) r.location = locale.length;
     NSRange r2 = [locale rangeOfString:@"-"];
   if (r2.length == 0) r2.location = locale.length;
     return [[locale substringToIndex:MIN(r.location, r2.location)]
     lowercaseString];
}

- (UITextInputMode *) textInputMode {
   NSString *myLanguage = [[NSLocale preferredLanguages]
   objectAtIndex:0];
   for (UITextInputMode *tim in [UITextInputMode activeInputModes]) {
       if ([[self langFromLocale:myLanguage ] isEqualToString:[self
       langFromLocale:tim.primaryLanguage]]) return tim;
    }
    return [super textInputMode];
}

@end
</code>
this allowed me to set the language of keyboard, but when I wanted to remove the change language button I got an answer to change the keyboard from default to ascii. therefore, now the language is usually on english!!!!
waiting for an answer!!
thanx!!
Answer: this option is not possible in IOS keyboard, the button is default in this mode.


How to make Drupal Commerce tokens available in the Commerce Message module?

Question: In addition to the Drupal Commerce module, I installed the Commerce Message module for Drupal 7. Everything works fine so far.
I created a new Rule to send a billing e-mail in addition to the order completed e-mail to the customer.
But now I have the problem that I can not apply any tokens that give me the address or full name of the customer. It seems, that the standard Drupal Commerce tokens do not work in the Commerce Message module.
I looked through the files of Commerce Message and I can only find a few tokens that do not help at all.
According to law I need to send billing information to the customer. Including the customer's full name and address.
How can I use the Drupal Commerce standard tokens with Commerce Message?
Also despite saying that it would be able to use multiple html tags it does not. Whenever I use  (for example: italic) it does not include such  in the e-mail (for example: it only includes  /italic/).
Any help?
Answer: Even though your question is about the "Commerce Message" module, at its core your question relates to the Message module. And since you are using the Rules module, you can make the missing tokens (= the commerce standard tokens, as in your question ...) available by using the Replacement patterns for each message type.
So the answer to your question is "Whatever token you're missing, just make it available via Rules, by creating a replacement token for them". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.
These Replacement tokens are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".
Answer: About this part of your question (near the end):

... use multiple html tags ...

That's really a different question, so here is a separated answer to that also: it must be that for the "Message text" you're using, you're using an HTML filter in which the  tag is not allowed (yet). So make sure to use an HTML filter in which it is allowed.
Comment: The strange things is that I use FULL HTML Filter for that.
It just doesn't seem to be the filter that is applied.
For now I used a workaround concerning the html problem.


How do i set one second delay between iterations?

Question: var arr = [[1,2,3],[4,5,6],[7,8,9]];

function out(ar){

  var interval = setInterval(function(){
    for (var i=0; i<ar.length;i++){

      for (var j=0;j<ar[i].length;j++){

        document.write(ar[i][j]);

      }
    document.write("
");
    }
  clearInterval(interval);
  },1000);

}

out(arr);

http://jsbin.com/edanib/edit
This code works, but i would like to make one second delay before outputting every number.
The above code cannot do that. How do i do that in vanilla Javascript?
Answer: setInterval isn't guaranteed to get you 1 second spacing because other things might run, but you can get close with the following
function out(ar) {
  var i = 0, j = 0;
  var interval = setInterval(function(){
    // Start with the next row if the last one was finished.
    if (i < ar.length && j == ar[i].length) {
      ++i;
      j = 0;
      // Put a line after it.
      document.body.appendChild(document.createElement('br'));
    }
    // Check if we're out of rows.
    if (i >= ar.length) { clearInterval(interval); return; }

    // Write out a number.
    document.body.appendChild(document.createTextNode('' + ar[i][j]));

    // We're done with the cell that we just wrote.
    ++j;
  }, 1000 /* milliseconds */);
}

Put the array indices outside the function, so each time the interval fires, it gets the loop state from the last run.
Also, you can't use document.write inside an interval handler because calling document.write after the document has closed clobbers the existing document.
Comment: thanks! but i would like to output them like this 123 br 456 br 789  Is it possible??
Answer: The easiest way to do this is to create a loop with setInterval.  Have the function capture the counters and increment them appropriate at every turn
Try the following
function output(arr) {
  var i = 0;
  var j = 0;
  var interval = setInterval(function () {

    while (i < arr.length && j === arr[i].length) {
      j = 0;
      i++;
    }

    if (i === arr.length) {
      clearInterval(interval);
    } else {
      document.write(arr[i][j]);
    }
    j++;
  }, 1000);
};

Comment: Minor nit.  This will cause exception spam in the console if passed an empty array.
Comment: @MikeSamuel good catch.  Updated to handle empty `arr` and properly handle empty sub arrays (`arr[i]`)
Answer: try it like this: first, create a single-dimension array, which you give to an output function that calls itself delayed:
var arr = [[1,2,3],[4,5,6],[7,8,9]];

function out(ar){
    var singleDim = []
    for (var i=0; i<ar.length;i++){

      for (var j=0;j<ar[i].length;j++){

          singleDim.push(ar[i][j]);

      }
    }
    outDelayed(singleDim,0,1000);
}

function outDelayed(arr,index,delay) {
    if (index < arr.length) {
        document.write(arr[index]);
        setTimeout(function(){
            outDelay(arr,index+1,delay);
        },delay);
    }
}

out(arr);


How do I create a scheduled task that will run as the logged in user

Question: I am trying to write a scheduled task that will run in the context of the currently logged in user.
It appears there was an option to run the task as a group in Windows 7 (see https://superuser.com/questions/656964/what-user-must-a-scheduled-task-run-as-in-order-to-be-visible-for-all-users), but this option is not present in Windows 10:

How can I achieve this in Windows 10?
Comment: I see, but that is what the `Change User or Group` is for, which context the task will run in. The user creating the task still probably needs admin rights to be allowed to create tasks for other users. If you create the task as admin, but assign the group you want it to run as, I think you will get the results you want.
Comment: Could it be the fact that you are running on Windows 10 Home Edition? On my Windows 10 Pro, I have the option to "Change User or Group"
Comment: @jcrossbeam - No, I'm on Win10 Enterprise :-(
Comment: And do you have local admin rights on the user currently logged on with? You could perhaps run `Task Scheduler` as Administrator, and see if that makes a difference.
Comment: Unfortunately I need this to run as the currently logged in user (who will not have admin privileges) as the task is designed to log information about whoever is currently logged in.
Comment: Sure - but the problem I have is that I can't assign it to a group, only to a user. If you compare the image above (mine) to the Windows 7 one in the link above, you'll see the button on Win7 says "change user or group" and the one on Win10 just says "change user". (Even if I go into object types the only available object type is "Users")
Comment: I understand what you mean, but if you have the ability to run the task scheduler as administrator, you will be able to `change user or group`. I just tried this on my own PC. With a normal user, you can only `Change User`, but with admin right, you can change both
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/39998/discussion-between-ben-and-jcrossbeam).
Answer: If you run Task Scheduler as Administrator, the option to Change User or Group will be available. There you can set the task itself to run as a non-privileged group.
Comment: @Ali123 I had the same doubt and I found that setting the "user account" to not be an user but instead to be the group itself named `users` worked for me. See here: https://superuser.com/a/656966/559711
Comment: I have this option on the scheduler: "When running the task use the following user account". How to set it to the current user please?
Comment: I'd like to note that the use case of the [first comment](https://superuser.com/a/656966/443147) (application should only start once per user) doesn't play well with `Users`, as the app will start for all logged in users simultaneously.
Comment: There is the dedicated group "INTERACTIVE" (with [SID "S-1-5-4"](https://learn.microsoft.com/en-us/windows/win32/secauthz/well-known-sids)) that serves the goals you are looking for. If that particular group is not selectable in the Task Scheduler console you can work around by exporting the task as XML, change the GroupID to "S-1-5-4" and reimport the XML.


error publishing my app on azure "A network-related or instance-specific error occurred while establishing a connection to SQL Server."

Question: I am trying to publish my application in azure for the first time, but I am getting the error below
I would appreciate any suggestion of how to fix the error
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
SQLExpress database file auto-creation error:
The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
Sql Server Express must be installed on the machine.
The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.

Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager) +947
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +6043115
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38
System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +531 System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +156
System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +22 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) +92
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +219
System.Data.SqlClient.SqlConnection.Open() +101
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +78
[HttpException (0x80004005): Unable to connect to SQL Server database.]
System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131
System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +92
System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +30
System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +410
Answer: Error is self-explanatory. From viewing your Stack Trace. Check below steps:
Step1: Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
Step2: The provider attempted to automatically create the application services database because the provider determined
that the database does not exist.
2.1 If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary
to enable automatic creation of the provider database.
2.2 App_Data directory does not already exist, the web server account must have read and write access to the application's directory.
2.3 The process identity for the web server account must have a local user profile. See the readme document for details on how to
create a local user profile for both machine and domain accounts.
You can also check if that is Azure SQL PaaS
in firewall settings on SQL Server, "Allow Azure Services: should set to "Yes"
You can refer to link - https://learn.microsoft.com/en-US/troubleshoot/sql/connect/resolving-connectivity-errors


k-fold cross validation overestimates test error?

Question: Say I have 1000 points in my data and perform 5-fold cross validation.
Each fold uses 800 instances to train the model, then calculates the error on the holdout fold of 200.
The 800 training instances will not be distributed exactly as per the original 1000. The average of each predictor variable amongst the 800 will be slightly higher or lower than the average of the 1000. So the 200 holdout fold are necessarily biased in the opposite direction of the 800.
Does it follow that the cross validation error is biased higher than the error on an unseen testing sample?
In my simplistic terms, each fold is tested on data that systematically differs from its training data.
I am aware that k-fold cross validation can overestimate test set error because each fold removes 1/k training instances, provided error increases as training set size decreases. This point is made much better in Hastie, Elements of Statistical Learning 7.10.
I think my question/point is different since it does not rely on error varying with training data size, but please correct or enlighten me.
Thanks.
Answer: You're describing a scenario in which you use k-fold cross validation on the training set, and the holdout would be considered the validation set, and is not the test set.
Use the validation set to find parameters which minimize the training error, then run on the test set.


Compute $\lim \limits_{x\to\infty} (\frac{x-2}{x+2})^x$

Question: Compute
$$\lim \limits_{x\to\infty} (\frac{x-2}{x+2})^x$$
I did
$$\lim_{x\to\infty} (\frac{x-2}{x+2})^x = \lim_{x\to\infty} \exp(x\cdot \ln(\frac{x-2}{x+2})) =  \exp( \lim_{x\to\infty} x\cdot \ln(\frac{x-2}{x+2}))$$
But how do I continue? The hint is to use L Hopital's Rule. I tried changing to
$$\exp(\lim_{x\to\infty} \frac{\ln(x-2)-\ln(x+2)}{1/x})$$
This is
$$(\infty - \infty )/0 = 0/0$$
But I find that I can keep differentiating?
Answer: Hint :
Rewrite limit into form :
$$\lim_{x\to\infty} \left(1+\frac{1}{\left(\frac{x+2}{-4}\right)}\right)^{\left(\frac{x+2}{-4}\right) \cdot \left(\frac{-4x}{x+2}\right)}$$
Answer: A nitpick: $\infty-\infty$ is not 0! It's undefined. Your limit is of the form $0/0$ though.
You can apply L'H'ôpital from the start if you like: $\lim\limits_{x\rightarrow\infty}{x-2\over x+2} =1$, and $\ln 1=0$.
So
$$
 \lim_{x\rightarrow\infty} \Bigl(x \ln{x-2\over x+2} \Bigr)
=\lim_{x\rightarrow\infty}  {\ln{x-2\over x+2}\over1/x}
=\lim_{x\rightarrow\infty}   {{x+2\over x-2}\cdot{1(x+2)-1(x-2)\over (x+2)^2} \over- 1/x^2 }
=\lim_{x\rightarrow\infty}  {{-4x^2\over (x+2) (x-2)}   }=-4.
$$
(use L'Hopital again to evaluate the limit on the right hand side if you like).
So,
$$\lim_{x\rightarrow\infty}\Bigl({x-2\over x+2}\Bigr)^x
=e^{ \lim\limits_{x\rightarrow\infty}\bigl(x\ln{x-2\over x+2}\bigr)}=e^{-4}.
$$

To answer more directly, L'Hôpital applied to $$\lim_{x\rightarrow\infty}{\ln(x-2)-\ln(x+2)\over 1/x}$$ gives you
 $$\lim_{x\rightarrow\infty}{{1\over x-2}-{1\over x+2}\over- 1/x^2}.$$
Now simplify:
$$
{{1\over x-2}-{1\over x+2}\over- 1/x^2}
=-x^2\Bigl({1\over x-2}-{1\over x+2}\Bigr)
= {-4x^2\over (x+2)(x-2)}.
$$
So, using L'Hôpital's rule again
$$
\lim_{x\rightarrow\infty}{{1\over x-2}-{1\over x+2}\over- 1/x^2}
=\lim_{x\rightarrow\infty} {-4x^2\over (x+2)(x-2)}
=\lim_{x\rightarrow\infty} {-8x\over (x+2)+(x-2)}
=\lim_{x\rightarrow\infty} {-8x\over2x}=-4.
$$
Answer: This can be done using only the definition of $e$,
$$e = \lim_{n\to\infty}(1+1/n)^n.$$
Notice that this implies immediately that $1/e =  \lim_{n\to\infty}(1-1/n)^n$
and, more generally,
$$\lim_{n\to\infty} (1+ a/n)^n = e^{a n}.$$
We find
$$\lim_{x\to\infty} \left(\frac{x-2}{x+2}\right)^x
= \lim_{x\to\infty} \left(\frac{1-2/x}{1+2/x}\right)^x
= \frac{e^{-2}}{e^2}$$
and so
$$\lim_{x\to\infty} \left(\frac{x-2}{x+2}\right)^x = \frac{1}{e^4}.$$
Answer: $$\lim_{x\to\infty} (\frac{x-2}{x+2})^x$$
$$\lim_{x\to\infty} (1-\frac{4}{x+2})^x = y$$
taking log on both sides we get
$$ln(y) = x ln (1- \frac{4}{x+2})$$
the  expansion for $ln (1+r) $ is $ r- \frac{r^2}{2} +\frac{r^3}{3}$ ....
where r tends to zero
$$ln(y) = x (  \frac{-4}{x+2} - \frac{\frac{-4}{x+2}^2}{2} +\frac{\frac{-4}{x+2}^3}{3} ....)$$
$ln (y) = \frac{-4x}{x+2}$ {rest all terms will terminate to zero}
$$ln (y) =\lim_{x\to\infty} \frac{-4x}{x+2} = -4$$
$$y = \frac{1}{e^4}$$
Answer: you can use
$$\left( \frac{x-2}{x+2}\right)^x = \left(1 - \frac{4}{x+2}\right)^x$$
and $(1 + \frac ax)^x \to \exp(a)$,
HTH, AB
Answer: If you want to use LHopital then $ \lim_{u\to 0} \frac{\ln(1+u)}{u}=1 $ by Lhopital's rule.
 $ l= \lim_{x\to \infty} (\frac{x-2}{x+2})^x=\lim_{x\to \infty} \exp((x+2)\ln(1-\frac{4}{x+2})-2\ln(1-\frac{4}{x+2}))$
For $ u = -\frac{4}{x+2}: $ $l= \lim_{u\to 0}\exp(-4\times\frac{\ln(1+u)}{u}-2\ln(1+u))=\exp(-4)$


Failing to customize form field label size in angular material

Question: We are using angular material in our app.
I am trying to find a way to make the floating labels of all fields bigger.
As an examples:

I can, of course, just drive it by additional class, but:
 * I will have to do it on each and every field
 * In case of an outlined field (as shown), the text will be on top of the border.
How can I make the change globally? and how to make sure that the space for the label text also increased?
Comment: The size relationship between label and field value is achieved using a scale transform `transform: translateY(-1.59375em) scale(.75);` in the class `mat-form-field-label`. The translateY will also need to be changed in order to position the label properly. Already this is a bit complicated. For Outline fields, you will also need to modify the outline border so that the gap matches the size of the label. The outline is actually 3 pieces: `mat-form-field-outline-start`, `mat-form-field-outline-gap`, and `mat-form-field-outline-end`. Now it's really complicated. Not worth the effort IMO.
Answer: I handled this by overriding a couple things in a global SCSS/CSS file.

Keep the translateY() value and change the scale to be 1.

<code>.mat-form-field-appearance-outline.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label,
 .mat-form-field-appearance-outline.mat-form-field-can-float .mat-input-server:focus + .mat-form-field-label-wrapper .mat-form-field-label {
        transform: translateY(-1.7175em) scale(1);
    }
</code>

Apply your font changes to the label, and add background to it, which overlaps with the outline and makes it look like there is the desired gap.

<code>.mat-form-field-can-float.mat-form-field-should-float .mat-form-field-label {
    letter-spacing: 0.025rem;
     line-height: 1.34;
      font: {
        size:  0.75rem;
        weight: 600;
      }

          mat-label {
           background: white;

            &::after {
              background: white;
              content: '';
              display: inline-block;
              width: 0.25rem;
            }
          }
</code>
Comment: You'll need to throw an `!important` at the end of the changed scale value:

`transform: translateY(-1.7175em) scale(1) !important;`
Otherwise Material will  overwrite it and keep it at .75
Comment: @SteveWhitmore since I added these to the global styles, I don't need `!important`
Answer: They are all dominated by the selector of <code>.mat-form-field-label</code> that you can manipulate your self, but it will change all the behaviours of it's translation and scale from label to floating label so it's a little bit complicated if you can not handle modifications of its translation and typography.


undeclared identifier error occurs when I already have declared the variable

Question: I got an undeclared identifier error from the follow code, but i have clearly declared  the variable "length" in both cases. what did I do wrong?
int startWordLenRec(char s[]) {
    if (isLetter(s) == false){
        int length = 0;
    }
    else if{
        int length = 1 + startWordLenRec(s+1);
    }
    return length;
}

Comment: As an aside, if that is your construct it is perfectly valid to insert return statements where you do assignment. For instance `return 0` instead of `int length = 0` and then `return length` later on.
Answer: You've declared two variables in two different blocks, but then tried to use them outside of those blocks. Instead you want to declare one variable, and assign a value to it within each of the blocks:
int startWordLenRec(char s[]) {
    int length;
    if (isLetter(s) == false){
        length = 0;
    }
    else {
        length = 1 + startWordLenRec(s+1);
    }
    return length;
}

(I removed the extraneous "if" from after the "else".)
However, a conditional expression would be clearer (IMO):
int startWordLenRec(char s[]) {
    return isLetter(s) ? 1 + startWordLenRec(s+1) : 0;
}

Answer: A declaration is local to the scope you declare it in.  So if you declare it inside {}, it cannot be used after the closing }.
int startWordLenRec(char s[]) {
    int length;
    if (isLetter(s) == false){
        length = 0;
    }
    else if{
        length = 1 + startWordLenRec(s+1);
    }
    return length;
}

Of course, you can also return 0; directly, without a separate variable.
Answer: Move the declaration of length outside of the if statement.  The way your currently have it declared it ceases to exit after the if statement executes so return length is always undeclared
Answer: Declare length outside of the if statements.
Answer: length needs to be declared at the top, since it is used in both branches of the if and outside (in the return statement).
Answer: You declared the variable "length" inside first and second if statements. Thus, it is not visible outside if statements


Can ViewerSupport.bind() be used in conjunction with images?

Question: In my Eclipse RCP View, I use JFace databinding to bind model data to a org.eclipse.jface.viewers.TreeViewer. I use ViewerSupport.bind() to bind the data as shown in the snippets, and it works just fine.
ViewerSupport.bind(viewer, model, BeanProperties.list("children",
          ModelObject.class), BeanProperties.value(ModelObject.class, "name"));

Now I'd really like to display an image along with the text on the nodes. Without databinding, I'd just override a LabelProvider's getImage(Object element) method, but the content + label provider method and the use of ViewerSupport don't work together. I haven't found a solution to my problem in the ViewerSupport API. Is there a solution, perhaps using org.eclipse.core.databinding.property.value.IValuePropertys?
Answer: ViewerSupport uses ObservableMapLabelProvider as the label provider. Unfortunately the getImage method for this just returns null.
You could perhaps uses a sub-class of ObservableMapLabelProvider to provide the images. You can't use ViewerSupport to do that so you would have to duplicate some of the code.
This is how ViewerSupport.bind sets up the tree:
public static void bind(AbstractTreeViewer viewer, Object input,
        IListProperty childrenProperty, IValueProperty[] labelProperties) {
  Realm realm = DisplayRealm.getRealm(viewer.getControl().getDisplay());

  ObservableListTreeContentProvider contentProvider = new ObservableListTreeContentProvider(
            childrenProperty.listFactory(realm), null);

  if (viewer.getInput() != null)
    viewer.setInput(null);

  viewer.setContentProvider(contentProvider);

  viewer.setLabelProvider(new ObservableMapLabelProvider(Properties
            .observeEach(contentProvider.getKnownElements(),
                    labelProperties)));

  if (input != null)
    viewer.setInput(input);
}

Comment: Should've thought of that myself really, thanks. Lack of an OOP mind. Shame that these methods are `static`, would've made extending so much easier.


How to process core-dumps with Splunk?

Question: We are managing an application, which some times crashes and dumps core. We have a script, which outputs the application's stack from the core -- and some other details useful for debugging.
Can Splunk be configured to invoke a script upon encountering a fresh core-dump in a directory -- and store the script's output on the centralized server?
I know, we can do this ourselves -- invoke the script, store its output in the log, and have Splunk monitor that log. But it would be more convenient (for non-technical reasons) in our situation, if Splunk were to do the watching on its own...
Returning to this problem 4 years later... The "scripted input" solution is not really a great one, because it foregoes the file-tracking already built into the Universal Forwarder -- the custom script has to do all three of the:

Detecting new core-dumps.
Processing all of the newly-detected core-dumps.
Keeping track of the already-processed core-dumps.

Which makes it only slightly better, than simply using cron -- or incrond.
I'd much prefer being able to use the standard UF facilities for the items 1. and 3. -- and implementing only the second step, as my own core2json... Can something like the below be done?
[monitor:///my/application/directory/core.*]
disabled=0
sourcetype=coredump
process_with=/my/scripts/core2json

Is there anything like the process_with in the inputs.conf syntax?
Comment: Splunk can monitor a directory for new files and log those, or obviously grab new data added to existing files - is this what you mean?
Comment: But can it run a custom script -- and grab its output -- _instead_ of the entire core-file? So as to log just the application's stack at crash time, instead of the entire core-dump?
Comment: Interesting use case - I've never thought of that before.
Answer: Splunk can do this. What you're looking for is a scripted input.
Splunk has documentation on this at http://docs.splunk.com/Documentation/Splunk/7.0.2/AdvancedDev/ScriptedInputsIntro
Rather than watch for a core dump, I would think that it would be more efficient to have the scripted input run periodically, process any core dumps, then move them to a different directory (or delete them) so that the same core dumps aren't repeatedly processed.
Comment: Thanks for the pointer. With "scripted inputs" it is not really Splunk doing it, though -- my own script/daemon would be processing the core-dumps and outputting the text into a file, which Splunk will then be watching... I knew, this is an option, but would've preferred for Splunk to execute the script upon encountering a new core-dump instead -- because of how the application-management and the OS-management roles are split in our organization :-(

And, heavens, no "periodic" script -- a core dump is already an _event_ and can trigger an action immediately, no need to wait...

How to process core-dumps with Splunk?


Beginner Q: Residual Sum Squared (RSS) and R2

Question: I'm new to the forum and posting my first of many questions. I'm working on a Linear Regression model and the $R^2$ is 0.89 which tells me my regression line is a good fit. When I calculated the residual sum squared, the number is around 4060, which is telling me the difference between the predicted and actual values are large.
Do the values $R^2$ = 0.89 and RSS = 4060 contradict each other?
Answer: No, these numbers do not contradict each other. It sounds like you have an understanding of what $R^2$ means: it represents the proportion of the variance in your data which is explained by your model; the closer to one, the better the fit.
The residual sum of squares (RSS) is the sum of the squared distances between your actual versus your predicted values:
$RSS = \sum\limits_{i=1}^{n}(y_i-\hat y_i)^2$
Where $y_i$ is a given datapoint and $\hat y_i$ is your fitted value for $y_i$.
The actual number you get depends largely on the scale of your response variable. Taken alone, the RSS isn't so informative.
Example:
Picture your residuals as a vertical line connecting your actual values to your predicted value (red traces in the plot below). You can imagine that if your y-axis is on a different scale, the number you get will be very different.
For instance, consider that your y-axis were kilometers, and a given point is about 0.5km away from your line of best fit. Then, the residual on that given datapoint is 0.5. However, if your scale is meters, then that same datapoint has a residual of 500. Your RSS will be much larger, but the fit does not change at all; in fact the data don't change at all either. But the RSS changes drastically.
Comment: Excellent!, thank you so much for explaining how RSS can be affected by the y scale. I really appreciate you taking the time to provide a thorough explanation. I have 1 follow up question, what other item do you personally look at besides the R2 to determine if your regression line it the best fit?
Comment: $R^2$ is a good metric for linear regression. Take a look at [this answer](https://stats.stackexchange.com/questions/123915/how-to-know-if-best-fit-line-really-represents-known-set-of-data) for more details
Comment: I don't want to be 'that guy', but linear regression is a bad choice when the data is not I(0). I know that it's easier to display deviations around a trend, but it gets people used to seeing bad practice. Gauss-Markov, anyone?


Select on which page a view has to be display

Question: I am new to the Views module in Drupal 7. I enable the Taxonomy Term view and customize it a bit. For now the view is displayed in the default page of my theme in the main content region. But I would like this view to be displayed in a custom page defined by my theme on a particular region.
It seems to be an easy task but I can't figure how to do that.
Answer: It is easy, Edit your View and Click on Add (A popup near upper left) and choose Block
This newly created block will inherit all the settings from your existing view display.
You can Override any setting for your block display.
Choose appropriate template relevant to block following Theme: Information
Save your view and head on to block listing page to adjust your newly created block.
Comment: Ok finally I succeed in displaying the block by disabling/enabling the view !
Comment: Thanks for your answer. I test your solution but nothing appear in the region within I put the new created block.
Comment: Make sure if you are not using any argument and there is not any contextual condition.
Comment: Deleting contextual filter do nothing. The problem is not that the view has nothing to display, because if I set a header or a footer for the block it don't appear


Angle to side of rectangle

Question: The title is probably misleading (if I knew what to call it I'm sure I'd have found my answer searching), so here's a graphic demonstrating what I mean.

Basically, say I have either an angle (in radians, I used degrees only for clarity) or, preferably, a normal vector $(x,y)$ "pointing" the same way ($(0.7,0.7)$ being the same as the red line at $270\deg$). How would I translate that to a point on the side of a rectangle?
In the particular case I'm working with, as seen in the graphic, I'm working with sides from -1 to 1. There's probably a word for all of this but I'm not fluent in maths lingo, so hopefully the visual explains my question well enough.
Thanks.
Comment: It is a little odd and confusing to see you've written $\;270^\circ\;$ for the angle the red line forms...with **what** ? It is customary to measure angles, both in radians and degrees, from the positive direction of the $\;x$- axis and counter clockwise to the other line, so here it should be an angle of about $\;50^\circ\;$ or so. Why then did you mark $\;270^\circ\;$ ?
Comment: Apologies, it's 315. I'm using this in an application where 0 degrees begins as marked in the graphic and goes around clockwise. It's what I'm used to since this is how it is processed in the language I'm using (I didn't feel that bit was necessary since this isn't SO).
Comment: Then perhaps you will have to "translate" some stuff being answered/commented to you as in physics/mathematics angles are *usually* measured counter clockwise (though in physics is more usual to make changes on this than in maths.)
Answer: When the angle (in counter-clockwise direction) is $\alpha$, you get the following coöridates on the unit circle:
$$
\left(\begin{matrix} \cos \alpha\\ \sin\alpha\end{matrix}\right)
$$
When $-\frac 14\pi\leq \alpha\leq \frac 14 \pi$, you want the first coördinate to be $1$, so you devide both of them by $\cos\alpha$, getting
$$
\left(\begin{matrix} 1\\ \tan\alpha\end{matrix}\right)
$$
The other cases are similar.
Answer: Measuring angles of vectors "anchored" at the origin, we can see the rectangle's vertices are joined to the origin by vectors with angles
$$\begin{align*}(1,1)&\longrightarrow 45^\circ=\frac\pi4\; Rad.\\
(-1,1)&\longrightarrow 135^\circ=\frac{3\pi}4\;Rad. \\
(-1,-1)&\longrightarrow 225^\circ=\frac{5\pi}4\;Rad.\\
(1,-1)&\longrightarrow315^\circ=\frac{7\pi}4\;Rad.\end{align*}$$
Thus for instance, any vector with forming with the positive direction of the $\;x$-axis an angle $\;\theta\;,\;\;\frac\pi4 <\theta<\frac{2\pi}4\;$ will intersect the upper side of the rectange, which is on the straight horizontal line $\;y=1\;$ ,  and similarly with the other cases.
Now, how to calculate the coordinates where such a vector intersects the rectangle: take a vector, which is only a segment of a line $\;y=mx\;$ , with $\;m=\tan\theta\;$, and solve the equation
$$mx=1\iff x=\frac1m=\frac1{\tan\theta}=\cot\theta$$
and you're done since then you already have the abscissa $\;x\;$ and, of course, you know the ordinate $\;y\;$, which in the above example is $\;y=1\;$, so your point on the rectangle is $\;\left(\cot\theta\,,\,1\right)\;$
Comment: I'm sure you gave me everything I asked for, I'm just not as mathematically literate as I'd hoped. Going to accept it and mull it over until I can translate it, as you said, into my application. Thanks.
Comment: Forgive me if you answered this and it flew over my head, but basically I would end up with multiple conditions based on the angle/signs of the vector?
Comment: No if you know what the range of the angle is, @fay .

Angle to side of rectangle


RD Connection Broker direct user to specfic RD Session Host

Question: Let me state the objective first.  I would like to configure a Remote Desktop Services paradigm such that a Remote Desktop Client is able to connect to an entity, likely an RD Gateway or RD Connection Broker, and be directed to a specific server with the RD Session Host role -- based on the user's group membership.
For example, if there exist servers with RD Session host roles called SVR1 and SVR2 and a RD Connection Broker named CB1 with a farm called rd-farm of which SVR1 and SVR2 are members.  I'd like to be able to point the user Remote Desktop Client at rd-farm and based on the user's group membership, be directed to SVR1 xor SVR2, but not both.
RD Gateway or RD Connection Broker are both on the table for achieving the objective.
From the investigation I have done I understand it such the RD Connection Broker can use either session load balancing or round-robin DNS like behavior for handing off sessions to Session Hosts.  However, I'd like to use a user's group membership to determine to what Session Host they are redirected, not session load balancing or round-robin.
The reason why we would like to achieve this is that we have a fleet of session hosts that are not identical -- and as such are not a "farm" in the truest sense of the word.  However, we would still like to push out a single client profile (be it from a single RDP icon across the enterprise, a Wyse thin client configuration, etc.) that directs users to the same RD Connection Broker/Gateway and have the user's Active Directory group membership determine to which Session Host they are redirected.
This serverfault Use RD Gateway to direct users to certain term server? doesn't answer the question with the specific qualifiers -- group membership, Connection Broker, or with single remote desktop client profile.
Comment: AFAIK, that isn't possible.  But it would be neat if I was wrong.
Answer: I do not believe the exact configuration you are looking for is possible in the way you are looking to implement it.
I would possibly look at creating multiple collections based on the different types of users you have and then using RDWeb to deploy the RDP icons. You can control what icons are displayed by using groups in RDWeb.
This way you could deploy a single icon (Shortcut to http://rdweb.mycompany.com) across your enterprise and still control everything by groups.
Answer: Your shortcut could be a batch file (you can turn it into an exe with some free tools like batch2exe) that looks up a configuration file for which server you want to send the user to.
Answer: Windows RD Session hosts use a crappy NLB load balancer, basically a round robin DNS, this is not load balancing as if you switch off a session host the broker will still route traffic to it - in order to get traffic management, server health checks, sticky session and ssl off loading you need a proper load balancer and virtualize the IP address for all hosts, here is a long article on LB a RD deployment with Kemp load balancers, I'm sure you could do this with HAProxy
https://charbelnemnom.com/2015/03/how-to-load-balance-remote-desktop-session-host-with-kemp-virtual-loadmaster-kemptech-rds-hyperv/
Comment: If you have a particular issue, I'd suggest asking a question. Otherwise, Google is your friend.
Comment: RDSH can use a number of methods to load balance, only one of which is NLB (which is very different then from DNS RR). You are right that Kemp and HAProxy can be used though.
Comment: @GregL - can you direct users to specific hosts with it? - the question wasn't how many bad load load balancing methods can RDSH do, which ones can it do by the way?


Why is there no $C>0$ such that $C||f||_q \leq ||f||_p$?

Question:
Show that for $1\leq p <q \leq \infty$, there is no $C>0$ such that
  $C||f||_q \leq ||f||_p$ for all $f\in C([0,1])$.
Definition:
Let $a,b\in \mathbb{R}$ with $a<b$ and for $f\in C([a,b])$, $1\leq p
 <\infty$ let
$$||f||_p=\left(\int_{a}^{b}|f(x)|^p \, dx\right)^{1/p} \text{and }  |
|f||_\infty := \max\limits_{x\in [a,b]}|f(x)|$$

There's a hint that tells me to compute $||f_n||_p$ and $||f_n||_q$ with  $f_n : [0,1]\to \mathbb{R} , t\mapsto f_n(t)=t^n$ mit $n\in \mathbb{N}$, what exactly do I have to compute? I don't see why this helps...
Comment: Well, you could start by computing $\|f_n\|_p$. What do you get?
Comment: $$||f_n||_p=\left(\int_{a}^{b}|t^n|^p \, dt\right)^{1/p} =\left(\int_{a}^{b}t^{np} \, dt\right)^{1/p} =\left(\frac{t^{np+1}}{np+1}\Bigg |_a^b\right)^{1/p}=\left(\frac{b^{np+1}-a^{np+1}}{np+1}\right)^{1/p}$$ But why?
Comment: But here we are working on the interval $[0,1]$.
Comment: Assume that $C||t^n||_q \le ||t^n||_p$ for all $n$ and let $n \to \infty$. That's what the hint is saying.
Comment: Thanks, Trevor.
Answer: The hint is saying that you can show that $C$ has to be $0$ (a contradiction) by assuming that $C||t^n||_q \le ||t^n||_p$ for all $n$. For example, if $q = \infty$, we have
$$ C||t^n||_{\infty} = C \le ||t^n||_p = \frac{1}{(1+pn)^{1/p}} \xrightarrow{n\to\infty} 0. $$
Therefore there is no $C > 0$ such that $C||t^n||_{\infty} < ||t^n||_p$ for all $n$.
Now do the same thing but with $q < \infty$.
Comment: $$ \frac{(1+qn)^{1/q}}{(1+pn)^{1/p}} \to \frac{(1+qn)}{(1+pn)^{q/p}} \to \frac{q}{\frac qp (1+pn)^{q/p - 1}} $$ and since $q/p - 1 > 0$, this tends to $0$ as $n \to \infty$. @ParabolicAlcoholic
Comment: Hmm, for $q<\infty$, we have: $C\leq \frac{(1+qn)^{1/q}}{(1+pn)^{1/p}}$. What am I missing?
Comment: @ParabolicAlcoholic It goes to $0$ but it's harder to show. Try raising the fraction to the power of $p$ or $q$ (I'm not sure which works better; maybe both options work) and applying l'Hôpital's rule.
Comment: Okay, I'm trying the squeeze theorem first.
Comment: Doesn't really appear to be working for me...
Comment: Oh my god! As a result of my laziness, I used WolframAlpha to derive $\frac{(1+qn)}{(1+pn)^{q/p}}$ and the result was horrible. What I was missing is how to correctly use L'Hospital's Rule (deriving denominator and numerator seperately)


SQL Server Create VIEW for Sorting

Question: I have a database table that has the following structure:
TABLE_A
DOC_ID | STATUS
   1   |   0

   2   |   1

TABLE_B
PK_ID | DOC_ID | NAME | VALUE
 1   |   1    |  A   |   1

 2   |   1    |  B   |   2

 3   |   2    |  A   |   1

 4   |   2    |  B   |   1

 5   |   2    |  C   |   1

DOC_ID is the FOREIGN KEY on TABLE_B.
Then I create a VIEW so that I may more easily sort on NAME.
CREATE VIEW [dbo].[V_MY_VIEW] AS
    SELECT a.DOC_ID, a1.VALUE AS 'A', a2.VALUE AS 'B', a3.VALUES AS 'C'
    FROM dbo.TABLE_A a,
        ( SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'A') a1
    LEFT OUTER JOIN  ( SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'B') a2
        ON a1.DOC_ID = a2.DOC_ID
    LEFT OUTER JOIN ( SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'C') a3
        ON a1.DOC_ID = a3.DOC_ID
    WHERE a.STATUS IN (0, 1)

This view will only include the rows with DOC_ID = 2 since the rows with DOC_ID = 1 do not have a row with NAME = C.  How should I modify the VIEW so that it will include all the rows from TABLE_B?
Thanks.
Answer: SELECT * FROM TABLE_A LEFT OUTER JOIN TABLE_B ON TABLE_A.DOC_ID = TABLE_B.DOC_ID
WHERE TABLE_A.STATUS IN (0, 1)

Replace * with the columns you want to display.
Include an ISNULL(Name, ) in your order by clause unless you want none matches at the top.
Comment: Oops, hang on, just read your full creation script in full, will update in a minute
Comment: Nope, still dont see what you are trying to achieve that the select statement I have written there doesnt provide, let me know if it is not what you are after.
Answer: CREATE VIEW [dbo].[V_MY_VIEW] AS

SELECT a.DOC_ID, a1.VALUE AS A, a2.VALUE AS B, a3.VALUE AS C
FROM dbo.TABLE_A a
LEFT JOIN (SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'A') a1
    ON a.DOC_ID = a1.DOC_ID
LEFT OUTER JOIN  ( SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'B') a2
    ON a.DOC_ID = a2.DOC_ID
LEFT OUTER JOIN ( SELECT DOC_ID, VALUE FROM dbo.TABLE_B WHERE NAME = 'C') a3
    ON a.DOC_ID = a3.DOC_ID
WHERE a.STATUS IN (0, 1)

Look the results at http://sqlfiddle.com/#!3/5574b/4/0
Comment: Looks good.  I am getting all the rows I am expecting to get now.  Thanks.

SQL Server Create VIEW for Sorting


jquery draggable re-order after drag and drop

Question: I am trying to do a list of 10 iteam that are draggable, stacked from 1 to 10 from top to bottom in order.
If a user wants to drag an item at position 1 to lets say position 5. I want all the items to move up 1 position. Similary if a user moves the item from position 10 to position 7, I want item 9 to move to position 10, item 8 to position 9, item 7 to position 8 so previously positioned item 10 can take place at position 7.
Comment: Possible duplicate of [Sort Divs in Jquery Based on Attribute 'data-sort'?](http://stackoverflow.com/questions/6133723/sort-divs-in-jquery-based-on-attribute-data-sort)
Answer: Check this question and answers.. You can use it after drop
Sort Divs in Jquery Based on Attribute 'data-sort'


Compactness and compact-finite measure in Lusin theorem (Rudin)

Question: I have two questions about some hypotheses in Lusin's theorem as stated in Rudin's "Real and Complex Analysis".
The proof initially deals with a subcase, that is the function $f$ is supposed to be limited in $[0,1[$ and the nonzero elements (through $f$) are in $A$ that is  assumed to be compact.
First question: why do we assume that $A$ is compact?
Second question: why do we assume the measure to be finite over compact sets?
I was not able to recognize where in the proof those assumptions are needed.
Thank you
Answer:
Rudin takes an open set $V$ such that $A\subset V$ and $\overline V$ is compact. Without compactness of $A$, such $V$ would not necessarily exist.
Although we already assume $\mu(A)<\infty$, this isn't enough: in the course of the proof we step outside of $A$ a bit (Urysohn's lemma needs some room to work), taking an open set $V$ containing $A$. In order to keep the measure under control, we need $\mu(V)$ to be finite. The assumption that $\mu$ is finite on compact sets, together with $\overline V$ being compact, guarantee that.

By the way: the assumptions on $\mu$ to which Rudin refers to (stated in Thm. 2.14) are very common for measures found in analysis; these days one would simply say that $\mu$ is a Radon measure. Thus, book authors may impose this standard set of assumptions on $\mu$, even if they do not need all of them.
Comment: Why can't we just assume the existance of an open set $V$ containing $A$ such that that $\mu(V)<\infty$? Surely if every open set $V$ containing $A$, has infinite measure then $\mu(A)=\infty$


Mensagem sobre dppx e dpi no console do Chrome

Question: Quando entro no sistema interno que estou fazendo aqui na empresa vou no console e aparece uma mensagem estranha:

Consider using 'dppx' units instead of 'dpi', as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min-resolution: 144dpi)

O que significa?
obs: é só no meu sistema, em outros sites como Google por exemplo não aparece.
Answer: dppx é uma métrica de detecção de resolução/tamanho de tela, assim como o dpi. No entanto o dpi não representa a tela de uma maneira exata.

dppx: Número de pixels do dispositivo/tela por pixel de CSS
dpi: Pontos por polegada

O chrome por padrão exibe essa mensagem caso a página utilize dpi em seu css, uma vez que o dppx é uma métrica mais exata e orientada ao dispositivo que está visualizando. Mas é apenas um aviso do navegador recomendando o uso do dppx ao invés do dpi para que suporte melhor os diversos tipos de tamanhos de tela.
Desabilitar a mensagem creio que não seja possível, pois é um comportamento padrão do navegador. Mas é possível converter o uso do dpi para o dppx.
<code>1px / 1dppx = 96dpi
</code>
No seu caso 2dppx poderiam ser usados no lugar dos 144dpi.
Mas, acredito que esse recurso ainda não seja bem suportado por navegadores como IE.
Seguem links para ajuda:

http://drewwells.net/blog/2013/working-with-dppx/
http://dev.w3.org/csswg/css-values/#resolution
Comment: Você sabe se é possível desligar essas mensagens?
Comment: Creio que não. Mas é possível converter dpi para dppx e eliminar a mensagem. Editei a resposta com mais informações.
Comment: Meu laptop tem resolução de tela de 120 dpi. Nesta situação devo então supor que 1dppx = 120 dpi ?


Automação de testes em páginas web

Question: Gostaria da indicação de ferramentas para realizar a gravação da entrada de dados na página. Já usei o Selenium IDE, Selenium Web Driver. Vi que existe o iMacros. Estou programando em JSF, Java e Primefaces.
Meu problema é o seguinte, eu gravei através dos Selenium IDE, mas tem hora que ele perde a referencia das entradas na página. Ai tenho que refazer o teste a partir da referencia errada, então há outra ferramentas a se trabalhar para automatizar a entrada de dados?
O iMacros não gostei muito pois ele não é tão simples e eficiente de se trabalhar como o Selenium IDE.
Answer: Aqui tem uma lista completa de ferramentas de automação de testes.
O Selenium é uma excelente ferramenta e recomendo tentar arrumar o problema dele seguindo alguns passos como indicado Aqui.
Pelo que vi você tem que aguardar o elemento aparecer na pagina e ficar fixo antes de utilizar ele.
Comment: Cara a página é totalmente carregada entende, mas a referencia de alguns elementos esta errada. Não sei porque mudam. E quando se tem um `comboBox` usam o `Tab` ele n seleciona, somente através do `click`. Vou ler o que você postou. Obrigado
Answer: O problema que tu estás enfrentando pode ser dividido em dois pontos:

elementos com IDs dinâmicos
alguns elementos parecerem como um elemento html (como uma combobox), mas na verdade são uma junção de vários elementos (ao invés de ser um  com vários  ele tem geralmente uma  com várias s ou s).

Nos indique como é o comportamento do código-fonte html ou mesmo da combo. Existem tipos de localização no Selenium que podem te ajudar a interagir com elementos assim.
Answer: Certa feita criei um framework de testes web, que na verdade é um wrapper para o Selenium, para uma empresa que trabalha com JSF.
O problema com o JSF é exatamente aquele apontado pelo Elias no primeiro item da lista: ele gera ID's dinâmicos para muitos elementos. Isso inviabiliza que a gravação pelo Selenium IDE do Firefox seja executada sempre da mesma forma.
Por exemplo, se você não definir um ID para qualquer elemento da página, o JSF vai se encarregar de fazê-lo. Um botão num formulário, por exemplo, pode acabar como o id meuFormulario:j_id45674 (isso pode mudar de uma execução para outra) e um campo em um dataTable tabela:0:nomeCampo (não muda, mas é difícil de trabalhar).
Para contornar esses problemas, a solução foi usar seletores CSS e XPath usando o atributo name para campos de formulário e outros atributos para imagens.
Enfim, a solução que encontrei foi criar o tal framework que, entre outras coisas, provia alguns métodos que encapsulavam seletores para os componentes padrão da empresa.
Por exemplo, todo cadastro de inclusão tinha um botão com um atributo class específico, por exemplo, botao-incluir. Em outros casos, o botão continha uma imagem específica. Então criei uma classe que todos as classes de teste poderiam estender ou importar estaticamente e usar mais ou menos assim (em Java):
public class CadastroCliente extends TestBase {

    @Test
    public void cadastrarCliente() {
        type(campo("nome"));
        type(campo("idade"));
        click(botaoIncluir());
        aguardar();
    }

}

Em JSF, o campo nome, por exemplo, poderia ter o ID gerado como formCad:panel10:nome. Então o método campo() retornaria na verdade um seletor assim:
css=input[id$=':nome']

O seletor acima é um seletor CSS que busca um elemento input na página cujo ID termina com :nome.
Os métodos type e click que estão no código de exemplo são wrappers do selenium que fiz especialmente adaptados para o sistema em questão.
A vantagem de abstrair os métodos originais do Selenium é que frequentemente havia algum comportamento específico que exigia tratamento especial. Nesse caso, eu simplesmente ajustava a classe Wrapper sem precisar tocar nos testes.
O método aguardar(), por exemplo, pode automaticamente fazer verificações sobre erros de validação, isso é claro, se houver um padrão seguido em todo o sistema.

Automação de testes em páginas web


Programmatically update Webform Submission by sid

Question: I'm trying create/update Webform Submission programmatically. I already know how the create new submission by following the Drupal 8 API. Now I'm trying to build a update method, I refer to the Webform module source-code and API documents but couldn't find a solution. I guess they remove webform_get_submission webform_submission_update functions in Drupal 8.3 as-well.
$values = [
  'webform_id' => 'attendees_info',
  'in_draft' => FALSE,
  'uid' => $uid,
  'langcode' => 'en',
  'token' => 'at_'.$token,
  'uri' => '/webform/attendees/api',
  'remote_addr' => '',
  'data' => [
    'name' => $name,
    'email' => $email,
    'gallery_url' => 'gallery/'.$token,
  ],
];

$webform = Webform::load($values['webform_id']);
$is_open = WebformSubmissionForm::isOpen($webform);

if ($is_open === TRUE) {
    // Validate submission.
    $errors = WebformSubmissionForm::validateValues($values);

    // Check there are no validation errors.
    if (!empty($errors)) {
       return $errors;
    }
    else {
      // Submit values and get submission ID.
      $webform_submission = WebformSubmissionForm::submitValues($values);
      return $webform_submission->id();
    }
}

Above is my Submission creation code, I don't know how to do the update method. Is anyone face this issue before? Hope someone will help me on this, thanks.
Answer: Try using \Drupal\webform\WebformSubmissionInterface::getData(); and
\Drupal\webform\WebformSubmissionInterface::setData($data);
// Load submission using sid.
/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\Entity\WebformSubmission::load($sid);

// Get submission data.
$data = $webform_submission->getData();

// Change submission data.
$data['element_key'] = 'custom_element_value';

// Set submission data.
$webform_submission->setData($data);

// Save submission.
$webform_submission->save();

Comment: Using this code in custom submit handler, new entry is created in webform_submission_data table, instead of updating existing data with sid.
Appreciate any help
Answer: jrockowitz's above code is the correct and clean approach. Below also works, just wanted to share.
$query = \Drupal::database()->merge('webform_submission_data');
$query->key([
    'sid' => $sid,
    'name' => 'your_custom_key',
])->fields([
    'value' => 'your_value',
]);
$query->execute();

Comment: This works too, as $ws->setData() doesn't do any validation, however it may change in the future. Plus, by skipping $ws->save() change_date doesn't get updated which may cause inconsistency later. It's always a good practice to avoid touching row data.
Answer: To only change one element, use:
 $webform_submission->setElementData('element_key', 'custom_element_value')

For example:

/** @var \Drupal\webform\WebformSubmissionInterface $webform_submission */
$webform_submission = \Drupal\webform\entity\WebformSubmission::load($sid);
$webform_submission->setElementData('element_key', 'custom_element_value');
$webform_submission->save();

Source: https://www.drupal.org/project/webform/issues/2911356


Qual o código e linguagem fazem a tag input fazer o que faz?

Question: A tag input é uma tag html, ou seja linguagem de marcação, no entanto essa tag executa instruções como de uma linguagem de programação.
Afinal como a tag "input file", faz para acessar o sistema operacional e trazer o arquivo selecionado?
Como alterar a mensagem:"Nenhum arquivo selecionado" sem javascript ?
Comment: A pergunta está um pouco confusa, especialmente o último parágrafo que não parece ter relação com o resto. Não sei se dá para responder a pergunta facilmente, já que teria que explicar muita coisa, o que tornaria a pergunta muito ampla. Talvez dê para fazer um resumo, sei lá. Se melhorar a pergunta, deixando ela um pouco mais específica, fica mais fácil obter uma resposta.
Comment: Essas tags sinalizam para o navegador que ele deve fazer alguma coisa. A implementação da ação delas está no código fonte do navegador, não na página/aplicação Web que você faz.
Comment: Não é muito bem direcionado a sua pergunta, mas como a dúvida beira para a ideia de "como o HTML é processado?", fica aqui um material amigável:
http://www.html5rocks.com/pt/tutorials/internals/howbrowserswork/
Answer: O input não é parte de uma linguagem de programação especifica, ele é parte de algo que chamamos interface (https://www.w3.org/TR/html-markup/input.file.html#input.file-interface), cada navegador tem um motor próprio de renderização que vai implementar esta interface cada qual é feito na sua propria linguagem de programação, a maioria dos motores são escritos em c++, mas existem motores que são escritos em c ou java.
Lista de motores mais populares

Chrome e Opera usam o motor Blink (fork do Webkit)
Safari usa o motor Webkit
InternetExplorer usa o motor Trident (descontinuado em favor do EdgeHTML e MS Edge)
Microsoft Edge usa o motor EdgeHTML
Firefox usa o motor Gecko

Quando você colocar um elemento assim dentro do html:
<input type="file">

O navegador inicialmente vai ler como texto, mas então ele vai processar o documento todo e começa a gerar o que chamamos de "widgets" (os widgets gerados baseados no sistema operacional ou não), isso pode ocorrer em quanto a página esta carregando ou somente quando ela termina de carregar (vai depender do tipo de buffer).
Não há como você manipular, a estrutura HTML e XML é renderizada pelo navegador e não por um script externo, os motores já são compilados, a única maneira de alterar de verdade seria criar o seu próprio motor, ou pegar um existente e modificar (tal como a google fez com o Webkit)
No entanto com CSS e HTML é possível simular um input customizado assim:

var fakeInput   = document.querySelector(".file-customizado");
var realInput   = document.querySelector(".file-customizado input[type=file]");
var selectLabel = document.querySelector(".file-customizado .label");
var pathFile    = document.querySelector(".file-customizado .path");

//Remove o path do arquivo, assim é exibido apenas o nome do arquivo
function basename(path) {
   path = String(path);
   var d = path.split(/\\|\//);
   return d[d.length - 1];
}

//O input customizado dispara o evento no input real
fakeInput.onclick = function() {
     realInput.click();
};

//O input detecta a troca de arquivo para mostrar que o input não esta vazio no label
realInput.onchange = function() {
    if (realInput.value) {
       selectLabel.className = "label hide";
       pathFile.innerHTML = basename(realInput.value);
       pathFile.className = "path";
    } else {
       pathFile.className = "path hide";
       selectLabel.className = "label";
    }
};
.file-customizado {
    border-radius: 10px;
    position: relative;
    overflow: hidden;
    width: 200px;
    background-color: #f00;
    color: #fff;
    display: inline-block;
    cursor: pointer;
}
.file-customizado input[type=file] {
    position: absolute;
    visibility: hidden;
    top: -9990px;
    left: -9999px;
}
.file-customizado .label, .file-customizado .path {
    display: block;
    padding: 10px 0;
    text-align: center;
}
.file-customizado .hide {
    display: none !important;
}

    <input type="file" name="campo">
    Selecionar...

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/54204/discussion-on-answer-by-guilherme-nascimento-qual-o-codigo-e-linguagem-fazem-a-t)
Answer: O elemento input é próprio da linguagem de marcação HTML,e faz parte de um modelo para um conjunto de dados, o formulário, associado a um método e ação URI.  HTML elements
O funcionameto para o acesso dos arquivos no sistema operacional
ocorre resumidamente da seguinte forma:
Quando o usuário clica no botão relativo ao elemento "input file", o navegador faz uma requisição ao servidor (no caso o próprio sistema operacional), e estabelece uma conexão com o servidor através de um socket de rede.
Cada plataforma possui uma biblioteca Web com um script interno(ou interface) exemplo .Net Framework  de modo a tornar a conexão possível, onde ocorre o apelidado handshake-aperto de mão.
Desta forma é feita uma chamada no Sistema Operacional (lado do servidor) que
abre sua própria caixa de diálogos (no Windows OpenFileDialog) contendo
uma lista de arquivos para seleção.
Após a seleção do arquivo, a transferência é realizada através do protocolo
apropriado, HTTP ou outro dependendo do tipo de arquivo.
Alguns meta dados (nem todos) do(s) arquivo(s) selecionados ficam disponíveis para manipulação no browser.
O HTMLInputElement interface fornece propriedades especiais e métodos
(para além do normal HTMLElement interface que ele também tem à sua
disposição por herança) para manipular o layout e apresentação dos
elementos de entrada.
A mensagem "Nenhum arquivo selecionado", faz parte do código interno do navegador e desconheço uma forma de alterá-la sem javascript.