问:
Set the "File/Product version" of a Windows' binary to arbitrary string
all. Currently, I want to set the version of a Windows' application (exe), dynamically-linked library (dll) or statically-linked library (lib) to a one using not the standard version format <major>.<minor>.<patch>.<build> (example: 3.2.0.73) but the semantic versioning 2.0's one (example: 3.2.0-RC3+73). Looking at the specifications of the version information resource (VERSIONINFO) both the FILEVERSION and the PRODUCTVERSION fields consist of:

two 32-bit integers, defined by four 16-bit integers

Hence, both version fields should be specified as having 4 version segments/parts/numbers where each of them is 16-bit (unsigned short integer) wide:

```<code>#define VER_FILEVERSION             3,10,349,0
#define VER_FILEVERSION_STR         "3.10.349.0\0"

#define VER_PRODUCTVERSION          3,10,0,0
#define VER_PRODUCTVERSION_STR      "3.10\0"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
FILEFLAGSMASK   VS_FFI_FILEFLAGSMASK
FILEFLAGS       (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG)

// ...

BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",      VER_COMPANYNAME_STR
            VALUE "FileDescription",  VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",      VER_FILEVERSION_STR

            // ...

            VALUE "ProductVersion",   VER_PRODUCTVERSION_STR
        END
    END

    // ...
END
</code>```

The situation is different about the string variants of the corresponding fields. Scanning the same specification near the bottom and more particularly the section:

Remarks -> string-name

what becomes obvious is that those string representations of the 4-segment 16-bit file and product versions, could contain any characters:

FileVersion | Version number of the file. For example, "3.10" or "5.00.RC2". This string is required.

...

ProductVersion | Version of the product with which the file is distributed. For example, "3.10" or "5.00.RC2". This string is required.

So, the first question (Q1): is it officially specified that the contents of the string representations can have arbitrary contents? Q2: Next, even though I have set both fields to have the same semantic versioning 2.0-formatted version string, only the product version appears to be affected. This is strange since both fields have the same specification that they should contain a string but only one of them is actually alternated. Also both fields don't explicitly state that the VALUE "FileVersion" field can be assigned any string value, but an explicit example is given of such value containing characters different from 0-9 and .:

5.00.RC2

Thus again the restriction over the file version field compared to the product version one is paradoxical. The third question (Q3): is there a more detailed specification and reference for the VERSIONINFO resouce, which provides the full set of possible parameters and parameter values? Currently, I don't see any description and details about the possible values of the FILEFLAGS property: (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG). Here a value of interest is the VER_PRERELEASE one which matches the meaning of the PRERELEASE version part in the semantic versioning 2.0 specification.

答:
The version information in a PE file starts with a fixed block (VS_FIXEDFILEINFO) followed by any number of freeform strings.

The string and flag combinations are not really verified anywhere and even the documentation cannot make up its mind about which strings are required:

VS_FF_PRIVATEBUILD File was not built using standard release procedures. If this value is given, the StringFileInfo block must contain a PrivateBuild string.

VS

VS_FF_PRIVATEBUILD The file was not built using standard release procedures. If this flag is set, the StringFileInfo structure should contain a PrivateBuild entry.

Q1:

An arbitrary Unicode string. The szKey member can be one or more of the following values. These values are guidelines only...

Q2:

Some applications/fields display the number from the fixed block and some use the "standard" strings.

Q3:

Contains a bitmask that specifies the Boolean attributes of the file. This member can include one or more of the following values...

Body:
all. Currently, I want to set the version of a Windows' application (exe), dynamically-linked library (dll) or statically-linked library (lib) to a one using not the standard version format <major>.<minor>.<patch>.<build> (example: 3.2.0.73) but the semantic versioning 2.0's one (example: 3.2.0-RC3+73). Looking at the specifications of the version information resource (VERSIONINFO) both the FILEVERSION and the PRODUCTVERSION fields consist of:

two 32-bit integers, defined by four 16-bit integers

Hence, both version fields should be specified as having 4 version segments/parts/numbers where each of them is 16-bit (unsigned short integer) wide:

#define VER_FILEVERSION             3,10,349,0
#define VER_FILEVERSION_STR         "3.10.349.0\0"

#define VER_PRODUCTVERSION          3,10,0,0
#define VER_PRODUCTVERSION_STR      "3.10\0"

VS_VERSION_INFO VERSIONINFO
FILEVERSION     VER_FILEVERSION
PRODUCTVERSION  VER_PRODUCTVERSION
FILEFLAGSMASK   VS_FFI_FILEFLAGSMASK
FILEFLAGS       (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG)

// ...

BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904E4"
        BEGIN
            VALUE "CompanyName",      VER_COMPANYNAME_STR
            VALUE "FileDescription",  VER_FILEDESCRIPTION_STR
            VALUE "FileVersion",      VER_FILEVERSION_STR

            // ...

            VALUE "ProductVersion",   VER_PRODUCTVERSION_STR
        END
    END

    // ...
END

The situation is different about the string variants of the corresponding fields. Scanning the same specification near the bottom and more particularly the section:

Remarks -> string-name

what becomes obvious is that those string representations of the 4-segment 16-bit file and product versions, could contain any characters:

FileVersion | Version number of the file. For example, "3.10" or "5.00.RC2". This string is required.

...

ProductVersion | Version of the product with which the file is distributed. For example, "3.10" or "5.00.RC2". This string is required.

So, the first question (Q1): is it officially specified that the contents of the string representations can have arbitrary contents? Q2: Next, even though I have set both fields to have the same semantic versioning 2.0-formatted version string, only the product version appears to be affected. This is strange since both fields have the same specification that they should contain a string but only one of them is actually alternated. Also both fields don't explicitly state that the VALUE "FileVersion" field can be assigned any string value, but an explicit example is given of such value containing characters different from 0-9 and .:

5.00.RC2

Thus again the restriction over the file version field compared to the product version one is paradoxical. The third question (Q3): is there a more detailed specification and reference for the VERSIONINFO resouce, which provides the full set of possible parameters and parameter values? Currently, I don't see any description and details about the possible values of the FILEFLAGS property: (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG). Here a value of interest is the VER_PRERELEASE one which matches the meaning of the PRERELEASE version part in the semantic versioning 2.0 specification.


来源: stackexchange

问:
Docker for windows issue while installing and running
I have been trying to install Docker for windows in Windows 10 pro edition but I am getting always error in cmd or powershell when I type docker info I am getting result like this

error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.26/info: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

I have installed using InstallDocker.msi file but not able to fix this issue. I dont have any VM or Virtual Box running and I have make sure that Hyper-V and Virtualisation has been enabled in my PC. Please help me in this issue.

Thanks In Advance.

答:
Did the installation end successfully with the Docker welcome window?
If not, probably something went wrong during the installation.
You can either reinstall it or try to follow answers in this issue:
https://github.com/docker/docker/issues/22338</p>

ContentLicense: CC BY-SA 3.0


问:
Django 1.7 - makemigrations not detecting changes
As the title says, I can't seem to get migrations working.

The app was originally under 1.6, so I understand that migrations won't be there initially, and indeed if I run python manage.py migrate I get:

```<code>Operations to perform:
  Synchronize unmigrated apps: myapp
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  No migrations to apply.
</code>```

If I make a change to any models in myapp, it still says unmigrated, as expected.

But if I run python manage.py makemigrations myapp I get:

```<code>No changes detected in app 'myapp'
</code>```

Doesn't seem to matter what or how I run the command, it's never detecting the app as having changes, nor is it adding any migration files to the app.

Is there any way to force an app onto migrations and essentially say "This is my base to work with" or anything? Or am I missing something?

My database is a PostgreSQL one if that helps at all.

答:
Maybe that can help someone, I had the same problem.

I've already created two tables with the serializer class and the views.
So when I wanted to updated, I had this error.

I followed this steps:

I made .\manage.py makemigrations app

I executed .\manage.py migrate

I erased both tables of my models.py

I erased all reference to my tables from serializer and view class.

I executed step 1 and 2.

I retrieved my changes just in the models.py

I executed again step 5.

I restored all my changes.

If you're working with Pycharm, local history is very helpfull.

Body:
As the title says, I can't seem to get migrations working.

The app was originally under 1.6, so I understand that migrations won't be there initially, and indeed if I run python manage.py migrate I get:

Operations to perform:
  Synchronize unmigrated apps: myapp
  Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  No migrations to apply.

If I make a change to any models in myapp, it still says unmigrated, as expected.

But if I run python manage.py makemigrations myapp I get:

No changes detected in app 'myapp'

Doesn't seem to matter what or how I run the command, it's never detecting the app as having changes, nor is it adding any migration files to the app.

Is there any way to force an app onto migrations and essentially say "This is my base to work with" or anything? Or am I missing something?

My database is a PostgreSQL one if that helps at all.


问:
Spread Syntax with Map and Filter
I found this interesting problem and wanted to share with you guys.
The question is :

```<code>[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]
</code>```

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

ContentLicense: CC BY-SA 4.0

Title: Spread Syntax with Map and Filter

Body:
I found this interesting problem and wanted to share with you guys.
The question is :

[...[0,1,...[-1,0,1].map((x)=> x+1)].filter((x)=>x)),7]

I easily solved the first section upto the filter as [0,1,(-1+1),(0+1),(1+1)] = [0,1,0,1,2].

I was surprised to find the 7 hanging at the end. I thought it was some typo but copying the problem into the  console gave me [1,1,2,7]. I couldn't quite understand 2 things.

why were the 0's left out of filter

what's the 7 doing there

Body:
The code evaluates in the following steps:

[...[0, 1, ...[-1, 0, 1].map((x)=>x+1)].filter((x)=>x)), 7] // map
[...[0, 1, ...[(x=>x+1)(-1), (x=>x+1)(0), (x=>x+1)(1)]].filter((x)=>x)), 7] // function application
[...[0, 1, ...[0, 1, 2]].filter((x)=>x)), 7] // spread
[...[0, 1, 0, 1, 2].filter((x)=>x)), 7] // filter
[...[...(x=>x)(0)?[0]:[], ...(x=>x)(1)?[1]:[], ...(x=>x)(0)?[0]:[], ...(x=>x)(1)?[1]:[], ...(x=>x)(2)?[2]:[]], 7] // function application
[...[...0?[0]:[], ...1?[1]:[], ...0?[0]:[], ...1?[1]:[], ...2?[2]:[]], 7] // conditional
[...[...[], ...[1], ...[], ...[1], ...[2]], 7] // spread (from filter)
[...[1, 1, 2], 7] // spread
[1, 1, 2, 7]


问:
How to add screen sharing to programmable video?
Hi I am developing a virtual classroom for a E-Learning platform in sweden and Currently I am using programmable video from Twilio to handle the audio and video feed.

It is working perfectly how I want it to but right now what I want to add is screen sharing.

I can't find anything on how to add it to the "room", is there anywhere I can go to do so?

I have looked into webrtc experiments a bit but is it easy to implement with twilio?

Thanks

答:
A web app/chrome extension is required for this. The extension is very lightweight and just prompts the user to escalate permissions to enable Chrome's screen sharing functionality. Since Chrome extensions are associated with specific domains, you'll need to publish and manage your own extension but you can basically just copy/paste it from the given template.

Here is Twilio's guide: https://www.twilio.com/docs/api/video/screen-capture-chrome


问:
How to get books listed in someone's Facebook profile in Graph API Explorer
I've been reading FBSDK docs and found the Graph API Explorer, which I think would be a great way to test before I implement this feature in my iOS code. So I go here:

https://developers.facebook.com/docs/graph-api/reference/user/books/

and click on Graph API Explorer. Once in the Explorer page, I click on GetToken...Get User Access Token, and just to be sure I select ALL permissions.

In the url:

```<code>{user-id}/books
</code>```

I replace {user-id} with the actual 15-digit long ID of my account and I click Submit.

I see this as a result:

```<code>{
  "data": [
  ]
}
</code>```

What's going on? Why can't I see my books? According to the documentation I should see "books listed in my Facebook profile". And I do have 2 books listed in my profile.

BTW - I went to my profile and made sure I share the books with Public, so now it says: "Share books you like on Facebook with:  Public", but it didn't help - still get an empty array when requesting .

Thanks in advance!

答:
There was an answer earlier today but then it got deleted. The correct path that provides the books from user profile is:

```<code>me/books.reads
</code>```

with permission

```<code>user_actions.books
</code>```

Body:
I've been reading FBSDK docs and found the Graph API Explorer, which I think would be a great way to test before I implement this feature in my iOS code. So I go here:

https://developers.facebook.com/docs/graph-api/reference/user/books/

and click on Graph API Explorer. Once in the Explorer page, I click on GetToken...Get User Access Token, and just to be sure I select ALL permissions.

In the url:

{user-id}/books

I replace {user-id} with the actual 15-digit long ID of my account and I click Submit.

I see this as a result:

{
  "data": [
  ]
}

What's going on? Why can't I see my books? According to the documentation I should see "books listed in my Facebook profile". And I do have 2 books listed in my profile.

BTW - I went to my profile and made sure I share the books with Public, so now it says: "Share books you like on Facebook with:  Public", but it didn't help - still get an empty array when requesting .

Thanks in advance!

Body:
There was an answer earlier today but then it got deleted. The correct path that provides the books from user profile is:

me/books.reads

with permission

user_actions.books


问:
Undraggable After Sorting
Please take a look: http://jsfiddle.net/JeaffreyGilbert/VkghS/25/

Currently we can drag the bars to the left/right well. The problem is after we sort the color names, we cannot drag (not sort) the bars.

Any help would be appreciated, thank you.

答:
the colornames sortable update handler should include a reinitialization of the draggable.  the thing is you're adding new bars that didn't exist on document ready.  so, it should look something like this:</p>

```<code>   $( ".colorNames" ).sortable({
        handle: '.handle',
        update : function () {
            var barsOrder = $('.gantt').sortable('serialize');
            var namesOrder = $('.colorNames').sortable('serialize');

            barsTemp = $('<div></div>');

            colorNames = namesOrder.split('&');
            for (i = 0; i < colorNames.length; i++) {
                bar = $('#barWrap_' + (colorNames[i].split("="))[1]);
                barsTemp.append(bar);
            }

            $('.gantt').append(barsTemp.html());
            $( ".bar" ).draggable({
                grid: [ 20, 0 ]
            });
        }
    });
</code>```

ContentLicense: CC BY-SA 2.5

Title: Undraggable After Sorting

Body:
the colornames sortable update handler should include a reinitialization of the draggable.  the thing is you're adding new bars that didn't exist on document ready.  so, it should look something like this:

   $( ".colorNames" ).sortable({
        handle: '.handle',
        update : function () {
            var barsOrder = $('.gantt').sortable('serialize');
            var namesOrder = $('.colorNames').sortable('serialize');

            barsTemp = $('<div></div>');

            colorNames = namesOrder.split('&');
            for (i = 0; i < colorNames.length; i++) {
                bar = $('#barWrap_' + (colorNames[i].split("="))[1]);
                barsTemp.append(bar);
            }

            $('.gantt').append(barsTemp.html());
            $( ".bar" ).draggable({
                grid: [ 20, 0 ]
            });
        }
    });


问:
How to install xgboost in python on MacOS?
I am a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next: </p>

```<code>pip install xgboost -
</code>```

答:
It's a little more complicated if you want to use multi-threading.  For the record, I am using a Mac with OS X 10.10 (Yosemite).  It took me a while to work through the various issues, but it is now running nicely in my Anaconda (Py36) environment.

For multi-threading you need to do the following first (install homebrew if you have not done so):

```<code>brew install gcc --without-multilib
</code>```

You might get some warnings to unlink directories or delete them if you have other versions installed; follow the warnings/instructions.

Next get the xgboost files from Github.  I downloaded it to Anaconda/pkgs directory.

```<code>git clone --recursive https://github.com/dmlc/xgboost
</code>```

The next series of steps differ from the documentation on the xgboost site, and I cobbled it together from lots of sources and also experimenting.  The problem is that some key lines in the make files are commented out and also not fully specified.

```<code>cd xgboost; cp make/config.mk ./config.mk
</code>```

Now, use your favorite editor (I used vi), and go into the file that you copied from /make to /xgboost

```<code>vi config.mk
</code>```

Uncomment the lines near the top of the file:

export CC = gcc

export CXX = g++

Change them to the following:

```<code>export CC = gcc-6

export CXX = g++-6
</code>```

It is possible that simply uncommenting the lines solves the problem.  It did not for me; I needed to add the -6 to both lines.  Save the file.

Also, make changes to the file xgboost/Makefile; change lines:

```<code>export CC = $(if $(shell which clang), clang, gcc)
...
...
export CXX = $(if $(shell which clang++), clang++, g++)
</code>```

to the following:

```<code>export CC = $(if $(shell which clang), clang, gcc-6)
...
...
export CXX = $(if $(shell which clang++), clang++, g++-6)
</code>```

Again, I used vi for this editing.

Save the file and now you need to run a cleaning step since you changed the Makefile.

```<code>make clean_all && make -j4
</code>```

This should configure it cleanly and build the library.  You still need to install it.

```<code>cd python-package; python setup.py install
</code>```

Now restart Python/Anaconda and you should be able to import the library.

Body:
I am a newbie and learning python. Can someone help me- how to install xgboost in python. Im using Mac 10.11. I read online and did the below mentioned step, but not able to decode what to do next:

pip install xgboost -

Body:
It's a little more complicated if you want to use multi-threading.  For the record, I am using a Mac with OS X 10.10 (Yosemite).  It took me a while to work through the various issues, but it is now running nicely in my Anaconda (Py36) environment.

For multi-threading you need to do the following first (install homebrew if you have not done so):

brew install gcc --without-multilib

You might get some warnings to unlink directories or delete them if you have other versions installed; follow the warnings/instructions.

Next get the xgboost files from Github.  I downloaded it to Anaconda/pkgs directory.

git clone --recursive https://github.com/dmlc/xgboost

The next series of steps differ from the documentation on the xgboost site, and I cobbled it together from lots of sources and also experimenting.  The problem is that some key lines in the make files are commented out and also not fully specified.

cd xgboost; cp make/config.mk ./config.mk

Now, use your favorite editor (I used vi), and go into the file that you copied from /make to /xgboost

vi config.mk

Uncomment the lines near the top of the file:

export CC = gcc

export CXX = g++

Change them to the following:

export CC = gcc-6

export CXX = g++-6

It is possible that simply uncommenting the lines solves the problem.  It did not for me; I needed to add the -6 to both lines.  Save the file.

Also, make changes to the file xgboost/Makefile; change lines:

export CC = $(if $(shell which clang), clang, gcc)
...
...
export CXX = $(if $(shell which clang++), clang++, g++)

to the following:

export CC = $(if $(shell which clang), clang, gcc-6)
...
...
export CXX = $(if $(shell which clang++), clang++, g++-6)

Again, I used vi for this editing.

Save the file and now you need to run a cleaning step since you changed the Makefile.

make clean_all && make -j4

This should configure it cleanly and build the library.  You still need to install it.

cd python-package; python setup.py install

Now restart Python/Anaconda and you should be able to import the library.


问:
How do you update links in excel based on specific text in the link using VBA?
How do you update links in excel based on specific text in the link using VBA?
Using Office 2016

I have 40 locations with independent servers for each location.

All of the file names are the same at each location and saved in the same folder with only the location name being different.

For example:

```<code>Store 1\Schedules\2017\04_01_17.xlxb
Store 2\Schedules\2017\04_01_17.xlxb
Store 3\Schedules\2017\04_01_17.xlxb
</code>```

Each location has a schedule for each week of the year as well as several previous years.

The issue is that the Master recap file that reaches out to each one of these files has to be manipulated currently by editing links one at a time if I wanted to retrieve data for only the 04_01_17 week.

If the entire file was to be enabled it would pull every linked file for the entire year and several previous years and take hours to complete.

What I was looking for was VBA code that would ask for text that is contained in the link and would pull all files that matched.

For Example

```<code>"Contains"
Answer=04_01_17
</code>```

Thanks in Advance

Brad

答:
These two subroutines below show you how to view / manipulate links in a file.
The key part you are looking for is ActiveWorkbook.LinkSources(xlExcelLinks) to get an array with the list of links, and ActiveWorkbook.ChangeLink to ... change the link.

```<code>Sub gen_links()
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(aLinks) Then
    For i = 1 To UBound(aLinks)
        MsgBox "Link " & i & ":" & Chr(13) & aLinks(i)
    Next i
End If
End Sub

Sub swap_links1()
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(aLinks) Then
    For i = 1 To UBound(aLinks)
    If aLinks(i) = "C:\tests\2017(1)\Test1.xlsx" Then
        ActiveWorkbook.ChangeLink "C:\tests\2017(1)\Test1.xlsx", "C:\tests\2017(2)\Test2.xlsx", xlExcelLinks
    End If
    If aLinks(i) = "C:\tests\2017(2)\Test2.xlsx" Then
        ActiveWorkbook.ChangeLink "C:\tests\2017(2)\Test2.xlsx", "C:\tests\2017(1)\Test1.xlsx", xlExcelLinks
    End If
    MsgBox "Link " & i & ":" & Chr(13) & aLinks(i)
    Next i
End If
End Sub
</code>```

ChangeLink documentation

LinkSources documentation

You can utilise this by building an if-test for every possible option, or more sensibly, creating a variable and doing an if-not-test. E.g.

```<code>My_Store_Name = "Store 1"
My_Year_Name = "2017"
My_File_Name = "04_01_17"
My_Test_file = My_Store_Name & "\Schedules\"  & My_Year_Name & "\" & My_File_Name & ".xlxb"
If aLinks(i) <> My_Test_file Then
</code>```

Body:
How do you update links in excel based on specific text in the link using VBA?
Using Office 2016

I have 40 locations with independent servers for each location.

All of the file names are the same at each location and saved in the same folder with only the location name being different.

For example:

Store 1\Schedules\2017\04_01_17.xlxb
Store 2\Schedules\2017\04_01_17.xlxb
Store 3\Schedules\2017\04_01_17.xlxb

Each location has a schedule for each week of the year as well as several previous years.

The issue is that the Master recap file that reaches out to each one of these files has to be manipulated currently by editing links one at a time if I wanted to retrieve data for only the 04_01_17 week.

If the entire file was to be enabled it would pull every linked file for the entire year and several previous years and take hours to complete.

What I was looking for was VBA code that would ask for text that is contained in the link and would pull all files that matched.

For Example

"Contains"
Answer=04_01_17

Thanks in Advance

Brad

Body:
These two subroutines below show you how to view / manipulate links in a file.
The key part you are looking for is ActiveWorkbook.LinkSources(xlExcelLinks) to get an array with the list of links, and ActiveWorkbook.ChangeLink to ... change the link.

Sub gen_links()
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(aLinks) Then
    For i = 1 To UBound(aLinks)
        MsgBox "Link " & i & ":" & Chr(13) & aLinks(i)
    Next i
End If
End Sub

Sub swap_links1()
aLinks = ActiveWorkbook.LinkSources(xlExcelLinks)
If Not IsEmpty(aLinks) Then
    For i = 1 To UBound(aLinks)
    If aLinks(i) = "C:\tests\2017(1)\Test1.xlsx" Then
        ActiveWorkbook.ChangeLink "C:\tests\2017(1)\Test1.xlsx", "C:\tests\2017(2)\Test2.xlsx", xlExcelLinks
    End If
    If aLinks(i) = "C:\tests\2017(2)\Test2.xlsx" Then
        ActiveWorkbook.ChangeLink "C:\tests\2017(2)\Test2.xlsx", "C:\tests\2017(1)\Test1.xlsx", xlExcelLinks
    End If
    MsgBox "Link " & i & ":" & Chr(13) & aLinks(i)
    Next i
End If
End Sub

ChangeLink documentation

LinkSources documentation

You can utilise this by building an if-test for every possible option, or more sensibly, creating a variable and doing an if-not-test. E.g.

My_Store_Name = "Store 1"
My_Year_Name = "2017"
My_File_Name = "04_01_17"
My_Test_file = My_Store_Name & "\Schedules\"  & My_Year_Name & "\" & My_File_Name & ".xlxb"
If aLinks(i) <> My_Test_file Then


问:
Check for ascending order of a list in Racket
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

```<code>(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))
</code>```

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

答:
If you write down the properties of an ascending list in bullet form;

An ascending list is either

the empty list, or

a one-element list, or

a list where

the first element is smaller than the second element, and

the tail of the list is ascending

you can wind up with a pretty straight translation:

```<code>(define (ascending? ls)
  (or (null? ls)
      (null? (rest ls))
      (and (< (first ls) (first (rest ls)))
           (ascending? (rest ls)))))
</code>```

Body:
I'm new to racket and trying to write a function that checks if a list is in strictly ascending order.

'( 1 2 3) would return true
'(1 1 2) would return false (repeats)
'(3 2 4) would return false

My code so far is:
Image of code

(define (ascending? 'list)
   (if (or (empty? list) (= (length 'list) 1)) true
      (if (> first (first (rest list))) false
          (ascending? (rest list)))))

I'm trying to call ascending? recursively where my base case is that the list is empty or has only 1 element (then trivially ascending).

I keep getting an error message when I use check-expect that says "application: not a procedure."

Body:
If you write down the properties of an ascending list in bullet form;

An ascending list is either

the empty list, or

a one-element list, or

a list where

the first element is smaller than the second element, and

the tail of the list is ascending

you can wind up with a pretty straight translation:

(define (ascending? ls)
  (or (null? ls)
      (null? (rest ls))
      (and (< (first ls) (first (rest ls)))
           (ascending? (rest ls)))))


问:
Array of observables type
I am just curious, what will be the correct type of Observables array?

I tried:

```<code>let myObservables: Observable[] = new Array();
let myObservables: Observable<Array<any>> = new Array();
let myObservables: Observable<[]> = new Array();
</code>```

but none of them are working.

I just want an array in which i can push observables so that i can pass it to Observable.forkJoin(myObservables)

答:
Use:

let myObservables: Observable[] = [];

Title: Array of observables type

Body:
I am just curious, what will be the correct type of Observables array?

I tried:

let myObservables: Observable[] = new Array();
let myObservables: Observable<Array<any>> = new Array();
let myObservables: Observable<[]> = new Array();

but none of them are working.

I just want an array in which i can push observables so that i can pass it to Observable.forkJoin(myObservables)


问:
Display none fails while page is rendering
Considering I have a basic nav like list:

```<code><nav>
  <ul>
    <li id="unhide" style="display:none;"></li>
    <li></li>
    <li></li>
  </ul>
</nav>
</code>```

And some jquery...

```<code>jQuery(document).ready(function($) {
  $("#unhide").on('mouseenter', function() {
    $(this).css('display', 'block');
  }).on('mouseleave', function() {
    $(this).css('display', 'none');
  })
})
</code>```

Why would the menu temporarily show while the page is loading but when the loading has completed, it's properly hidden. How can I fix that?

答:
I would suggest this

```<code>    jQuery(document).ready(function($) {
$("#unhide").mouseover(function() {
$(this).attr("class", '');
}).mouseout(function() {
$(this).attr("class", 'hide');
});
});
</code>```

css

If you wonder why i did not apply the styles to the id directly. Its because you might want to target it with jquery for something else but it would also work by using #unhide instead of .hide

```<code>.hide {
   /* you can use the height 0.1 if you dont want
   it in layout else you can just erase the height proprety */
   height:0.1px;

   /* 0 opacity works */
   opacity:0;
}
</code>```

html

```<code><nav>
  <ul>
    <li id="unhide" class='hide'>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</nav>
</code>```

You could also use the css attributes on the element directly like this

```<code><nav>
      <ul>
        <li id="unhide" style="height:0.1px;
         opacity:0;">One</li>
        <li>As said before the height is not useful</li>
        <li>Three</li>
      </ul>
    </nav>
</code>```

and jquery

```<code>jQuery(document).ready(function($) {
    $("#unhide").mouseover(function() {
    $(this).css("opacity", '1');
    // if height
    $(this).css("height", '');
    }).mouseout(function() {
    $(this).css("opacity", '0');
    //if height
    $(this).css("height", '0.1px');
    });
    });
</code>```

I think that should work, and i also think that the problems comes from the fact that display none actually prevents mouse hover event listeners

https://jsfiddle.net/qh7gwecc/2/

Body:
Considering I have a basic nav like list:

And some jquery...

jQuery(document).ready(function($) {
  $("#unhide").on('mouseenter', function() {
    $(this).css('display', 'block');
  }).on('mouseleave', function() {
    $(this).css('display', 'none');
  })
})

Why would the menu temporarily show while the page is loading but when the loading has completed, it's properly hidden. How can I fix that?

Body:
I would suggest this

    jQuery(document).ready(function($) {
$("#unhide").mouseover(function() {
$(this).attr("class", '');
}).mouseout(function() {
$(this).attr("class", 'hide');
});
});

css

If you wonder why i did not apply the styles to the id directly. Its because you might want to target it with jquery for something else but it would also work by using #unhide instead of .hide

.hide {
   /* you can use the height 0.1 if you dont want
   it in layout else you can just erase the height proprety */
   height:0.1px;

   /* 0 opacity works */
   opacity:0;
}

html

<nav>
  <ul>
    <li id="unhide" class='hide'>One</li>
    <li>Two</li>
    <li>Three</li>
  </ul>
</nav>

You could also use the css attributes on the element directly like this

<nav>
      <ul>
        <li id="unhide" style="height:0.1px;
         opacity:0;">One</li>
        <li>As said before the height is not useful</li>
        <li>Three</li>
      </ul>
    </nav>

and jquery

jQuery(document).ready(function($) {
    $("#unhide").mouseover(function() {
    $(this).css("opacity", '1');
    // if height
    $(this).css("height", '');
    }).mouseout(function() {
    $(this).css("opacity", '0');
    //if height
    $(this).css("height", '0.1px');
    });
    });

I think that should work, and i also think that the problems comes from the fact that display none actually prevents mouse hover event listeners

https://jsfiddle.net/qh7gwecc/2/


问:
Poor performance of long list rendering in Angular2
I have an application with a history stream, containing user actions. The history is displayed by days or whole weeks. During one day there is approximately around 400-2k of events to display.

There are few types of actions that may occur and each one is displayed differently (e.g. comment or object modification). Therefore there is some logic in each loop iteration to determinate the final structure of each element.

The problem is that it lots of time to render, ~1300 elements renders around 6s. For me it is pretty long time to wait for such thing. I have tried to optimise the code to do the required minimum, but still the best I could get is 6s for ~1300 elements.

The other bigger problem with that is freezed browser during the rendering which is not acceptable for such long time.

I'm not sure if I have done something wrong or I have found a week spot of Angular2 which is not possible to resolve. So any hint is welcome.
I'm not interested in advices like: use pagination or use infinite scroll, I'm am looking for a way to make it work faster and smother.

I will also add that previously the history was rendered on the servers side and putting the result into the DOM was super quick, no matter of the number of events. Further screenshots also shows that the real rendering time is just a very small part of the process.

I have prepared simplified version of the rendering code in the plunker which shows the problem:
http://plnkr.co/edit/QrYmYezmlV3MkQV5bOA8?p=preview

The main rendering parts:

Root ngFor element

```<code><div class="history-stream">
  <div *ngFor="let action of history"
       class="activity" [ngClass]="{'first-of-user': action.firstOfUser, 'last-of-user': action.lastOfUser}">
    <p class="date" *ngIf="action.firstOfDay">{{ action.date | date:'mediumDate' }}</p>
    <div class="user-entry" [ngSwitch]="action.type">
      <comment *ngSwitchCase="'comment'" [object]="action"></comment>
      <modified *ngSwitchCase="'modified'" [object]="action"></modified>
    </div>
  </div>
</div>
</code>```

Comment component:

```<code><div class="entry comment" [ngClass]="{'comment-resolved': object.extra.is_resolved}">
  <a href="{{ getDeleteUrl(object.extra.comment_id) }}" data-target="metabase-modal-ajax" class="comment-action">Delete</a>
  <a href="#" class="comment-action" *ngIf="!object.extra.is_resolved" (click)="resolveComment($event)">Mark as resolved</a>
  <a href="#" class="comment-action" *ngIf="object.extra.is_resolved" (click)="unResolveComment($event)">Unresolve</a>
  <p class="action" [innerHTML]="object.action"></p>
  <p>{{ object.comment }}</p>
  <small class="text-muted">{{ object.date | date:'shortTime' }} <span class="dot">·</span> {{ object.date | date:'shortTime' }}</small>
</div>
</code>```

Modified event component:

```<code><div class="entry modified">
  <p class="action" [innerHTML]="object.action"></p>
  <ul class="changes list-unstyled">
    <li *ngFor="let change of object.changes">
      <span class="attribute">{{ change.attribute }}:</span>
      <modified-value [change]="change.from"></modified-value>
      <span class="arrow">→</span>
      <modified-value [change]="change.to"></modified-value>
      <small class="time text-muted">{{ change.date | date:'shortTime' }} <span class="dot">·</span> {{ change.date | date:'shortTime' }}</small>
    </li>
  </ul>
</div>
</code>```

And modified-value component:

```<code><span [ngSwitch]="getChangeType()">
  <span *ngSwitchCase="'complex'">
    <span *ngFor="let item of change">
      <span class="badge">{{ item.tag }}</span>
      <span [ngSwitch]="isArray(item.value)">
        <span *ngSwitchCase="true">
          <span *ngFor="let valueItem of item.value" class="value tag">{{ valueItem }}</span>
          <span *ngIf="isEmpty(item.value)" class="value text-muted">None</span>
        </span>
        <span *ngSwitchCase="false">
          <span *ngIf="item.value" class="value">{{ item.value }}</span>
          <span *ngIf="!item.value" class="value text-muted">None</span>
        </span>
      </span>
    </span>
  </span>
  <span *ngSwitchDefault>
    <span *ngIf="change" class="value">{{ change }}</span>
    <span *ngIf="!change" class="value text-muted">None</span>
  </span>
</span>
</code>```

Also a few screenshots of profiles recording:

答:
There are a few good ways to improve performance in Angular.  I would suggest you read this: http://blog.mgechev.com/2015/03/02/immutability-in-angularjs-immutablejs/  on using immutable data structures to improve performance.

Let me know if you have any questions after reading.

Body:
I have an application with a history stream, containing user actions. The history is displayed by days or whole weeks. During one day there is approximately around 400-2k of events to display.

There are few types of actions that may occur and each one is displayed differently (e.g. comment or object modification). Therefore there is some logic in each loop iteration to determinate the final structure of each element.

The problem is that it lots of time to render, ~1300 elements renders around 6s. For me it is pretty long time to wait for such thing. I have tried to optimise the code to do the required minimum, but still the best I could get is 6s for ~1300 elements.

The other bigger problem with that is freezed browser during the rendering which is not acceptable for such long time.

I'm not sure if I have done something wrong or I have found a week spot of Angular2 which is not possible to resolve. So any hint is welcome.
I'm not interested in advices like: use pagination or use infinite scroll, I'm am looking for a way to make it work faster and smother.

I will also add that previously the history was rendered on the servers side and putting the result into the DOM was super quick, no matter of the number of events. Further screenshots also shows that the real rendering time is just a very small part of the process.

I have prepared simplified version of the rendering code in the plunker which shows the problem:
http://plnkr.co/edit/QrYmYezmlV3MkQV5bOA8?p=preview

The main rendering parts:

Root ngFor element

{{ action.date | date:'mediumDate' }}

      <comment *ngSwitchCase="'comment'" [object]="action"></comment>
      <modified *ngSwitchCase="'modified'" [object]="action"></modified>

Comment component:

  Delete
  Mark as resolved
  Unresolve

{{ object.comment }}

  {{ object.date | date:'shortTime' }} · {{ object.date | date:'shortTime' }}

Modified event component:

      {{ change.attribute }}:
      <modified-value [change]="change.from"></modified-value>
      →
      <modified-value [change]="change.to"></modified-value>
      {{ change.date | date:'shortTime' }} · {{ change.date | date:'shortTime' }}

And modified-value component:

      {{ item.tag }}

          {{ valueItem }}
          None

          {{ item.value }}
          None

    {{ change }}
    None

Also a few screenshots of profiles recording:


问:
Java program not liking the word "Scanner"
```<code>import java.lang.*;
import java.util.*;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;

public class Test
{
  public static void main(String[] args) throws IOException
  {
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    boolean[] correctAnswers = new boolean[20];
    infile.close();
  }
}
</code>```

I'm getting these errors for some reason:

```<code>C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    ^
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
                         ^
2 errors

Tool completed with exit code 1
</code>```

I have no idea what's going on.
Help is appreciated, Thanks.

答: Which version of Java are you using? Scanner was added in 1.5.

Body:
import java.lang.*;
import java.util.*;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.IOException;

public class Test
{
  public static void main(String[] args) throws IOException
  {
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    boolean[] correctAnswers = new boolean[20];
    infile.close();
  }
}

I'm getting these errors for some reason:

C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
    ^
C:\Users\Rawr\Documents\Test.java:11: cannot resolve symbol
symbol  : class Scanner
location: class Test
    Scanner infile = new Scanner(new FileReader("historyGrades.txt"));
                         ^
2 errors

Tool completed with exit code 1

I have no idea what's going on.
Help is appreciated, Thanks.


问:
Swift: Binary search for standard array?
I have a sorted array and want to do binary search on it.

So I'm asking if something is already available in Swift library like sort etc.? Or is there a type independend version available?

Of course I could write it by my own, but I like to avoid reinventing the wheel again.

答:
Here's a full example with several test cases for Swift 3.1. There is no chance that this is faster than the default implementation, but that's not the point. Array extension is at the bottom:

```<code>//  BinarySearchTests.swift
//  Created by Dan Rosenstark on 3/27/17
import XCTest
@testable import SwiftAlgos

class BinarySearchTests: XCTestCase {

    let sortedArray : [Int] = [-25, 1, 2, 4, 6, 8, 10, 14, 15, 1000]

    func test5() {
        let traditional = sortedArray.index(of: 5)
        let newImplementation = sortedArray.indexUsingBinarySearch(of: 5)
        XCTAssertEqual(traditional, newImplementation)
    }

    func testMembers() {
        for item in sortedArray {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testMembersAndNonMembers() {
        for item in (-100...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testSingleMember() {
        let sortedArray = [50]
        for item in (0...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testEmptyArray() {
        let sortedArray : [Int] = []
        for item in (0...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }
}

extension Array where Element : Comparable {
    // self must be a sorted Array
    func indexUsingBinarySearch(of element: Element) -> Int? {
        guard self.count > 0 else { return nil }
        return binarySearch(for: element, minIndex: 0, maxIndex: self.count - 1)
    }

    private func binarySearch(for element: Element, minIndex: Int, maxIndex: Int) -> Int? {
        let count = maxIndex - minIndex + 1
        // if there are one or two elements, there is no futher recursion:
        // stop and check one or both values (and return nil if neither)
        if count == 1 {
            return element == self[minIndex] ? minIndex : nil
        } else if count == 2 {
            switch element {
                case self[minIndex]: return minIndex
                case self[maxIndex]: return maxIndex
                default: return nil
            }
        }

        let breakPointIndex = Int(round(Double(maxIndex - minIndex) / 2.0)) + minIndex
        let breakPoint = self[breakPointIndex]

        let splitUp = (breakPoint < element)
        let newMaxIndex : Int = splitUp ? maxIndex : breakPointIndex
        let newMinIndex : Int = splitUp ? breakPointIndex : minIndex

        return binarySearch(for: element, minIndex: newMinIndex, maxIndex: newMaxIndex)
    }
}
</code>```

This is quite homemade, so... caveat emptor. It does work and does do binary search.

Body:
Here's a full example with several test cases for Swift 3.1. There is no chance that this is faster than the default implementation, but that's not the point. Array extension is at the bottom:

//  BinarySearchTests.swift
//  Created by Dan Rosenstark on 3/27/17
import XCTest
@testable import SwiftAlgos

class BinarySearchTests: XCTestCase {

    let sortedArray : [Int] = [-25, 1, 2, 4, 6, 8, 10, 14, 15, 1000]

    func test5() {
        let traditional = sortedArray.index(of: 5)
        let newImplementation = sortedArray.indexUsingBinarySearch(of: 5)
        XCTAssertEqual(traditional, newImplementation)
    }

    func testMembers() {
        for item in sortedArray {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testMembersAndNonMembers() {
        for item in (-100...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testSingleMember() {
        let sortedArray = [50]
        for item in (0...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }

    func testEmptyArray() {
        let sortedArray : [Int] = []
        for item in (0...100) {
            let traditional = sortedArray.index(of: item)
            let newImplementation = sortedArray.indexUsingBinarySearch(of: item)
            XCTAssertEqual(traditional, newImplementation)
        }
    }
}

extension Array where Element : Comparable {
    // self must be a sorted Array
    func indexUsingBinarySearch(of element: Element) -> Int? {
        guard self.count > 0 else { return nil }
        return binarySearch(for: element, minIndex: 0, maxIndex: self.count - 1)
    }

    private func binarySearch(for element: Element, minIndex: Int, maxIndex: Int) -> Int? {
        let count = maxIndex - minIndex + 1
        // if there are one or two elements, there is no futher recursion:
        // stop and check one or both values (and return nil if neither)
        if count == 1 {
            return element == self[minIndex] ? minIndex : nil
        } else if count == 2 {
            switch element {
                case self[minIndex]: return minIndex
                case self[maxIndex]: return maxIndex
                default: return nil
            }
        }

        let breakPointIndex = Int(round(Double(maxIndex - minIndex) / 2.0)) + minIndex
        let breakPoint = self[breakPointIndex]

        let splitUp = (breakPoint < element)
        let newMaxIndex : Int = splitUp ? maxIndex : breakPointIndex
        let newMinIndex : Int = splitUp ? breakPointIndex : minIndex

        return binarySearch(for: element, minIndex: newMinIndex, maxIndex: newMaxIndex)
    }
}

This is quite homemade, so... caveat emptor. It does work and does do binary search.


问:
Compare two Cells and Return Highest Value from third cells
Need help please. I am working on report which shows different names in coloumn A. I want to compare the two cells within the same coloumn and then display the highest value from COL B  into COL C:</p>

```<code>          COL A     COL B          COL C (OUTPUT RESULT REQUIRED)
Row 1     USA        $3             $7
Row 2     USA        $7             -
Row 3     Italy      $1             $1
Row 4     France     $9             $9
Row 5     France     $2             -
Row 6     France     $4             -
</code>```

答:
I will assume that you have a header row.  Use this formula:

```<code>=IF(A2<>A1,AGGREGATE(14,6,$B$2:$B$7/($A$2:$A$7=A2),1),"-")
</code>```

If you do not have a header row we need to do the IF a little different:

```<code>=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),AGGREGATE(14,6,$B$1:$B$6/($A$1:$A$6=A1),1),"-")
</code>```

Edit:

Also if you have Office 365 Excel then you can use MAXIFS() in place of the AGGREGATE:

```<code>=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),MAXIFS(B:B,A:A,A1),"-")
</code>```

Edit #2

If you are using an older version of Excel(2007 or later) then you will need to use the following array formula:

```<code>=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),MAX(IF($A$1:$A$6=A1,$B$1:$B$6)),"-")
</code>```

Being an array formula one must confirm with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done properly then Excel will put {} around the formula.

Body:
Need help please. I am working on report which shows different names in coloumn A. I want to compare the two cells within the same coloumn and then display the highest value from COL B  into COL C:

          COL A     COL B          COL C (OUTPUT RESULT REQUIRED)
Row 1     USA        $3             $7
Row 2     USA        $7             -
Row 3     Italy      $1             $1
Row 4     France     $9             $9
Row 5     France     $2             -
Row 6     France     $4             -

Body:
I will assume that you have a header row.  Use this formula:

=IF(A2<>A1,AGGREGATE(14,6,$B$2:$B$7/($A$2:$A$7=A2),1),"-")

If you do not have a header row we need to do the IF a little different:

=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),AGGREGATE(14,6,$B$1:$B$6/($A$1:$A$6=A1),1),"-")

Edit:

Also if you have Office 365 Excel then you can use MAXIFS() in place of the AGGREGATE:

=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),MAXIFS(B:B,A:A,A1),"-")

Edit #2

If you are using an older version of Excel(2007 or later) then you will need to use the following array formula:

=IF(OR(ROW()=1,A1<>INDEX(A:A,ROW()-1)),MAX(IF($A$1:$A$6=A1,$B$1:$B$6)),"-")

Being an array formula one must confirm with Ctrl-Shift-Enter instead of Enter when exiting edit mode.  If done properly then Excel will put {} around the formula.


问:
Why Admin don't see Profile edit option?
I am new to the SalesForce. As an administrator I should be able to see edit page. Not sure why edit page not coming ?

Why I cant see edit, only clone. I am Administrator to this org.

答: Could you confirm that "Enhanced Profile User Interface" is disabled?  Go to Setup -> Customize -> User Interface page.  Under the "Setup" section, make sure the "Enable Enhanced Profile User Interface" is unchecked.</p>


问:
SPARQL, RDF & processing Data
I'm new to this entire semantics stuff, and i've been plunged into a project which requires me to use the SPARQL endpoint from dbpedia to retrieve information about certain things such as a City for example. The idea is that my application collects a few of these keywords (which are predefined, such as City, Country & Region) and rely on dbpedia to get some sensible information about this.

After fiddling around with the SPARQL endpoint for some time, I came up with the following query:

```<code>PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX prop: <http://dbpedia.org/property/>

SELECT ?city
WHERE {
?city prop:name "X"@en;
a dbo:PopulatedPlace
}
</code>```

Where X stands for the name of the city that I'm trying to get information about. When I run this query against the SPARQL endpoint, I receive a URI in a RDF structure that points to a RDF store on DBPedia (at least that's how I interpret it, please correct me if I'm wrong)

The returned result for the City "Antwerpen" looks like this:

```<code><rdf:RDF><rdf:Description rdf:nodeID="rset"><rdf:type rdf:resource="http://www.w3.org/2005/sparql-results#ResultSet"/><res:resultVariable>city</res:resultVariable><res:solution rdf:nodeID="r0"><res:binding rdf:nodeID="r0c0"><res:variable>city</res:variable><res:value rdf:resource="http://dbpedia.org/resource/Antwerp"/></res:binding></res:solution></rdf:Description></rdf:RDF>
</code>```

I'm using Ruby on Rails with the RDF for Ruby gem to work with RDF data. But honestly, I'm clueless on how to actually work with this information. When I follow the link, I seem to be receiving an RDF store that contains all information about the city I queried.

Am I right in that I probably need to point my Code to the URI received and parse our the information I desire? Or should it be possible for example to select some information directly through the SPARQL endpoint? Like for example the description & demographic data?

I know this is a pretty vague question, but I'm trying my best to get the hang of this technology, and looking for some examples to help me better understand it.

答:
yes, you can use the URI received and parse out the information, or, you can use "bind" in your SPARQL to get the information only. For example, in the following SPARQL code:

```<code>PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX prop: <http://dbpedia.org/property/>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos/>

SELECT ?city, ?latitude, ?longitude
WHERE {
?city prop:name "Edinburgh"@en;
    a dbo:PopulatedPlace;
    geo:lat ?lat;
    geo:long ?long.
    bind(strafter(str(?lat), "http://www.w3.org/2003/01/geo/wgs84_pos/") as ?latitude)
    bind(strafter(str(?lat), "http://www.w3.org/2003/01/geo/wgs84_pos/") as ?longitude)
}
</code>```

instead of get "http://www.w3.org/2003/01/geo/wgs84_pos/55.93" for latitude, you will get "55.93" only.

Of course, if you do not have to use SPARQL endpoint, Jena (for java) and rdflib (for python) are very good choices to handle SPARQL queries and edit ontology.

Title: SPARQL, RDF & processing Data

Body:
I'm new to this entire semantics stuff, and i've been plunged into a project which requires me to use the SPARQL endpoint from dbpedia to retrieve information about certain things such as a City for example. The idea is that my application collects a few of these keywords (which are predefined, such as City, Country & Region) and rely on dbpedia to get some sensible information about this.

After fiddling around with the SPARQL endpoint for some time, I came up with the following query:

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX prop: <http://dbpedia.org/property/>

SELECT ?city
WHERE {
?city prop:name "X"@en;
a dbo:PopulatedPlace
}

Where X stands for the name of the city that I'm trying to get information about. When I run this query against the SPARQL endpoint, I receive a URI in a RDF structure that points to a RDF store on DBPedia (at least that's how I interpret it, please correct me if I'm wrong)

The returned result for the City "Antwerpen" looks like this:

<rdf:RDF><rdf:Description rdf:nodeID="rset"><rdf:type rdf:resource="http://www.w3.org/2005/sparql-results#ResultSet"/><res:resultVariable>city</res:resultVariable><res:solution rdf:nodeID="r0"><res:binding rdf:nodeID="r0c0"><res:variable>city</res:variable><res:value rdf:resource="http://dbpedia.org/resource/Antwerp"/></res:binding></res:solution></rdf:Description></rdf:RDF>

I'm using Ruby on Rails with the RDF for Ruby gem to work with RDF data. But honestly, I'm clueless on how to actually work with this information. When I follow the link, I seem to be receiving an RDF store that contains all information about the city I queried.

Am I right in that I probably need to point my Code to the URI received and parse our the information I desire? Or should it be possible for example to select some information directly through the SPARQL endpoint? Like for example the description & demographic data?

I know this is a pretty vague question, but I'm trying my best to get the hang of this technology, and looking for some examples to help me better understand it.

Body:
yes, you can use the URI received and parse out the information, or, you can use "bind" in your SPARQL to get the information only. For example, in the following SPARQL code:

PREFIX dbo: <http://dbpedia.org/ontology/>
PREFIX prop: <http://dbpedia.org/property/>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos/>

SELECT ?city, ?latitude, ?longitude
WHERE {
?city prop:name "Edinburgh"@en;
    a dbo:PopulatedPlace;
    geo:lat ?lat;
    geo:long ?long.
    bind(strafter(str(?lat), "http://www.w3.org/2003/01/geo/wgs84_pos/") as ?latitude)
    bind(strafter(str(?lat), "http://www.w3.org/2003/01/geo/wgs84_pos/") as ?longitude)
}

instead of get "http://www.w3.org/2003/01/geo/wgs84_pos/55.93" for latitude, you will get "55.93" only.

Of course, if you do not have to use SPARQL endpoint, Jena (for java) and rdflib (for python) are very good choices to handle SPARQL queries and edit ontology.


问:
Managing concurrent reads from a single Socket in a .Net application
I am writing a multi-threaded .Net application in which many callers need to concurrently read from a single Socket.

Data read from the socket is split into records / chunks of data - each record is targetted at a specific caller identified by a CallerID in the header, so for example the stream of bytes read from the socket might be something along the lines of:

```<code>Header: CallerId = 1, Length = 5
Data:   "Hello"
Header: CallerId = 2, Length = 6
Data:   "Stack "
Header: CallerId = 1, Length = 7
Data:   " World!"
Header: CallerId = 2, Length = 8
Data:   "Overflow"
</code>```

In which case the stream of data read by caller 1 should read "Hello World!", while the stream of data read by caller 2 should read "Stack Overflow".

My thoughts are that each callers data stream should be exposed through some class inheriting from Stream, so that callers are able to use both synchronous (Read) and asynchronous (BeginRead) programming models.

I'd like to avoid having a dedicated reading thread per socket, as my application will be dealing with many such sockets at any one time.

The callers shouldn't block each other, so for example in the above example the following shouldn't deadlock:

```<code>caller1Stream.Read(12) // Hello world!
caller2Stream.Read(14) // Stack Overflow
```

I've had a go at figuring out to do this however I found that things quickly became complicated, in particular; as the data needs to be read sequentially, and so while reading data for callers needs to be buffered - this makes the act of reading the stream for a given caller much more complicated:

Readers must first check their buffer to see if someone else has already read enough data

I'm struggling to find a suitable FIFO memory buffer / stream (does one exist already or do I need to write one?)

If not enough data has been read then the reader needs to read data from the socket until enough data intended for the given caller has been read, buffering data intended for other callers as it goes.

The buffering of data is fine (I can maintain a list of readers and look up the correct buffer by caller ID) however,

How do I prevent deadlocks where multiple threads attempt to read from the socket at the same time, however read each others data?

How do I notify callers that are waiting for data that their data has been read by another caller?

How do I make sure that the header and the data blocks of messages are read together?  (The data block is of variable length, and so it is necessary to read the fixed-length header block first to determine how much data to read)

Surely this must be a fairly common problem - is there not a .Net class that can make this whole thing a lot simpler? (Note that I'm not able to change the transport mechanism / protocol).  Is there any way to use one of the listener-style classes to do the above?

If not, how might I go about solving these problems?

答:
I'm not sure how much freedom you have to choose alternatives, but here are two:

Use pipes instead of sockets.  Open a Windows Named Pipe in mode PIPE_READMODE_MESSAGE.  The messages arrive in complete chunks only.

Use a higher-level socket abstraction like ZeroMQ.  You'll end up writing thousands fewer lines of code for complicated network messaging.

Body:
I am writing a multi-threaded .Net application in which many callers need to concurrently read from a single Socket.

Data read from the socket is split into records / chunks of data - each record is targetted at a specific caller identified by a CallerID in the header, so for example the stream of bytes read from the socket might be something along the lines of:

Header: CallerId = 1, Length = 5
Data:   "Hello"
Header: CallerId = 2, Length = 6
Data:   "Stack "
Header: CallerId = 1, Length = 7
Data:   " World!"
Header: CallerId = 2, Length = 8
Data:   "Overflow"

In which case the stream of data read by caller 1 should read "Hello World!", while the stream of data read by caller 2 should read "Stack Overflow".

My thoughts are that each callers data stream should be exposed through some class inheriting from Stream, so that callers are able to use both synchronous (Read) and asynchronous (BeginRead) programming models.

I'd like to avoid having a dedicated reading thread per socket, as my application will be dealing with many such sockets at any one time.

The callers shouldn't block each other, so for example in the above example the following shouldn't deadlock:

caller1Stream.Read(12) // Hello world!
caller2Stream.Read(14) // Stack Overflow

I've had a go at figuring out to do this however I found that things quickly became complicated, in particular; as the data needs to be read sequentially, and so while reading data for callers needs to be buffered - this makes the act of reading the stream for a given caller much more complicated:

Readers must first check their buffer to see if someone else has already read enough data

I'm struggling to find a suitable FIFO memory buffer / stream (does one exist already or do I need to write one?)

If not enough data has been read then the reader needs to read data from the socket until enough data intended for the given caller has been read, buffering data intended for other callers as it goes.

The buffering of data is fine (I can maintain a list of readers and look up the correct buffer by caller ID) however,

How do I prevent deadlocks where multiple threads attempt to read from the socket at the same time, however read each others data?

How do I notify callers that are waiting for data that their data has been read by another caller?

How do I make sure that the header and the data blocks of messages are read together?  (The data block is of variable length, and so it is necessary to read the fixed-length header block first to determine how much data to read)

Surely this must be a fairly common problem - is there not a .Net class that can make this whole thing a lot simpler? (Note that I'm not able to change the transport mechanism / protocol).  Is there any way to use one of the listener-style classes to do the above?

If not, how might I go about solving these problems?


问:
Can Enum.ToString support precision specifiers like "X2"?
Enum.ToString(string) does not support direct usage of precision specifiers like X2 or D5 to apply a padding to numeric values.  Formattings like ToString("X") or ToString("D") are implemented and well documented. Of course I can explicitely cast it to int before and so make use of the format specifiers implemented for ints to convert it to a padded string.

I was wondering if there is some direct support for this functionallity for enum without the need to cast them. On first sight it seems strange that this is not directly implemented as it was done for ints or other numeric types. But maybe I am missing something more important which could explicitely explain that it wasn't done like that for enums?

```<code>public enum Number
{
    Ten = 10
}

Console.WriteLine(Number.Ten);                      //OK: Ten
Console.WriteLine(Number.Ten.ToString());           //OK: Ten
Console.WriteLine(Number.Ten.ToString("D"));        //OK: 10
Console.WriteLine(Number.Ten.ToString("D5"));       //Expected 00010 - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or
Console.WriteLine(Number.Ten.ToString("X"));        //OK: 0000000A
Console.WriteLine(Number.Ten.ToString("X2"));       //Expected 0A - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or "d"
Console.WriteLine(10.ToString("X2"));               //OK: 0A
Console.WriteLine(10.ToString("D5"));               //OK: 00010
Console.WriteLine(((int)Number.Ten).ToString("X2"));//OK: 0A
</code>```

A short summary from the accepted answer:
It is not explicitely there because it is already implicitely done depending on the size of the underlying type. So if you like X2 instead of X8 just use byte as underlying type and ToString("X") will behave like ToString("X2").

答:
Maybe because enum can be an byte, sbyte, short, ushort, int, uint, long, or ulong.

If you check .net source code you'll see the implementation of ToString("X"):

```<code>switch (Convert.GetTypeCode(value))
  {
    case TypeCode.Boolean:
      return Convert.ToByte((bool) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Char:
      return ((ushort) (char) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.SByte:
      return ((byte) (sbyte) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Byte:
      return ((byte) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Int16:
      return ((ushort) (short) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.UInt16:
      return ((ushort) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.Int32:
      return ((uint) (int) value).ToString("X8", (IFormatProvider) null);
    case TypeCode.UInt32:
      return ((uint) value).ToString("X8", (IFormatProvider) null);
    case TypeCode.Int64:
      return ((ulong) (long) value).ToString("X16", (IFormatProvider) null);
    case TypeCode.UInt64:
      return ((ulong) value).ToString("X16", (IFormatProvider) null);
    default:
      throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
  }
</code>```

If you change your code to this, it'll use ToString("X2"):

```<code>public enum Number : byte
{
    Ten = 10
}
</code>```

Body:
Enum.ToString(string) does not support direct usage of precision specifiers like X2 or D5 to apply a padding to numeric values.  Formattings like ToString("X") or ToString("D") are implemented and well documented. Of course I can explicitely cast it to int before and so make use of the format specifiers implemented for ints to convert it to a padded string.

I was wondering if there is some direct support for this functionallity for enum without the need to cast them. On first sight it seems strange that this is not directly implemented as it was done for ints or other numeric types. But maybe I am missing something more important which could explicitely explain that it wasn't done like that for enums?

public enum Number
{
    Ten = 10
}

Console.WriteLine(Number.Ten);                      //OK: Ten
Console.WriteLine(Number.Ten.ToString());           //OK: Ten
Console.WriteLine(Number.Ten.ToString("D"));        //OK: 10
Console.WriteLine(Number.Ten.ToString("D5"));       //Expected 00010 - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or
Console.WriteLine(Number.Ten.ToString("X"));        //OK: 0000000A
Console.WriteLine(Number.Ten.ToString("X2"));       //Expected 0A - Failed: System.FormatException, can only be "G","g","X","x","F","f","D" or "d"
Console.WriteLine(10.ToString("X2"));               //OK: 0A
Console.WriteLine(10.ToString("D5"));               //OK: 00010
Console.WriteLine(((int)Number.Ten).ToString("X2"));//OK: 0A

A short summary from the accepted answer:
It is not explicitely there because it is already implicitely done depending on the size of the underlying type. So if you like X2 instead of X8 just use byte as underlying type and ToString("X") will behave like ToString("X2").

Body:
Maybe because enum can be an byte, sbyte, short, ushort, int, uint, long, or ulong.

If you check .net source code you'll see the implementation of ToString("X"):

switch (Convert.GetTypeCode(value))
  {
    case TypeCode.Boolean:
      return Convert.ToByte((bool) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Char:
      return ((ushort) (char) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.SByte:
      return ((byte) (sbyte) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Byte:
      return ((byte) value).ToString("X2", (IFormatProvider) null);
    case TypeCode.Int16:
      return ((ushort) (short) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.UInt16:
      return ((ushort) value).ToString("X4", (IFormatProvider) null);
    case TypeCode.Int32:
      return ((uint) (int) value).ToString("X8", (IFormatProvider) null);
    case TypeCode.UInt32:
      return ((uint) value).ToString("X8", (IFormatProvider) null);
    case TypeCode.Int64:
      return ((ulong) (long) value).ToString("X16", (IFormatProvider) null);
    case TypeCode.UInt64:
      return ((ulong) value).ToString("X16", (IFormatProvider) null);
    default:
      throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
  }

If you change your code to this, it'll use ToString("X2"):

public enum Number : byte
{
    Ten = 10
}


问:
caching sql result set in java
I know that caching the resultset of frequently used sql statements is better for the performance I am searching about the best way to cache sql result set in java. I found some codes but, it requires adding new jar files to netbeans.
Can anybody help me how can do that without needing to additional apis?</p>

答:
You should cache the data only. I would advise you to use an external api because you will probably also need to evict old data from cache(to prevent from using to much memory).

Using guave:

ConcurrentMap _continueContexts = new MapMaker()
    .expiration(10, TimeUnit.SECONDS)
    .makeMap();

P.S: You should something like maven to manage your dependencies.

Title: caching sql result set in java


问:
How to make the .net HttpClient use http 2.0?
I have an asp.net web api hosted on IIS 10 (windows server 2016). When I make a GET request to this from a Microsoft Edge browser, I see that HTTP 2.0 is used in IIS logs

```<code>2015-09-20 21:57:59 100.76.48.17 GET /RestController/Native - 443 - 73.181.195.76 HTTP/2.0 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/42.0.2311.135+Safari/537.36+Edge/12.10240 - 200 0 0 7299
</code>```

However, when a GET request is made through a .net 4.6 client as below,

```<code>using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("https://myapp.cloudapp.net/");

    HttpResponseMessage response = await client.GetAsync("RestController/Native");
    if (response.IsSuccessStatusCode)
    {
        await response.Content.CopyToAsync(new MemoryStream(buffer));
    }
}
</code>```

I see the following HTTP 1.1 log in the server logs

```<code>2015-09-20 20:57:41 100.76.48.17 GET /RestController/Native - 443 - 131.107.160.196 HTTP/1.1 - - 200 0 0 707
</code>```

How can I make the .net client use HTTP/2.0 ?

答:
1.Make sure you are on the latest version of Windows 10.

2.Install WinHttpHandler:

```<code>Install-Package System.Net.Http.WinHttpHandler
</code>```

3.Extend WinHttpHandler to add http2.0 support:

```<code>public class Http2CustomHandler : WinHttpHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        request.Version = new Version("2.0");
        return base.SendAsync(request, cancellationToken);
    }
}
</code>```

4.Pass above handler to the HttpClient constructor

```<code>using (var httpClient = new HttpClient(new Http2CustomHandler()))
{
      // your custom code
}
</code>```

Body:
I have an asp.net web api hosted on IIS 10 (windows server 2016). When I make a GET request to this from a Microsoft Edge browser, I see that HTTP 2.0 is used in IIS logs

2015-09-20 21:57:59 100.76.48.17 GET /RestController/Native - 443 - 73.181.195.76 HTTP/2.0 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/42.0.2311.135+Safari/537.36+Edge/12.10240 - 200 0 0 7299

However, when a GET request is made through a .net 4.6 client as below,

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("https://myapp.cloudapp.net/");

    HttpResponseMessage response = await client.GetAsync("RestController/Native");
    if (response.IsSuccessStatusCode)
    {
        await response.Content.CopyToAsync(new MemoryStream(buffer));
    }
}

I see the following HTTP 1.1 log in the server logs

2015-09-20 20:57:41 100.76.48.17 GET /RestController/Native - 443 - 131.107.160.196 HTTP/1.1 - - 200 0 0 707

How can I make the .net client use HTTP/2.0 ?

Body:
1.Make sure you are on the latest version of Windows 10.

2.Install WinHttpHandler:

Install-Package System.Net.Http.WinHttpHandler

3.Extend WinHttpHandler to add http2.0 support:

public class Http2CustomHandler : WinHttpHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
        request.Version = new Version("2.0");
        return base.SendAsync(request, cancellationToken);
    }
}

4.Pass above handler to the HttpClient constructor

using (var httpClient = new HttpClient(new Http2CustomHandler()))
{
      // your custom code
}


问:
Passing and returning a struct from a function
I have a function with a book struct array, but when i try to return it to my main it does not return the values and store them in the array. If the addBook function has to be void how would i work around that so that i can access the array elements later.</p>

```<code>void addBook(struct Book book[], int *size) {

    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");

    }
    else {

        printf("ISBN:");
        scanf("%d", &book[*size]._isbn);
        printf("Title:");
        scanf("%s", book[*size]._title);
        getchar();
        printf("Year:");
        scanf("%d", &book[*size]._year);
        printf("Price:");
        scanf("%f", &book[*size]._price);
        printf("Quantity:");
        scanf("%d", &book[*size]._qty);
        *size++;
        printf("The book is successfully added to the inventory.\n");
    }
    return book;
}

int main(void) {

    struct Book book[MAX_BOOKS];
    int size = 0;
    int i;
    int option;

    printf("Welcome to the Book Store\n");
    printf("=========================\n");

    do {
        menu();
        printf("Select: ");
        scanf("%d", &option);

        switch (option) {

        case 0:
            printf("Goodbye!\n");
            break;
        case 1:
            displayInventory(book, size);
            break;
        case 2:
            addBook(book, &size);
            break;
        case 3:
            //checkPrice();
            break;
        default:
            printf("Invalid input, try again:\n");
        }
    } while (option != 0);
}
</code>```

答:
Your return statement isn't going to do what you're intending as the addBook's function signature says it returns void. I'm surprised that the code as is actually compiled without an error about this.

Anyways, the book data can be returned from the same way it was passed in - as an input and output parameter.

Essentially your code could look like the following (which is only meant to be an example of code that compiles and works to save info entered in from standard input into the book):

```<code>#include <stdio.h>

struct Book {
    int value;
};

#define MAX_BOOKS 2

void addBook(struct Book book[], int *size) {
    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");
    }
    else {
        printf("Value:");
        scanf("%d", &book[*size].value);
        (*size)++;
        printf("The book is successfully added to the inventory.\n");
    }
}

int main(void) {
    struct Book book[MAX_BOOKS];
    int size = 0;

    addBook(book, &size);
    printf("Book 1: Value=%d\n", book[0].value);
}
</code>```

And here's how this looks when run:

```<code>$ ./main
Value:9
The book is successfully added to the inventory.
Book 1: Value=9
</code>```

Hope this answers your question.

Body:
I have a function with a book struct array, but when i try to return it to my main it does not return the values and store them in the array. If the addBook function has to be void how would i work around that so that i can access the array elements later.

void addBook(struct Book book[], int *size) {

    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");

    }
    else {

        printf("ISBN:");
        scanf("%d", &book[*size]._isbn);
        printf("Title:");
        scanf("%s", book[*size]._title);
        getchar();
        printf("Year:");
        scanf("%d", &book[*size]._year);
        printf("Price:");
        scanf("%f", &book[*size]._price);
        printf("Quantity:");
        scanf("%d", &book[*size]._qty);
        *size++;
        printf("The book is successfully added to the inventory.\n");
    }
    return book;
}

int main(void) {

    struct Book book[MAX_BOOKS];
    int size = 0;
    int i;
    int option;

    printf("Welcome to the Book Store\n");
    printf("=========================\n");

    do {
        menu();
        printf("Select: ");
        scanf("%d", &option);

        switch (option) {

        case 0:
            printf("Goodbye!\n");
            break;
        case 1:
            displayInventory(book, size);
            break;
        case 2:
            addBook(book, &size);
            break;
        case 3:
            //checkPrice();
            break;
        default:
            printf("Invalid input, try again:\n");
        }
    } while (option != 0);
}

Body:
Your return statement isn't going to do what you're intending as the addBook's function signature says it returns void. I'm surprised that the code as is actually compiled without an error about this.

Anyways, the book data can be returned from the same way it was passed in - as an input and output parameter.

Essentially your code could look like the following (which is only meant to be an example of code that compiles and works to save info entered in from standard input into the book):

#include <stdio.h>

struct Book {
    int value;
};

#define MAX_BOOKS 2

void addBook(struct Book book[], int *size) {
    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");
    }
    else {
        printf("Value:");
        scanf("%d", &book[*size].value);
        (*size)++;
        printf("The book is successfully added to the inventory.\n");
    }
}

int main(void) {
    struct Book book[MAX_BOOKS];
    int size = 0;

    addBook(book, &size);
    printf("Book 1: Value=%d\n", book[0].value);
}

And here's how this looks when run:

$ ./main
Value:9
The book is successfully added to the inventory.
Book 1: Value=9

Hope this answers your question.


问:
Angular 2 cannot include Material lib
I am using the Microsoft.AspNetCore.SpaTemplates example of angular 2, I installed the angular/materiel npm module and tried to include that for use of the input material.

EDIT -- New question posted regarding removing the server-side rendering.

Link -- Click Here

I tried to import it in app.module.ts and after doing so cannot seem to get my application to load anymore.

```<code>@NgModule({
bootstrap: [ AppComponent ],
declarations: [
    AppComponent,
    HeaderComponent,
    LoginComponent
],
imports: [
    UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
    RouterModule.forRoot([
        { path: '', redirectTo: 'account', pathMatch: 'full' },
        { path: 'login', component: LoginComponent },
        { path: '**', redirectTo: 'account' }
    ]), MaterialModule
]
</code>```

})

Now I am trying to create a simple login view with an email and password input box. I wanted to use angular material to make it look better.

Here is my exception on page load.

```<code>An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: Error: This method is not implemented in Parse5DomAdapter: getCookie
at _notImplemented (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:91062:12) [angular]
at Parse5DomAdapter.module.exports.Parse5DomAdapter.getCookie (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:91657:69) [angular]
at CookieXSRFStrategy.configureRequest (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:63677:109) [angular]
at XHRBackend.createConnection (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:63726:32) [angular]
at httpRequest (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64076:24) [angular]
at Http.request (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64185:38) [angular]
at Http.get (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64199:25) [angular]
at AccountService.ping (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\main-server.js:22373:30) [angular]
at new AccountService (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\main-server.js:22370:14) [angular]
at CompiledTemplate.proxyViewClass.View_AppComponent0.createInternal (/AppModule/AppComponent/component.ngfactory.js:15:30) [angular]
at CompiledTemplate.proxyViewClass.AppView.create (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:11951:25) [angular]
at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.createInternal (/AppModule/AppComponent/host.ngfactory.js:15:19) [angular]
at CompiledTemplate.proxyViewClass.AppView.createHostView (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:11964:25) [angular]
at ComponentFactory.create (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:7361:29) [angular]
</code>```

I now understand that the Universal Module is what is creating pre-rendering. This is really great and all except to be completely honest I don't need it.

To revise my question now. How can someone take the Microsoft.AspNetCore.SpaTemplate for angular 2 and remove the Universal Module and still have a working angular website. Simply removing the Universal Module from the imports causing other errors to start showing up. What changes need to be made throughout other sections of the template, and am I losing anything aside from server-side pre-rendering?

答:
I had the same issue and fixed it by putting the MaterialModule before the UniversalModule.  I know the SPA template says it should go first, but that order seemed to break it.

```<code>imports: [
        MaterialModule.forRoot(),
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.

        RouterModule.forRoot([
            { path: '', redirectTo: 'account', pathMatch: 'full' },
            { path: 'account', component: AccountListComponent },
            { path: 'detail/:id', component: AccountDetailComponent },
            { path: '**', redirectTo: 'account' }
        ])
    ],
</code>```

Edit - Actually, it looks to be more complicated than this.  Here is a GitHub issue on it:
https://github.com/angular/material2/issues/308

I ended up pulling out the UniversalModule because Angular Material was more important to me than server side rendering at this point.  There are a few changes you would need to make to get the SPA template to work with Angular Material.  Let me know if you would like more help.

Edit

I have down voted this question since the OP marked my answer, then un-marked despite considerable effort to assist.  The answer I provided is the correct answer.

Title: Angular 2 cannot include Material lib

Body:
I am using the Microsoft.AspNetCore.SpaTemplates example of angular 2, I installed the angular/materiel npm module and tried to include that for use of the input material.

EDIT -- New question posted regarding removing the server-side rendering.

Link -- Click Here

I tried to import it in app.module.ts and after doing so cannot seem to get my application to load anymore.

@NgModule({
bootstrap: [ AppComponent ],
declarations: [
    AppComponent,
    HeaderComponent,
    LoginComponent
],
imports: [
    UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
    RouterModule.forRoot([
        { path: '', redirectTo: 'account', pathMatch: 'full' },
        { path: 'login', component: LoginComponent },
        { path: '**', redirectTo: 'account' }
    ]), MaterialModule
]

})

Now I am trying to create a simple login view with an email and password input box. I wanted to use angular material to make it look better.

Here is my exception on page load.

An unhandled exception occurred while processing the request.

Exception: Call to Node module failed with error: Error: This method is not implemented in Parse5DomAdapter: getCookie
at _notImplemented (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:91062:12) [angular]
at Parse5DomAdapter.module.exports.Parse5DomAdapter.getCookie (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:91657:69) [angular]
at CookieXSRFStrategy.configureRequest (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:63677:109) [angular]
at XHRBackend.createConnection (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:63726:32) [angular]
at httpRequest (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64076:24) [angular]
at Http.request (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64185:38) [angular]
at Http.get (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:64199:25) [angular]
at AccountService.ping (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\main-server.js:22373:30) [angular]
at new AccountService (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\main-server.js:22370:14) [angular]
at CompiledTemplate.proxyViewClass.View_AppComponent0.createInternal (/AppModule/AppComponent/component.ngfactory.js:15:30) [angular]
at CompiledTemplate.proxyViewClass.AppView.create (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:11951:25) [angular]
at CompiledTemplate.proxyViewClass.View_AppComponent_Host0.createInternal (/AppModule/AppComponent/host.ngfactory.js:15:19) [angular]
at CompiledTemplate.proxyViewClass.AppView.createHostView (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:11964:25) [angular]
at ComponentFactory.create (C:\Users\baile\Source\Repos\Programming2017\BankSoftware\ClientApp\dist\vendor.js:7361:29) [angular]

I now understand that the Universal Module is what is creating pre-rendering. This is really great and all except to be completely honest I don't need it.

To revise my question now. How can someone take the Microsoft.AspNetCore.SpaTemplate for angular 2 and remove the Universal Module and still have a working angular website. Simply removing the Universal Module from the imports causing other errors to start showing up. What changes need to be made throughout other sections of the template, and am I losing anything aside from server-side pre-rendering?

Body:
I had the same issue and fixed it by putting the MaterialModule before the UniversalModule.  I know the SPA template says it should go first, but that order seemed to break it.

imports: [
        MaterialModule.forRoot(),
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.

        RouterModule.forRoot([
            { path: '', redirectTo: 'account', pathMatch: 'full' },
            { path: 'account', component: AccountListComponent },
            { path: 'detail/:id', component: AccountDetailComponent },
            { path: '**', redirectTo: 'account' }
        ])
    ],

Edit - Actually, it looks to be more complicated than this.  Here is a GitHub issue on it:
https://github.com/angular/material2/issues/308

I ended up pulling out the UniversalModule because Angular Material was more important to me than server side rendering at this point.  There are a few changes you would need to make to get the SPA template to work with Angular Material.  Let me know if you would like more help.

Edit

I have down voted this question since the OP marked my answer, then un-marked despite considerable effort to assist.  The answer I provided is the correct answer.


问:
Javascript Uncaught TypeError: Cannot read property 'append' of null in code
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>

    <script>

function checkDistance(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 51.714236,
      "lon": 50.710236
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
];

for(var i = 0;i < data.length;i++){

    var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

    if(result <= distanceLimit){
        var resultList = document.getElementById('resultList');
        resultList.append(data[i].name + ', ');
    }
}

    </script>

</head>
<body>

   <div id="resultList"></div>

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

Why I'm I getting this error and how can I fix it?

答:
You need to declare a variable for resultList; it is not yet defined.

```<code>var resultList = document.getElementById('resultList');
</code>```

Just make sure that line is above the offending append code.

Body:
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title></title>

Why I'm I getting this error and how can I fix it?

Body:
You need to declare a variable for resultList; it is not yet defined.

var resultList = document.getElementById('resultList');

Just make sure that line is above the offending append code.


问:
How to display the output of the following code using iterators?
This code is for creating adjacency list(i think) and i want to display the content in the vector

```<code>#include<iostream>
#include<vector>
int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector< int > graph[ N + 1 ];
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph[ u ].push_back( v );
    }
    /*vector<int>iterator::it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;*/
}
</code>```

I tried to display the output using the lines commented in the code but it gives me compile error saying:

```<code>struct std::iterator used without template parameters
</code>```

Your help will be appreciated....

答:
```<code>#include<iostream>
#include<vector>
int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    std::vector< int > graph[ N + 1 ]; //try to use std::vector<std::vector<int>> - c kind array should have fixed (compilation time) size
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph[ u ].push_back( v );
    }
    for ( int i = 0; i <= N; ++i){
        std::cout << i << ": ";
        for ( std::vector<int>::const_iterator it = graph[i].begin(); it != graph[i].end(); ++it){
            std::cout << *it << " ";
        }
    }
}
//try to use some compilation flag:
//-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wfloat-equa
</code>```

Body:
This code is for creating adjacency list(i think) and i want to display the content in the vector

#include<iostream>
#include<vector>
int main() {
    int N, M;
    fscanf( stdin, "%d%d", &N, &M );
    vector< int > graph[ N + 1 ];
    int i, u, v;
    for ( i = 0; i < M; ++i ) {
        fscanf( stdin, "%d%d", &u, &v );
        graph[ u ].push_back( v );
    }
    /*vector<int>iterator::it;
    for(it=graph.begin();it!=graph.end();it++)
    cout<<*it<<endl;*/
}

I tried to display the output using the lines commented in the code but it gives me compile error saying:

struct std::iterator used without template parameters

Your help will be appreciated....


问:
Best way to multi-thread?
What is the best way to multi-thread in the C language? I want something that is very efficient and not a CPU hog. Thanks.</p>

答:
Your question is a bit general to answer effectively. You might look into such things as:

CreateThread in the windows SDK

boost::thread

OwnerDisplayName: Sasayins

Title: Best way to multi-thread?

LastEditorDisplayName: John

OwnerDisplayName: 1800 INFORMATION


问:
jar resources in jnlp are not signed by the same certificate
I've been working with web start for a couple years now and have experience with signing the jars and what not. I am taking my first attempt at deploying a RCP app with web start and though I have in fact signed all of the jars with the same certificate I keep getting this error: 'jar resources in jnlp are not signed by the same certificate'

Has anyone else came across this? If so, any ideas on how to fix?

答:
This may be a stale manifest entry from an already signed jar that you use as a library. I encountered this problem with jogl via webstart. Try this:

Unzip all jars, purge all META-INF directories, jar and sign them again.

OwnerDisplayName: Stefan Tannenbaum