How to count with two "HAVING" situation in sql?

Question: I need to count how many id_no does have ALL line_number with test_activity = approved and test_status = completed and filtered by work_type which is B.
id  id _no  line_number   work_type   date        test_activity     test_status
P   P-01       1               b      2020-02-02    approved          completed
P   P-01       2               b      2020-02-02    approved          completed
P   P-01       3               b      2020-02-02    approved          completed
P   P-02       4               b      2020-02-02    approved          incompleted
P   P-02       5               b      2020-02-02    approved          incompleted
P   P-02       6               b      2020-02-02    approved          completed
Q   Q-01       7               b      2020-02-02    in progress       incompleted
Q   Q-01       8               b      2020-02-02    in progress       incompleted
Q   Q-01       9               b      2020-02-02    not started       incompleted
Q   Q-02      10               b      2020-02-02    approved          completed
Q   Q-02      11               b      2020-02-02    approved          completed
Q   Q-02      12               b      2020-02-02    approved          completed

I tried:
select date, count(*) as count
from (select id, id_no, date
      from pt_pretest pp where work_type = 'b'
      group by id, id_no, date
      having min(test_activity) = max(test_activity) and min(test_activity ) = 'approved'
      and having min(test_status) = max(test_status) and min(test_status) = 'completed'
      ) as x group by date

But it did not work. From the sample above, the expected result is:
id   date         count
P    2020-02-02     1
Q    2020-02-02     1

How should I write my query so I will the expected result?
Thankyou
Comment: What does "But it did not work" mean? Did you get an error? If so, which error message? Or did you get an unexpected result? If so, in which way was it different from what you expected?
Comment: And what is it you really want to count? You say you want to count how many id_no are approved/completed only. But then you also group by id and date. And then you create a query that counts such id_no per date. And then you show an expected result that does not only contain a date, but also an id. That is four different things.
Answer: There is one having too many in your query. Remove it.
select id, id_no, date, count(*)
from pt_pretest pp
where work_type = 'b'
group by id, id_no, date
having min(test_activity) = max(test_activity) and min(test_activity ) = 'approved'
   and min(test_status) = max(test_status) and min(test_status) = 'completed'
order by id, id_no, date;

Answer: The following returns all ids that have at least one id_no that fails the condition:
select id, count(*)
from (select id, id_no
      from t
      where not (test_activity = 'approved' and test_status = 'completed')
      group by id, id_no
     ) ii
group by id;

If you want zeros in the result set, use conditional aggregation in the subquery:
select id, count( num_bad > 0 )
from (select id, id_no,
             sum( not (test_activity = 'approved' and test_status = 'completed') ) as num_bad
      from t
      group by id, id_no
     ) ii
group by id;


How can I see full server request to track suspicious requests?

Question: I have very bad luck with spammers. Even though I employ both reCAPTCHA, Spamicide and BOTCHA, I get about one spammer per day, though 300 are blocked. I guess that's a pretty good ratio, but it still justifies me having to manually authorize new user accounts.
My website gets about 30K requests per day (as per access logs) of which 500 are POST requests. It runs on Drupal 6, though we are soon moving to 7.
I want to be able to see what the spammer sends when they make the request. Ideally, I would like to see the reCAPTCHA challenge they saw and what they wrote down. I'll be good with only the postdata, though.
Is there a way to achieve this using triggered rules? Is there a module which will allow me to do so (i.e. send the full request to log/email?)
Comment: Hello. To see full server request, you probably should work one level lower, at the webserver or gate step. So how is this question really Drupal related? How it would be different if you were using Wordpress or Joomla?
Comment: It's Drupal related since I want to achieve this in Drupal. Any solution would have to do with using either Drupal API or PHP.
Answer: I can't think of a module that would do this for all the different anti-spam modules. I know that the CAPTCHA module implements this for its own fields.
An alternative is a simple custom module that implements hook_form_alter to target the the desired form, adds a new submit handler to the form and store the submitted information using watchdog.
Comment: Thanks for the Drupal API way. I found out in the meantime that BOTCHA has a logging level to allow just that. Perhaps one day I'll write this module, but not today.
Comment: Thanks. I'll have a look at that BOTCHA logging as well. I'm especially curious since it doesn't offer a challenge similar to that of CAPTCHA.
Answer: This is not a general solution, but it works under the configuration specified.
BOTCHA has a logging option which also logs server variables (under /admin/user/botcha, 'Log Level'). What's more, it will log the post data, so you can get both the reCAPTCHA challenge code and response.


Covering vector space over finite field by subspaces

Question: In the course of investigating this problem, I needed to use the following fact: If $T,W$ are proper subspaces of a vector space $V$, then $T\cup W$ is not the entire space $V$.  Provided $V$ is a vector space over the $\mathbb{R}$ or $\mathbb{C}$, this is trivial, and in fact the analogous statement holds for any finite number of subspaces.  You can see this to be true using e.g. the fact that the measure of a proper subspace intersected with a ball of radius 1 is zero, so the union of any finite (or countable) number of subspaces can't fill the ball.
However, to prove this fact using only ideas from linear algebra is surprisingly subtle.  The reason is that the generalized claim is false for vector spaces over general fields, e.g. finite fields.  For instance, the vector space $\mathbb{F}^2_2$ over the finite field $\mathbb{F}_2$ can be decomposed as a union of three proper subspaces.
This leads me to the following question: For a vector space $V$ of dimension $n$ over a finite field $\mathbb{F}_{p^q}$, what is the minimum number $m$ of subspaces $W_1,\dots,W_m$, each of dimension $k$ (with $k<n$), such that $V = \cup_{j=1}^m W_j$?

Edit: For what it's worth, here's a proof that two proper subspaces $T,W$ of $V$ can never have union equal to $V$:
$T$ proper means there is some $v\in V$ with $v\notin T$.  Then $T$ and $T+v$ are disjoint.  If $T\cup W = V$, then all $w\in v+T$ lie in $W$, and in particular $v\in W$.  But this means that for any $t\in T$, both $v\in W$ and $t+v\in W$, hence $t\in W$, hence $T\subset W$, hence $T\cup W = W = V$, contradicting that $W$ is a proper subspace.
This shows that the $m$ sought above must be greater than 2.
Comment: I'm inclined to call this a duplicate [of this older question](https://math.stackexchange.com/q/60698/11619). But, because I answered that one I should not initiate the closure process.
Answer: There's an answer without an hypothesis on the dimension of the subspaces, thanks to this result:

If a vector space over a field $F$ is the union of $n$ proper subspaces, then $|F|\le n-1$.

For a proof, you can look at my answer to this question.
Thus  for a finite field $\mathbf F_q$, where $q$ is some prime power $p^r$, we must have
$$n\ge p^r+1.$$
Comment: Very cool.  To put this in the notation of the OP, it proves that $m\geq p^q+1$.  I wouldn't call this an answer, but it is a nice bound.


Remove DOM element from variable with jquery

Question: Please help me solve this:
I have got this:
var text='
Job 1
'+
         '
Job 2
'+
         '
Job 3
';

and I want to remove one element, something like this:
$("#job2",$(text)).remove();

this doesnt work. Is there a way how to do it? thanks.
EDIT:
And I want to save result back to text:
 text='
Job 1

Job 3
';

Answer: your var text is just a variable that's holding a string

Job 1

Job 2

Job 3

And string is not an object so you cannot use .remove()

But once you do for eg:
$('#someElement').append(text);
than you can simply do:
$('#job2').remove();
and retrieve your new string using:
text = $('#someElement').html(); // '
Job 1

Job 3
'

Comment: Owwww yeah. Thanks a lot I need this.
Comment: But once you wrap it in `$()` it will become jQuery object.
Answer: Try like this...
*Update FIDDLE
My first version of code $(text).find("#job2").remove(); did't worked in jsfiddle, but when I've added

 to the code its worked like charm. I've no idea why did't worked with first instance without ul And I do not see any occasion where li will come without ul So please try like this.
var text='

Job 1
'+
         '
Job 2
'+
         '
Job 3

';

$text = $(text);
// console.log($text);
$text.find("li#job2").remove();
// console.log($text.find("li#job2"));
$('div').append($text);

Answer: if you want to remove 'job2' from text
$(text).find("#job2").remove();

Comment: And how to save the result back to the variable?
Comment: +1 for simplicity. @petkopalko, The variable `text` will contain the new (amended) string.


SQL Join query that selects rows and checks if they exist in another table

Question: Not sure if this is possible in a single query but looking to do this directly in SequelPro.
I have a table containing cars, and if they are sold or live.
I also have another table which is called data_store and contains some information about those cars. However, not all of the cars have data in this table.
To get the cars that are live is currently:
SELECT * from cars where `sale_status` = 'live'

I now need it to be like:
SELECT * from cars where `sale_status` = 'live' AND THERE IS A ROW IN THE DATA_STORE TABLE FOR THIS CARS REGISTRATION NUMBER.

There is a registration number field in each of the tables.
Thanks, still getting my head around joins.
Comment: looking up some information about join and left join will be very helpful for you. http://www.w3schools.com/sql/sql_join.asp have a read!
Answer: You want to do a simple join :
select *
from cars
join data_store on cars.registration_number = data_store.registration_number

change registration_number with whatever is the link with cars in data_store.
This will return only cars containing a row in data_store.
Comment: Perfect, I'll look into why this works and what happens. Thanks.
Comment: I think the join should be a left join since some information might be missing in the data_store table.
Comment: @A.D no, the OP want only cars that are in data_store.


Woocommerce new customer email to store manager

Question: Option 1
I'm trying to override the Woocommerce template structure in the following way:
http://docs.woothemes.com/document/template-structure/.
The file I'm trying to override is: your_template_directory/woocommerce/emails/customer-new-account.php.
At the end of this file I added the following code:
<?php do_action( 'new_customer_registered', $user_login ); ?>
In functions.php add this:

function new_customer_registered_send_email_admin($user_login) {
  ob_start();
  do_action('woocommerce_email_header', 'New customer registered');
  $email_header = ob_get_clean();
  ob_start();
  do_action('woocommerce_email_footer');
  $email_footer = ob_get_clean();

  woocommerce_mail(
    get_bloginfo('admin_email'),
    get_bloginfo('name').' - New customer registered',
    $email_header.'
The user '.esc_html( $user_login ).' is registered to the website
'.$email_footer
  );
}
add_action('new_customer_registered', 'new_customer_registered_send_email_admin');

This code is to send an e-mail to the admin of the website. The admin_email is retrieved by the get_bloginfo function. However, I'm trying to send the e-mail to the store manager instead. Any idea what function or code should be used in this case?
Option 2
Another option could be to add the following code to the functions.php file and adapt this so it sends a notification to the store manager instead of the admin:
/**
 * Notify admin when a new customer account is created
 */
add_action( 'woocommerce_created_customer', 'woocommerce_created_customer_admin_notification' );
function woocommerce_created_customer_admin_notification( $customer_id ) {
  wp_send_new_user_notifications( $customer_id, 'admin' );
}

Answer: Solved this as follows. I've added the following code in my functions.php file:
/* SEND NEW CUSTOMER EMAIL TO KILIKILI */
/* --- */
add_filter( 'woocommerce_email_headers', 'mycustom_headers_filter_function', 10, 2);

function mycustom_headers_filter_function( $headers, $object ) {
    if ($object == 'customer_new_account') {
        $headers .= 'BCC: Store manager name <email@example.com>' . "\r\n";
    }
    return $headers;
}


How to print all console output after a match is found in a DOS batch file?

Question: Using DOS batch syntax, I need to wait until a pattern shows up in console output, and then print everything after that (or at least print N lines after the match). How can I do that? (Something like grep +A in Unix). I can simply do this, to get the pattern:
run_my_command | findstr "my_pattern"

But looking at findstr manual, it doesn't seem there is a switch to print everything (or N lines after the pattern). I am not an expert in DOS batch, so if you have ideas, please be direct.
EDIT:
Here is the last part from my output (i.e. There are LOTs of lines before these lines, But all I am interested in, is the results of the tests, i.e. everything after "Results :" which is bold)

...
...
21:23:26.332 [Thread-4] DEBUG o.s.b.f.s.DisposableBeanAdapter -
  Invoking destroy() on bean with name 'ehcache'
21:23:26.332 [Thread-4] INFO  o.s.c.e.EhCacheManagerFactoryBean -
  Shutting down EhCache CacheManager
21:23:26.332 [Thread-4] DEBUG net.sf.ehcache.CacheManager -
  CacheManager already shutdown
Results : Tests in error:    ReceiptsSearchRequestBuilderTest.testCreateSearchRequest_loadDate:97 »
  IllegalArgument   ReceiptLineControllerTest.testFind:26 » NullPointer
  Tests run: 229, Failures: 0, Errors: 2, Skipped: 0
[INFO] ----------------------------------
[INFO] BUILD FAILURE
[INFO] ----------------------------------
[INFO] Total time: 23.213 s
[INFO] Finished at: 2015-08-03T14:23:26-07:00
[INFO] Final Memory: 19M/453M
[INFO] -------------------------------

EDIT:
Here is my script. When I don't redirect to %log%, it only prints the text after my pattern, which is what I want. But when I redirect it to %log%, the log file contains ALL the text (stderr correctly gets dumped to null as well).
@echo OFF

SET MAVEN_PROFILE=ie
SET root_dir="%USERPROFILE%\Desktop\MyFolder"
SET log=%root_dir%/log.txt

powershell -c "$txt=(&mvn -P %MAVEN_PROFILE% -Dtest=LoginTest test > %log% 2> null) -join \"`r`n\"; $i=$txt.indexof('Results :'); if($i -ge 0) { $j=$txt.lastindexof(\"`n\",$i); write-host $txt.substring([math]::max(0,$j+1))}"

Answer: What do you mean pattern shows up? And where you want to find? Since you want to print N lines or everything after that, I assume you are searching for a word in a text file instead of pattern.
@echo off
set /p word = What word/pattern you are searching for? ^>
set bool = 0

for /f "tokens=*" %%a in (Text.txt) do (
    if %%a == %word% set bool = 1
    if %bool% == 1 echo %%a
)

This script only print everything after the word you're looking for is found.
Comment: dark fang, I am running a command that produces a ton of output. I want to ignore most of the output and basically only print the whatever is written after my pattern. (eventually redirect it into another file and save). So I am not working with a static (fixed size) text file. How can I use your script to make it work with a real time command output?
Comment: simply redirect the command's output to a temporary file: `run_my_command >text.txt`
Comment: dark fang, I am running a maven command that builds our project. The output is about 120 MB (and that's after I use the --quiet switch to decrease the output). I replaced the "Text.txt" part of your script with "mvn install" and also with " 'mvn install' ", but they don't seem to work. Is there a way make it work for my case?
wOxxOm, yes I would do that eventually, but first I need to be able to discard most of the output and only capture the output that I am interested in.
Comment: I'm not familiar with Maven, but does "mvn install" can be called in cmd? If it can, try replace `cmd /c mvn install` with Text.txt. Since batch is slow, I don't think it can be done quickly
Comment: Yes, it can. But it didn't work. All I see is a CMD window that flashes (The maven command should take a couple of minutes to finish at least, but when I run the script, all I see in a flash of a CMD window, and then nothing).
Answer: Here's a one-liner using powershell which you can run from your batch file, it takes 10 seconds to find a string at the end of 120MB output:
powershell -c "$txt=(&your_console_app -with -arguments) -join \"`r`n\"; $i=$txt.indexof('string_to_search_for'); if($i -ge 0) { $j=$txt.lastindexof(\"`n\",$i); $txt.substring([math]::max(0,$j+1)) }"

Replace your_console_app -with -arguments and string_to_search_for accordingly. If those contain doublequotes escape them as \".
Add pause on a new line to keep the console window open if needed.

An example using your actual command line which outputs to standard output redirected to a file:
@echo OFF

SET MAVEN_PROFILE=ie
SET root_dir="%USERPROFILE%\Desktop\MyFolder"
SET log=%root_dir%/log.txt

powershell -c "$txt=(&mvn -P %MAVEN_PROFILE% -Dtest=LoginTest test 2>nul) -join \"`r`n\"; $i=$txt.indexof('Results :'); if($i -ge 0) { $j=$txt.lastindexof(\"`n\",$i); $txt.substring([math]::max(0,$j+1)) }" >results.txt

Alternatively you can write to the file directly from within powershell code:
powershell -c "$txt=(&mvn -P %MAVEN_PROFILE% -Dtest=LoginTest test 2>nul) -join \"`r`n\"; $i=$txt.indexof('Results :'); if($i -ge 0) { $j=$txt.lastindexof(\"`n\",$i); $txt.substring([math]::max(0,$j+1)) | out-file 'results.txt' }"

Comment: Great. This works when and it prints only what I want to the console. How can I make the redirect work also? (Please see my code above in the original question). I can see the log files get created, so it seems like your command can resolve the %log%, but the problem is the log contains ALL console output (instead of just the output after the pattern)
Comment: Added an actual example. Note that there's no need to redirect to %log% because powershell reads stdout of the command. When you redirected it the command sent its full output to log file and then powershell saw nothing.
Comment: Ah! Makes sense. The script works successfully now. Thank you very much!
Comment: ok, I see a problem with this now. It does work when the console output is small (i.e. It works when I only run 1 test. Console output is not too much so it seems to work fine). But when I tried it for our test suite as a whole (56 tests at the moment) the command seems to never finish, so the script never terminates :(
Thoughts?
Comment: And what happens if you run the entire test suite with output redirection to a file from the command line: `mvn .......... >logfile.txt`?
Comment: hmm... Looks like maybe the script fails when I run the whole test suite, but maybe for a different reason. Not sure yet. I'll post an update soon.
Comment: OK, I had a mis-configuration in my test-suite. I confirmed the above solution works successfully :)
Thanks again
Answer: Of course, you need to execute both parts connected via a pipe, like in your example. Although it is possible to write the right-side pipe process in pure Batch, batch file processing have synchronization problems when reading from a pipe, so we need to use a different language.
JScript is a programming language more powerful than Batch that is available in all Windows versions from XP on, and it is very easy to combine both Batch and JScript code in the same hybrid script:
EDIT: There was a @ missing in line one. Fixed
@set @Batch=1 /*
@echo off
run_my_command | CScript //nologo //E:JScript "%~F0"
goto :EOF    */

// JScript section

var lineFound = false, numOfLines = N;
while ( ! WScript.Stdin.AtEndOfStream ) {
   line = WScript.Stdin.ReadLine();
   if ( ! lineFound  &&  line.indexOf("my_pattern") >= 0 ) lineFound = true;
   if ( lineFound  &&  numOfLines ) {
      WScript.Stdout.WriteLine(line);
      --numOfLines;
   }
}

Save previous code in a file with .bat extension; you need to adjust a couple details in the code.
Comment: Please, edit your question and insert a _small_ section of the output data (10 or 15 lines), and the pattern search, so I can do my own tests. Note that "It didn't work" describe nothing... When complete the changes, post a comment here as advice.
Comment: Updated my post with sample output.
Comment: Ops! There was a `@` missing before the "Batch" name in line 1: `@set @Batch=1 /*`. Please, fix it and try again... **`:(`**
Comment: Aacini, when I try it, I get this error:
`Microsoft JScript compilation error: Expected ';' `

From the last line of the script (at the end of your code). I tried putting a ; after "%~F0" but then I got "myfile.bat cannot be found" error.
Answer: Here is a similar idea to Aacini's answer, except it uses an already written hybrid JScript/batch utility called JREPL.BAT that provides sophisticated regular expression text processing capabilities to batch. JREPL.BAT is pure script that runs natively on any Windows machine from XP onward. Full documentation is embedded within the script.
To skip output and begin printing with the first line that begins with Results :
yourCommand | jrepl "^Results :[\s\S]*" "$0" /jmatch /m

To print only the lines that begin with Results :, plus the next 4 lines (5 total)
yourCommand | jrepl "^Results :(.*\n){0,4}.*$" "$0" /jmatch /m

Both commands above use the /M multi-line option, which means the entire output must be loaded into memory. Nothing will print until the command completes. This could be a problem if the output is multiple gigabytes, or if it is long running, and you want to see output as soon as possible.
With a bit more code, and user supplied JScript, it is possible to process and print each line independently - with no delay, and no size limitation:
To print everything starting with the first line beginning with Results :
yourCommand | jrepl "^Results :.*|^.*" "go=true;$0|go?$0:false" /jmatch /t "|" /jbeg "var go=false"

To print only lines that begin with Results :, plus the next 4 lines (5 total)
yourCommand | jrepl "^Results :.*|^.*" "go=5;$0|(--go>0)?$0:false" /jmatch /t "|" /jbeg "var go=0"


MIgrate data from SQL Server to Bluemix Database as a Service

Question: I am trying to move data from a local SQL Server 2014 database to Bluemix's database as a service. The IBM SQL database console limits uploads to 20 MB.  Some of my tables are significantly larger than that.
What would be the best way to move the data?
Thanks
Answer: If you install the DB2 client on your local machine, you can connect directly to your SQLDB database and use the IMPORT or LOAD** utilities to load the data.
For example,
load client from /tmp/mssql.cust.csv of del replace into my_table

** With LOAD, you have to use LOAD CLIENT ... in order to load data from your client machine instead of the server.
Comment: I have Data Stuiod and clpplus.  Where would I run this command?  Thanks!


Separation of tiers with Azure and Docker

Question: Being new to Docker (but not Azure) I would like to understand how tiers of an application are usually separated when deploying Docker containers to Azure (I am thinking of using Azure Container Services).
For example, if not using Docker, I would place a VM in a web tier/subnet, and a VM in the database tier/subnet and set the NSG rules accordingly.
How is this achieved with Docker, would I deploy Docker into multiple subnets, or would I just have one subnet say, to which I deploy all containers and then somehow set the networking rules between those containers?
Thanks
Answer: Docker Swarm-mode has the concept of network-definitions in your docker-compose file which provides a form of fine grained network segmentation. If this is not sufficient for you then you can run separate instance of Docker in the different network segments and use non-swarm mechanisms for the services to find each other.
Answer:
How is this achieved with Docker, would I deploy Docker into multiple
  subnets, or would I just have one subnet say.

In Azure container service, if we choose kubernetes, Azure will create multiple subnets for masters and nodes.
Container use cluster IP(different with azure VM IP) address communicate with other containers, if we want this container can be access from the internet, we can expose this container to the Internet with Azure public Load Balancer, then use this public IP address to access it from the Internet. Azure VM in the this Vnet can't communicate with containers.
So, if we chose kubernetes, we can create multiple containers work as database server, and create another container work as web server, connect web container to database containers, then expose this web container to the Internet, in this way, we can access this web via Azure Load Balancer Public IP address. Web container and database containers in one pod, different pods with different pod CIDR.
Kubernetes is a open-source, production-grade container orchestrator tool, the following image show how kubernetes works on Azure:

If you want to use docker to deploy multiple containers, we should design network, different subnets, different bridge networks and so on. The most convenient way is to use container orchestrator tool, like kubernetes, swarm or DC/OS.
Comment: Thanks for your answer. If I wanted to deploy a Docker image that would scale (a web app say) but then also some that shouldn't scale (a database say), would I deploy both to the same Azure Container Services instance/cluster or should I use separate clusters for each?
Comment: @P2l Yes, we should deploy both to same azure container service, about scale out or in, all the containers will be created in the same pods, no need to create them in separate clusters.
Comment: @P2l If you need more help, please let me know. Also if it helps, please don't forget to accept it as an answer, thanks.


how to modify drupal 7 mysite/user/login and mysite/user/registration pages "in-place"?

Question: I am trying to find out a way to add fields/modify existing fields/theme the default Drupal 7 login/registration pages in-place.
What I mean "in-place" is to find a way to not create new login/registration pages through creating "page--user--register.tpl.php" files.
I am looking for a way to add/modify/theme the mysite/user/login and mysite/user/registration pages without having to create page--user--register.
However, if overriding the hook_theme() in "template.php" and creating "page--user--register.tpl.php" file is the only way, then is there a way to have it use the same theme as the rest of the pages? I can make the custom registration page have the same theme through coyping code from "page.tpl.php" and pasting it in my "page--user--register.tpl.php" file, but this seems wrong to me.
Any help or comments are appreciated.
Answer: If you want add form fields to either the login or registration form(s) you will have to write custom PHP code in a module file to make any use of the fields.
The forms are just blocks on the page, and should inherit or reuse block.tpl.php pretty much everywhere. Since they are just blocks, sitewide css can target them specifically once you've made them.
The drupal login and registration system is fairly pluggable, you can "inject" your own validation code (to handle your own custom fields) and authentication pretty much however you wish.
A useful tutorial/blog post might be:
http://omegadelta.net/2011/03/23/custom-authentication-with-drupal-7/
It doesn't add custom fields, but does modify the existing drupal login behavior which is what you're trying to do as well.
In your case you probably want to do something like:

create a custom login/registration block in a module, it simply
loads the default login or registration block as an object.
Implement hook_block family of functions.
hook_form_alter() the block and inject your fields and override the default user authentication validator with your own to consume your fields
(similar to the linked blog posts' _geospike_user_login_form_alter()
function).
define a hook_menu path which outputs a page that
loads/outputs your custom defined block to login or register.

Drupal can do what you want with basically a custom module and like a few hook functions. Your not creating your own user login or registration form, and your not writing your login login validators from scratch -- you are just overriding the pre-existing ones for new ones your basically telling drupal exist now via your module.
Comment: thanks for the help tenken. i am also wondering, if i wanted to add a drop down list of countries to the registration form, how would i do that? i have read a lot of how to add drop-down menus, but none seem to tell me how you how to detail the addition of a drop-down list for countries. thanks
Comment: You would add a "select" widget to the $form array using the drupal Form API (FAPI), http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#select

You could make a database table with: id, country and use db_query() to get an array of all the countries you want in your select list.
Comment: you can use the location or addressfield module to add a country to the registration form
Answer: Add this to you template.php file, where your_themename is the machine name of theme you are using
function your_themename_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'your_themename') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
      'your_themename_preprocess_user_login'
    ),
  );
  return $items;
}

Create a user-login.tpl.php file and add this
<?php
    print drupal_render($form['name']);
    print drupal_render($form['pass']);
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
?>

This is a summary of what I found on this blog post
Comment: Have added the summary
Comment: Please try to include a summary with link-only answers.  Link only answers are no longer useful when links break.
Answer: If you just want to change the theme for each page alot install Devel Themer and it can tell you a specific way to name a tpl file for your site theme to change its look/HTML/CSS specifically.
Answer: Drupal 7
Add this code to your template.php in your theme directory.
    function yourtheme_theme() {
      return array(
        'user_login' => array(
          'template' => 'user-login',
          'arguments' => array('form' => NULL),
        ),
      );
    }

    function yourtheme_theme() {
      $items = array();
      $items['user_login'] = array(
        'render element' => 'form',
        'path' => drupal_get_path('theme', 'yourtheme') . '/templates',
        'template' => 'user-login',
        'preprocess functions' => array(
           'yourtheme_preprocess_user_login'
        ),
      );
      return $items;
    }

    function yourtheme_preprocess_user_login(&$vars) {
      $vars['intro_text'] = t('This is my awesome login form');
    }

Create a file in your theme's "templates" folder called user-login.tpl.php.
Add this code and change "yourtheme" to your theme name.
 <?php print drupal_render_children($form) ?>

Clear you cache.
Source (Where you can find details on how to do this for user-register-form, user-password-form, and Drupal 6)
https://drupal.org/node/350634


DX10 Skybox Shader

Question: I'm trying to write a skybox shader in DX10 using the following HLSL code:
//////////////////////////////////////////////////////////////////////////
// world matrix for each rendered object
float4x4 g_mWorld;

// single cubemap texture
Texture2D g_tCubeMap;

// basic mirror texture sampler
SamplerState g_sSamplerMirror
{
    Filter = MIN_MAG_MIP_POINT;
    AddressU = MIRROR;
    AddressV = MIRROR;
};

//////////////////////////////////////////////////////////////////////////
// pre-defined vertex formats for vertex input layouts
struct VS_INPUT
{
    float3 Position     : POSITION;
};

struct PS_INPUT
{
    float4 SPosition    : SV_POSITION;
    float3 UV           : TEXCOORD;
};

//////////////////////////////////////////////////////////////////////////
PS_INPUT VS_Default( VS_INPUT Input )
{
    PS_INPUT Output = (PS_INPUT)0;

    Output.SPosition = float4(Input.Position,1.0f);
    Output.UV = normalize( mul( Output.SPosition, g_mWorld ) ).xyz;

    return Output;
}

//////////////////////////////////////////////////////////////////////////
float4 PS_Default( PS_INPUT Input ) : SV_TARGET0
{
    return float4( texCUBE( g_sSamplerMirror, Input.UV ) );
}

//////////////////////////////////////////////////////////////////////////
technique10 TECH_Default
{
    pass
    {
        SetVertexShader( CompileShader( vs_4_0, VS_Default() ) );
        SetPixelShader( CompileShader( ps_4_0, PS_Default() ) );
        SetGeometryShader( 0 );
    }
}

Which gives the error "DX-9 style intrinsics are disabled when not in dx9 compatibility mode."  on line 46:
return float4( texCUBE( g_sSamplerMirror, Input.UV ) );

Is there an alternative to texCUBE? How can I fix this without enabling dx9 compatibility mode?
Answer: Since you are using Shader Model 4 you should be able to create a TextureCube object and then call the Sample method.
Comment: This fixes the problem but gives me this error:
D3D10: ERROR: ID3D10Device::DrawIndexed: Rasterization Unit is enabled (PixelShader is not NULL or Depth/Stencil test is enabled) but position is not provided by the last shader before the Rasterization Unit. [ EXECUTION ERROR #362: DEVICE_DRAW_POSITION_NOT_PRESENT ]
D3D10: ERROR: ID3D10Device::DrawIndexed: A Vertex Shader is always required when drawing, but none is currently bound. [ EXECUTION ERROR #341: DEVICE_DRAW_VERTEX_SHADER_NOT_SET ]
Comment: Ah, D3D10's exceedingly verbose error messages. Unfortunately I don't quite see how those are being generated from just the code you pasted above; it seems like you are both writing a position in your vertex shader *and* setting the shader in the effect -- maybe the vertex shader is being unset accidentally in your C++ code?

DX10 Skybox Shader


Representing a vector field locally

Question: A couple of questions occured to me when reading about the Poincare-Hopf theorem. Any pointers or comments would be appreciated!
Let $M$ be a closed oriented Riemannian manifold and $V$ a vector field on $M$.
1) Is the statement that the zeros of $V$ are non-degenerate (by which I mean the Hessian at these points is invertible) equivalent to saying that $V$ is a transverse section of $TM$ (in the sense that it is transverse to the $0$ section)?
2) It is claimed that locally around each critical point $p$, there exist coordinates $y = (y_1,...,y_n)$ such that $V$ can be written as $V = y A_p$ for some constant matrix $A_p$. This sounds like something to do with the inverse function theorem, but how does one go about choosing the coordinates $y$ and the matrix $A_p$?
Thanks.
Answer: I've since heard back from the author of the book, who agrees that there is an issue with 2). It seems to me that the Hartman-Grobman theorem would suffice provided the zeros are hyperbolic. It was suggested to me that $V$ can be perturbed a little bit to make this true without changing the index of its zeros (since we want to prove the Poincare-Hopf theorem). How this is done, however, is a mystery to me.

Representing a vector field locally


É possível pegar o Numero de Erro retornado pela Página

Question: Criei uma página (sequindo o ensinado nesta pagina ) de erro para o Erro 404, porém desta forma teria de fazer uma página de erro para cada Status HTTP, então gostária de fazer uma gnerica onde fosse possivel pegar o possivel erro do header http e criar com base no erro a página de erro, ai quando se fosse definir as paginas de erro no apache ficaria desta forma:
ErrorDocument 403 http://localhost/pasta-do-meu-projeto/erro.html
ErrorDocument 404 http://localhost/pasta-do-meu-projeto/erro.html
ErrorDocument 501 http://localhost/pasta-do-meu-projeto/erro.html

Comment: Ricardo, descobri o motivo da URL redirecionar em alguns casos e em outros não, editei a resposta.
Answer: Se for PHP, pode tentar isto:
ErrorDocument 403 http://localhost/pasta-do-meu-projeto/erro.php?status=403
ErrorDocument 404 http://localhost/pasta-do-meu-projeto/erro.php?status=404
ErrorDocument 501 http://localhost/pasta-do-meu-projeto/erro.php?status=501

E o PHP:
<?php
if (isset($_GET['status'])) {
    echo $_GET['status'];
}

Redirecionamento vs mod_rewrite
Se você quer não quer que a URL mude ao atingir uma página de erro, mas mesmo assim ocorra o redirecionamento, você deve usar o RewriteCond combinado com o RewriteRule, ficaria algo como:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /up/erro.php?status=404 [L]

Porém, se você quer que a url fique algo como http://localhost/erro.php?status=404, então não use-o, use apenas o ErrorDocument.
Reescrita sem mod_rewrite
Ao fazer os alguns testes notei que
ErrorDocument 404 http://localhost/pasta-do-meu-projeto/erro.php?status=404

é diferente de
ErrorDocument 404 /pasta-do-meu-projeto/erro.php?status=404

Quando usamos o primeiro modo, o Apache não pode detectar ao certo se é um subdomínio, ou outro domínio ou o mesmo domínio, então não acontece acaba que redirecionando para a outra página, note também que não é possível pegar a variável REDIRECT_STATUS.
Porém ser usarmos o segundo modo com o caminho começando por / o redirecionamento é "interno", ou seja a página não redireciona, mas a resposta vem de outro local, o que nos permite acesso as variáveis como REDIRECT_STATUS, note que não é necessário o mod_rewrite habilitado.
Atualização
Se estiver usando o PHP5.4+ você pode usar a função http_response_code
Então o ErrorDocument não vai precisar do ?status=
Relatado: Pegar http status em versões do PHP inferiores ao 5.4
Comment: @RicardoHenrique Por nada, acredita que eu fui criar a minha url-reescrita e comecei a apanhar, kkkk, agora já consegui descobrir várias coisas, só to com dificuldade em fazer o mesmo efeito no Nignix e no Lighttpd (servidores tipo apache), se eu conseguir tudo posto aqui pra compartilhar com o pessoal.
Comment: .@GuilhermeNascimento obrigado por descobrir era justamente a segunda forma que estava usando, se pudesse dava upvote novamente em sua resposta.


Why dim(Ker(A)+dim Im(A)) not equal N?

Question: Let $\mathscr A$ be a linear transformation on an n-dimensional linear space $V$ ($n\geqslant 3 $), take a set of bases $\alpha_1,\alpha_2,\cdots,\alpha_n$ in $V$, def $\mathscr{A}\left(\alpha_{i}\right)=\left\{\begin{array}{l}\textbf{0}, i=1,2 \\ \alpha_{3}, i=3, \cdots, n\end{array}\right.$
Then, $Ker(\mathscr A)= L(\alpha_1 ,\alpha_2)$, $\mathscr A V=L(\alpha_3)$
$\dim Ker(\mathscr A) = 2$,$\dim \mathscr A V =1$
why $\dim Ker(\mathscr A) +\dim \mathscr A V = 3 \neq n$ ?
Comment: The kernel is much more than just the linear span of $\alpha_1$ and $\alpha_2$ when $n\geq 4$. For example, it also contains any vector of the form $\kappa_3\alpha_3+\cdots+\kappa_n\alpha_n$ in which $\kappa_3+\cdots+\kappa_n=0$. Thus, $\alpha_3-\alpha_4$ is in the kernel, for example. In other words: it's not adding up because you are miscomputing the kernel.
Comment: While the image can be found by just looking at what happens to basis vectors, the kernel cannot be found just by looking at which basis vectors map to zero.
Comment: Think about what space each of those spaces live in
Comment: I know now. The answer on the book is wrong
Comment: Thanks everyone
Answer: The kernel has dimension $n-1$ and the image has dimension $1$. The sum is indeed $n$. For example, not only do $a_1$ and $a_2$ get sent to zero, but since $a_3$ and $a_4$ both map to $a_3$, the difference $a_3-a_4$ maps to zero.
One basis for the kernel is $\{a_1,a_2,a_3-a_4,a_3-a_5,\ldots, a_3-a_n\}$. You can show these vectors are linearly independent, so the null space is $(n-1)$-dimensional.

Why dim(Ker(A)+dim Im(A)) not equal N?


Let ${f}$ be a differentiable function in $x=6$ so that $\lim_{x\to6}{\frac{x^{3}f(x)-1512}{x-6}}=262.144$. Find the values of $f(6)$ and $f(6)'$.

Question:
Let ${f}$ be a differentiable function in $x=6$ so that $$\lim_{x\to6}{\frac{x^{3}f(x)-1512}{x-6}}=262.144$$ Find the values of $f(6)$ and $f(6)'$.

The right answers are, respectively 7 and 1.21.
This was a problem presented in a quiz I had this week in Calculus I. By my understanding it would suffice to do $x^{3}f(x)-1512 = 0$ since the upper part should be $0$ just as $x-6$ for the function to exist in $x=6$. This would return $f(6)=7$. Doing l'Hôpital's rule and deriving the function makes $f(6)'=-2.28$...
My other problem is that using $7$ in the place of $f(x)$ does NOT give a limit of $262.144$ as it's intended. Any enlightnment would be appreciated!
UPDATE:
You can really find $f(6)$ by just isolating it. To get $f(6)'$ it's necessary to use the definition of derivatives when ${x\to6}$. That is:
$\lim_{x\to6}\frac{f(x)-f(6)}{x-6}$. Multiplying both sides by $\frac{1}{x^{3}}$ back in the original limit and using $x=6$ we get to:
$$\lim_{x\to6}\frac{f(x)-7}{x-6} = \frac{262.144}{6^{3}}$$
It looks exactly like f(6)'... Since $\frac{262.144}{6^{3}}=1.21$, that's the derivative wanted.
A huge thanks to the people that helped me understand it here.
Comment: Well we have $f(6)=7$ and not $f(x) =7$ (for all $x$). Hence we can't replace $f(x) $ with $7$.
Answer: I suspect there may be a mistake in the given solution. Notice that
$$\begin{align}
\lim_{x\to6}\frac{x^3f(x)-1512}{x-6} &= \lim_{x\to6}\frac{x^3f(x)-216f(x)+216f(x)-1512}{x-6}\\[1ex]
&=\lim_{x\to6}\frac{(x^3-216)f(x)+216(f(x)-7)}{x-6} \\[1ex]
&= \lim_{x\to6}(x^2+6x+36)f(x) + 216\lim_{x\to6}\frac{f(x)-7}{x-6}
\end{align}$$
But if $f(x)$ is differentiable and $f(6)=7$, then $\lim\limits_{x\to6}f(x)=7$, while the second limit is simply $f'(6)$, and this yields the same result,
$$108\cdot7+216f'(6) = 262.144 \implies f'(6) = -2.28\ldots$$
Comment: Firstly, thanks for the reply! But I guess I don't understand properly the answer. By the given solution you mean 7 and 1.21? Because testing using 7 in the problem and inserting it in a limits calculator it seems the limit should actually be 756(?). I don't really know how to get to an answer here.
Comment: Yes, that's what I meant by "given solution". And as another user mentioned, you cannot simply replace $f(x)$ with $7$. Ultimately my solution agrees with yours, just without the use of L'Hopital's rule, and it's my suspicion that the "given solution" is simply incorrect.


Visualisations for the Decision Surface of Probabilties

Question: Say that I learned a function f(x) and its range lies in 0 - 1. I have only two features in my input space. Other than overlaying a probability map on a cartesian plane, how do I visualize/interpret the probabilistic behaviour of my classifier?
Answer: Off the top of my head, the only other reasonable possibility I can imagine are partial dependence plots.

[...] a tool for visualizing the model estimated by any supervised
  learning algorithm.  Classical partial dependence plots (PDPs) help
  visualize the average partial relationship between the predicted
  response and one or more features.  In the presence of substantial
  interaction effects, the partial response relationship can be
  heterogeneous.  Thus, an average curve,  such  as  the  PDP,  can
  obfuscate  the  complexity  of  the  modeled relationship.
  Accordingly, ICE plots redefine the partial dependence plot by
  graphing the functional relationship between the predicted response
  and the feature for individual observations.

Basically it plots the mean expected response of your model given inputs partial variation (e.g. a curve is plotted with the mean response versus values of one feature, that's why it's partial).

But with only two dimensions plotting the actual probability surface sounds more fun.
Comment: yeah, those 2 are the only i can think of. thx
Comment: @sponge_knight I'm curious why you would accept the answer (in effect indicating the answer solved your problem) but not also upvote it (indicating the answer was useful). It would seem odd to suggest an answer solved your problem without also being useful. You're free to vote as you see fit but it seems an odd signal to send to an answerer. What should they interpret this to mean?
Comment: yea, you're right! upvoted!


In node add, how to upload file using image from clipboard

Question: How can I paste image from clipboard and save into image_field ?
Answer: You could try the FileField Sources module. It provides quite a few additional options to upload files.

Re-use files by an auto-complete textfield
Attach server-side files uploaded via FTP
Transfer files from a remote server (cURL required)
Paste a file directly from the clipboard (Drupal 7 only)
Select existing files through the IMCE file browser
Comment: works fine, tks


how to run NStimer in background Mode?

Question: i am developing app that counts the work Hours for the employee.
so i want to run a timer which stay alive in backGround mode, but i did not found any way how to do this directly.
i think i can achieve this by following strategy...

save current time in userDefault in applicationDidEnterBackground method.
when application again become active, get saved time from userDefault, then find the difference with current Time in applicationWillEnterForeground method.Then display that calculated time.

now, i want to know, is this right way to do this? or is there any best way??
Thanks!!
Answer: There's no reason to save the current time on applicationDidEnterBackground.
All you really need at any moment is the time the user "started work", or nil if the user hasn't started work. Whenever you need to know the time worked, you can compute it as the current time minus the started-work time:
let workStartTimeKey = "workStartTime"

class ViewController: UIViewController {

    var secondsWorked: CFTimeInterval? {
        guard UserDefaults.standard.object(forKey: workStartTimeKey) != nil else { return nil }
        let startTime = UserDefaults.standard.double(forKey: workStartTimeKey)
        return CFAbsoluteTimeGetCurrent() - startTime
    }

(Since the iOS SDK mostly uses the second as the unit of time, it's better to store and compute using seconds instead of hours. You can convert to hours if necessary for display or when communicating with your server or whatever.)
I assume you have a button in your user interface for the user to tap when she starts work. When the button is tapped, you record the current time, start a timer to update the display periodically, and also update the display immediately:
    @IBOutlet var startWorkButton: UIButton!

    @IBAction func startWork() {
        guard secondsWorked == nil else {
            // Already started work.
            return
        }

        UserDefaults.standard.set(CFAbsoluteTimeGetCurrent(), forKey: workStartTimeKey)
        startDisplayUpdateTimer()
        updateViews()
    }

    private var displayUpdateTimer: Timer?

    private func startDisplayUpdateTimer() {
        displayUpdateTimer = Timer(timeInterval: 1, repeats: true, block: { [weak self] _ in
            self?.updateViews()
        })
        RunLoop.main.add(displayUpdateTimer!, forMode: .commonModes)
    }

I assume you have another button to stop work. When it's tapped, you grab the current value of secondsWorked, clear the stored start-work time, cancel the display update timer, and do whatever you want with the grabbed value of secondsWorked. Here I'll just print it:
    @IBOutlet var stopWorkButton: UIButton!

    @IBAction func stopWork() {
        guard let secondsWorked = self.secondsWorked else {
            // Didn't start work yet!
            return
        }

        displayUpdateTimer?.invalidate()
        displayUpdateTimer = nil
        UserDefaults.standard.removeObject(forKey: workStartTimeKey)
        updateViews()
        print("seconds worked: \(secondsWorked)")
    }

To update the display, you probably want to show the current time worked in a label. You can also enable or disable the buttons based on whether the user is currently working:
    @IBOutlet var timeWorkedLabel: UILabel!

    private func updateViews() {
        if let secondsWorked = secondsWorked {
            startWorkButton.isEnabled = false
            stopWorkButton.isEnabled = true
            timeWorkedLabel.text = timeWorkedFormatter.string(from: secondsWorked)
        } else {
            startWorkButton.isEnabled = true
            stopWorkButton.isEnabled = false
            timeWorkedLabel.text = "Not working"
        }
    }

    private let timeWorkedFormatter: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute, .second]
        formatter.allowsFractionalUnits = true
        formatter.collapsesLargestUnit = true
        formatter.maximumUnitCount = 2
        formatter.unitsStyle = .abbreviated
        formatter.zeroFormattingBehavior = .dropLeading
        return formatter
    }()

When the view is loaded, you should see if the user is already working. This can happen if the app was killed and relaunched after she started working. If she's already working, start the display update timer. Also you need to update the views regardless:
    override func viewDidLoad() {
        super.viewDidLoad()
        if secondsWorked != nil { startDisplayUpdateTimer() }
        updateViews()
    }

Finally, you should cancel the timer when the view controller is destroyed, in case you have it in a navigation controller that allows it to be popped:
    deinit {
        displayUpdateTimer?.invalidate()
    }

}

Comment: thanks @rob mayoff
you provided whole sourceCode for the app...i just need to create storyBoard..ha ha
Comment: Glad I could help. I see questions like this often enough that I wanted to write a detailed answer, so I can point to it when I see similar questions in the future.

how to run NStimer in background Mode?


Is it valid to report the mean of Cohen's kappa coefficients and the associated confidence intervals?

Question: I am studying the interrater and intrarater reliability of a classification system (seven categories; nominal).
I recruited 16 unique raters to classify 35 items according to the system. The raters classified all items twice (two sessions, one month apart)
I am assessing interrater reliability using Fleiss' kappa. This approach results in 2 values, one per session.
I am assessing intrarater reliability using Cohen's kappa. This approach results in 16 values, one per rater.
So, for each rater, I have the value of Cohen's kappa and the associated confidence interval. I am interested in a summary measure (intrarater reliability) for all 16 raters. Is it valid to report the mean Cohen's kappa coefficient, mean lower bound of the 95% CI, and mean upper bound of the 95% CI?
Thank you.

EXAMPLE
Format: Cohen's kappa coefficient (95% CI)

0.40 (0.20–0.60)
0.10 (–0.10–0.30)
0.50 (0.25–0.75)
0.45 (0.25–0.65)

Is it valid to report the mean? (i.e., 0.36 [0.15–0.57])
Answer: It's okay to report the mean of Cohen's kappa.  However instead of reporting mean upper/lower confidence limits, report the mean standard error.
Comment: Thank you for your answer. Could you please expand on why the mean confidence interval is not appropriate?
Answer: If you have the standard errors of the kappa values and are willing to assume they are normally distributed you could summarise them using techniques from meta-analysis. Each would be inversely weighted by its variance to form the summary and the weights used to form the standard error of the summary and hence to form confidence intervals. Meta-analysis is available in Stata and R, I would not try doing it by hand so I do not give the formulas here.
The CRAN Task View on MetaAnalysis contains more than 100 packages for some variety of meta-analysis. Disclaimer, I maintain the Task View.
Comment: Thank you for your reply. Could you please name the R package you are referring to?


Apache mod rewrite, authentication problem

Question: I am doing a rewrite, in an .htaccess file, to another domain like so:
RewriteEngine On
RewriteRule folder/(.*)  http://newdomain.com/folder/$1

http://newdomain.com/folder is password protected.
I get an authentication popup from newdomain when the rewrite happens. When I enter credentials, it authenticates them against the server doing the rewrite, not newdomain.  The browser just hangs, and in my server error logs it continuously writes "user x not found" until I stop the connection.
Answer: Which domain is supposed to be doing the authentication?  It seems that it should be the new domain, not the old one, given that otherwise one could simply go to the URL with the new domain and access the content without authentication.
In that case, you probably want to rewrite the URL in the user's URL bar, which can be done with the R flag:
RewriteRule folder/(.*) http://newdomain.com/folder/$1 [R]

At that point, everything should be happening on the new domain.
Comment: There is authentication on both servers which I think may have been the problem.  I forgot to add the [P,L] flags, which I was using with the RewriteRule as well. It is working now the way I originally had it. I just changed the htaccess file to point to a different .htpasswd and used Require valid-user instead of Require 'specificUsername'.  May have something to do with the new .htpasswd corresponding to one on newdomain...


Cannot get the desired tone when recording a Nirvana song

Question: I am trying to record the main riff of "Come As You Are" by Nirvana.
I searched on the Internet the amp settings that I should use and I ended up using this :
bass 4, mids 5, treble 6, high gain, chorus effect.
It sounds like this : recording .
I am sure that you have noticed that it sounds a million miles away from the official recording or even from live performances ( like this one :  Come As You Are ) and I have the feeling that it's not by changing the bass, gain or treble settings ( I did try ) that I will come closer to the right tone. My recording doesn't have the warm tone of the original, it sounds too metallic.
Do you know what effects I am missing here ?
Comment: There are more factors that come into play (literally) than mere amp. settings. I can guarantee that if you jumped on stage and grabbed the guitar after he finished playing that song, you still wouldn't sound the same.
Answer: You Cannot Match a Sound
There is simply no way for anyone to give you the formula to match a sound, there are too many factors. The best you can do is approximate. As Tim said in a comment there are many factors that go into your sound other than amp settings. To truly match a sound here is a short list off the top of my head of things that you would need to consider.

Amp settings: Bass? Mids? Treble? Gain? Presence? More settings?
Amp type: Tubes? Solid State? Brand? Modifications? Cabinet?
Guitar settings: Volume? Tone? Pickup selection? Setup? Tuning/Intonation?
Guitar type: Pickups? String gauge? Brand?
Guitar playing: Picking tendencies? 'Finger tone'? Muting?
Effects: What pedals? Pedal settings? More EQ?

For trying to match a live recording there are even more considerations. Room shape, PA system, the recording equipment, etc.
Obviously, something like amp settings makes much more of a difference to your sound than your string gauge for example, but all of the above can still contribute to the overall sound.
How To Get Close
Unfortunately, the link to your performance does not work, but I would be surprised if you were using even nearly the same equipment that Kurt used in the recording. It does not really matter however because the process for 'matching' a sound is the same.
0. Accept defeat
Accept that you will not perfectly match the sound. Also accept that you might not have the time for tweaking settings and research, money for gear, or patience for trial and error.
1. Approximate gear as close as possible
Use whatever amp, guitar, etc. that you have that is closest to what they used on the recording. You can usually find exactly what gear was used in the studio if they are a bigger band like Nirvana.
2. Approximate settings as close as possible
Sometimes the settings that were used in the recording for gear is available, but chances are that won't translate well into whatever gear you are using, as you have found out. Unfortunately, the only guidance I can give here is to use your ear.
3. Use your ear
Is the tone very treble-heavy? Increase your treble etc. You can usually get pretty close to the sound by using your ear with trial and error alone. This is where you should spend most of your time. This is also the part that people have the most trouble with as 'use your ear' is vague and is something only learned through excessive trial and error in my experience. Getting a second opinion or two from an experienced ear can help out a lot too in shaping a sound.
Comment: One thing that nobody ever seems to mention, but is very important with respect to the sound is the microphones and their placement. The same exact equipment live in the same room will sound different than what gets onto the tape.
Comment: Thank you for your answer. I have updated the link
Comment: York's point is a great one. To go even further, the mix is mastered, eq'd and compressed in an isolation booth. The sound of any modern recording might feel raw and lively but actually they are highly pasteurised and well polished by engineers who have the goal of making this sound engaging on a car radio. An over simplifications obviously, but you can't recreate post production in a live setting.


Transformar Collections em Stream

Question: Haveria como transformar o seguinte código para java 8 Stream?
    setores = new SetorBusiness().buscarEtiquetaFuncionario(null, codDiretoriaSelecionada, codCoordSelecionada, uf, cidade, servidor, null, null, agencia);
    parametrosRelatorio = new ParametrosRelatorio("QtdUorgFunc", SaidaRelatorioEnum.buscaEnum(tipo));
    parametrosRelatorio.getParams().put("sub", FacesContext.getCurrentInstance().getExternalContext().getRealPath("/relatorios/SubQtdUorgFunc"));
    if (!setores.isEmpty()) {
    List<Setor> listaSetores = new ArrayList<Setor>();
    Setor set;
    Map<String, List<Setor>> lista = new LinkedHashMap<String, List<Setor>>();

    for (Setor s : setores) {
        if (lista.containsKey(s.getSiglaSetor())) {
            lista.get(s.getSiglaSetor()).add(s);

        } else {
            List<Setor> se = new ArrayList<Setor>();
            se.add(s);
            lista.put(s.getSiglaSetor(), se);

        }
    }

    for (List<Setor> l : lista.values()) {
        set = new Setor();
        set.setSiglaSetor(l.get(0).getSiglaSetor());
        set.setCodigo(l.get(0).getCodigo());

        set.getSetorImpressaoPDF().addAll(l);
        listaSetores.add(set);
    }

   Util.gerarRelatorio(listaSetores, parametrosRelatorio);

Comment: Um `Setor`pode ter vários outros setores dentro do `setorImpressaoPDF`? Isso é estranho. Se o setor pai e o setor filhos forem coisas dieferentes, a situação fica mais simples.
Comment: é isso mesmo victor
Um Setor pode ter vários outros setores dentro do setorImpressaoPDF. ao final eu fico grupado com o código e siglasetor e uma lista . É justamente para relatório.
Answer: Isso daqui deve resolver:
Map<String, List<Setor>> map = setores
        .stream()
        .collect(Collectors.groupingBy(Setor::getSiglaSetor));

List<Setor> listaSetores = map.values().stream().map(lista -> {
    Setor set = new Setor();
    set.setSiglaSetor(lista.get(0).getSiglaSetor());
    set.setCodigo(lista.get(0).getCodigo());
    set.getSetorImpressaoPDF().addAll(lista);
    return set;
}).collect(Collectors.toList());

Ou então, pode usar esse equivalente, se você quiser ser um pouco mais breve:
List<Setor> listaSetores = setores
        .stream()
        .collect(Collectors.groupingBy(Setor::getSiglaSetor))
        .values()
        .stream()
        .map(lista -> {
            Setor set = new Setor();
            set.setSiglaSetor(lista.get(0).getSiglaSetor());
            set.setCodigo(lista.get(0).getCodigo());
            set.getSetorImpressaoPDF().addAll(lista);
            return set;
        }).collect(Collectors.toList());

Entretanto:

O que você quer montar é uma lista de grupos de setores, e não uma lista de setores. A classe Setor deveria ter uma única responsabilidade, que é a de descrever o que é um setor no seu domínio da aplicação. Entretanto, a sua classe Setor está com uma segunda responsabilidade, que é a de agrupar setores de mesmo código para a impressão do PDF. Assim sendo, o melhor é ter uma classe Grupo para que cada classe tenha só uma responsabiliade.
O nome do método getSiglaSetor() é redundante, pois uma vez que ele está na classe Setor, o sufixo Setor no nome é desnecessário e getSigla() já seria o suficiente.

Assim, com essa classe nova, acho que isso seria melhor:
public class Grupo {
    private final String sigla;
    private final String codigo;
    private final List<Setor> setores;

    public Grupo(List<Setor> setores) {
         this.sigla = setores.get(0).getSigla();
         this.codigo = setores.get(0).getCodigo();
         this.setores = setores;
    }

    public String getSigla() {
        return sigla;
    }

    public String getCodigo() {
        return codigo;
    }

    public List<Setor> getSetorImpressaoPDF() {
        return setores;
    }
}

O código com o stream ficaria assim:
List<Grupo> listaGrupos = setores
        .stream()
        .collect(Collectors.groupingBy(Setor::getSigla))
        .values()
        .stream()
        .map(Grupo::new)
        .collect(Collectors.toList());

Caso queira manter a ordem original, pode trocar isso:
        .collect(Collectors.groupingBy(Setor::getSigla))

Por isso:
        .collect(Collectors.groupingBy(
            Setor::getSigla,
            LinkedHashMap::new,
            Collectors.toList()
        ))

Comment: Funcionou mas a ordenação não veio a mesma. Como posso fazer com LinkedHashMap no groupingBy?
Comment: Acho que com LinkedHashMap manterá a ordenação que veio da lista
Comment: @user2509556 Resposta editada.

Transformar Collections em Stream


Will the compiler inline the codes if the codes involving thread manipulations?

Question: I want to figure out the behavior of C++ compilers when a function involving thread manipulations and marked as inline.
For instance, this is a member method of a class. :
  inline Vec3 Pos() {
    unique_lock lock(mutex_);
    return pos_;
  }

If it's called by some client codes, will the compiler inline the codes (i.e. unroll the codes)? If it does, what is the unrolled version? Unscoped or scoped?
Answer: In machine code there is no somthing like "scope". "scope" is language concept, which defines lifetime of variables.
Now in C/C++ there is "AS IF rule", meaning that compiler has right to do any transformation of code as long as all its visible outcomes remains unchanged. So effects of "scope" must remain unchanged.
In the past inline keyword meant "ensure this code is inserted to caller code". Nowadays it means "do not report an error, if you will find redefinition of this function". Compiler may insert this function code into callers code, but it doesn't have to.


Mongo eval arguments taken from a list bash script

Question: I am working on a bash script and would like to have a for loop iterate over specific collections in mongo and perform a count. If any of these specific collections is non-zero, then break the loop.
I have initialize this variable inside my script (assume the connection is working):
MONGO_EVAL="mongo prod $MONGO_CONN_CONF --quiet --eval"

and also a list for specific collections (initialized above, at an early phase in the script):
db_collections=(collectionA collectionB collectionC....)

Then iterate over a for loop and count the documents on each collection.
 for str in ${db_collections[@]}; do
   $MONGO_EVAL 'db.$db_collections.count();'
 done

How do I do it the right way?
Answer: Should be rather this:
db_collections=(collectionA collectionB collectionC....)

for str in ${db_collections[@]}; do
    mongo "$MONGO_CONN_CONF" --quiet --eval "db.${str}.count();"
done

or
for str in ${db_collections[@]}; do
    mongo "$MONGO_CONN_CONF" --quiet --eval "db.getCollection('${str}').count();"
done

or
mongo "$MONGO_CONN_CONF" --quiet --eval "for (let c of ['collectionA', 'collectionB', 'collectionC']) db.getCollection(c).count();"

Note, you have to use double quotes ("), otherwise ${str} is not replaced by variable value.
Regarding your actual problem "If any of these specific collections is non-zero, then break the loop" if could be like this:
for (let c of ['collectionA', 'collectionB', 'collectionC']) {
   let count = db.getCollection(c).count();
   if (count > 0) break;
}

Bear in mind, this loop actually does nothing, just count and potentially exit. I assume you would also need at least a print(c) or something similar.
Comment: Just another question if I may, is it possible to count and use the array list in the same for loop? I mean,        MONGO_EVAL="mongo prod $MONGO_CONN_CONF --quiet --eval"

for str in ${db_collections[@]}; do
  let count= ($MONGO_EVAL "db.${str}.count();")
  if (count > 0) break;
done
Comment: You mix **bash** script and **javaScript** When you use `--eval "xxx"` then `xxx` is a `JavaScript`, anything outside is `bash`.
Comment: I see. So if I use the first solution you suggested, Is there a way to retrieve the count result into a variable? I mean, I don't want to repeat the array values all the time as I use it in multiple places in my script. I want to be able to use my bash array somehow or extract to a js file and pull it from there.  So say I have the following lines (which works): `db_collections=(CollectionA CollectionB CollectionC..)     for str in ${db_collections[@]}; do
  $MONGO_EVAL "db.${str}.count();"
done
`    how do I save the output of the $MONGO_EVAL query? Sorry I'm new to it, tried multiple wa
Comment: Would be `cnt=$( mongo "$MONGO_CONN_CONF" --quiet --eval "db.${str}.count();" )`  or `cnt=\`mongo "$MONGO_CONN_CONF" --quiet --eval "db.${str}.count();"\``  (Syntax `$( )` is more modern than `\`\``) The eval prints the number of documents, to STDOUT and this value will be stored in variable `cnt`


How to analyse a Likert-type scale with a very small sample size (n=15)?

Question: Data description: I have data from questionnaire data on 15 participants (small sample). Parents rated the frequency that they rough and tumble with their child: (1) Never, (2) not very often, (3) once per month, (4) once or more per week, (5) every day.
Initial analyses: So far I have created several bar charts and am explaining them using percentages (e.g., 78% of the boys rough and tumble with one or other or both of their parents once or more per week this figure is only 60% for the girls).
Questions

Should I use  medians  instead of  means?
Is the sample size of 15 too small for meaningful results?
Can I perform a meaningful Chi-square or other statistical test?
Comment: In broad terms, chi-square tests are possible, but the sample size of 15 is likely to bite in one or two ways (1) your expected frequencies may be small (2) you need strong effects to establish significant differences. Also, the chi-square tests take no account of the Likert scale. Those are reasons why many people would prefer Mann-Whitney-Wilcoxon or ordinal logit here, although as said your sample size is small. In broad terms, if sample size is small for one test it is small for another and using a different test is not a solution. Using the best test for the data is always a good idea.
Comment: Incidentally, this really hasn't much to do with a Likert scale.
Answer: With a sample size of 15, any difference that is statistically significant will have to be huge, but the results will be "meaningful".
However, as an analysis technique, I'd suggest ordinal logistic regression with the Likert scale as the dependent variable and one independent variable at a time.


Finding poles of $\frac{1}{1 + z^4}$?

Question: $$f(z) = \frac{1}{1 + z^4}$$
has poles when $z^4 + 1 = 0$
$\implies (z^2 + i)(z^2 - i) = 0$
$\implies (z^2 - i) = 0$ when $z = \sqrt{i}$ or $z = -\sqrt{i}$.
But how do I solve the equation $(z^2 + i) = 0$?
Thanks.
Comment: If $z=i$ is $z^2-i=0?$ Pretty sure that's wrong.
Comment: It is not true that $\;z^2-i=0\implies z=\pm i\;$ ...you must calculate both square roots of $\;i\;$ , and of $\;-i\;$ for $\;z^2=i=0\;$ .
Comment: Sorry, typo! Fixed.
Answer: $$z^4=-1=e^{i\pi}=e^{(2n+1)\pi i}$$ where $n$ is any integer
$$\implies z=e^{\dfrac{(2n+1)\pi i}4}$$ where $n\equiv0,1,2,3\pmod4$
We can use Euler Formula to express $z$ in a more familiar form
Answer: To have $z^2+i=0$ that means $z^2 = -i$. We know $e^{3i\pi/2} = -i$, so $$z^2 =e^{3i\pi/2} \\ \implies z = \pm \sqrt{e^{3i\pi/2}} \\ \implies z = \pm e^{3i\pi /4}$$
Answer: For example:
$$z^2=-i=e^{\frac{3\pi i}2+2k\pi i}=e^{\frac{\pi i}2\left(3+4k\right)}\;\implies z=e^{\frac{\pi i}4\left(3+4k\right)}\;,\;\;k=0,1\implies$$
$$z_0=e^{\frac{3\pi i}4}=\frac1{\sqrt2}(-1+i)$$
$$z_1=e^{\frac{7\pi i}4}=\frac1{\sqrt2}(1-i)$$

Finding poles of $\frac{1}{1 + z^4}$?


Rewrite Links Array to include Nesting

Question: I'm attempting to modify the language switcher links in a block so that the items are properly nested per my site's menu structure.
Currently, it outputs:

English Link

Japanese Link

Spanish Link

I need:

English Link

Japanese Link

Spanish Link

The $build['content']['#links'] array contains:
array (size=4)
  'en' =>
    array (size=5)
      'url' =>
        object(Drupal\Core\Url)[14062]
        ...
    'ja' =>
        array (size=5)
          'url' =>
            object(Drupal\Core\Url)[14062]

How can I modify this array so that elements are nested in a ul under the first link?
Answer: In my experience, the structure you're looking for is created by the template layer. I would not recommend changing the link array directly. A good example template is core's stable theme's menu.html.twig. It uses a recursive twig macro to create nested lists.

Rewrite Links Array to include Nesting


Divisibility of polynomials in a subfield of a field.

Question: I am trying to prove the following assertion:

Let $K\subset L$ be fields, let $f,g\in K[x]$ be such that $f\mid g $ in $L[x]$, then $f\mid g$ in $K[x]$.

We clearly have that $fh=g$ for some $h\in L[x]$. We want to show that $h\in K[x]$. Suppose that $h\notin K[x]$. I am not sure how to argue towards a contradiction from here.
Comment: maybe I can say that the coefficients of $h$ are obtained from the coefficients of $f$ and $g$ by operations $\pm, \times, /$ and this means that these coefficients have to be in $K$?
Answer: Let $A$ and $B$ be domains with $A\subseteq B$. We say that the ring extension $B/A$ is good if the following implication holds:
$$\style{font-family:inherit;}{\text{For every}}\ f\in A\setminus\{0\}\ \style{font-family:inherit;}{\text{and}}\ h\in B,\ \style{font-family:inherit;}{\text{if}}\ fh\in A\ \style{font-family:inherit;}{\text{then}}\ h\in A\,.$$
We claim that if $B/A$ is good then $B[x]/A[x]$ is good as well. In fact, let $f\in A[x]\setminus\{0\}$ and $h\in B[x]\setminus\{0\}$ of degrees $m$ and $n$ respectively be such that $fh\in A[x]$. If $f=ax^m+f_1$ and $h=bx^n+h_1$, with $a\in A\setminus\{0\}$ and $b\in B\setminus\{0\}$, then the leading coefficient of $fh$, namely $ab$, lies in $A$ by hypothesis, so by goodness we obtain $b\in A$. This implies $fh_1=fh-bx^nf\in A[x]$, and now we can repeat the argument with $h_1$ instead of $h$. Continuing in this way we prove that all the coefficients of $h$ lie in $A$ as desired.
As a corollary, we obtain (as mentioned by user26857) that if $L/K$ is a field extension then the ring extension $L[x_1,\dots,x_n]/K[x_1,\dots,x_n]$ is good (because it is easily verified that $L/K$ is good).
Comment: (+1) This is nice! Is the notion of *goodness* something completely genuine for this purpose, or does it show up in other contexts es well?
Comment: @azimut Whenever I am working on a problem I call the relevant property "good" just for brevity ;-). The notion of *goodness* in this case is completely *ad hoc*, just for the problem, but who knows? perhaps in some distant future it will become important!!
Comment: @azimut Such extensions are called *inert* by Paul Cohn. They play a key role in various factorization matters, e.g. see [this answer.](https://math.stackexchange.com/a/127332/242)
Comment: @BillDubuque: thank you for that pointer!
Answer: Let $\varphi:K[x]\to L[x]$ be the inclusion. Denote by $\langle f\rangle_L$ the ideal generated by $f$ in $L[x]$ and by $\langle f\rangle_K$ the ideal generated by $f$ in $K[x]$. I claim that $\varphi^{-1}(\langle f\rangle_L)=\langle f\rangle_K$. This will prove your statement.
Indeed, $\varphi^{-1}(\langle f\rangle_L)$ is an ideal of $K[x]$ and $K[x]$ is a principal ideal domain, therefore $\varphi^{-1}(\langle f\rangle_L)$ is generated by some polynomial $f'\in K[x]$. Since $f\in\varphi^{-1}(\langle f\rangle_L)=\langle f'\rangle_K$, this means that $f=u\cdot f'$ for $u\in K[x]$. Conversely, $\varphi(f')\in\varphi(\varphi^{-1}(\langle f\rangle_L))\subseteq\langle f\rangle_L$, so (remember that $\varphi$ is just an inclusion) basically $f'\in\langle f\rangle_L$, i.e. $f'=v\cdot f$ for some $v\in L[x]$.
Sticking the two equations together, this means $f=uvf$ and canceling $f$ implies $u=v^{-1}$, so $u,v\in K$. This means that $\varphi^{-1}(\langle f\rangle_L)=\langle f\rangle_K$ as claimed.
Finally, $g\in\langle f\rangle_L$ is just the same as saying $f\mid g$ in $L[x]$ and equivalently over $K$.
Comment: Though this proof doesn't work for polynomial rings in several variables, the result holds true.
Answer: Let $f\mid g$ in $L[x]$. Polynomial long division yields a polynomial $q\in L[x]$ with $f = gq$. A closer look at the polynomial long division algorithm shows that the coefficients of $q$ are computed by repeatedly applying field operations to the coefficients of $f$ and $g$. So if the coefficients of $f$ and $g$ are in $K$, then the computed coefficients of $q$ must be in $K$, too.
This shows that $q \in K[x]$ and therefore $f\mid g$ in $K[x]$.
Answer: Write $g=fq+r$, with $q,r \in K[x]$ and $r=0$ or $\deg(r)<\deg(f)$. Write $g=fh$, with $h \in L[x]$.
Then $r = f(h-q)$. If $r\ne0$, then $h-q\ne0$, and so $\deg(f(h-q))\ge \deg(f) > \deg(r)$. Thus, $r=0$.
The only detail is that the degree of a polynomial in $K[x]$ remains the same when it is considered as a polynomial in $L[x]$.


What is the gradient of $f(x, y, z) = \sqrt{x^2+y^2+z^2}$?

Question: What is the gradient of $f(x, y, z) = \sqrt{x^2+y^2+z^2}$?
I know that $\nabla f = \left\langle\frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z}\right\rangle$ or equivalently $\nabla f = \frac{\partial f}{\partial x}\mathbf{i} + \frac{\partial f}{\partial y}\mathbf{j} + \frac{\partial f}{\partial z}\mathbf{k}$.
Eventually, I am going to evaluate this gradient at a point and then dot it with some given unit vector to find a directional derivative. I think maybe what is troubling me is the radical in $f$. Will I have to use the chain rule in order to find the three partial derivatives?
I tried this:
$$\frac{\partial f}{\partial x} = \frac{1}{2}(x^2 + y^2 + z^2)^{-\frac{1}{2}}2x$$
$$= \frac{x}{\sqrt{x^2 + y^2 + z^2}}$$
That result looks ugly to me. However, if I did that partial derivative correctly, then I think I know what I am doing.
Comment: The partial derivative is correct. The other two are similar. I disagree that it looks ugly.
Comment: It's correct, not ugly at all.
Comment: Note that the denominator is the distance $r$ from the origin, so $\dfrac{\partial f}{\partial x}=\dfrac{x}{r}.$ We get analogous results for the other derivatives, so $\nabla r=\dfrac{\mathbf{r}}{r}=\hat{\mathbf{r}}$---a cute result if there ever was one!
Answer: $$\nabla \|x\| = \frac{x}{\|x\|} $$
where $x = (x_1,x_2,\ldots, x_n)$ and $\|x\| = \sqrt{x_1^2+x_2^2+\ldots + x_n^2}$.
Answer: I'm fond of deriving this result as such. Note that $f(\mathbf{r})^2=x^2+y^2+z^2=\mathbf{r}\cdot \mathbf{r}$ by the definition of the dot product. Then the product rule for gradients implies $\nabla (f(\mathbf{r})^2)=2f(r)\nabla f(\mathbf{r})$ and therefore $$\nabla f(\mathbf{r})=\dfrac{\nabla (f(\mathbf{r})^2)}{2f(\mathbf{r})}=\dfrac{\nabla(x^2+y^2+z^2)}{2f(\mathbf{r})}=\dfrac{\langle 2x,2y,2z\rangle}{2f(\mathbf{r})}=\dfrac{\langle x,y,z\rangle}{\sqrt{x^2+y^2+z^2}}$$
In this form, the seemingly 'ugly' components become symmetric. Moreover, note that 1) this is a unit vector, 2) the denominator is just $\mathbf{r}$. So $\nabla f(\mathbf{r})=\dfrac{\mathbf{r}}{\sqrt{x^2+y^2+z^2}}=\dfrac{\mathbf{r}}{|\mathbf{r}|}=\hat{\mathbf{r}},$ i.e. the gradient is always a unit vector pointing outwards from the origin. That seems rather nice to me!
Answer: So you're asking about what is $\nabla_{\vec{v}}f$ where $f = \sqrt{x^2 + y^2 + z^2}$. First, lets organize the answer:
$\nabla_{\vec{v}}f =
\begin{aligned}
     \begin{bmatrix}
          \frac{\partial f}{\partial x} \\
          \frac{\partial f}{\partial y} \\
          \frac{\partial f}{\partial z}
     \end{bmatrix}
\end{aligned}$ $\cdot \, \vec{v}$
Now, lets solve for
$\frac{\partial f}{ \partial x}$.
$$\frac{\partial}{\partial x}\left(\sqrt{x^2 + \overbrace{y^2 + z^2}^{\mathrm{a\ constant}}}\right)$$
Now, lets start, also just for the sake of space, I'll make this substitution $y^2 + z^2 =c$, so we have
$$
\frac{\partial f }{\partial x}
= \frac{d}{dx}\sqrt{x^2 + c}
$$
so $g(x) = \sqrt{x},\, h(x) = x^2 + c$
I am going to skip some steps.
$$g'(x) = \frac{1}{2\sqrt{x}}, \qquad h'(x) = 2x$$
$$\frac{d}{dx} = g'(h(x)) \bullet  h'(x) \rightarrow \frac{4x}{\sqrt{x^2 \, + \, c }} \rightarrow  \mathbf{\frac{x}{\sqrt{x^2 + y^2 + z^2}}}$$
Then, $$\frac{\partial f}{\partial x} = \frac{x}{\sqrt{x^2 + y^2 + z^2}}, \, \frac{\partial f}{\partial y} = \frac{y}{\sqrt{x^2 + y^2 + z^2}}, \, \frac{\partial f}{\partial z} = \frac{z}{\sqrt{x^2 + y^2 + z^2}}.$$
Okay, so now let's find a directional derivative! But first, let's go to the gradient. say $\vec{v} =
\begin{aligned}
      \begin{bmatrix}
            a \\
            b \\
            c
      \end{bmatrix}
\end{aligned}$
$$\begin{aligned}
       \begin{bmatrix}
       \frac{x}{\sqrt{x^2 + y^2 + z^2}} \\
       \frac{y}{\sqrt{x^2 + y^2 + z^2}} \\
       \frac{z}{\sqrt{x^2 + y^2 + z^2}}
       \end{bmatrix}
            \cdot
       \begin{bmatrix}
       a \\
       b \\
       c \\
       \end{bmatrix}
\end{aligned} =
\frac{xa \,+ \, yb \, + \, zc}{\sqrt{x^2 \, +\,  y^2 \, + \, z^2}}$$
I hope I helped you out on this page.


python pandas weird indexing for multiple rows but not one

Question: I have been playing around with pandas indexing and stumbled upon something pretty odd. I am trying to assign multiple rows of one dataframe to another dataframe. Assigning one row works, but assigning multiple rows does not. Below is some reproducible data. I generate my two dataframes.
centers=pd.DataFrame(np.nan, index=list(string.ascii_uppercase[:3]), columns=['x','y'])
data=pd.DataFrame(np.random.randn(50,2), index=range(50), columns=['x','y'])

Centers is an empty dataframe and I want to make the first three rows of 'centers' equal to the first three rows of 'data'.
centers
    x   y
A NaN NaN
B NaN NaN
C NaN NaN

data.head()
          x         y
0  1.195444  0.666973
1 -0.933807 -0.382923
2  0.582849  0.533059
3 -0.411232 -1.142588
4  0.144402 -0.991504

Originally, I thought it was an indexing issue as centers has letters and data has numbers. However I no longer think this is the case, because indexing one row at a time gives me the desired result. Here is zero index and here is one index both with desired results.
centers.iloc[0,:]=data.ix[0,['x','y']]
centers
          x         y
A  1.195444  0.666973
B       NaN       NaN
C       NaN       NaN

centers.iloc[1,:]=data.ix[1,['x','y']]
centers
          x         y
A  1.195444  0.666973
B -0.933807 -0.382923
C       NaN       NaN

However doing this with multiple rows does not.
centers.iloc[0:3,:]=data.ix[0:2,['x','y']]
centers
    x   y
A NaN NaN
B NaN NaN
C NaN NaN

Each dataframe individually is exactly what I think it is.
centers.iloc[0:3,:]
    x   y
A NaN NaN
B NaN NaN
C NaN NaN

data.ix[0:2,['x','y']]
          x         y
0  1.195444  0.666973
1 -0.933807 -0.382923
2  0.582849  0.533059

Why might this be the case and how do I fix it? (I know I can solve this exact issue by setting centers equal to my data index, but I want an answer with indexing)
Answer: The issue is that the indices don't match hence no assignment occurs if you call .values to return a np.array then it works:
In [76]:
print(centers.iloc[0:3,:])
print(data.ix[0:2,['x','y']])

    x   y
A NaN NaN
B NaN NaN
C NaN NaN
          x         y
0 -1.081909 -0.672130
1 -0.144562  0.863694
2  0.214779  1.193998

In [77]:
centers.iloc[0:3,:] = data.ix[0:2,['x','y']].values
centers

Out[77]:
          x         y
A -1.081909 -0.672130
B -0.144562  0.863694
C  0.214779  1.193998

So what you're observing is not a bug, it is by design
Comment: Thank you for your response. I see that the indices do not match, but when I just do the first index, centers is index A and data is index 0 and it works. If I replace 1 with 0 it works too. So only when I do multiple rows does it break, thus I do not think it is in index not matching issue
Comment: Please edit your question demonstrating how you think that aligning on the index doesn't work and is not relevant
Comment: Sorry if I was not clear in my response, I have added the changing 1 index in my question
Comment: When you select a single row and assign to a single row it's a series so there is no alignment on the index needed, when you select multiple rows you return a df and assign to a df, alignment is performed on the index and columns hence the error


Intuitive examples of importance sampling

Question: My background is computer science. I am fairly new to monte carlo sampling methods and, although I understand the math, I have hard time coming up with intuitive examples for importance sampling. More precisely, could someone provide examples of:

an original distribution one cannot sample from but one can estimate
an importance distribution which can be sampled from and adequate for this original distribution.
Answer: Suppose you want to simulate the mean of a standard normal distribution that is truncated to the unit interval $[0,1]$.
An inefficient way would be to take draws from $N(0,1)$, but only keep draws in [0,1]. Then you calculate the mean using only the data you kept.
A more efficient way would be to draw from $U(0,1)$, and calculate the importance weights, which you can use in calculating a weighted mean.


How to move a website to a new server?

Question: I am going to move my website to a new server.
I need to copy the /var/www directory to the new server.
Should I use SCP or RSYNC ?
Answer: You can use either SCP or Rsync, they will both copy files for what you need.
For the following example, assume the following:

Your username on www1.example.com is jcitizen.
Your old web server is www1.example.com.
Your new web server is www2.example.com.
jcitizen on the old server has read permissions recursively on /var/www
The user on the new server has read & write permissions recursively on /var/www

SCP
scp -r email@example.com:/var/www /var/www

RSYNC
rsync -avzh email@example.com:/var/www /var/www

How to move a website to a new server?


Best practice to upgrade drupal 9.4 to 9.5? Composer or Drush method?

Question: I can run this command to upgrade drupal 9.4 to 9.5, but I can also do it in drush. Which method is better and why?
composer require drupal/core-recommended:9.5.0 drupal/core-composer-scaffold:9.5.0 drupal/core-project-message:9.5.0 --update-with-all-dependencies
Comment: As far as I know it cannot (should not) be done with Drush. Everyone should be leveraging Composer at this point.
Answer: Let me preface with what each of these are:
Drush is a command line shell and Unix scripting interface for Drupal. Drush core ships with lots of useful commands and generators. Similarly, it runs update.php, executes SQL queries, runs content migrations, and misc utilities like cron or cache rebuild.
Composer is a tool for dependency management in PHP. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.

You cannot use Drush to update/upgrade Drupal 9. That particular Drush functionally/feature got deprecated. As Drupal 9 requires Drush 10 or higher, it doesn't have it.

 source: Updating Drupal core via Drush
Composer is a very popular PHP tool used outside the Drupal world to manage dependencies.
Drupal decided to adopt it. Once this happened, there was no need for Drush to re-invent the wheel when there is already a dedicated tool built for this job specifically and that does it very well.


Scalable way to install SSL certificates without downtime

Question: We have a SaaS application that allows customers to use their own domain – pretty typical. At its core, the architecture has a simple catch-all virtual host (apache) and the software does the work of resolving which customer it is based on the hostname.
However, many of our customers require that custom domain to support SSL. Currently we do this by adding a (higher precedence) virtual host with an SSL certificate and restarting apache.
While this works, it has a number of issues:

You either have to restart apache which means momentary downtown, or switch the dns to an entirely new server stack.
On the off chance there is an issue we didn't catch with the SSL certificate, Apache throws a fatal error and will not be able to restart.
It would be impossible or at least impractical to roll this out to thousands of users.

In short – it doesn't scale. We've explored SSL termination at the load balancer...it's promising, but we can't find any load balancers that support multiple SSL certificates (via SNI).
Moving forward this is increasingly a bottle neck of the product – to the point we would be willing to alter architecture or move away from apache if needed.
Comment: More than one server behind a load balancer, with rolling restarts.
Comment: You said "we would be willing to alter architecture". Restarting servers used by thousands of concurrent users is a solved problem.
Comment: Sure, that falls into the drawback #1 category though – something we're trying not to do. The spirit of the question is how can we install these things without a major update (like a restart). Restarting servers for 1000s of users and having them flow in/out of load balancers seems like a serious issue.
Comment: Interesting. I suppose I could see that working (+1). Similarly we could spin up new servers with the SSL installed and dropping old servers out...could work. Our plan is to have SSL installation be a feature the customers perform themselves, which gives me some pause to think their actions directly affect server count - maybe an unnecessary fear. So let me change the question slightly then to keep digging – are there any technologies that allow "hot" installation of ssl certificates without the need for *anything* to restart?
Answer:
We've explored SSL termination at the load balancer...it's promising, but we can't find any load balancers that support multiple SSL certificates (via SNI)

Really?  I had to double take on the post time of this question to make sure it wasn't a years old necro-thread because I can't think of any load balancers that don't support SNI in 2016.
Though the one I'm most familiar with is HAProxy which has supported SNI since 1.5 which apparently came out in June 2014.
While 1.5 doesn't technically support true zero downtime reloads for config changes, it has a "fast reload" option that is generally fast enough to not impact a typical site. But if you really want to get there, there's a Yelp Engineering blog post describing a method to do "true zero downtime" reloads that involves some fancy work with Linux tc and iptables to delay SYN packets during a reload.  From the article:

Restarting HAProxy has basically no effect on our traffic, causing only minor delays as can be seen in Figure 3. Note that this method is heavily dependent on how long HAProxy takes to load its configuration, and because we are running such a reduced configuration, these results are deceivingly fast. In our production environment we do observe about a 20ms penalty during HAProxy restarts.
Comment: This is great to know, I'm familiar with cloud balancers such as Rackspace and Amazon's ELB – neither of which currently support SNI. You're making a good case for having home-rolled one though.
Comment: Hah, I didn't even consider the case that you guys might be hosting your SaaS app in a public cloud environment.  I'm definitely not as well versed in the LBaaS options.
Answer: A load balancer means restarting a drained server is fine and not something to be avoided.
The customer could request a new domain or certificate. On the next batch of updates, this change is in a new config is deployed to some web servers. Drain the old web servers and stop them at zero connections. New connections are going to the new working config. If there is a problem, revert to the last config.
Add web servers to the load balancer for performance and availability reasons. Add load balancers when the complexity of the config is too much.


Baire category and relative topology

Question: The present problem is realted to the following posting in MSE.
Recall that for a given a topological space $(X,\tau)$, a set $E\subset X$ is nowhere dense in $X$ if $\operatorname{Int}(\overline{E})=\emptyset$. A subset of $X$ that can be written as a countable union of nowhere dense sets in $X$  is said to be a set of first category. The space $(X,\tau)$ is said to be of first category if $X$, as a subset of itself, is set of first category.
A set $A$ may be of first category in some space $(X,\tau)$ but not a subspace of first category. For example, $\mathbb{Z}\subset\mathbb{R}$ is a set of first category in $\mathbb{R}$ (the latter endowed with the usual Euclidean topology) but, $\mathbb{Z}$ as a subspace of $\mathbb{R}$ is not of first category, for the topology on $\mathbb{Z}$ inherited by that on $\mathbb{R}$ is the discrete topology in which every subset of $\mathbb{Z}$ is both open and closed.
The question that I have is: Suppose $A$ is considered as a subspace of $X$, that is $A$ is endowed with the topology $\tau_A$ described above. If $(A,\tau_A)$ is a space of first category, is $A$ a set of first category in $(X,\tau)$?

At first this may appear as a problem of semantics, but I think it is more nuanced than that.
I  think that in general, the answer to my question is no, but I have not found any counter-example yet.

Edit: following the reasoning of @Ruy, it turns out my guess was wrong, and that in fact $A$ is a set of first category in $X$.
Thanks for the interest and the answer!
Answer: Given a subset $C\subseteq A$, which is closed in $A$ and has no interior in $A$, then $\bar C$ (closure in $X$) cannot have interior in $X$.  Otherwise there is some non-empty open subset $U$ of $X$ with $U\subseteq \bar C$. Consequently $$U\cap A\subseteq \bar C\cap A =C,$$
And clearly $U\cap A$ is non-empty since otherwise
$$U\subseteq\text{int}(X\setminus A) =X\setminus\bar A\subseteq X\setminus\bar C,
$$
a contradiction.
This should be enough to prove your statement.

Baire category and relative topology


Calling function with variable that is being initialized

Question: I am learning C++ using the books listed here. In particular, I read that using an uninitialized local variable of built in type is undefined behavior. Now, I came across the below given example where the user seems to be using uninitialized variables x and y. The user says:

#include <string>

template<typename T>
T num_convert(const char* s, const T) {
 return static_cast<T>(std::stoll(s));
}

int main() {
//--------------------------v---------------> is this UB because x is uninitialized?
  int x = num_convert("55", x);
//-----------------------------------v------> is this UB because y is uninitialized?
  long y = num_convert("5555555555", y);
}

In the above example, I've used arrows to highlight the points where I have doubts. In particular, I want to know that are the above two highlighted statements UB because x and y are not initialized and the user is passing those to the function by value?
Comment: I disagree with @MartinMorterol. Using an indeterminate value in any way, even passing it to a function, is using the value and thus leads to UB. Remember: You pass the argument by *value* which means the value is copied and therefore used. If you passed it by reference or as a pointer to the variable, then that would be fine.
Comment: why do you want to pass a variable in the first place? It is unused and you simply want to convert it. Just do it like `int x = num_convert("55");`
Comment: If the second parameter was used in the function that will be UB. In your case it is not, so even if the value is undefined the programe is not UB. Having a nullptr pointer is not UB, dereferencing it is, same logic with uninitilized variables
Comment: @Raildex This is not my code. Note in my question I have clearly mentioned that this code is posted by some other user [here](https://stackoverflow.com/questions/73515132/is-there-any-generic-conversion-from-stdstring-to-numeric-type/73515190#73515190). I am just trying to understand this code for academic purposes.
Comment: I say run the code through ubsan, if it doesn't light up, it's probably a safe bet it's safe.
Comment: Turn on warnings when building: The compiler should tell you that you're *using* the variables.
Comment: The original author of that code is correct: it's a hack. Why not create a class for this and overload the conversion operators: https://godbolt.org/z/edsrrjsvr
Comment: @Someprogrammerdude of course you are right in principle. But to be honest since the uninitialized variable is ignored I cannot imagine a situation where this is actually causing a problem.  Can you think of a concrete example where a compiler optimization will cause the program to misbehave due to the UB here ?
Comment: @wohlstad While the UB might not create an issue in practical terms, the [warning](https://godbolt.org/z/45MfP14nc) definitely can. If you use this in a project that treats warnings as errors, and it warns on uninitialized values, then you will have a problem.
Comment: @paddy I usually enforce "treats warnings as errors" in all my projects so it's a valid point. But I was trying to understand what kind of actual runtime problem can arise from this (due to the optimizer messing up the code due to the UB).
Comment: @wohlstad In a constexpr context : https://wandbox.org/permlink/zych05m1K23th7P4
even without warning as error, it wont compile (like any UB). If you change `const T` to `const T&` It not UB anymore and it compile
Comment: @Someprogrammerdude No, you should look carefully. The unused argument is/was passed by value. The user [changed their answer](https://stackoverflow.com/questions/73515132/is-there-any-generic-conversion-from-stdstring-to-numeric-type/73515190#comment130047670_73515190) by [editing](https://stackoverflow.com/posts/73515190/revisions) after i told them that the program has UB. Did you not see the [comments](https://stackoverflow.com/questions/73515132/is-there-any-generic-conversion-from-stdstring-to-numeric-type/73515190#comment130047246_73515190) below that answer?
Comment: @JasonLiam Ah, missed the editing history. Thanks for pointing it out.
Comment: @Someprogrammerdude ok
Answer:
I want to know that are the above two highlighted statements UB because x and y are not initialized and the user is passing those to the function by value?

Yes, your understanding is correct. The variable x and y are uninitialized local variables and they're being used/passed by value when calling the functions. Thus, the program has undefined behavior as x and y have indeterminate values and you're using/copying those values to the parameter of the function.
Comment: @TheDreamsWind The `value` part is important because there is always a **conceptual copy** when passing argument by value. So even in principle, the program has UB.
Comment: I wonder why the `value` part is important in this context: despite being passed that way, the actual values are not used in the body of the function, and the compiler still can deduce the types from declarations. E.g. in unevaluated context couldn't, say, `sizeof(x)` be defined behaviour even if `x` is only defined as `int x`?