问:
SqlCommandBuilder not assigning ConnectionString
I'm using a devexpress XtraGrid in layout view to edit a recently created database row.
This is the code I use to load data:

```<code>Public Function SetData(ByVal connString As String, ByVal tabla As String) As Boolean
    Dim d As New DataTable
    Dim cmd As New SqlCommand

    Try
        Using conn As New SqlConnection(connString)
            conn.Open()
            cmd.Connection = conn

            m_Tabla = tabla
            If (m_Id = "") Then
                cmd.CommandText = "SELECT * FROM " & m_Tabla
            Else
                cmd.CommandText = "SELECT * FROM " & m_Tabla & " WHERE IdCaptura = '" & m_Id & "'"
            End If

            m_Adapter = New SqlDataAdapter(cmd)
            m_DataSet = New DataSet()
            m_Adapter.Fill(m_DataSet, m_Tabla)

            grdMetadata.DataSource = m_DataSet.Tables(m_Tabla)
            Return True
        End Using

    Catch ex As Exception
        Return False
    End Try
End Function
</code>```

The database can be different from client to client, so AFAIK I can't write the update command; I've been investigating the issue and my conclusion was that I need to use a SqlCommandBuilder to get it automatically generated.

When the user ends editing data, I use the following snippet to update the database:

```<code>Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
    Try
        Dim builder As New SqlCommandBuilder(m_Adapter)

        grdLayoutView.CloseEditor()
        grdLayoutView.UpdateCurrentRow()
        m_Adapter.Update(m_DataSet, m_Tabla) *

    Catch ex As Exception
        lblEstado.Text = ex.Message
    End Try
End Sub
</code>```

In the line marked with *, I get a "The ConnectionString Property has not been initialized" exception. The table has a Primary Key column (IdCaptura), and I can see that the DataAdapter.UpdateCommand is set to nothing if I put a breakpoint in said line.

Any idea about what's wrong here?

答:
By the time your second code snippet is called, the SqlConnection you made in the first one has been disposed of, per the using statement.  That's why it's not initialized.  You're going to have to either not dispose of the connection there, or create another connection for your second code snippet.

Like this, for example:

```<code>Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
    Try
        Using conn As New SqlConnection(connString) ' <--- need to get the connection string from somewhere here '
            conn.Open()
            m_Adapter.UpdateCommand.Connection = conn
            Dim builder As New SqlCommandBuilder(m_Adapter)

            grdLayoutView.CloseEditor()
            grdLayoutView.UpdateCurrentRow()
            m_Adapter.Update(m_DataSet, m_Tabla) *
        End Using
    Catch ex As Exception
        lblEstado.Text = ex.Message
    End Try
End Sub
</code>```

Body:
I'm using a devexpress XtraGrid in layout view to edit a recently created database row.
This is the code I use to load data:

Public Function SetData(ByVal connString As String, ByVal tabla As String) As Boolean
    Dim d As New DataTable
    Dim cmd As New SqlCommand

    Try
        Using conn As New SqlConnection(connString)
            conn.Open()
            cmd.Connection = conn

            m_Tabla = tabla
            If (m_Id = "") Then
                cmd.CommandText = "SELECT * FROM " & m_Tabla
            Else
                cmd.CommandText = "SELECT * FROM " & m_Tabla & " WHERE IdCaptura = '" & m_Id & "'"
            End If

            m_Adapter = New SqlDataAdapter(cmd)
            m_DataSet = New DataSet()
            m_Adapter.Fill(m_DataSet, m_Tabla)

            grdMetadata.DataSource = m_DataSet.Tables(m_Tabla)
            Return True
        End Using

    Catch ex As Exception
        Return False
    End Try
End Function

The database can be different from client to client, so AFAIK I can't write the update command; I've been investigating the issue and my conclusion was that I need to use a SqlCommandBuilder to get it automatically generated.

When the user ends editing data, I use the following snippet to update the database:

Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
    Try
        Dim builder As New SqlCommandBuilder(m_Adapter)

        grdLayoutView.CloseEditor()
        grdLayoutView.UpdateCurrentRow()
        m_Adapter.Update(m_DataSet, m_Tabla) *

    Catch ex As Exception
        lblEstado.Text = ex.Message
    End Try
End Sub

In the line marked with *, I get a "The ConnectionString Property has not been initialized" exception. The table has a Primary Key column (IdCaptura), and I can see that the DataAdapter.UpdateCommand is set to nothing if I put a breakpoint in said line.

Any idea about what's wrong here?

Body:
By the time your second code snippet is called, the SqlConnection you made in the first one has been disposed of, per the using statement.  That's why it's not initialized.  You're going to have to either not dispose of the connection there, or create another connection for your second code snippet.

Like this, for example:

Private Sub btnAceptar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAceptar.Click
    Try
        Using conn As New SqlConnection(connString) ' <--- need to get the connection string from somewhere here '
            conn.Open()
            m_Adapter.UpdateCommand.Connection = conn
            Dim builder As New SqlCommandBuilder(m_Adapter)

            grdLayoutView.CloseEditor()
            grdLayoutView.UpdateCurrentRow()
            m_Adapter.Update(m_DataSet, m_Tabla) *
        End Using
    Catch ex As Exception
        lblEstado.Text = ex.Message
    End Try
End Sub


来源: stackexchange

问:
How two rows can be swapped in a torch tensor?
```<code>var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]

var = torch.Tensor(var)
</code>```

Here, var is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?

```<code>2, -3, 2, 1
0, 1, -4, 8
5, -8, 7, 1
</code>```

答:
Generate the permutation index you desire:

```<code>index = torch.LongTensor([1,0,2])
</code>```

Apply the permutation:

```<code>var[index] = var
</code>```

ContentLicense: CC BY-SA 3.0

Body:
var = [[0, 1, -4, 8],
       [2, -3, 2, 1],
       [5, -8, 7, 1]]

var = torch.Tensor(var)

Here, var is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?

2, -3, 2, 1
0, 1, -4, 8
5, -8, 7, 1

Body:
Generate the permutation index you desire:

index = torch.LongTensor([1,0,2])

Apply the permutation:

var[index] = var


问:
Remove git repository from Eclipse
I added a git repository to my project and then I hit Team > Disconnect. How do I remove this repository completely? I'm trying to set up a new git repository on my project, but I keep getting an error message.

答:
If you just want to remove the repository from the Eclipse but not want to delete the data from your computer, follow these steps :

First switch to Git perspective (Window - > Open Perspective -> Other -> Search for Git)

In the Git Repositories section, right click your repository and select Remove Repository from View. This will prompt you to confirm if you want to remove the projects that are imported in Eclipse from this repository. Click Yes and you are done.

Title: Remove git repository from Eclipse


问:
Documentation event listeners
I have a question concerning this code down here:

```<code>on.("click", () => {...})
</code>```

Currently I try to figure out Electron. In a code example I saw the use of the usual event listener function. In the fat-arrow function the developer used different kinds of properties. For example:

```<code>on.("click", () => {event, bounds})
</code>```

I am interested in the amount of properties you can use... there are probably more than just those two. I could not find any documentation on this.
That did not help me at all: https://developer.mozilla.org/en/docs/Web/Events/click

Maybe someone can help me out on this.

答:
I assume, what confused you is - Desctructuring assignment.
This code(which is not very correct):

```<code>.on("click", () => {event, bounds})
</code>```

Can be overwritten by this one:

```<code>.on("click", e => {
  return {
    event: e.event,
    bounds: e.bounds
  };
});
</code>```

Title: Documentation event listeners

Body:
I have a question concerning this code down here:

on.("click", () => {...})

Currently I try to figure out Electron. In a code example I saw the use of the usual event listener function. In the fat-arrow function the developer used different kinds of properties. For example:

on.("click", () => {event, bounds})

I am interested in the amount of properties you can use... there are probably more than just those two. I could not find any documentation on this.
That did not help me at all: https://developer.mozilla.org/en/docs/Web/Events/click

Maybe someone can help me out on this.

Body:
I assume, what confused you is - Desctructuring assignment.
This code(which is not very correct):

.on("click", () => {event, bounds})

Can be overwritten by this one:

.on("click", e => {
  return {
    event: e.event,
    bounds: e.bounds
  };
});


问:
Remove element from vector of maps
I have a vector of maps:

```<code>typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;
</code>```

How can I remove some elements from rows?

The following code does not work.

```<code>struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());
</code>```

I got the following error.

```<code>error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'
</code>```

Thanks.

答:
remove expects a value.  You are trying to use a functor, you need to use remove_if for that.

Also, your functor needs to accept an object of type aMap, not rVec.

ContentLicense: CC BY-SA 2.5

Title: Remove element from vector of maps

Body:
I have a vector of maps:

typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;

How can I remove some elements from rows?

The following code does not work.

struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());

I got the following error.

error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'

Thanks.


问:
Set scroll position to top in new page using barba.js
I use the code from barba.js documentation as below to switch between pages.

```<code>var FadeTransition = Barba.BaseTransition.extend({
    start: function() {
        Promise
            .all([this.newContainerLoading, this.fadeOut()])
            .then(this.fadeIn.bind(this));
    },

    fadeOut: function() {
        return $(this.oldContainer).animate({ opacity: 0 }).promise();
    },

    fadeIn: function() {
        var _this = this;
        var $el = $(this.newContainer);

        $(this.oldContainer).hide();

        $el.css({
        visibility : 'visible',
        opacity : 0
        });
        $el.animate({ opacity: 1 }, 400, function() {
        _this.done();
        });
    }
});

Barba.Pjax.getTransition = function() {
    return FadeTransition;
};
</code>```

The problem is that the scroll position retained in the new page.
I tried to add $(window).scrollTop(0); inside fadeIn function, but this gives unwanted scroll when pressing back button. How can it be solved?

The following is the behavior after adding $(window).scrollTop(0);

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B scroll to the position of page A and then fades out

page A enters and has scroll position at top

scroll down and press forward button. Page A scroll to top and then fades out

page B enters and has scroll position at top

The following is the expected behavior:

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B fades out without scrolling

page A enters and has scroll position as step 1

答:
```<code>Barba.Dispatcher.on('newPageReady', function(current, prev, container) {
    history.scrollRestoration = 'manual';
});
</code>```

Adding this solve the jumping issue. This, however, lose the scroll position of the last page i.e. always on top no matter entering new page or old page.

reference: https://github.com/luruke/barba.js/issues/133

polyfill: https://github.com/bfred-it/scroll-restoration-polyfill

Body:
I use the code from barba.js documentation as below to switch between pages.

var FadeTransition = Barba.BaseTransition.extend({
    start: function() {
        Promise
            .all([this.newContainerLoading, this.fadeOut()])
            .then(this.fadeIn.bind(this));
    },

    fadeOut: function() {
        return $(this.oldContainer).animate({ opacity: 0 }).promise();
    },

    fadeIn: function() {
        var _this = this;
        var $el = $(this.newContainer);

        $(this.oldContainer).hide();

        $el.css({
        visibility : 'visible',
        opacity : 0
        });
        $el.animate({ opacity: 1 }, 400, function() {
        _this.done();
        });
    }
});

Barba.Pjax.getTransition = function() {
    return FadeTransition;
};

The problem is that the scroll position retained in the new page.
I tried to add $(window).scrollTop(0); inside fadeIn function, but this gives unwanted scroll when pressing back button. How can it be solved?

The following is the behavior after adding $(window).scrollTop(0);

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B scroll to the position of page A and then fades out

page A enters and has scroll position at top

scroll down and press forward button. Page A scroll to top and then fades out

page B enters and has scroll position at top

The following is the expected behavior:

in page A, scroll down and press link to page B. Page B enters and has scroll position at top

press back button, page B fades out without scrolling

page A enters and has scroll position as step 1

Body:
Barba.Dispatcher.on('newPageReady', function(current, prev, container) {
    history.scrollRestoration = 'manual';
});

Adding this solve the jumping issue. This, however, lose the scroll position of the last page i.e. always on top no matter entering new page or old page.

reference: https://github.com/luruke/barba.js/issues/133

polyfill: https://github.com/bfred-it/scroll-restoration-polyfill


问:
Unable to install Newtonsoft Json
I am trying to install Newtonsoft Json (with the package manager console) so that I can use it in my C# console app, but I get this error:

```<code>PM> Install-Package Newtonsoft.Json
Install-Package : Unable to find package 'Newtonsoft.Json'
At line:1 char:1
+ Install-Package Newtonsoft.Json
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
</code>```

Why am I getting this error?

答:
I might be just be late to answer, but this is usually caused by the incorrect package source, different packages come from different sources, for example angularJS.core packages comes from nuget.org source so if you search it and you have Microsoft and .NET set as your source, then you wont be able to find it.

To attempt to answer your question, please select the change the source on your your PM console(see attached screenshot) , you might also want to make sure that you point to the correct project(attached screenshot will also guide you on that regard). Or even better just select "All" on your source and you should be good

Title: Unable to install Newtonsoft Json

Body:
I am trying to install Newtonsoft Json (with the package manager console) so that I can use it in my C# console app, but I get this error:

PM> Install-Package Newtonsoft.Json
Install-Package : Unable to find package 'Newtonsoft.Json'
At line:1 char:1
+ Install-Package Newtonsoft.Json
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand

Why am I getting this error?


问:
Is there a way to pass an entire file from file system mini filter driver (kernel mode) up to a user mode application?
I have a scanner file system mini filter driver using the WDK 8.1 samples.

I'm wondering if I can send the entire file up to the user land application so I can do more complicated calculations such as MD5 Hash or anything else really so that I don't have to write more complicated actions in the mini filter driver but instead in the user land application where I don't mind bringing in windows.h and where I can allocate memory on the heap instead of using ExAllocatePoolWithTag and stuff like that.

Can I pass the entire file up to user land mode in one notification?

If not how would I go about chunking that out and syncing.

Here is the interface for the 8.1 scanner file system mini filter driver sample that dictates the communication between the mini filter driver and the user land application:

```<code>/*++

Copyright (c) 1999-2002  Microsoft Corporation

Module Name:

    scanuk.h

Abstract:

    Header file which contains the structures, type definitions,
    constants, global variables and function prototypes that are
    shared between kernel and user mode.

Environment:

    Kernel & user mode

--*/

#ifndef __SCANUK_H__
#define __SCANUK_H__

//
//  Name of port used to communicate
//

const PWSTR ScannerPortName = L"\\ScannerPort";

#define SCANNER_READ_BUFFER_SIZE   1024

typedef struct _SCANNER_NOTIFICATION {

    ULONG BytesToScan;
    ULONG Reserved;             // for quad-word alignement of the Contents structure
    UCHAR Contents[SCANNER_READ_BUFFER_SIZE];

} SCANNER_NOTIFICATION, *PSCANNER_NOTIFICATION;

typedef struct _SCANNER_REPLY {

    BOOLEAN SafeToOpen;

} SCANNER_REPLY, *PSCANNER_REPLY;

#endif //  __SCANUK_H__
</code>```

Notice how there is a 1024 limit on the buffer size being passed. This means I cannot do the MD5 hash on the entire file in the user land application and then would be forced to do it in the mini filter driver, which I want to avoid, if possible.

And here is the function in the mini filter driver that sends the message to the user land application using the interface above:

```<code>//////////////////////////////////////////////////////////////////////////
//  Local support routines.
//
/////////////////////////////////////////////////////////////////////////

NTSTATUS
ScannerpScanFileInUserMode (
    _In_ PFLT_INSTANCE Instance,
    _In_ PFILE_OBJECT FileObject,
    _Out_ PBOOLEAN SafeToOpen
    )
/*++

Routine Description:

    This routine is called to send a request up to user mode to scan a given
    file and tell our caller whether it's safe to open this file.

    Note that if the scan fails, we set SafeToOpen to TRUE.  The scan may fail
    because the service hasn't started, or perhaps because this create/cleanup
    is for a directory, and there's no data to read & scan.

    If we failed creates when the service isn't running, there'd be a
    bootstrapping problem -- how would we ever load the .exe for the service?

Arguments:

    Instance - Handle to the filter instance for the scanner on this volume.

    FileObject - File to be scanned.

    SafeToOpen - Set to FALSE if the file is scanned successfully and it contains
                 foul language.

Return Value:

    The status of the operation, hopefully STATUS_SUCCESS.  The common failure
    status will probably be STATUS_INSUFFICIENT_RESOURCES.

--*/

{
    NTSTATUS status = STATUS_SUCCESS;
    PVOID buffer = NULL;
    ULONG bytesRead;
    PSCANNER_NOTIFICATION notification = NULL;
    FLT_VOLUME_PROPERTIES volumeProps;
    LARGE_INTEGER offset;
    ULONG replyLength, length;
    PFLT_VOLUME volume = NULL;

    *SafeToOpen = TRUE;

    //
    //  If not client port just return.
    //

    if (ScannerData.ClientPort == NULL) {

        return STATUS_SUCCESS;
    }

    try {

        //
        //  Obtain the volume object .
        //

        status = FltGetVolumeFromInstance( Instance, &volume );

        if (!NT_SUCCESS( status )) {

            leave;
        }

        //
        //  Determine sector size. Noncached I/O can only be done at sector size offsets, and in lengths which are
        //  multiples of sector size. A more efficient way is to make this call once and remember the sector size in the
        //  instance setup routine and setup an instance context where we can cache it.
        //

        status = FltGetVolumeProperties( volume,
                                         &volumeProps,
                                         sizeof( volumeProps ),
                                         &length );
        //
        //  STATUS_BUFFER_OVERFLOW can be returned - however we only need the properties, not the names
        //  hence we only check for error status.
        //

        if (NT_ERROR( status )) {

            leave;
        }

        length = max( SCANNER_READ_BUFFER_SIZE, volumeProps.SectorSize );

        //
        //  Use non-buffered i/o, so allocate aligned pool
        //

        buffer = FltAllocatePoolAlignedWithTag( Instance,
                                                NonPagedPool,
                                                length,
                                                'nacS' );

        if (NULL == buffer) {

            status = STATUS_INSUFFICIENT_RESOURCES;
            leave;
        }

        notification = ExAllocatePoolWithTag( NonPagedPool,
                                              sizeof( SCANNER_NOTIFICATION ),
                                              'nacS' );

        if(NULL == notification) {

            status = STATUS_INSUFFICIENT_RESOURCES;
            leave;
        }

        //
        //  Read the beginning of the file and pass the contents to user mode.
        //

        offset.QuadPart = bytesRead = 0;
        status = FltReadFile( Instance,
                              FileObject,
                              &offset,
                              length,
                              buffer,
                              FLTFL_IO_OPERATION_NON_CACHED |
                              FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET,
                              &bytesRead,
                              NULL,
                              NULL );

        if (NT_SUCCESS( status ) && (0 != bytesRead)) {

            notification->BytesToScan = (ULONG) bytesRead;

            //
            //  Copy only as much as the buffer can hold
            //

            RtlCopyMemory( &notification->Contents,
                           buffer,
                           min( notification->BytesToScan, SCANNER_READ_BUFFER_SIZE ) );

            replyLength = sizeof( SCANNER_REPLY );

            status = FltSendMessage( ScannerData.Filter,
                                     &ScannerData.ClientPort,
                                     notification,
                                     sizeof(SCANNER_NOTIFICATION),
                                     notification,
                                     &replyLength,
                                     NULL );

            if (STATUS_SUCCESS == status) {

                *SafeToOpen = ((PSCANNER_REPLY) notification)->SafeToOpen;

            } else {

                //
                //  Couldn't send message
                //

                DbgPrint( "!!! scanner.sys --- couldn't send message to user-mode to scan file, status 0x%X\n", status );
            }
        }

    } finally {

        if (NULL != buffer) {

            FltFreePoolAlignedWithTag( Instance, buffer, 'nacS' );
        }

        if (NULL != notification) {

            ExFreePoolWithTag( notification, 'nacS' );
        }

        if (NULL != volume) {

            FltObjectDereference( volume );
        }
    }

    return status;
}
</code>```

答: If you want to read complete file and send it through the port then you should take care of FltReadFile API and its parameter, There is a parameter which is responsible for how much the file should get read. You have to set the buffer size proper along with Tagged pool. </p>

Body:
I have a scanner file system mini filter driver using the WDK 8.1 samples.

I'm wondering if I can send the entire file up to the user land application so I can do more complicated calculations such as MD5 Hash or anything else really so that I don't have to write more complicated actions in the mini filter driver but instead in the user land application where I don't mind bringing in windows.h and where I can allocate memory on the heap instead of using ExAllocatePoolWithTag and stuff like that.

Can I pass the entire file up to user land mode in one notification?

If not how would I go about chunking that out and syncing.

Here is the interface for the 8.1 scanner file system mini filter driver sample that dictates the communication between the mini filter driver and the user land application:

/*++

Copyright (c) 1999-2002  Microsoft Corporation

Module Name:

    scanuk.h

Abstract:

    Header file which contains the structures, type definitions,
    constants, global variables and function prototypes that are
    shared between kernel and user mode.

Environment:

    Kernel & user mode

--*/

#ifndef __SCANUK_H__
#define __SCANUK_H__

//
//  Name of port used to communicate
//

const PWSTR ScannerPortName = L"\\ScannerPort";

#define SCANNER_READ_BUFFER_SIZE   1024

typedef struct _SCANNER_NOTIFICATION {

    ULONG BytesToScan;
    ULONG Reserved;             // for quad-word alignement of the Contents structure
    UCHAR Contents[SCANNER_READ_BUFFER_SIZE];

} SCANNER_NOTIFICATION, *PSCANNER_NOTIFICATION;

typedef struct _SCANNER_REPLY {

    BOOLEAN SafeToOpen;

} SCANNER_REPLY, *PSCANNER_REPLY;

#endif //  __SCANUK_H__

Notice how there is a 1024 limit on the buffer size being passed. This means I cannot do the MD5 hash on the entire file in the user land application and then would be forced to do it in the mini filter driver, which I want to avoid, if possible.

And here is the function in the mini filter driver that sends the message to the user land application using the interface above:

//////////////////////////////////////////////////////////////////////////
//  Local support routines.
//
/////////////////////////////////////////////////////////////////////////

NTSTATUS
ScannerpScanFileInUserMode (
    _In_ PFLT_INSTANCE Instance,
    _In_ PFILE_OBJECT FileObject,
    _Out_ PBOOLEAN SafeToOpen
    )
/*++

Routine Description:

    This routine is called to send a request up to user mode to scan a given
    file and tell our caller whether it's safe to open this file.

    Note that if the scan fails, we set SafeToOpen to TRUE.  The scan may fail
    because the service hasn't started, or perhaps because this create/cleanup
    is for a directory, and there's no data to read & scan.

    If we failed creates when the service isn't running, there'd be a
    bootstrapping problem -- how would we ever load the .exe for the service?

Arguments:

    Instance - Handle to the filter instance for the scanner on this volume.

    FileObject - File to be scanned.

    SafeToOpen - Set to FALSE if the file is scanned successfully and it contains
                 foul language.

Return Value:

    The status of the operation, hopefully STATUS_SUCCESS.  The common failure
    status will probably be STATUS_INSUFFICIENT_RESOURCES.

--*/

{
    NTSTATUS status = STATUS_SUCCESS;
    PVOID buffer = NULL;
    ULONG bytesRead;
    PSCANNER_NOTIFICATION notification = NULL;
    FLT_VOLUME_PROPERTIES volumeProps;
    LARGE_INTEGER offset;
    ULONG replyLength, length;
    PFLT_VOLUME volume = NULL;

    *SafeToOpen = TRUE;

    //
    //  If not client port just return.
    //

    if (ScannerData.ClientPort == NULL) {

        return STATUS_SUCCESS;
    }

    try {

        //
        //  Obtain the volume object .
        //

        status = FltGetVolumeFromInstance( Instance, &volume );

        if (!NT_SUCCESS( status )) {

            leave;
        }

        //
        //  Determine sector size. Noncached I/O can only be done at sector size offsets, and in lengths which are
        //  multiples of sector size. A more efficient way is to make this call once and remember the sector size in the
        //  instance setup routine and setup an instance context where we can cache it.
        //

        status = FltGetVolumeProperties( volume,
                                         &volumeProps,
                                         sizeof( volumeProps ),
                                         &length );
        //
        //  STATUS_BUFFER_OVERFLOW can be returned - however we only need the properties, not the names
        //  hence we only check for error status.
        //

        if (NT_ERROR( status )) {

            leave;
        }

        length = max( SCANNER_READ_BUFFER_SIZE, volumeProps.SectorSize );

        //
        //  Use non-buffered i/o, so allocate aligned pool
        //

        buffer = FltAllocatePoolAlignedWithTag( Instance,
                                                NonPagedPool,
                                                length,
                                                'nacS' );

        if (NULL == buffer) {

            status = STATUS_INSUFFICIENT_RESOURCES;
            leave;
        }

        notification = ExAllocatePoolWithTag( NonPagedPool,
                                              sizeof( SCANNER_NOTIFICATION ),
                                              'nacS' );

        if(NULL == notification) {

            status = STATUS_INSUFFICIENT_RESOURCES;
            leave;
        }

        //
        //  Read the beginning of the file and pass the contents to user mode.
        //

        offset.QuadPart = bytesRead = 0;
        status = FltReadFile( Instance,
                              FileObject,
                              &offset,
                              length,
                              buffer,
                              FLTFL_IO_OPERATION_NON_CACHED |
                              FLTFL_IO_OPERATION_DO_NOT_UPDATE_BYTE_OFFSET,
                              &bytesRead,
                              NULL,
                              NULL );

        if (NT_SUCCESS( status ) && (0 != bytesRead)) {

            notification->BytesToScan = (ULONG) bytesRead;

            //
            //  Copy only as much as the buffer can hold
            //

            RtlCopyMemory( &notification->Contents,
                           buffer,
                           min( notification->BytesToScan, SCANNER_READ_BUFFER_SIZE ) );

            replyLength = sizeof( SCANNER_REPLY );

            status = FltSendMessage( ScannerData.Filter,
                                     &ScannerData.ClientPort,
                                     notification,
                                     sizeof(SCANNER_NOTIFICATION),
                                     notification,
                                     &replyLength,
                                     NULL );

            if (STATUS_SUCCESS == status) {

                *SafeToOpen = ((PSCANNER_REPLY) notification)->SafeToOpen;

            } else {

                //
                //  Couldn't send message
                //

                DbgPrint( "!!! scanner.sys --- couldn't send message to user-mode to scan file, status 0x%X\n", status );
            }
        }

    } finally {

        if (NULL != buffer) {

            FltFreePoolAlignedWithTag( Instance, buffer, 'nacS' );
        }

        if (NULL != notification) {

            ExFreePoolWithTag( notification, 'nacS' );
        }

        if (NULL != volume) {

            FltObjectDereference( volume );
        }
    }

    return status;
}


问:
Convert 8 bit persample to 1 bit per sample image
I have 8 bit per sample image grayscale. I want to convert it using Libtiff.net:

```<code> using (Tiff input = Tiff.Open(fileIn, "r"))
            {
                using (Tiff output = Tiff.Open(fileOut, "w"))
                {
                    for (short page = 0; page < input.NumberOfDirectories(); page++)
                    {
                        input.SetDirectory(page);
                        output.SetDirectory(page);

                        if (input.GetField(TiffTag.COMPRESSION)[0].ToInt() == (int)Compression.LZW)
                        {
                            int width = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
                            int height = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
                            int xres = input.GetField(TiffTag.XRESOLUTION)[0].ToInt();
                            int yres = input.GetField(TiffTag.YRESOLUTION)[0].ToInt();

                            int samplesPerPixel = input.GetField(TiffTag.SAMPLESPERPIXEL)[0].ToInt();
                            int bitsPerSample = input.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
                            int photo = input.GetField(TiffTag.PHOTOMETRIC)[0].ToInt();

                            int scanlineSize = input.ScanlineSize();

                            byte[][] buffer = new byte[height][];

                            for (int i = 0; i < height; ++i){
                                buffer[i] = new byte[scanlineSize];
                                input.ReadScanline(buffer[i], i);
                            }

                            output.SetField(TiffTag.IMAGEWIDTH, width);
                            output.SetField(TiffTag.IMAGELENGTH, height);
                            output.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
                            output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                            output.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                            output.SetField(TiffTag.BITSPERSAMPLE, 1);
                            output.SetField(TiffTag.XRESOLUTION, xres);
                            output.SetField(TiffTag.YRESOLUTION, yres);

                            for (int i = 0; i < height; ++i)
                                output.WriteScanline(buffer[i], i);

                            output.WriteDirectory();

                        }
                    }
                }

            }
</code>```

How can i get 8 bit array to 1 bit array image?
I want to do it without converting byte array to bitmap object.
What is the right way?
Thanks

答:
First of all, if you go for 1 bit per pixel, note that you get an image with pure black and white pixels.

If your source is a grayscale image, you could just cap it off at 127, and make all > 127 values '1' and all <= 127 values '0', but to get a more accurate representation it might be useful to look into dithering functions.

For the 127-cutoff way, though, you just make an array of your 8-bit data, which should just have the brightness of each pixel as 0-255 range on each byte. The conversion to black and white is pretty trivial:

```<code>for (Int32 i=0; i > imagedata.Length; i++)
    imagedata[i] = imagedata[i] > 127 ? 1 : 0;
</code>```

Then, to convert it to an array of 1-bit data, you can use this function. The "stride" is what you got as scanlineSize in your code. Note that this function only allocates the minimum needed amount of bytes for the stride.

```<code>    /// <summary>
    /// Converts given raw image data for a paletted 8-bit image to lower amount of bits per pixel.
    /// </summary>
    /// <param name="data8bit">The eight bit per pixel image data</param>
    /// <param name="width">The width of the image</param>
    /// <param name="height">The height of the image</param>
    /// <param name="newBpp">The new amount of bits per pixel</param>
    /// <param name="stride">Stride used in the original image data. Will be adjusted to the new stride value.</param>
    /// <param name="bigEndian">Values inside a single byte are read from the largest to the smallest bit.</param>
    /// <returns>The image data converted to the requested amount of bits per pixel.</returns>
private static Byte[] ConvertFrom8Bit(Byte[] data8bit, Int32 width, Int32 height, Int32 bitsLength, Boolean bigEndian)
    {
        if (newBpp > 8)
            throw new ArgumentException("Cannot convert to bit format greater than 8!", "newBpp");
        if (stride < width)
            throw new ArgumentException("Stride is too small for the given width!", "stride");
        if (data8bit.Length < stride * height)
            throw new ArgumentException("Data given data is too small to contain an 8-bit image of the given dimensions", "data8bit");
    Int32 parts = 8 / bitsLength;
    // Amount of bytes to write per width
    Int32 stride = ((bpp * width) + 7) / 8;
    // Bit mask for reducing original data to actual bits maximum.
    // Should not be needed if data is correct, but eh.
    Int32 bitmask = (1 << bitsLength) - 1;
    Byte[] dataXbit = new Byte[stride * height];
    // Actual conversion porcess.
    for (Int32 y = 0; y < height; y++)
    {
        for (Int32 x = 0; x < width; x++)
        {
            // This will hit the same byte multiple times
            Int32 indexXbit = y * stride + x / parts;
            // This will always get a new index
            Int32 index8bit = y * width + x;
            // Amount of bits to shift the data to get to the current pixel data
            Int32 shift = (x % parts) * bitsLength;
            // Reversed for big-endian
            if (bigEndian)
                shift = 8 - shift - bitsLength;
            // Get data, reduce to bit rate, shift it and store it.
            dataXbit[indexXbit] |= (Byte)((data8bit[index8bit] & bitmask) << shift);
        }
    }
    return dataXbit;
}
</code>```

Then it's just a matter of creating a new 1-bit tiff of the correct dimensions, getting its stride, and writing these resulting bytes into the tiff, line by line, keeping the stride in mind.

Note: I don't know how this is with tiff, but in .Net, 1-bit images are paletted, so you might need to give the new image a palette containing that black and white.

Body:
I have 8 bit per sample image grayscale. I want to convert it using Libtiff.net:

 using (Tiff input = Tiff.Open(fileIn, "r"))
            {
                using (Tiff output = Tiff.Open(fileOut, "w"))
                {
                    for (short page = 0; page < input.NumberOfDirectories(); page++)
                    {
                        input.SetDirectory(page);
                        output.SetDirectory(page);

                        if (input.GetField(TiffTag.COMPRESSION)[0].ToInt() == (int)Compression.LZW)
                        {
                            int width = input.GetField(TiffTag.IMAGEWIDTH)[0].ToInt();
                            int height = input.GetField(TiffTag.IMAGELENGTH)[0].ToInt();
                            int xres = input.GetField(TiffTag.XRESOLUTION)[0].ToInt();
                            int yres = input.GetField(TiffTag.YRESOLUTION)[0].ToInt();

                            int samplesPerPixel = input.GetField(TiffTag.SAMPLESPERPIXEL)[0].ToInt();
                            int bitsPerSample = input.GetField(TiffTag.BITSPERSAMPLE)[0].ToInt();
                            int photo = input.GetField(TiffTag.PHOTOMETRIC)[0].ToInt();

                            int scanlineSize = input.ScanlineSize();

                            byte[][] buffer = new byte[height][];

                            for (int i = 0; i < height; ++i){
                                buffer[i] = new byte[scanlineSize];
                                input.ReadScanline(buffer[i], i);
                            }

                            output.SetField(TiffTag.IMAGEWIDTH, width);
                            output.SetField(TiffTag.IMAGELENGTH, height);
                            output.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
                            output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                            output.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                            output.SetField(TiffTag.BITSPERSAMPLE, 1);
                            output.SetField(TiffTag.XRESOLUTION, xres);
                            output.SetField(TiffTag.YRESOLUTION, yres);

                            for (int i = 0; i < height; ++i)
                                output.WriteScanline(buffer[i], i);

                            output.WriteDirectory();

                        }
                    }
                }

            }

How can i get 8 bit array to 1 bit array image?
I want to do it without converting byte array to bitmap object.
What is the right way?
Thanks

Body:
First of all, if you go for 1 bit per pixel, note that you get an image with pure black and white pixels.

If your source is a grayscale image, you could just cap it off at 127, and make all > 127 values '1' and all <= 127 values '0', but to get a more accurate representation it might be useful to look into dithering functions.

For the 127-cutoff way, though, you just make an array of your 8-bit data, which should just have the brightness of each pixel as 0-255 range on each byte. The conversion to black and white is pretty trivial:

for (Int32 i=0; i > imagedata.Length; i++)
    imagedata[i] = imagedata[i] > 127 ? 1 : 0;

Then, to convert it to an array of 1-bit data, you can use this function. The "stride" is what you got as scanlineSize in your code. Note that this function only allocates the minimum needed amount of bytes for the stride.

    /// <summary>
    /// Converts given raw image data for a paletted 8-bit image to lower amount of bits per pixel.
    /// </summary>
    /// <param name="data8bit">The eight bit per pixel image data</param>
    /// <param name="width">The width of the image</param>
    /// <param name="height">The height of the image</param>
    /// <param name="newBpp">The new amount of bits per pixel</param>
    /// <param name="stride">Stride used in the original image data. Will be adjusted to the new stride value.</param>
    /// <param name="bigEndian">Values inside a single byte are read from the largest to the smallest bit.</param>
    /// <returns>The image data converted to the requested amount of bits per pixel.</returns>
private static Byte[] ConvertFrom8Bit(Byte[] data8bit, Int32 width, Int32 height, Int32 bitsLength, Boolean bigEndian)
    {
        if (newBpp > 8)
            throw new ArgumentException("Cannot convert to bit format greater than 8!", "newBpp");
        if (stride < width)
            throw new ArgumentException("Stride is too small for the given width!", "stride");
        if (data8bit.Length < stride * height)
            throw new ArgumentException("Data given data is too small to contain an 8-bit image of the given dimensions", "data8bit");
    Int32 parts = 8 / bitsLength;
    // Amount of bytes to write per width
    Int32 stride = ((bpp * width) + 7) / 8;
    // Bit mask for reducing original data to actual bits maximum.
    // Should not be needed if data is correct, but eh.
    Int32 bitmask = (1 << bitsLength) - 1;
    Byte[] dataXbit = new Byte[stride * height];
    // Actual conversion porcess.
    for (Int32 y = 0; y < height; y++)
    {
        for (Int32 x = 0; x < width; x++)
        {
            // This will hit the same byte multiple times
            Int32 indexXbit = y * stride + x / parts;
            // This will always get a new index
            Int32 index8bit = y * width + x;
            // Amount of bits to shift the data to get to the current pixel data
            Int32 shift = (x % parts) * bitsLength;
            // Reversed for big-endian
            if (bigEndian)
                shift = 8 - shift - bitsLength;
            // Get data, reduce to bit rate, shift it and store it.
            dataXbit[indexXbit] |= (Byte)((data8bit[index8bit] & bitmask) << shift);
        }
    }
    return dataXbit;
}

Then it's just a matter of creating a new 1-bit tiff of the correct dimensions, getting its stride, and writing these resulting bytes into the tiff, line by line, keeping the stride in mind.

Note: I don't know how this is with tiff, but in .Net, 1-bit images are paletted, so you might need to give the new image a palette containing that black and white.


问:
Elastic search backup - snapshot disk whilst running?
Im running a single ES instance. After I have inserted around 100k documents would I be able to take a snapshot of the disk where the data dir is and restore it without any issues every time? (Whilst ES is still running).

Or do I need to shutdown ES, or have an explicit "write all inserts to disk" config?

MySQL Innodb tables will only restore cleanly if you take the disk snapshot after MySQL has run its shutdown. Is ES the same?

My ES version:

```<code>   "version": {
      "number": "5.4.2",
      "build_hash": "929b078",
      "build_date": "2017-06-15T02:29:28.122Z",
      "build_snapshot": false,
      "lucene_version": "6.5.1"
   },
</code>```

答: There is no guarantee that this will contain a useful point-in-time snapshot that can be restored. You would need to jump through several hoops to ensure this (stoppping indexing, flushing, ensuring no merges are happening). As this is too complicated the official way of doing a backup is using the snapshot and restore API. This ensures a valid point in time snapshot, that can also be restored on other clusters.</p>

Body:
Im running a single ES instance. After I have inserted around 100k documents would I be able to take a snapshot of the disk where the data dir is and restore it without any issues every time? (Whilst ES is still running).

Or do I need to shutdown ES, or have an explicit "write all inserts to disk" config?

MySQL Innodb tables will only restore cleanly if you take the disk snapshot after MySQL has run its shutdown. Is ES the same?

My ES version:

   "version": {
      "number": "5.4.2",
      "build_hash": "929b078",
      "build_date": "2017-06-15T02:29:28.122Z",
      "build_snapshot": false,
      "lucene_version": "6.5.1"
   },


问:
TCL, extract 2 integers from string into list?
I have 2 string formatted as such:

```<code>(1234, 4567)
</code>```

And I have a list

```<code>points {0 1 2 4}
</code>```

I would like to extract 2 integers from the first list and replace the first two integers in the list, after that extract two more integers from the 2nd list and replace the 3rd and 4th integers in the list so at the end I will have a list of 4 integers from the two strings.

So far I have tried all kind of things but always end up with errors or brackets in the list which I do not want. I feel I am missing out on the easy way to do that.

答:
With the first set of values, you can parse with scan or regexp; in this case, I think scan looks better:

```<code>set input "(1234, 5678)"
scan $input "(%d,%d)" a b
</code>```

To update a Tcl list (formally, one in a variable), you use lset; you can give a sequence of (zero-based) indices to it to navigate into the exact place in the list where you want to update:

```<code>set workingArea "points {0 1 2 4}"
lset workingArea 1 2 $a
lset workingArea 1 3 $b

puts $workingArea
# prints: points {0 1 1234 5678}
</code>```

Body:
I have 2 string formatted as such:

(1234, 4567)

And I have a list

points {0 1 2 4}

I would like to extract 2 integers from the first list and replace the first two integers in the list, after that extract two more integers from the 2nd list and replace the 3rd and 4th integers in the list so at the end I will have a list of 4 integers from the two strings.

So far I have tried all kind of things but always end up with errors or brackets in the list which I do not want. I feel I am missing out on the easy way to do that.

Body:
With the first set of values, you can parse with scan or regexp; in this case, I think scan looks better:

set input "(1234, 5678)"
scan $input "(%d,%d)" a b

To update a Tcl list (formally, one in a variable), you use lset; you can give a sequence of (zero-based) indices to it to navigate into the exact place in the list where you want to update:

set workingArea "points {0 1 2 4}"
lset workingArea 1 2 $a
lset workingArea 1 3 $b

puts $workingArea
# prints: points {0 1 1234 5678}


问:
.NET Core Dependency Tree
Is it possible to view dependencies for a project in a .net core application?  I'm using Visual Studio 2017 Professional.

At the moment I have the following nugget packages referenced in my csproj.

```<code><ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.1" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />
    <PackageReference Include="SimpleInjector.Integration.AspNetCore.Mvc" Version="4.0.8" />
</ItemGroup>
</code>```

Where you can navigate dependencies.

But it makes it hard to find a particular dependency - a tree is good if you know what you are looking for.  Is there a way to output a flat list of dependant assemblies and there versions?

答:
You can add an msbuild target to your project file (inside the <Project> element) like this:

```<code><Target Name="PrintAllReferences" DependsOnTargets="RunResolvePackageDependencies">
  <Message Importance="high" Text="Referenced package: %(PackageDefinitions.Identity)" />
</Target>
</code>```

Which you can call like this (a line without a parent package name means it is referenced by the project directly):

```<code>$ dotnet msbuild /nologo /t:PrintAllReferences
  Referenced package: Microsoft.NETCore.Platforms/1.1.0
  Referenced package: Microsoft.NETCore.Targets/1.1.0
  Referenced package: Microsoft.Win32.Primitives/4.3.0
  Referenced package: NETStandard.Library/1.6.1
  Referenced package: runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.fedora.23-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.fedora.24-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.native.System/4.3.0
  Referenced package: runtime.native.System.IO.Compression/4.3.0
  Referenced package: runtime.native.System.Net.Http/4.3.0
  Referenced package: runtime.native.System.Security.Cryptography.Apple/4.3.0
  Referenced package: runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.opensuse.13.2-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.opensuse.42.1-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: System.Buffers/4.3.0
  Referenced package: System.Collections/4.3.0
  …
</code>```

If you wanted a "reverse dependency tree" - a list of packages and which packages reference them - you can do something similar to:

```<code><Target Name="PrintPackagesAndParents" DependsOnTargets="RunResolvePackageDependencies">
  <Message Importance="high" Text="* %(PackageDependencies.Identity) referenced by:%0a^---@(PackageDependencies->'%(ParentPackage) - target %(ParentTarget)', '%0a^---')" />
</Target>
</code>```

which produces the following output:

```<code>$ dotnet msbuild /nologo /t:PrintPackagesAndParents
  * JetBrains.Annotations/10.2.1 referenced by:
  ^--- - target .NETStandard,Version=v1.3
  * System.IO.FileSystem.Primitives/4.0.1 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.IO.Compression.ZipFile/4.0.1 - target .NETStandard,Version=v1.3
  ^---System.IO.FileSystem/4.0.1 - target .NETStandard,Version=v1.3
  ^---System.Xml.ReaderWriter/4.0.11 - target .NETStandard,Version=v1.3
  * System.Linq/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.Security.Cryptography.Encoding/4.0.0 - target .NETStandard,Version=v1.3
  * System.Linq.Expressions/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  * System.Net.Http/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  * System.Net.Primitives/4.0.11 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.Net.Http/4.1.0 - target .NETStandard,Version=v1.3
  ^---System.Net.Sockets/4.1.0 - target .NETStandard,Version=v1.3
  …
</code>```

There isn't really documentation about these items, but they have "public" name and are generated by the ResolvePackageDependencies task which is executed as part of the RunResolvePackageDependencies target and produces a few very useful items: TargetDefinitions, PackageDefinitions, PackageDependencies, FileDependencies and DiagnosticMessages.

Title: .NET Core Dependency Tree

Body:
Is it possible to view dependencies for a project in a .net core application?  I'm using Visual Studio 2017 Professional.

At the moment I have the following nugget packages referenced in my csproj.

<ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.1" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />
    <PackageReference Include="SimpleInjector.Integration.AspNetCore.Mvc" Version="4.0.8" />
</ItemGroup>

Where you can navigate dependencies.

But it makes it hard to find a particular dependency - a tree is good if you know what you are looking for.  Is there a way to output a flat list of dependant assemblies and there versions?

Body:
You can add an msbuild target to your project file (inside the <Project> element) like this:

<Target Name="PrintAllReferences" DependsOnTargets="RunResolvePackageDependencies">
  <Message Importance="high" Text="Referenced package: %(PackageDefinitions.Identity)" />
</Target>

Which you can call like this (a line without a parent package name means it is referenced by the project directly):

$ dotnet msbuild /nologo /t:PrintAllReferences
  Referenced package: Microsoft.NETCore.Platforms/1.1.0
  Referenced package: Microsoft.NETCore.Targets/1.1.0
  Referenced package: Microsoft.Win32.Primitives/4.3.0
  Referenced package: NETStandard.Library/1.6.1
  Referenced package: runtime.debian.8-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.fedora.23-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.fedora.24-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.native.System/4.3.0
  Referenced package: runtime.native.System.IO.Compression/4.3.0
  Referenced package: runtime.native.System.Net.Http/4.3.0
  Referenced package: runtime.native.System.Security.Cryptography.Apple/4.3.0
  Referenced package: runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.opensuse.13.2-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: runtime.opensuse.42.1-x64.runtime.native.System.Security.Cryptography.OpenSsl/4.3.0
  Referenced package: System.Buffers/4.3.0
  Referenced package: System.Collections/4.3.0
  …

If you wanted a "reverse dependency tree" - a list of packages and which packages reference them - you can do something similar to:

<Target Name="PrintPackagesAndParents" DependsOnTargets="RunResolvePackageDependencies">
  <Message Importance="high" Text="* %(PackageDependencies.Identity) referenced by:%0a^---@(PackageDependencies->'%(ParentPackage) - target %(ParentTarget)', '%0a^---')" />
</Target>

which produces the following output:

$ dotnet msbuild /nologo /t:PrintPackagesAndParents
  * JetBrains.Annotations/10.2.1 referenced by:
  ^--- - target .NETStandard,Version=v1.3
  * System.IO.FileSystem.Primitives/4.0.1 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.IO.Compression.ZipFile/4.0.1 - target .NETStandard,Version=v1.3
  ^---System.IO.FileSystem/4.0.1 - target .NETStandard,Version=v1.3
  ^---System.Xml.ReaderWriter/4.0.11 - target .NETStandard,Version=v1.3
  * System.Linq/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.Security.Cryptography.Encoding/4.0.0 - target .NETStandard,Version=v1.3
  * System.Linq.Expressions/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  * System.Net.Http/4.1.0 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  * System.Net.Primitives/4.0.11 referenced by:
  ^---NETStandard.Library/1.6.0 - target .NETStandard,Version=v1.3
  ^---System.Net.Http/4.1.0 - target .NETStandard,Version=v1.3
  ^---System.Net.Sockets/4.1.0 - target .NETStandard,Version=v1.3
  …

There isn't really documentation about these items, but they have "public" name and are generated by the ResolvePackageDependencies task which is executed as part of the RunResolvePackageDependencies target and produces a few very useful items: TargetDefinitions, PackageDefinitions, PackageDependencies, FileDependencies and DiagnosticMessages.

ContentLicense: CC BY-SA 4.0


问:
SimpleSchema: Conditionally required field is not working
This is how I'm doing a validation using SimpleSchema with a conditionally required field (module). So this should only be required if type has the value 'start'

client

```<code>const   module = 'articles',
        _id = 'bmphCpyHZLhTc74Zp'

console.log(module, _id)
// returns as expected 'articles' and 'bmphCpyHZLhTc74Zp'

example.call(
    {
        type  : 'start',
        module: module,
        _id   : _id
    },
    (error, result) => {
        if (error)  console.log(error)
    }
)
</code>```

server

```<code>example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        _id : { type: SimpleSchema.RegEx.Id },
        type: {
            type         : String,
            allowedValues: ['start', 'stop'] },
        module: {
            type         : String,
            optional     : true,
            allowedValues: ['articles'],
            custom       : function() {
                if (this.field('type').value === 'start') return 'required'
                return null
            }
        }
    }).validator(),

    run({ type, _id, module }) {
        console.log(_id, module)
    }
})
</code>```

But I do get the error "validation-error" with reason "Module is required".

I do not understand that, as you can see module has a value at all!

答:
The validation error occurs because you don't check if module contains any value(my answer to your previous question contained error), so every time when type value equals start the method throw error about a required field. It don't even check if module field has any value. I post your fixed code.

```<code>example = new ValidatedMethod({
  name    : 'example',
  validate: new SimpleSchema({
    _id : { type: SimpleSchema.RegEx.Id },
    type: {
      type: String,
      allowedValues: ['start', 'stop']
    },
    module: {
      type: String,
      optional: true,
      allowedValues: ['articles'],
      custom: function() {
        if (this.field('type').value === 'start') {
          if(!this.isSet || this.value === null || this.value === "") {
            return 'required'
          }
        }
      }
    }
  }).validator(),
  run({ type, _id, module }) {
    console.log(_id, module)
  }
})
</code>```

Body:
This is how I'm doing a validation using SimpleSchema with a conditionally required field (module). So this should only be required if type has the value 'start'

client

const   module = 'articles',
        _id = 'bmphCpyHZLhTc74Zp'

console.log(module, _id)
// returns as expected 'articles' and 'bmphCpyHZLhTc74Zp'

example.call(
    {
        type  : 'start',
        module: module,
        _id   : _id
    },
    (error, result) => {
        if (error)  console.log(error)
    }
)

server

example = new ValidatedMethod({
    name    : 'example',
    validate: new SimpleSchema({
        _id : { type: SimpleSchema.RegEx.Id },
        type: {
            type         : String,
            allowedValues: ['start', 'stop'] },
        module: {
            type         : String,
            optional     : true,
            allowedValues: ['articles'],
            custom       : function() {
                if (this.field('type').value === 'start') return 'required'
                return null
            }
        }
    }).validator(),

    run({ type, _id, module }) {
        console.log(_id, module)
    }
})

But I do get the error "validation-error" with reason "Module is required".

I do not understand that, as you can see module has a value at all!

Body:
The validation error occurs because you don't check if module contains any value(my answer to your previous question contained error), so every time when type value equals start the method throw error about a required field. It don't even check if module field has any value. I post your fixed code.

example = new ValidatedMethod({
  name    : 'example',
  validate: new SimpleSchema({
    _id : { type: SimpleSchema.RegEx.Id },
    type: {
      type: String,
      allowedValues: ['start', 'stop']
    },
    module: {
      type: String,
      optional: true,
      allowedValues: ['articles'],
      custom: function() {
        if (this.field('type').value === 'start') {
          if(!this.isSet || this.value === null || this.value === "") {
            return 'required'
          }
        }
      }
    }
  }).validator(),
  run({ type, _id, module }) {
    console.log(_id, module)
  }
})


问:
Browser displaying "Directory Listing -- /"
I'm developing the most simple ASP.NET application which is giving me an annoying error.

I'm having a textbox- and a button-control, where I would like the text in the textbox to be saved to a database table when clicking the button. The text will be propagated to the database by means of a WCF service.

Since I'm a rather mediocre programmer, I tend to get errors now and then which results in lots of error messages displayed in the browser. That I can understand. I fix them and build my solution and press F5 to get going. But after fixing the errors, everytime the browser displays a directory listening like the one below instead of my astonishing UI.

Directory Listing -- /

```<code>Monday, December 20, 2010 10:10 PM        <dir> bin
Saturday, December 18, 2010 10:10 PM      1,303 MainForm.aspx
Monday, December 20, 2010 10:28 PM        467 MainForm.aspx.cs
Saturday, December 18, 2010 10:09 PM      2,118 MainForm.aspx.designer.cs
Friday, December 17, 2010 10:25 PM        <dir> obj
Friday, December 17, 2010 10:25 PM        <dir> Properties
Sunday, December 19, 2010 10:09 PM        <dir> Service References
Monday, December 20, 2010 02:01 PM        5,552 SimpleChat.csproj
Monday, December 20, 2010 02:01 PM        1,170 SimpleChat.csproj.user
Sunday, December 19, 2010 10:09 PM        1,810 Web.config
Friday, December 17, 2010 10:25 PM        1,285 Web.Debug.config
Friday, December 17, 2010 10:25 PM        1,346 Web.Release.config
</code>```

Version Information: ASP.NET
  Development Server 10.0.0.0

Why on earth is this happening?

I know how to work around but its tedious: in MainForm.aspx.cs I comment the rows concerning the call to the service, then I rebuild the solution, uncomment the call to the service and rebuild the solution again. Then everything works as expected till I ran into the next bug.

Thanks for reading... ;-)

答: I'm no expert on ASP, but I'd say you're missing an index page.</p>

Body:
I'm developing the most simple ASP.NET application which is giving me an annoying error.

I'm having a textbox- and a button-control, where I would like the text in the textbox to be saved to a database table when clicking the button. The text will be propagated to the database by means of a WCF service.

Since I'm a rather mediocre programmer, I tend to get errors now and then which results in lots of error messages displayed in the browser. That I can understand. I fix them and build my solution and press F5 to get going. But after fixing the errors, everytime the browser displays a directory listening like the one below instead of my astonishing UI.

Directory Listing -- /

Monday, December 20, 2010 10:10 PM        <dir> bin
Saturday, December 18, 2010 10:10 PM      1,303 MainForm.aspx
Monday, December 20, 2010 10:28 PM        467 MainForm.aspx.cs
Saturday, December 18, 2010 10:09 PM      2,118 MainForm.aspx.designer.cs
Friday, December 17, 2010 10:25 PM        <dir> obj
Friday, December 17, 2010 10:25 PM        <dir> Properties
Sunday, December 19, 2010 10:09 PM        <dir> Service References
Monday, December 20, 2010 02:01 PM        5,552 SimpleChat.csproj
Monday, December 20, 2010 02:01 PM        1,170 SimpleChat.csproj.user
Sunday, December 19, 2010 10:09 PM        1,810 Web.config
Friday, December 17, 2010 10:25 PM        1,285 Web.Debug.config
Friday, December 17, 2010 10:25 PM        1,346 Web.Release.config

Version Information: ASP.NET
  Development Server 10.0.0.0

Why on earth is this happening?

I know how to work around but its tedious: in MainForm.aspx.cs I comment the rows concerning the call to the service, then I rebuild the solution, uncomment the call to the service and rebuild the solution again. Then everything works as expected till I ran into the next bug.

Thanks for reading... ;-)


问:
WCF Service - Getting list from request header
I'm trying to recover a list key-value from request header in a WCF service. I'm able to recover a single property, but I can't find how to recover a list.

This is my call:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
  <soapenv:Header>
    <tem:header1>Header 1</tem:header1>
    <tem:Properties>
      <tem:property>
        <key>KEY.ONE</key>
        <value>value1</value>
      </tem:property>
      <tem:property>
        <key>KEY.TWO</key>
        <value>value2</value>
      </tem:property>
    </tem:Properties>
  </soapenv:Header>
  <soapenv:Body>
    <tem:function1>
      <tem:param1>100</tem:param1>
    </tem:function1>
  </soapenv:Body>
</soapenv:Envelope>
</code>```

And this is how I recover "header1":

```<code>MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string header1 = headers.GetHeader<string>("header1", "http://tempuri.org/");
</code>```

I thought that I could use something like:

```<code>IDictionary<string, string> properties = headers.GetHeader<Dictionary<string, string>>("Properties", "http://tempuri.org/");
</code>```

But properties is always null.

答:
As MSDN says the GetHeader<T>(string, string) method only is capable of returning header that is serialized by DataContractSerializer, which means your property objects should exist as a .NET type.

What you can do instead is to use GetHeader<T>(string, string, XmlObjectSerializer) which uses serializer to deserialize the content of the header value and return it.

For that you need to implement your own serializer that will read the content and return dictionary. I think something like that would work (depends on whether key and value are strictly in this order or can be swapped). Also, I didn't check what happens with namespaces.

```<code>public class MySerializer : XmlObjectSerializer
{

  public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
  {
    reader.ReadFullStartElement();
    Dictionary<string, string> r = new Dictionary<string, string>();
    while (reader.IsStartElement("property"))
    {
      reader.ReadFullStartElement("property");
      reader.ReadFullStartElement("key");
      string key = reader.ReadContentAsString();
      reader.ReadEndElement();
      reader.ReadFullStartElement("value");
      string value = reader.ReadContentAsString();
      reader.ReadEndElement();
      r.Add(key, value);

      reader.ReadEndElement();
      reader.MoveToContent();
    }
    return r;
  }

  public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
  {
    throw new NotImplementedException();
  }

  public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
  {
    throw new NotImplementedException();
  }

  public override void WriteEndObject(XmlDictionaryWriter writer)
  {
    throw new NotImplementedException();
  }

  public override bool IsStartObject(XmlDictionaryReader reader)
  {
    throw new NotImplementedException();
  }
}
</code>```

Body:
I'm trying to recover a list key-value from request header in a WCF service. I'm able to recover a single property, but I can't find how to recover a list.

This is my call:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
  <soapenv:Header>
    <tem:header1>Header 1</tem:header1>
    <tem:Properties>
      <tem:property>
        <key>KEY.ONE</key>
        <value>value1</value>
      </tem:property>
      <tem:property>
        <key>KEY.TWO</key>
        <value>value2</value>
      </tem:property>
    </tem:Properties>
  </soapenv:Header>
  <soapenv:Body>
    <tem:function1>
      <tem:param1>100</tem:param1>
    </tem:function1>
  </soapenv:Body>
</soapenv:Envelope>

And this is how I recover "header1":

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string header1 = headers.GetHeader<string>("header1", "http://tempuri.org/");

I thought that I could use something like:

IDictionary<string, string> properties = headers.GetHeader<Dictionary<string, string>>("Properties", "http://tempuri.org/");

But properties is always null.

Body:
As MSDN says the GetHeader<T>(string, string) method only is capable of returning header that is serialized by DataContractSerializer, which means your property objects should exist as a .NET type.

What you can do instead is to use GetHeader<T>(string, string, XmlObjectSerializer) which uses serializer to deserialize the content of the header value and return it.

For that you need to implement your own serializer that will read the content and return dictionary. I think something like that would work (depends on whether key and value are strictly in this order or can be swapped). Also, I didn't check what happens with namespaces.

public class MySerializer : XmlObjectSerializer
{

  public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
  {
    reader.ReadFullStartElement();
    Dictionary<string, string> r = new Dictionary<string, string>();
    while (reader.IsStartElement("property"))
    {
      reader.ReadFullStartElement("property");
      reader.ReadFullStartElement("key");
      string key = reader.ReadContentAsString();
      reader.ReadEndElement();
      reader.ReadFullStartElement("value");
      string value = reader.ReadContentAsString();
      reader.ReadEndElement();
      r.Add(key, value);

      reader.ReadEndElement();
      reader.MoveToContent();
    }
    return r;
  }

  public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
  {
    throw new NotImplementedException();
  }

  public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
  {
    throw new NotImplementedException();
  }

  public override void WriteEndObject(XmlDictionaryWriter writer)
  {
    throw new NotImplementedException();
  }

  public override bool IsStartObject(XmlDictionaryReader reader)
  {
    throw new NotImplementedException();
  }
}


问:
FolderExists returning wrong value
I'm trying to get the last modified date of a file that is on a different server than the one I have the website page on. The problem is that the path to that file is like \\something.com\foldername\file.xlsx. I read that you can't use Server.MapPath with a path that contains double slashes or backslashes. I tried to replace the double backslash with one, three or four backslashes but it's not working. This is my code until now:

```<code><%
dim fs, f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile(Server.MapPath("\\something.com\foldername\file.xlsx"))
Response.Write("The file was last modified on: <h1 id='dateTime'>")
Response.Write(f.DateLastModified)
Response.Write("</h1>")
set f=nothing
set fs=nothing
%>
</code>```

If I copy the file in the directory that contains the code and replace that line with..

```<code>set f=fs.GetFile(Server.MapPath("file.xlsx"))
</code>```

..it works, but I don't get it how I can make it work with the original file.

Does anyone know how what I can do to replace the double backslash so that the program will work? I get a blank page if I try to use the code I posted.

答:
I think you do not know the difference between a relative and absolute path.

Say you want to create a link on your site to download the xlsx, you create a link like this.

```<code><a href="/foldername/file.xlsx">file.xlsx</a>
</code>```

However the absolute path on the server is something like

```<code>C:\inetpub\wwwroot\something.com\foldername\file.xlsx
</code>```

What Server.MapPath does is translate the relative path to the absoule path so that the file can be located in a normal file system. So you use it like you would a normal html link.

```<code>Server.MapPath("/foldername/file.xlsx")
</code>```

So if you want to know the last modified date you now do this:

```<code>FileInfo file = new FileInfo(Server.MapPath("/foldername/file.xlsx"));
Label1.Text = file.LastWriteTime.ToString();
</code>```

Title: FolderExists returning wrong value

Body:
I'm trying to get the last modified date of a file that is on a different server than the one I have the website page on. The problem is that the path to that file is like \\something.com\foldername\file.xlsx. I read that you can't use Server.MapPath with a path that contains double slashes or backslashes. I tried to replace the double backslash with one, three or four backslashes but it's not working. This is my code until now:

<%
dim fs, f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile(Server.MapPath("\\something.com\foldername\file.xlsx"))
Response.Write("The file was last modified on:
")
Response.Write(f.DateLastModified)
Response.Write("
")
set f=nothing
set fs=nothing
%>

If I copy the file in the directory that contains the code and replace that line with..

set f=fs.GetFile(Server.MapPath("file.xlsx"))

..it works, but I don't get it how I can make it work with the original file.

Does anyone know how what I can do to replace the double backslash so that the program will work? I get a blank page if I try to use the code I posted.

Body:
I think you do not know the difference between a relative and absolute path.

Say you want to create a link on your site to download the xlsx, you create a link like this.

<a href="/foldername/file.xlsx">file.xlsx</a>

However the absolute path on the server is something like

C:\inetpub\wwwroot\something.com\foldername\file.xlsx

What Server.MapPath does is translate the relative path to the absoule path so that the file can be located in a normal file system. So you use it like you would a normal html link.

Server.MapPath("/foldername/file.xlsx")

So if you want to know the last modified date you now do this:

FileInfo file = new FileInfo(Server.MapPath("/foldername/file.xlsx"));
Label1.Text = file.LastWriteTime.ToString();


问:
how to ignore dir-prop-base in .svn folder?
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

```<code>Apps\.svn\dir-prop-base
Apps\.svn\entries
</code>```

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

```<code>syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*
</code>```

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.

答:
The following simple .hgignore works fine for me to ignore all .svn folders (on Windows, hg 1.7):

```<code>syntax: glob
.svn
</code>```

Body:
I've read several posts here about ignoring files in Mercurial but I'm stumped on this one.

I have a couple of .svn files in my repository (I'm using hg for local commits, then pushing to svn). The files are:

Apps\.svn\dir-prop-base
Apps\.svn\entries

I've got several ignore entries in my .hgignore but none of them seem to be covering these two files.

syntax: glob
.svn/*
**/.svn/**.*
syntax: regexp
\.svn\\*

I'm trying a couple of things to see which sticks there. To me, it looks like those files should be ignored twice. The strange thing is that Apps\.svn\all-wcprops is being ignored. Clearly I'm missing something. I'm checking whether the files are ignored by opening a new status window using TortoiseHg. I can't detect any difference between that and hg status.

Body:
The following simple .hgignore works fine for me to ignore all .svn folders (on Windows, hg 1.7):

syntax: glob
.svn


问:
Common link to redirect to PlayStore or AppStore accordingly using nodejs
I need to create a common link that redirect to Android PlayStore or Apple App Store according to the os. This link will open in the browser.</p>

答:
You can do that using javascript:</p>

```<code>function changeLink(){
    document.getElementById('link').href= getMobileOperatingSystem();
}

function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      // Windows Phone must come first because its UA also contains "Android"
    if (/windows phone/i.test(userAgent)) {
        return "windows-link";
    }

    if (/android/i.test(userAgent)) {
        return "android-link";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "ios-link";
    }

    return "ios-link"; // default
}
</code>```

Body:
You can do that using javascript:

function changeLink(){
    document.getElementById('link').href= getMobileOperatingSystem();
}

function getMobileOperatingSystem() {
  var userAgent = navigator.userAgent || navigator.vendor || window.opera;

      // Windows Phone must come first because its UA also contains "Android"
    if (/windows phone/i.test(userAgent)) {
        return "windows-link";
    }

    if (/android/i.test(userAgent)) {
        return "android-link";
    }

    // iOS detection from: http://stackoverflow.com/a/9039885/177710
    if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
        return "ios-link";
    }

    return "ios-link"; // default
}


问:
Token-based Authentication with Cornice for Pyramid
I am using the Resources strategy of developing a RESTful API within a Pyramid App.
http://cornice.readthedocs.io/en/latest/resources.html. However I couldn't find an example of adding authentication for the API. Any guidance is greatly appreciated.</p>

答:
As Antoine Leclair pointed out, Cornice relies on Pyramid. You will have to enable an authorization and an authentication policies during your app initialization. For example (here using pyramid-jwt):

```<code>from pyramid.config import Configurator
from pyramid.authorization import ACLAuthorizationPolicy

def main():
    config = Configurator()
    # Pyramid requires an authorization policy to be active.
    config.set_authorization_policy(ACLAuthorizationPolicy())
    # Enable JWT authentication.
    config.include('pyramid_jwt')
    config.set_jwt_authentication_policy('secret')
</code>```

You can also create your own policy, by inheriting from builtin Pyramid classes in pyramid.authentication:

```<code>from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy
from zope.interface import implementer

@implementer(IAuthenticationPolicy)
class MyAuthenticationPolicy(CallbackAuthenticationPolicy):
    def __init__(self, realm='Realm'):
        self.realm = realm

    def unauthenticated_userid(self, request):
        user_id = self._get_credentials(request)
        return user_id

    def forget(self, request):
        return [('WWW-Authenticate', 'MyAuth realm="%s"' % self.realm)]

    def _get_credentials(self, request):
        authorization = request.headers.get('Authorization', '')
        # your own strategy...
        # if valid: return user_id
        # else return None
</code>```

Check out existing projects on awesome-pyramid to see if what you need is already there...

Body:
As Antoine Leclair pointed out, Cornice relies on Pyramid. You will have to enable an authorization and an authentication policies during your app initialization. For example (here using pyramid-jwt):

from pyramid.config import Configurator
from pyramid.authorization import ACLAuthorizationPolicy

def main():
    config = Configurator()
    # Pyramid requires an authorization policy to be active.
    config.set_authorization_policy(ACLAuthorizationPolicy())
    # Enable JWT authentication.
    config.include('pyramid_jwt')
    config.set_jwt_authentication_policy('secret')

You can also create your own policy, by inheriting from builtin Pyramid classes in pyramid.authentication:

from pyramid.authentication import CallbackAuthenticationPolicy
from pyramid.interfaces import IAuthenticationPolicy
from zope.interface import implementer

@implementer(IAuthenticationPolicy)
class MyAuthenticationPolicy(CallbackAuthenticationPolicy):
    def __init__(self, realm='Realm'):
        self.realm = realm

    def unauthenticated_userid(self, request):
        user_id = self._get_credentials(request)
        return user_id

    def forget(self, request):
        return [('WWW-Authenticate', 'MyAuth realm="%s"' % self.realm)]

    def _get_credentials(self, request):
        authorization = request.headers.get('Authorization', '')
        # your own strategy...
        # if valid: return user_id
        # else return None

Check out existing projects on awesome-pyramid to see if what you need is already there...


问:
Android Studio wrong breakpoints
I try to debug some code, but Android Studio debugger behaves strange today.

It accepts breakpoints like randomly. Where there is no executable code preview sometimes shows there is. And for executable lines preview says that the code is not executable.

I tried to sync, clean, rebuild, invalidate cashes/restart, but notheng had effect.

Has someone faced this problem before and whta is the solution?

答: that is an invalid break point that shows when the breakpoint is set on a commented or non-executable line indicating that such breakpoint would not be hit.</p>

Title: Android Studio wrong breakpoints


问:
pip install pyemd error?
I'm trying to install pyemd package in Python through pip and getting following error:

```<code>C:\Users\dipanwita.neogy>pip install pyemd
Collecting pyemd
  Using cached pyemd-0.4.3.tar.gz
Requirement already satisfied: numpy<2.0.0,>=1.9.0 in c:\users\dipanwita.neogy\a
naconda3\lib\site-packages (from pyemd)
Building wheels for collected packages: pyemd
  Running setup.py bdist_wheel for pyemd ... error
  Complete output from command C:\Users\dipanwita.neogy\Anaconda3\python.exe -u
-c "import setuptools, tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Loca
l\\Temp\\pip-build-nk13uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open)(
__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __fil
e__, 'exec'))" bdist_wheel -d C:\Users\DIPANW~1.NEO\AppData\Local\Temp\tmpngn2np
rmpip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-3.6
  creating build\lib.win32-3.6\pyemd
  copying pyemd\__about__.py -> build\lib.win32-3.6\pyemd
  copying pyemd\__init__.py -> build\lib.win32-3.6\pyemd
  running build_ext
  building 'pyemd.emd' extension
  error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C+
+ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

  ----------------------------------------
  Failed building wheel for pyemd
  Running setup.py clean for pyemd
Failed to build pyemd
Installing collected packages: pyemd
  Running setup.py install for pyemd ... error
    Complete output from command C:\Users\dipanwita.neogy\Anaconda3\python.exe -
u -c "import setuptools, tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Lo
cal\\Temp\\pip-build-nk13uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open
)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __f
ile__, 'exec'))" install --record C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-e
rihhtfj-record\install-record.txt --single-version-externally-managed --compile:

    running install
    running build
    running build_py
    creating build
    creating build\lib.win32-3.6
    creating build\lib.win32-3.6\pyemd
    copying pyemd\__about__.py -> build\lib.win32-3.6\pyemd
    copying pyemd\__init__.py -> build\lib.win32-3.6\pyemd
    running build_ext
    building 'pyemd.emd' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    ----------------------------------------
Command "C:\Users\dipanwita.neogy\Anaconda3\python.exe -u -c "import setuptools,
 tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Local\\Temp\\pip-build-nk1
3uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read(
).replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install
 --record C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-erihhtfj-record\install-r
ecord.txt --single-version-externally-managed --compile" failed with error code
1 in C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-build-nk13uh5b\pyemd\
</code>```

I cannot find anything regarding this error. Please suggest me what should I do?

答:
The error you are receiving is: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools. You need to read the error message carefully.

You just need to go to the link they have provided for you and follow the instructions: http://landinghub.visualstudio.com/visual-cpp-build-tools

Title: pip install pyemd error?

Body:
I'm trying to install pyemd package in Python through pip and getting following error:

C:\Users\dipanwita.neogy>pip install pyemd
Collecting pyemd
  Using cached pyemd-0.4.3.tar.gz
Requirement already satisfied: numpy<2.0.0,>=1.9.0 in c:\users\dipanwita.neogy\a
naconda3\lib\site-packages (from pyemd)
Building wheels for collected packages: pyemd
  Running setup.py bdist_wheel for pyemd ... error
  Complete output from command C:\Users\dipanwita.neogy\Anaconda3\python.exe -u
-c "import setuptools, tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Loca
l\\Temp\\pip-build-nk13uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open)(
__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __fil
e__, 'exec'))" bdist_wheel -d C:\Users\DIPANW~1.NEO\AppData\Local\Temp\tmpngn2np
rmpip-wheel- --python-tag cp36:
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build\lib.win32-3.6
  creating build\lib.win32-3.6\pyemd
  copying pyemd\__about__.py -> build\lib.win32-3.6\pyemd
  copying pyemd\__init__.py -> build\lib.win32-3.6\pyemd
  running build_ext
  building 'pyemd.emd' extension
  error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C+
+ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

  ----------------------------------------
  Failed building wheel for pyemd
  Running setup.py clean for pyemd
Failed to build pyemd
Installing collected packages: pyemd
  Running setup.py install for pyemd ... error
    Complete output from command C:\Users\dipanwita.neogy\Anaconda3\python.exe -
u -c "import setuptools, tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Lo
cal\\Temp\\pip-build-nk13uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open
)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __f
ile__, 'exec'))" install --record C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-e
rihhtfj-record\install-record.txt --single-version-externally-managed --compile:

    running install
    running build
    running build_py
    creating build
    creating build\lib.win32-3.6
    creating build\lib.win32-3.6\pyemd
    copying pyemd\__about__.py -> build\lib.win32-3.6\pyemd
    copying pyemd\__init__.py -> build\lib.win32-3.6\pyemd
    running build_ext
    building 'pyemd.emd' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

    ----------------------------------------
Command "C:\Users\dipanwita.neogy\Anaconda3\python.exe -u -c "import setuptools,
 tokenize;__file__='C:\\Users\\DIPANW~1.NEO\\AppData\\Local\\Temp\\pip-build-nk1
3uh5b\\pyemd\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read(
).replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install
 --record C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-erihhtfj-record\install-r
ecord.txt --single-version-externally-managed --compile" failed with error code
1 in C:\Users\DIPANW~1.NEO\AppData\Local\Temp\pip-build-nk13uh5b\pyemd\

I cannot find anything regarding this error. Please suggest me what should I do?


问:
SQL query to fetch rows from one table which are not present in other 3 tables
I have 4 tables,

A, B , C , D

A has column Aid,
B has column Aid,
C has column Aid,
D has column Aid

(Aid is common column in all the 4 tables)

now i want to fetch rows from A table which are not present in B or C or D
can anyone please let me know the SQL query for this.

答:
SELECT A.aid
 FROM   A
 WHERE  NOT EXISTS (select 1 from B where B.aid = A.aid) AND
        NOT EXISTS (select 1 from C where C.aid = A.aid) AND
        NOT EXISTS (select 1 from D where D.aid = A.aid)


问:
Using table row and column header information in IBM Watson Discovery service
My team wants to apply cognitive search to a large body of unstructured "Policy" documents (for example, Automobile Insurance Policy documents). Some of the information in these documents is organized within formatted tables. A human reader would use row and column headings to interpret the documents.

For example, my policy coverage may differ depending on the nature of an incident and which of my vehicles is involved. In the context of my solution, this information is available in a table within on of thepolicy documents, where the rows of the table lists the various types of incidents, and columns list the different vehicles covered in the policy. Each table cell describes the coverage for a specific incident / vehicle combination.

The natural thing to do, would be to annotate each table cell with relationships to the column and row headers for that cell. I'm hoping Watson Discovery already does this or can do this for me. However, in my experiments, I'm not seeing results that would indicate this is so. Are there facililies in either Discovery or Watson Knowledge Studio that facilitate taking advantage of the information in Row and Column headers, within tables?

答:
Table contents are structured data and not suitable for WKS/Discovery for analyzing.
WKS accept plain text of natural language text. Although Discovery accepts HTML/WORD/PDF document, the ingested document is converted into plain text in pre-process and all table structures will be removed. Therefore relations of table are not considered in the text analyzing.
I recommend you to handle such table contents data as a structured data and handle them in other method like programmatically.</p>


问:
how to import modules without problems
after working with nodeJS require for awhile, Python3 module system is confusing me. After re-reading the tutorial https://docs.python.org/2/tutorial/modules.html

I have

```<code>app.py
config/
    __init__.py
    app_config.py
</code>```

in app.py I have:

```<code>import config.app_config
</code>```

ie import FOLDER/FILE

then I should be able to refer to variables/methods in that file by a fully-qualified name eg: config.app_config.varname

But my linter says E0611 No name 'app_config' in module 'config'

NB python3.6 I don't think the __init__ files are needed anymore.

Update: to further confuse things, the above syntax is OK in some files but not ok in others - that are sitting at exactly the same point in the folder hierarchy. >.<; What is python doing wrong to me?

答: OK i think this is because my linter was somehow using a different environment version of python. seems to work when executed. love/hate linters!</p>

Title: how to import modules without problems

Body:
after working with nodeJS require for awhile, Python3 module system is confusing me. After re-reading the tutorial https://docs.python.org/2/tutorial/modules.html

I have

app.py
config/
    __init__.py
    app_config.py

in app.py I have:

import config.app_config

ie import FOLDER/FILE

then I should be able to refer to variables/methods in that file by a fully-qualified name eg: config.app_config.varname

But my linter says E0611 No name 'app_config' in module 'config'

NB python3.6 I don't think the __init__ files are needed anymore.

Update: to further confuse things, the above syntax is OK in some files but not ok in others - that are sitting at exactly the same point in the folder hierarchy. >.<; What is python doing wrong to me?