答:
The problem is not with the assignment of the return value of strings.Split() to the local variable slice, which is totally fine.

The problem is that you used fmt.Printf() which expects a format string, and based on that format string it formats / substitutes expected parameters. Since your format string does not contain any verbs, that fmt.Printf() call expects no parameters, yet you pass it one, so it signals this with those extra characters (kind of error string).

Provide a valid format string where you indicate you will supply 1 parameter, a slice:

```<code>fmt.Printf("answer: %v", slice)
</code>```

With this, the output is:

```<code>answer: [f u l l t e x t]
</code>```

Or alternatively use fmt.Println(), which does not expect a format string:

```<code>fmt.Println("answer:", slice)
</code>```

(Note that there is no space after the colon, as fmt.Println() adds a space between 2 values if one of them is of type string).

Output is the same. Try the examples on the Go Playground.

Staying with fmt.Printf(), when the parameter involves string values, the %q verb is often more useful, as that will print quoted string values, much easier to spot certain mistakes (e.g. invisible characters, or if a string contains spaces, it will become obvious):

```<code>fmt.Printf("answer: %q\n", slice)
</code>```

Output of this (try it on the Go Playground):

```<code>answer: ["f" "u" "l" "l" "t" "e" "x" "t"]
</code>```

If you'd wanted to append the result of a function call, this is how it could look like:

```<code>slice := []string{"initial", "content"}
slice = append(slice, strings.Split(str, "")...)

fmt.Printf("answer: %q\n", slice)
</code>```

And now the output (try it on the Go Playground):

```<code>answer: ["initial" "content" "f" "u" "l" "l" "t" "e" "x" "t"]
</code>```

Title: How to write the result of a function in a slice

Body:
The problem is not with the assignment of the return value of strings.Split() to the local variable slice, which is totally fine.

The problem is that you used fmt.Printf() which expects a format string, and based on that format string it formats / substitutes expected parameters. Since your format string does not contain any verbs, that fmt.Printf() call expects no parameters, yet you pass it one, so it signals this with those extra characters (kind of error string).

Provide a valid format string where you indicate you will supply 1 parameter, a slice:

fmt.Printf("answer: %v", slice)

With this, the output is:

answer: [f u l l t e x t]

Or alternatively use fmt.Println(), which does not expect a format string:

fmt.Println("answer:", slice)

(Note that there is no space after the colon, as fmt.Println() adds a space between 2 values if one of them is of type string).

Output is the same. Try the examples on the Go Playground.

Staying with fmt.Printf(), when the parameter involves string values, the %q verb is often more useful, as that will print quoted string values, much easier to spot certain mistakes (e.g. invisible characters, or if a string contains spaces, it will become obvious):

fmt.Printf("answer: %q\n", slice)

Output of this (try it on the Go Playground):

answer: ["f" "u" "l" "l" "t" "e" "x" "t"]

If you'd wanted to append the result of a function call, this is how it could look like:

slice := []string{"initial", "content"}
slice = append(slice, strings.Split(str, "")...)

fmt.Printf("answer: %q\n", slice)

And now the output (try it on the Go Playground):

answer: ["initial" "content" "f" "u" "l" "l" "t" "e" "x" "t"]


来源: stackexchange

问:
Saving Problems in ImagePlus
I'm trying to change bit depth of a gray-scale image to 16-bit in Java. This is my source code. Though original gray-scale image is converted to 16-bit, after saving it in the PC, bit depth of that saved image is the same size of original image not the converted one (16-bit). How can I fix this problem. Thank You.</p>

```<code>public class ImageConverter {
    private ImagePlus imp;
    private int type;
    private static boolean doScaling = true;

    /** Construct an ImageConverter based on an ImagePlus object. */
    public ImageConverter(ImagePlus imp) {
        this.imp = imp;
        this.type = imp.getType();
        System.out.println(imp.getType());
    }

    /** Convert your ImagePlus to 16-bit grayscale. */
    public ImagePlus convertToGray16() {
        System.out.println(this.imp.getBitDepth());
        if (this.type==ImagePlus.GRAY16)
            return imp;
        if (!(this.type==ImagePlus.GRAY8||this.type==ImagePlus.GRAY32||this.type==ImagePlus.COLOR_RGB))
            throw new IllegalArgumentException("Unsupported conversion");
        ImageProcessor ip = imp.getProcessor();
        imp.trimProcessor();
        Calibration cal = imp.getCalibration();
        //imp.setProcessor(null, ip.convertToFloat());
        imp.setProcessor(null, ip.convertToShort(doScaling));
        imp.setCalibration(cal); //update calibration
        return imp;
    }

    /** Set true to scale to 0-255 when converting short to byte or float
        to byte and to 0-65535 when converting float to short.
     * @param scaleConversions */
    public static void setDoScaling(boolean scaleConversions) {
        doScaling = scaleConversions;
        IJ.register(ImageConverter.class);
    }

    /** Returns true if scaling is enabled.
     * @return  */
    public static boolean getDoScaling() {
        return doScaling;
    }

    public static void main(String []args) throws IOException{
         ImagePlus i=new ImagePlus("D:\\grayScaleImage.bmp");
         ImageConverter ic=new ImageConverter(i);
         i=ic.convertToGray16();
         //BufferedImage imgBuffer=i.getProcessor().getBufferedImage();

         //System.out.println(imgBuffer);
         System.out.println(i.getBitDepth());
         //***********************************************//
         //problem here-though bit depth of converted image is 32, after saved in the PC, size becomes the original image size
         FileSaver fs=new FileSaver(i);
         boolean result=fs.saveAsBmp("D:\\grayScaleImage_32.bmp");

    }
}
</code>```

答:
ImageJ's BMP_Writer class (which gets called by FileSaver) seems to only support 8-bit and 24-bit (RGB) images.

When saving any grayscale image, it applies the current 8-bit lookup table (LUT) and always saves 8-bit. See the source code here:

https://github.com/imagej/imagej1/blob/master/ij/plugin/BMP_Writer.java#L63-L81

You might want to try using SCIFIO or Bio-Formats for saving instead (although I didn't check if they support any other bit depth).

Also, instead of copy-pasting code from ImageJ 1.x, you can simply depend on the ImageJ Ops library to do your conversion. Here's a simple Groovy script (using script parameters and runnable from the script editor) illustrating this:

#@ OpService ops
#@ Img inputImage

result = ops.run("convert.uint16", inputImage)
```

ContentLicense: CC BY-SA 3.0

Title: Saving Problems in ImagePlus

Body:
I'm trying to change bit depth of a gray-scale image to 16-bit in Java. This is my source code. Though original gray-scale image is converted to 16-bit, after saving it in the PC, bit depth of that saved image is the same size of original image not the converted one (16-bit). How can I fix this problem. Thank You.

public class ImageConverter {
    private ImagePlus imp;
    private int type;
    private static boolean doScaling = true;

    /** Construct an ImageConverter based on an ImagePlus object. */
    public ImageConverter(ImagePlus imp) {
        this.imp = imp;
        this.type = imp.getType();
        System.out.println(imp.getType());
    }

    /** Convert your ImagePlus to 16-bit grayscale. */
    public ImagePlus convertToGray16() {
        System.out.println(this.imp.getBitDepth());
        if (this.type==ImagePlus.GRAY16)
            return imp;
        if (!(this.type==ImagePlus.GRAY8||this.type==ImagePlus.GRAY32||this.type==ImagePlus.COLOR_RGB))
            throw new IllegalArgumentException("Unsupported conversion");
        ImageProcessor ip = imp.getProcessor();
        imp.trimProcessor();
        Calibration cal = imp.getCalibration();
        //imp.setProcessor(null, ip.convertToFloat());
        imp.setProcessor(null, ip.convertToShort(doScaling));
        imp.setCalibration(cal); //update calibration
        return imp;
    }

    /** Set true to scale to 0-255 when converting short to byte or float
        to byte and to 0-65535 when converting float to short.
     * @param scaleConversions */
    public static void setDoScaling(boolean scaleConversions) {
        doScaling = scaleConversions;
        IJ.register(ImageConverter.class);
    }

    /** Returns true if scaling is enabled.
     * @return  */
    public static boolean getDoScaling() {
        return doScaling;
    }

    public static void main(String []args) throws IOException{
         ImagePlus i=new ImagePlus("D:\\grayScaleImage.bmp");
         ImageConverter ic=new ImageConverter(i);
         i=ic.convertToGray16();
         //BufferedImage imgBuffer=i.getProcessor().getBufferedImage();

         //System.out.println(imgBuffer);
         System.out.println(i.getBitDepth());
         //***********************************************//
         //problem here-though bit depth of converted image is 32, after saved in the PC, size becomes the original image size
         FileSaver fs=new FileSaver(i);
         boolean result=fs.saveAsBmp("D:\\grayScaleImage_32.bmp");

    }
}


问:
Rails3: How do I visit a subdomain in a steak(rspec) spec using Capybara
I want to access user1.application.local.dev/panel/new from a steak spec.

How do I do it?

答:
This is a Capybara question. Set the default_host when you need it

```<code>Capybara.default_host = 'sub.domain.com'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is a Capybara question. Set the default_host when you need it

Capybara.default_host = 'sub.domain.com'


答:
For example, For each Depth value in the left table I basically want to look up the similar depth range in the Right table and return the closest inclination for that depth.

The problem is the 'Depth' values in 'Left Table' are Time Series Data so I would basically get a row of values every 5 seconds. The 'Right table' 'MeasuredDepth' column values are only recorded every 95 feet. So I'm just trying to get the closest inclination value from the Right table that matches up with the more random 'Depth' value in the Left Table.

enter image description here

Title: Python Pandas Calc Column

Body:
I have two Pandas dataframes and I am trying to join the right table on the left table where Inclination closest matches the Left tables 'Depth' from the Right Tables 'MeasuredDepth'?

Example left table  (main table)

index     Date_Time         Depth
6659    4/25/2017 1:26       2073.02
6660    4/25/2017 1:26       2073.287
6661    4/25/2017 1:26       2073.916
6662    4/25/2017 1:26       2074.64
6663    4/25/2017 1:26       2075.335
6664    4/25/2017 1:26       2076.044

Example Right table (Reference table)

index   MeasuredDepth   Inclination
16      1844           1.42
17      1939           1.69
18      2034           1.43
19      2128           1.39
20      2223           1.12
21      2317           1.22
22      2412           1.1
23      2600           0.56
24      2695           1.97

Example Result Table

index   DATETIME        Depth        Inclination
6659    4/25/2017 1:26      2073.02          1.43
6660    4/25/2017 1:26      2073.287         1.43
6661    4/25/2017 1:26      2073.916         1.43
...
26704   5/3/2017 23:23      2625.316         0.56
26705   5/3/2017 23:23      2626.143         0.56
26706   5/3/2017 23:24       2627.08         0.56
26707   5/3/2017 23:24      2628.056         0.56

Any help would be appreciated!


问:
My minute variable is displaying 900 minutes ahead
My end result is something like: 918 minutes past 3 o'clock on July
 9, 2017, 1st Era.

918 minutes is weird, and I'm not willing to do that much math to figure out what time it is. Here is my code below.

```<code>package learn;

import java.time.*;
import java.time.temporal.*;

class time {

    public static void main (String[] args) {

    LocalDateTime now = LocalDateTime.now();

    int minute = now.get(ChronoField.MINUTE_OF_DAY);
    int hour = now.get(ChronoField.HOUR_OF_DAY);
    int day = now.get(ChronoField.DAY_OF_MONTH);
    int month = now.get(ChronoField.MONTH_OF_YEAR);
    int year = now.get(ChronoField.YEAR_OF_ERA);
    int era = now.get(ChronoField.ERA);

    if (hour < 12) {
        System.out.println("Good morning you sack o' shit.");
    }
    else if (hour < 17) {
        System.out.println("Get a job hobo. ");
    }
    else {
        System.out.println("Night night, jobless");
    }

    System.out.print("It's: ");
    if (minute != 0) {

    System.out.print("" + minute + " ");

    System.out.print( (minute != 1) ? "minutes" : "minute");
    System.out.print(" past");

    }
    System.out.print(" ");
    System.out.print( (hour > 12) ? (hour - 12) : hour);
    System.out.print(" o'clock on ");

    switch (month) {
        case 1: System.out.println("January"); break;
        case 2: System.out.println("February"); break;
        case 3: System.out.println("March"); break;
        case 4: System.out.println("April"); break;
        case 5: System.out.println("May"); break;
        case 6: System.out.println("June"); break;
        case 7: System.out.println("July"); break;
        case 8: System.out.println("August"); break;
        case 9: System.out.println("September"); break;
        case 10: System.out.println("October"); break;
        case 11: System.out.println("November"); break;
        case 12: System.out.println("December"); break;
       }
    System.out.println(" " + day + ", " + year + ", " + era + "st Era.");

    }

}
</code>```

答:
From the ChronoField Javadoc, here is the list of fields you appear to need:

MINUTE_OF_HOUR
The minute-of-hour.

HOUR_OF_DAY
The hour-of-day.

DAY_OF_MONTH
The day-of-month.

MONTH_OF_YEAR
The month-of-year, such as March.

YEAR
The proleptic year, such as 2012.

Body:
My end result is something like: 918 minutes past 3 o'clock on July
 9, 2017, 1st Era.

918 minutes is weird, and I'm not willing to do that much math to figure out what time it is. Here is my code below.

package learn;

import java.time.*;
import java.time.temporal.*;

class time {

    public static void main (String[] args) {

    LocalDateTime now = LocalDateTime.now();

    int minute = now.get(ChronoField.MINUTE_OF_DAY);
    int hour = now.get(ChronoField.HOUR_OF_DAY);
    int day = now.get(ChronoField.DAY_OF_MONTH);
    int month = now.get(ChronoField.MONTH_OF_YEAR);
    int year = now.get(ChronoField.YEAR_OF_ERA);
    int era = now.get(ChronoField.ERA);

    if (hour < 12) {
        System.out.println("Good morning you sack o' shit.");
    }
    else if (hour < 17) {
        System.out.println("Get a job hobo. ");
    }
    else {
        System.out.println("Night night, jobless");
    }

    System.out.print("It's: ");
    if (minute != 0) {

    System.out.print("" + minute + " ");

    System.out.print( (minute != 1) ? "minutes" : "minute");
    System.out.print(" past");

    }
    System.out.print(" ");
    System.out.print( (hour > 12) ? (hour - 12) : hour);
    System.out.print(" o'clock on ");

    switch (month) {
        case 1: System.out.println("January"); break;
        case 2: System.out.println("February"); break;
        case 3: System.out.println("March"); break;
        case 4: System.out.println("April"); break;
        case 5: System.out.println("May"); break;
        case 6: System.out.println("June"); break;
        case 7: System.out.println("July"); break;
        case 8: System.out.println("August"); break;
        case 9: System.out.println("September"); break;
        case 10: System.out.println("October"); break;
        case 11: System.out.println("November"); break;
        case 12: System.out.println("December"); break;
       }
    System.out.println(" " + day + ", " + year + ", " + era + "st Era.");

    }

}


问:
Javascript counter on key input instead of button?
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

```<code><html>
<head>
<script type="text/javascript">

function modify_qty(val) {
var qty = document.getElementById('qty').value;
var new_qty = parseInt(qty,10) + val;

if (new_qty < 0) {
    new_qty = 0;
}

document.getElementById('qty').value = new_qty;
return new_qty;
}

function modify_qtyn(val) {
var qtyn = document.getElementById('qtyn').value;
var new_qtyn = parseInt(qtyn,10) + val;

if (new_qtyn < 0) {
    new_qtyn = 0;
}

document.getElementById('qtyn').value = new_qtyn;
return new_qtyn;
}

</script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="box">
    <label for="Positive"><abbr title="Positive">Qty</abbr></label>
    <label for="Negative"><abbr title="Negative">Qtyn</abbr></label>
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

</div>

</body>
</html>
</code>```

I found the solution by adding this:

```<code>function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};
</code>```

答:
I found the solution by adding this:</p>

```<code>function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};
</code>```

Body:
So I have this counter that increments 'positive' and 'negative' values, it's working fine. Now I also want to assign keyboard key to increment the values, 'f' for negative and 'j' for positive. How do I do this?
I have been fiddling with onkeypress/onkeyup but it is still confusing.

<link rel="stylesheet" type="text/css" href="style.css">

    Qty
    Qtyn
    <input id="qtyn" value="0" />
    <input id="qty" value="0" />
    <button id="down" onclick="modify_qtyn(1)">MINUS</button>
    <button id="up" onclick="modify_qty(1)">PLUS</button>

I found the solution by adding this:

function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
    var key = code(e);
    if (key==102) {modify_qtyn(1);}
    if (key==70) {modify_qtyn(1);}
    if (key==106) {modify_qty(1);}
    if (key==74) {modify_qty(1);}
   };
};


问:
Microsoft (R) Visual C# Compiler version 4.6.1590.0 for C# 5
```<code>Microsoft (R) Visual C# Compiler version 4.6.1590.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240

error CS0016: Could not write to output file 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\8d0dec5c\beef09e6\App_Code.ax95x44c.dll' -- 'Access is denied. '
</code>```

How to solve this issue? I tried many things giving permissions to the folders, installing this (Install-Package Microsoft.Net.Compilers -Version 2.2.0) etc but no result.

Please suggest. I am a beginner to programming.

答:
Open a Developer Command Prompt for VS20xx (2012,2013,2015,2017). You can find this in the start menu.
Then run this command:

```<code>aspnet_regiis -i
</code>```

This should set up IIS to be run and oftentimes resolves this error. See this SO post for more info should that not work.

Body:
Microsoft (R) Visual C# Compiler version 4.6.1590.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.

This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240

error CS0016: Could not write to output file 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root\8d0dec5c\beef09e6\App_Code.ax95x44c.dll' -- 'Access is denied. '

How to solve this issue? I tried many things giving permissions to the folders, installing this (Install-Package Microsoft.Net.Compilers -Version 2.2.0) etc but no result.

Please suggest. I am a beginner to programming.

Body:
Open a Developer Command Prompt for VS20xx (2012,2013,2015,2017). You can find this in the start menu.
Then run this command:

aspnet_regiis -i

This should set up IIS to be run and oftentimes resolves this error. See this SO post for more info should that not work.


问:
Yeoman | yo command not found
Saw that there were some similar questions as this one but didn't find the answers satisfying enough or applicable to my problem so thought I'd thought I'd ask one more time.

i'm having trouble with the "$ yo" command and that my cmd keeps telling me that the command is not found.

i've installed yeoman through:

```<code>$npm install -g yo
</code>```

without any problems. I've also checked my $PATH under

```<code>$ echo $PATH
/c/Users/Anton/bin:.:/usr/local/bin:/mingw/bin:/bin:.:/c/Program Files (x86)/Java/jre7/bin:/usr/cmd:/usr/bin:/c/Program Files (x86)/nodejs/:/c/Users/Anton/AppData/Roaming/npm
</code>```

and confirmed that yo is installed together with other node modules. I'm able to call other commands such as:

```<code>$ bower

Usage:

bower <command> [<ar.....
</code>```

and

```<code>$ yeoman
==========================================================================
We're constantly looking for ways to make yeoman better!
May we anonymously report .....
</code>```

with out any problems. While yo results in failure

```<code>$ yo
sh.exe": yo: command not found
</code>```

Does anyone have any suggestions of what's wrong? I've read that ther might be something wrong with the $PATH? Can I reset it in any way?

(OS: Windows 8.1 | Node v0.10.29)

答:
Try these (Worked for me in Mac)</p>

```<code>1.  export PATH="$PATH":~/.node/bin

2.  npm config set prefix ~/npm

3.  echo "export NODE_PATH=$NODE_PATH:/home/$USERNAME/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc
</code>```

Title: Yeoman | yo command not found

Body:
Saw that there were some similar questions as this one but didn't find the answers satisfying enough or applicable to my problem so thought I'd thought I'd ask one more time.

i'm having trouble with the "$ yo" command and that my cmd keeps telling me that the command is not found.

i've installed yeoman through:

$npm install -g yo

without any problems. I've also checked my $PATH under

$ echo $PATH
/c/Users/Anton/bin:.:/usr/local/bin:/mingw/bin:/bin:.:/c/Program Files (x86)/Java/jre7/bin:/usr/cmd:/usr/bin:/c/Program Files (x86)/nodejs/:/c/Users/Anton/AppData/Roaming/npm

and confirmed that yo is installed together with other node modules. I'm able to call other commands such as:

$ bower

Usage:

bower <command> [<ar.....

and

$ yeoman
==========================================================================
We're constantly looking for ways to make yeoman better!
May we anonymously report .....

with out any problems. While yo results in failure

$ yo
sh.exe": yo: command not found

Does anyone have any suggestions of what's wrong? I've read that ther might be something wrong with the $PATH? Can I reset it in any way?

(OS: Windows 8.1 | Node v0.10.29)

Body:
Try these (Worked for me in Mac)

1.  export PATH="$PATH":~/.node/bin

2.  npm config set prefix ~/npm

3.  echo "export NODE_PATH=$NODE_PATH:/home/$USERNAME/npm/lib/node_modules" >> ~/.bashrc && source ~/.bashrc


问:
modifying text of a div using dojo
I have a dojo widget.For widget i have  2 files A.js and A.html.Now inside A.html i have something like

```<code><div id ="xyz" dojoAttachpoint="xyz"> </div>
</code>```

The above line is one line inside the widget template and its a normal html div

Now in A.js i make a asynchronous call to server.In the callback function of remote method i want modify the text of span xyz.I tryed following 3 ways, but none of them is working.

1) dojo.byId("xyz").innerHTML = "some text"

2) this.xyz.innerHTML ="some text"

3)

```<code> var myWidget = dijit.byId("pack1.abc.widget.widgetname_id");
            myWidget.xyz.innerHTML ="some text"
</code>```

None of the above approach works.

When i use approach 1 in other functions of A.js(non callback functions) it works fine.

答:
You cannot hardcode the id of a widget in it's template. The id has to identify an instance of a widget-type uniquely, so it has to be given on creation.

You can for example do something like, programmatic in js:

```<code>var myA = new myWidgets.A({});
myA.startup();
myA.xyz.innerHTML = "some text"
</code>```

or declaratively in html:

```<code><div data-dojo-type="myWidgets.A" data-dojo-props="id:'myA'"></div>
</code>```

and js:

```<code>dijit.byId("myA").xyz.innerHTML = "some text";
</code>```

Title: modifying text of a div using dojo

Body:
I have a dojo widget.For widget i have  2 files A.js and A.html.Now inside A.html i have something like

The above line is one line inside the widget template and its a normal html div

Now in A.js i make a asynchronous call to server.In the callback function of remote method i want modify the text of span xyz.I tryed following 3 ways, but none of them is working.

1) dojo.byId("xyz").innerHTML = "some text"

2) this.xyz.innerHTML ="some text"

3)

 var myWidget = dijit.byId("pack1.abc.widget.widgetname_id");
            myWidget.xyz.innerHTML ="some text"

None of the above approach works.

When i use approach 1 in other functions of A.js(non callback functions) it works fine.

Body:
You cannot hardcode the id of a widget in it's template. The id has to identify an instance of a widget-type uniquely, so it has to be given on creation.

You can for example do something like, programmatic in js:

var myA = new myWidgets.A({});
myA.startup();
myA.xyz.innerHTML = "some text"

or declaratively in html:

<div data-dojo-type="myWidgets.A" data-dojo-props="id:'myA'"></div>

and js:

dijit.byId("myA").xyz.innerHTML = "some text";


问:
Pre-selected option in select Angularjs
I have tried everything in the book. I just cant get option 1 value="1" User to be preselected. I am using angular website. If I remove ng-model="type" it gets preselected. but just cant get it working with ng-model="type" in it.

   <select name="type" id="type" class="form-control" ng-model="type">
       <option value="1" selected="selected">User</option>
       <option>Broadcasters</option>
   </select>

```

答:
Simple solution: You can use ng-selected directive

```<code><div class="form-group">
   <select name="type" id="type" class="form-control" ng-model="type">
      <option value="1" ng-selected="true">User</option>
      <option>Broadcasters</option>
   </select>
</div>
</code>```

It happens because you pass Number to ng-model, instead input has string as value. Also it will work without ng-selected directive if you will pass String to ng-model.

Better to use: ng-options

```<code><select ng-options="type as type.label for type in types" ng-model="currentType"></select>

$scope.types = [{
            id: 1,
            label: 'User'
        }, {
            id: 2,
            label: 'Broadcasters'
        }];

$scope.currentType = $scope.types[0]; //default type
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pre-selected option in select Angularjs

Body:
Simple solution: You can use ng-selected directive

<div class="form-group">
   <select name="type" id="type" class="form-control" ng-model="type">
      <option value="1" ng-selected="true">User</option>
      <option>Broadcasters</option>
   </select>
</div>

It happens because you pass Number to ng-model, instead input has string as value. Also it will work without ng-selected directive if you will pass String to ng-model.

Better to use: ng-options

<select ng-options="type as type.label for type in types" ng-model="currentType"></select>

$scope.types = [{
            id: 1,
            label: 'User'
        }, {
            id: 2,
            label: 'Broadcasters'
        }];

$scope.currentType = $scope.types[0]; //default type


问:
Android pass jsonObject to another activity by clicking on recyclerview
I'm making an app in Android.

I'm getting JSON data containing pokemons name from URL(http://kerast.com/pokemon/pokemons.json) using retrofit. The names and types display in a recyclerView and after clicking on one another Activity opens and display attack, defense and moves.

So far I've been able to open a new activity but have no idea how to pass the object. I suppose there is no need to reload the json by re writing the same code twice for each activity ?

Here is my class :

```<code>public class Pokemon {

    private String name;
    private String type;
    private Integer attack;
    private Integer defense;
    private Integer evolveLevel;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public Integer getattack() { return attack; }

    public Integer getdefense() { return defense; }

    public Integer getEvolveLevel() { return evolveLevel; }
}
</code>```

My DataAdpater :

```<code>public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable {

    private ArrayList<Pokemon> mArrayList;
    private ArrayList<Pokemon> mFilteredList;

    public DataAdapter(ArrayList<Pokemon> arrayList) {
        mArrayList = arrayList;
        mFilteredList = arrayList;

    }

    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

        viewHolder.tv_name.setText(mFilteredList.get(i).getName());
        viewHolder.tv_version.setText(mFilteredList.get(i).getName());
        viewHolder.tv_api_level.setText(mFilteredList.get(i).getType());
    }

    @Override
    public int getItemCount() {

        return mFilteredList.size();
    }

    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    mFilteredList = mArrayList;
                } else {

                    ArrayList<Pokemon> filteredList = new ArrayList<>();

                    for (Pokemon marraylist : mArrayList) {

                        if (marraylist.getName().toLowerCase().contains(charString) ||  marraylist.getType().toLowerCase().contains(charString)) {

                            filteredList.add(marraylist);
                        }
                    }

                    mFilteredList = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = mFilteredList;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                mFilteredList = (ArrayList<Pokemon>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_name,tv_version,tv_api_level;
        public ViewHolder(View view) {
            super(view);

            tv_name = (TextView)view.findViewById(R.id.tv_name);
            tv_version = (TextView)view.findViewById(R.id.tv_version);
            tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), Main2Activity.class);
                    intent.putExtra("attack", Pokemon);
                    view.getContext().startActivity(intent);
                }
            });

        }
    }

}
</code>```

And finally my MainActivity :

```<code>public class MainActivity extends AppCompatActivity {

    public static final String BASE_URL = "http://kerast.com";
    private RecyclerView mRecyclerView;
    private ArrayList<Pokemon> mArrayList;
    private DataAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViews();
        loadJSON();
    }

    private void initViews(){
        mRecyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
    }
    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

                JSONResponse jsonResponse = response.body();
                mArrayList = new ArrayList<>(Arrays.asList(jsonResponse.getPokemons()));
                mAdapter = new DataAdapter(mArrayList);
                mRecyclerView.setAdapter(mAdapter);
            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
        search(searchView);
        return true;
    }

    private void search(SearchView searchView) {

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                mAdapter.getFilter().filter(newText);
                return true;
            }
        });
    }
}
</code>```

So how can I get only Attack Defense and evolveLevel to be display in the second Activity ?

答:
implement the Serializable interface Pokemon implements Serializable
  and
   then you can pass object instances in the intent extra using the putExtra()

```<code>//send :
intent.putExtra("Pokemon", obj);
//retrieve :
getIntent().getSerializableExtra("MyClass");
</code>```

Body:
I'm making an app in Android.

I'm getting JSON data containing pokemons name from URL(http://kerast.com/pokemon/pokemons.json) using retrofit. The names and types display in a recyclerView and after clicking on one another Activity opens and display attack, defense and moves.

So far I've been able to open a new activity but have no idea how to pass the object. I suppose there is no need to reload the json by re writing the same code twice for each activity ?

Here is my class :

public class Pokemon {

    private String name;
    private String type;
    private Integer attack;
    private Integer defense;
    private Integer evolveLevel;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public Integer getattack() { return attack; }

    public Integer getdefense() { return defense; }

    public Integer getEvolveLevel() { return evolveLevel; }
}

My DataAdpater :

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> implements Filterable {

    private ArrayList<Pokemon> mArrayList;
    private ArrayList<Pokemon> mFilteredList;

    public DataAdapter(ArrayList<Pokemon> arrayList) {
        mArrayList = arrayList;
        mFilteredList = arrayList;

    }

    @Override
    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

        viewHolder.tv_name.setText(mFilteredList.get(i).getName());
        viewHolder.tv_version.setText(mFilteredList.get(i).getName());
        viewHolder.tv_api_level.setText(mFilteredList.get(i).getType());
    }

    @Override
    public int getItemCount() {

        return mFilteredList.size();
    }

    @Override
    public Filter getFilter() {

        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    mFilteredList = mArrayList;
                } else {

                    ArrayList<Pokemon> filteredList = new ArrayList<>();

                    for (Pokemon marraylist : mArrayList) {

                        if (marraylist.getName().toLowerCase().contains(charString) ||  marraylist.getType().toLowerCase().contains(charString)) {

                            filteredList.add(marraylist);
                        }
                    }

                    mFilteredList = filteredList;
                }

                FilterResults filterResults = new FilterResults();
                filterResults.values = mFilteredList;
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                mFilteredList = (ArrayList<Pokemon>) filterResults.values;
                notifyDataSetChanged();
            }
        };
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private TextView tv_name,tv_version,tv_api_level;
        public ViewHolder(View view) {
            super(view);

            tv_name = (TextView)view.findViewById(R.id.tv_name);
            tv_version = (TextView)view.findViewById(R.id.tv_version);
            tv_api_level = (TextView)view.findViewById(R.id.tv_api_level);

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), Main2Activity.class);
                    intent.putExtra("attack", Pokemon);
                    view.getContext().startActivity(intent);
                }
            });

        }
    }

}

And finally my MainActivity :

public class MainActivity extends AppCompatActivity {

    public static final String BASE_URL = "http://kerast.com";
    private RecyclerView mRecyclerView;
    private ArrayList<Pokemon> mArrayList;
    private DataAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initViews();
        loadJSON();
    }

    private void initViews(){
        mRecyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
        mRecyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
    }
    private void loadJSON(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface request = retrofit.create(RequestInterface.class);
        Call<JSONResponse> call = request.getJSON();
        call.enqueue(new Callback<JSONResponse>() {
            @Override
            public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {

                JSONResponse jsonResponse = response.body();
                mArrayList = new ArrayList<>(Arrays.asList(jsonResponse.getPokemons()));
                mAdapter = new DataAdapter(mArrayList);
                mRecyclerView.setAdapter(mAdapter);
            }

            @Override
            public void onFailure(Call<JSONResponse> call, Throwable t) {
                Log.d("Error",t.getMessage());
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(search);
        search(searchView);
        return true;
    }

    private void search(SearchView searchView) {

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                mAdapter.getFilter().filter(newText);
                return true;
            }
        });
    }
}

So how can I get only Attack Defense and evolveLevel to be display in the second Activity ?

Body:
implement the Serializable interface Pokemon implements Serializable
  and
   then you can pass object instances in the intent extra using the putExtra()

//send :
intent.putExtra("Pokemon", obj);
//retrieve :
getIntent().getSerializableExtra("MyClass");


问:
OpenGL screen coordinates to world coordinates
I am trying to get world Coordinates from screen coordinates with OpenGl. I made some research but values returned are uncoherent. In fact in my world I have a surface at Z=0 and I want to have the 3d coordinates of a point in that surface so with Z=0. Here my research : </p>

```<code>float cursZ = 1;
long posX, posY, posZ = 0;

int viewport[4];
viewport[0] = Originex;
viewport[1] = Originey;
viewport[2] = largeFen;
viewport[3] = hautFen;
CMatrix4 modelView;
CMatrix4 proj;
CMatrix4 A;
CMatrix4 out;

typeCoorDepl proche = 100.;
typeCoorDepl loin = largeFen + hautFen;

Renderer.GetMatrix(MAT_MODELVIEW, modelView);
Renderer.GetMatrix(MAT_PROJECTION, proj);

modelView.LookAt(TVector3T(sendAngleX, angleY, SendAngleZ), TVector3T(0, 0, 0));

switch (modeVue)// get MAT_PROJECTION
{
case 1: // mode isometrique rotation centree sur l'ecran
    proj.OrthoOffCenter(-(largeFen / 2.0f), (hautFen / 2.0f), (largeFen / 2.0f), -(hautFen / 2.0f), proche, loin);
    break;
case 2: // mode conique rotation centree sur l'ecran
    proj.PerspectiveFOV((70.0*pi / 180) / 2, largeFen / hautFen, proche, loin);
    break;
case 3: // mode isometrique rotation centree sur l'ecran
    proj.OrthoOffCenter(-(largeFen / 2.0f), (hautFen / 2.0f), (largeFen / 2.0f), -(hautFen / 2.0f), proche, loin);
    break;
case 4: // mode conique rotation centree sur l'objet et non sur l'ecran
    proj.PerspectiveFOV((70.0*pi / 180), largeFen / hautFen, proche, loin);
    break;
default:
    break;
}

cursY = hautFen - cursY; // windows start from top-left as openGL from bottom-left
double posx, posy, posz;

float m[16];//, A[16];
float in[4];//, out[4];

A = proj*modelView;

A.Inverse();

in[0] = cursX;
in[1] = cursY;
in[2] = cursZ;
in[3] = 1.0;

/* Map x and y from window coordinates */
in[0] = (in[0] - viewport[0]) / viewport[2];
in[1] = (in[1] - viewport[1]) / viewport[3];

/* Map to range -1 to 1 */
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;

CMatrix4 forTestIn;
forTestIn.a11 = in[0];
forTestIn.a12 = in[1];
forTestIn.a13 = in[2];
forTestIn.a14 = in[3];

out = A*forTestIn;
out.a11 /= out.a14;
out.a12 /= out.a14;
out.a13 /= out.a14;

*finPosX = out.a11;
*finPosY = out.a12;
*finPosZ = out.a13;
</code>```

<p>Here my OrthoOffCenter and PerspectiveFOV function : </p>

```<code>inline void CMatrix4::OrthoOffCenter(typeCoorDepl Left, typeCoorDepl Top, typeCoorDepl Right, typeCoorDepl Bottom, typeCoorDepl Near, typeCoorDepl Far)
{
    a11 = 2 / (Right - Left); a12 = 0.0f;               a13 = 0.0f;           a14 = (Left + Right) / (Left - Right);
    a21 = 0.0f;               a22 = 2 / (Top - Bottom); a23 = 0.0f;           a24 = (Bottom + Top) / (Bottom - Top);
    // a31 = 0.0f;               a32 = 0.0f;               a33 = -2/(Far - Near); a34 = (Near + Far) / (Far - Near);
    // substitution Far/Near cause pb depth buffer
    a31 = 0.0f;               a32 = 0.0f;               a33 = -2/(Near - Far); a34 = (Far + Near) / (Near - Far);
    a41 = 0.0f;               a42 = 0.0f;               a43 = 0.0f; a44 = 1.0f;
}

inline void CMatrix4::PerspectiveFOV(typeCoorDepl Fov, typeCoorDepl Ratio, typeCoorDepl Near, typeCoorDepl Far)
{
    typeCoorDepl YScale = 1.0f / std::tan(Fov / 2);
    typeCoorDepl XScale = YScale / Ratio;
    typeCoorDepl Coeff  = Far / (Far - Near);

    a11 = XScale; a12 = 0.0f;   a13 = 0.0f;  a14 = 0.0f;
    a21 = 0.0f;   a22 = YScale; a23 = 0.0f;  a24 = 0.0f;
    a31 = 0.0f;   a32 = 0.0f;   a33 = Coeff; a34 = Near * -Coeff;
    a41 = 0.0f;   a42 = 0.0f;   a43 = 1.0f;  a44 = 0.0f;
    // nb : agir sur a14, a24 déplace le centre "de rotation"
}
</code>```

答:
If you draw something on the viewport the following transformations are performed:

Transformation by the modelview matrix (which may consists of a separated model matrix and view matrix).

Transformation by the projection matrix (regardless of whether you have perspective or orthographic projection).

After this transformations the coordinates are in the Normalized Device Coordinates space (NDC). The NDC is in a range from (-1,-1,-1) to (1,1,1).

If you want to convert back a point from the Normalized Device Coordinates (NDC) to the world space you have to do the exactly reverse transformations:

Transform back by the inverse projection matrix.

Transform back by the inverse modelview matrix.

See the answers to the Stack Overflow Question inverting a 4x4 matrix to see how to calculate a inverse matrix:

```<code>template < typename T_MD, typename T_MS = T_MD, typename T_SCALAR = float >
void mat44_inverse( T_MD &res, const T_MS &m )
{
    T_SCALAR Coef00 = (T_SCALAR)(m[2][2] * m[3][3] - m[3][2] * m[2][3]);
    T_SCALAR Coef02 = (T_SCALAR)(m[1][2] * m[3][3] - m[3][2] * m[1][3]);
    T_SCALAR Coef03 = (T_SCALAR)(m[1][2] * m[2][3] - m[2][2] * m[1][3]);

    T_SCALAR Coef04 = (T_SCALAR)(m[2][1] * m[3][3] - m[3][1] * m[2][3]);
    T_SCALAR Coef06 = (T_SCALAR)(m[1][1] * m[3][3] - m[3][1] * m[1][3]);
    T_SCALAR Coef07 = (T_SCALAR)(m[1][1] * m[2][3] - m[2][1] * m[1][3]);

    T_SCALAR Coef08 = (T_SCALAR)(m[2][1] * m[3][2] - m[3][1] * m[2][2]);
    T_SCALAR Coef10 = (T_SCALAR)(m[1][1] * m[3][2] - m[3][1] * m[1][2]);
    T_SCALAR Coef11 = (T_SCALAR)(m[1][1] * m[2][2] - m[2][1] * m[1][2]);

    T_SCALAR Coef12 = (T_SCALAR)(m[2][0] * m[3][3] - m[3][0] * m[2][3]);
    T_SCALAR Coef14 = (T_SCALAR)(m[1][0] * m[3][3] - m[3][0] * m[1][3]);
    T_SCALAR Coef15 = (T_SCALAR)(m[1][0] * m[2][3] - m[2][0] * m[1][3]);

    T_SCALAR Coef16 = (T_SCALAR)(m[2][0] * m[3][2] - m[3][0] * m[2][2]);
    T_SCALAR Coef18 = (T_SCALAR)(m[1][0] * m[3][2] - m[3][0] * m[1][2]);
    T_SCALAR Coef19 = (T_SCALAR)(m[1][0] * m[2][2] - m[2][0] * m[1][2]);

    T_SCALAR Coef20 = (T_SCALAR)(m[2][0] * m[3][1] - m[3][0] * m[2][1]);
    T_SCALAR Coef22 = (T_SCALAR)(m[1][0] * m[3][1] - m[3][0] * m[1][1]);
    T_SCALAR Coef23 = (T_SCALAR)(m[1][0] * m[2][1] - m[2][0] * m[1][1]);

    _TMat44Helper<T_SCALAR> Fac0(Coef00, Coef00, Coef02, Coef03);
    _TMat44Helper<T_SCALAR> Fac1(Coef04, Coef04, Coef06, Coef07);
    _TMat44Helper<T_SCALAR> Fac2(Coef08, Coef08, Coef10, Coef11);
    _TMat44Helper<T_SCALAR> Fac3(Coef12, Coef12, Coef14, Coef15);
    _TMat44Helper<T_SCALAR> Fac4(Coef16, Coef16, Coef18, Coef19);
    _TMat44Helper<T_SCALAR> Fac5(Coef20, Coef20, Coef22, Coef23);

    _TMat44Helper<T_SCALAR> Vec0((T_SCALAR)m[1][0], (T_SCALAR)m[0][0], (T_SCALAR)m[0][0], (T_SCALAR)m[0][0]);
    _TMat44Helper<T_SCALAR> Vec1((T_SCALAR)m[1][1], (T_SCALAR)m[0][1], (T_SCALAR)m[0][1], (T_SCALAR)m[0][1]);
    _TMat44Helper<T_SCALAR> Vec2((T_SCALAR)m[1][2], (T_SCALAR)m[0][2], (T_SCALAR)m[0][2], (T_SCALAR)m[0][2]);
    _TMat44Helper<T_SCALAR> Vec3((T_SCALAR)m[1][3], (T_SCALAR)m[0][3], (T_SCALAR)m[0][3], (T_SCALAR)m[0][3]);

    _TMat44Helper<T_SCALAR> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2);
    _TMat44Helper<T_SCALAR> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4);
    _TMat44Helper<T_SCALAR> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5);
    _TMat44Helper<T_SCALAR> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5);

    _TMat44Helper<T_SCALAR> SignA((T_SCALAR)+1.0, (T_SCALAR)-1.0, (T_SCALAR)+1.0, (T_SCALAR)-1.0);
    _TMat44Helper<T_SCALAR> SignB((T_SCALAR)-1.0, (T_SCALAR)+1.0, (T_SCALAR)-1.0, (T_SCALAR)+1.0);
    std::array< _TMat44Helper<T_SCALAR>, 4 > Inverse{ Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB };

    _TMat44Helper<T_SCALAR> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]);

    _TMat44Helper<T_SCALAR> Dot0( Row0 );
    Dot0 = Dot0 * _TMat44Helper<T_SCALAR>( (T_SCALAR)m[0][0], (T_SCALAR)m[0][1], (T_SCALAR)m[0][2], (T_SCALAR)m[0][3] );
    T_SCALAR Dot1 = (Dot0[0] + Dot0[1]) + (Dot0[2] + Dot0[3]);

    T_SCALAR OneOverDeterminant = static_cast<T_SCALAR>(1.0) / Dot1;

    for ( int inx1 = 0; inx1 < 4; inx1 ++ )
    {
        for ( int inx2 = 0; inx2 < 4; inx2 ++ )
            res[inx1][inx2] = Inverse[inx1][inx2] * OneOverDeterminant;
    }
}

template< typename SCALAR_TYPE = float >
struct _TMat44Helper
{
    _TMat44Helper( void ) {}
    _TMat44Helper( SCALAR_TYPE x, SCALAR_TYPE y, SCALAR_TYPE z, SCALAR_TYPE w ) : m_v( { x, y, z, w } ){}
    _TMat44Helper( const std::array< SCALAR_TYPE, 4 > & v ) : m_v( v ) {}
    _TMat44Helper( const SCALAR_TYPE v[4] ) { std::memcpy( m_v.data(), v, 4 * sizeof( SCALAR_TYPE ) ); }
    _TMat44Helper( const _TMat44Helper &src ) : m_v( src.m_v ) {}

    _TMat44Helper & operator = ( const _TMat44Helper<SCALAR_TYPE> &src ) { m_v = src.m_v; return *this; }

    SCALAR_TYPE & operator[](int inx) { return m_v[inx]; }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator *( SCALAR_TYPE_OP s )
    {
        _TMat44Helper res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] * (SCALAR_TYPE)s;
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator +( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] + (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator -( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] - (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator *( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] * (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    std::array< SCALAR_TYPE, 4 > m_v;
};
</code>```

To map a point from viewport (screen) coordinates to the NDC you have to map the X-coordinate and the Y-coordinate to the range (-1.0, 1.0).
The Z-coordinate is more tricky, for this you have to access the depth buffer (The depth buffer can be rendered to a texture).
Read the depth at the XY position and convert it to the NDC:

```<code>X_ndc = X_screen * 2.0 / VP_sizeX - 1.0;
Y_ndc = Y_screen * 2.0 / VP_sizeY - 1.0;
Z_ndc = 2.0 * depth - 1.0;
</code>```

In your case you have only a 2D geometry and an orthographic projection, so you do not have to care about the depth, because the Z coordinate is always 0.0.

If you transform a point by the projection matrix (or the inverse projection matrix) you will get a point in a homogeneous coordinate system. To transform a point from a homogeneous coordinates system to a cartesian coordinate system you have to devide its X, Y and Z coordinate by it weight.
A general transformation function of a point in a cartesian coordinate system with a homogeneous 4*4 matrix may look like this:

```<code>using TVec3 = std::array<float, 3>;
using TVec4 = std::array<float, 4>;
using TMat4 = std::array<TVec4, 4>;

TVec3 Transform( const TVec3 &vec, const TMat4 &mat )
{
    h {
        vec[0] * mat[0][0] + vec[1] * mat[1][0] + vec[2] * mat[2][0] + mat[3][0],
        vec[0] * mat[0][1] + vec[1] * mat[1][1] + vec[2] * mat[2][1] + mat[3][1],
        vec[0] * mat[0][2] + vec[1] * mat[1][2] + vec[2] * mat[2][2] + mat[3][2],
        vec[0] * mat[0][3] + vec[1] * mat[1][3] + vec[2] * mat[2][3] + mat[3][3]
    };
    if ( h[3] == 0.0 )
        return TVec3{ 1.0e99 }; // division by zero
    return TVec3{ h[0]/h[3], h[1]/h[3], h[2]/h[3] };
}
</code>```

See the following WebGL example, where the color of the object, where the mouse hovers, is found by calculating back from the screen coordinates to the model coordinates.

            <form name="inputs">

  <input type="color" value="#000000" id="color" disabled>

  0

  0

            </form>

            <canvas id="camera-canvas" style="border: none;" width="256" height="256"></canvas>

```

Body:
I am trying to get world Coordinates from screen coordinates with OpenGl. I made some research but values returned are uncoherent. In fact in my world I have a surface at Z=0 and I want to have the 3d coordinates of a point in that surface so with Z=0. Here my research :

float cursZ = 1;
long posX, posY, posZ = 0;

int viewport[4];
viewport[0] = Originex;
viewport[1] = Originey;
viewport[2] = largeFen;
viewport[3] = hautFen;
CMatrix4 modelView;
CMatrix4 proj;
CMatrix4 A;
CMatrix4 out;

typeCoorDepl proche = 100.;
typeCoorDepl loin = largeFen + hautFen;

Renderer.GetMatrix(MAT_MODELVIEW, modelView);
Renderer.GetMatrix(MAT_PROJECTION, proj);

modelView.LookAt(TVector3T(sendAngleX, angleY, SendAngleZ), TVector3T(0, 0, 0));

switch (modeVue)// get MAT_PROJECTION
{
case 1: // mode isometrique rotation centree sur l'ecran
    proj.OrthoOffCenter(-(largeFen / 2.0f), (hautFen / 2.0f), (largeFen / 2.0f), -(hautFen / 2.0f), proche, loin);
    break;
case 2: // mode conique rotation centree sur l'ecran
    proj.PerspectiveFOV((70.0*pi / 180) / 2, largeFen / hautFen, proche, loin);
    break;
case 3: // mode isometrique rotation centree sur l'ecran
    proj.OrthoOffCenter(-(largeFen / 2.0f), (hautFen / 2.0f), (largeFen / 2.0f), -(hautFen / 2.0f), proche, loin);
    break;
case 4: // mode conique rotation centree sur l'objet et non sur l'ecran
    proj.PerspectiveFOV((70.0*pi / 180), largeFen / hautFen, proche, loin);
    break;
default:
    break;
}

cursY = hautFen - cursY; // windows start from top-left as openGL from bottom-left
double posx, posy, posz;

float m[16];//, A[16];
float in[4];//, out[4];

A = proj*modelView;

A.Inverse();

in[0] = cursX;
in[1] = cursY;
in[2] = cursZ;
in[3] = 1.0;

/* Map x and y from window coordinates */
in[0] = (in[0] - viewport[0]) / viewport[2];
in[1] = (in[1] - viewport[1]) / viewport[3];

/* Map to range -1 to 1 */
in[0] = in[0] * 2 - 1;
in[1] = in[1] * 2 - 1;
in[2] = in[2] * 2 - 1;

CMatrix4 forTestIn;
forTestIn.a11 = in[0];
forTestIn.a12 = in[1];
forTestIn.a13 = in[2];
forTestIn.a14 = in[3];

out = A*forTestIn;
out.a11 /= out.a14;
out.a12 /= out.a14;
out.a13 /= out.a14;

*finPosX = out.a11;
*finPosY = out.a12;
*finPosZ = out.a13;

Here my OrthoOffCenter and PerspectiveFOV function :

inline void CMatrix4::OrthoOffCenter(typeCoorDepl Left, typeCoorDepl Top, typeCoorDepl Right, typeCoorDepl Bottom, typeCoorDepl Near, typeCoorDepl Far)
{
    a11 = 2 / (Right - Left); a12 = 0.0f;               a13 = 0.0f;           a14 = (Left + Right) / (Left - Right);
    a21 = 0.0f;               a22 = 2 / (Top - Bottom); a23 = 0.0f;           a24 = (Bottom + Top) / (Bottom - Top);
    // a31 = 0.0f;               a32 = 0.0f;               a33 = -2/(Far - Near); a34 = (Near + Far) / (Far - Near);
    // substitution Far/Near cause pb depth buffer
    a31 = 0.0f;               a32 = 0.0f;               a33 = -2/(Near - Far); a34 = (Far + Near) / (Near - Far);
    a41 = 0.0f;               a42 = 0.0f;               a43 = 0.0f; a44 = 1.0f;
}

inline void CMatrix4::PerspectiveFOV(typeCoorDepl Fov, typeCoorDepl Ratio, typeCoorDepl Near, typeCoorDepl Far)
{
    typeCoorDepl YScale = 1.0f / std::tan(Fov / 2);
    typeCoorDepl XScale = YScale / Ratio;
    typeCoorDepl Coeff  = Far / (Far - Near);

    a11 = XScale; a12 = 0.0f;   a13 = 0.0f;  a14 = 0.0f;
    a21 = 0.0f;   a22 = YScale; a23 = 0.0f;  a24 = 0.0f;
    a31 = 0.0f;   a32 = 0.0f;   a33 = Coeff; a34 = Near * -Coeff;
    a41 = 0.0f;   a42 = 0.0f;   a43 = 1.0f;  a44 = 0.0f;
    // nb : agir sur a14, a24 déplace le centre "de rotation"
}

Body:
If you draw something on the viewport the following transformations are performed:

Transformation by the modelview matrix (which may consists of a separated model matrix and view matrix).

Transformation by the projection matrix (regardless of whether you have perspective or orthographic projection).

After this transformations the coordinates are in the Normalized Device Coordinates space (NDC). The NDC is in a range from (-1,-1,-1) to (1,1,1).

If you want to convert back a point from the Normalized Device Coordinates (NDC) to the world space you have to do the exactly reverse transformations:

Transform back by the inverse projection matrix.

Transform back by the inverse modelview matrix.

See the answers to the Stack Overflow Question inverting a 4x4 matrix to see how to calculate a inverse matrix:

template < typename T_MD, typename T_MS = T_MD, typename T_SCALAR = float >
void mat44_inverse( T_MD &res, const T_MS &m )
{
    T_SCALAR Coef00 = (T_SCALAR)(m[2][2] * m[3][3] - m[3][2] * m[2][3]);
    T_SCALAR Coef02 = (T_SCALAR)(m[1][2] * m[3][3] - m[3][2] * m[1][3]);
    T_SCALAR Coef03 = (T_SCALAR)(m[1][2] * m[2][3] - m[2][2] * m[1][3]);

    T_SCALAR Coef04 = (T_SCALAR)(m[2][1] * m[3][3] - m[3][1] * m[2][3]);
    T_SCALAR Coef06 = (T_SCALAR)(m[1][1] * m[3][3] - m[3][1] * m[1][3]);
    T_SCALAR Coef07 = (T_SCALAR)(m[1][1] * m[2][3] - m[2][1] * m[1][3]);

    T_SCALAR Coef08 = (T_SCALAR)(m[2][1] * m[3][2] - m[3][1] * m[2][2]);
    T_SCALAR Coef10 = (T_SCALAR)(m[1][1] * m[3][2] - m[3][1] * m[1][2]);
    T_SCALAR Coef11 = (T_SCALAR)(m[1][1] * m[2][2] - m[2][1] * m[1][2]);

    T_SCALAR Coef12 = (T_SCALAR)(m[2][0] * m[3][3] - m[3][0] * m[2][3]);
    T_SCALAR Coef14 = (T_SCALAR)(m[1][0] * m[3][3] - m[3][0] * m[1][3]);
    T_SCALAR Coef15 = (T_SCALAR)(m[1][0] * m[2][3] - m[2][0] * m[1][3]);

    T_SCALAR Coef16 = (T_SCALAR)(m[2][0] * m[3][2] - m[3][0] * m[2][2]);
    T_SCALAR Coef18 = (T_SCALAR)(m[1][0] * m[3][2] - m[3][0] * m[1][2]);
    T_SCALAR Coef19 = (T_SCALAR)(m[1][0] * m[2][2] - m[2][0] * m[1][2]);

    T_SCALAR Coef20 = (T_SCALAR)(m[2][0] * m[3][1] - m[3][0] * m[2][1]);
    T_SCALAR Coef22 = (T_SCALAR)(m[1][0] * m[3][1] - m[3][0] * m[1][1]);
    T_SCALAR Coef23 = (T_SCALAR)(m[1][0] * m[2][1] - m[2][0] * m[1][1]);

    _TMat44Helper<T_SCALAR> Fac0(Coef00, Coef00, Coef02, Coef03);
    _TMat44Helper<T_SCALAR> Fac1(Coef04, Coef04, Coef06, Coef07);
    _TMat44Helper<T_SCALAR> Fac2(Coef08, Coef08, Coef10, Coef11);
    _TMat44Helper<T_SCALAR> Fac3(Coef12, Coef12, Coef14, Coef15);
    _TMat44Helper<T_SCALAR> Fac4(Coef16, Coef16, Coef18, Coef19);
    _TMat44Helper<T_SCALAR> Fac5(Coef20, Coef20, Coef22, Coef23);

    _TMat44Helper<T_SCALAR> Vec0((T_SCALAR)m[1][0], (T_SCALAR)m[0][0], (T_SCALAR)m[0][0], (T_SCALAR)m[0][0]);
    _TMat44Helper<T_SCALAR> Vec1((T_SCALAR)m[1][1], (T_SCALAR)m[0][1], (T_SCALAR)m[0][1], (T_SCALAR)m[0][1]);
    _TMat44Helper<T_SCALAR> Vec2((T_SCALAR)m[1][2], (T_SCALAR)m[0][2], (T_SCALAR)m[0][2], (T_SCALAR)m[0][2]);
    _TMat44Helper<T_SCALAR> Vec3((T_SCALAR)m[1][3], (T_SCALAR)m[0][3], (T_SCALAR)m[0][3], (T_SCALAR)m[0][3]);

    _TMat44Helper<T_SCALAR> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2);
    _TMat44Helper<T_SCALAR> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4);
    _TMat44Helper<T_SCALAR> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5);
    _TMat44Helper<T_SCALAR> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5);

    _TMat44Helper<T_SCALAR> SignA((T_SCALAR)+1.0, (T_SCALAR)-1.0, (T_SCALAR)+1.0, (T_SCALAR)-1.0);
    _TMat44Helper<T_SCALAR> SignB((T_SCALAR)-1.0, (T_SCALAR)+1.0, (T_SCALAR)-1.0, (T_SCALAR)+1.0);
    std::array< _TMat44Helper<T_SCALAR>, 4 > Inverse{ Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB };

    _TMat44Helper<T_SCALAR> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]);

    _TMat44Helper<T_SCALAR> Dot0( Row0 );
    Dot0 = Dot0 * _TMat44Helper<T_SCALAR>( (T_SCALAR)m[0][0], (T_SCALAR)m[0][1], (T_SCALAR)m[0][2], (T_SCALAR)m[0][3] );
    T_SCALAR Dot1 = (Dot0[0] + Dot0[1]) + (Dot0[2] + Dot0[3]);

    T_SCALAR OneOverDeterminant = static_cast<T_SCALAR>(1.0) / Dot1;

    for ( int inx1 = 0; inx1 < 4; inx1 ++ )
    {
        for ( int inx2 = 0; inx2 < 4; inx2 ++ )
            res[inx1][inx2] = Inverse[inx1][inx2] * OneOverDeterminant;
    }
}

template< typename SCALAR_TYPE = float >
struct _TMat44Helper
{
    _TMat44Helper( void ) {}
    _TMat44Helper( SCALAR_TYPE x, SCALAR_TYPE y, SCALAR_TYPE z, SCALAR_TYPE w ) : m_v( { x, y, z, w } ){}
    _TMat44Helper( const std::array< SCALAR_TYPE, 4 > & v ) : m_v( v ) {}
    _TMat44Helper( const SCALAR_TYPE v[4] ) { std::memcpy( m_v.data(), v, 4 * sizeof( SCALAR_TYPE ) ); }
    _TMat44Helper( const _TMat44Helper &src ) : m_v( src.m_v ) {}

    _TMat44Helper & operator = ( const _TMat44Helper<SCALAR_TYPE> &src ) { m_v = src.m_v; return *this; }

    SCALAR_TYPE & operator[](int inx) { return m_v[inx]; }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator *( SCALAR_TYPE_OP s )
    {
        _TMat44Helper res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] * (SCALAR_TYPE)s;
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator +( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] + (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator -( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] - (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    template< typename SCALAR_TYPE_OP >
    _TMat44Helper<SCALAR_TYPE> operator *( const _TMat44Helper<SCALAR_TYPE_OP> &b )
    {
        _TMat44Helper<SCALAR_TYPE> res;
        for ( int inx = 0; inx < 4; inx ++ )
            res.m_v[inx] = m_v[inx] * (SCALAR_TYPE)b.m_v[inx];
        return res;
    }

    std::array< SCALAR_TYPE, 4 > m_v;
};

To map a point from viewport (screen) coordinates to the NDC you have to map the X-coordinate and the Y-coordinate to the range (-1.0, 1.0).
The Z-coordinate is more tricky, for this you have to access the depth buffer (The depth buffer can be rendered to a texture).
Read the depth at the XY position and convert it to the NDC:

X_ndc = X_screen * 2.0 / VP_sizeX - 1.0;
Y_ndc = Y_screen * 2.0 / VP_sizeY - 1.0;
Z_ndc = 2.0 * depth - 1.0;

In your case you have only a 2D geometry and an orthographic projection, so you do not have to care about the depth, because the Z coordinate is always 0.0.

If you transform a point by the projection matrix (or the inverse projection matrix) you will get a point in a homogeneous coordinate system. To transform a point from a homogeneous coordinates system to a cartesian coordinate system you have to devide its X, Y and Z coordinate by it weight.
A general transformation function of a point in a cartesian coordinate system with a homogeneous 4*4 matrix may look like this:

using TVec3 = std::array<float, 3>;
using TVec4 = std::array<float, 4>;
using TMat4 = std::array<TVec4, 4>;

TVec3 Transform( const TVec3 &vec, const TMat4 &mat )
{
    h {
        vec[0] * mat[0][0] + vec[1] * mat[1][0] + vec[2] * mat[2][0] + mat[3][0],
        vec[0] * mat[0][1] + vec[1] * mat[1][1] + vec[2] * mat[2][1] + mat[3][1],
        vec[0] * mat[0][2] + vec[1] * mat[1][2] + vec[2] * mat[2][2] + mat[3][2],
        vec[0] * mat[0][3] + vec[1] * mat[1][3] + vec[2] * mat[2][3] + mat[3][3]
    };
    if ( h[3] == 0.0 )
        return TVec3{ 1.0e99 }; // division by zero
    return TVec3{ h[0]/h[3], h[1]/h[3], h[2]/h[3] };
}

See the following WebGL example, where the color of the object, where the mouse hovers, is found by calculating back from the screen coordinates to the model coordinates.

<script type="text/javascript">

draw_vert =
"precision mediump float; \n" +
"attribute vec2 inPos; \n" +
"uniform   mat4 u_projectionMat44;" +
"uniform   mat4 u_modelViewMat44;" +
"void main()" +
"{" +
"    vec4 viewPos  = u_modelViewMat44 * vec4( inPos.xy, 0.0, 1.0 );" +
"    gl_Position   = u_projectionMat44 * viewPos;" +
"}";

draw_frag =
"precision mediump float; \n" +
"uniform vec3 u_color;" +
"void main()" +
"{" +
"    gl_FragColor = vec4( u_color.xyz, 1.0 );" +
"}";

glArrayType = typeof Float32Array !="undefined" ? Float32Array : ( typeof WebGLFloatArray != "undefined" ? WebGLFloatArray : Array );

function IdentityMat44() {
    var m = new glArrayType(16);
    m[0]  = 1; m[1]  = 0; m[2]  = 0; m[3]  = 0;
    m[4]  = 0; m[5]  = 1; m[6]  = 0; m[7]  = 0;
    m[8]  = 0; m[9]  = 0; m[10] = 1; m[11] = 0;
    m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1;
    return m;
};

function RotateAxis(matA, angRad, axis) {
    var aMap = [ [1, 2], [2, 0], [0, 1] ];
    var a0 = aMap[axis][0], a1 = aMap[axis][1];
    var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
    var matB = new glArrayType(16);
    for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i];
    for ( var i = 0; i < 3; ++ i ) {
        matB[a0*4+i] = matA[a0*4+i] * cosAng + matA[a1*4+i] * sinAng;
        matB[a1*4+i] = matA[a0*4+i] * -sinAng + matA[a1*4+i] * cosAng;
    }
    return matB;
}

function Translate( matA, trans ) {
    var matB = new glArrayType(16);
    for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i];
    for ( var i = 0; i < 3; ++ i )
        matB[12+i] = matA[i] * trans[0] + matA[4+i] * trans[1] + matA[8+i] * trans[2] + matA[12+i];
    return matB;
}

function Scale( matA, scale ) {
    var matB = new glArrayType(16);
    for ( var i = 0; i < 16; ++ i ) matB[i] = matA[i];
    for ( var a = 0; a < 4; ++ a )
        for ( var i = 0; i < 3; ++ i )
            matB[a*4+i] = matA[a*4+i] * scale[0];
    return matB;
}

Ortho = function( l, r, t, b, n, f ) {
    var fn  = f + n;
    var f_n = f - n;
    var m = IdentityMat44();
    m[0]  = 2/(r-l); m[1]  = 0;       m[2]  =  0;       m[3]  = 0;
    m[4]  = 0;       m[5]  = 2/(t-b); m[6]  =  0;       m[7]  = 0;
    m[8]  = 0;       m[9]  = 0;       m[10] = -2 / f_n; m[11] = -fn / f_n;
    m[12] = 0;       m[13] = 0;       m[14] = 0;        m[15] = 1;
    return m;
}

vec4_add = function( a, b ) { return [ a[0]+b[0], a[1]+b[1], a[2]+b[2], a[3]+b[3] ]; }
vec4_sub = function( a, b ) { return [ a[0]-b[0], a[1]-b[1], a[2]-b[2], a[3]-b[3] ]; }
vec4_mul = function( a, b ) { return [ a[0]*b[0], a[1]*b[1], a[2]*b[2], a[3]*b[3] ]; }
vec4_scale = function( a, s ) { return [ a[0]*s, a[1]*s, a[2]*s, a[3]*s ]; }

mat44_inverse = function( m ) {

    var Coef00 = m[2*4+2] * m[3*4+3] - m[3*4+2] * m[2*4+3];
    var Coef02 = m[1*4+2] * m[3*4+3] - m[3*4+2] * m[1*4+3];
    var Coef03 = m[1*4+2] * m[2*4+3] - m[2*4+2] * m[1*4+3];
    var Coef04 = m[2*4+1] * m[3*4+3] - m[3*4+1] * m[2*4+3];
    var Coef06 = m[1*4+1] * m[3*4+3] - m[3*4+1] * m[1*4+3];
    var Coef07 = m[1*4+1] * m[2*4+3] - m[2*4+1] * m[1*4+3];
    var Coef08 = m[2*4+1] * m[3*4+2] - m[3*4+1] * m[2*4+2];
    var Coef10 = m[1*4+1] * m[3*4+2] - m[3*4+1] * m[1*4+2];
    var Coef11 = m[1*4+1] * m[2*4+2] - m[2*4+1] * m[1*4+2];
    var Coef12 = m[2*4+0] * m[3*4+3] - m[3*4+0] * m[2*4+3];
    var Coef14 = m[1*4+0] * m[3*4+3] - m[3*4+0] * m[1*4+3];
    var Coef15 = m[1*4+0] * m[2*4+3] - m[2*4+0] * m[1*4+3];
    var Coef16 = m[2*4+0] * m[3*4+2] - m[3*4+0] * m[2*4+2];
    var Coef18 = m[1*4+0] * m[3*4+2] - m[3*4+0] * m[1*4+2];
    var Coef19 = m[1*4+0] * m[2*4+2] - m[2*4+0] * m[1*4+2];
    var Coef20 = m[2*4+0] * m[3*4+1] - m[3*4+0] * m[2*4+1];
    var Coef22 = m[1*4+0] * m[3*4+1] - m[3*4+0] * m[1*4+1];
    var Coef23 = m[1*4+0] * m[2*4+1] - m[2*4+0] * m[1*4+1];

    var Fac0 = [Coef00, Coef00, Coef02, Coef03];
    var Fac1 = [Coef04, Coef04, Coef06, Coef07];
    var Fac2 = [Coef08, Coef08, Coef10, Coef11];
    var Fac3 = [Coef12, Coef12, Coef14, Coef15];
    var Fac4 = [Coef16, Coef16, Coef18, Coef19];
    var Fac5 = [Coef20, Coef20, Coef22, Coef23];

    var Vec0 = [ m[1*4+0], m[0*4+0], m[0*4+0], m[0*4+0] ];
    var Vec1 = [ m[1*4+1], m[0*4+1], m[0*4+1], m[0*4+1] ];
    var Vec2 = [ m[1*4+2], m[0*4+2], m[0*4+2], m[0*4+2] ];
    var Vec3 = [ m[1*4+3], m[0*4+3], m[0*4+3], m[0*4+3] ];

    var Inv0 = vec4_add( vec4_sub( vec4_mul(Vec1, Fac0), vec4_mul(Vec2, Fac1) ), vec4_mul( Vec3, Fac2 ) );
    var Inv1 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac0), vec4_mul(Vec2, Fac3) ), vec4_mul( Vec3, Fac4 ) );
    var Inv2 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac1), vec4_mul(Vec1, Fac3) ), vec4_mul( Vec3, Fac5 ) );
    var Inv3 = vec4_add( vec4_sub( vec4_mul(Vec0, Fac2), vec4_mul(Vec1, Fac4) ), vec4_mul( Vec2, Fac5 ) );

    var SignA = [+1.0, -1.0, +1.0, -1.0];
    var SignB = [-1.0, +1.0, -1.0, +1.0];
    var Inverse = [ vec4_mul(Inv0, SignA), vec4_mul(Inv1, SignB), vec4_mul(Inv2, SignA), vec4_mul(Inv3, SignB) ];

    var Row0 = [Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0] ];

    var Dot0 = [Row0[0], Row0[1], Row0[2], Row0[3] ];
    Dot0 = vec4_mul( Dot0, [ m[0], m[1], m[2], m[3] ] );
    var Dot1 = (Dot0[0] + Dot0[1]) + (Dot0[2] + Dot0[3]);

    var OneOverDeterminant = 1 / Dot1;

    var res = IdentityMat44();
    for ( var inx1 = 0; inx1 < 4; inx1 ++ ) {
        for ( var inx2 = 0; inx2 < 4; inx2 ++ )
            res[inx1*4+inx2] = Inverse[inx1][inx2] * OneOverDeterminant;
    }
    return res;
}

Transform = function(vec, mat) {
    var h = [
        vec[0] * mat[0*4+0] + vec[1] * mat[1*4+0] + vec[2] * mat[2*4+0] + mat[3*4+0],
        vec[0] * mat[0*4+1] + vec[1] * mat[1*4+1] + vec[2] * mat[2*4+1] + mat[3*4+1],
        vec[0] * mat[0*4+2] + vec[1] * mat[1*4+2] + vec[2] * mat[2*4+2] + mat[3*4+2],
        vec[0] * mat[0*4+3] + vec[1] * mat[1*4+3] + vec[2] * mat[2*4+3] + mat[3*4+3] ]
    if ( h[3] == 0.0 )
        return [0, 0, 0]
    return [ h[0]/h[3], h[1]/h[3], h[2]/h[3] ];
}

// shader program object
var ShaderProgram = {};
ShaderProgram.Create = function( shaderList, uniformNames ) {
    var shaderObjs = [];
    for ( var i_sh = 0; i_sh < shaderList.length; ++ i_sh ) {
        var shderObj = this.CompileShader( shaderList[i_sh].source, shaderList[i_sh].stage );
        if ( shderObj == 0 )
          return 0;
        shaderObjs.push( shderObj );
    }
    var progObj = this.LinkProgram( shaderObjs )
    if ( progObj != 0 ) {
        progObj.unifomLocation = {};
        for ( var i_n = 0; i_n < uniformNames.length; ++ i_n ) {
            var name = uniformNames[i_n];
            progObj.unifomLocation[name] = gl.getUniformLocation( progObj, name );
        }
    }
    return progObj;
}
ShaderProgram.Use = function( progObj ) { gl.useProgram( progObj ); }
ShaderProgram.SetUniformInt = function( progObj, name, val ) { gl.uniform1i( progObj.unifomLocation[name], val ); }
ShaderProgram.SetUniform2f = function( progObj, name, arr ) { gl.uniform2fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.SetUniform3f = function( progObj, name, arr ) { gl.uniform3fv( progObj.unifomLocation[name], arr ); }
ShaderProgram.SetUniformMat44 = function( progObj, name, mat ) { gl.uniformMatrix4fv( progObj.unifomLocation[name], false, mat ); }
ShaderProgram.CompileShader = function( source, shaderStage ) {
    var shaderObj = gl.createShader( shaderStage );
    gl.shaderSource( shaderObj, source );
    gl.compileShader( shaderObj );
    var status = gl.getShaderParameter( shaderObj, gl.COMPILE_STATUS );
    if ( !status ) alert(gl.getShaderInfoLog(shaderObj));
    return status ? shaderObj : 0;
}
ShaderProgram.LinkProgram = function( shaderObjs ) {
    var prog = gl.createProgram();
    for ( var i_sh = 0; i_sh < shaderObjs.length; ++ i_sh )
        gl.attachShader( prog, shaderObjs[i_sh] );
    gl.linkProgram( prog );
    status = gl.getProgramParameter( prog, gl.LINK_STATUS );
    if ( !status ) alert("Could not initialise shaders");
    gl.useProgram( null );
    return status ? prog : 0;
}

function drawScene(){

    var canvas = document.getElementById( "camera-canvas" );
    var currentTime = Date.now();
    var deltaMS = currentTime - startTime;
    var aspect =  canvas.width / canvas.height;
    var matOrtho = Ortho( -aspect, aspect, 1, -1, -1, 1 );
    var matOrthoInv = mat44_inverse( matOrtho )

    gl.viewport( 0, 0, canvas.width, canvas.height );
    gl.enable( gl.DEPTH_TEST );
    gl.clearColor( 0.0, 0.0, 0.0, 1.0 );
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
    ShaderProgram.Use( progDraw );
    gl.enableVertexAttribArray( progDraw.inPos );
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
    gl.vertexAttribPointer( progDraw.inPos, 2, gl.FLOAT, false, 0, 0 );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
    ShaderProgram.SetUniformMat44( progDraw, "u_projectionMat44",  matOrtho );

    var col = [ [1.0,0.0,0.0], [1.0,1.0,0.0], [0.0,0.0,1.0] ];
    var invMat = []
    for ( var i = 0; i < 3; ++ i ) {
        var modelMat = Scale( IdentityMat44(), [ 0.3, 0.3, 0.3] );
        var angRad = CalcAng( currentTime, 20.0 ) + i * Math.PI * 2 / 3;
        var sinAng = Math.sin(angRad), cosAng = Math.cos(angRad);
        modelMat[12] = cosAng * 0.6;
        modelMat[13] = sinAng * 0.6;
        invMat.push( mat44_inverse( modelMat ) );

        ShaderProgram.SetUniformMat44( progDraw, "u_modelViewMat44", modelMat );
        ShaderProgram.SetUniform3f( progDraw, "u_color", col[i] );
        gl.drawElements( gl.TRIANGLES, bufObj.inx.len, gl.UNSIGNED_SHORT, 0 );
    }
    gl.disableVertexAttribArray( progDraw.pos );

    var newColor = "#000000";
    var colorMap = ["#ff0000", "#ffff00", "#0000ff" ];
    var pos = [-1, -1];
    if (mousePos[0] > 0 && mousePos[1] > 0 ) {
        var pos = [2.0 * mousePos[0] / canvas.width - 1.0, 1.0 - 2.0 * mousePos[1] / canvas.height];
        for ( var i = 0; i < 3; ++ i ) {
            var testVec = [ pos[0], pos[1], 0 ];
            testVec = Transform(testVec, matOrthoInv);
            testVec = Transform(testVec, invMat[i]);
            if (testVec[0] > -1.0 && testVec[0] < 1.0 && testVec[1] > -1.0 && testVec[1] < 1.0 ) {
                newColor = colorMap[i];
            }
        }
    }
    document.getElementById( "color" ).value = newColor;
    document.getElementById( "mouseX" ).innerHTML = pos[0];
    document.getElementById( "mouseY" ).innerHTML = pos[1];
}

var startTime;
function Fract( val ) {
    return val - Math.trunc( val );
}
function CalcAng( currentTime, intervall ) {
    return Fract( (currentTime - startTime) / (1000*intervall) ) * 2.0 * Math.PI;
}
function CalcMove( currentTime, intervall, range ) {
    var pos = self.Fract( (currentTime - startTime) / (1000*intervall) ) * 2.0
    var pos = pos < 1.0 ? pos : (2.0-pos)
    return range[0] + (range[1] - range[0]) * pos;
}

var mousePos = [-1, -1];
var gl;
var prog;
var bufObj = {};
function cameraStart() {

    var canvas = document.getElementById( "camera-canvas");
    gl = canvas.getContext( "experimental-webgl" );
    if ( !gl )
      return;

    progDraw = ShaderProgram.Create(
      [ { source : draw_vert, stage : gl.VERTEX_SHADER },
        { source : draw_frag, stage : gl.FRAGMENT_SHADER }
      ],
      [ "u_projectionMat44", "u_modelViewMat44", "u_color"] );
    progDraw.inPos = gl.getAttribLocation( progDraw, "inPos" );
    if ( prog == 0 )
        return;

    var pos = [ -1, -1, 1, -1, 1, 1, -1, 1 ];
    var inx = [ 0, 1, 2, 0, 2, 3 ];
    bufObj.pos = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, bufObj.pos );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( pos ), gl.STATIC_DRAW );
    bufObj.inx = gl.createBuffer();
    bufObj.inx.len = inx.length;
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, bufObj.inx );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( inx ), gl.STATIC_DRAW );

    startTime = Date.now();
    setInterval(drawScene, 50);
}

(function() {
    document.onmousemove = handleMouseMove;
    function handleMouseMove(event) {
        var dot, eventDoc, doc, body, pageX, pageY;

        event = event || window.event; // IE-ism

        if (event.pageX == null && event.clientX != null) {
            eventDoc = (event.target && event.target.ownerDocument) || document;
            doc = eventDoc.documentElement;
            body = eventDoc.body;

            event.pageX = event.clientX +
              (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
              (doc && doc.clientLeft || body && body.clientLeft || 0);
            event.pageY = event.clientY +
              (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
              (doc && doc.clientTop  || body && body.clientTop  || 0 );
        }

        var canvas = document.getElementById( "camera-canvas");
        var x = event.pageX - canvas.offsetLeft;
        var y = event.pageY - canvas.offsetTop;
        mousePos = [-1, -1];
        if ( x >= 0 && x < canvas.width && y >= 0 && y < canvas.height ) {
            mousePos = [x, y];
        }
    }
})();

</script>

<body onload="cameraStart();">
    <div style="margin-left: 260px;">
        <div style="float: right; width: 100%; background-color: #CCF;">
            <form name="inputs">
                <table>
                    <tr> <td> <input type="color" value="#000000" id="color" disabled></td> </tr>
                    <tr> <td> <span id="mouseX">0</span> </td> </tr>
                    <tr> <td> <span id="mouseY">0</span> </td> </tr>
                </table>
            </form>
        </div>
        <div style="float: right; width: 260px; margin-left: -260px;">
            <canvas id="camera-canvas" style="border: none;" width="256" height="256"></canvas>
        </div>
        <div style="clear: both;"></div>
    </div>
</body>


问:
About TextField with a small icon
I want to code a TextField component with icon.
So the behavior is as follow:

If the TextField  contains an empty string, I use "lens.png".

Otherwise, i use "cross.png".

using the JavaFX Scene Builder, I added a TextFiled and an ImageView in the stack pane.
My code is the following:

```<code>    @FXML
    private TextField textSearch;
    @FXML
    private ImageView imageView;
    final Image lensIcon = new Image("/issue/images/lens.png");
    final Image crossIcon = new Image("/issue/images/cross.png");

    //initialize () method
     textSearch.textProperty().addListener(obs -> {
            final String text = textSearch.getText();
            Image icon = (text==null || text.isEmpty()) ? lensIcon : crossIcon;
            imageView.setImage(icon);
            imageView.setMouseTransparent(icon == lensIcon);
        }
        );
        imageView.setOnMouseClicked(evt -> textSearch.setText(null));
</code>```

my issue is the following:
How to prevent writing caracters below the icon (ImageView). the following figure illustrate my issue.

答:
ControlsFX is an JavaFX API that supplies a ton of advanced controls UI that didn't come with JavaFX out of the box.

ControlsFX - http://fxexperience.com/controlsfx/

FontAwesomeFX supplies hundreds of icons (such as a cross in your case above)

FontAwesomeFX - https://bitbucket.org/Jerady/fontawesomefx/downloads/

Here is a demo solution to your problem after importing both these fantastic APIs

```<code>public class TextFields_Demo extends Application {

    private Parent createContent() {
        Pane root = new Pane();
        CustomTextField customTextField = new CustomTextField();
        FontAwesomeIconView icon = new FontAwesomeIconView(FontAwesomeIcon.CLOSE);
        customTextField.setRight(icon);
        root.getChildren().add(customTextField);
        return root;
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(createContent());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

Title: About TextField with a small icon

Body:
I want to code a TextField component with icon.
So the behavior is as follow:

If the TextField  contains an empty string, I use "lens.png".

Otherwise, i use "cross.png".

using the JavaFX Scene Builder, I added a TextFiled and an ImageView in the stack pane.
My code is the following:

    @FXML
    private TextField textSearch;
    @FXML
    private ImageView imageView;
    final Image lensIcon = new Image("/issue/images/lens.png");
    final Image crossIcon = new Image("/issue/images/cross.png");

    //initialize () method
     textSearch.textProperty().addListener(obs -> {
            final String text = textSearch.getText();
            Image icon = (text==null || text.isEmpty()) ? lensIcon : crossIcon;
            imageView.setImage(icon);
            imageView.setMouseTransparent(icon == lensIcon);
        }
        );
        imageView.setOnMouseClicked(evt -> textSearch.setText(null));

my issue is the following:
How to prevent writing caracters below the icon (ImageView). the following figure illustrate my issue.

Body:
ControlsFX is an JavaFX API that supplies a ton of advanced controls UI that didn't come with JavaFX out of the box.

ControlsFX - http://fxexperience.com/controlsfx/

FontAwesomeFX supplies hundreds of icons (such as a cross in your case above)

FontAwesomeFX - https://bitbucket.org/Jerady/fontawesomefx/downloads/

Here is a demo solution to your problem after importing both these fantastic APIs

public class TextFields_Demo extends Application {

    private Parent createContent() {
        Pane root = new Pane();
        CustomTextField customTextField = new CustomTextField();
        FontAwesomeIconView icon = new FontAwesomeIconView(FontAwesomeIcon.CLOSE);
        customTextField.setRight(icon);
        root.getChildren().add(customTextField);
        return root;
    }

    @Override
    public void start(Stage primaryStage) {
        Scene scene = new Scene(createContent());
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


问:
SQL dump of users tables Gmed emr
I am working for a company that uses Gmed EMR. Gmed lacks some features that my client requires and I have had to build an external secure web based application to fill in. Gmed runs on Microsoft SQL server. I have access to the server, but I've never used Microsoft SQL server before. How can I safety SQL dump the users tables? Should I even try this?</p>

答: It depends on the format you want them in.  It's pretty easy to export to a text file.  Open SQL Server Management Studio (the GUI), right-click the database you want to export from, then click Export Data.  It's a straightforward wizard that lets you select what tables or other objects you want to export, and in what format or to what file.

Title: SQL dump of users tables Gmed emr


问:
BLAS.axpy! slower than += in Julia
Consider the following 4 functions in Julia: They all pick/compute a random column of a matrix A and adds a constant times this column to a vector z.

The difference between slow1 and fast1 is how z is updated and likewise for slow2 and fast2.

The difference between the 1 functions and 2 functions is whether the matrix A is passed to the functions or computed on the fly.

The odd thing is that for the 1 functions, fast1 is faster (as I would expect when using BLAS instead of +=), but for the 2 functions slow1 is faster.
On this computer I get the following timings (for the second run of each function):

```<code>@time slow1(A, z, 10000);
0.172560 seconds (110.01 k allocations: 940.102 MB, 12.98% gc time)

@time fast1(A, z, 10000);
0.142748 seconds (50.07 k allocations: 313.577 MB, 4.56% gc time)

@time slow2(complex(float(x)), complex(float(y)), z, 10000);
2.265950 seconds (120.01 k allocations: 1.529 GB, 1.20% gc time)

@time fast2(complex(float(x)), complex(float(y)), z, 10000);
4.351953 seconds (60.01 k allocations: 939.410 MB, 0.43% gc time)
</code>```

Is there an explanation to this behaviour? And a way to make BLAS faster than +=?

```<code>M = 2^10
x = [-M:M-1;]

N = 2^9
y = [-N:N-1;]

A = cis( -2*pi*x*y' )
z = rand(2*M) + rand(2*M)*im

function slow1(A::Matrix{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:size(A,2);]

    for iter = 1:maxiter
        idx = rand(S)
        col = A[:,idx]
        a = rand()
        z += a*col
    end
end

function fast1(A::Matrix{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:size(A,2);]

    for iter = 1:maxiter
        idx = rand(S)
        col = A[:,idx]
        a = rand()
        BLAS.axpy!(a, col, z)
    end
end

function slow2(x::Vector{Complex{Float64}}, y::Vector{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:length(y);]

    for iter = 1:maxiter
        idx = rand(S)
        col = cis( -2*pi*x*y[idx] )
        a = rand()
        z += a*col
    end
end

function fast2(x::Vector{Complex{Float64}}, y::Vector{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:length(y);]

    for iter = 1:maxiter
        idx = rand(S)
        col = cis( -2*pi*x*y[idx] )
        a = rand()
        BLAS.axpy!(a, col, z)
    end
end
</code>```

Update:
Profiling slow2:

```<code>2260 task.jl; anonymous; line: 92
 2260 REPL.jl; eval_user_input; line: 63
  2260 profile.jl; anonymous; line: 16
   2175 /tmp/axpy.jl; slow2; line: 37
    10   arraymath.jl; .*; line: 118
    33   arraymath.jl; .*; line: 120
    5    arraymath.jl; .*; line: 125
    46   arraymath.jl; .*; line: 127
    3    complex.jl; cis; line: 286
    3    complex.jl; cis; line: 287
    2066 operators.jl; cis; line: 374
     72   complex.jl; cis; line: 286
     1914 complex.jl; cis; line: 287
   1    /tmp/axpy.jl; slow2; line: 38
   84   /tmp/axpy.jl; slow2; line: 39
    5  arraymath.jl; +; line: 96
    39 arraymath.jl; +; line: 98
    6  arraymath.jl; .*; line: 118
    34 arraymath.jl; .*; line: 120
</code>```

Profiling fast2:

```<code>4288 task.jl; anonymous; line: 92
 4288 REPL.jl; eval_user_input; line: 63
  4288 profile.jl; anonymous; line: 16
   1    /tmp/axpy.jl; fast2; line: 47
    1 random.jl; rand; line: 214
   3537 /tmp/axpy.jl; fast2; line: 48
    26   arraymath.jl; .*; line: 118
    44   arraymath.jl; .*; line: 120
    1    arraymath.jl; .*; line: 122
    4    arraymath.jl; .*; line: 125
    53   arraymath.jl; .*; line: 127
    7    complex.jl; cis; line: 286
    3399 operators.jl; cis; line: 374
     116  complex.jl; cis; line: 286
     3108 complex.jl; cis; line: 287
   2    /tmp/axpy.jl; fast2; line: 49
   748  /tmp/axpy.jl; fast2; line: 50
    748 linalg/blas.jl; axpy!; line: 231
</code>```

Oddly, the computing time of col differs even though the functions are identical up to this point.
But += is still relatively faster than axpy!.

答:
Some more info now that julia 0.6 is out. To multiply a vector by a scalar in place, there are at least four options. Following Tim's suggstions, I used BenchmarkTool's @btime macro. It turns out that loop fusion, the most julian way to write it, is on par with calling BLAS. That's something the julia developers can be proud of!

```<code>using BenchmarkTools
function bmark(N)
           a = zeros(N);
           @btime $a *= -1.;
           @btime $a .*= -1.;
           @btime LinAlg.BLAS.scal!($N, -1.0, $a, 1);
           @btime scale!($a, -1.);
       end
</code>```

And the results for 10^5 numbers.

```<code>julia> bmark(10^5);
  78.195 μs (2 allocations: 781.33 KiB)
  35.102 μs (0 allocations: 0 bytes)
  34.659 μs (0 allocations: 0 bytes)
  34.664 μs (0 allocations: 0 bytes)
</code>```

The profiling backtrace shows that scale! just calls blas in the background, so they should give the same best time.

Title: BLAS.axpy! slower than += in Julia

Body:
Consider the following 4 functions in Julia: They all pick/compute a random column of a matrix A and adds a constant times this column to a vector z.

The difference between slow1 and fast1 is how z is updated and likewise for slow2 and fast2.

The difference between the 1 functions and 2 functions is whether the matrix A is passed to the functions or computed on the fly.

The odd thing is that for the 1 functions, fast1 is faster (as I would expect when using BLAS instead of +=), but for the 2 functions slow1 is faster.
On this computer I get the following timings (for the second run of each function):

@time slow1(A, z, 10000);
0.172560 seconds (110.01 k allocations: 940.102 MB, 12.98% gc time)

@time fast1(A, z, 10000);
0.142748 seconds (50.07 k allocations: 313.577 MB, 4.56% gc time)

@time slow2(complex(float(x)), complex(float(y)), z, 10000);
2.265950 seconds (120.01 k allocations: 1.529 GB, 1.20% gc time)

@time fast2(complex(float(x)), complex(float(y)), z, 10000);
4.351953 seconds (60.01 k allocations: 939.410 MB, 0.43% gc time)

Is there an explanation to this behaviour? And a way to make BLAS faster than +=?

M = 2^10
x = [-M:M-1;]

N = 2^9
y = [-N:N-1;]

A = cis( -2*pi*x*y' )
z = rand(2*M) + rand(2*M)*im

function slow1(A::Matrix{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:size(A,2);]

    for iter = 1:maxiter
        idx = rand(S)
        col = A[:,idx]
        a = rand()
        z += a*col
    end
end

function fast1(A::Matrix{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:size(A,2);]

    for iter = 1:maxiter
        idx = rand(S)
        col = A[:,idx]
        a = rand()
        BLAS.axpy!(a, col, z)
    end
end

function slow2(x::Vector{Complex{Float64}}, y::Vector{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:length(y);]

    for iter = 1:maxiter
        idx = rand(S)
        col = cis( -2*pi*x*y[idx] )
        a = rand()
        z += a*col
    end
end

function fast2(x::Vector{Complex{Float64}}, y::Vector{Complex{Float64}}, z::Vector{Complex{Float64}}, maxiter::Int)
    S = [1:length(y);]

    for iter = 1:maxiter
        idx = rand(S)
        col = cis( -2*pi*x*y[idx] )
        a = rand()
        BLAS.axpy!(a, col, z)
    end
end

Update:
Profiling slow2:

2260 task.jl; anonymous; line: 92
 2260 REPL.jl; eval_user_input; line: 63
  2260 profile.jl; anonymous; line: 16
   2175 /tmp/axpy.jl; slow2; line: 37
    10   arraymath.jl; .*; line: 118
    33   arraymath.jl; .*; line: 120
    5    arraymath.jl; .*; line: 125
    46   arraymath.jl; .*; line: 127
    3    complex.jl; cis; line: 286
    3    complex.jl; cis; line: 287
    2066 operators.jl; cis; line: 374
     72   complex.jl; cis; line: 286
     1914 complex.jl; cis; line: 287
   1    /tmp/axpy.jl; slow2; line: 38
   84   /tmp/axpy.jl; slow2; line: 39
    5  arraymath.jl; +; line: 96
    39 arraymath.jl; +; line: 98
    6  arraymath.jl; .*; line: 118
    34 arraymath.jl; .*; line: 120

Profiling fast2:

4288 task.jl; anonymous; line: 92
 4288 REPL.jl; eval_user_input; line: 63
  4288 profile.jl; anonymous; line: 16
   1    /tmp/axpy.jl; fast2; line: 47
    1 random.jl; rand; line: 214
   3537 /tmp/axpy.jl; fast2; line: 48
    26   arraymath.jl; .*; line: 118
    44   arraymath.jl; .*; line: 120
    1    arraymath.jl; .*; line: 122
    4    arraymath.jl; .*; line: 125
    53   arraymath.jl; .*; line: 127
    7    complex.jl; cis; line: 286
    3399 operators.jl; cis; line: 374
     116  complex.jl; cis; line: 286
     3108 complex.jl; cis; line: 287
   2    /tmp/axpy.jl; fast2; line: 49
   748  /tmp/axpy.jl; fast2; line: 50
    748 linalg/blas.jl; axpy!; line: 231

Oddly, the computing time of col differs even though the functions are identical up to this point.
But += is still relatively faster than axpy!.

Body:
Some more info now that julia 0.6 is out. To multiply a vector by a scalar in place, there are at least four options. Following Tim's suggstions, I used BenchmarkTool's @btime macro. It turns out that loop fusion, the most julian way to write it, is on par with calling BLAS. That's something the julia developers can be proud of!

using BenchmarkTools
function bmark(N)
           a = zeros(N);
           @btime $a *= -1.;
           @btime $a .*= -1.;
           @btime LinAlg.BLAS.scal!($N, -1.0, $a, 1);
           @btime scale!($a, -1.);
       end

And the results for 10^5 numbers.

julia> bmark(10^5);
  78.195 μs (2 allocations: 781.33 KiB)
  35.102 μs (0 allocations: 0 bytes)
  34.659 μs (0 allocations: 0 bytes)
  34.664 μs (0 allocations: 0 bytes)

The profiling backtrace shows that scale! just calls blas in the background, so they should give the same best time.