What's the difference between EWI fingering and saxophone fingering?

Question: I recently purchased an Akai EWI Solo - it's an electronic woodwind instrument that mimics a saxophone. As I watched several videos of experienced EWI players unboxing the EWI Solo, I heard advice that I should use the default EWI fingering instead of the saxophone fingering I might be used to.
I started practicing with the default EWI fingering, but haven't noticed any differences so far. What's the difference between EWI fingering and saxophone fingering? Why should I use EWI fingering instead of saxophone fingering?
Answer: There are different EWI fingerings but the general idea is that standard saxophone fingerings will work, and some other that are not working on a real sax will also work. In my experience, palm keys for the right hand will move the output a certain number of semi tones higher or lower on every notes whereas it only works for some on a real sax. For instance, the top right hand palm key will add a semi tone on every note and not only on the top F.
Another one is to press one or several fingers of the right hand while not all fingers of left hand are pressed, which should lower the sound by half a semi tone. Try non standard things which seem logical ;).
Edit: page 22 of the user manual ( https://www.akaipro.com/ewi-solo ) of your EWI is describing the EWI fingerings.
As it is not bound by acoustics, EWI fingerings should be more practical as you have more different combinations for every notes. Their use or not depends if you see the EWI as a real instrument or as a silent practice of saxophone. For the latter, you should probably stick to sax fingerings. Also, sometimes playing with EWI fingerings can be annoying as it is "too" sensitive: if you slightly touch a key that you did not want to it might produce an unwanted sound. With saxophone fingerings, only valid fingerings will be taken into account which can help limit the amount of unwanted note the instrument is producing.


Using aggregate value in condition in SELECT statement

Question: I'm creating a SELECT statement between two tables with a one-to-many relationship and I want to use the aggregate value in the condition where I want to get a list of records with more than one related records in table B.
The following SELECT statement gives me the number of related records in table2 but I only want those records in my result where there are more than one related records in table2. In other words, in the following code, I want the NumberOfRelatedRecords to be greater than 1.
How do I use that in my WHERE condition?
select a.Id, count(b.Id) as NumberOfRelatedRecords
from table1 as a
   inner join table2 as b on a.Id = b.RelatedId
group by a.Id

Answer: You can try using HAVING
select a.Id, count(b.Id) as NumberOfRelatedRecords
from table1 as a
   inner join table2 as b on a.Id = b.RelatedId
group by a.Id
HAVING Count(b.ID) > 1

Comment: Glad it worked. When you are able, please mark as answer so others can find this if they have the same question.
Comment: Will do! For some reason SO doesn't let me mark it as the answer right away.Thanks again.


FAPI redirect *and* store to local database

Question: What I'm trying to achieve
I am successfully using the Form API in Drupal 7 to dynamically alter Webforms to redirect to an off-site URL on submit.
What I need is twofold; I need (a) for the client to visit the offsite URL so the site can store a lead via query string parameters, as well as (b) for the same information to be documented in my local Drupal database.
Every lead must be documented, so I have tentatively ruled out JavaScript/AJAX as an option.
How I tried it
I thought the best way to do this was to set up a module with $form_state['redirect']:
/**
 * Implement hook_form_alter to change the form's submit action
 */
function myform_form_alter(&$form, &$form_state, $form_id) {
    $form['actions']['submit']['#submit'][]='myform_submit';
}

/**
 * Callback as specified above
 */
function myform_submit($form, &$form_state) {
    // Values for the query string
    $vals = array('mykey' => 'myval');

    // Redirect appropriately
    $form_state['redirect'] = array(
        // $path
        'http://www.anotherwebsite.com/',
        // $options
        array('query' => $vals),
        // $http_response_code
        302,
    );
}

I did that, and as expected, the user is redirected immediately after form submission. However, the Form API does not submit to my database before redirecting the user.
I read the FAPI documentation for Drupal 7. I sought using #action, although it apparently reports only accepting internal values and my users must visit an offsite URL. I wound up using redirect in the meantime, which was no longer documented but was suggested in the comments.
Where do I go from here?
EDIT: tenken's response works, but I have another problem!
My callback now uses array_unshift($form['#submit'],'my_callback') and via drupal_http_request, is submitting to both websites. However, my webform is still not saving submissions locally, and instead on submit, redirects to self (even with no hook_form_alter).
Comment: By "does not submit to my database" do you mean the Webform module doesn't save it's data to the db?
Answer: EDIT: added option (1) after thinking about this more, haha. It's a much simpler solution.
(1)
If the below is to complex you (and you actually want to POST something) you could form_alter the form and append your own additional FAPI #submit function which uses drupal_http_request() to POST/GET the url with all the submitted form params.
(2)
I think you want to set the destination value from within the #action of the form to be wherever the default webform submit path is and tag on a destination querystring parameter to the action which drupal will then goto after the form has been validated/submitted.
I know you said you tried using #action but I'm talking about the action being the drupal action and destination being a remote url (url-escaped).
Eg, I have customized a login form to use various login backend logic depending on the url of the login: /user/login, /student/login, /staff/login ... etc. I then make the destination of a succcessful login goto a specific drupal page. destination is used by drupal_goto() to redirect the user anywhere -- even an external url.
Here is a small example from code I have in D7:
/**
 * The following 2 functions allow our form overrides to occur.
 */
function MYMODULE_form_user_login_block_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_staff_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function MYMODULE_form_user_login_alter(&$form, &$form_state) {
  if (_MYMODULE_auth_is_student_login_page_url()) {
    $form = $form + array('#auth-destination' => 'student');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
  if (_MYMODULE_auth_is_id_login_page_url()) {
    $form = $form + array('#auth-destination' => 'staff');
    _MYMODULE_auth_user_login_form_alter($form, $form_state);
  }
}

function _MYMODULE_auth_user_login_form_alter(&$form, &$form_state) {
  global $conf;
  $saveForm = $form;
  $form = array();
  # overrides the default validator.
  foreach ($saveForm as $key => $value) {
    if ($key == '#validate') {
      $form[$key] = array();
      foreach ($value as $validator) {
        if ($validator == 'user_login_authenticate_validate') {
          // If we progressed down to this level of nested Alters, we have
          // #auth-destination.
          $type_of_login = $saveForm['#auth-destination'];
          switch($type_of_login) {
            case 'staff':
              // These functions are custom validate functions whose logic is
              // copied/altered from the default
              // 'user_login_authenticate_validate' implementation.
              $validator = 'MYMODULE_auth_staff_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=staff/login&destination=%3Cfront%3E';
              break;
            case 'student':
              $validator = 'MYMODULE_auth_student_authenticate_validate';
              // the form posts back to itself and supplies a unique destintation.
              $form['#action'] = '/?q=student/login&destination=student/my-surveys';
              break;
            default:
              break;
          }
        }
        $form[$key][] = $validator;
      }
    }
    else {
      $form[$key] = $value;
    }
  }
  $form['name']['#title'] = ($type_of_login == 'Staff') ? 'Staff Username' : 'StudentCampusID';
  unset($form['links']);
}

Comment: Hi @tenken, thanks! I've tried both methods, but I like that #1 keeps the user on the page. The form now (a) submits to the foreign website, and (b) returns to the "action" attribute after submitting. However, I still get "There are no submissions for this form" when viewing the results tab. Am I appending the additional #submit correctly? (http://pastebin.com/bhnQZiSH) Reading the documentation, it looks like it uses an array() to specify the #submit callback, but that throws me a server error.
Comment: Just a note, I've decided to go the route of `array_unshift($form['#submit'],'my_custom_callback');`, which seems to work (to some extent). However, I've completely disabled my module, and it looks like I'm having further problems with the Webform module itself just not submitting anything.
Comment: Are you using D7 webforms? or a FAPI custom built form. Webform may be processing its forms in another manner (that you should be able to hook into I believe). So, you should be able to track down the issue similar to this thread: http://drupal.stackexchange.com/questions/9436/how-do-i-add-an-additional-submit-handler
Comment: @tenken I'm using D7 Webforms. Your solution answered my original question, and that article is something I've tried and makes sense (thank you).  but even with zero altering, my Webform submit handlers aren't saving...a whole other issue altogether! (I've opened a separate Drupal Question.)


Twilio programmable SMS not sending in deployed Lambda function

Question: I am working on a Serverless AWS service that uses Twilio's programmable SMS to deliver text messages.
My setup is consistently delivering messages successfully when I run the stack locally (e.g. sls offline start), but in the deployed environment I seem to be unable to even call the method on the Twilio client.
Here's how the message delivery is set up:
const twilio = require('twilio');

const twilioClient = twilio(
  process.env.TWILIO_SID,
  process.env.TWILIO_TOKEN,
  {
    lazyLoading: true,
  }
);

export function sendMessage(user, message) {
  twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER,
    to: user.phone,
    body: message,
  }, function(err, message) {
    console.log('error', err);
    console.log('message', message);
  });
}

// And then usage in a Serverless Function Handler

function example(event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;

  // user is also determined here
  sendMessage(user, 'This is a message');

  return {
    body: JSON.stringify({}),
    statusCode: 200
  };
}

Locally, running this works and I am able to see the output of the message log, with nothing on the error log. However, when deployed, running this yields nothing -- the method appears to not even get called (and I can verify in the Twilio logs that no API call was made), therefor no error or message logs are made in the callback.
In debugging I've tried the following:

I've logged all the environment variables (Twilio SSID, auth token, phone number), as well as the function arguments, and they all appear to be in place. I also checked out the Lambda function itself to make sure the environment variables exist.
I've examined my CloudWatch logs; no errors or exceptions are logged. Other than the Twilio method not getting called the Lambda function is executed without issue.
I've tried logging things like twilio and twilioClient.messages.create to make sure the client and function definition didn't get wiped out somehow.
I thought maybe it had to do with context.callbackWaitsForEmptyEventLoop so I changing it from false to true.

I have come up empty, I can't figure out why this would be working locally, but not when deployed.

Edit: per the Twilio client example, if you omit the callback function the method will return a Promise. I went ahead and tried to await the response of the method:
export function sendMessage(user, message) {
  return twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER!,
    to: user.phone,
    body: message,
  });
}

// Usage...

async function example(event, context, callback) {
  context.callbackWaitsForEmptyEventLoop = false;

  try {
    const message = await sendMessage(user, 'This is a message');
    console.log('message', message)
  } catch (error) {
    console.log('error', error);
  }

  return {
    body: JSON.stringify({}),
    statusCode: 200
  };
}

In this example the Lambda function is successful, but neither the message nor the error are logged.
Comment: I haven't used Lambda but with Twilio Functions, you need to me mindful of asynchronous functions and and the associate callback to indicate the end of the function - specifically - https://www.twilio.com/docs/runtime/functions/invocation#callback-and-asynchronous-limitations. Could this be what is going on in this case as well? Maybe some details here? https://docs.aws.amazon.com/lambda/latest/dg/nodejs-handler.html
Comment: @Alan I suspect you are on to something, but I unfortunately have not been able to solve it. I've updated my question to note that I've given a Promise-based method a shot, with no luck.
Answer: I tried this and it works. I tried to make my code as similar to use, with a few changes.
const twilio = require('twilio');

const twilioClient = twilio(
  process.env.TWILIO_SID,
  process.env.TWILIO_TOKEN
);

let user = '+14075551212';

function sendMessage(user, message) {
  return twilioClient.messages.create({
    from: process.env.TWILIO_NUMBER,
    to: user,
    body: message,
  });
}

exports.handler = async function(event, context, callback) {
  try {
    const message = await sendMessage(user, 'This is a message');
    console.log('message', message);
    callback(null, {result: 'success'});
  } catch (error) {
    console.log('error', error);
    callback("error");
  }
};

Comment: Hi Jody, I do but not my speciality. It may be best for another post. A diagram of your topology would help others provide a more focused answer. I would normally think IAM permissions is more an issue with Lambda but I have not really worked that much with it, 100% on my growing to-do list though.
Comment: Thanks for this, Alan! Sure enough, like you mentioned, this works as written. I'm going to mark this as the answer. Unfortunately, in my case, I think there's something else going on, and I think it's the VPC I have set up on the Lambda function. It's needed to communicate with an RDS instance, and I think somewhere in there it's blocking outbound requests to Twilio. I neglected to mention this in my original post, apologies. If you have any VPC / Subnet / NAT gateway knowledge, I'm all ears. Otherwise, thanks for this answer!
Comment: It was the `await` that I needed. Thanks!


Why a[21] is not equal to a[021]?

Question: #include<bits/stdc++.h>
using namespace std;
int a[500];
int main()
{
    a[21]=10;
    if(a[21]==a[021])puts("Yes");
    else puts("No");
    return 0;
}

g++ -std=c++11
The output is No, can anyone tell me why?
Comment: `021` is an octal literal -- 17 in decimal
Answer: In C++ a leading 0 on an integer literal means that value is in octal (similar to the way that 0x21 means that value is in hexadecimal).
Each of these values will be different. Here's a quick online demo:
http://cpp.sh/3cws4n
Note: the default output format for cout is decimal so the values you see are in decimal.

Why a[21] is not equal to a[021]?


Nginx upstream keepalive with SNI

Question: I've got Nginx setup to proxy two subdomains. SNI is used so each subdomain has a different SSL certificate. Nginx setup is roughly:
upstream a_example_443 {
    server 188.8.131.52:443;
    keepalive 128;
    keepalive_timeout 180s;
}
upstream b_example_443 {
    server 220.127.116.11:443;
    keepalive 128;
    keepalive_timeout 180s;
}
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_ssl_server_name on;
server {
    listen 443 ssl;
    server_name aproxy.example.com;
    location / {
        proxy_pass https://a_example_443;
    }
}
server {
    listen 443 ssl;
    server_name bproxy.example.com;
    location / {
        proxy_pass https://b_example_443;
    }
}

This works, the SNI names are a_example_443 and b_example_443 and the subdomains have aliases for those. However, is it bad that I use two upstreams?
I tried configuring it to use one upstream. After quite some effort, this works:
upstream example_443 {
    server 126.96.36.199:443;
    keepalive 128;
    keepalive_timeout 180s;
}
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_ssl_server_name on;
proxy_ssl_session_reuse off;
server {
    listen 443 ssl;
    server_name aproxy.example.com;
    location / {
        proxy_set_header HOST a.example.com;
        proxy_ssl_name a.example.com;
        proxy_pass https://example_443;
    }
}
server {
    listen 443 ssl;
    server_name bproxy.example.com;
    location / {
        proxy_set_header HOST b.example.com;
        proxy_ssl_name b.example.com;
        proxy_pass https://example_443;
    }
}

First I had to set the HOST and proxy_ssl_name to the SNI name. This is fine, except it seems when I added proxy_set_header HOST, I lose all the proxy_set_header I had at the http configuration level (not shown here). I'd love to know why, but OK fine, I put those in a file and include it in each server. Edit, found out why, proxy_set_header docs:

These directives are inherited from the previous level if and only if there are no proxy_set_header directives defined on the current level.

Next I had to set proxy_ssl_session_reuse off. What are the ramifications of using this? I understand it disables abbreviated handshakes, but when is that needed? My guess is when using keep alive, not very often. Is that right?
Keepalive is where things become unclear for me about exactly how the upstream connections work. Nginx gets a request, opens an SSL connection to the upstream, sends the an SNI name. The upstream routes it to the right subdomain, uses that subdomain's certificate, etc. Later Nginx receives another request -- can it reuse the previous SSL connection that is still because of keepalive? If so, what if the second request is for the other SNI name? Does it just send the request and let the upstream use the Host header to route it?
Ultimately, should I use two upstreams or one?
Comment: Nginx can handle this, but at this level of complexity it's time to start looking at more full-featured load balancers, like haproxy, which handles this scenario without blinking.
Answer: It seems that the above configuration is wrong: the SSL connections are reused and if the connection doesn't match the SNI name then the upstream rejects it. I suppose this means the answer is that two upstreams are required, one for each SNI name.

Nginx upstream keepalive with SNI


Date Comparsion in Matlab

Question: I would like to check whether the date I pass in into a function comes after 01/02 or 01/08. How do i do that in Matlab? This comparsion does is independent of the year.
Need some guidance on this.
Btw, how do u calculate the difference between dates irregardless of year?
Comment: A simple google search will give you [`datenum`](http://www.mathworks.in/help/matlab/ref/datenum.html)
Comment: you can use datenum with date formart as `mm/dd`. No need to include year.
Comment: i know but it will include the year as well...I don't want to include the year...
Answer: Use datenum, with a format specifier if you want to be explicit:
D0 = datenum('01/02','mm/dd'); % current year is inferred (irrelevant)
D1 = datenum('01/08'); % 'mm/dd' is inferred

This allows you to test with regular comparison operators:
>> D = datenum('01/03')
>> D > D0
ans =
     1
>> D > D1
ans =
     0

Date Comparsion in Matlab


Choosing from a bag that contains 10 purple balls and 10 orange balls, how many must a man select to get at least 3 purple balls?

Question: What are the steps to doing a problem like this? Do we first calculate the total number of balls in the bag?
Answer: This is the pigeonhole principle. To guarantee the selection of $3$ purple balls, the number of balls chose must exceed the number of orange balls by $3$. That is, $10 + 3 = 13$ balls.


Can you help on complex analysis problem

Question: The question: Let $D = {z : |z| < 1}$, and let $f : D → D$ have a zero of order $n$ at zero.
Show that $|f(z)| ≤ |z|^{n}$ on $D$.
My attempt: I am not sure what theorem's are applied to this problem I think we use Rouche's Theorem but there may be some problems with that theorem. Do I consider the function $g(z) = f(z) - z$; or could I use the function $h(z) = \frac{f(z)}{z}$ and try to use the maximum modulus principle. I think I am not heading in the right direction. Can you please give me some hints on how to approach this problem? Thanks a lot guys!
Comment: Do you know (Schwarz lemma) ? [ https://en.wikipedia.org/wiki/Schwarz_lemma ]. Try to apply induction on n and look at $\frac{f(z)}{z}$. This is, of course, an application of Maximum Modulus Principle.
Comment: Oh I get it. Thanks a lot!
Comment: One doesn't even need induction; consider $f(z)/z^n$ directly.
Answer: Since $f$ has at $z=0$ a zero of order $n$, then
$$
g(z)=\frac{f(z)}{z^n}
$$
is analytic in the unit disk.
If $0<r<1$ and $M_r=\max_{|z|\le r}|g(z)|$, then
$$
M_r=\max_{|z|\le r}|g(z)|=\max_{|z|= r}\frac{|f(z)|}{|z|^n}\le \frac{1}{r^n}
$$
Maximum principle implies that
$$
\sup_{|z|<1}|g(z)|=\lim_{r\to 1}M_r\le \lim_{r\to 1}\frac{1}{r^n}= 1.
$$
Hence
$$
|f(z)|=|g(z)||z|^n\le |z|^n,
$$
for all $|z|<1$.
Note. If $|f(z)|=|z|^n$, for some $|z|<1$, then there exists an $a\in\mathbb C$, with $|a|=1$, such that $f(z)=az^n$, for all $|z|<1$, due to maximum principle.
Answer:
Since the image of $f$ is $\mathbb D$, $|f|\le 1$.
Consider $h(z)=f(z)z^{-n}$ which is clearly analytic on $\mathbb D$.
By maximum modulus principle, $|h(z)|$ is maximized on $\partial\mathbb D$.
Thus, $$\max |h(z)|=\max_{|z|=1}|f(z)||z|^{-n}=\max_{|z|=1}|f(z)|\le 1$$
$|h|\le 1\implies|f|\le|z|^n$ on $\mathbb D$.


Capturando elementos por tag e inserindo dentro de um array

Question: Bom, estou montando um carrossel em um projeto teste, e me surgiu uma dúvida, como posso, com vanillaJS, capturar determinados elementos pela tag, e colocá-los dentro de um array ? A ideia seria mais precisamente, capturar de acordo com a posição no corpo do HTML, por exemplo;capturar todos os figure que estão dentro de uma div cujo o pai é #banners.
Como posso fazer isso ao carregar a página ?
Comment: Poderia adicionar o código?
Comment: Tenta assim: var arr = document.querySelectorAll("#banners figure");
Comment: Beleza, vou responder então.
Comment: não tem um código pronto, o array seria o meu primeiro passo, só esquematizei em papel mesmo :D
Comment: tenho só o html, mas seria como o próprio exemplo dado, não teria nada de diferente msm
Comment: Entendi, mais poste por favor, vai ajudar bastante
Comment: perfeito @JuniorNunes
Comment: posta código como resposta man :D
Answer: Você pode usar o document.querySelectorAll, assim:
var arr = document.querySelectorAll("#banners figure")


Active Directory with nodes in multiple IP Addresses

Question: I have written some code to fetch user information from an Active Directory Server. Suppose the Active Directory Server has nodes, each of which is another Active Directory Installation in a different geographic location. Eg: one AD server in US and another in Australia with a root AD Server in US with the former two as nodes.
Would the filter queries I write for searching users across geographic locations work if I run them on the root AD server ?. The query I use is
<code>(|(objectClass=user)(objectClass=person)(objectClass=inetOrgPerson))
</code>
I cannot actually test this scenario but need to know the what will happen here.
Answer: The AD is distributed and multimaster database, in general terms you can query any of the Domain Controllers about a user and get the same answer in any of the DC (nodes).
In AD you can configure the replication of data changes between servers, so if a user change some attribute in Australia, and you query for some data against the server in NY maybe you will get different answers. The domain administrator can tell you about time replication in the domain.
Once the replication takes place, you have the same information in any of the DC. Usually replication times are about minutes, but in some cases it is only set to 1 or 2 times per day.
I hope this answer your question.
Answer: Your terminology WRT Active Directory is not precise. There are two concerns that I can see for you:

Querying the closest replica of the AD
Understanding the behaviour of queries in a multi-domain environment

The Global Catalog maintains a subset of the contents of all domains in the forest. If your use of the term "node" refers to disperate domains, queries against the Global Catalog will allow you to query all domains in the forest in a single query (assuming the attributes you're looking for are part of the subset replicated into the GC).
Location of a physically-close DC is accomplished through a combination of DNS and LDAP queries. A Goooooogle search on "dns ldap find closest domain controller" returns some good first steps (Finding closest Domain Controller through LDAP).
If you're developing on Windows you can get domain controller location "for free" by using the ADSI API.
Comment: Thanks. I was able to fetch the user data across domains by querying the GC.
Answer: What is not clear here is what you mean with the term "node".

A single Active Directory domain with multiple domain controllers geographically distributed?
A single domain with OUs containing users and computers for each geographical location?
Multiple domains representing various company regional offices?

As long as you're querying domain controllers of the same domain, you will get the same answer to the same query from any one of them (aside from replication issues).
But if you have multiple domains, or if you want to query specific subtrees (OUs) of a given domain, you will get different answers.
Comment: yes, I mean A single Active Directory domain with multiple domain controllers geographically distributed
Answer: r u sure you want the "OR" "|" operator in the query, it doesn't make sense.  Also are you equating nodes with domains?
also the following will give you an example where you don't need code to test with.
dsquery * domainroot -filter (|(objectClass=user)(objectClass=person)(objectClass=inetOrgPerson))" -attr *
but like I said the "OR" | operator doesn't make sense.
oddly I found a bug in serverfaults answer code, it will be wierd if after doing this it disappears


Not getting output from SQL query

Question: I am trying to make a script which will display the latest posts from my friends AND me.
There are 3 tables related to this - statusUpdates (contains posts), friends (links between friends using IDs) and users (contains details of all users of the website).
The script I am using at the moment is as follows.
$myQuery = mysql_query ("SELECT * FROM statusUpdates AS su
             LEFT JOIN (friends AS fr) ON
                (fr.frHostID = su.authorID OR fr.frContactID = su.authorID)
             WHERE (fr.frHostID = 105090)
             GROUP BY su.statusID
             ORDER BY su.statusID
             DESC LIMIT 0,5");

Please note that 105090 is my own ID.
Problem is that when I have no friends, not even a single post is showing up even though I have made more than one status update.
A solution would be to create a row in the friends table, adding me as my own friend.
But in that case, I would have to prevent my own name from occuring in a "Show List of Friends" page, and any other related page.
I was initially using INNER JOIN and having the above problem. Then I came a similar issue, and modified my script with LEFT JOIN as was suggested. It seemed to have solved the issue of the OP of that post, but not mine.
I cannot submit comments in that post (probably because it is 2 years old). So I am creating this post.
Comment: [Please, don't use mysql_* functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about prepared statements instead, and use [pdo](https://wiki.php.net/rfc/mysql_deprecation) or [mysqli](http://stackoverflow.com/questions/tagged/mysqli).
Comment: You don't have to worry. You won't spend that much time to discover PDO or MySQLi. Just keep in mind `mysql_` are already deprecated, and will be remove in a future PHP version.
Comment: @zessx At the moment I don't have much knowledge of either PDO or MySQLi. I'll start learning PDO after I am done with this project, which I need to complete as soon as possible. But thank you for your advice.
Answer: UPDATE: I didn't take into account you also wanted your friends' posts.
Although you already marked an answer as correct, as the IN statement is usually slower than a JOIN, you can try this:
SELECT *
FROM statusUpdates AS su LEFT JOIN friends AS fr
ON fr.frContactID = su.authorID
WHERE (fr.frHostID = 105090 or su.authorID = 105090)
GROUP BY su.statusID
ORDER BY su.statusID
DESC LIMIT 0,5

INITIAL ANSWER:
Just change the where condition from:
WHERE (fr.frHostID = 105090)

to
WHERE (su.authorID = 105090)

The reason is that you are putting a where condition in the right part of the left join, so you are forcing the existance of friends.
BTW, take care of this two posts:
Why shouldn't I use mysql_* functions in PHP?
and
How can I prevent SQL injection in PHP?
Comment: In my opinion, and in my own experience, a `JOIN` usually works faster than an `IN` clause, especially with thousands of rows, although it may depend on your query because they are not exactly the same.  Generally you have to experiment and test for performance issues.
Comment: I know you already marked an answer as correct, but I updated my answer.
Comment: Thanks a lot. It works perfectly now. Added a JOIN statement after the LEFT JOIN clause to pull username and other details from another table _users_.
`JOIN (users AS u) ON (u.roll = su.authorID)`

Just another question, though. Is this the most efficient technique for handling such cases - even for a huge number of rows?
Comment: Is it advisable to use them for handling even larger number of rows, say 1 million? Or are there more alternatives?
Comment: I would use this `LEFT JOIN` example rather than the `IN` one, especially in those cases.
Comment: Yeah, I am already using that one in my current script. Thank you. :-)
Answer: Use this query instead :
SELECT * FROM statusUpdates AS su
WHERE su.authorID = 105090
OR su.authorID IN (
    SELECT fr.frContactID
    FROM friends AS fr
    WHERE fr.frHostID = 105090
)
GROUP BY su.statusID
ORDER BY su.statusID DESC
LIMIT 0,5

Comment: That solves the problem as of now. Thank you.
But could you please help me with another thing? I need to extract data from another table **users** which contains fields such as _username_, _profileLink_, _profilePic_.
I tried using `INNER JOIN (users AS u) ON (u.roll = su.authorID)` but it didn't work. In fact, using INNER JOIN prevented my query from pulling any data at all! It used to work, however, with my earlier code (the one in the original post).
Comment: Okay, I found the answer. The modified code now reads as

`$myQuery = mysql_query("SELECT * FROM statusUpdates AS su
JOIN (users AS u) ON (u.roll = su.authorID)
WHERE su.authorID = 105090
OR su.authorID IN (
    SELECT fr.frContactID
    FROM friends AS fr
    WHERE fr.frHostID = 105090
)
GROUP BY su.statusID
ORDER BY su.statusID DESC
LIMIT 0,5");`
Answer: try this query
SELECT * FROM statusUpdates
WHERE autherID in (select frContactID from friends where frHostID = 105090)
or authorID = 105090
LIMIT 0,5

Not getting output from SQL query


Get the latest date record

Question: I have two tables in my SQL Database.
ID  CDATE
1   12/04/14
2   14/05/14
3   20/01/14

ID  NAME
1    A
2    A
3    B

But I need the output as below.
NAME  CDATE
A     14/05/14
B     20/01/14

Do you have any suggestions for me ?
Comment: You must have tried *something*.  Please edit your question with your attempts.  (Hint:  this is a basic SQL query with a `join` and `group by`.)
Comment: Please show us the code you have tried, and what you are having truoble with.
Answer: SELECT MAX(t1.CDATE), t2.NAME FROM table1 t1 LEFT JOIN table2 t2 ON t1.ID = t2.ID GROUP BY t2.NAME ORDER BY t1.CDATE DESC

Comment: I guess this query will list all the rows..but I want to eliminate those that are old. I want only the record that was created latest.
Comment: @user2037445, see my answer. You need to do a `select top 2`.
Answer: Try this:
SELECT t1.cdate, t2.name
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id=t2.id
ORDER BY t1.cdate DESC;

Edit:
SELECT s1.cdate,
  t2.name
FROM table2 t2
LEFT JOIN
  (SELECT ID, MAX(cdate) cdate FROM table1 GROUP BY ID
  ) s1
ON s1.id=t2.id
ORDER BY s1.cdate DESC;

Comment: I guess this query will list all the rows..but I want to eliminate those that are old. I want only the record that was created latest
Comment: Do you want the two oldest?
Comment: No the latest one for every entry of ID
Comment: @user2037445 Then please edit your question to specify this, as it is clearly not obvious.
Answer: EDIT: Since you changed the question...
SELECT TOP 2 n.NAME, d, CDATE
FROM Dates d
LEFT JOIN Names n ON d.ID=n.ID
ORDER BY d.CDATE;

Comment: I think op wants, for each name, the latest corresponding date in his first table. Your query works for the dummy sample, but doesn't accomplish that for larger datasets. But I reckon the question is of very poor quality.
Answer: To Make table you need to create relation between this table
http://www.w3schools.com/sql/sql_foreignkey.asp
and then to get data from two table
http://www.w3schools.com/sql/sql_join.asp

Get the latest date record


Como inserir uma nova div e empilhá-las após clicar em um botão

Question: Tenho uma div HTML que exibe totais de um cálculo, e preciso que cada vez que seja gerada uma nova (no clique do botão Gerar) uma nova div em branco seja criada para receber os valores, empilhando as já geradas uma embaixo da outra.
Código HTML
BOTAO
<input type="button" value="Gerar Lote" />

HTML

Resumo

    Débitos
    <input value="0.00" />

    Créditos
    <input value="0.00" />

Comment: Vc quer gerar só uma div em branco cada vez que clicar no botão?
Answer: Para criar copias dos elementos que já possui pode utilizar a função cloneNode. Tendo as cópias em mão precisa apenas de as colocar no local certo, que seria no fim de todas as outras que já tem. Consegue fazer isso utilizando a função insertBefore, especificando o elemento de referência como o pai, e indicando null como nó de referência.
Exemplo:

const resumo = document.querySelector(".l1");
const [debitos, creditos] = [...document.querySelectorAll(".l25")];

//definir o código para o evento de click no botão gerar
document.getElementById("gerar").addEventListener("click", () => {

  //clonar os 3 divs
  const novoResumo = resumo.cloneNode(true); //true indica cópia profunda
  const novoDebito = debitos.cloneNode(true);
  const novoCredito = creditos.cloneNode(true);

  //inserir no fim por ordem cada um dos divs clonados
  resumo.parentNode.insertBefore(novoResumo, null);
  resumo.parentNode.insertBefore(novoDebito, null);
  resumo.parentNode.insertBefore(novoCredito, null);
});

<input id="gerar" type="button" value="Gerar Lote" />

Resumo

    Débitos
    <input value="0.00" />

    Créditos
    <input value="0.00" />

Funcionalidades utilizadas que pode querer aprofundar:

querySelector
querySelectorAll
Destructuring Assignment
Comment: Obrigado Isac, funcionou perfeitamente.


PHP query in a view will cause website error

Question: I'm using a global PHP query in a View to find out the count of membership users.
The first query, that extracts the total number of users from the database works fine, but when I use the WHERE clause in a query for a comparison with a string, I received a website error like in the image attached below.
This is the query:
<code><?php
$count_users_premium = db_query('SELECT COUNT(license_id) FROM {commerce_license} WHERE state="active"')->fetchField();
print $count_users_premium;
?>
</code>
So, if I want to use WHERE some_number=3, it will work, but comparison with a string didn't work. (Drupal 8 version)
Answer: You cannot directly insert values into queries in Drupal. They need to be escaped. You would want something like this:
<code>$count_users_premium = db_query('SELECT COUNT(license_id) FROM {commerce_license} WHERE state=:active', [':active' => 'active'])->fetchField();
</code>
Comment: You're a hero! Thank you!!!


Showing $\lim\frac{\left| a_{n+1} z^{n+1} \right|}{\left| a_n z^n \right|} = |z| \lim \frac{ a_{n+1} }{ a_n }$

Question: Let $\sum a_n z^n$ be a complex power series.  I've seen it asserted without explanation in a text that
$$
\lim\frac{\left| a_{n+1} z^{n+1} \right|}{\left| a_n z^n \right|} = |z| \lim \frac{ a_{n+1}  }{ a_n  }
$$
This is not an obvious equality to me.  How is it being derived?
Comment: You can cancel $z^n$ (or $\lvert z\rvert^n$) from the quotient, and pull the constant $\lvert z\rvert$ out of the limit.
Answer: $$\lim\frac{|a_{n+1}z^{n+1}|}{|a_nz^n|}=\lim\frac{|a_{n+1}||z^{n+1}|}{|a_n||z^n|}=\lim\frac{|a_{n+1}|}{|a_n|}\left|\frac{z^{n+1}}{z^n}\right|=\lim\frac{|a_{n+1}|}{|a_n|}|z|=|z|\lim\frac{|a_{n+1}|}{|a_n|}$$


What is the purpose of the metal bar behind the nut on the Ibanez S6570SK?

Question: The Ibanez S6570SK has a metal bar on the headstock, right behind the nut.
I have seen guitars that have metal hooks behind the nut (the Fender Telecaster comes to mind), but such guitars usually have an open nut, and a flat headstock, and the metal hooks are used to force a downward angle on the strings to avoid buzzing.
This Ibanez, on the other hand, has a locking nut. Surely this by itself fixes the buzzing hazard. So, what is the point of having that bar behind the nut?
Answer: It's a part of the double locking vibrato system called string retainer, and its purpose is to press the strings against the nut for the entire width of the nut. The nut has three clamps that lock the strings in place by pressing them against the nut. The idea is to first tune the guitar using normal tuners, then clamp the strings at nut so that using the vibrato won't make them slide in their slots. If the strings were just leaving the nut at shallow angle on the tuner side, like they do on guitars without that bar, tightening the clamps would increase string tension and make the tuning sharp.
Comment: Surely one would consider that from the start, and position the secondary tuners (I guess they exist) accordingly.
Comment: The bar has been there from the start, because it is needed. The secondary tuners are in the bridge, and not having to use them every time after locking the strings removes one big hassle. If you are willing to read how the entire Floyd Rose setup (Ibanez had license to copy it until the patents expired) works instead of thinking yourself, there are plenty of descriptions online.
Answer: The only reason I can think of is to be able to have a consistent downward angle on the headstock side of the locking nut. Even with a tilted headstock it's possible for the strings to hit the nut at slightly different angles.
Comment: This does not really explain why the angle needs to be consistent on this guitar and why Fender and Gibson get away without one.
Comment: @ojs Fender and Gibson guitars do not typically have locking nuts. This Ibanez does. What other reason would there be for having a string tree for all 6 strings?
Comment: @JohnBelzaguy you wrote something about "consistent string angles" that doesn't sound like it's related to locking nut at all.
Answer: Going against the grain here. I don't think there's any particular reason why there has to be a bar at that point. The strings are all trapped before that point - at the nut, and securely, too.
On other guitars - mainly those with 6 in a line tuners, although I have a couple of 3 a side tuner guitars with them - it's to hold down the strings, especially the top one, from popping out of the nut slot, as it's quite shallow.
But with a locking nut, that's never going to happen, as the bar on top clamps the strings to the fretboard underneath.
More a matter of belt and braces, for my money. And to stop new strings from flailing around when changing. Proof of the pudding would be to use an Ibanez for a while without it - or better still, direct the question to Ibanez themselves.
Comment: https://hazeguitars.com/blog/locking-nut-string-retainer-bar-adjustment
Comment: true, if you start your string wind at the top of the bobbin and work it down, but having had an ibanez just like this, if you wind randomly then a string that finishes at the top of the bobbin does not sit flush with the locking nut surface and so can be sent sharp when clamping down. The retainer bar removes this likelihood
Comment: @bigbadmouse - guess I didn't consider that, as I always wind downwards as a matter of course, whatever the guitar/bass. Just seemed a sensible way.
Comment: *experienced* people do, beginners do not know it and there's nothing more off-putting for a newbie than unexplained detrimental changes the moment you try and do something yourself, like change the strings.  **"I broke it"** isnt something Ibanez want people saying about their new shiny guitar. My only note of criticism of them is that the string end tends to dig into the headstock paint as you pass it under, I learned to put a little bend on it first.
Comment: @bigbadmouse - just wonder how many beginners would be using a 2 grand + guitar like this one!
Comment: It was also on the Jem look-a-like that I had
Comment: @Tim now that the Floyd Rose patents have expired, there are €130 Harley Bentons that have double locking vibratos.
Comment: Would it have been that difficult to just look for setup instructions that would tell what the bar is?


How to delete cache after updating/deleting/adding new content using hooks?

Question: We have a custom services module and a site in Drupal 7, and I got the task to delete the cache after the editor adds new content or update the existing ones.
I've read about a module called Cache Actions, but, as i said, i need to create the function on my custom module.
Also, I've started reading about Drupal hooks, but still don't have a clue of how to implement this task. Any suggestions? Thanks.
Comment: This could be implemented in a few ways. How often does your editor update/delete/add new content?
Comment: Very often, because we use drupal as the manager of the data to make web services for mobile apps. I couldn't tell you exactly how frequently we add or modify data, but the main request is to clear the cache every time a change happens.
Answer: It sounds like you've already got a custom module, but just in case you haven't see the Module Developer's Guide.
The hooks you're looking for are hook_node_insert() and hook_node_update(), and the function to clear the cache will either be cache_clear_all() or drupal_flush_all_caches. The former will let you clear specific cache bins (and even specific cache items), and the latter will clear absolutely everything.
For example:
function MYMODULE_node_insert($node) {
  drupal_flush_all_caches();
}

or to clear only the static page cache after a node has been updated:
function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}

Comment: It goes in your own module file, hacking core files is a big no-no in Drupal :)
Comment: Ok, i understand it. Just one more question, do i have to add the code in my .module file or in the node module file of drupal?
Answer: You can easily clear specific node cache after updating them. Ex. :
function MYMODULE_node_update($node) {
  $nodeurl = url('node/'. $node->nid, array('absolute' => TRUE));
  cache_clear_all($nodeurl, 'cache_page');
}

Please note that you must need to specify array('absolute' => TRUE).


Invalidate cache on ConfigFormBase submit

Question: I have a ConfigFormBase called TextConfiguration where I have defined several fields for the address, phone number, etc...
These variables are shown in the contact form on my website. When I modify them and enter as anonymous in /contact, the value is not updated.
I've tried this in my ConfigFormBase form submit, but it does not work.
<code>// Additionally, clear cache to prevent mismatch data.
$tags = $this->config(static::COMPET_SETTINGS)->getCacheTags();
if ($tags) {
  Cache::invalidateTags($tags);
}
</code>
I'm doing something wrong? I need to configure or do something to get it to update the data when a value is changed? Thanks all!
Edit: Example of how I'm rendering the fields.
Comment: How do you render the fields, did you add the cache tags there as well?
Comment: I'm adding the fields as markups to the $form var, in a FormAlter.
Comment: I've uploaded a photo showing how I do it.
Answer: You have to add the cache tags to the rendered output of the config field:
<code>$form['example'] = [
  '#markup' => $settings->get('name'),
  '#cache' => [
    'tags' => $settings->getCacheTags(),
  ],
];
</code>


The difference between means in t-test

Question: When the sample size is large, the results tend to be statistically significant even when there is a small difference between the means of two groups. however, sometimes we see the results are not significant, despite the fact that the difference between the means of two groups is small with a large sample size. Can anyone describe its reason within a simple approach? Many thanks
Comment: It also depends on the variability in the groups.
Answer: The explanation is in the formula for the t statistic:
$t = \frac{m_a-m_b}{\sqrt{S^2/n_A + S^2/n_b}}$
The numerator is the difference in means. The denominator is the variation in the groups. So, you can have different t statistics for the same difference in means with the same sample size, depending on how much variation there is in each group.
If you would like a very intuitive explanation with no math, I wrote one about ANOVA (and a t-test is an ANOVA with only two groups and one IV). Very briefly, the t test compares variation between groups to variation within groups.
Comment: Peter has done an excellent job identifying the intent then; I could not discern it from your question. You seek an example of what, exactly? Note that there are examples of using t-tests in R (whether Welch or ordinary equal-variance t-test or one-sample t-test / paired t-test in the help - see `?t.test` and scroll down)
Comment: Is that the Welch statistic you're discussing?
Comment: @Glen_b, Yes, the Welch statistic. it is very useful if you give me an example using R

The difference between means in t-test


probability expressed as an exponent

Question: I have been trying to understand some complex probabilities expressed using exponents.  I am used to treating probabilities as logits.  I obtained a result I was not expecting with exponents and am hoping someone might offer an explanation for the following simple example.  I realize this must be a very remedial request.  The probabilities in question come from fisheries.
A <- 0.10
B <- 0.75

# Presumably this is the instantaneous probability of A.
# An example is the instantaneous probability of mortality of fish with constant fishing
pA.exp <- exp(-A)
pA.exp
#[1] 0.9048374

# Presumably this is the instantaneous probability of A then B.
pAB.exp <- exp(-(A * B))
pAB.exp
#[1] 0.9277435

# I was not expecting this product to equal pA.exp above but it does
pA2.exp <- exp(-(A * B)) * exp(-(A * (1 - B)))
pA2.exp
#[1] 0.9048374

# I was expecting this sum would equal pA.exp but it does not
pA3.exp <- exp(-(A * B)) + exp(-(A * (1 - B)))
pA3.exp
#[1] 1.903053

As mentioned above I am far more familiar with probabilities expressed as logits and provide an example of what I had been expecting with the above exponents.
# probability of A
pA.logit <- exp(A) / (1 + exp(A))
pA.logit
#[1] 0.5249792

# probability of B
pB.logit <- exp(B) / (1 + exp(B))
pB.logit
#[1] 0.6791787

# I understand the probability of A and B
pA.logit * pB.logit
#[1] 0.3565547

# I understand this sum equals pA.logit
pA.logit * pB.logit + pA.logit * (1 - pB.logit)
#[1] 0.5249792

I realize my request for an explanation of pA2.exp and pA3.exp is very remedial, but it would also be very helpful.
EDIT
My original question was why does this relationship hold:
exp(-A) == exp(-(A * B)) * exp(-(A * (1 - B)))
#[1] TRUE

The following was originally intended as an answer.  However, it is more accurately a detailed demonstration that the relationship does hold rather than an explanation for why it holds.  So, I have moved my answer to here and deleted the answer itself.
A <- 0.10
B <- 0.75
n <- 100

# instantaneous probability of survival
pA.alive <- exp(-A)
pA.alive
#[1] 0.9048374

# instantaneous sequential survival probability of A then B
pA2.alive <- exp(-(A * B)) * exp(-(A * (1 - B)))
pA2.alive
#[1] 0.9048374

# instantaneous probability of mortality
pA.dead <- 1 - exp(-A)
pA.dead
#[1] 0.09516258

# instantaneous sequential mortality probability of A then B
pA2.dead <- 1 - exp(-(A * B)) * exp(-(A * (1 - B)))
pA2.dead
#[1] 0.09516258

nA.dead <- n * pA.dead
nA.dead
#[1] 9.516258

nA2.dead <- n * pA2.dead
nA2.dead
#[1] 9.516258

ndead.AB <- n * (1 - exp(-(A * B)))
ndead.AB
#[1] 7.225651

ndead.AnotB <- (n - ndead.AB) * (1 - exp(-(A * (1 - B))))
ndead.AnotB
#[1] 2.290607

ndead.AB + ndead.AnotB
#[1] 9.516258

round(ndead.AB + ndead.AnotB, 8) == round(nA.dead, 8)
#[1] TRUE

round(ndead.AB + ndead.AnotB, 8) == round(nA2.dead, 8)
#[1] TRUE

Answer: Why does this expression hold?
A <- 0.10
B <- 0.75

exp(-A) == exp(-(A * B)) * exp(-(A * (1 - B)))
#[1] TRUE

Because that expression is simply a re-expression of:
log(X*Y) == log(X) + log(Y)

Where: X = exp(-(A * B)) and Y = exp(-(A * (1 - B)))
Take the log of both sides of this expression: exp(-A) == exp(-(A * B)) * exp(-(A * (1 - B))):
round(log(exp(-A)),8) == round(-A,8)
[1] TRUE

round(log(exp(-(A * B)) * exp(-(A * (1 - B)))),8) == round(log(exp(-(A * B))) + log(exp(-(A * (1 - B)))),8)
#[1] TRUE

So, log(exp(-A)) = log(exp(-(A * B))) + log(exp(-(A * (1 - B))))
Which equals: -A == -A * B + -(A * (1 - B))
Or: A == A * B + A * (1 - B)

probability expressed as an exponent


using certificate in AZURE asp.net websites

Question: I am moving one asp.net app to azure environement.In the application we are using one X509Certificate2 while calling some webservices.I used cert.import method to import the certificate and then adding certificate object to client certificate property of service.It was working fine when we hosted our app on IIS servers.
This is how we are doing it :
abcservice service = new abcservice ();

string CertificatePath = ConfigurationManager.AppSettings["CertificatePath"].ToString();
string certPwd = ConfigurationManager.AppSettings["CertificatePwd"].ToString();
cert.Import(CertificatePath, certPwd , X509KeyStorageFlags.DefaultKeySet);
service.ClientCertificates.Add(cert);

But when we move to azure ,it stops working and start showing me cant find specified file at cert.import .I came to know that MyStore is not working in Azure.So i am looking for some alternatives for that.I found one solution that how i can do this without using Import.
abcservice service = new abcservice ();

string CertificatePath =ConfigurationManager.AppSettings["CertificatePath"].ToString();

string certPwd = ConfigurationManager.AppSettings["CertificatePwd"].ToString();
X509Certificate2 cert = new X509Certificate2(CertificatePath , certPwd , X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
service.ClientCertificates.Add(cert);

Now it start adding certificate in service object but when i am calling service it start give me following Error :
Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectName', FindValue 'abc-123.pqr.com'.
In web.config ,we have set following properties :
<clientCertificate findValue="abc-123.pqr.com" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />

        <serviceCertificate>
          <defaultCertificate findValue="xyz Gateway" storeLocation="LocalMachine" storeName="TrustedPeople" x509FindType="FindBySubjectName" />
          <authentication certificateValidationMode="ChainTrust" revocationMode="Online" />

I have set up abc-123.pqr.com as DNS name for my website and i am able to access website using this URL and uploaded the certificate in azure portal against this URL.
Answer: If you want to use the cert on the Azure Website,
you need to add an app setting named WEBSITE_LOAD_CERTIFICATES with its value set to the thumbprint of the certificate will make it accessible to your web application. For more information, please refer to this tutorial.

Add an app setting called WEBSITE_LOAD_CERTIFICATES and set its value to the thumbprint of the certificate. To make multiple certificates accessible, use comma-separated thumbprint values. To make all certificates accessible, set the value to *.
Comment: Have you uploaded the .pfx file to the Azure webApp? You also could get the code demo from this [link](https://learn.microsoft.com/en-us/azure/app-service/app-service-web-ssl-cert-load#use-certificate-in-c-code).


Adding a custom HTML block to a view

Question: I have a view in Drupal 8 that looks as follows (see screenshot). To make the long story short, I need to make this view output a fixed HTML block (piece of code, not Drupal Block) and not pull any dynamic data from the respective content type.
What is the most efficient way of doing this?
Answer: In your screen shot, there is HEADER and FOOTER section. Click add in one of them and add a Global: Text Area, and put your HTML there, for text filter use FULL HTML.
Comment: Why make it difficult if you can K.I.S.S., right?
Answer: Output the block to the page. View the HTML source for the page. Copy the HTML for the block.
If you want to display the block on the site, then create a new block through the admin interface, and paste the HTML there.
Comment: I already have the HTML that I would like the view to display. Could you give a more step-by-step instructions on how this can be achieved?
Answer: If it helps anyone, what i ended up doing was creating a new custom Block in Drupal and pasting the needed HTML there as Full HTML format. I then placed this new Block in place of the View in question on the needed page. I did the latter on the Block Layout page.

Adding a custom HTML block to a view


SelectQuery::fields and Drupal's naming conventions - how to make it all match?

Question: Convention for database column names is underscore_notation. Convention for class properties is camelCaseNotation. But when I'm using SelectQuery::fields('t') and then fetchObject(), fetched object's properties are in underscore_notation.
I know I can use code like:
foreach($fields as $field)
    $query->addField($table_name, $field, to_camel_case($field));

That's a solution when I know fields I'm supposed to get. What if I don't? If all I want is good old SELECT * FROM {table}? Is there a simple way to fetch object compatible with Drupal's naming convention?
I know that formally, as written, convention does not apply to objects generated dynamically and returned from PDO. I want to avoid mixed namings none the less. It feels wrong to make user input $object->camelCase and give him $output->underscored_answer back. Bad as in causing errors and confusion.
Answer: What the naming conventions actually say is that "Methods and class properties should use lowerCamel naming." (my emphasis).
The properties added to the object returned by a query are not class properties. This is confirmed by the PHP documentation which defines "properties" (or "class member variables") as "defined by using one of the keywords public, protected, or private, followed by a normal variable declaration". There is no such declaration that applies here.
The object you are looking at is of type StdClass. There isn't much about the concept behind StdClass in the PHP documentation (unless I missed it), but the concept of a class-less object with dynamic fields is sometimes known as "anonymous object". You can create one in PHP by doing:
$obj = (object)(array('field' => 'value'));
echo $obj->field; // Outputs 'value'

In the case of the object returned by the query, it doesn't even have methods - it could just be an array (which it would be if you fetched your data using DatabaseStatementInterface::fetchAssoc). So we can think of anonymous objects as containers, rather than instantiations of classes to which the coding style should apply.
Since this object is a container of fields from the database, I think it makes sense for the database convention to apply. It is an object wrapper around a database row.
As a Drupal programmer, if I get a result that is essentially a database row, I will actually expect it to be in underscore notation. While it may feel wrong, it is what people are used to expect. Every time I use [node_load][4], the result I get is an object in underscore notation. Even when you use the entity meta data wrappers, which essentially are there to provide an object interface around Drupal entities, you still use the underscore notation. Changing this approach would potentially confuse other Drupal programmers.
I understand that if you are writing, say, an API which returns your own data, you may want to abstract the fact the result is a database row and present it as an object like any other (as suggested by your param vs. result example). One option, though one that has some overheads, would be to create a class to hold such result, and casting the database result object to it. This would at least make it clear that what you are returning is a proper object, not just a container around a database row. You could do something like this:
Class MyApiResult {
  function __construct($row) {
    $vars = get_object_vars($row);
    foreach ($vars as $name => $value) {
      $cc_name = to_camel_case($field);
      $this->{$cc_name} = $value;
    }
  }
}

Then your API would return:
return new MyApiResult($row);

However this has some overheads, it depends whether those will be acceptable in your particular case.
Comment: I know coder module does not blame me about `$result->some_name`. I just want to avoid mixing `$params->someName` with `$result->some_name`. No matter how formally justified it is, it just feels wrong. Long story short - I know I don't have to, but I'm asking "how", not "if".
Comment: @Mołot : I think in that case you should at least cast the result to an object of a specific class, to make it clear your result is not just a database row. See the edit to my answer.
Comment: Well, my "rows" was meant to function like a proper classes and be extendable, so now that's a way to go. Well, probably with automagic instead of foreach to only convert properties that are actually used, but that's just an implementation issue.

For the overheads - I expect writes couple times a week and reads will be cached and possibly boosted, so it's not a problem. Last but not least - cpu is cheap in comparison to time.

For developers that are used to get it old way, we are not planning on unsetting underscored properties.
Answer: I've mucked to much with PDO and Drupal -- try this it out and let us know :).
The database layer in Drupal uses PDO. You can fetch results to a custom class typically by setting the FETCH_MODE .... welllll I was gonna link you here Fetching into a custom class
But, it looks the answer is more simple but probably doesn't buy you much. But maybe you'll find this helpful. Read on ...
You just need to tell PDO to respect the case semantics of your SQL statement for your queries (trying to do this on all queries in drupal, see below, will probably blow chunks).
Relevent Additional Documentation is here:

https://stackoverflow.com/questions/9438860/php-pdofetch-class-is-mapping-to-all-lowercase-properties-instead-of-camelcase
http://php.net/manual/en/pdo.setattribute.php
https://drupal.org/node/726192
(I replied here and use Migrate alot with funky PDO tweaks ...) Drush Fails to Connect to MySQL DB Server Using PDO SSL Options

I think you'd have to write your queries similar to:
// This gets the default drupal database connection, you can pass parameters to
// select alternate dbs defined in settings.php
$db = Database::getConnection();
// This tells PDO to use the case of the raw SQL statement allowing you to write:
// SELECT foo_bar AS fooBar, some_other_property AS someOtherProperty ...
// and they will return in your fetchObject object as camelCased (natual, whatever you AS'd as case) ...
$db->setAttribute( PDO::ATTR_CASE, PDO::CASE_NATURAL );
// This is the long route of writing db_select('table')->fields() ...
// caveat the db_select->fields() method doesnt allow aliasing, you have to
// add fields to your query via addField()
$query = $db->select('some_table', 'some_table_alias');
// Then add to your select query as needed.
$query->addField('some_table_alias', 'foo_bar', 'fooBar');

Some other notes:

Without getting reallllly creative I dont think you can do this using db_query(). db_query() is a simple helper method to the default database connection (not any db) and I'm not sure you can Database::getConnection()->query("...");
You could try to set this globally in drupal in your settings.php by using a patch https://drupal.org/node/726192 to allow abritrary PDO attributes to be set on the database connection defined in settings.php. I dont recommend this.
Comment: setAttribute was half of an answer, thank you. Second half, avoiding using addField and explicitly stating all fields needed, is still unanswered. I kinda hoped renaming can be done at Drupal side. Fetching into a custom class and magic methods can be an answer. Or at least close enough.
Comment: @Molot yea i linked the the custom class stuff in ... beyond that the 2 concepts i've listed above are the only means i'm aware of to achieve this. just play with it ... gluck.


Finding if $\frac{-yi+xj}{x^2+y^2}$ is a conservative field

Question: Let $\frac{s}{r}$ be a vector field such that: $s=-yi+xj,r=\sqrt{x^2+y^2}$

Is $\frac{s}{r}$ a conservative field?

My attempt:
$\frac{s}{r}$ is a conservative field $\iff \displaystyle\oint F\cdot dr=0$
$$\frac{s}{r}=\frac{-y\hat i+x\hat j}{\sqrt{x^2+y^2}}$$
$$\boxed{=\frac{-y}{\sqrt{x^2+y^2}}\cdot \hat i+\frac{x}{\sqrt{x^2+y^2}} \cdot \hat j }$$
Let $Q:=\frac{x}{\sqrt{x^2+y^2}}$ , let $P:=\frac{-y}{\sqrt{x^2+y^2}} $
$\frac{s}{r}$ is a conservative field $\iff \frac{\partial Q}{\partial x}=\frac{\partial P}{\partial x}$
Finding $\frac{\partial Q}{\partial x}$: $\color{blue}{\frac{\partial Q}{\partial x}=\frac{y^2}{(x^2+y)^{3/2}}}$
Finding $\frac{\partial P}{\partial x}$: $\color{blue}{\frac{\partial P}{\partial y}=-\frac{y^2}{(x^2+y)^{3/2}}}$
$\Longrightarrow \frac{\partial P}{\partial x} \neq \frac{\partial P}{\partial x}$  therfore $\frac{s}{r}$ is not conservative field.

Is it correct?
Answer: The usual way to show that a particular vector field is not conservative is to take the line integral around a closed loop and see that the result is not zero.
For your field, taking the line integral around the unit circle gives a value of $2\pi$, so the field is not conservative. In fact, your field and that line integral are (almost) the examples given by Wikipedia for a non-conservative field.


Error getting response stream (ReadDone2): ReceiveFailure

Question: I am using the below code for fetching data from live server...
try
            {
    var httpReq = (HttpWebRequest)HttpWebRequest.Create(new Uri(url_builder.ToString()));
                httpReq.BeginGetResponse((ar) =>
                {
                        var request = (HttpWebRequest)ar.AsyncState;

                        using (var response = (HttpWebResponse)request.EndGetResponse(ar))
                        {

                            //Enter Code here............................

                            response.Close();
                        }
                });
                }, httpReq);
 }
            catch (Exception ex)
            {
                Global.EmailExceptionMessage(ex);
            }

And getting inner exception i.e.
Inner Exception:   at System.Net.WebConnection.HandleError(WebExceptionStatus st, System.Exception e, System.String where)
   at System.Net.WebConnection.ReadDone(IAsyncResult result)
Comment: what is the actual message on the InnerException?
Answer: You can try this one code to get httpresponse.
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        WebHeaderCollection header = response.Headers;
        var encoding = ASCIIEncoding.ASCII;
        using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
        {
            string responseText = reader.ReadToEnd();
        }

Comment: Ok @Umesh Sehta your code is good but i want to know that what wrong with my code because it emit exception some time and other time it working fine.....Please help me if you have solution using my code...
Comment: The actual problem is that the code is working fine approx 9 time out of 10 and only 1 time it give exception to me..... @Umesh Sehta


Are Guitar Patterns an Absolute Necessity for Improvisation?

Question: Box Patterns
I learned to play guitar like everyone else using box patterns. That worked for a bit. The boxes were getting in my way of "true musical improvisation". Usually making it hard to connect box one to box 4 unless I used the same lick or slide.
Intervals
Then I decided to learn intervals. That worked for a bit. I am able to find scale tones relatively fast by locating the root - and that's the problem. I can only play notes adjacent to the root... Why? Because it seems like a massive undertaking to learn the distance between every combination of interval in a scale; not to mention it would be impossible to solo thinking about every distance of interval.
No one speaks thinking of words. Everyone thinks in phrases, which seems box patterns would then be a better solution.
What to do?
I thought maybe I should learn licks for different interval combinations in order to have more interval combos under my belt - but... how is this different to just using the dang box patterns?
Should I just use pattern boxes while being aware of the underlying intervals? Seems like this solution would too limit my ability.
So... what is the ultimate way to improvise guitar with complete freedom and not let the guitar boxes and intervals play me?
Comment: Are you aware of the CAGED system? I'd assume so, but just checking....
Comment: "The boxes were getting in my way of "true musical improvisation" Really? I think you got it backwards.  They lead to true musical improvisation.  Listen to players you like and transcribe there solos.  That can teach you how one would approach improvising over progressions. Many solos are based on box pattern shapes.
Answer: The simple answer is that you do all of that and more. I guess you don't have to but the chances of being a good improviser without working out your ears and fingers will be greatly diminished.
First, understand that there's not exactly "true improvisation" because everything you might play is based upon things you've heard or learned before. A common refrain in teaching improv is to "play what you hear" and that's good advice. But "what you hear" doesn't come from some magical creative vacuum. It's based on things you've already learned, music you've listened to and the idiomatic patterns in it, and the underlying harmony.
So when you practice things like "box patterns"—which btw don't have to be single position boxes, there are linear/horizontal/diagonal patterns as well—or intervals what you are doing is getting those patterns and sounds drilled into your brain. And most importantly you are connecting the sound and theory of all that to your muscle memory. This improves both "what you hear"—your capacity for imagining appropriate melodies—as well as your ability to quickly get your fingers to play those melodies.
As for what you should practice, the answer is to practice as much as you can with as much variety as possible. Variety is key to having flexibility in how you move around and think about the fretboard. Here's a non-exhaustive list of ideas off the top of my head in no particular order:
(This doesn't cover everything you'd want to study or practice for improvisation, but just the fretboard work. You'd also want to work in some theory work, ear training, and a lot of learning, listening, and transcribing of tunes)

Sing/say the note name or interval or scale degree or whatever you're trying to learn while you play it.
The chromatic scale. Yes that's all the notes which doesn't sound helpful but practicing playing up and down the neck using as many different "pathways" as you can is actually pretty helpful for breaking out of position-based boxes as you mentioned.
Scales and associated modes (major, melodic minor, harmonic minor, pentatonic, diminished scales, whole-tone, etc, etc)
Triad arpeggios including all inversions
7th chord arpeggios including all inversions
Intervals. Not just 2 notes. Try playing a particular interval all the way up and down the neck as well.
Chord voicings (triads, 7ths, drop voicings, etc, etc). Go beyond just using these shapes for comping and try to relate them to your melodic work. Play the chord and then work on the melodic structures contained and surrounding them.
Idiomatic patterns - licks and patterns popular in a given genre, transcribed solos, techniques like enclosures, sequencing, or whatever.

The take those patterns and more and find ways to mix it up.

Play both ascending and descending
Mix up the order with inversions or starting from the middle of a pattern rather always using the root.
Mix 2 or more scales or patterns together. For instance play 1 bar of one scale and switch to the nearest note of another scale on the downbeat of bar 2.
Play in several directions. Rather than just playing "box patterns" try connecting the boxes linearly (horizontally/diagonally). And also try playing on a single string sometimes.
Pick a different starting point and order for anything you can. Don't always start in key of C and then G, etc. Use the circle of 5ths but not always, mix it up. Don't always start low on the neck and move up to higher positions. Mix up every aspect you can think from day to day.
When playing licks/patterns, learn them in as many positions and registers as possible. And play them in all keys. Ideally you should be able to play the lick from wherever you happen to be on the fretboard. This is not only good for the sake of recalling the lick, but it helps you learn the fretboard.

Lastly, try not to think of any fretboard work you do as a task to complete. It's not as if you'll suddenly be a great improviser once you've learned all the scales. Think of it more like an athlete working out in the gym each day. They're never "done" working out nor does working out replace what they do on the actual field. So do your fretboard workout a bit each day trying to push yourself and become more flexible and it will come out in your playing during the real work—playing over actual changes in an actual song.
Comment: Great answer. Most folk probably wouldn't live long enough to complete everything here, but here goes..! +1.
Answer:
what is the ultimate way to improvise guitar with complete freedom and not let the guitar boxes and intervals play me?

Practice, practice, practice. No matter what fundamental mechanical knowledge you start with to improvise, your goal will be to transcend that knowledge so that you are no longer thinking about it, but you are more intuitively following (or leading) the music.
In terms of what mechanical viewpoint is best to base your practice on, I suggest that you should learn multiple ways to view the fretboard for improvisation, and work on combining the different patterns.
Even though no adult thinks of individual words while speaking (well sometimes we do, but your analogy is valid), when a child is learning to speak, they learn one word at a time. So must you learn improvisation. Learning intervals and box patterns and scales and arpeggios and licks are all valid, and ideally you would pursue all of those methods to a greater or lesser extent. You'll know it when it starts to become automatic and eventually you won't have to focus on the "individual words" of improvisation.
Comment: this is what grasped from your response. "use box patterns while being aware of intervals and someday, hopefully, they'll merge together. :) many thanks, by the way.
Comment: @user3704920 I meant to say that they **will** merge together. Not "hopefully", definitely.
Comment: @user3704920 There isn't a simple solution.  Like Todd said, practice, practice, practice.  People spend 12 hours a day to do this stuff.


Underscore is added to links in view

Question: I'm writing a workaround to fix the breaking changes introduced to our XML feed when we updated from Drupal 8.4 to 8.5. Since PATH is no longer available but has been replaced with LINK, I've had to craft the Rewrite Results to be /news/{{ view_node }}, which displays a properly formatted URL in the preview:
<link>http://sitename.com/news/article-title</link>

However, in the actual XML feed, it comes out like this:
<link>http://sitename.com/news/article-title_</link>

arbitrarily adding an underscore and breaking the URL. Is there a way to make this not happen?
Comment: +1 for having created the issue on drupal.org ([link](https://www.drupal.org/project/drupal/issues/2987954)).
Answer: After much work I came up with a workaround. My first thought was to add a Twig filter to views-view-row-rss.html.twig like so <link>{{ link | replace('_', '') }}</link> but the underscore was still being displayed, which told me that either 1. the Twig filter wasn't working or 2. the underscore was being applied later in the render process.
The Twig template's documenation made reference to a template_preprocess_views_view_row_rss() hook I found implemented in /core/modules/views/views.theme.inc so I added the following hook to my custom.theme PHP file:
function ncei_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
   $variables['title'] = $item->title;

   //$variables['link'] = $item->link;
   $variables['link'] = str_replace("_", "", $item->link);

   if (isset($item->description) && is_array($item->description)) {
     $variables['description'] = (string) \Drupal::service('renderer')-
       >render($item->description);
   }

 $variables['item_elements'] = [];
 foreach ($item->elements as $element) {
   if (isset($element['attributes']) && is_array($element['attributes'])) {
     $element['attributes'] = new Attribute($element['attributes']);
   }
   $variables['item_elements'][] = $element;
 }
}

I commented out the original line above for reference, but I'm setting the link variable to the item's link, stripped of all undertscores. This isn't the best solution, and will break if the link actually contains underscores, but it worked as a temporary workaround in the meantime.

Underscore is added to links in view


Has anyone achieved true differential sync with rsync in ESXi?

Question: Berate me later on the fact that I'm using the service console to do anything in ESXi...
I've got a working rsync binary (v3.0.4) that I can use in ESXi 4.1U1.  I tend to use rsync over cp when copying VM's or backups from one local datastore to another local datastore.  I've used rsync to copy data from one ESXi box to another but that was just for small files.
In now trying to do true differential syncs of backups taken via ghettoVCB between my primary ESXi machine and a secondary one.  But even when I do this locally (one datastore to another datastore on the same ESXi machine) rsync appears to copy the files in their entirety.  I've got two VMDK's totally 80GB in size, and rsync still takes anywhere between 1 and 2 hours but the VMDK's aren't growing that much daily.
Below is the rsync command I'm executing.  I am copying locally because ultimately these files will get copied onto a datastore created from a LUN on a remote system.  Its not an rsync that'll be serviced by an rsync daemon on a remote system.
rsync -avPSI VMBACKUP_2011-06-10_02-27-56/* VMBACKUP_2011-06-01_06-37-11/ --stats --itemize-changes --existing --modify-window=2 --no-whole-file
sending incremental file list
>f..t...... VM-flat.vmdk
 42949672960 100%   15.06MB/s    0:45:20 (xfer#1, to-check=5/6)
>f..t...... VM.vmdk
         556 100%    4.24kB/s    0:00:00 (xfer#2, to-check=4/6)
>f..t...... VM.vmx
        3327 100%   25.19kB/s    0:00:00 (xfer#3, to-check=3/6)
>f..t...... VM_1-flat.vmdk
 42949672960 100%   12.19MB/s    0:56:01 (xfer#4, to-check=2/6)
>f..t...... VM_1.vmdk
         558 100%    2.51kB/s    0:00:00 (xfer#5, to-check=1/6)
>f..t...... STATUS.ok
          30 100%    0.02kB/s    0:00:01 (xfer#6, to-check=0/6)

Number of files: 6
Number of files transferred: 6
Total file size: 85899350391 bytes
Total transferred file size: 85899350391 bytes
Literal data: 2429682778 bytes
Matched data: 83469667613 bytes
File list size: 129
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 2432530094
Total bytes received: 5243054

sent 2432530094 bytes  received 5243054 bytes  295648.92 bytes/sec
total size is 85899350391  speedup is 35.24

Is this because ESXi is itself making so many changes to the VMDK's that as far as rsync is concerned the entire file has to be retransmitted?
Has anyone actually achieved actual diff sync with ESXi?
Comment: rsynce is incremental by default. Hard to beleive, but true. I'm curious where you go the download for rsynce that works on ESXi. I have ESXi 4.1
Answer: It looks like you've only transferred 2GB of incremental changes. Remember that rsync still has to read in one whole file and checksum it so it has to read 80GB of data. Check your server stats during the rsync. Are you cpu or IO bound during the operation? How fast can you read the 80GB file off disk? That will be near your absolute minimum transfer time.
Also of note is that rsync makes a copy of the file while transferring then moves the final file into place in an atomic operation. You can see this by seeing a similiar filename with a random suffix during the transfer in the destination directory. This means that you have to read 160GB of data (80GB each for each source and destination) and write out 80GB on the destination side. Have you looked at the --inplace option? It may be beneficial here.
In short you may only have 2GB of changes but rsync is doing LOTS of work. You're probably IO bound as all that reading and writing on the same disk would could cause lots of contention and slowdown.
Comment: Thanks bot403 for your response.
I did notice that the bytes transferred were significantly lower, but I was still looking at a 30-45+ minute wait time.  I might as well have just re-sent the files in their entirety.  There could be an IO bottle neck here but I think that's within ESXi & not so much the hardware.  I'll move it to a LUN & test there.
Thanks so much all.
Answer: This Thread is very old, but may it help's someone.
As ESX is locking the filesystem on every write of new blocks, the performance isn't that great,
with the Option --inplace you may get better results, but be aware, if you cancel the sync, the file will not be consistent any more.
About consistency, rsync of an open file could be inconsistent any way -> better use snapshot before rsync.
Best Regards
Marc
Answer: By the looks of it, you are doing a local-to-local copy with rsync. In that case, the default behaviour of rsync is to turn off the delta-transfer algorithm, and do "whole-file" transfers. The rationale for this default behaviour is that local-to-local transfers using the delta-xfer algorithm  would usually be slower than simply copying the whole files, since the delta algorithm involves much more CPU crunching than just doing whole-file copying.
If you feel that a local-to-local copy would benefit from using the delta-xfer algorithm, you can force rsync to use it by specifying the --no-W (or --no-whole-file) option.
Comment: Thanks for the response Steven!  You're correct: I am doing a local copy purely for testing purposes (aka to confirm it'll actually do a differential sync).  Ultimately the files will get copied to a local datastore, a LUN that I've exposed that resides on a remote machine.  It won't actually be an rsync-to-rsync daemon type of sync.

For what its worth I am using the `--no-whole-file` option as part of the rsync command; its beyond the view of the screen.
Comment: @Julius: Whoops, I missed that horizontal scroll bar! Oh well, sorry for wasting your time.


Progressbar Thread doesn't abort after execution, application crashing -WPF

Question: I am trying to show progressbar when user is trying to login into system. Durin the operation I am showing the progressbar window to the user. I did this using a backgroundworker and it works. But sometime the system crashes. It seems windows 8 is creating the problem. Because it's running in Windows 7 without any error.Here is my loadingview.xaml.cs code which contains the progressbar related code
public partial class LoadingViewControl : Window
{
    System.ComponentModel.BackgroundWorker mWorker;

    public LoadingViewControl()
    {
        InitializeComponent();
        Load();
    }

    public LoadingViewControl(bool Close)
    {
        this.Close();
    }
    public void Load()
    {
        mWorker = new System.ComponentModel.BackgroundWorker();
        mWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(worker_DoWork);
        mWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(worker_ProgressChanged);
        mWorker.WorkerReportsProgress = true;
        mWorker.WorkerSupportsCancellation = true;
        mWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        mWorker.RunWorkerAsync();

        while (pbProcessing.Value < 99)
        {
            if (!mWorker.CancellationPending)
            {
                try
                {
                    if (pbProcessing.Value > 95)
                    {
                        mWorker.CancelAsync();
                        //Uri uri = new Uri("/View/LoginchildView.xaml", UriKind.Relative);
                        break;
                    }
                    else
                    {
                    pbProcessing.Value = (pbProcessing.Value + 0.005) % 100;
                    }
                }
                catch (System.Exception ex)
                {
                    // No action required
                }
            }
            else
            {
                break;
            }

            System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background,
                                   new System.Threading.ThreadStart(delegate { }));
        }
    }

    private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        // Do your work here, its on seperate thread
    }

    private void worker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
    {
        pbProcessing.Value = e.ProgressPercentage;
    }

    private void worker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
    {
        // Stop Progressbar updatation
    }

    private void LoadingViewControl_Load(object sender, EventArgs e)
    {
        SetFocus();
    }

    public void SetFocus()
    {
        this.Focus();
        this.Activate();
    }
}

Now I am showing you my Loginviewform.xaml.cs code which implements the progressbar.
        if (txtUserName.Text != "")
        {
            if (txtPassword.Password != "")
            {

                if (STAThread == null)
                {
                    STAThread = new Thread(() => { new LoadingViewControl().ShowDialog(); });
                    STAThread.SetApartmentState(ApartmentState.STA);
                    STAThread.IsBackground = true;
                    STAThread.Start();
                }
                else
                {
                    STAThread.SetApartmentState(ApartmentState.STA);
                    STAThread.IsBackground = true;
                    STAThread.Start();
                }

                result = User.Instance.Authenticicate(txtUserName.Text, txtPassword.Password);
                if (result == true)
                {

                    pbProcessing.Value = 100;
                    ServiceLocator.Current.GetInstance<ContainerViewModel>().ExecuteLobbyBasicViewCommand();

                    //redirect on specific page.
                    if (STAThread.IsAlive)
                    {
                        Thread.CurrentThread.Interrupt();
                        STAThread.Interrupt();
                        STAThread.Abort();
                        STAThread = null;
                    }
                    PopUp objpopup = new PopUp();
                    objpopup.txtNotice.Text = "sign in";
                    objpopup.txtMessage.Text = "successfully sign in.";
                    objpopup.ShowDialog();
                    Global.GetUserName = txtUserName.Text;
                }
                else
                {
                    //MessageBox.Show("Sign In was unsuccessful. Please correct the errors and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);

                    STAThread.Abort();
                    STAThread = null;
                    PopUp objPopUp = new PopUp();
                    objPopUp.txtNotice.Text = "Error";
                    objPopUp.txtMessage.Text = "Sign In was unsuccessful. Please correct the errors and try again.";
                    objPopUp.ShowDialog();
                    txtUserName.Focus();
                    //pbProcessing.Value = 0;
                    stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
                }
            }
            else
            {
                //MessageBox.Show("Please enter the valid Password.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                PopUp objPopUp = new PopUp();
                objPopUp.txtNotice.Text = "Error";
                objPopUp.txtMessage.Text = "Please enter the valid Password.";
                objPopUp.ShowDialog();
                txtPassword.Focus();
                stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
            }
        }
        else
        {
            //MessageBox.Show("Please enter the valid Player ID.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            PopUp objPopUp = new PopUp();
            objPopUp.txtNotice.Text = "Error";
            objPopUp.txtMessage.Text = "Please enter the valid Player ID.";
            objPopUp.ShowDialog();
            txtUserName.Focus();
            stackpanelLoading.Visibility = System.Windows.Visibility.Hidden;
        }

Any idea what is going wrong? Any help would be appreciated.Thanks
Comment: It crash during running.At STAThread.Abort();, actually it is not aborted, thread still alive.
Comment: Have you declared it as a background-thread? So it will be disposed of, when you shutdown your main-thread.
Comment: you mean this?  STAThread.IsBackground = true; i have set this property equals to true
Comment: When you call Thread.Interrupt() you'll need to catch a `ThreadInterruptedException`; I can't see any `try/catch` here at all...
Comment: without interrupt() its working,but sometimes it crashes during running and also thread is still alive.
Comment: What does your debugger say?
Comment: a) don't run ShowDialog on another Thread, b) don't Abort() threads.
Comment: so how should i open that showdialog without using thread?
Comment: You need a major rethink... The login should be simple event-driven, major work can go in a Bgw. For the Pb you only need a Timer. Keep it simple.
Comment: its crashes the application at the time of abort and other work perfectly
Comment: I don't have a fix for your current code but it looks way too complicated. I suspect you don't need any threads, certainly not the STA one. Try a question like: I want to have a login-form that ..."
Comment: How i show loadingviewcontrol without create a new thread?
Answer: It's very strange code. Try refactor it like this:
public partial class LoadingViewControl : Window
{
    public LoadingViewControl(string userName, string password)
    {
        InitializeComponent();
        Initialize(userName, password);
    }

    private void Initialize(string userName, string password)
    {
        pbProcessing.IsIndeterminate = true;
        var thread = new Thread(() =>
                                    {
                                        DialogResult = User.Instance.Authenticicate(userName, password);
                                        Close();
                                    });
        thread.IsBackground = true;
        thread.Start();
    }
}

And some method :
public void Do()
        {
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                if (string.IsNullOrEmpty(txtPassword.Password))
                {
                    var view = new LoadingViewControl(txtUserName.Text, txtPassword.Password);
                    result = view.ShowDialog();
                    if (result == true)
                    {
                        ServiceLocator.Current.GetInstance<ContainerViewModel>().ExecuteLobbyBasicViewCommand();
                        PopUp objpopup = new PopUp();
                        objpopup.txtNotice.Text = "sign in";
                        objpopup.txtMessage.Text = "successfully sign in.";
                        objpopup.ShowDialog();
                        Global.GetUserName = txtUserName.Text;
                    }
                    else
                    {
                        //MessageBox.Show("Sign In was unsuccessful. Please correct the errors and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        PopUp objPopUp = new PopUp();
                        objPopUp.txtNotice.Text = "Error";
                        objPopUp.txtMessage.Text = "Sign In was unsuccessful. Please correct the errors and try again.";
                        objPopUp.ShowDialog();
                        txtUserName.Focus();
                        stackpanelLoading.Visibility = Visibility.Hidden;
                    }
                }
                else
                {
                    PopUp objPopUp = new PopUp();
                    objPopUp.txtNotice.Text = "Error";
                    objPopUp.txtMessage.Text = "Please enter the valid Password.";
                    objPopUp.ShowDialog();
                    txtPassword.Focus();
                    stackpanelLoading.Visibility = Visibility.Hidden;
                }
            }
            else
            {
                PopUp objPopUp = new PopUp();
                objPopUp.txtNotice.Text = "Error";
                objPopUp.txtMessage.Text = "Please enter the valid Player ID.";
                objPopUp.ShowDialog();
                txtUserName.Focus();
                stackpanelLoading.Visibility = Visibility.Hidden;
            }
        }

That's method looks ugly and you must refactor it to. But i just want to show main idea