问:
Electron - Resize Window from renderer process
I am working on an Electron app and as part of the interface I want to increase the size of the window once something has happened (I have bound this to a button for now) so I can display additional data. I have attempted to do this with the following code that is activated on a onclick=resize():

```<code>require('./renderer.js');

let remote = require('electron').remote;
function resize() {
    let win = remote.getCurrentWindow().setBounds({
        height: 1000
    });
}
</code>```

However, I am getting the following error in the window/browser console:

```<code>Uncaught Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at metaToValue (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:234:13)
    at Object.remoteMemberFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:118:18)
    at resize (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:41:45)
    at HTMLButtonElement.onclick (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:22:86)
</code>```

Any suggestions on how I can fix this?

答:
Definition of Rectangle object (which is the first argument of setBounds) is more strict than you expected. Since its properties don't have default values you have to define all of them.

For example:

```<code>remote.getCurrentWindow().setBounds({
    x: 1621,
    y: 611,
    width: 10,
    height: 1000
});
</code>```

Also, if you want to adjust only size you can use setSize of BrowserWindow

Body:
I am working on an Electron app and as part of the interface I want to increase the size of the window once something has happened (I have bound this to a button for now) so I can display additional data. I have attempted to do this with the following code that is activated on a onclick=resize():

require('./renderer.js');

let remote = require('electron').remote;
function resize() {
    let win = remote.getCurrentWindow().setBounds({
        height: 1000
    });
}

However, I am getting the following error in the window/browser console:

Uncaught Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
Error: Could not call remote function 'setBounds'. Check that the function signature is correct. Underlying error: Error processing argument at index 0, conversion failure from #<Object>
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at callFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:257:11)
    at EventEmitter.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\rpc-server.js:357:5)
    at emitMany (events.js:127:13)
    at EventEmitter.emit (events.js:204:7)
    at WebContents.<anonymous> (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\browser\api\web-contents.js:256:13)
    at emitTwo (events.js:106:13)
    at WebContents.emit (events.js:194:7)
    at metaToValue (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:234:13)
    at Object.remoteMemberFunction (C:\Users\Thomas\AppData\Roaming\npm\node_modules\electron\dist\resources\electron.asar\renderer\api\remote.js:118:18)
    at resize (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:41:45)
    at HTMLButtonElement.onclick (file:///D:/Documents/Development/Projects/ShortenMeURL/V1/index.html:22:86)

Any suggestions on how I can fix this?

Body:
Definition of Rectangle object (which is the first argument of setBounds) is more strict than you expected. Since its properties don't have default values you have to define all of them.

For example:

remote.getCurrentWindow().setBounds({
    x: 1621,
    y: 611,
    width: 10,
    height: 1000
});

Also, if you want to adjust only size you can use setSize of BrowserWindow


来源: stackexchange

问:
execute powershell commands from ruby
I was trying to execute a powershell command from ruby code.
Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'" |Select-Object -Property version

It gives me the version of the product perefectly. But the same thing when i try to execute from ruby like(entire command in backticks) :
find = powershell.exe  Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name=''"|Select-Object -Property version

The command breaks, it cant interpret the quotes, pipes etc in ruby. I tried to escape those quotes but it still it breaks. I dont know how to escape that pipe as well.
Kindly help me here or refer me to something relevant. Many thanks.

答:
I have tested this now:

```<code>require 'base64'
cmd = %{Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'"|Select-Object -Property version}
encoded_cmd = Base64.strict_encode64(cmd.encode('utf-16le'))
find = `powershell.exe -encodedCommand #{encoded_cmd}`
</code>```

Powershell expects UTF-16LE-encoded strings, so you have to convert from Ruby's encoding (UTF-8) before the base64 conversion.

Alternatively you could try using shellescape from shellwords to escape the command so the shell interprets it as a single string.

Another alternative is to use powershell.exe -Command - with popen3. That will let you write your commands and read their results using a file stream.

ContentLicense: CC BY-SA 3.0

Title: execute powershell commands from ruby

Body:
I have tested this now:

require 'base64'
cmd = %{Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='Qlik Sense Client'"|Select-Object -Property version}
encoded_cmd = Base64.strict_encode64(cmd.encode('utf-16le'))
find = `powershell.exe -encodedCommand #{encoded_cmd}`

Powershell expects UTF-16LE-encoded strings, so you have to convert from Ruby's encoding (UTF-8) before the base64 conversion.

Alternatively you could try using shellescape from shellwords to escape the command so the shell interprets it as a single string.

Another alternative is to use powershell.exe -Command - with popen3. That will let you write your commands and read their results using a file stream.


问:
transform Text file to csv with new columns
I have a text file with a list of names and numbers.
Example of text file format:

james 500

Katrina 200

kyle 600 etc

I want to create a csv file from this text file with 2 columns, Names and count where name holds names and count hold the numbers. Below is what ive tried so far,

```<code>import csv

class csvTest(object):
    def __init__(self):
        self.convertToCSV()

    def convertToCSV(self):
        names = []
        with open('BoysNames.txt', 'r') as b_names, open('popular_names.csv', 'w') as out_file, open('GirlsNames.txt', 'r') as g_names:

            for b_lines in b_names:
                b_lines = b_lines.strip().split('\t')
                names.append(b_lines)
            #for g_lines in g_names:
             #   g_lines = g_lines.split('\t')
              #  names.append(g_lines)

            writer = csv.writer(out_file)
            writer.writerow(('FirstName', 'Count'))
            writer.writerows(names)

if __name__ == '__main__':
    csvTest()
</code>```

I'm not able to split the columns properly it all goes into names. Please help.

答:
How about this solution with pandas. First let's create some sample data:

```<code>import io

# first let's recreate your file
data1 = '''\
james 500
kyle 600'''

data2 ='''\
Katrina 200'''

file1 = io.StringIO(data1)
file2 = io.StringIO(data2)
</code>```

Now we do the real operation:

```<code>import pandas as pd

#Let's put them in a list
#This list should in reality be changed to ["path/to/file1", path/to/file2 ...
files = [file1,file2]

# now let's read this data with pandas to a dataframe
names = ["FirstName","Count"]
df = pd.concat(pd.read_csv(f, sep=" ", header=None, names=names) for f in files)

# and output to csv:
df.to_csv("output.csv", sep=",", index=False)
</code>```

Result 'output.csv':

```<code>FirstName,Count
james,500
kyle,600
Katrina,200
</code>```

Body:
I have a text file with a list of names and numbers.
Example of text file format:

james 500

Katrina 200

kyle 600 etc

I want to create a csv file from this text file with 2 columns, Names and count where name holds names and count hold the numbers. Below is what ive tried so far,

import csv

class csvTest(object):
    def __init__(self):
        self.convertToCSV()

    def convertToCSV(self):
        names = []
        with open('BoysNames.txt', 'r') as b_names, open('popular_names.csv', 'w') as out_file, open('GirlsNames.txt', 'r') as g_names:

            for b_lines in b_names:
                b_lines = b_lines.strip().split('\t')
                names.append(b_lines)
            #for g_lines in g_names:
             #   g_lines = g_lines.split('\t')
              #  names.append(g_lines)

            writer = csv.writer(out_file)
            writer.writerow(('FirstName', 'Count'))
            writer.writerows(names)

if __name__ == '__main__':
    csvTest()

I'm not able to split the columns properly it all goes into names. Please help.

Body:
How about this solution with pandas. First let's create some sample data:

import io

# first let's recreate your file
data1 = '''\
james 500
kyle 600'''

data2 ='''\
Katrina 200'''

file1 = io.StringIO(data1)
file2 = io.StringIO(data2)

Now we do the real operation:

import pandas as pd

#Let's put them in a list
#This list should in reality be changed to ["path/to/file1", path/to/file2 ...
files = [file1,file2]

# now let's read this data with pandas to a dataframe
names = ["FirstName","Count"]
df = pd.concat(pd.read_csv(f, sep=" ", header=None, names=names) for f in files)

# and output to csv:
df.to_csv("output.csv", sep=",", index=False)

Result 'output.csv':

FirstName,Count
james,500
kyle,600
Katrina,200


问:
NOTIFYICONDATA icon notification c++
I have an application which runs as a service, as well as a secondary application which monitors the service. The monitoring application exists in the system tray using NOTIFYICONDATA, which works fine.

What I am currently trying to do, is when the application notices that the services has stopped, I want to display a notification (similar to as if the battery is running low on a laptop). I am basing my code off of this article. The function I have to do this is as follows:

```<code>void CALLBACK checkit( HWND hwnd, UINT umsg, UINT timerid, DWORD dwtime ) {
    if ( isServiceRunning() ) {
        if ( nidApp.dwInfoFlags != NIIF_NONE ) {
            Log( "dwInfoFlags != NIFF_NONE" );
            nidApp.dwInfoFlags = NIIF_NONE;
            strcpy_s( nidApp.szInfoTitle, sizeof( nidApp.szInfoTitle ), "" );
            strcpy_s( nidApp.szInfo, sizeof( nidApp.szInfoTitle ), "" );
            Log( "%d", Shell_NotifyIcon( NIM_MODIFY, &nidApp ) );
        }
    } else {
        if ( nidApp.dwInfoFlags != NIIF_WARNING ) {
            Log( "dwInfoFlags != NIIF_WARNING" );
            nidApp.dwInfoFlags = NIIF_WARNING;
            strcpy_s( nidApp.szInfoTitle, sizeof( nidApp.szInfoTitle ), "Service Stopped" );
            strcpy_s( nidApp.szInfo, sizeof( nidApp.szInfo ), "The " PROGRAM_NAME " service has been stopped. Any runs in progress have been terminated." );
            nidApp.uTimeout = 10000;
            Log( "%d", Shell_NotifyIcon( NIM_MODIFY, &nidApp ) );
        }
    }
}
</code>```

This function is called every five seconds. Using the logs, I am able to see that the dwInfoFlags is set properly, and Shell_NotifyIcon returns TRUE, however, no notification is displayed. I'm sure I must be missing something, but I cannot figure out what it is.

nidApp is defined at the top of the CPP file as NOTIFYICONDATA nidApp; as is setup as follows:

```<code>hMainIcon = LoadIcon( hInstance, (LPCTSTR)MAKEINTRESOURCE( IDI_ICON1 ) );
nidApp.cbSize = sizeof( NOTIFYICONDATA ); // sizeof the struct in bytes
nidApp.hWnd = (HWND)hWnd;            //handle of the window which will process this app. messages
nidApp.uID = IDI_ICON1;       //ID of the icon that willl appear in the system tray
nidApp.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_GUID | NIF_SHOWTIP; //ORing of all the flags
nidApp.hIcon = hMainIcon; // handle of the Icon to be displayed, obtained from LoadIcon
nidApp.uCallbackMessage = WM_USER_SHELLICON;
nidApp.uVersion = NOTIFYICON_VERSION_4;
nidApp.guidItem = myGUID;
strcpy_s( nidApp.szTip, sizeof( nidApp.szTip ), PROGRAM_NAME " Service Controller" );
Shell_NotifyIcon( NIM_ADD, &nidApp );
Shell_NotifyIcon( NIM_SETVERSION, &nidApp );
</code>```

答: You should set nidApp.uFlags to NIF_INFO to display notification. Right now you are calling Shell_NotifyIcon with the same flags as were used to create notification icon.

Title: NOTIFYICONDATA icon notification c++

Body:
I have an application which runs as a service, as well as a secondary application which monitors the service. The monitoring application exists in the system tray using NOTIFYICONDATA, which works fine.

What I am currently trying to do, is when the application notices that the services has stopped, I want to display a notification (similar to as if the battery is running low on a laptop). I am basing my code off of this article. The function I have to do this is as follows:

void CALLBACK checkit( HWND hwnd, UINT umsg, UINT timerid, DWORD dwtime ) {
    if ( isServiceRunning() ) {
        if ( nidApp.dwInfoFlags != NIIF_NONE ) {
            Log( "dwInfoFlags != NIFF_NONE" );
            nidApp.dwInfoFlags = NIIF_NONE;
            strcpy_s( nidApp.szInfoTitle, sizeof( nidApp.szInfoTitle ), "" );
            strcpy_s( nidApp.szInfo, sizeof( nidApp.szInfoTitle ), "" );
            Log( "%d", Shell_NotifyIcon( NIM_MODIFY, &nidApp ) );
        }
    } else {
        if ( nidApp.dwInfoFlags != NIIF_WARNING ) {
            Log( "dwInfoFlags != NIIF_WARNING" );
            nidApp.dwInfoFlags = NIIF_WARNING;
            strcpy_s( nidApp.szInfoTitle, sizeof( nidApp.szInfoTitle ), "Service Stopped" );
            strcpy_s( nidApp.szInfo, sizeof( nidApp.szInfo ), "The " PROGRAM_NAME " service has been stopped. Any runs in progress have been terminated." );
            nidApp.uTimeout = 10000;
            Log( "%d", Shell_NotifyIcon( NIM_MODIFY, &nidApp ) );
        }
    }
}

This function is called every five seconds. Using the logs, I am able to see that the dwInfoFlags is set properly, and Shell_NotifyIcon returns TRUE, however, no notification is displayed. I'm sure I must be missing something, but I cannot figure out what it is.

nidApp is defined at the top of the CPP file as NOTIFYICONDATA nidApp; as is setup as follows:

hMainIcon = LoadIcon( hInstance, (LPCTSTR)MAKEINTRESOURCE( IDI_ICON1 ) );
nidApp.cbSize = sizeof( NOTIFYICONDATA ); // sizeof the struct in bytes
nidApp.hWnd = (HWND)hWnd;            //handle of the window which will process this app. messages
nidApp.uID = IDI_ICON1;       //ID of the icon that willl appear in the system tray
nidApp.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_GUID | NIF_SHOWTIP; //ORing of all the flags
nidApp.hIcon = hMainIcon; // handle of the Icon to be displayed, obtained from LoadIcon
nidApp.uCallbackMessage = WM_USER_SHELLICON;
nidApp.uVersion = NOTIFYICON_VERSION_4;
nidApp.guidItem = myGUID;
strcpy_s( nidApp.szTip, sizeof( nidApp.szTip ), PROGRAM_NAME " Service Controller" );
Shell_NotifyIcon( NIM_ADD, &nidApp );
Shell_NotifyIcon( NIM_SETVERSION, &nidApp );


问:
How to use preprocessor directives inside a MENU in MFC .rc file?
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

```<code>IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END
</code>```

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.

答:
You can put your code in separate rc files and include them using the Compile-Time Directives field of the Set includes dialog. See Using Multiple Resource Files in the Same Project

If the resources are not changed frequently you can move them to the .rc2 file which is not modified by the Resource editor. And you can use pre-processor freely.

The other option is to create multiple .rc files (for example copy the original .rc file and remove the rest) and include them conditionally in the "Resource Includes.. > Compile-time directives" section which the Resource editors stores in the .rc file and repeats at the end of the .rc file as-is.

For example:

Create two .rc files like

ResourcesDebug.rc:

```<code>....

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
    MENUITEM "&About TEST...",               ID_APP_ABOUT
    END
END

....
</code>```

ResourcesRelease.rc:

```<code>....

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
    END
END

....
</code>```

You can add them to your repo, but need not to add them to the project. But if you add them to your project you have to exclude them from the compilation.

Compile-time directives (Resource view > Right click the .rc):

```<code>#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES

#include "res\TestApp.rc2"  // non-Microsoft Visual C++ edited resources

#ifdef TEST_APP
    #include ResourcesDebug.rc
#else
    #include ResourcesRelease.rc
#endif

....
</code>```

Some more links:

Files Affected by Resource Editing

How to: Include Resources at Compile Time

Body:
I want to be able to dynamically change code in my resource file depending on which version of my app is being ran. For example, I have an about menu. I would like the about menuitem to have a different description based on a preprocessor directive. The issue I have is I am able to add the code in. But when I edit the resource file and save it, the .aps file overwrites my preprocessor directives. How can I get around this? The code below is an example of what I would like to have in my resource script.

IDR_EXAMPLE_MENU MENU
BEGIN

/*

Other Menu items

*/

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
#ifdef TEST_APP
    MENUITEM "&About TEST...",               ID_APP_ABOUT
#else
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
#endif
    END
END

If I am running the TEST version I would like it to display "About TEST" in the menuitem and if it the RELEASE version I would like it to display "About RELEASE"
How can I add code like this to my resource file without having the .aps file overwrite the preprocessor directives when saving the .rc file?

Edit: This explains how files are affected by resource editing.

Body:
You can put your code in separate rc files and include them using the Compile-Time Directives field of the Set includes dialog. See Using Multiple Resource Files in the Same Project

If the resources are not changed frequently you can move them to the .rc2 file which is not modified by the Resource editor. And you can use pre-processor freely.

The other option is to create multiple .rc files (for example copy the original .rc file and remove the rest) and include them conditionally in the "Resource Includes.. > Compile-time directives" section which the Resource editors stores in the .rc file and repeats at the end of the .rc file as-is.

For example:

Create two .rc files like

ResourcesDebug.rc:

....

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
    MENUITEM "&About TEST...",               ID_APP_ABOUT
    END
END

....

ResourcesRelease.rc:

....

POPUP "&Help"
BEGIN
    MENUITEM "&Help Topics",                ID_HELP_FINDER
    MENUITEM SEPARATOR
    MENUITEM "&About RELEASE...",             ID_APP_ABOUT
    END
END

....

You can add them to your repo, but need not to add them to the project. But if you add them to your project you have to exclude them from the compilation.

Compile-time directives (Resource view > Right click the .rc):

#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES

#include "res\TestApp.rc2"  // non-Microsoft Visual C++ edited resources

#ifdef TEST_APP
    #include ResourcesDebug.rc
#else
    #include ResourcesRelease.rc
#endif

....

Some more links:

Files Affected by Resource Editing

How to: Include Resources at Compile Time


问:
Compute median of column in SQL common table expression
In MSSQL2008, I am trying to compute the median of a column of numbers from a common table expression using the classic median query as follows:

```<code>WITH cte AS
(
   SELECT number
   FROM table
)

SELECT cte.*,
(SELECT
  (SELECT (
    (SELECT TOP 1 cte.number
     FROM
     (SELECT TOP 50 PERCENT cte.number
      FROM cte
      ORDER BY cte.number) AS medianSubquery1
    ORDER BY cte.number DESC)
    +
  (SELECT TOP 1 cte.number
   FROM
    (SELECT TOP 50 PERCENT cte.number
     FROM cte
     ORDER BY cte.number DESC) AS medianSubquery2
   ORDER BY cte.number ASC) ) / 2)) AS median

FROM cte
ORDER BY cte.number
</code>```

The result set that I get is the following:

```<code>NUMBER    MEDIAN
x1        x1
x1        x1
x1        x1
x2        x2
x3        x3
</code>```

In other words, the "median" column is the same as the "number" column when I would expect the median column to be "x1" all the way down.  I use a similar expression to compute the mode and it works fine over the same common table expression.

答:
This is not an entirely new answer as it mostly expands on Mark Byer's answer, but there are a couple of options for simplifying the query even further.

The first thing is to really make use of CTE's.  Not only can you have multiple CTE's, but they can refer to each other.  With this in mind, we can create an additional CTE to compute the median based on the results of the first.  This encapsulates the median computation and leaves the actual SELECT to do only what it needs to do.  Note that the ROW_NUMBER() had to be moved into the first CTE.

```<code>;WITH cte AS
(
   SELECT number, ROW_NUMBER() OVER(ORDER BY number) AS rn
   FROM table1
),
med AS
(
    SELECT AVG(number) AS median
    FROM cte
    WHERE cte.rn = ((SELECT COUNT(*) FROM cte) + 1) / 2
    OR cte.rn = ((SELECT COUNT(*) FROM cte) + 2) / 2
)
SELECT cte.number, med.median
FROM cte
CROSS JOIN med
</code>```

And to further reduce complexity, you "could" use a custom CLR Aggregate to handle the Median (such as the one provided in the free SQL# library at http://www.SQLsharp.com/ [which I am the author of]).

```<code>;WITH cte AS
(
   SELECT number
   FROM table1
),
med AS
(
    SELECT  SQL#.Agg_Median(cte.number) AS median
    FROM    cte
)
SELECT cte.number, med.median
FROM cte
CROSS JOIN med
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In MSSQL2008, I am trying to compute the median of a column of numbers from a common table expression using the classic median query as follows:

WITH cte AS
(
   SELECT number
   FROM table
)

SELECT cte.*,
(SELECT
  (SELECT (
    (SELECT TOP 1 cte.number
     FROM
     (SELECT TOP 50 PERCENT cte.number
      FROM cte
      ORDER BY cte.number) AS medianSubquery1
    ORDER BY cte.number DESC)
    +
  (SELECT TOP 1 cte.number
   FROM
    (SELECT TOP 50 PERCENT cte.number
     FROM cte
     ORDER BY cte.number DESC) AS medianSubquery2
   ORDER BY cte.number ASC) ) / 2)) AS median

FROM cte
ORDER BY cte.number

The result set that I get is the following:

NUMBER    MEDIAN
x1        x1
x1        x1
x1        x1
x2        x2
x3        x3

In other words, the "median" column is the same as the "number" column when I would expect the median column to be "x1" all the way down.  I use a similar expression to compute the mode and it works fine over the same common table expression.

Body:
This is not an entirely new answer as it mostly expands on Mark Byer's answer, but there are a couple of options for simplifying the query even further.

The first thing is to really make use of CTE's.  Not only can you have multiple CTE's, but they can refer to each other.  With this in mind, we can create an additional CTE to compute the median based on the results of the first.  This encapsulates the median computation and leaves the actual SELECT to do only what it needs to do.  Note that the ROW_NUMBER() had to be moved into the first CTE.

;WITH cte AS
(
   SELECT number, ROW_NUMBER() OVER(ORDER BY number) AS rn
   FROM table1
),
med AS
(
    SELECT AVG(number) AS median
    FROM cte
    WHERE cte.rn = ((SELECT COUNT(*) FROM cte) + 1) / 2
    OR cte.rn = ((SELECT COUNT(*) FROM cte) + 2) / 2
)
SELECT cte.number, med.median
FROM cte
CROSS JOIN med

And to further reduce complexity, you "could" use a custom CLR Aggregate to handle the Median (such as the one provided in the free SQL# library at http://www.SQLsharp.com/ [which I am the author of]).

;WITH cte AS
(
   SELECT number
   FROM table1
),
med AS
(
    SELECT  SQL#.Agg_Median(cte.number) AS median
    FROM    cte
)
SELECT cte.number, med.median
FROM cte
CROSS JOIN med


问:
VPN certificates always state "This certificate has an invalid digital signature." on one machine
While attempting to connect to the Windows Azure Virtual Network (and knowing all keys are installed), I always get the error message:

```<code>A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
 (Error 0x800b0109)
</code>```

When I investigate my certificates, I see that my FunnelFire and Root Agency certificates are both station that "This certificate has an invalid digital signature".

I have several other machines setup with these keys and with the same VPN client install, and they all work fine. I am using windows 8.1 on each machine.

答:
Although this question was asked over 3 years ago, I would like to provide an answer for others that stumble across this same challenge.

Overview:
You'll need to import the .cer certificate into the local computer\Trusted Root Certification Authorities.

Steps:

Open the Azure VPN .exe file (I use 7-Zip)

Extract the .cer file

Import the .cer file into the local computer\Trusted Root Certification Authorities

Connect to the Azure VPN

Body:
While attempting to connect to the Windows Azure Virtual Network (and knowing all keys are installed), I always get the error message:

A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
 (Error 0x800b0109)

When I investigate my certificates, I see that my FunnelFire and Root Agency certificates are both station that "This certificate has an invalid digital signature".

I have several other machines setup with these keys and with the same VPN client install, and they all work fine. I am using windows 8.1 on each machine.


问:
Show a "title" in the cmd.exe title-bar from a batch file?
According to the Microsoft Documentation, this is the syntax of the Start command:

```<code>start ["<Title>"] [/d <Path>] [/i] [{/min | /max}] [{/separate | /shared}] [{/low | /normal | /high | /realtime | /abovenormal | belownormal}] [/affinity <HexAffinity>] [/wait] [/b {<Command> | <Program>} [<Parameters>]]
</code>```

So I created a batch file "test.bat" with this content:

```<code>START "My test" /WAIT notepad
</code>```

...to supposedly have the cmd.exe console window showing the title "My test" in the title-bar.

However, when executing this .BAT file, the title "My test" is not displayed in the title bar of the console window:

So I tried this command in the .BAT file:

```<code>START title "My test" /WAIT notepad
</code>```

However, when executing this .BAT file, the whole command line was displayed in the title-bar of the console window:

...and notepad was not started.

So how can I display only the "title" in the title-bar of the console window and have the command executed?

OS: Windows 7 x64 SP1

答:
The title command changes inside the window, just put title command in the actual file, or if you want some kind of launcher (I don't know why you would want this) then have a bat using call to call the other bat (The one that would have the title command inside it)

EDIT: I found the answer, if you're starting a program (with the command start "foo\bar\some spaces\path\yourbat.bat) then the start command automatically interperets foo\bar\some spaces\path\yourbat.bat to be the title, too, but if you call start "title" "foo\bar\some spaces\path\yourbat.bat" then it will run your file AND interpret the first quotation marks to be the title, and the second the path

Body:
According to the Microsoft Documentation, this is the syntax of the Start command:

start ["<Title>"] [/d <Path>] [/i] [{/min | /max}] [{/separate | /shared}] [{/low | /normal | /high | /realtime | /abovenormal | belownormal}] [/affinity <HexAffinity>] [/wait] [/b {<Command> | <Program>} [<Parameters>]]

So I created a batch file "test.bat" with this content:

START "My test" /WAIT notepad

...to supposedly have the cmd.exe console window showing the title "My test" in the title-bar.

However, when executing this .BAT file, the title "My test" is not displayed in the title bar of the console window:

So I tried this command in the .BAT file:

START title "My test" /WAIT notepad

However, when executing this .BAT file, the whole command line was displayed in the title-bar of the console window:

...and notepad was not started.

So how can I display only the "title" in the title-bar of the console window and have the command executed?

OS: Windows 7 x64 SP1


问:
how to getting numbers from calculator text area(without operators)?
in my previous question, i got no useful answer, i hope i get something :)

here's my code:

```<code>import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Calculator extends JFrame
{
  public Calculator()
{
    JFrame jf = new JFrame("Calculator");
    jf.setLocation(500,200);
    jf.setSize(600,400);
    jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

    /*=======================Add panel==============================
    ================================================================*/
    JPanel jp = new JPanel();
    jp.setLayout(null);
    jp.setBackground(Color.cyan);
    jf.add(jp);

    /*========================Add Textarea========================
    ================================================================*/

    JTextArea jta = new JTextArea("");
    jta.setBounds(100,25,290,50);
    jp.add(jta);

    /*========================Creating Font========================
    ===============================================================*/

    Font labels = new Font("Lucida Console",Font.PLAIN, 20);
    Font nums = new Font("Lucida Console",Font.PLAIN, 9);

    /*========================Add Labels============================
    ================================================================*/

    /*  for H align: ,SwingConstants.CENTER */
    JLabel jlbl = new JLabel("=");
    jlbl.setFont(labels);   //  MAKING FONT BIGGER
    jlbl.setBounds(400,30,50,40);
    jp.add(jlbl);

    JLabel jlbl_result = new JLabel();
    String temp = jta.getText();
    jlbl_result.setText(temp);

    /*=========================Adding button============================
    ====================================================================*/

    JButton jbtn1 = new JButton("1");
    jbtn1.setBounds(120,100,50,40);
    jbtn1.setBackground(Color.green);
    jp.add(jbtn1);

    JButton jbtn2 = new JButton("2");
    jbtn2.setBounds(180,100,50,40);
    jbtn2.setBackground(Color.green);
    jp.add(jbtn2);

    JButton jbtn3 = new JButton("3");
    jbtn3.setBounds(240,100,50,40);
    jbtn3.setBackground(Color.green);
    jp.add(jbtn3);

    JButton jbtn4 = new JButton("4");
    jbtn4.setBounds(120,155,50,40);
    jbtn4.setBackground(Color.green);
    jp.add(jbtn4);

    JButton jbtn5 = new JButton("5");
    jbtn5.setBounds(180,155,50,40);
    jbtn5.setBackground(Color.green);
    jp.add(jbtn5);

    JButton jbtn6 = new JButton("6");
    jbtn6.setBounds(240,155,50,40);
    jbtn6.setBackground(Color.green);
    jp.add(jbtn6);

    JButton jbtn7 = new JButton("7");
    jbtn7.setBounds(120,210,50,40);
    jbtn7.setBackground(Color.green);
    jp.add(jbtn7);

    JButton jbtn8 = new JButton("8");
    jbtn8.setBounds(180,210,50,40);
    jbtn8.setBackground(Color.green);
    jp.add(jbtn8);

    JButton jbtn9 = new JButton("9");
    jbtn9.setBounds(240,210,50,40);
    jbtn9.setBackground(Color.green);
    jp.add(jbtn9);

    JButton jbtn0 = new JButton("0");
    jbtn0.setBounds(180,265,50,40);
    jbtn0.setBackground(Color.green);
    jp.add(jbtn0);

    JButton jbtn_sum = new JButton("+");
    jbtn_sum.setBounds(380,100,40,40);
    jbtn_sum.setFont(nums);
    jbtn_sum.setBackground(Color.gray);
    jp.add(jbtn_sum);

    JButton jbtn_sub = new JButton("-");
    jbtn_sub.setBounds(380,100,40,40);
    jbtn_sub.setFont(nums);
    jbtn_sub.setBackground(Color.gray);
    jp.add(jbtn_sub);

    JButton jbtn_equal = new JButton("-");
    jbtn_equal.setBounds(380,155,40,40);
    jbtn_equal.setFont(nums);
    jp.add(jbtn_equal);

    jf.setVisible(true);

            jbtn1.addActionListener(e->jta.append("1"));
            jbtn2.addActionListener(e->jta.append("2"));
            jbtn3.addActionListener(e->jta.append("3"));
            jbtn4.addActionListener(e->jta.append("4"));
            jbtn5.addActionListener(e->jta.append("5"));
            jbtn6.addActionListener(e->jta.append("6"));
            jbtn7.addActionListener(e->jta.append("7"));
            jbtn8.addActionListener(e->jta.append("8"));
            jbtn9.addActionListener(e->jta.append("9"));
            jbtn0.addActionListener(e->jta.append("0"));
            jbtn_equal.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt2)
                {

                }
            });
            //jbtn_sub.addActionListener(e->jta.append("-"));
            jbtn_sum.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {

                }
            });
}
public static void main(String...ser)
{
    new Calculator();
}
}
</code>```

i know! there is a lot of code, i want to put number that i entered to JTextArea inside variable, how to get numbers(just numbers without operators )
and assign it to variable?

and... how many variable is required to do it?(in case if i have more than 5 variable)

and a lot of questions..., i cant write it down here

thank you for help(forgive me of my bad grammar)

答:
You download the text from JTextArea and save it to the new String. If you download only numbers, just use the parseInt () function to convert String to int.
If you enter an action with operators eg 2 + 2 then you can use patterns to capture numbers, you can use the split () function to separate 2 numbers in the String with some sign, the possibilities are many;)

If this is not what you had in mind, compose the question and I will try to help.

Body:
in my previous question, i got no useful answer, i hope i get something :)

here's my code:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

class Calculator extends JFrame
{
  public Calculator()
{
    JFrame jf = new JFrame("Calculator");
    jf.setLocation(500,200);
    jf.setSize(600,400);
    jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

    /*=======================Add panel==============================
    ================================================================*/
    JPanel jp = new JPanel();
    jp.setLayout(null);
    jp.setBackground(Color.cyan);
    jf.add(jp);

    /*========================Add Textarea========================
    ================================================================*/

    JTextArea jta = new JTextArea("");
    jta.setBounds(100,25,290,50);
    jp.add(jta);

    /*========================Creating Font========================
    ===============================================================*/

    Font labels = new Font("Lucida Console",Font.PLAIN, 20);
    Font nums = new Font("Lucida Console",Font.PLAIN, 9);

    /*========================Add Labels============================
    ================================================================*/

    /*  for H align: ,SwingConstants.CENTER */
    JLabel jlbl = new JLabel("=");
    jlbl.setFont(labels);   //  MAKING FONT BIGGER
    jlbl.setBounds(400,30,50,40);
    jp.add(jlbl);

    JLabel jlbl_result = new JLabel();
    String temp = jta.getText();
    jlbl_result.setText(temp);

    /*=========================Adding button============================
    ====================================================================*/

    JButton jbtn1 = new JButton("1");
    jbtn1.setBounds(120,100,50,40);
    jbtn1.setBackground(Color.green);
    jp.add(jbtn1);

    JButton jbtn2 = new JButton("2");
    jbtn2.setBounds(180,100,50,40);
    jbtn2.setBackground(Color.green);
    jp.add(jbtn2);

    JButton jbtn3 = new JButton("3");
    jbtn3.setBounds(240,100,50,40);
    jbtn3.setBackground(Color.green);
    jp.add(jbtn3);

    JButton jbtn4 = new JButton("4");
    jbtn4.setBounds(120,155,50,40);
    jbtn4.setBackground(Color.green);
    jp.add(jbtn4);

    JButton jbtn5 = new JButton("5");
    jbtn5.setBounds(180,155,50,40);
    jbtn5.setBackground(Color.green);
    jp.add(jbtn5);

    JButton jbtn6 = new JButton("6");
    jbtn6.setBounds(240,155,50,40);
    jbtn6.setBackground(Color.green);
    jp.add(jbtn6);

    JButton jbtn7 = new JButton("7");
    jbtn7.setBounds(120,210,50,40);
    jbtn7.setBackground(Color.green);
    jp.add(jbtn7);

    JButton jbtn8 = new JButton("8");
    jbtn8.setBounds(180,210,50,40);
    jbtn8.setBackground(Color.green);
    jp.add(jbtn8);

    JButton jbtn9 = new JButton("9");
    jbtn9.setBounds(240,210,50,40);
    jbtn9.setBackground(Color.green);
    jp.add(jbtn9);

    JButton jbtn0 = new JButton("0");
    jbtn0.setBounds(180,265,50,40);
    jbtn0.setBackground(Color.green);
    jp.add(jbtn0);

    JButton jbtn_sum = new JButton("+");
    jbtn_sum.setBounds(380,100,40,40);
    jbtn_sum.setFont(nums);
    jbtn_sum.setBackground(Color.gray);
    jp.add(jbtn_sum);

    JButton jbtn_sub = new JButton("-");
    jbtn_sub.setBounds(380,100,40,40);
    jbtn_sub.setFont(nums);
    jbtn_sub.setBackground(Color.gray);
    jp.add(jbtn_sub);

    JButton jbtn_equal = new JButton("-");
    jbtn_equal.setBounds(380,155,40,40);
    jbtn_equal.setFont(nums);
    jp.add(jbtn_equal);

    jf.setVisible(true);

            jbtn1.addActionListener(e->jta.append("1"));
            jbtn2.addActionListener(e->jta.append("2"));
            jbtn3.addActionListener(e->jta.append("3"));
            jbtn4.addActionListener(e->jta.append("4"));
            jbtn5.addActionListener(e->jta.append("5"));
            jbtn6.addActionListener(e->jta.append("6"));
            jbtn7.addActionListener(e->jta.append("7"));
            jbtn8.addActionListener(e->jta.append("8"));
            jbtn9.addActionListener(e->jta.append("9"));
            jbtn0.addActionListener(e->jta.append("0"));
            jbtn_equal.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt2)
                {

                }
            });
            //jbtn_sub.addActionListener(e->jta.append("-"));
            jbtn_sum.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent evt)
                {

                }
            });
}
public static void main(String...ser)
{
    new Calculator();
}
}

i know! there is a lot of code, i want to put number that i entered to JTextArea inside variable, how to get numbers(just numbers without operators )
and assign it to variable?

and... how many variable is required to do it?(in case if i have more than 5 variable)

and a lot of questions..., i cant write it down here

thank you for help(forgive me of my bad grammar)


问:
check file permission in javascript
I am writing a simple web page using HTML and Javascript. I have fetched a file from local machine. I am able to get the details about the file like size,type etc. But i don't know how to get the file permission details without using ActiveXObject.

Here is my javascript part.

```<code>var f = document.getElementById("fileToLoad").files[0];
</code>```

fileToLoad is the field id from html.

f.type provides file type.
But i want file permission (read,write).
How can i get it?

答:
You can't.

That kind of metadata isn't an intrinsic part of the file (unlike, for instance, its size) and depends on the operating systems file permissions system.

The cross-platform File API provided by browsers doesn't implement anything that would give you any of that information.

Title: check file permission in javascript

Body:
I am writing a simple web page using HTML and Javascript. I have fetched a file from local machine. I am able to get the details about the file like size,type etc. But i don't know how to get the file permission details without using ActiveXObject.

Here is my javascript part.

var f = document.getElementById("fileToLoad").files[0];

fileToLoad is the field id from html.

f.type provides file type.
But i want file permission (read,write).
How can i get it?


问:
Nim: find the index of an item in an array or sequence
Is there a builtin method to find the index of an item in an array or sequence, equivalent to Python index ? (It may return the index of the first occurrence, or all the indices.)

答:
There's find.

Returns the first index of item in a or -1 if not found. This requires appropriate items and == operations to work.


问:
Haskell: Couldn't match expected type ‘Tree Char’ with actual type ‘Char -> Tree Char’

I want to construct a binary tree in Haskell. This tree construction is different from normal BST because the input is in Pre-order traversal and I want to reconstruct the binary tree from this input. However, I got an error when compiling this following code:

```<code>module Main where

import System.IO
import Text.Printf

data Tree a = Nil | Leaf | Branch a (Tree a) (Tree a) deriving (Eq, Show)

main = do
    -- get input tree
    line <- getLine
    return ()

insert :: Tree Char -> Char -> Tree Char
insert Nil a = Branch a Nil Nil
insert (Branch v t1 t2) a
    | t1 == Nil && t2 == Nil && v == '*' = Branch v (makeB a) t2    --If *     has no child, insert a to leftside of the tree
    | (getElement t1) == '*' && v == '*' = Branch v (insert t1 a) t2
    | (getElement t1) /= '*' && v == '*' = Branch v t1 (makeB a)

getElement :: Tree Char -> Char
getElement (Branch v t1 t2) = v

makeB :: Char -> Tree Char
makeB a =  Branch a Nil Nil

inputTree :: Tree Char -> [Char] -> Tree Char
inputTree tr [] = tr
inputTree tr (x:xs) = inputTree newtree xs
    where newtree = insert (tr x)
</code>```

The problem is in >> inputTree newtree xs.  It said

```<code>main.hs:43:33: error:
• Couldn't match expected type ‘Tree Char’
              with actual type ‘Char -> Tree Char’
• Probable cause: ‘newtree’ is applied to too few arguments
  In the first argument of ‘inputTree’, namely ‘newtree’
  In the expression: inputTree newtree xs
  In an equation for ‘inputTree’:
      inputTree tr (x : xs)
        = inputTree newtree xs
        where
            newtree = insert (tr x)
main.hs:44:29: error:
• Couldn't match expected type ‘Char -> Tree Char’
              with actual type ‘Tree Char’
• The function ‘tr’ is applied to one argument,
  but its type ‘Tree Char’ has none
  In the first argument of ‘insert’, namely ‘(tr x)’
  In the expression: insert (tr x)
</code>```

My newtree should have type Tree Char but it has type Char -> Tree Char instead. I don't know how to fix it. Thanks for any help

答:
insert (tr x) means "apply the function tr to the argument x and then apply the function insert to the result". Since insert has type Tree Char -> Char -> Tree Char and you're only applying it to one argument, this means that you get back a function of type Char -> Tree Char, which expects the second argument. That's why you get type errors about newTree having type Char -> Tree Char

The next problem is that tr isn't actually a function, so applying it to an argument makes no sense. That's the "The function ‘tr’ is applied to one argument, but its type ‘Tree Char’ has none" error.

You can fix both of those by instead applying insert to the arguments tr and x (insert tr x), as you presumably meant to all along.

Body:
I want to construct a binary tree in Haskell. This tree construction is different from normal BST because the input is in Pre-order traversal and I want to reconstruct the binary tree from this input. However, I got an error when compiling this following code:

module Main where

import System.IO
import Text.Printf

data Tree a = Nil | Leaf | Branch a (Tree a) (Tree a) deriving (Eq, Show)

main = do
    -- get input tree
    line <- getLine
    return ()

insert :: Tree Char -> Char -> Tree Char
insert Nil a = Branch a Nil Nil
insert (Branch v t1 t2) a
    | t1 == Nil && t2 == Nil && v == '*' = Branch v (makeB a) t2    --If *     has no child, insert a to leftside of the tree
    | (getElement t1) == '*' && v == '*' = Branch v (insert t1 a) t2
    | (getElement t1) /= '*' && v == '*' = Branch v t1 (makeB a)

getElement :: Tree Char -> Char
getElement (Branch v t1 t2) = v

makeB :: Char -> Tree Char
makeB a =  Branch a Nil Nil

inputTree :: Tree Char -> [Char] -> Tree Char
inputTree tr [] = tr
inputTree tr (x:xs) = inputTree newtree xs
    where newtree = insert (tr x)

The problem is in >> inputTree newtree xs.  It said

main.hs:43:33: error:
• Couldn't match expected type ‘Tree Char’
              with actual type ‘Char -> Tree Char’
• Probable cause: ‘newtree’ is applied to too few arguments
  In the first argument of ‘inputTree’, namely ‘newtree’
  In the expression: inputTree newtree xs
  In an equation for ‘inputTree’:
      inputTree tr (x : xs)
        = inputTree newtree xs
        where
            newtree = insert (tr x)
main.hs:44:29: error:
• Couldn't match expected type ‘Char -> Tree Char’
              with actual type ‘Tree Char’
• The function ‘tr’ is applied to one argument,
  but its type ‘Tree Char’ has none
  In the first argument of ‘insert’, namely ‘(tr x)’
  In the expression: insert (tr x)

My newtree should have type Tree Char but it has type Char -> Tree Char instead. I don't know how to fix it. Thanks for any help


问:
UIViews with UIPageControl
I'm a beginner when it comes to page control, and that's why I'm not sure 100% if my title agrees with what I want.  I want to make a UIPageControl that when the user swipes on the screen, the view would switch over to another view and the UIPageController at the bottom of the screen would update itself.  Also, to make my request even more confusing, I want a tab bar at the bottom of the screen that would stay put as the views change.

A great example of this is The Iconfactory's Ramp Champ:
http://img.slidetoplay.com/screenshots/ramp-champ_5.jpg

The bar at the bottom stays put while the rest of the items on the screen moves. What would be the easiest way to do this?

EDIT: I know I have to use a UISrollView, I just don't know how to go about implementing it...

答:
You need to use a UIScrollView

Assuming you have a named ivar called scrollView

```<code>    int amountOfFrames = 10;
    scrollView.pagingEnabled = TRUE;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * amountOfFrames, scrollView.frame.size.height);
     scrollView.delegate = self;
</code>```

You will then need to implement the required delegate methods, so that you can update your page control

```<code>- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
}
</code>```

You need to place whatever content you want to be scrollable inside these scrollview, ideally lazyload into it, if the content you will displaying will require a lot of heap memory, use the scrollviewDidScroll to remove and add content at the required positions

Title: UIViews with UIPageControl

Body:
You need to use a UIScrollView

Assuming you have a named ivar called scrollView

    int amountOfFrames = 10;
    scrollView.pagingEnabled = TRUE;
scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * amountOfFrames, scrollView.frame.size.height);
     scrollView.delegate = self;

You will then need to implement the required delegate methods, so that you can update your page control

- (void)scrollViewDidScroll:(UIScrollView *)sender
{
    // Switch the indicator when more than 50% of the previous/next page is visible
    CGFloat pageWidth = scrollView.frame.size.width;
    int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
}

You need to place whatever content you want to be scrollable inside these scrollview, ideally lazyload into it, if the content you will displaying will require a lot of heap memory, use the scrollviewDidScroll to remove and add content at the required positions


问:
How to define CustomAnalyzer through C# code when creating Azure Search Index
I saw the note from here: https://learn.microsoft.com/en-us/rest/api/searchservice/custom-analyzers-in-azure-search
that: Custom analyzers that you create are not exposed in the Azure portal. The only way to add a custom analyzer is through code that makes calls to the API when defining an index.

Currently I am using the following C# code to create the Azure search index:

```<code>var definition = new Microsoft.Azure.Search.Models.Index()
{
    Name = "test-index",
    Fields = new List<Field>
    {
        new Field("field1", Microsoft.Azure.Search.Models.DataType.String) { IsKey = false, IsSearchable = false, IsFilterable = false, IsSortable = false, IsFacetable = false, IsRetrievable = true }
    }
}
searchClient.Indexes.CreateOrUpdate(myIndex);
</code>```

Is there a way that I can add some code in here such as:

```<code>var analyzer = new CustomAnalyzer();
analyzer.Tokenizer = TokenizerName.Keyword;
analyzer.TokenFilters.Add(TokenFilterName.Lowercase);
</code>```

and then add this custom analyzer in my code above somewhere to let "field1" use my defined analyzer?

答:
Yes, you can add custom analyzers through the SDK, here are some examples:
https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/search/Microsoft.Azure.Search/tests/Tests/CustomAnalyzerTests.cs</p>

Body:
I saw the note from here: https://learn.microsoft.com/en-us/rest/api/searchservice/custom-analyzers-in-azure-search
that: Custom analyzers that you create are not exposed in the Azure portal. The only way to add a custom analyzer is through code that makes calls to the API when defining an index.

Currently I am using the following C# code to create the Azure search index:

var definition = new Microsoft.Azure.Search.Models.Index()
{
    Name = "test-index",
    Fields = new List<Field>
    {
        new Field("field1", Microsoft.Azure.Search.Models.DataType.String) { IsKey = false, IsSearchable = false, IsFilterable = false, IsSortable = false, IsFacetable = false, IsRetrievable = true }
    }
}
searchClient.Indexes.CreateOrUpdate(myIndex);

Is there a way that I can add some code in here such as:

var analyzer = new CustomAnalyzer();
analyzer.Tokenizer = TokenizerName.Keyword;
analyzer.TokenFilters.Add(TokenFilterName.Lowercase);

and then add this custom analyzer in my code above somewhere to let "field1" use my defined analyzer?

ContentLicense: CC BY-SA 4.0


问:
`break` and `continue` in `forEach` in Kotlin
Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local):

```<code>repeat(5) {
    break
}

(1..5).forEach {
    continue@forEach
}
</code>```

The goal is to mimic usual loops with the functional syntax as close as it might be. It was definitely possible in some older versions of Kotlin, but I struggle to reproduce the syntax.

The problem might be a bug with labels (M12), but I think that the first example should work anyway.

It seems to me that I've read somewhere about a special trick/annotation, but I could not find any reference on the subject. Might look like the following:

```<code>public inline fun repeat(times: Int, @loop body: (Int) -> Unit) {
    for (index in 0..times - 1) {
        body(index)
    }
}
</code>```

答:
This will print 1 to 5. The return@forEach acts like the keyword continue in Java, which means in this case, it still executes every loop but skips to the next iteration if the value is greater than 5.

fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    nums.forEach {
       if (it > 5) return@forEach
       println(it)
    }
}
```
<p>This will print 1 to 10 but skips 5.</p>
<pre class="lang-kotlin prettyprint-override"><code>fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    nums.forEach {
       if (it == 5) return@forEach
       println(it)
    }
}
</code>```

This will print 1 to 4, and break when reaching 5.

fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    run breaking@ {
        nums.forEach {
           if (it == 5) return@breaking
           println(it)
        }
    }
}
```

Link to code snippet from ashuges.

Body:
Kotlin has very nice iterating functions, like forEach or repeat, but I am not able to make the break and continue operators work with them (both local and non-local):

repeat(5) {
    break
}

(1..5).forEach {
    continue@forEach
}

The goal is to mimic usual loops with the functional syntax as close as it might be. It was definitely possible in some older versions of Kotlin, but I struggle to reproduce the syntax.

The problem might be a bug with labels (M12), but I think that the first example should work anyway.

It seems to me that I've read somewhere about a special trick/annotation, but I could not find any reference on the subject. Might look like the following:

public inline fun repeat(times: Int, @loop body: (Int) -> Unit) {
    for (index in 0..times - 1) {
        body(index)
    }
}

Body:
This will print 1 to 5. The return@forEach acts like the keyword continue in Java, which means in this case, it still executes every loop but skips to the next iteration if the value is greater than 5.

fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    nums.forEach {
       if (it > 5) return@forEach
       println(it)
    }
}

This will print 1 to 10 but skips 5.

fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    nums.forEach {
       if (it == 5) return@forEach
       println(it)
    }
}

This will print 1 to 4, and break when reaching 5.

fun main(args: Array<String>) {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    run breaking@ {
        nums.forEach {
           if (it == 5) return@breaking
           println(it)
        }
    }
}

Link to code snippet from ashuges.


问:
Get a variable name from database
I'm a little confused - how do I get a variable name stored to a database?!
Record in the database is a string: "$test"

The variable $user is set before the records a fetched from database. So I want to "convert" this string to a real variable to get the value of it.

The following didn't work:

```<code>// $test is set to 'bla'
$test = 'bla';
// $var is the value from the database
$var = '$test';
// print $test
echo ${$var};
</code>```

I know that it would work if I remove the '$' from the database record

```<code>$var = 'test';
echo $$var;
</code>```

But how to handle this without?

答:
I was facing a similar problem just now.
Here is what I did:
$res[0] is obtained from mysql_fetch_array() and it contains another query which has $variable embedded.

```<code>$qry="select query from sql_list where id=".$sql_id;
$result=mysql_query($qry);
$res=mysql_fetch_array($result);
eval("\$qry_2 = \"$res[0]\";");
mysql_query($qry_2)
</code>```

It works! Maybe someone can suggest a better way.

Title: Get a variable name from database

Body:
I'm a little confused - how do I get a variable name stored to a database?!
Record in the database is a string: "$test"

The variable $user is set before the records a fetched from database. So I want to "convert" this string to a real variable to get the value of it.

The following didn't work:

// $test is set to 'bla'
$test = 'bla';
// $var is the value from the database
$var = '$test';
// print $test
echo ${$var};

I know that it would work if I remove the '$' from the database record

$var = 'test';
echo $$var;

But how to handle this without?

Body:
I was facing a similar problem just now.
Here is what I did:
$res[0] is obtained from mysql_fetch_array() and it contains another query which has $variable embedded.

$qry="select query from sql_list where id=".$sql_id;
$result=mysql_query($qry);
$res=mysql_fetch_array($result);
eval("\$qry_2 = \"$res[0]\";");
mysql_query($qry_2)

It works! Maybe someone can suggest a better way.


问:
Highest appearance of a value within each group
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

```<code>| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |
</code>```

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

答:
This may look complicated but it will only aggregate the data once only, then pass through it ranking the results and choosing only the first one

```<code>select userid, websiteid, visits
from
(
select
 userid, websiteid, visits,
 @r := case when @u=userid then @r+1 else 1 end r,
 @u := userid
from
(select @u:=null) x,
(select userid, websiteid, count(*) visits
 from visit
 group by userid, websiteid
 order by userid, visits desc) y
) z
where r=1
</code>```

The inner select generates counts for each user-website combination and orders it by the most visits. This is then passed through the middle query that ranks the records per user, giving the rank in the column r.

This is a variation, which will show ALL websites for a user that have EQUAL rank.  The difference with the previous query is that if websites A and B both have 10 visits from user X, both A and B are listed in the result whereas the previous query selects one randomly to show.

```<code>select userid, websiteid, visits
from
(
select
 userid, websiteid, visits,
 @r := case
    when @u=userid and @v=visits then @r  # same rank
    when @u=userid then @r+1              # next rank
    else 1                                # different user
    end r,
 @u := userid, @v := visits
from
(select @u:=null, @v:=null) x,
(select userid, websiteid, count(*) visits
 from visit
 group by userid, websiteid
 order by userid, visits desc) y
) z
where r=1
</code>```

This is the test table used

```<code>create table visit (userid int, websiteid int);
insert into visit select 1,1;
insert into visit select 1,2;
insert into visit select 1,1;
insert into visit select 1,4;
insert into visit select 2,1;
insert into visit select 2,2;
insert into visit select 2,5;
insert into visit select 2,2;
</code>```

Body:
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

Body:
This may look complicated but it will only aggregate the data once only, then pass through it ranking the results and choosing only the first one

select userid, websiteid, visits
from
(
select
 userid, websiteid, visits,
 @r := case when @u=userid then @r+1 else 1 end r,
 @u := userid
from
(select @u:=null) x,
(select userid, websiteid, count(*) visits
 from visit
 group by userid, websiteid
 order by userid, visits desc) y
) z
where r=1

The inner select generates counts for each user-website combination and orders it by the most visits. This is then passed through the middle query that ranks the records per user, giving the rank in the column r.

This is a variation, which will show ALL websites for a user that have EQUAL rank.  The difference with the previous query is that if websites A and B both have 10 visits from user X, both A and B are listed in the result whereas the previous query selects one randomly to show.

select userid, websiteid, visits
from
(
select
 userid, websiteid, visits,
 @r := case
    when @u=userid and @v=visits then @r  # same rank
    when @u=userid then @r+1              # next rank
    else 1                                # different user
    end r,
 @u := userid, @v := visits
from
(select @u:=null, @v:=null) x,
(select userid, websiteid, count(*) visits
 from visit
 group by userid, websiteid
 order by userid, visits desc) y
) z
where r=1

This is the test table used

create table visit (userid int, websiteid int);
insert into visit select 1,1;
insert into visit select 1,2;
insert into visit select 1,1;
insert into visit select 1,4;
insert into visit select 2,1;
insert into visit select 2,2;
insert into visit select 2,5;
insert into visit select 2,2;


问:
In Prolog, how can I create a list of lists when I am using a variable bound to several values?

Issue

I am trying to move all new lists that I create into one super list of lists. Instead the output is formatted as a bunch of individually changed lists.

The problem likely stems from the fact I use between to assign Iterations and Size, but I am not sure what else I can do.

Input

```<code>placeRedBlocks(4, X), loopReplace(X, Y), append([X], [Y], Z).
</code>```

Expectation

```<code>Z = [[b, b, b, b], [r, r, r, b], [r, r, r, r], [b, r, r, r]]
</code>```

Reality

```<code>X = [b, b, b, b],
Y = [r, r, r, b],
Z = [[b, b, b, b], [r, r, r, b]]
X = [b, b, b, b],
Y = [r, r, r, r],
Z = [[b, b, b, b], [r, r, r, r]]
X = [b, b, b, b],
Y = [b, r, r, r],
Z = [[b, b, b, b], [b, r, r, r]]
false
</code>```

Code Explanation

This prolog code takes a list of values and replaces the designated values and returns it into another list.

```<code>placeRedBlocks(Length, List) :-
    findall('b', between(1, Length, _), List).

replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
  I > -1,
  NI is I-1,
  replace(T, NI, X, R), !.

replaceX(A,_,0,_,A):- !.
replaceX(Line,Index,NumElm,Elm,NLine) :-
  replace(Line,Index,Elm,BLine),
  Index1 is Index+1,
  NumElm1 is NumElm-1,
  replaceX(BLine,Index1,NumElm1,Elm,NLine).

loopReplace(ListToReplace, NewList) :-
    length(ListToReplace, Len),
    TotalCount is Len-3,
    between(0, TotalCount, Iterations),
    between(3, Len, Size),
    replaceX(ListToReplace, Iterations, Size, 'r', NewList).
</code>```

In replaceX:

Line is the list you are trying to replace the values in. Index is the position in the list where you start replacing values. NumElm is the number of elements you are replacing in total. Elm is the character or number that replaces the other values in the list. NLine is the list where the output will go.

答:
After messing around with findall/3 and bagof/3 I found an answer that works for my question.

Input

```<code>placeRedBlocks(7, X), findall(Y, loopReplace(X, Y), Z).
</code>```

would get me

```<code>Z = [[r, r, r, b, b, b, b], [r, r, r, r, b, b, b], [r, r, r, r, r, b, b], [r, r, r, r, r, r, b], [r, r, r, r, r, r, r], [b, r, r, r, b, b, b], [b, r, r, r, r, b, b], [b, r, r, r, r, r, b], [b, r, r, r, r, r, r], [b, b, r, r, r, b, b], [b, b, r, r, r, r, b], [b, b, r, r, r, r, r], [b, b, b, r, r, r, b], [b, b, b, r, r, r, r], [b, b, b, b, r, r, r]]
</code>```

Body:
Issue

I am trying to move all new lists that I create into one super list of lists. Instead the output is formatted as a bunch of individually changed lists.

The problem likely stems from the fact I use between to assign Iterations and Size, but I am not sure what else I can do.

Input

placeRedBlocks(4, X), loopReplace(X, Y), append([X], [Y], Z).

Expectation

Z = [[b, b, b, b], [r, r, r, b], [r, r, r, r], [b, r, r, r]]

Reality

X = [b, b, b, b],
Y = [r, r, r, b],
Z = [[b, b, b, b], [r, r, r, b]]
X = [b, b, b, b],
Y = [r, r, r, r],
Z = [[b, b, b, b], [r, r, r, r]]
X = [b, b, b, b],
Y = [b, r, r, r],
Z = [[b, b, b, b], [b, r, r, r]]
false

Code Explanation

This prolog code takes a list of values and replaces the designated values and returns it into another list.

placeRedBlocks(Length, List) :-
    findall('b', between(1, Length, _), List).

replace([_|T], 0, X, [X|T]).
replace([H|T], I, X, [H|R]):-
  I > -1,
  NI is I-1,
  replace(T, NI, X, R), !.

replaceX(A,_,0,_,A):- !.
replaceX(Line,Index,NumElm,Elm,NLine) :-
  replace(Line,Index,Elm,BLine),
  Index1 is Index+1,
  NumElm1 is NumElm-1,
  replaceX(BLine,Index1,NumElm1,Elm,NLine).

loopReplace(ListToReplace, NewList) :-
    length(ListToReplace, Len),
    TotalCount is Len-3,
    between(0, TotalCount, Iterations),
    between(3, Len, Size),
    replaceX(ListToReplace, Iterations, Size, 'r', NewList).

In replaceX:

Line is the list you are trying to replace the values in. Index is the position in the list where you start replacing values. NumElm is the number of elements you are replacing in total. Elm is the character or number that replaces the other values in the list. NLine is the list where the output will go.

Body:
After messing around with findall/3 and bagof/3 I found an answer that works for my question.

Input

placeRedBlocks(7, X), findall(Y, loopReplace(X, Y), Z).

would get me

Z = [[r, r, r, b, b, b, b], [r, r, r, r, b, b, b], [r, r, r, r, r, b, b], [r, r, r, r, r, r, b], [r, r, r, r, r, r, r], [b, r, r, r, b, b, b], [b, r, r, r, r, b, b], [b, r, r, r, r, r, b], [b, r, r, r, r, r, r], [b, b, r, r, r, b, b], [b, b, r, r, r, r, b], [b, b, r, r, r, r, r], [b, b, b, r, r, r, b], [b, b, b, r, r, r, r], [b, b, b, b, r, r, r]]


问:
JavaScript toggle divs
I want to toggle between 3 divs. Unfortunately it only works for 2 divs.

My code (for two divs):

```<code>$(function() {
  $('#playerbargreen').hide();
  $('#playerbaroff,#playerbargreen').click(function() {
    $('#playerbargreen,#playerbaroff').toggle();
  });
});
</code>```

The end result must be:

show first div --> click --> hide first div and show second div --> Click --> hide second div and show third div

Has someone any idea? Thanks in advance!

答:
You can try something like this

$('#Div2').hide();
$('#Div3').hide();

$('#Div1').click(function() {
    $('#Div1').hide();
    $('#Div2').show();
});

$('#Div2').click(function() {
    $('#Div2').hide();
    $('#Div3').show();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
width:100px;
height:100px;
background-color:green;
color:white;
text-align:center;
}</code>```

div1

div2

div3
```

Title: JavaScript toggle divs

Body:
I want to toggle between 3 divs. Unfortunately it only works for 2 divs.

My code (for two divs):

$(function() {
  $('#playerbargreen').hide();
  $('#playerbaroff,#playerbargreen').click(function() {
    $('#playerbargreen,#playerbaroff').toggle();
  });
});

The end result must be:

show first div --> click --> hide first div and show second div --> Click --> hide second div and show third div

Has someone any idea? Thanks in advance!

Body:
You can try something like this

$('#Div2').hide();
$('#Div3').hide();

$('#Div1').click(function() {
    $('#Div1').hide();
    $('#Div2').show();
});

$('#Div2').click(function() {
    $('#Div2').hide();
    $('#Div3').show();
});

div{
width:100px;
height:100px;
background-color:green;
color:white;
text-align:center;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Div1">div1</div>
<div id="Div2">div2</div>
<div id="Div3">div3</div>


问:
CNTK: How do I initialize LSTM hidden state?
I'm trying convert a working image captioning CNN-LSTM network from TensorFlow to CNTK, and have what I think is a correctly trained model, but am having trouble figuring out how to extract predictions from the final trained CNTK model.

This is the general architecture I'm working with:

This is my CNTK model:

```<code>def create_lstm_model(image_features, text_features):
    embedding_dim = 512
    hidden_dim = 512
    cell_dim = 512
    vocab_dim = 77

    image_embedding = Embedding(embedding_dim)
    text_embedding = Embedding(embedding_dim)
    lstm_classifier = Sequential([Stabilizer(),
                                  Recurrence(LSTM(hidden_dim)),
                                  Recurrence(LSTM(hidden_dim)),
                                  Stabilizer(),
                                  Dense(vocab_dim)])

    embedded_images = BatchNormalization()(image_embedding(image_features))
    embedded_text = text_embedding(text_features)
    lstm_input = C.plus(embedded_images, embedded_text)
    lstm_input = C.dropout(lstm_input, 0.5)
    output = lstm_classifier(lstm_input)

    return output
</code>```

I'm providing my data in CTF format, with fixed caption sequence sizes of 40, using this structure:

```<code>def create_reader(path, is_training):
    return MinibatchSource(CTFDeserializer(path, StreamDefs(
        target_tokens = StreamDef(field='target_tokens', shape=vocab_len, is_sparse=True),
        input_tokens = StreamDef(field='input_tokens', shape=vocab_len, is_sparse=True),
        image_features = StreamDef(field='image_features', shape=image_features_dim, is_sparse=False)
    )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)
</code>```

Aside: the reason for three streams of data - I have an input image feature vector (last 2048-dim layer of a pre-trained ResNet), a sequence of input text tokens, and a sequence of output text tokens. So basically my CTF file, in terms of sequences, looks like:

```<code>0 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
0 | target_token_1  | input_token_1 | empty array of 2048 zeros
0 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
0 | target_token_40 | input_token_40 | empty array of 2048 zeros
1 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
1 | target_token_1  | input_token_1 | empty array of 2048 zeros
1 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
1 | target_token_40 | input_token_40 | empty array of 2048 zeros
</code>```

Basically, I couldn't figure out how to slice & splice two sequences together in CNTK (even though you can splice two tensors easily), so I'm hacking around it by providing only the first element in a sequence with an input 2048-dim image feature vector, and the remaining elements in a sequence with an empty 2048-dim vector of zeros - setup for:

C.plus(embedded_images, embedded_text)

in the model above - where the goal is to essentially take the first element of a sequence of 40 [2048]->[512] image embeddings and hack-splice(TM) it in front of the last 39 elements of a sequence of 40 [vocab_dim]->[512] word embeddings. I'm counting on pretty empty [2048]->[512] image embeddings being learned for the empty image vectors (2048 zeros), so I'm taking my embedded image sequence and element-wise adding it to my embedded text sequence before all goes into the LSTM. Basically, this:

```<code>image embedding sequence: [-1, 40, 512]  (e.g., [-1, 0, 512])
text embedding sequence:  [-1, 40, 512]  (e.g., [-1, 1:40, 512)
+
---------------------------------------
lstm input sequence:      [-1, 40, 512]
</code>```

Which brings me to my actual question. Now that I have a model that trains decently well, I'd like to extract caption predictions from the model, basically doing something like this (from this PyTorch image captioning tutorial):

```<code>def sample(self, features, states=None):
    """Samples captions for given image features (Greedy search)."""
    sampled_ids = []
    inputs = features.unsqueeze(1)
    for i in range(20):                                      # maximum sampling length
        hiddens, states = self.lstm(inputs, states)          # (batch_size, 1, hidden_size),
        outputs = self.linear(hiddens.squeeze(1))            # (batch_size, vocab_size)
        predicted = outputs.max(1)[1]
        sampled_ids.append(predicted)
        inputs = self.embed(predicted)
        inputs = inputs.unsqueeze(1)                         # (batch_size, 1, embed_size)
    sampled_ids = torch.cat(sampled_ids, 1)                  # (batch_size, 20)
    return sampled_ids.squeeze()
</code>```

The problem is, I can't figure out the CNTK equivalent for getting the hidden state out of an LSTM and pumping it back in next time step:

```<code>hiddens, states = self.lstm(inputs, states)
</code>```

How does this work in CNTK?

答:
I think the function you are looking is RecurrenceFrom(). Its documentation contains the following example:

```<code>Example:
 >>> from cntk.layers import *
 >>> from cntk.layers.typing import *

 >>> # a plain sequence-to-sequence model in training (where label length is known)
 >>> en = C.input_variable(**SequenceOver[Axis('m')][SparseTensor[20000]])  # English input sentence
 >>> fr = C.input_variable(**SequenceOver[Axis('n')][SparseTensor[30000]])  # French target sentence

 >>> embed = Embedding(300)
 >>> encoder = Recurrence(LSTM(500), return_full_state=True)
 >>> decoder = RecurrenceFrom(LSTM(500))       # decoder starts from a data-dependent initial state, hence -From()
 >>> emit = Dense(30000)
 >>> h, c = encoder(embed(en)).outputs         # LSTM encoder has two outputs (h, c)
 >>> z = emit(decoder(h, c, sequence.past_value(fr)))   # decoder takes encoder outputs as initial state
 >>> loss = C.cross_entropy_with_softmax(z, fr)
</code>```

Body:
I'm trying convert a working image captioning CNN-LSTM network from TensorFlow to CNTK, and have what I think is a correctly trained model, but am having trouble figuring out how to extract predictions from the final trained CNTK model.

This is the general architecture I'm working with:

This is my CNTK model:

def create_lstm_model(image_features, text_features):
    embedding_dim = 512
    hidden_dim = 512
    cell_dim = 512
    vocab_dim = 77

    image_embedding = Embedding(embedding_dim)
    text_embedding = Embedding(embedding_dim)
    lstm_classifier = Sequential([Stabilizer(),
                                  Recurrence(LSTM(hidden_dim)),
                                  Recurrence(LSTM(hidden_dim)),
                                  Stabilizer(),
                                  Dense(vocab_dim)])

    embedded_images = BatchNormalization()(image_embedding(image_features))
    embedded_text = text_embedding(text_features)
    lstm_input = C.plus(embedded_images, embedded_text)
    lstm_input = C.dropout(lstm_input, 0.5)
    output = lstm_classifier(lstm_input)

    return output

I'm providing my data in CTF format, with fixed caption sequence sizes of 40, using this structure:

def create_reader(path, is_training):
    return MinibatchSource(CTFDeserializer(path, StreamDefs(
        target_tokens = StreamDef(field='target_tokens', shape=vocab_len, is_sparse=True),
        input_tokens = StreamDef(field='input_tokens', shape=vocab_len, is_sparse=True),
        image_features = StreamDef(field='image_features', shape=image_features_dim, is_sparse=False)
    )), randomize = is_training, max_sweeps = INFINITELY_REPEAT if is_training else 1)

Aside: the reason for three streams of data - I have an input image feature vector (last 2048-dim layer of a pre-trained ResNet), a sequence of input text tokens, and a sequence of output text tokens. So basically my CTF file, in terms of sequences, looks like:

0 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
0 | target_token_1  | input_token_1 | empty array of 2048 zeros
0 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
0 | target_token_40 | input_token_40 | empty array of 2048 zeros
1 | target_token_0  | input_token_0 | input_image_feature_vector (2048-dim)
1 | target_token_1  | input_token_1 | empty array of 2048 zeros
1 | target_token_2  | input_token_2 | empty array of 2048 zeros
...
1 | target_token_40 | input_token_40 | empty array of 2048 zeros

Basically, I couldn't figure out how to slice & splice two sequences together in CNTK (even though you can splice two tensors easily), so I'm hacking around it by providing only the first element in a sequence with an input 2048-dim image feature vector, and the remaining elements in a sequence with an empty 2048-dim vector of zeros - setup for:

C.plus(embedded_images, embedded_text)

in the model above - where the goal is to essentially take the first element of a sequence of 40 [2048]->[512] image embeddings and hack-splice(TM) it in front of the last 39 elements of a sequence of 40 [vocab_dim]->[512] word embeddings. I'm counting on pretty empty [2048]->[512] image embeddings being learned for the empty image vectors (2048 zeros), so I'm taking my embedded image sequence and element-wise adding it to my embedded text sequence before all goes into the LSTM. Basically, this:

image embedding sequence: [-1, 40, 512]  (e.g., [-1, 0, 512])
text embedding sequence:  [-1, 40, 512]  (e.g., [-1, 1:40, 512)
+
---------------------------------------
lstm input sequence:      [-1, 40, 512]

Which brings me to my actual question. Now that I have a model that trains decently well, I'd like to extract caption predictions from the model, basically doing something like this (from this PyTorch image captioning tutorial):

def sample(self, features, states=None):
    """Samples captions for given image features (Greedy search)."""
    sampled_ids = []
    inputs = features.unsqueeze(1)
    for i in range(20):                                      # maximum sampling length
        hiddens, states = self.lstm(inputs, states)          # (batch_size, 1, hidden_size),
        outputs = self.linear(hiddens.squeeze(1))            # (batch_size, vocab_size)
        predicted = outputs.max(1)[1]
        sampled_ids.append(predicted)
        inputs = self.embed(predicted)
        inputs = inputs.unsqueeze(1)                         # (batch_size, 1, embed_size)
    sampled_ids = torch.cat(sampled_ids, 1)                  # (batch_size, 20)
    return sampled_ids.squeeze()

The problem is, I can't figure out the CNTK equivalent for getting the hidden state out of an LSTM and pumping it back in next time step:

hiddens, states = self.lstm(inputs, states)

How does this work in CNTK?

Body:
I think the function you are looking is RecurrenceFrom(). Its documentation contains the following example:

Example:
 >>> from cntk.layers import *
 >>> from cntk.layers.typing import *

 >>> # a plain sequence-to-sequence model in training (where label length is known)
 >>> en = C.input_variable(**SequenceOver[Axis('m')][SparseTensor[20000]])  # English input sentence
 >>> fr = C.input_variable(**SequenceOver[Axis('n')][SparseTensor[30000]])  # French target sentence

 >>> embed = Embedding(300)
 >>> encoder = Recurrence(LSTM(500), return_full_state=True)
 >>> decoder = RecurrenceFrom(LSTM(500))       # decoder starts from a data-dependent initial state, hence -From()
 >>> emit = Dense(30000)
 >>> h, c = encoder(embed(en)).outputs         # LSTM encoder has two outputs (h, c)
 >>> z = emit(decoder(h, c, sequence.past_value(fr)))   # decoder takes encoder outputs as initial state
 >>> loss = C.cross_entropy_with_softmax(z, fr)


问:
BMI calculator in Java
I am new to Java and still trying to learn my way around it. Today my teacher gave an assignment where we make a BMI calculator in Java. One of the steps is to make it show the BMI categories. So the user would be able to look at it and see where they stand. I got everything else done but am running into an issue.

Here is the script:

```<code>import java.util.Scanner;

public class BMI {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        double weight = 0.0;
        double height = 0.0;
        double bmi = 0.0;

        System.out.print("Enter your weight in pounds: ");
        weight = input.nextInt();

        System.out.print("Enter your height: ");
        height = input.nextInt();

        bmi = ((weight * 703)/(height * height));

        System.out.printf("Your BMI is", bmi);

        System.out.println("BMI VALUES");
        System.out.println("Underweight: Under 18.5");
        System.out.println("Normal: 18.5-24.9 ");
        System.out.println("Overweight: 25-29.9");
        System.out.println("Obese: 30 or over");
     }
    }
</code>```

Here is the result:

```<code>Your BMI isBMI VALUES
Underweight: Under 18.5
Normal: 18.5-24.9
Overweight: 25-29.9
Obese: 30 or over
</code>```

What am I doing wrong and how do I fix this?

答:
https://github.com/arghadasofficial/BMI/blob/master/src/argha/bmi/Bmi.java</p>

```<code>public class Bmi {

    //Variables
    private double result; //Stores the result
    private String bmi; //Stores the Bmi result in String
    private String status; //Stores the status (Normal......)
    private static DecimalFormat decimalFormat = new DecimalFormat(".#"); //Formating the result

    /**
     * Get the BMI from calculation and returns the result in String format
     *
     * @return BMI
     */
    public String getBmi() {
        /**
         * Following code example : bmi = decimalFormat.format(result);
         *
         * if bmi is 23.12345 then remove 2345 and return 23.1 using DecimalFormat class provided by Java
         *
         */
        bmi = decimalFormat.format(result);
        return bmi;
    }

    /**
     * Get the status according to the BMI result and returns the Status in
     * String format
     *
     * @return Status
     */
    public String getStatus() {
        return status;
    }

    /**
     * Get weight and height in double format and do the calculation for you
     *
     * @param weight - accepts weight in kilograms
     * @param height - accept height in centimeters
     */
    public void calculateBmi(double weight, double height) {
        /**
         * First get weight and height then convert height to meters then
         * multiply the height itself to height and then divide the height with
         * weight then set the actual value to result variable
         */

        //Convert the height from cm to m
        double meters = height / 100;

        //Multiply height by height
        double multiply = meters * meters;

        //divide the height with weight in kg
        double division = weight / multiply;

        //set the value to result variable
        result = division;

        //call checkStatus method for checking Status
        checkStatus();
    }

    /**
     * Private method for checking bmi and returns the status It remains private
     * because we don't need to access this from somewhere else.
     */
    private void checkStatus() {
        /**
         * Check :
         *
         * if BMI is less than 18.5 then set status to Underweight if BMI is
         * greater than 18.5 and less than 25 then set status to Normal if BMI
         * is greater than 25 and less than 30 then set status to Overweight if
         * BMI equals to 30 or greater than 30 then set status to Obese
         */
        if (result < 18.5) {
            status = "Underweight";
        } else if (result > 18.5 && result < 25) {
            status = "Normal";
        } else if (result > 25 && result < 30) {
            status = "Overweight";
        } else if (result == 30 || result > 30) {
            status = "Obese";
        }
    }
}
</code>```

Title: BMI calculator in Java

Body:
I am new to Java and still trying to learn my way around it. Today my teacher gave an assignment where we make a BMI calculator in Java. One of the steps is to make it show the BMI categories. So the user would be able to look at it and see where they stand. I got everything else done but am running into an issue.

Here is the script:

import java.util.Scanner;

public class BMI {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        double weight = 0.0;
        double height = 0.0;
        double bmi = 0.0;

        System.out.print("Enter your weight in pounds: ");
        weight = input.nextInt();

        System.out.print("Enter your height: ");
        height = input.nextInt();

        bmi = ((weight * 703)/(height * height));

        System.out.printf("Your BMI is", bmi);

        System.out.println("BMI VALUES");
        System.out.println("Underweight: Under 18.5");
        System.out.println("Normal: 18.5-24.9 ");
        System.out.println("Overweight: 25-29.9");
        System.out.println("Obese: 30 or over");
     }
    }

Here is the result:

Your BMI isBMI VALUES
Underweight: Under 18.5
Normal: 18.5-24.9
Overweight: 25-29.9
Obese: 30 or over

What am I doing wrong and how do I fix this?

Body:
https://github.com/arghadasofficial/BMI/blob/master/src/argha/bmi/Bmi.java

public class Bmi {

    //Variables
    private double result; //Stores the result
    private String bmi; //Stores the Bmi result in String
    private String status; //Stores the status (Normal......)
    private static DecimalFormat decimalFormat = new DecimalFormat(".#"); //Formating the result

    /**
     * Get the BMI from calculation and returns the result in String format
     *
     * @return BMI
     */
    public String getBmi() {
        /**
         * Following code example : bmi = decimalFormat.format(result);
         *
         * if bmi is 23.12345 then remove 2345 and return 23.1 using DecimalFormat class provided by Java
         *
         */
        bmi = decimalFormat.format(result);
        return bmi;
    }

    /**
     * Get the status according to the BMI result and returns the Status in
     * String format
     *
     * @return Status
     */
    public String getStatus() {
        return status;
    }

    /**
     * Get weight and height in double format and do the calculation for you
     *
     * @param weight - accepts weight in kilograms
     * @param height - accept height in centimeters
     */
    public void calculateBmi(double weight, double height) {
        /**
         * First get weight and height then convert height to meters then
         * multiply the height itself to height and then divide the height with
         * weight then set the actual value to result variable
         */

        //Convert the height from cm to m
        double meters = height / 100;

        //Multiply height by height
        double multiply = meters * meters;

        //divide the height with weight in kg
        double division = weight / multiply;

        //set the value to result variable
        result = division;

        //call checkStatus method for checking Status
        checkStatus();
    }

    /**
     * Private method for checking bmi and returns the status It remains private
     * because we don't need to access this from somewhere else.
     */
    private void checkStatus() {
        /**
         * Check :
         *
         * if BMI is less than 18.5 then set status to Underweight if BMI is
         * greater than 18.5 and less than 25 then set status to Normal if BMI
         * is greater than 25 and less than 30 then set status to Overweight if
         * BMI equals to 30 or greater than 30 then set status to Obese
         */
        if (result < 18.5) {
            status = "Underweight";
        } else if (result > 18.5 && result < 25) {
            status = "Normal";
        } else if (result > 25 && result < 30) {
            status = "Overweight";
        } else if (result == 30 || result > 30) {
            status = "Obese";
        }
    }
}


问:
Weka runtime error
I am trying to copy the first attribute of my training dataset, and copy the corresponding from Test set for book-keeping purpose.  My code compiles successfully. But I am not able to run it.

I get the following errorwhen run java WekaRF

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: weka/core/converters/CSVLoader
    at WekaRF.main(WekaRF.java:17)
Caused by: java.lang.ClassNotFoundException: weka.core.converters.CSVLoader
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
</code>```

If I run, java -cp weka-3-8-1/weka.jar WekaRF, I get

```<code>Error: Could not find or load main class WekaRF
</code>```

My code is given below

```<code>import java.io.*;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.RandomForest;
import weka.core.Instances;
import weka.filters.unsupervised.attribute.Remove;
import weka.core.converters.*;

public class WekaRF {
    public static void main(String[] args) {
        int percent = 60;
        Instances data = null;
        try {
            CSVLoader loader = new CSVLoader();
            loader.setSource(new File("../../rf.csv"));
            data = loader.getDataSet();
        } catch (Exception e) {
            e.printStackTrace();
            return;
            }
        int TrainSize = (int) Math.round(data.numInstances() * percent/ 100);
        int TestSize = data.numInstances() - TrainSize;

        Instances Train = new Instances(data, 0, TrainSize);
        Instances Test = new Instances(data, TrainSize, TestSize);
        System.out.println(Test.attribute(0).name());
        Remove remove = new Remove();
        String[] options = new String[2];
        options[0] = "-R";
        options[1] = "1";
        remove.setOptions(options);
        remove.setInputFormat(data2);
        Test = Filter.useFilter(Test, remove);
        Train.setClassIndex(Train.numAttributes() - 1);
    }
}
</code>```

答:
Your classpath does not include current directory so java didn't see your WekaRF class.
Try to use java -cp .;weka-3-8-1/weka.jar WekaRF instead.
Notice dot at the start of -cp argument. It denotes current directory.

Upd: Character used to separate individual class path entries is operation system-depended. Windows uses ; and most other systems use :. The actual path separator can be retrieved by querying java.io.File::pathSeparator field.

Title: Weka runtime error

Body:
I am trying to copy the first attribute of my training dataset, and copy the corresponding from Test set for book-keeping purpose.  My code compiles successfully. But I am not able to run it.

I get the following errorwhen run java WekaRF

Exception in thread "main" java.lang.NoClassDefFoundError: weka/core/converters/CSVLoader
    at WekaRF.main(WekaRF.java:17)
Caused by: java.lang.ClassNotFoundException: weka.core.converters.CSVLoader
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

If I run, java -cp weka-3-8-1/weka.jar WekaRF, I get

Error: Could not find or load main class WekaRF

My code is given below

import java.io.*;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.RandomForest;
import weka.core.Instances;
import weka.filters.unsupervised.attribute.Remove;
import weka.core.converters.*;

public class WekaRF {
    public static void main(String[] args) {
        int percent = 60;
        Instances data = null;
        try {
            CSVLoader loader = new CSVLoader();
            loader.setSource(new File("../../rf.csv"));
            data = loader.getDataSet();
        } catch (Exception e) {
            e.printStackTrace();
            return;
            }
        int TrainSize = (int) Math.round(data.numInstances() * percent/ 100);
        int TestSize = data.numInstances() - TrainSize;

        Instances Train = new Instances(data, 0, TrainSize);
        Instances Test = new Instances(data, TrainSize, TestSize);
        System.out.println(Test.attribute(0).name());
        Remove remove = new Remove();
        String[] options = new String[2];
        options[0] = "-R";
        options[1] = "1";
        remove.setOptions(options);
        remove.setInputFormat(data2);
        Test = Filter.useFilter(Test, remove);
        Train.setClassIndex(Train.numAttributes() - 1);
    }
}