Drawing a shape on a JPanel which already uses the paint method

Question: Let's say I have two classes, the first extends JPanel and using Graphics draws a playing board on it. The second makes a JFrame and adds the panel to it.
You can imagine the frame looking something like this:

I now want to add an ellipse to a specific rectangle on click. I understand that I would be using a two-dimensional array in order to get the position I wanted, but I don't understand how the ellipse itself would be drawn on to the existing panel since I used the paint(Graphics g) to draw the playing board.
Here is the code for drawing the board itself if you need it:
class MyBoard extends JPanel {
    private static int height = 6;
    private static int width = 7;
    private static int squareSize = 100;
    private int board[][] = new int[height][width];

    public void paint(Graphics g) {
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
            }
        }
    }
}

Thanks!
Comment: First off: You should never override `paint` but always `paintComponent`. Second: In the overriden code you should generally call `super.paint` (or `super.paintComponent` once you made the switch). Third: You could simply save the square you want to draw in (let's say x = 1, y = 0) and then draw the ellipse there after your two for-loops like `g.drawOval(x*squareSize + squareSize/4, y*squareSize + squareSize/4, squareSize/2, squareSize/2);`
Comment: @Ben Thanks! I switched to the `paintComponent` and added the `super` , but could you tell me what the difference is? They do the same thing right? Also lets say I wanted to create the ellipse on click. How would I go about that? Make an mouse listener and get the coordinates, but how would I then pass those x and y values to the `paintComponent` ?
Answer: First two things that you should remember: Never override paint but paintComponent and call super.paintComponent in there so that borders and everything works as expected. Regarding why this is the case, reference this question: Difference between paint() and paintcomponent()?

Now to answer your question. Assuming you have an existing logic to determine in which square you want to draw your Ellipse (let's assume you have two Integers elX and elY that are the column and row of your square) you can simply go and draw it after you have finished drawing the board itself.
Imagine sample code like this:
@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    // Draw the board
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            g.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
        }
    }

    // Draw the ellipse at the correct location using half the size of a normal square.
    g.drawOval(elX * squareSize + squareSize / 4, elY * squareSize + squareSize / 4, squareSize / 2 , squareSize / 2);
}

Now the final part of how to go about actually determining where to draw your ellipse.
A simple solution would be to add a MouseListener to your panel. And then in the mouseClicked method you calculate where you actually did click.
Could look like this:
this.addMouseListener(new MouseListener()
{

    @Override
    public void mouseClicked(MouseEvent e)
    {
        int column = e.getX() / squareSize;
        int row = e.getY() / squareSize;

        board[column][row] = 1;
    }

    [...] // add the other methods to override

}

Then you slightly adapt your paintComponent method with something like this:
for (int column = 0; column < width; ++column)
{
    for (int row = 0; row < height; ++row)
    {
        if (board[column][row] == 1)
        {
            g.drawOval(column * squareSize + squareSize / 4, row * squareSize + squareSize / 4, squareSize / 2, squareSize / 2);
        }
    }
}

and now you draw an ellipse everywhere you click. You could also check if the clicked square already has 1 set as a value and reset it to 0 to have some toggle mechanism or increment it and draw different things based on the integer value... it's all up to you :)
Comment: Thanks! I also have a follow up question : how could I draw the ellipse on different squares when I pressed on them? I would use the mouse listener and get the x and y coordinates and then what would I do to pass them to the `paintComponent` ?
Comment: @SomeStudent I've updated the answer a bit. Also I just used the currently unused `board` 2D-Array for this. Obviously feel free to change this to single variables or just use another array.
Comment: Glad I could help.


How do I make a table that prints out in a row all the same columns in a database?

Question: What I am trying to do here is echo out every columns "unit" within my database. In my database I have columns: evaluation, unit, percent and due date. I want all the units to appear on the table in a row as I have tried to do it but can't seem to find out how to do this. this is the code that I have tried <?php echo $unit ?> but does not seem to work.
Example
My database:
project0     unit1     15%     22-07-2014
project1     unit1     10%     24-07-2014
project2     unit2     20%     27-07-2014
project3     unit3     30%     29-07-2014

Code
<?php
mysql_connect('localhost','root','root');
mysql_select_db('Eviden');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sin título</title>

<form id="form1" name="form1" method="post" action="">

    <?php
        $result = mysql_query("SELECT * FROM peviden");
        while($row=mysql_fetch_array($result)){
            $unit=$row['unit'];
            $name=$row['name'];
      ?>

        <?php echo $unit ?>
        <?php echo $unit ?>
        <?php echo $unit ?>
        <?php echo $unit ?>

        Name

        Sebastian

        Zack

        Daniel

      <?php
      }
      ?>

</form>

Comment: Can you add the column names to your database sample?
Answer: I believe this is happening because mysql_fetch_array returns an array, which would store the results of each row as

    row[0] // evaluation
    row[1] // unit
    row[2] // percent
    row[3] // due date

Try using the array format, and optionally specify the order for the array as you go:

<?php
    $result = mysql_query("SELECT evaluation, unit, percent, due_date FROM peviden");
        while($row=mysql_fetch_array($result)){
            $evaluation=$row[0];
            $unit=$row[1];
            $percent=$row[2];
            $duedate=$row[3];
?>

Answer: The first thing you have to do is fix your database call. Right now you are looping over the results and assigning $unit a new value at each iteration over the loop. So, we're going to fix that here:
$result = mysql_query("SELECT * FROM peviden");

// New Array to avoid PHP notifications
$unitsArray = array();

// Start our loop over our results
while($row=mysql_fetch_array($result)){
    // Add an entry to our array with two values for unit and name
    $unitsArray[] = array( 'unit' => $row['unit'],
                         'name' => $row['name']
                       );
}

Now that we've assigned all our units to a useable value, in your HTML code you need to loop over them again to get them displayed correctly:

<?php
    foreach($unitsArray as $entry) {
?>
    <?php echo $entry['unit']; ?>
<?php
    }
?>

This will create one TD for each unit across the table.


3 NICs in VMware ESX 5.5.0 cannot connect to each other

Question: I have a Vmware ESXi 5.5.0 hypervisor, installed on a desktop pc with 3 physical NICs. The first NIC is connected to the internet (WAN), the 2nd and 3rd NICs have Access Points installed (plugged in) to them.
I would like to create a single network above them, in which all devices can connect to each other, and install a Windows server, that would connect to the internet and distribute internet among the virtual machines I install on the server, and the 2 APs.
The issue is that no matter what settings I try in the ESX network configuration, I cannot team or bridge the 2nd and 3rd NIC to the first one. The result is that the virtual machines can get internet from a Windows server, if I set them up to be on the same vSwitch, but the 2 APs are not getting a DHCP, or cannot ping the Windows server.
Is there a way to connect these 3 NICs using only this machine, and virtual machines on it to combine the 3 networks, and make them accessible for each other?
Answer: This is a bit of a mess and not a good application for VMware ESXi. A physical router/firewall and switch would be the better way to approach this.
However, you can create multiple vswitches.

vswitch0 could contain the public-facing network uplink and the public interface (vnic) of the Windows server.
vswitch1 could have the private interface of the Windows server, as well as the vnics of the other VMs you wish to have on the local "network".
vswitch1 should also have the other two physical NICS added to it as uplinks. You'd connect the access points to these.

For your Windows server, you need to have Routing and Remote Access features installed and ideally provide DHCP other other services on its private vnic.
Comment: Thanks for the help! We cannot add any new physical devices to the network. We have set up a solution like this in the first place, and the issue is, that the access points connected, cannot get a DHCP address. Other machines on vswitch1 do get an IP address via DHCP, but the two access points fail to get an IP address, also the DHCP server cannot be pinged from them, it looks like, that something in ESX is blocking the communication between vswitch1 and the two physical NICS, and the access points attached to them.


Question: Drupal 8 creates <link rel="canonical" href="/relative/url" /> by default.  support.google.com says:

Use absolute paths rather than relative paths with the rel="canonical"
  link element.
Use this structure:
  https://www.example.com/dresses/green/greendresss.html Not this
  structure: /dresses/green/greendress.html

I used the Google Search Console URL Inspection and found Google does not recognize relative urls as canonical.  It says:

User-declared canonical N/A

I believe this is causing some indexing problems for our multiple language website.  How can we convert the canonical urls to absolute as recommended by Google?
Answer: The metatag module gives you the ability to overwrite the 'canonical' metatag:

On the module's settings page (/admin/config/search/metatag)
Edit the General type
Under Advanced you'll find the Canonical field
Set the field's value to [current-page:url:absolute]
Save

That should do it. The instructions above are for Drupal 8.
Update 1:
If you are comfortable using hooks and working with PHP you may also use a theme hook (hook_page_attachments_alter) to achieve the same thing. Here's the api spec on drupal.org for the function.
Answer: The following function updates the rel tags in the head section of all pages on a website.  The "revision" and "shortlink" tags are deleted using unset(). The "canonical" tag is converted from a relative to an absolute url.  This function should be called from modulename_preprocess_html() of your custom module.
function canonical_shortlink_revision(&$variables) {

  foreach($variables['page']['content']['system_main']['#attached']['html_head_link'] as $key => $value) {

    if( ($value[0]["rel"] === "revision") || ($value[0]["rel"] === "shortlink") )
      unset($variables['page']['content']['system_main']['#attached']['html_head_link'][$key]);

    if($value[0]["rel"] === "canonical") {
      $href = $variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"];
      $href = \Drupal::request()->getSchemeAndHttpHost() . $href;
      $variables['page']['content']['system_main']['#attached']['html_head_link'][$key][0]["href"] = $href;
    }

  }
}

Comment: This is being addressed in Drupal core as well.  https://www.drupal.org/project/drupal/issues/3003713


How to properly set values to the controls of an instantiated View Controller?

Question: I have a class ErrorMessageViewController:
// ErrorMessageViewController.h
@interface ErrorMessageViewController: UIViewController
@property (nonatomic, strong) IBOutlet UILabel* messageTitle;
@property (nonatomic, strong) IBOutlet UILabel* messageContent;
@end

// ErrorMessageViewController.m
@implementation ErrorMessage
@synthesize messageTitle, messageContent;
@end

And I instantiate this view controller like this:
UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ErrorMessageViewController * errorMessage = (ErrorMessageViewController *) [storyboard instantiateViewControllerWithIdentifier:@"ErrorMessage"];
[[errorMessage messageTitle] setText:@"Error"];
[[errorMessage messageContent] setText:@"Duplicate ID"];
[[self navigationController] pushViewController:errorMessage animated:YES];

But the appearing View Controller's messageTitle and messageContent UILabel is empty. I have double check and make sure that the UILabels are connected to the Storyboard's UILabels.
Why is this happened? How to properly init an object's controls from instantiateViewControllerWithIdentifier:?
Answer: // ErrorMessageViewController.h
@interface ErrorMessageViewController: UIViewController
@property (nonatomic, strong) IBOutlet UILabel* messageTitle;
@property (nonatomic, strong) IBOutlet UILabel* messageContent;

@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *msg;

@end

UIStoryboard * storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ErrorMessageViewController * errorMessage = (ErrorMessageViewController *) [storyboard instantiateViewControllerWithIdentifier:@"ErrorMessage"];
errorMessage.title = @"Error";
errorMessage.msg = @"Duplicate ID";

[[self navigationController] pushViewController:errorMessage animated:YES];

In your 'viewDidLoad'
- (void)viewDidLoad {
    [super viewDidLoad];

    messageTitle.text = title;
    messageContent.text = msg;
}

Comment: Hey, this works! Thanks! Can I ask why this works, instead of setting the values directly to the controls?
Comment: Because upon your initialization it is not yet created. Your outlet are still null whether you set it to strong. Its like the viewController's View isn't yet created so upon viewDidLoad it works since on this part loadView() is already called and your outlets are created.
Comment: Agree, and change the outlets to weak.
Comment: @nferocious76 okay. thanks! Can I ask one more thing? Before, I also make a function to init the `title` and `msg` like `initWithTitle:andContent:`, which I call before `pushViewController:animated:` to replace `errorMessage.text = @"Error"` and `errorMessage.msg = @"Duplicate ID"`. But when viewDidLoad is called, their content is different (apparently, they return to become an uninitialised string, or even unallocated string, because the debugger raised error when I tried to access these variables when I init them using function like that). Why is that happened?
Comment: Because even if you pass it like that.. not until your view controller is pushed your view is just then prepared for you. What you can do is to fully customize it and start with loadView()
Comment: Note to your custom init: If you do it like that the content you'll see is the content set in the IB.


getting checkbox value from ag-grid column

Question: I have a checkbox in an ag-grid that I'm displaying the following way:
  {header: 'Cancel',
    field: 'IsCancel',
    cellRenderer: params => {
      return `<input type='checkbox' ${params.value ? 'checked': ''} />`
    }
  }

What I'm trying to achieve is that when the user clicks the Save button, I go thru each row and find out which checkbox has been checked.
I've tried using the code below to find out which checkbox has been checked.  Unfortunately, node.data.IsCancel is false even when I check a checkbox in the ag-grid:
  saveCustomer() {
    this.api.forEachNode(this.printNode)
  }

  printNode(node, index) {
    console.log('Customer Number is: ' + node.data.CustomerNumber);
    console.log('Cancel is: ' + node.data.IsCancel);
    if (node.data.IsCancel.checked) {
      console.log('Customer Number in checked is: ' + node.data.CustomerNumber);
    }
  }

Here is all of the code:
cancellation.component.html

  <ag-grid-angular class="ag-fresh"
    [columnDefs]="columnDefs"
    [rowData]="customerNames"
    (gridReady)="onGridReady($event)"
    class="ag-theme-balham">
  </ag-grid-angular>

  <button mat-raised-button color="primary" (click)="saveCustomer()">Save</button>

cancellation.component.ts
import { Component, Input, AfterViewInit, OnInit } from '@angular/core';
import { CustomerNameService } from '../customer-name.service';
import { CustomerNameCancellation } from '../customername-cancellation';
import { ColDef, GridApi, ColumnApi } from 'ag-grid-community';

@Component({
  selector: 'app-cancellation',
  templateUrl: './cancellation.component.html',
  styleUrls: ['./cancellation.component.css']
})
export class CancellationComponent implements OnInit {
  @Input('zipCode') zipCode: string;
  @Input('lastName') lastName: string;
  customerNames: Array<CustomerNameCancellation>;

  private api: GridApi;
  columnApi: ColumnApi;
  columnDefs: ColDef[];
  loadCancellation: boolean;
  params: any;

  constructor (private customerNameService: CustomerNameService) {
   this.columnDefs = this.createColumnDefs();
  }

  ngOnInit() {
    this.customerNameService
    .getCustomerNames(this.zipCode, this.lastName)
    .subscribe(data => {this.customerNames = data;})
    console.log("finished loading customers");
    console.log("zipcode is: " + this.zipCode);
    console.log("lastname is: " + this.lastName);
    this.loadCancellation = true;
  }

  onGridReady(params) : void {
    this.api = params.api;
    this.columnApi = params.columnApi;
    this.api.sizeColumnsToFit();
    this.params = params;
  }

  private createColumnDefs() {
    return [
      {header: 'Customer Number', field: 'CustomerNumber', sortable: true, filter: true},
      {header: 'First Name', field: 'FirstName', sortable: true, filter: true},
      {header: 'Middle Name', field: 'MiddleName', sortable: true, filter: true},
      {header: 'Last Name', field: 'LastName', sortable: true, filter: true},
      {header: 'Address', field: 'Address1', sortable: true, filter: true},
      {header: 'City', field: 'City', sortable: true, filter: true},
      {header: 'State', field: 'StateCd', sortable: true, filter: true},
      {header: 'Zip Code', field: 'ZipCode', sortable: true, filter: true},
      {header: 'Magazine Code', field: 'MagazineCd', sortable: true, filter: true},
      {header: 'Cancel',
        field: 'IsCancel',
        cellRenderer: params => {
          return `<input type='checkbox' ${params.value ? 'checked': ''} "/>`
        }
      },
      {header: 'Cancellation Date', field: 'CancellationDate', sortable: true, filter: true}
    ]
  }

  saveCustomer() {
    this.api.forEachNode(this.printNode)
  }

  printNode(node, index) {
    console.log('Customer Number is: ' + node.data.CustomerNumber);
    console.log('Cancel is: ' + node.data.IsCancel);
    if (node.data.IsCancel.checked) {
      console.log('Customer Number in checked is: ' + node.data.CustomerNumber);
    }
  }

  public checkedVal() {
    console.log(this.params.node.data);
    console.log(this.params.value);
  }

}

Update
I also tried using checkboxSelection: true.  But it shows "true" or "false" right next to the checkbox.
Updated #2
I used checkboxSelection: true.
There are two issues:
1) The value "true" or "false" shows next to the checkbox.  Please see the image.
2) For those checkboxes that already come back as "true" from the database, the checkbox isn't already checked.

Here is the updated code:
import { Component, Input, AfterViewInit, OnInit } from '@angular/core';
import { CustomerNameService } from '../customer-name.service';
import { CustomerNameCancellation } from '../customername-cancellation';
import { ColDef, GridApi, ColumnApi } from 'ag-grid-community';

@Component({
  selector: 'app-cancellation',
  templateUrl: './cancellation.component.html',
  styleUrls: ['./cancellation.component.css']
})
export class CancellationComponent implements OnInit {
  @Input('zipCode') zipCode: string;
  @Input('lastName') lastName: string;
  customerNames: Array<CustomerNameCancellation>;

  private api: GridApi;
  columnApi: ColumnApi;
  columnDefs: ColDef[];
  loadCancellation: boolean;
  params: any;

  constructor (private customerNameService: CustomerNameService) {
   this.columnDefs = this.createColumnDefs();
  }

  ngOnInit() {
    this.customerNameService
    .getCustomerNames(this.zipCode, this.lastName)
    .subscribe(data => {this.customerNames = data;})
    console.log("finished loading customers");
    console.log("zipcode is: " + this.zipCode);
    console.log("lastname is: " + this.lastName);
    this.loadCancellation = true;
  }

  onGridReady(params) : void {
    this.api = params.api;
    this.columnApi = params.columnApi;
    this.api.sizeColumnsToFit();
    this.params = params;
  }

  private createColumnDefs() {
    return [
      {headerName: 'Customer Number', field: 'CustomerNumber', sortable: true, filter: true},
      {headerName: 'First Name', field: 'FirstName', sortable: true, filter: true},
      {headerName: 'Middle Name', field: 'MiddleName', sortable: true, filter: true},
      {headerName: 'Last Name', field: 'LastName', sortable: true, filter: true},
      {headerName: 'Address', field: 'Address1', sortable: true, filter: true},
      {headerName: 'City', field: 'City', sortable: true, filter: true},
      {headerName: 'State', field: 'StateCd', sortable: true, filter: true},
      {headerName: 'Zip Code', field: 'ZipCode', sortable: true, filter: true},
      {headerName: 'Magazine Code', field: 'MagazineCd', sortable: true, filter: true},
      {headerName: 'Cancel',
        field:'IsCancel',
        editable: true,
        sortable: true,
        filter: true,
        checkboxSelection:true
      },
      // {header: 'Cancel',
      //   field: 'IsCancel',
      //   cellRenderer: params => {
      //     return `<input type='checkbox' ${params.value ? 'checked': ''} "/>`
      //   }
      // },
      {header: 'Cancellation Date', field: 'CancellationDate', sortable: true, filter: true}
    ]
  }

  saveCustomer() {
    // this.api.forEachNode(this.printNode)
    let selectedRows;
    selectedRows = this.api.getSelectedRows();
    console.log(selectedRows);
  }
}

Answer: For check box selection you can use checkboxSelection: true in you columnDef instead to use cell render:
this.columnDefs = [
  {
    headerName: 'Name',
    field: 'testName',
    checkboxSelection: true, //HERE !!!!
    width: 150
  }

and than you can easy get rows, when checkbox selected :
someMethod() {
  let selectedRows;
  selectedRows = this.gridApi.getSelectedRows();
  console.log(selectedRows);
  ///than you can map your selectedRows
  selectedRows.map((row) => {
   console.log(row);
   console.log(row.data);
  });
}

If you need to set checked or not depended on data from dataBase you can use:
     onGridReady(params) {
        this.gridApi = params.api;
        this.gridColumnApi = params.columnApi;
        this.transportApi.getCustomerNames().subscribe((res) => {
          this.rowData = res;
          if (res) {
 this.transportApi.getSelectedCustomerNames().subscribe((selectedCustomers) => {
                if (selectedCustomers) {
                  this.gridApi.forEachNode((node) => {
                    selectedCustomers.map((customer) => {
                      if (node.data.CustomerNumber=== customer.CustomerNumber) {
                        node.setSelected(true);
                      }
                    });
                  });
                }
              });

            }
          }
        }, error1 => console.log(error1));
      }

Transport method is example use yours in code;
Comment: I dont understand, why you need to use cellRenderer for checkbox selection. Try to use it without cellRenderer.
Comment: And dont use cellRenderer for checkBox selection. Simple add checkboxSelection: true to column where you wanna add checkbox
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/187571/discussion-between-anton-skybun-and-rds80).
Comment: I had tried the checkboxSelection: true option. The only thing I don't like about that is that it shows "true" or "false" right next to the checkbox.  Please see update in original post.
Comment: I did try "checkboxSelection: true", but it also shows the value "true" or "false" next to the checkbox.  Please see the image I included in the original post.
Comment: Please see the second upate to my original post.  It shows that I'm using checkbox selection.  And the two issues I'm having.
Comment: @AntonSkybun How do I make checkbox `checked` based on the data from the database when using the server-side model? Right now i am using `cellRendererFramework` for first column with custom `checkbox component` which uses `node.setSelected()` to mark row selected based on condition passed. But the problem with this approach is the method `api.getSelectedRows()` returns the selected rows from only rendered rows from 1st page and *other pages only if i have visited them*. *continued...*
Comment: @AntonSkybun Another problem is when I visit lets say 2nd page and `uncheck` the already `checked` row and go back to page 1 and then revisit page 2 it will mark the row `checked` again.
Comment: @SushmitSagar i need to see you code and some play with it - to clear help you. If it possible - let me know


How can I get a list of ordered rows from a list of ordered ids from a MySQL table?

Question: I'm working in PHP, and I have a list of ids, which are ranked, with the first being the most important. I'm retrieving the rows using something like this (simplified for clarity):
$id_as_sql_list = implode("','", $id_list);

$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')";

This basically works out as:
WHERE id in ('456', '123', '789')

The problem is, the result from the database isn't coming back in the order of the list. What's the best way to get them back in this order?
Answer: Take a look at order by field syntax.
This is an example
select * from table
where id in (x,y,z)
order by field(id,x,y,z)

Comment: Particularly useful to get data from MySQL for scores kept in Redis for instance!
Answer: $sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list')
ORDER BY YourRankingField ";

Answer: use ORDER BY
$sql = "SELECT * FROM books
WHERE id in ('$id_as_sql_list') ORDER BY whatever";

where whatever is the field you wish to order by.
Comment: Obviously the question asked is to get the links from MySQL in the order of the ID's used in the query. 'order by whatever' is therefor not the answer to this question. Getting information in the order of the ID's given can be particularly useful when getting data from rows read from Redis (in a Redis/MySQL combi)


How can I make a node link to another node

Question: According to this site http://asblab.mie.utoronto.ca/news, you can see how
Home>>News just below the menu. If I could add in this node http://asblab.mie.utoronto.ca/node/12525
such that Rise of the robots page would have
Home>>News>>Rise of the robots . How do I link them together?
Thank you guys, this forum has been helping me alot. If my question doesnt make sense, please inform me so I can try my best to edit and make the question better.
Answer: Try to use drupal_set_breadcrumb() in template file if you want to do it programmatic.
Or configure Custom Breadcrumb module.
Comment: hmmm,is there no other functionality within drupal features. I don't want to add that module because it was causing problems for my theme. Can I just make a menu link look active, but not taking care of where it goes , check this link http://asblab.mie.utoronto.ca/research , when you click on "assistive robotics" , you can see the menu tab"Research "  is still highlighted as active.
Comment: Do you want to add title of current page to breadcrumb?  What breadcrumb do you want to have on "assistive robotics" page?
Comment: I want the Research button menu, to look active.
Comment: I open http://asblab.mie.utoronto.ca/assistiveRobotics an see that Research button menu is active. So i don't see any problem!


If $\vec a\times\vec b=\vec c,\vec b\times\vec c=\vec a$ and $|\vec a|=2$ then is $\vec a\times((\vec b+\vec c)\times(\vec b\times\vec c))=\vec0?$

Question:
Let three vectors $\vec a,\vec b$ and $\vec c$ be such that $\vec a\times\vec b=\vec c,\vec b\times\vec c=\vec a$ and $|\vec a|=2$. Then which one of the following is not true?

A)$\;\vec a\times((\vec b+\vec c)\times(\vec b\times\vec c))=\vec0$
B)$\;$ Projection of $\vec a$ on $(\vec b\times\vec c)$ is $2$
C)$\;[\vec a\;\vec b\;\vec c]+[\vec c\;\vec a\;\vec b]=8$
D)$|3\vec a+\vec b-2\vec c|^2=51$

Option A:
LHS=$(\vec b+\vec c)(\vec a\cdot(\vec b\times\vec c))-(\vec b\times\vec c)(\vec a\cdot(\vec b+\vec c))$
Given that $\vec b\times\vec c=\vec a\implies\vec a\cdot(\vec b\times\vec c)=|\vec a|^2=4$
So, LHS=$4(\vec b+\vec c)-(\vec b\times\vec c)(\vec a\cdot\vec b+\vec a\cdot\vec c)$
Given that $\vec a=\vec b\times \vec c\implies\vec a\cdot\vec b=0=\vec a\cdot\vec c$
So, LHS=$4(\vec b+\vec c)\ne0$
So, Option A) is not true, right? (I am not very sure about the nature of $\vec b+\vec c.$)
Option B and option C are easy for me to see that they are true.
Option D:
LHS=$(3\vec a+\vec b-2\vec c)\cdot(3\vec a+\vec b-2\vec c)=9|\vec a|^2+|\vec b|^2+4|\vec c|^2=36+|\vec b|^2+4|\vec c|^2$
Given $\vec a\times\vec b=\vec b\implies\vec c\times(\vec a\times\vec b)=\vec b\times\vec c=\vec a\implies\vec a|\vec b|^2-\vec b(\vec a\cdot\vec b)=\vec a\implies|\vec b|=1$
So, LHS=$37+4|\vec c|^2$
Given $\vec b\times\vec c=\vec a\implies(\vec b\times\vec c)\times\vec b=\vec a\times\vec b=\vec c\implies\vec c|\vec b|^2-\vec b(\vec b\cdot\vec c)=\vec c$
So, $\vec b\cdot\vec c=0$ i.e. the angle between $\vec b$ and $\vec c$ is $\dfrac\pi2$ (In fact, I had used this result while opening $|3\vec a+\vec b-2\vec c|^2$)
So, $|\vec b\times\vec c|=|\vec a|\implies|\vec c|=2$
So, LHS=$53\ne51$
So, option $D$ is not true.
Is there any other way to approach option A) and option D)?
Answer: Here is an alternative way to solve this question (more like a variation on your answer to option D). Create an orthonormal system, with $\hat i$ along $\vec a$, $\hat j$ in the plane of $\vec a$ and $\vec b$, perpendicular to $\hat i$, and $\hat k=\hat i\times\hat j$. Then $\vec a=2\hat i$, $\vec b=b_x\hat i+b_y\hat j$. From $\vec a\times \vec b=\vec c$ you get $\vec c=2b_y\hat k$. Then, if $\vec b\times\vec c=\vec a$ you get $b_x=0$ and $b_y=1$. Your result for part D is then immediately obtained. For part A, since $\vec b$ and $\vec c$ are not collinear $\vec b+\vec c\ne 0$. Or you can plug in the values for $\vec a, \vec b, \vec c$ into the LHS expression.$$\vec a\times((\vec b+\vec c)\times\vec a)=4(\vec b+\vec c)=4\hat j+8\hat k\ne 0$$
Comment: Thank you, got it


Send form values to JS file

Question: As clearly titled I want to send a form values to js file in Drupal 8.
I've made some researches and all I successfully coded was sending a PHP variable from a Controller to the JS file I'am using.
Here is the code:
library_name.libraries.yml
library_name:
  version: 1.x
  js:
    js/<js_file_name>.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

controller_name.php (class)
namespace Drupal\module_name\Controller;

use Drupal\Core\Controller\ControllerBase;

class <class_name> extends ControllerBase {

  public function <method>(){

      return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

  }

js_file_name.js (under /js folder)
console.log(drupalSettings.<module_name>.<library_name>.foo);

Everything works great!
But how about using a form? I've declared a form extending from FormBase and in the submitForm() overridden method I typed the same array:
return array(
        '#attached' => array(
            'library' => array(
            '<module_name>/<library_name>'
            ),
            'drupalSettings' => array(
                '<module_name>' => array(
                  '<library_name' => array(
                      'foo' => 'bar'
                  )
                )
            )
        )
      );

I know this won't work! But any ideas? I thought about using another library, point to a js file there, and use that js file to get the form values  using the #attached tag like above, and then send those values to the other js file using JSON
If any one can provide me with a better Drupal Standard? that would be great! cause this my first time using Drupal.

EDIT:
I fixed this, using: the module_name.settings.yml file under module_name/config/install folder and also by using the module_name.module file where I've implemented the hook_form_alter() method.
So,
From my module_name.module file, here goes my code:
/**
 * Implements hook_form_alter().
 */

function modulename_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){

     if($form_id === your_form_id){

        $form['#attached']['library'][] = 'module_name/route_name';
    // that's the route name you've defined in your module_name.libraries.yml file
    // where you've located the js file you're going to use

        $form['#attached']['drupalSettings']
        [module_name][route_name][send_this_variable_to_js] = \Drupal::config(module_name.settings)->get(key);

        return $form;
    }

}

Now in your JS file, you can console.log like this:
console.log(drupalSettings.module_name.route_name.server.send_this_variable_to_js)

Hope this help!
Answer: You'll either need to add a js behavior that attaches itself to the normal submit event of the form, or create an AJAX Command that invokes a function in your script.
See: https://www.drupal.org/node/2290235
Comment: Thanks Kevin for the answer!
I am still in the same prob since yesterday, trying to find how can I pass through this using the Drupal API... which needs a LOT of time to get used to, for such a beginner like me.
Comment: I've made some changes, switching from FormBase to ConfigFormBase, and also saving all form data in a .settings.yml file. However, I have a Javascript file that needs to handle the form data as well, and I am still trying to know what's the best way to do this. Thinking of parsing the YAML file using javascript... it's possible btw... however, I am still searching for a Drupal way to do this.
Comment: In that case, your form ajax submit needs to return an AjaxResponse, you can attach an InvokeCommand to call your jQuery method and pass data as arguments. See this answer which is similar (for D7 though): http://drupal.stackexchange.com/a/193144/57
Comment: Also see: http://www.kalose.net/oss/drupal-8-ajax-forms/
Comment: Still nothing new Kevin. Here's my code: http://pastebin.com/khdVNJ3e, see the title.
Comment: Actually, I've made it, using another way :)
Comment: I don't see any Ajax in that code?
Comment: Well, it turns out that AJAX wasn't necessary LOL
Please review my EDIT post :)
Answer: #attached only works on a page that is rendered. A form submission isn't, it's redirect and goes to some other page. It also doesn't have a return value.
You need to store this information somewhere, for example in the user session and then display it on the next page.
Alternatively, you could use $form_state->setRebuild(TRUE), store it with $form_state->set(), then buildForm() will be called again and you can add it there to $form. That's however usually only done when you actually explicitly want to keep the user "in" he form, somethink like an upload image or "add another" button.
Comment: Thanks for answering Berdir!
As I have wrote to Kevin, I've made some changes to my code, switching the form from FormBase to ConfigFormBase, and also saving all form data in a .settings.yml file. However, I have a Javascript file that needs to handle the form data as well, and I am still trying to know what's the best way to do this. Thinking of parsing the YAML file using javascript... it's possible btw... however, I am still searching for a Drupal way to do this.
Comment: So you store the settings in yaml and then later on need to use it *somewhere* and send it to JS? That's not a problem, just access the config (in PHP, there is no way you can access that from JS), add it to drupalSettings and you're done?
Comment: Hi Bedir, Yes, and I want to send the Values from the **submitForm()** overriden method (myclass extends from **ConfigFormBase**), to make sure that the values are in the submit stage so they're safe to send.
I tried to attach a js file for let's say debugging to make sure that I can add variables later, this line didn't work:

`$form['#attached']['library'][] = '/';`
`return parent::submitForm($form, $form_state);`

However in the **buildForm()** it worked
Comment: Thanks Berdid, I did likely the same solution you've pointed to.

Send form values to JS file


Evaluate $\int_{0}^{\infty}x\left ( \operatorname{Ci}(x)^2 +\operatorname{si}(x)^2\right )\operatorname{Ci}(x)\text{d}x$

Question:
Evaluate
$$
I_1=\int_{0}^{\infty}x\left ( \operatorname{Ci}(x)^2
+\operatorname{si}(x)^2\right )\operatorname{Ci}(x)\text{d}x.
$$
Where $\operatorname{Ci}(x)=-\int_{x}^{\infty}\frac{\cos(t)}{t}\text{d}t,\operatorname{si}(x)=-\int_{x}^{\infty}\frac{\sin(t)}{t}\text{d}t$ are cosine integral function and (modified) sine integral function respectively.

By integrating numerically, one gives $I_1=0$. My evaluation is a bit complex, so I would like to see a canonical one. Thanks for replying.

A related version:
$$
I_2=\int_{0}^{\infty}x\left ( \operatorname{Ci}(x)^2
+\operatorname{si}(x)^2\right )\operatorname{si}(x)\text{d}x=\frac\pi2\left(1-2\ln(2)\right).
$$

A sophisticated version:
$$
I_3=\int_{0}^{\infty}\left ( \operatorname{Ci}(x)^2+\operatorname{si}(x)^2\right )^2\left (
 \operatorname{Ci}(x)^2+\operatorname{si}(x)^2+3\pi\operatorname{si}(x)\right ) \text{d}x
=6\pi^3\operatorname{Li}_2\left ( \frac{1}{4}  \right ) +12\pi^3\ln(2)^2.
$$
Where $\operatorname{Li}_2(z)=\sum_{k=1}^{\infty}\frac{z^k}{k^2}$ is the dilogarithm.
Comment: Is there a negative sign missing from the answer to $I_2$?
Comment: @JamesArathoon I like to use $\operatorname{si}(x)=\frac\pi2-\operatorname{Si}(x)$ personally, but the de facto definition is $\operatorname{si}(x)=\operatorname{Si}(x)-\frac\pi2.$
Answer: We can make use of the following result:$$\boxed{\operatorname{Ci}^2(x)+\operatorname{si}^2(x)=\int_0^\infty \frac{e^{-xy}\ln(1+y^2)}{y}dy}$$

$$I_1=\int_0^\infty x\left(\operatorname{Ci}^2(x)+\operatorname{si}^2(x)\right)\operatorname{Ci}(x)dx$$
$$=\int_0^\infty \int_0^\infty \frac{xe^{-xy}\ln(1+y^2)\operatorname{Ci}(x)}{y}dydx$$
$$=\int_0^\infty \frac{\ln(1+y^2)}{y}\left(\int_0^\infty x e^{-xy}\operatorname{Ci}(x)dx\right)dy$$
$$=\int_0^\infty \frac{\ln(1+y^2)}{y}\left(-\frac{d}{dy}\int_0^\infty e^{-xy}\operatorname{Ci}(x)dx\right)dy$$
$$=\frac12\int_0^\infty \frac{\ln(1+y^2)}{y}\frac{d}{dy}\left(\frac{\ln(1+y^2)}{y}\right)dy=\frac14\left(\frac{\ln(1+y^2)}{y}\right)^2\bigg|_0^\infty =0$$
Above the Laplace transform of the cosine integral was used.

Similarly, for $I_2$ we have:
$$I_2=\int_0^\infty \frac{\ln(1+y^2)}{y}\left(\int_0^\infty x e^{-xy}\operatorname{si}(x)dx\right)dy$$
$$=\int_0^\infty \frac{\ln(1+y^2)}{y}\left(-\frac{d}{dy}\int_0^\infty e^{-xy}\operatorname{si}(x)dx\right)dy$$
$$=\int_0^\infty \frac{\ln(1+y^2)}{y}\frac{d}{dy}\left(\frac{\arctan y}{y}\right)dy$$
$$=\int_0^\infty \left(\frac{\ln(1+y^2)}{y^2(1+y^2)}-\color{blue}{\frac{\arctan y\ln(1+y^2)}{y^3}}\right)dy$$
$$\overset{\color{blue}{IBP}}=\int_0^\infty \left(\frac12\frac{\ln(1+y^2)}{y^2}-\frac12\frac{\ln(1+y^2)}{1+y^2}-\color{red}{\frac{\arctan y}{y(1+y^2)}}\right)dy$$
$$\overset{\color{red}{IBP}}=\int_0^\infty \left(\frac12\underbrace{\frac{\ln(1+y^2)}{y^2}}_{\pi}-\underbrace{\frac{\ln(1+y^2)}{1+y^2}}_{\pi\ln 2}+\underbrace{\frac{\ln y}{1+y^2}}_{0}\right)dy=\frac{\pi}{2}-\pi\ln 2$$
This time the Laplace transform of the sine integral was used.

Proof for the mentioned result
Since $2\cos x= e^{ix}+e^{-ix}$, we can write:
$$\operatorname{Ci}(x)=-\int_x^\infty \frac{\cos t}{t}dt=-\frac12\int_x^\infty \frac{e^{it}}{t}dt-\frac12\int_x^\infty \frac{e^{-it}}{t}dt$$
$$=-\frac12\int_x^\infty \int_0^\infty e^{it}e^{-ty}dydt-\frac12\int_x^\infty \int_0^\infty e^{-it}e^{-ty}dydt$$
$$=-\frac12 \int_0^\infty\int_x^\infty e^{-(y-i)t}dtdy-\frac12\int_0^\infty\int_x^\infty e^{-(y+i)t}dtdy$$
$$=-\frac12 e^{ix} \int_0^\infty \frac{e^{-xy}}{y-i}dy-\frac12 e^{-ix} \int_0^\infty \frac{e^{-xy}}{y+i}dy$$
By the same approach, using $2i\sin x= e^{ix}-e^{-ix}$, we arrive at:
$$\operatorname{si}(x)=-\frac1{2i} e^{ix} \int_0^\infty \frac{e^{-xy}}{y-i}dy+\frac1{2i} e^{-ix} \int_0^\infty \frac{e^{-xy}}{y+i}dy$$
Finally, writting $2(a^2+b^2)$ as $(a+b)^2+(a-b)^2$ yields:
$$\small \operatorname{Ci}^2(x)+\operatorname{si}^2(x)=\int_0^\infty \frac{e^{-xy}}{y-i}dy\int_0^\infty \frac{e^{-xz}}{z+i}dz\overset{y+z\to y}=\int_0^\infty \int_z^\infty \frac{e^{-xy}}{(y-z-i)(z+i)}dydz$$
$$\small =\int_0^\infty e^{-xy} \int_0^y \frac{1}{(y-z-i)(z+i)}dzdy=\int_0^\infty \frac{e^{-xy}\ln(1+y^2)}{y}dy$$
Answer: We can actually use $I_{1}$ and $I_{2}$ to find closed-form expressions for $$\int_{0}^{\infty} x \operatorname{Ci}(x)^{3} \, \mathrm dx$$ and
$$\int_{0}^{\infty} x \operatorname{si}(x)^{3} \, \mathrm dx.$$

Let $E_{1}(z)$ be the exponential integral function defined in the right half-plane by the integral $$E_{1}(z) = \int_{1}^{\infty} \frac{e^{-zt}}{t} \, \mathrm dt, \quad \left( \Re(z) \ge 0, z \ne 0 \right). $$
For positive values of $x$, $E_{1}(x) = - \operatorname{E}_{i}(-x)$.
Similar to the my answer here, if we integrate the function $zE_{1}(z)^{3}$ around an infinitely-large closed quarter circle in the first quadrant of the complex plane, we get $$ \begin{align} \oint zE_{1}(z)^{3} dz &=\int_{0}^{\infty} x E_{1}(x)^{3} \, \mathrm dx - \int_{0}^{\infty} (ix) E_{1}(ix)^{3} \, i \, \mathrm dx  \\ &= \small\int_{0}^{\infty} x E_{1}(x)^{3} \, \mathrm dx + \int_{0}^{\infty}x\left(-\operatorname{Ci}(x)^{3}+3i \operatorname{Ci}(x)^{2}\operatorname{si}(x) +3 \operatorname{Ci}(x) \operatorname{si}(x)^{2} -i \operatorname{si}(x)^{3}\right) \,  \mathrm dx \\ &=0. \end{align}$$
Equating the real parts on both side of the equation, we have $$\int_{0}^{\infty} x E_{1}(x)^{3} \, \mathrm dx+ \int_{0}^{\infty} x\left(-\operatorname{Ci}(x)^{3}+3\operatorname{Ci}(x) \operatorname{si}(x)^{2} \right) \, \mathrm dx =0.$$
And combining the above equation with $I_{1}$, we get $$\int_{0}^{\infty}x \operatorname{Ci}(x)^{3} \, \mathrm dx = \frac{1}{4} \int_{0}^{\infty}x E_{1}(x)^{3} \, \mathrm dx. $$
(If you ask WolframAlpha to approximate the value of $\int_{0}^{a} x \left(\operatorname{Ci}(x)^{3}+ \frac{1}{4} \operatorname{E}_{i}(-x)^{3} \right) \, \mathrm dx $ for increasing positive values of $a$, it returns results that appear to be approaching zero.  But if you ask it to approximate $\int_{0}^{\infty} x \left(\operatorname{Ci}(x)^{3}+ \frac{1}{4} \operatorname{E}_{i}(-x)^{3} \right) \, \mathrm dx $, it strangely returns an approximation that is nowhere near zero. This could simply be the result of WolframAlpha needing more computation time.)
To evaluate $$\int_{0}^{\infty}xE_{1}(x)^{3}\, \mathrm dx, $$ we can do what I did here to evaluate $\int_{0}^{\infty}E_{1}(x)^{3}\, \mathrm dx $.
Specifically, we have
$\begin{align} \int_{0}^{\infty}xE_{1}(x)^{3}\, \mathrm dx &\overset{(1)}{=} \frac{3}{2} \int_{0}^{\infty} x e^{-x}E_{1}(x)^{2} \, \mathrm dx \\ &= \frac{3}{2} \int_{0}^{\infty}x e^{-x}  \int_{1}^{\infty} \int_{1}^{\infty} \frac{e^{-xy}}{y} \frac{e^{-xz}}{z} \, \mathrm dy \, \mathrm dz \, \mathrm dx \\ &= \frac{3}{2} \int_{1}^{\infty} \int_{1}^{\infty} \frac{1}{yz} \int_{0}^{\infty} x e^{-(1+y+z)x} \, \mathrm dx \, \mathrm dy \, \mathrm dz \\ &= \frac{3}{2} \int_{1}^{\infty} \int_{1}^{\infty} \frac{1}{yz} \frac{1}{(1+y+z)^{2}} \, \mathrm dy \,  \mathrm dz \\ &= \frac{3}{2} \int_{1}^{\infty} \frac{1}{z} \int_{1}^{\infty}\left(\frac{1}{(1+z)^2} \left(\frac{1}{y}-\frac{1}{1+y+z} \right) -\frac{1}{1+z} \frac{1}{(1+y+z)^{2}}\right) \, \mathrm dy \, \mathrm dz \\ &= \frac{3}{2} \int_{1}^{\infty} \frac{1}{z} \left(\frac{\ln(2+z)}{(1+z)^{2}} -\frac{1}{(1+z)(z+2)}  \right) \, \mathrm dz \\ &= \frac{3}{2} \left( \int_{1}^{\infty} \frac{1}{z} \frac{\ln(2+z)}{(1+z)^{2}} \, \mathrm dz - \ln(2) + \frac{\ln(3)}{2} \right) \\ &\overset{(2)}{=} \frac{3}{2} \left(\int_{0}^{1} \frac{u \ln(1+2u)}{(1+u)^{2}} \, \mathrm du - \int_{0}^{1} \frac{u \ln(u)}{(1+u)^{2}} \, \mathrm du  - \ln(2) + \frac{\ln(3)}{2} \right) \\ &=\frac{3}{2} \left(\int_{0}^{1} \frac{u \ln(1+2u)}{(1+u)^{2}} \, \mathrm du + \frac{\pi^{2}}{12}  -2 \ln (2) +  \frac{\ln(3)}{2} \right) \\ &\overset{(3)}{=} \small \frac{3}{2} \left(\frac{\ln(3)}{2} + \ln(2) \ln(3) -2 \int_{0}^{1} \frac{\mathrm du}{(1+2u)(1+u)} -2 \int_{0}^{1} \frac{\ln(1+u)}{1+2u} \, \mathrm du + \frac{\pi^{2}}{12} -2 \ln (2) +  \frac{\ln(3)}{2} \right) \\ &=\frac{3}{2} \left(\ln(2) \ln(3) -\ln(3) -2 \int_{0}^{1} \frac{\ln(1+u)}{1+2u} \, \mathrm du + \frac{\pi^{2}}{12} \right) \end{align}$
where $$ \begin{align} \int_{0}^{1} \frac{\ln(1+u)}{1+2u} \, \mathrm du &= \frac{1}{2} \int_{1}^{3} \frac{\ln (1+w) - \ln(2)}{w} \, \mathrm dw \\ &= \frac{1}{2} \left( \operatorname{Li}_{2}(-1)- \operatorname{Li}_{2}(-3) -\ln(2) \ln(3) \right) \\ & \overset{(4)}{=} \frac{\pi^{2}}{24} + \frac{\ln^{2}(3)}{4}+\frac{1}{2} \, \operatorname{Li}_{2}\left(-\frac{1}{3} \right) - \frac{\ln(2) \ln(3)}{2}. \end{align}$$
Therefore,
$$ \begin{align} \int_{0}^{\infty}xE_{1}(x)^{3}\, \mathrm dx &= -\int_{0}^{\infty} x \operatorname{E}_{i}(-x)^{3} \mathrm dx \\ &= \frac{3}{2} \left(2 \ln(2) \ln(3) -\ln(3)  -\frac{\ln^{2}(3)}{2} -\operatorname{Li}_{2} \left(-\frac{1}{3} \right)  \right) \\ &= 0.1949195673...  \end{align}$$
and $$\int_{0}^{\infty} x \operatorname{Ci}(x)^{3} \, \mathrm dx = \frac{3}{8} \left(2 \ln(2) \ln(3) -\ln(3)  -\frac{\ln^{2}(3)}{2} -\operatorname{Li}_{2} \left(-\frac{1}{3} \right)  \right).  $$

$(1)$ Integrate by parts.
$(2)$ Let $z= \frac{1}{u}$.
$(3)$ Integrate by parts.
$(4)$ Use the dilogarithm inversion formula.

If we equate the imaginary parts on both sides of the equation $$\small\int_{0}^{\infty} x E_{1}(x)^{3} \, \mathrm dx + \int_{0}^{\infty}x\left(-\operatorname{Ci}(x)^{3}+3i \operatorname{Ci}(x)^{2}\operatorname{si}(x) +3 \operatorname{Ci}(x) \operatorname{si}(x)^{2} -i \operatorname{si}(x)^{3}\right) \,  \mathrm dx =0, $$ we have $$\int_{0}^{\infty} \left(3x\operatorname{Ci}(x)^{2}\operatorname{si}(x) - x \operatorname{si}(x)^{3}  \right) \, \mathrm dx =0. $$
And combining the above equation with $I_{2}$, we get $$\int_{0}^{\infty} x \operatorname{si}(x)^{3} \, \mathrm dx = \frac{3 \pi}{8} \left(1-2 \ln(2) \right).$$


Como receber dados de formulário com HTML puro?

Question: Criei um formulário simples. Nele eu coloquei:
<form action="02.html" method="get" name="meu_formulario">
<input type="text" name="nome" size="60" maxlength="40"/>
</form>

Eu quero criar o 02.html que receba esse dado do formulário e exiba na tela o dado preenchido, só isso. Mas eu não posso usar PHP, tem que ser HTML puro. Como eu faço isso? É possível fazer isso?
Comment: Talvez usando javascript, mas n sei se é possivel sem uma linguagem server-side.
Comment: Pode usar HTML 5 @DiegoFelipe.
Comment: @Adriano, já que não pode usar uma tecnologia server-side, você pode fazer uma [app offline para o chrome](https://developer.chrome.com/apps/offline_apps) e para armazenar os dados, use um [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API)
Answer: Poderia fazer com javascript, mas o parâmetro seria quebrado de acordo com os caracteres contidos nele pois por URL ele passará a string, mas formatará em link, retirando espaços e acentos:
01.html
<form action="02.html" method="get">
    <input type="text" name="nome" size="60" maxlength="40"/>
</form>

02.html

Uma forma mais sofisticada que encontrei em Como faço para ler valores da URL em Javascript (QueryString)?, nele os erros que citei acima são tratados (exceto de acento), e para pegar valores seriam como em php:

Answer: Somente com HTML não é possível. Se usar GET, é possível com HTML + JavaScript, como mostrado em outras respostas. Para usar POST, você precisa de uma linguagem que execute no servidor.
Comment: É aí que entra o maravilhoso PHP
Answer: É possível enviar e receber parâmetros sem o uso de recursos server-side (php, asp, ruby, etc)
Há a forma tradicional pelo método GET onde basta ler a URI e extrair os parâmetros com JavaScript. Outra forma é usando cookies.
Extraindo dados da URI com JavaScript
Exemplo prático:
Suponha que essa página seja tmp.html

<title>test</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<form action="tmp.html" method="GET">
<input type="text" size="10" value="" name="foo" id="foo" />
</form>

Obtendo dados de cookies
Outra forma, é usando cookies, também com JavaScript.
Exemplo, simulando envio pelo método POST:

<title>test</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">

<form id="frm1" name="frm1" action="cookies.html" method="POST">
<input type="text" size="10" value="" name="foo" id="foo" />

<input type="text" size="10" value="" name="bar" id="bar" />
<input type="submit" value="enviar" />
</form>

obs: Os exemplos não utilizam códigos crossbrowser. O recomendado é utilizar um framework como JQuery.
Answer: se for somente um formulário simples, e você quiser apenas adicionar os dados dele a localStorage, você pode remover a tag  e fazer com que um botão ao final do formulário execute uma função em JavaScript que adicione os dados a Storage
por exemplo
Nome:
<input type="text" id="nome" value="Seu Nome">

para a pessoa digitar o nome num campo de texto
<button type="button" onclick="SendForm()">Enviar sua Mensagem</button>

para criar um botão que chama a função SendForm()
para que funcione você tem que linkar o arquivo JS
para isso use
no JS defina a função SendForm()
function SendForm() {
    var nome = document.getElementById("nome");

    var dados = JSON.parse(localStorage.getItem("dadosForm"));

    if (dados === null) {
        localStorage.setItem("dadosForm", "[]");
        dados = [];
    }

    var auxRegistro = {
        nome: nome.value,
    };
    dados.push(auxRegistro);
    localStorage.setItem("dadosForm", JSON.stringify(dados));

    alert('nome adicionado a localStorage');
    nome.value = "";
}


Linear programming with products as constraints.

Question: How is it possible to transform the following non-linear constraints into linear constraints? I can rewrite the constraints as follows:
$8x^2y \le 32, \frac{4xz^2}{y^3} \le 32, \frac{x^5y^2}{z^6} \le 32$.
Then I can convert them to equalities: $8x^2y+b_1 = 32, \frac{4xz^2}{y^3} +b_2= 32, \frac{x^5y^2}{z^6} +b_3=32$
However, once I am at this points, I don't see how I can put the constraints in an appropriate linear form. How can I proceed? Thanks
Answer: Can you take logarithm of everything both sides? The variables are strictly positive so the logarithm is well-defined, and it is an increasing function so it respects all the inequalities and the maximization.
Notice that the objective function is also a product. So, if you rename $u=\log(x)$, $v=\log(y)$, $w=\log(z)$, then the objective is to maximize $u+v+w$ (it is $\log(xyz)$, so logarithm of the previous objective function).
The first constraint, you can rewrite is as $\log(x^2yz)\leq\log(4)$ so $2u+v+w\leq\log(4)$. You can do the same for the other two constraints and it all becomes linear.
Comment: Thanks! This makes perfect sense.
Comment: Now I re-read it and I noticed my response is pretty badly written, in terms of well-structured thoughts and so on, but I am glad you got the idea and it was useful for you!


I don't like my voice

Question: I'm a 51  year old pro bass player – I play mainly blues and jazz – well that is where my passion is at.
I got sick and tired of hiring guitar players that can sing and play really well but were difficult to work with so I decided to take on singing.
Wow, why didn't I do this 30 years ago – I didn't realize how much I really enjoy singing. I haven't started singing on gigs yet because I'm so critical of myself.
I do record myself for self-assessment and quite frankly, on certain/most tunes, I don't like my voice. I'm from the old-school and have no desire to take vocal instructions (Ray Charles never took singing lessons and Greg Allman once said he sounded like crap in the beginning of his career).
I'm learning by imitating Nat King Cole and Ray Charles (Ray Charles learned by imitating Nat too). I have an app where I can adjust the keys of the songs for my vocal range.
I am just wondering on why I don't like my voice on some/most of the tunes? I know it is not because of the key because the app surely helps me  finding a comfortable key.
Is this normal for aspiring vocalists? I'm thinking it is because of my self-esteem and confidence and whey I was young, friends would say "you can't sing" so I'm wondering if this is plaguing me?
Answer: This is not meant to be harsh in any way, I'm just examining possibilities…
We start from not knowing what you actually do sound like.
Presumably, as you can play an instrument, you can also hit roughly the right note when singing [though it's not a guarantee, it's a fair bet].
Trouble is, without hearing you, no-one can say whether it's because you just aren't used to your own voice 'off tape' or because you really can't sing.
For the obvious & immediate 'straw poll' solution to that, I really wouldn't suggest you post up an example somewhere, because the anonymity of the interwebz is notorious for garnering some pretty harsh opinion with no fear of reprisal.
The chances are, you are simply not used to what you sound like yet, having heard your own voice through your skull more than ears for the entirety of your life.
I would suggest getting a lot more experience of what you sound like 'off tape' & get used to the results. There is no real substitute for practise, as we all know, but getting used to what you really sound like is a different curve.
I would also suggest [no laughing, please] to try some karaoke nights if that's an option near where you live - but somewhere where no-one knows you. Take a friend, get some confidence, learn how to feel audience reaction to what you do - something you already know from your previous experience as a player, but without the pressure of a first-time gig as lead vocalist.
Karaoke is 'low expectation' so the audience tends to be kinder - & will pretty much just ignore you if they don't like it, rather than be actually negative about it.
Work towards 'not being ignored' rather than actually 'getting rapturous applause' - & all the time you can know you're only practising - or be surprised if the audience doesn't realise you don't like your own results yet.
Appreciation is a good boost to confidence to push towards your first 'real' gig as a vocalist.
Comment: @rodbass63 - 'Fever' is a good song to sing with just bass! Seriously, if the backing was fuller, using more instruments, it would sound more like a proper track. Mic techniques need learning too. Don't go down the route of many singers and use loads of reverb - it masks what you need to hear. Try singing a bit higher or lower than the app says - it may not give the 'best' key for your voice.You also may find that playing and singing simultaneously is detracting from singing your best.
Comment: Good advice on posting my voice online. I've been practicing singing without a PA system -- just me, my bass, and my voice. Should I practice with a PA system and add a little effects to enhance?
Comment: +1 @Tim - hence my otherwise rather risible suggestion of karaoke... though you may not be able to get much control over the reverb ;)
Comment: @Tetsujin - fair enough, although there is a plethora of backing tracks out there to play guitar over - if he's singing blues songs, lots of 12 bar tracks available.
Comment: Sure thing - my only real point of karaoke (I'm starting to sound like I'm pushing it as a valid art-form now, I gotta stop;-) is that you're at performance volumes, rather than mumbling in the bedroom.
Answer: No-one likes the sound of their own voice.   Never let a vocalist engineer a recording, he'll ruin the voice track with plugins designed to make it sound like anyone except HIM.  And keep their hands off the mixer on a live gig, they'll want 10X too much reverb for the same reason.
Your vocals are OK if the rest of the band don't tell you to stop and the audience don't ALL walk out!
But, as a pro player, what would you say to a wanabee bassist who 'had no desire to take instructions'?
Comment: "No-one likes the sound of their own voice."  How true!  When I took singing lessons, I was encouraged to record the results on cassette tape.  After a year or two, I could just about bear to listen to the results…  (Which is how I could tell I'd improved!)

I don't like my voice


Nonattacking "queens" on tiled triangles

Question: I'll start with what my question is not. My question is not Nonattacking rooks on a triangular chessboard or The number of spacing $k$ non-attacking towers on the board $\left\{(i,j):1 \le i \le j \le n \right\}$. Those questions are about taking a square grid and making a "triangular chessboard" by removing the squares of a chessboard above the diagonal.
My question is about tiled triangles of the following form (not truncated square grids):

I will define a "queen" on this tiled triangle to attack in the three directions parallel to the triangle on which the queen is located. Below, I have placed a queen on the darkest blue triangle and the light blue triangles are where the queen attacks.

I am interested in the maximal number of non-attacking queens I can place on this tiled triangle. For example, I can imagine placing down queens until every triangle is under attack:

Or, as another example,

My questions are: For a tiled equilateral triangle of side length $n$, what is the maximal number of non-attacking queens I can add to the triangle? How many configurations have the maximal number of non-attacking queens? By side length, I mean for example that the above tiled triangles have a side-length of five.

I think my trouble has been that I'm unsure of a good coordinate system for the tiled triangle. It's two dimensional, but I take out three straight lines corresponding to the horizontal, diagonal, and antidiagonal directions when I add a queen. Further, knowing which horizontal row and diagonal I am in does not typically fix the antidiagonal I am in (there are typically two choice for the antidiagonal).
From inspection, it looks like the maximum number of non-attacking queens on a tiled triangle of sidelength $n$ is $\lceil n/2 \rceil$. Maybe induction on the length of the sides could work? It looks like adding row of triangles at the base of a maximal-number-of-queens odd $n$ triangle gives a maximal number-of-queens even $n+1$ triangle, but I am unsure of how to show this.
Comment: Are you familiar with setting up a coordinate system on a triangular grid? You have 3 directions to move in, and it uses 3 coordinates.
Answer: Your problem is similar to the one of placing non-attacking rooks on a triangular array of hexagons, discussed in this Math Overflow post: https://mathoverflow.net/questions/103540/hexagonal-rooks/103610. The same proof method works in your problem. I am generalizing the proof of optimality in this comment.

The maximal number of queens is $\left\lfloor 2n+1\over 3\right\rfloor$.
To place that many queens, do the following:

Letting $k=\left\lfloor 2n+1\over 3\right\rfloor$, place a queen in the leftmost triangle in the $k^{th}$ row from the bottom.

Place a queen in the rightmost triangle in the row below the previous.

Go down the rows one by one. For each row, either place a queen in the triangle below the queen in step $1$, or the queen in step $2$, alternating each time.

Here is an illustration when $n=10$:

Here is how you prove this is optimal. Each triangle has a triple of coordinates $(x,y,z)$, where $x$ is the number of triangles a queen must move to reach the left edge, and $y$ and $z$ are the corresponding distances for the right and bottom edges. Orient the entire grid so a vertex points upward, as in your pictures. You can show that:

For an upward pointing triangle, $x+y+z=2n-2$, and $x,y$ and $z$ are all even.

For downward pointing triangle, $x+y+z=2n-1$, and $x,y$ and $z$ are all odd.

For example, when $n=4$, you can verify the possible coordinates are permutations of $(0,0,6),(0,2,4),(2,2,2),(1,1,5)$ or $(1,3,3)$.
Now, for a placement of $k$ queens, let $\Sigma_x$ be the sum of the $x$-coordinates of the queens, and define $\Sigma_y$ and $\Sigma_z$ similarly. Furthermore, let $d$ be the number of queens on downward pointing triangles. The preceding two bullets imply
$$
\Sigma_x+\Sigma_y+\Sigma_z=k\cdot (2n-2)+d
$$
Therefore, at least one of the $\Sigma_x,\Sigma_y$ or $\Sigma_z$ must be at most $(k(2n-2)+d)/3$. WLOG, say $$\Sigma_x\le \frac{k(2n-2)+d}3.\tag1$$
Furthermore, as $i$ ranges over the $x$-coordinates of the queens, the values $\lfloor i/2\rfloor$ must be distinct, else the queens with the same value would attack each other in the direction parallel to the line $x=0$. If there are $k$ queens, the smallest possible value of $\Sigma_x$ for which the values $\lfloor i/2\rfloor$ are distinct is
$$
\Sigma_x \ge (0+2+4+\dots+2(k-1))+d=k(k-1)+d\tag2
$$
this is because the smallest value is attained by starting with the list $0,2,\dots,2(k-1)$, and increasing $d$ of these values by $1$, since the $d$ coordinates of the downard pointing triangles must be odd.
Combining $(1)$ and $(2)$, you get
$$
k(k-1)+d\le {k(2n-2)+d\over 3}
$$
Divide both sides by $k$ and rearrange to get
$$
k\le {2n-2\over 3}+1- {2d\over 3k}\le {2n-2\over 3}+1
$$
so $k\le \left\lfloor 2n+1\over 3\right\rfloor$.
Comment: By *similar* you mean *equivalent*, right?
Comment: @RobPratt No, I mean similar. Every rook placement on a hexagon grid translates to a queen placement on a triangle grid (just restrict your attention to the upward-pointing triangles only), but not the other way around. This means the proof of the upper bound for the triangle grid requires a bit of extra work to rule out the extra possibilities.
Comment: Very nice! That link to MathOverflow is also helpful to see some of the literature, as one of the answers discusses an alternative style of proof of optimality in this [link](https://www.cin.ufpe.br/~pcp/nonattacking_queens.pdf).


Storing vertices in Java - Mapping Edges

Question: I'm trying to build a graph with vertices, A, B, C & D. The graph must map an edge to a particular vertex if there is an overlap, For instance vertices A and C overlap as A has 1 -> 2, and C has 1 -> 4.
What would be an efficient way of storing these vertices then checking if their values overlap with one another?
Example:
A 1 2 3 4
B 9 10 12 13
C 1 4 2 3
D 15 16 17 18

Comment: Generally speaking, since little information and examples are provided - sounds like you want to use a `HashSet` or `HashMap`.
Comment: Can you give more example?
Answer: It depends how often these graphs are expected to change. If it's just once off, storing the vertex constraint in a Map<Vertex, Set<Constraint>, calculating the intersections and then storing the final graph as an adjacency list or matrix is just fine.
You would do something like
For each vertex v:
   For each other vertex u
    if constraints(u) intersect constraints(v)
        add edge between u and v

You will end up with a symmetric un-directed graph.
Comment: I would later like to add additional information to each vertex, would this change anything?  For instance A : Soccer  - B : Tennis etc.
Comment: Each time you add a new constraint, you will need to sweep over the whole vertex list again. If you are just tacking metadata to a vertex that doesn't change the graph's structure, nothing will change. If you could explain your usecase more, it might be easier to help you.
Comment: How would I define Map? It seems it's missing a '>' after Vertex is that right? What is Constraints? is that just a variable or a particular Object?

My usecase - when finding all the edges (overlaps between the integers) then I will need to assign the vertices a sport. Every adjacent vertex must be assigned to a different sport. Hence you can't do the same sport if there is an overlap.


How do I know if I installed latest version?

Question: I am trying to create a cron script which uses Drush, and that does the following (using pseudo-code).
if([My Drupal core version] < [The last core version]) {
    [Backup DB]
    [Put the site into maintenance mode]
    [Upgrade core]
    [Remove the site from maintenance mode]
}

I don't know, how to implement [My Drupal core version] < [The last core version].
How do I check if the site is using the latest version of Drupal?
Comment: It would be interesting, but what if something goes wrong with the updating process... I don't know, a new requirement, something is broken in the website, the server suddenly shuts down in the middle of the process... anything. I personally prefer to manually execute my updates to be able to fix anything in case there is a problem.
Answer: You could try drush pm-updatestatus drupal and see if you get any results.
Answer: See update_get_available function. It returns available list updates, including core.


JavaScript this.window not equal to window

Question: Consider the following top-level javascript code:
if (this.window === window)
    alert('same');
else
    alert('different'); // alerts: different

Why is this.window and window not strictly equal?  I've also tried 'this' on the rhs of the expression and get the same result.
Comment: If you're really getting that `this !== window`, I believe you must be running the code not in the top level. If `this === window` it follows that `this.window === window` as `window.window === window`.
Comment: Aidas and Dylan were corrrect, this is an IE8 peculiarity it seeems.  (this===window returns true, this.window===window returs false)
Comment: `this.window === window` returns `true` in Chrome.
Comment: What browser are you using? Both Firefox and Chrome return `true` for `this.window === window`. Or do you have any situation with Iframes?
Comment: what does ( window.window === window.window.window ) return in IE8?
Answer: In Internet Explorer (8.0.7600 is what I've tested), this with no qualifier actually resolves to the global window object. In all other browsers I've tried (Chrome, Firefox, Opera), this.window === window in that context - and, helpfully, this === window as well.
Try this in IE to verify:
if (this === window)
  alert('same');
else
  alert('different');

Comment: In the example you gave, 'same' is alerted in IE8.  I think you most precisely answered my original question... that this is really a pecularity to IE8.
Comment: The way IE8 treats this kind of makes more sense to me. `this.window` seems equivalent to `window.window`.
Answer: It seems as though HTML elements do not contain a pointer back to their parent window, as it does for parentNode.  Thus, this.window will return undefined when this is anything other than a window object.
The window object seems to be able to reference itself, perhaps because it is the only node high enough to "see" itself.  Thus, window == window.window.window.window and so on.
The idiosyncrasies between browsers seem to do with how each implements the DOM structure, and in particular, how they interpret this at the top-level.
Seeing as how individual HTML elements can't reference their parent window with .window, I don't really see a point in ever using this.window, though I'd love to be proved wrong here.
If you're working on code that involves manipulating objects across two different windows, I would suggest assigning your new window to a variable, e.g. var newWin = window.open(...) and subsequently using this variable to reference new objects.
Comment: @Chris: If you're trying to access the global object then you should use `this` rather than `window` if you want your code to run in non-browser environments. It's not true that `window` and the global object are precisely the same thing, although for most purposes in browsers they can be thought of as being so.
Comment: Extra bit on native JavaScript code: provided `this === window` in the current scope, `function t(){return this};`; `t() === window`, `(x = new t()) === x` (not `window`).
Comment: I believe the handling of `this` is defined rigidly for the top level; I know that at least Processing.js uses `this` instead of `window`, apparently because it's shorter (I asked because it surprised me when I saw it). In the global scope, `this === window` should always be true.
Comment: @Tim: I suppose that makes sense; however, Processing.js is targeting only browsers (due to its nature, using ``, etc.)
Comment: @Jeff - I would upvote this, but I don't have enough cred yet. :-(
Answer: Works here...
http://jsfiddle.net/rygar/DQYdk/
Comment: He said it was "top level javascript code", so your first answer was correct and your statement that you were wrong is wrong. It *does* work and is true.
Answer: Because this equals window in global context.
Comment: ... and so `this.window === window` as `window` is a global variable - `window.window === window`. `window.window.window === window` ;-)


Solve recurrence relation: $T(n) = \frac{n}{n+1}T(n-1) + 1$

Question: I am not able to solve this recurrence relation by substitution and variable change method.
$$T(n) = \frac{n}{n+1}T(n-1) + 1;\ \ T(1) = 1 $$
Comment: Is this what you mean?  $$\begin{cases} T_n=\frac{n}{n+1} \cdot T_{n-1}+1 \\ T_1=1\end{cases}$$
Comment: They probably want you to do the substitution $S(n) = (n+1)T(n)$, then solve for $S(n)$.
Comment: yes @AmateurMathPirate
Answer: This is a linear difference equation so
$$
T(n)=T_h(n)+T_p(n)
$$
where
$$
T_h(n)-\frac{n}{n+1}T_h(n-1) = 0\\
T_p(n)-\frac{n}{n+1}T_p(n-1) = 1\\
$$
For the homogeneous solution is is clear that making
$$
T_h(n) = \frac{C_0}{n+1}
$$
we have the solution. Now for the particular making $T_p(n)=  \frac{C_0(n)}{n+1}$ we have that
$$
C_0(n)-C_0(n-1)=n+1
$$
hence
$$
C_0(n) = \frac 12(n+1)(n+2)
$$
and finally
$$
T(n) = \frac{C_0}{n+1}+\frac{n+2}{2}
$$
Answer: evaluating a few terms you can find a pattern:
$T_1=1=\frac 2 2, T_2=\frac{5}{3}, T_3=\frac{9}{4}, T(4)=\frac {14} 5, \ldots$
Namely the pattern is that the numerator of the nth term is the sum of the first (n+1) terms diminished by 1.  This can be found most easily by noticing the difference in the numerator between successive terms.  The denominator is simply the (n+1)th term.  We can then prove it by mathematical induction:
$$T_n=\frac{\left(\sum_{i=1} ^ {n+1} i\right) -1}{n+1}= \cdots =\frac{n+2}{2}-\frac 1 {n+1}$$
Proof:
Base case: $n=1$ implies $T_1=\frac 3 2 - \frac 1 2 =1$ .  Good so far.
Inductive step:  Does our $T_n \implies T_{n+1} $?   Letting $n\to n+1 $ in the original definition, we multiply our $T_n$ by $\frac {n+1} {n+2}$ and add $1$, as this is what is defined by our formula with the index increased by 1....so do we get
$$T_{n+1}=\frac{n+3}{2}-\frac {1}{n+2}$$ ??
We do..
Answer: Let $$S_n=(n+1)T_n$$
Then
$$S_n=S_{n-1}+n+1$$
So
$$S_n=\sum_{k=3}^n k +S_1$$
You should be able to continue and compute $S_n$ and therefore $T_n$.
Answer: (n+1)T(n) = nT(n-1) + n+1

Let
 S(n) = (n+1)T(n)   S(0) = T(0) = c
       S(n) = S(n-1) + n+1

Since,    S(n-1) = S(n-2) + n
    therefore,   S(n) = S(n-2) + n+1 + n
          for k terms...
S(n) = S(n-k) + (n+1) +n +.....+ (n-k+2)
k = n
 S(n) = S(0) + (n+1) + n + ...+ (n-k+2)
      = c + (n+1) + n + (n-1) + ......+ 2 + 1 - 1
      = (n+1)(n+2)/2  + (c-1)
      = (n^2 + 3n + 2)/2  +  c - 1
      = n^2/2 + 3n/2  + c

S(n) = O(n^2)

from our substitution -
T(n)(n+1) = O(n^2)
T(n)=1/(n+1) O(n^2)
We can neglect +1 in n+1

then,
T(n) = O(n)


SOAP to Rest Service Using Adapter

Question: I have a legacy project where it has SOAP webservices exposed. Now I have a requirement to convert them to rest and use it accordingly.
Can I have implementation like Jersey available to consume these soap services and then publish the same as REST?
Answer: This is a common problem when dealing with legacy APIs. Since REST is not a protocol by definition you can implement either:

Protocol Bridging Pattern. It is a common SOA pattern that helps you transform between different protocols by using a bridging broker as intermediary. The broker holds the transformation logic. You can find more information here. Such bridges are available in most ESBs and EAI middle-wares.

Data Format Transformation Pattern. It transforms between data formats and you can use it to transform from XML to the REST format you are using. You can implement it by putting in some internal service logic, service agents, or a dedicated transformation service. You can see more here.. You can absolutely use Jersey to build a REST Facade and transform internally from XML, or build the logic inside each service.

It really depends on the size of your API and the type of solution you need. For few services I will choose the second approach - it's easier but a bit more coupled, while if I have many services I'd go for the first approach, which in my opinion abstracts transformation logic better, but it may require additional middleware and effort.
Comment: I have few services and want to go for second approach. But, can you please throw some light on examples of using Rest Facade to SOAP for data transformation.
Comment: @skanda, you asked if you can use Jersey for this - and yes, you can. In fact, you can use any framework to implement this. The solution I provided is technology agnostic and I hope my answer did help you. Alas, based on the relatively broad question you asked, I cannot provide specific code example if that is what you needed. Should you go with Jersey, you can implement a new REST API that consumes existing SOAP API with JAX-WS (see docs here http://docs.oracle.com/javaee/5/tutorial/doc/bnayn.html#bnayx ) and transforms each service, according to some template or based on custom logic.

SOAP to Rest Service Using Adapter


World-Wide Standard Music Certification

Question: Are there any world-wide known Music Certification tests that you can take to use in your resume: for example, to demonstrate basic musical abilities?
I used to work in IT, where it is very common for companies like Oracle and Zend to arrange that kind of certification for a programming language or framework.
Comment: Speaking generally, just about every country will have music exam boards, so passing a grade on an instrument and putting 'ABRSM grade VI clarinet' for example would be recognisable anywhere, with a possible bit of reasearch by someone reading a c.v.
Comment: You may want to search for the acronyms mentioned in the exam-grades tag I added, but in lack a of big responsible company this is strongly dependent on the country you live in.
Answer: Music is such a big field that it isn't really possible to answer this.
There are organisations and colleges such as Berklee which have some international reputation, it can be helpful to have something from them.
But in many areas, the qualification is simply showing you can do what is needed. For instance, as a jazz musician you are likely to pick up work by showing you can play your **** off without actually being an ****.
Music is a field that is extremely results driven. Pieces of paper don't really make much difference when you are on stage. Being able to be there on time, looking the part, and playing well are the main thing. Even people who do study at conservatory will often acknowledge that the main benefit was contacts they made, rather than the actual qualification.
Answer: There are systems of graded examinations in performance for most instruments, and for theory, designed to cover the stages from beginner to pre-college.
Here's a couple of 'classical' ones
https://gb.abrsm.org/
www.trinitycollege.com/
and one for 'rock'
www.rslawards.com/rockschool/
Those are UK-based.  There are equivalents elsewhere.  The next step is a diploma from a music conservatoire.
A few music software companies offer certification in their products.  You can become an 'Avid Certified User' in several of their products, including Protools and Sibelius.
www.avid.com/education/certification
Steinberg (Cubase) have 'Certified Training'.  I guess you get some sort of certificate after completing a course.
www.steinberg.net/en/education/certified_training.html
Answer: Adding to @danmcb answer: In some cases a college degree matters. E.g. in some countries Master in music is required to teach in a public school. A degree might be a plus when applying for other music related jobs.
But if the focus the job is music performance, a video showing you playing will be worth more than any paper. A degree is for sure worth mentioning, but bragging about it too much might actually make a bad impression.
Anything below academic level probably won't be worth much, except when you apply to study at the college.
Answer: Generally speaking, just about every country will have music exam boards, a lot of them world wide, like ABRSM. Most have been established for many years, and the standard at any particular grade should be just that - standard.
So, on a c.v., stating Grade VI clarinet ABRSM, Trinity, LCM, AMEB etc., should give a good clue to someone reading that c.v., possibly with a little homework.
Worth a look at IMEB - which it seems is the International Music Examination Board, and, as such, would have responsibility to align all boards.
Answer: Nothing completely world-wide, it seems.
I'm just a hobby musician, but before joining this stack I had never heard of the type of "grades" people seem to use to measure proficiency with musical instruments. I live in Sweden, and it doesn't seem to be a thing here. There are entry exams you need to pass to get into music schools and academies, of course, and there is collaboration between universities to standardise some tests, but nothing as organised as what I see people discuss here, and certainly not for children.
Just to be sure, I asked my girlfriend. Her parents are both professional musicians, and she's been playing the violin in various organised contexts since she was a kid. She majored in music in high school, continued at Folkhögskola(no idea how to translate..) and then spent 5 years at university to become a music teacher. A teacher should know about this, if anyone. She had never heard of anything remotely like the "grades" either.
There might be something that's fairly global, I don't know, but at least in one country it's not a thing.
Comment: There is nothing like this in the US either.

World-Wide Standard Music Certification


nginx proxy_pass regexp to another domain

Question: I have photoURL http://cs10821.vk.me/u712377/d_9da50e0f.jpg
It is does not have header Access-Control-Allow-Origin *;
I fix it with nginx. If I write
location /photo/cs10821.vk.me/u712377/d_9da50e0f.jpg {
    proxy_pass http://cs10821.vk.me/u712377/d_9da50e0f.jpg;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    add_header Access-Control-Allow-Origin *;
}

all work fine. I write http://servername.ru/photo/cs10821.vk.me/u712377/d_9da50e0f.jpg
and I have my photo with header Access-Control-Allow-Origin *;
But if I use regex
location ~ ^/photo/(.*)$ {
    proxy_pass http://$1;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    add_header Access-Control-Allow-Origin *;
}

I have error 502.
Help me please
Answer: Check the error log. You should have resolver defined.
Such as /etc/nginx/conf.d/resolver.conf:
resolver 22.214.171.124;

Comment: Excellent. Everything is working. Thank you very much


Android Target e o Android SDK não encontrado ou instalado... mas está tudo instalado, como resolver?

Question: Tive que formatar meu PC, Windows, e instalei tudo novamente: Java, Git, Python, Android Studio, Node, Ionic 3, Cordova, tudo.  E estava rodando antes normal.
Agora estou com este erro, não conseguindo rodar minha aplicação Ionic 3 com Cordova e Android.
<code>cordova requirements android

Requirements check results for android:
Java JDK: installed
Android SDK: installed true
Android target: not installed
Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable.
Gradle: not installed
Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.
Looked here: C:\Users\Ramos\AppData\Local\Android\Sdk\tools\templates\gradle\wrapper
Error: Some of requirements check failed
</code>
Mas meu ANDROID_HOME environment está correto:

Já baixei o Tools do site do Android Studio e coloqui na pasta. Fiz todas as recomendações que já vi na internet.
Como pedido nos comentários, o print da pasta SDK:

Como resolver?
Comment: E tem como tirar um print do conteudo da pasta `Android/Sdk`?
Comment: Oi @GuilhermeNascimento editei com o print.
Comment: Não tem o `SDK Manager.exe` nem o `AVD Manager.exe`, não sei de onde vc obteve esse SDK, mas com certeza esta faltando coisa
Comment: Ramos, eu tive um problema parecido e resolvi usando o próprio android studio, não o uso para programar, mas uso ele para gerenciar o sdk e o avd. Tenta usando ele aí, qualquer coisa comenta que tentaremos ajudar!
Comment: @Ramos além de  `C:\Users\Ramos\AppData\Local\Android\Sdk` coloque também o `C:\Users\Ramos\AppData\Local\Android\Sdk\tools` e `C:\Users\Ramos\AppData\Local\Android\Sdk\platforms` em seu ANDROID_HOME
Answer: Recomendo fortemente a utilização do Android Studio, por mais que você não vá desenvolver nele, ele é ótimo para dar manutenção no SDK. Além de na instalação resolver as variáveis de ambiente: Android Studio
Comment: Fiz isso. Não deu certo.
Comment: Lá no seu android studio tem como você ver o caminho do android home, copie ele e rode o comando:

set ANDROID_HOME=C:\ installation location \android-sdk

set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools


Prove $Q[x]/(x^2+4)$ is isomorphic to $Q[x]/(x^2+1)$

Question: I've been asked to prove Q[x]/(x^2+4) is isomorphic to Q[x]/(x^2+1); I've looked at lots of similar solutions, but haven't been able to understand this. I know each ring is the quotient ring for their respective polynomials (the remainder when divided by x^2 + 4 or x^2 + 1), but what exactly does this mean in the context of isomorphisms? How can I prove that they are the "same"?
I've got x^2 = -4 in one ring and x^2 = -1 in another, but I don't know where to go from there.
Thanks so much!
Comment: What can you say about $x^2+4$ and $x^2+1$ over Q? Are they reducible or irreducible? If they are irreducible, then the quotients are ..?
Comment: They're irreducible over Q, but then what can you say about the quotients? Is it not just like dividing a number by a prime number?
Answer: Let $A=\mathbb Q[x]/(x^2+4)$ and $B=\mathbb Q[x]/(x^2+1)$.
Then $A=\mathbb Q[a]$ with $a^2=-4$ and $B=\mathbb Q[b]$ with $b^2=-1$.
Essentially, $A=\mathbb Q[2i]$ and $B=\mathbb Q[i]$.
So, just send $a \mapsto 2b$.
More precisely, the map $u+va \mapsto u+2vb$ is a ring isomorphism.
You just need to check that this map is a ring homomorphism because the inverse map is easy.
Comment: @Piepod, exactly. Forget that these quotient rings are sets of cosets and use what quotient means: make something zero.
Comment: How do you get the intuition for this? If it were, say, any two polynomials, how could you see if it is isomorphic or not?
Comment: @Piepod, I've added a sentence about this specific case. The general case is harder of course.
Comment: So you've basically derived the ring's properties through x^2 = -4 and x^2 = -1 right? Basically, when Q[x] is divided by (x^2+4) and (x^2+1), x = 2i and x = i then?


Como alinhar elementos na página?

Question: Olá, eu sou iniciante em HTML e CSS, eu estou aprendendo por hobby para desenvolver temas para a rede social Tumblr, eu estou fazendo esse layout para fins de teste como fiz de rascunho no Photoshop:

Só que ao codificá-lo, a área da barra lateral e a de postagem estão desreguladas e eu já tentei de todas as formas alinhá-las, mas não consigo, o que eu estou fazendo de errado? Aí os meus códigos e o link do Tumblr que eu estou desenvolvendo o layout.

         /*Corpo da Página*/

            body {
                background: url("https://i.imgur.com/ujnC90p.png") no-repeat fixed;
                font-family: 'Open Sans Condensed', sans-serif;
                font-size: 15px;
                text-align: justify;
                color: #7db1a5;
            }

            /*Caixa*/

            #conteiner {
                display: flex;
                justify-content: center;
            }

            /*Conteúdo*/

            .content {
                display: flex;
                justify-content: center;
                width: 810px;
                background: #f3edcd;
                margin-top: 45px;
                margin-bottom: 40px;
            }

            /*Cabeçalho*/

            .header {
                width: 1000px;
                height: 1000px;
                background: url("https://i.imgur.com/gpaEEDj.png") no-repeat scroll;
                margin: 10px;
            }

            .entry {
                display: flex;
                flex-direction: row;
            }

            /*Barra Lateral*/

            .sidebar {
                width: 131px;
                height: 121px;
                background: red;
                margin-top: 10px;
                margin-right: 10px;
                padding: 10px;
            }

            /*Faixa*/

            .ribbon {
                margin-top: -10px;
                margin-left: -16px;
            }

            /*Postagem*/

            .post {
                width: 400px;
                background: transparent;
                margin-top: 150px;
                margin-bottom: 10px;
                padding: 10px;
            }

            /*Título*/

            .title {
                font-size: 20px;
                text-align: center;
                color: #f2d377;
                padding: 5px;
            }

                        {block:Posts}

                        {block:Text}

                            {Title}

                        {Body}

                        {/block:Text}

                        {/block:Posts}

O Tumblr: http://stripestheme.tumblr.com
Answer: Olá, fiz alguns ajustes no css apenas para alinhar corretamente da forma que você quer.

Answer:

                    {block:Posts}

                    {block:Text}

                        {Title}

                    {Body}

                    {/block:Text}

                    {/block:Posts}

Como alinhar elementos na página?


Frechet Differentiation and Equivalent Norm examples

Question: I have stumbled upon this interesting exercise, and I cannot seem to find conditions that satisfy all the properties needed, I can find several combinations which satisfy one or two of the properties, but not one for all three, I am really interested to see the solution so any help or hints would be greatly appreciated!
So the question is as follows:
Give an example of vector spaces $\mathbb{X}$ and $\mathbb{Y}$, two norms $||\cdot||_a$ and $||\cdot||_A$ on $\mathbb{X}$, where the two norms are equivalent, two norms $||\cdot||_b$ and $||\cdot||_B$ on $\mathbb{Y}$, where the two norms are equivalent, and a function $f:\mathbb{X} \to \mathbb{Y}$ such that all of the following hold:
a)  $\:f:(\mathbb{X},||\cdot||_a ) \to (\mathbb{Y},||\cdot||_b)$ is Frechet differentiable at every $x\in\mathbb{X}$;
b)  $\:f:(\mathbb{X},||\cdot||_A ) \to (\mathbb{Y},||\cdot||_b)$ is not Frechet differentiable at any $x\in\mathbb{X}$;
c)  $\:f:(\mathbb{X},||\cdot||_a ) \to (\mathbb{Y},||\cdot||_B)$ is not Frechet differentiable at any $x\in\mathbb{X}$.
It should be noted that the first part of this exercise was to prove that if a function is freshet differentiable everywhere with respect to two certain norms then if these are changed for equivalent ones the function is still freshet differentiable with the same derivative. So this can be assumed in the answer.
Thanks!
Comment: You can't, because of the last comment you made. A function cannot be differentiable for some pair of norms but non-differentiable for an equivalent pair. Either is differentiable for both pairs or non-differentiable for both pairs.
Comment: But the conditions only require switching out one of the equivalent norms not both.
Answer: Theorem. Let $\mathrm{V}$ and $\mathrm{W}$ be two normed spaces, and let $\| \cdot \|_1$ and $\| \cdot \|_a$ be a two equialent norms in $\mathrm{V}$ and, likewise $\| \cdot \|_2$ and $\| \cdot \|_b$ is a pair of equivalent norms for $\mathrm{W}.$ Suppose $f$ is defined on an open subset $\mathrm{A}$ of $\mathrm{V}$ into $\mathrm{W}$ and let $v$ be a point of $\mathrm{A}.$ Then, $f$ is differentiable in $v$ with respect to the pair $(\| \cdot \|_1, \| \cdot \|_2)$ if and only if it is differentiable in $v$ with respect to the pair $(\| \cdot \|_a, \| \cdot \|_b).$
Proof. There are constants $c, d, p, q$ all positive such that
$$c \| \cdot \|_1 \leq \| \cdot \|_a \leq d \| \cdot \|_1$$
and
$$p \| \cdot \|_2 \leq \| \cdot \|_b \leq q \| \cdot \|_2.$$
Then
$$\dfrac{c}{q} \dfrac{\|f(v + h) - f(v) - Th\|_b}{\|h\|_a} \leq \dfrac{\|f(v + h) - f(v) - Th\|_2}{\|h\|_1} \leq \dfrac{d}{p} \dfrac{\|f(v + h) - f(v) - Th\|_b}{\|h\|_a}$$
and the proof is complete.
How this theorem imply the excercise? Easy, clearly $\| \cdot \|$ is equivalent with itself.


Transcription Beats per minute

Question: For a personal project I was trying to transcribe a part of the flute solo in this piece. However, I am unsure at what speed I should transcribe the piece. I could either transcribe the piece at 250 bpm or 125 bpm. If the piece is transcribed with 250 bpm the transcription may be significantly less complicated, but 125 bpm may fit the piece better. I have transcribed the first few seconds of the piece at 250 bpm and 125 bpm respectively in the image below.
What BPM is would be considered more fitting? Or is this a subjective matter?
EDIT: I know this transcription is in the wrong key, it was just a quick mock-up to go with the question, to depict the rhythm. The actual transcription has been made in the right key. (:
Comment: This rhythm notation here is absolutely ok. But the notated key is wrong and not useful. Look up my answer.
Answer: This question is often subjective, but there are some objective rationalizations that make things easier.
I would strongly recommend transcribing this in a way that doesn't use so many small note values. Not only does this match the feel of the music better, it will also be easier for a performer to read; those 64th notes in the 125bpm transcription are pretty gnarly.
With that said, remember that you can transcribe something into a form of cut time. In this case, I'd use the 250bpm transcription but with a 2/2 time signature, signifying that the half note receives the beat instead of the quarter note (and thus it's really 125bpm).
Transcribing it in cut time is really the best of both worlds: you get the notational simplicity of the 250bpm transcription with the half-time feel of the 125bpm transcription.
Comment: @MarkMarketing Not if the beat value is a half note. If that's the case, then it will look like your 250bpm transcription, just with a 2/2 time signature.
Comment: If I then transcribe the piece at 125bpm should the 64th notes be in there still?
Answer: What I do in these cases is to listen to the drums. Listen to what the drummer is playing and you can easily deduct the tempo. In this song, the Kick Drum and the Snare Drum are being played on the beats 1,3 and 2,4 respectively and they are quarter notes. These quarter notes are on 125bpm, no matter how fast the flute is playing.
This is really common for the drummer; to play the kick and snare drums on quarter notes (this is the pulse of the song) and the hi hat on eighth notes, which is exactly the case in the song.
Comment: -1. OP is transcribing a **flute solo**.
Comment: @user42566 which is a part of a song; it's not on its own. There is a difference
Comment: Spot on. When in doubt, listen to the song and tap your foot to the music. I found myself grooving along at 125 bpm to variations of a standard 4/4 beat. If the flute happens to be played in 64th, tough luck. If a reader can't handle it, they should pick a piece with slower flute parts.
Comment: @Shevliaskovic Okay, never mind. Didn't realise the piece did have drums. Undownvoted, +1.
Answer:
I could either transcribe the piece at 250 bpm or 125 bpm. If the piece is transcribed with 250 bpm the transcription may be significantly less complicated, but 125 bpm may fit the piece better.

I would ask: Less complicated to whom? As it is notated by a computer program I assume you mean: to the interprete.
Even I risk to be critsized again that I don't answer the OP's question ... my advice will be:
All this discussion here about bpm is absolutely senseless as long your transcription is in the wrong key! You can forget your doubts what division to choose. This one here will be ok for every musician.
But this piece is in Eb major and your notation is almost unreadable as with all this accidentals it is pretty nonsense.
While in the correct key it will be much less complicated to reading.
Concerning your question about the bpm I'm thinking of Bach's famos Air of the Suite in D. There are lots of 32nd notes but it doesn't seem to be any problem for reading ...
Comment: Don't worry, the transcription I added was just a small mockup to show the rythm, the actual transcription was indeed done in Eb major.

Transcription Beats per minute


sys.databases in a cursor skipping databases

Question: I've seen a bit of production code that looks like it should be fine, and works 80% of the time, but the other 20% will appear to stop returning and iterating through the list of databases for no apparent reason:
DECLARE c_UserDatabases CURSOR FOR
  SELECT Name
  FROM   Sys.Databases SD (NOLOCK)
  ORDER  BY Name

OPEN c_UserDatabases
FETCH Next FROM c_UserDatabases INTO @v_DatabaseName
WHILE @@FETCH_STATUS = 0
  BEGIN
      -- Query that takes a few minutes to run (using dynamic SQL and EXEC, etc)
      FETCH Next FROM c_UserDatabases INTO @v_DatabaseName
  END

CLOSE c_UserDatabases
DEALLOCATE c_UserDatabases

This is on SQL Server 2008 SP3. I've noticed articles mentioning it was iffy on some versions if you did not order by Name, but nothing to indicate this failure condition. I think we might be in a rare situation because the inner section can takes so long to run?
I'd like to know if anyone else has seen this. I'm planning on rewriting it to select into a temp table and cursor through that instead.
Comment: Why're you using NOLOCK on SYS.DATABASES?!
Comment: I didn't write the code. But I did overhear an issue where long-running cursors on the user/login table were preventing logins during long runs, and it might be have been added after that as a safeguard? Why do you ask.
Answer: This is a really old question of mine but the answer was that if you are iterating Sys.Databases your cursor type should be STATIC.
Otherwise if something happens to that table while you're iterating it (i.e. backups, etc) it can skip a database. Same with sp_MSForeachDB.
Thankfully we moved past this bit long ago. And yeah, NOLOCK was taken out.
Answer: Although undocumented, sp_MSForeachDB provides a nice way of executing queries against all DBs. Would this approach help?
EXEC sp_MSForeachDB '
    SELECT * FROM [?].sys.tables
'


I have done crosstabs and a Correspondence Analysis, having trouble reporting and interpreting Chi-Squared and Inertia?

Question: I have data on 1500 cases with two variables (color, genus) with 5 colors and 6 genera. I almost had generally equal spread across genus, but one is disproportionately represented and has about twice as many cases as the other 5. Eyeballing the data, it is clear that within each genus, cases tend to be overwhelmingly one color or one of two colors, with a minority being the rest. Plus, within color groups, there tends to be a dramatic difference between the genus that have a high count and those that don't. It is clear that there are strong associations. That's as far as my brain gets me, but I did crosstabs and correspondence analysis and got a summary table and I am a bit lost on how to interpret it. I've read a few papers trying to explain what's going on but am still getting confused.

I need to report the inertia and chi-squared values and interpret them both. I can report Chi-Squared: (20, N=1500) = 941.653, p<0.001.
1) Is this right? I think it is based on my reading but I might be wrong.
2) How do I report Inertia? I'm not sure I fully understand how Inertia works because I have two values for it, Inertia in the third column and then again with Proportion of Inertia Accounted for, and these numbers are different. The first one adds up to .628 and the second to 1.000
3) And how am I meant to interpret Chi-Squared other than that it is high? What is high meant to be relative to?
4) How do I interpret Inertia and which Inertia value am I looking at?
Answer: The summary table supports that most of the variation is in the first dimension. Correspondence analysis is often best reported on visually, with biplots. Some examples in

How variables (constrained loadings) are selected in a biplot CCA
Interpreting biplots in correspondence analysis
Interpreting 2D correspondence analysis plots (Part II)
Some theory
PCA and Correspondence analysis in their relation to Biplot