问:
Including context objects through multiple HTTP handlers in golang
I just read this blog post about creating a function type and implementing the .ServeHTTP() method on that function to be able to handle errors. For example:

```<code>type appError struct {
    Error   error
    Message string
    Code    int
}

type appHandler func(http.ResponseWriter, *http.Request) *appError

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if e := fn(w, r); e != nil { // e is *appError, not os.Error.
        http.Error(w, e.Message, e.Code)
    }
}

func init() {
    http.Handle("/view", appHandler(viewRecord)) //viewRecord is an appHandler function
}
</code>```

I like this approach but I can't conceptually figure out how to include a context object through handler layers. For example:

```<code>func init() {
    http.Handle("/view", AuthHandler(appHandler(viewRecord)))
}
</code>```

AuthHandler would likely create a &SessionToken{User: user} object and set that in a context.Context object for each request. I can't work out how to get that to the viewRecord handler though. Ideas?

答:
Use r.Context(), which is available since Go 1.7.

See https://golang.org/pkg/net/http/#Request.Context

Body:
I just read this blog post about creating a function type and implementing the .ServeHTTP() method on that function to be able to handle errors. For example:

type appError struct {
    Error   error
    Message string
    Code    int
}

type appHandler func(http.ResponseWriter, *http.Request) *appError

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if e := fn(w, r); e != nil { // e is *appError, not os.Error.
        http.Error(w, e.Message, e.Code)
    }
}

func init() {
    http.Handle("/view", appHandler(viewRecord)) //viewRecord is an appHandler function
}

I like this approach but I can't conceptually figure out how to include a context object through handler layers. For example:

func init() {
    http.Handle("/view", AuthHandler(appHandler(viewRecord)))
}

AuthHandler would likely create a &SessionToken{User: user} object and set that in a context.Context object for each request. I can't work out how to get that to the viewRecord handler though. Ideas?


来源: stackexchange

问:
clang 4.0.0 cuda and cmake best practices for minimal warnings
I can't figure out how to get clang CUDA specific flags for only CUDA files:

```<code># building all except 20
set(BUILD_CUDA_ARCH "30;32;35;50;52;53")

# According to the docs, we need static cudart:
# http://llvm.org/docs/CompileCudaWithLLVM.html#compiling-cuda-code
list(APPEND EXTRA_LIBS "cudart_static")

# Let clang know exactly where cuda came from
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --cuda-path=${CUDA_TOOLKIT_ROOT_DIR}")

# Add the compilation trajectories for different architectures
# go to the docs linked above
foreach(arch ${BUILD_CUDA_ARCH})
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --cuda-gpu-arch=sm_${arch}")
endforeach()

# Add the executable like normal, now that CMAKE_CXX_FLAGS has been adjusted.
# clang will compile the .cu files separately
add_library(${LIB_NAME} ${LIBRARY_TYPE} ${CXX_INC} ${CXX_SRC} ${CUDA_INC} ${CUDA_SRC})
</code>```

Where elsewhere in the file is defined

LIB_NAME: the name of the library being built

LIBRARY_TYPE: either SHARED or STATIC

CXX_INC and CXX_SRC: pure C++ headers / source code

CUDA_INC and CUDA_SRC: straight CUDA code

EXTRA_LIBS: just used in target_link_libraries with other stuff

The problem is that this approach results in:

```<code>clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_30' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_32' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_35' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_50' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_52' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_53' [-Wunused-command-line-argument]
</code>```

warnings for every non-cuda compilation.  Do I have to separate this out into two separate libraries, or is there some way of telling clang?  The linked docs in the comments seem to indicate that it should only be doing cuda stuff with .cu files, but I can't seem to find specific flags for only that mode.  It feels awkward to split it into two libraries with how things are split up logically - the CPU version includes different files that effectively do the same thing w/o the gpu.

答:
There is a way to ignore it as shown in this answer

```<code># Squelch warnings about cuda flags for C++ files
foreach(cxx ${CXX_SRC} ${CXX_INC})
  set_source_files_properties(${cxx} PROPERTIES COMPILE_FLAGS -Wno-unused-command-line-argument)
endforeach()
</code>```

I don't think it's appropriate to give a blanket -Wno-unused-command-line-argument, but it seems likely separate treatment of flags is not in llvm.

ContentLicense: CC BY-SA 3.0

Body:
I can't figure out how to get clang CUDA specific flags for only CUDA files:

# building all except 20
set(BUILD_CUDA_ARCH "30;32;35;50;52;53")

# According to the docs, we need static cudart:
# http://llvm.org/docs/CompileCudaWithLLVM.html#compiling-cuda-code
list(APPEND EXTRA_LIBS "cudart_static")

# Let clang know exactly where cuda came from
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --cuda-path=${CUDA_TOOLKIT_ROOT_DIR}")

# Add the compilation trajectories for different architectures
# go to the docs linked above
foreach(arch ${BUILD_CUDA_ARCH})
  set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --cuda-gpu-arch=sm_${arch}")
endforeach()

# Add the executable like normal, now that CMAKE_CXX_FLAGS has been adjusted.
# clang will compile the .cu files separately
add_library(${LIB_NAME} ${LIBRARY_TYPE} ${CXX_INC} ${CXX_SRC} ${CUDA_INC} ${CUDA_SRC})

Where elsewhere in the file is defined

LIB_NAME: the name of the library being built

LIBRARY_TYPE: either SHARED or STATIC

CXX_INC and CXX_SRC: pure C++ headers / source code

CUDA_INC and CUDA_SRC: straight CUDA code

EXTRA_LIBS: just used in target_link_libraries with other stuff

The problem is that this approach results in:

clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_30' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_32' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_35' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_50' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_52' [-Wunused-command-line-argument]
clang-4.0: warning: argument unused during compilation: '--cuda-gpu-arch=sm_53' [-Wunused-command-line-argument]

warnings for every non-cuda compilation.  Do I have to separate this out into two separate libraries, or is there some way of telling clang?  The linked docs in the comments seem to indicate that it should only be doing cuda stuff with .cu files, but I can't seem to find specific flags for only that mode.  It feels awkward to split it into two libraries with how things are split up logically - the CPU version includes different files that effectively do the same thing w/o the gpu.

Body:
There is a way to ignore it as shown in this answer

# Squelch warnings about cuda flags for C++ files
foreach(cxx ${CXX_SRC} ${CXX_INC})
  set_source_files_properties(${cxx} PROPERTIES COMPILE_FLAGS -Wno-unused-command-line-argument)
endforeach()

I don't think it's appropriate to give a blanket -Wno-unused-command-line-argument, but it seems likely separate treatment of flags is not in llvm.


问:
Transfer from Stripe to another Stripe account
I implemented Stripe connect which provides token and other useful property of the signee(user). From the tokens provided, is there a way transfer payment from my account to the user Stripe account? This  an option https://stripe.com/docs/connect/collecting-fees#charges for me right now because I would like to collect the payments first then transfer it later to the user(recipients).

答:
there does seem to be support for this now:
https://support.stripe.com/questions/how-can-i-migrate-to-a-new-stripe-account</p>


问:
Report Definition Field Proper Case
i'm working on a rdlc file, for a report. I need the value of a field to be on ProperCase, however the syntax seems to be wrong.

Using the formula StrConv...

Using the formula ProperCase, it's not even recognized...

答: This is the correct syntax, for anyone that has the same problem

Title: Report Definition Field Proper Case


问:
Close secondary view completely in UWP
I am using a secondary view to run my media files, but When I close my secondary view with close button on it (while media is still playing) the secondary view/window closes but the media somehow keeps playing because I can hear the sound and source of sound seems to be the primary view (main app window). How can I completely terminate the secondary window when I close it?

Here is my code to create the secondary view.

```<code>await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var frame = new Frame();
            frame.MinHeight = 200;
            frame.MinWidth = 200;
            compactViewId = ApplicationView.GetForCurrentView().Id;
            frame.Navigate(typeof(CompactNowPlayingPage), caption);
            Window.Current.Content = frame;
            Window.Current.Activate();
            ApplicationView.GetForCurrentView().Title = Title;

        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsViewModeAsync(compactViewId, ApplicationViewMode.Default);
</code>```

Update

After some debugging I've come to know that close button pressed on the secondary view only hides the view but it keeps on running on its thread, I just want that close button to completely close the secondary view, close its thread and destroy the window as a whole.

Update 2

I followed windows samples multiple views and was able to complete all steps, the code runs fine until it reaches Windows.Current.Close() in released event.

Then it gives an exception when it tries "Window.Current.Close()" with in the released event. according to documentation exception occurs due to any on going changes ( which might be because of media file playing ), but I need to force close the window even when media file is playing how can I do that? Here is the exception:

Message = "COM object that has been separated from its underlying RCW cannot be used."

Update 3

This is the latest updated, I am not following official sample now, just following simpler approach now.

Code to open secondary view:

```<code>await Helpers.DeviceTypeHelper.CompactOpen(e.ClickedItem as Video, identifier); //where identified is just a string for some custom logic in the secondary view.

//following method is located in a helper class within the project
internal static async Task CompactOpen(Video PlayingVideo, string caption)
{
    ApplicationView newView = null;
    await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        var frame = new Frame();
        frame.Navigate(typeof(CompactNowPlayingPage),new object[] { PlayingVideo,caption});
        Window.Current.Content = frame;
        Window.Current.Activate();
        newView = ApplicationView.GetForCurrentView();
        newView.Title = PlayingVideo.MyVideoFile.DisplayName;
    });

    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newView.Id);

}
</code>```

Secondary View:

```<code>public sealed partial class CompactNowPlayingPage : Page
{
    public CompactNowPlayingViewModel ViewModel { get; } = new CompactNowPlayingViewModel();
    private CustomMediaTransportControls controls;
    public CompactNowPlayingPage()
    {
        InitializeComponent();
        this.Loaded += MediaPage_Loaded;
        this.Unloaded += MediaPage_Unloaded;
        Microsoft.Toolkit.Uwp.UI.Extensions.ApplicationView.SetExtendViewIntoTitleBar(this, true);
        Microsoft.Toolkit.Uwp.UI.Extensions.TitleBar.SetButtonBackgroundColor(this, Colors.Transparent);
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        string chk = "";
        var paramm = e.Parameter as object[];
        NowPlayingVideo = paramm[0] as Video;
        var vis = Visibility.Collapsed;
        chk = paramm[1].ToString();
        switch (chk)
        {
            case "library":
                vis = Visibility.Visible;
                break;
            case "playlist":
                vis = Visibility.Visible;
                break;
            case "history":
                vis = Visibility.Collapsed;
                break;
            case "directplay":
                vis = Visibility.Collapsed;
                break;
            default:
                break;
        }
        controls = new CustomMediaTransportControls(NowPlayingVideo,vis);
        Media.TransportControls = controls;
        PlayVideo();
    }
    private Video NowPlayingVideo { get; set; }
    private void PlayVideo()
    {
        if (NowPlayingVideo != null)
        {
            string token = "";
            if (StorageApplicationPermissions.FutureAccessList.Entries.Count == 800)
            {
                var en = StorageApplicationPermissions.FutureAccessList.Entries;
                StorageApplicationPermissions.FutureAccessList.Remove(en.Last().Token);
            }
            token = StorageApplicationPermissions.FutureAccessList.Add(NowPlayingVideo.MyVideoFile);
            Media.Source = null;
            Media.Source = $"winrt://{token}";
            SetViews();
        }
    }

    private void SetViews()
    {
        NowPlayingVideo.Views++;
        Database.DbHelper.UpdateViews(NowPlayingVideo.MyVideoFile.Path);
    }
    private void MediaPage_Loaded(object sender, RoutedEventArgs e)
    {
        Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated += MediaPage_Consolidated;
    }

    private void MediaPage_Unloaded(object sender, RoutedEventArgs e)
    {
        Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated -= MediaPage_Consolidated;
    }

    private void MediaPage_Consolidated(Windows.UI.ViewManagement.ApplicationView sender, Windows.UI.ViewManagement.ApplicationViewConsolidatedEventArgs args)
    {
        Window.Current.Close();
    }

}
</code>```

Secondary View XAML:

```<code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <vlc:MediaElement AreTransportControlsEnabled="True"
                      Name="Media"
                      HardwareAcceleration="True"
                      AutoPlay="True">
    </vlc:MediaElement>
</Grid>
</code>```

Case 1 : Everything runs perfect if I place a video file in Assets folder and give it as a source to the media element and comment the whole OnanvigatdTo method on secondary page. And I am able to successfully close the window as well.
...

Case 2 : But when I try to set the media through the NowPlayingVideo object as shown in the code above and I also use default Transport Controls, so I don't comment the lines used to assign custom transport controls in the above code it runs fine, but when I then try to close the window I get following exception in App.i.g.cs file but stacktrace doesn't exist:

Message = "Attempt has been made to use a COM object that does not have a backing class factory." Message = "COM object that has been separated from its underlying RCW cannot be used.

Case 3 : Exactly like case 2 but here I uncomment Custom transport controls lines so now I am assigning custom transport controls to my media element, this time exception is a bit different with some stacktrace as well

StackTrace = "   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)\r\n   at Windows.UI.Xaml.DependencyObject.get_Dispatcher()\r\n   at VLC.MediaElement.d__160.MoveNext()\r\n--- End of stack trace ...

Message = "Attempt has been made to use a COM object that does not have a backing class factory."

答: The short answer is: you need to make sure nothings holds on to your view instance, and you call Window.Close in the view's Consolidated event. The longer answer with code is here in the official sample. Take a look at the ViewLifetimeControl.cs source file: https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/MultipleViews/cs</p>

ContentLicense: CC BY-SA 4.0

Title: Close secondary view completely in UWP

Body:
I am using a secondary view to run my media files, but When I close my secondary view with close button on it (while media is still playing) the secondary view/window closes but the media somehow keeps playing because I can hear the sound and source of sound seems to be the primary view (main app window). How can I completely terminate the secondary window when I close it?

Here is my code to create the secondary view.

await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            var frame = new Frame();
            frame.MinHeight = 200;
            frame.MinWidth = 200;
            compactViewId = ApplicationView.GetForCurrentView().Id;
            frame.Navigate(typeof(CompactNowPlayingPage), caption);
            Window.Current.Content = frame;
            Window.Current.Activate();
            ApplicationView.GetForCurrentView().Title = Title;

        });
        bool viewShown = await ApplicationViewSwitcher.TryShowAsViewModeAsync(compactViewId, ApplicationViewMode.Default);

Update

After some debugging I've come to know that close button pressed on the secondary view only hides the view but it keeps on running on its thread, I just want that close button to completely close the secondary view, close its thread and destroy the window as a whole.

Update 2

I followed windows samples multiple views and was able to complete all steps, the code runs fine until it reaches Windows.Current.Close() in released event.

Then it gives an exception when it tries "Window.Current.Close()" with in the released event. according to documentation exception occurs due to any on going changes ( which might be because of media file playing ), but I need to force close the window even when media file is playing how can I do that? Here is the exception:

Message = "COM object that has been separated from its underlying RCW cannot be used."

Update 3

This is the latest updated, I am not following official sample now, just following simpler approach now.

Code to open secondary view:

await Helpers.DeviceTypeHelper.CompactOpen(e.ClickedItem as Video, identifier); //where identified is just a string for some custom logic in the secondary view.

//following method is located in a helper class within the project
internal static async Task CompactOpen(Video PlayingVideo, string caption)
{
    ApplicationView newView = null;
    await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        var frame = new Frame();
        frame.Navigate(typeof(CompactNowPlayingPage),new object[] { PlayingVideo,caption});
        Window.Current.Content = frame;
        Window.Current.Activate();
        newView = ApplicationView.GetForCurrentView();
        newView.Title = PlayingVideo.MyVideoFile.DisplayName;
    });

    await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newView.Id);

}

Secondary View:

public sealed partial class CompactNowPlayingPage : Page
{
    public CompactNowPlayingViewModel ViewModel { get; } = new CompactNowPlayingViewModel();
    private CustomMediaTransportControls controls;
    public CompactNowPlayingPage()
    {
        InitializeComponent();
        this.Loaded += MediaPage_Loaded;
        this.Unloaded += MediaPage_Unloaded;
        Microsoft.Toolkit.Uwp.UI.Extensions.ApplicationView.SetExtendViewIntoTitleBar(this, true);
        Microsoft.Toolkit.Uwp.UI.Extensions.TitleBar.SetButtonBackgroundColor(this, Colors.Transparent);
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        string chk = "";
        var paramm = e.Parameter as object[];
        NowPlayingVideo = paramm[0] as Video;
        var vis = Visibility.Collapsed;
        chk = paramm[1].ToString();
        switch (chk)
        {
            case "library":
                vis = Visibility.Visible;
                break;
            case "playlist":
                vis = Visibility.Visible;
                break;
            case "history":
                vis = Visibility.Collapsed;
                break;
            case "directplay":
                vis = Visibility.Collapsed;
                break;
            default:
                break;
        }
        controls = new CustomMediaTransportControls(NowPlayingVideo,vis);
        Media.TransportControls = controls;
        PlayVideo();
    }
    private Video NowPlayingVideo { get; set; }
    private void PlayVideo()
    {
        if (NowPlayingVideo != null)
        {
            string token = "";
            if (StorageApplicationPermissions.FutureAccessList.Entries.Count == 800)
            {
                var en = StorageApplicationPermissions.FutureAccessList.Entries;
                StorageApplicationPermissions.FutureAccessList.Remove(en.Last().Token);
            }
            token = StorageApplicationPermissions.FutureAccessList.Add(NowPlayingVideo.MyVideoFile);
            Media.Source = null;
            Media.Source = $"winrt://{token}";
            SetViews();
        }
    }

    private void SetViews()
    {
        NowPlayingVideo.Views++;
        Database.DbHelper.UpdateViews(NowPlayingVideo.MyVideoFile.Path);
    }
    private void MediaPage_Loaded(object sender, RoutedEventArgs e)
    {
        Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated += MediaPage_Consolidated;
    }

    private void MediaPage_Unloaded(object sender, RoutedEventArgs e)
    {
        Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Consolidated -= MediaPage_Consolidated;
    }

    private void MediaPage_Consolidated(Windows.UI.ViewManagement.ApplicationView sender, Windows.UI.ViewManagement.ApplicationViewConsolidatedEventArgs args)
    {
        Window.Current.Close();
    }

}

Secondary View XAML:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <vlc:MediaElement AreTransportControlsEnabled="True"
                      Name="Media"
                      HardwareAcceleration="True"
                      AutoPlay="True">
    </vlc:MediaElement>
</Grid>

Case 1 : Everything runs perfect if I place a video file in Assets folder and give it as a source to the media element and comment the whole OnanvigatdTo method on secondary page. And I am able to successfully close the window as well.
...

Case 2 : But when I try to set the media through the NowPlayingVideo object as shown in the code above and I also use default Transport Controls, so I don't comment the lines used to assign custom transport controls in the above code it runs fine, but when I then try to close the window I get following exception in App.i.g.cs file but stacktrace doesn't exist:

Message = "Attempt has been made to use a COM object that does not have a backing class factory." Message = "COM object that has been separated from its underlying RCW cannot be used.

Case 3 : Exactly like case 2 but here I uncomment Custom transport controls lines so now I am assigning custom transport controls to my media element, this time exception is a bit different with some stacktrace as well

StackTrace = "   at System.StubHelpers.StubHelpers.GetCOMIPFromRCW_WinRT(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget)\r\n   at Windows.UI.Xaml.DependencyObject.get_Dispatcher()\r\n   at VLC.MediaElement.d__160.MoveNext()\r\n--- End of stack trace ...

Message = "Attempt has been made to use a COM object that does not have a backing class factory."


问:
lsof command on HDFS
I would like to know if a file is currently being used or opened on HDFS.

I am trying to use the below command, but it's not working. Can someone give me the correct command to do this?

```<code>hadoop fs -lsof  /apps/hive/warehouse/db/table/.hive-staging_*
</code>```

答:
There is no such command (see list of available commands), but you can check for inconsistencies in HDFS using hdfs fsck together with the option -openforwrite to list files that are stuck in the OPENFORWRITE status

```<code>hdfs fsck <your_hdfs_path> -files -blocks -locations -openforwrite
</code>```

Title: lsof command on HDFS

Body:
I would like to know if a file is currently being used or opened on HDFS.

I am trying to use the below command, but it's not working. Can someone give me the correct command to do this?

hadoop fs -lsof  /apps/hive/warehouse/db/table/.hive-staging_*

Body:
There is no such command (see list of available commands), but you can check for inconsistencies in HDFS using hdfs fsck together with the option -openforwrite to list files that are stuck in the OPENFORWRITE status

hdfs fsck <your_hdfs_path> -files -blocks -locations -openforwrite


问:
Distance measure between two sets of possibly different size
I have 2 sets of integers, A and B, not necessarily of the same size. For my needs, I take the distance between each 2 elements a and b (integers) to be just abs(a-b).

I am defining the distance between the two sets as follows:

If the sets are of the same size, minimize the sum of distances of all pairs [a,b] (a from A and b from B), minimization over all possible 'pairs partitions' (there are n! possible partitions).

If the sets are not of the same size, let's say A of size m and B of size n, with m < n, then minimize the distance from (1) over all subsets of B which are of size m.

My question is, is the following algorithm (just an intuitive guess) gives the right answer, according to the definition written above.

Construct a matrix D of size m X n, with D(i,j) = abs(A(i)-B(j))

Find the smallest element of D, accumulate it, and delete the row and the column of that element. Accumulate the next smallest entry, and keep accumulating until all rows and columns are deleted.

for example, if A={0,1,4} and B={3,4}, then D is (with the elements above and to the left):

  3 4

0 3 4

1 2 3

4 1 0

And the distance is 0 + 2 = 2, coming from pairing 4 with 4 and 3 with 1.

答:
No It's not a best answer, for example:
A: {3,7} and B:{0,4} you will choose: {(3,4),(0,7)} and distance is 8  but you should choose {(3,0),(4,7)} in this case distance is 6.

ContentLicense: CC BY-SA 2.5


问:
hashbytes returns different values for int?
Running the following on SQL Server got 0xE864ECE8888043B67277C8B2CEFE96AD315FCCA4.

```<code>select hashbytes('SHA1', cast(10 as varbinary(max)));
</code>```

On Sybase the following SQLs return 0xEB408DDC4FA484E6BEFDF5954E56A2198C7A9FAB

```<code>select hashbytes('SHA1', cast(10 as varbinary(8000))), hashbytes('SHA1', 10 )
</code>```

Why the SHA1 got different values on different databases?

答:
Possible issue with MSSQL and Sybase running on cpu's with different endianness.

Consider the following run against Sybase ASE running on linux (I get the same results for Sybase ASE on Solaris/x86, too):

```<code>select hashbytes('SHA1', cast(10 as varbinary(8000))                  ),hashbytes('sha1',10                  )
select hashbytes('SHA1', cast(10 as varbinary(8000)),using         lsb),hashbytes('sha1',10,using         lsb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using         msb),hashbytes('sha1',10,using         msb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using unicode_lsb),hashbytes('sha1',10,using unicode_lsb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using unicode_msb),hashbytes('sha1',10,using unicode_msb)
go

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xe864ece8888043b67277c8b2cefe96ad315fcca4

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xe864ece8888043b67277c8b2cefe96ad315fcca4
</code>```

As you can see, I get both of the values you've mentioned; with the %CCA4 match coming from running hashbytes using msb or using unicode_msb.

What is your Sybase version?

```<code>select @@version
</code>```

Body:
Running the following on SQL Server got 0xE864ECE8888043B67277C8B2CEFE96AD315FCCA4.

select hashbytes('SHA1', cast(10 as varbinary(max)));

On Sybase the following SQLs return 0xEB408DDC4FA484E6BEFDF5954E56A2198C7A9FAB

select hashbytes('SHA1', cast(10 as varbinary(8000))), hashbytes('SHA1', 10 )

Why the SHA1 got different values on different databases?

Body:
Possible issue with MSSQL and Sybase running on cpu's with different endianness.

Consider the following run against Sybase ASE running on linux (I get the same results for Sybase ASE on Solaris/x86, too):

select hashbytes('SHA1', cast(10 as varbinary(8000))                  ),hashbytes('sha1',10                  )
select hashbytes('SHA1', cast(10 as varbinary(8000)),using         lsb),hashbytes('sha1',10,using         lsb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using         msb),hashbytes('sha1',10,using         msb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using unicode_lsb),hashbytes('sha1',10,using unicode_lsb)
select hashbytes('SHA1', cast(10 as varbinary(8000)),using unicode_msb),hashbytes('sha1',10,using unicode_msb)
go

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xe864ece8888043b67277c8b2cefe96ad315fcca4

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab

 ------------------------------------------ ------------------------------------------
 0xeb408ddc4fa484e6befdf5954e56a2198c7a9fab 0xe864ece8888043b67277c8b2cefe96ad315fcca4

As you can see, I get both of the values you've mentioned; with the %CCA4 match coming from running hashbytes using msb or using unicode_msb.

What is your Sybase version?

select @@version


问:
Split with multiple delimiters
I have a text file that I need to split line by line with two delimiters.

```
'Testing' # Libname
'Testing2' #Libname2
```

But, what I want is:

```
Testing Libname
Testing2 Libname2
```

For the moment my code just puts the following:

```
Testing
Libname
Testing2
Libname2
```

Any ideas?

```<code>Set objFile = objFSO.OpenTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, Chr(34), "'") 'Replace Double Quote for Single Quote
strNewText = Replace(strNewText, "'", "#")  'Replace
CharacterCount = (Len(strNewText) - Len(Replace(strNewText, "#", "")))

Set objNewFile = objFSO.CreateTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForWriting, True)
objNewFile.Write strNewText
objNewFile.Close

Set objFile = objFSO.OpenTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForWriting, True)

For i=1 To CharacterCount
    splitstr = Split(strNewText, "#")
    objFile.WriteLine splitstr(i) '& "#" & splitstr1(i)
    i = i + 1
Next

objFile.Close
WScript.Echo "  Process completed "
</code>```

答:
Here is the simple code which will open the file, read content and close it. And then re-open the file and write replaced content and close it.

```<code>Const ForReading = 1, ForWriting = 2, ForAppending = 8
filename = WScript.Arguments(0) & "\listofpaths.csv"

Set fso = CreateObject("Scripting.FileSystemObject")

'READ THE CONTENT
Set f = fso.OpenTextFile(filename, ForReading)
tempTxt = f.ReadAll()
f.Close

'REPLACE AND WRITE THE CONTENT BACK
Set f = fso.OpenTextFile(filename, ForWriting, False)
f.Write Replace(Replace(tempTxt, "'", ""), "#", "")

f.Close
Set f = Nothing : Set fso = Nothing
</code>```

Here is the before text:

'Testing' # Libname

  'Testing2' #Libname2

  'Testing3' # Libname

  'Testing' #Libname4

And here is the after text in a same file:

Testing  Libname

  Testing2 Libname2

  Testing3  Libname

  Testing Libname4

Title: Split with multiple delimiters

Body:
I have a text file that I need to split line by line with two delimiters.

'Testing' # Libname
'Testing2' #Libname2

But, what I want is:

Testing Libname
Testing2 Libname2

For the moment my code just puts the following:

Testing
Libname
Testing2
Libname2

Any ideas?

Set objFile = objFSO.OpenTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, Chr(34), "'") 'Replace Double Quote for Single Quote
strNewText = Replace(strNewText, "'", "#")  'Replace
CharacterCount = (Len(strNewText) - Len(Replace(strNewText, "#", "")))

Set objNewFile = objFSO.CreateTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForWriting, True)
objNewFile.Write strNewText
objNewFile.Close

Set objFile = objFSO.OpenTextFile(WScript.Arguments(0) & "\listofpaths.csv", ForWriting, True)

For i=1 To CharacterCount
    splitstr = Split(strNewText, "#")
    objFile.WriteLine splitstr(i) '& "#" & splitstr1(i)
    i = i + 1
Next

objFile.Close
WScript.Echo "  Process completed "

Body:
Here is the simple code which will open the file, read content and close it. And then re-open the file and write replaced content and close it.

Const ForReading = 1, ForWriting = 2, ForAppending = 8
filename = WScript.Arguments(0) & "\listofpaths.csv"

Set fso = CreateObject("Scripting.FileSystemObject")

'READ THE CONTENT
Set f = fso.OpenTextFile(filename, ForReading)
tempTxt = f.ReadAll()
f.Close

'REPLACE AND WRITE THE CONTENT BACK
Set f = fso.OpenTextFile(filename, ForWriting, False)
f.Write Replace(Replace(tempTxt, "'", ""), "#", "")

f.Close
Set f = Nothing : Set fso = Nothing

Here is the before text:

'Testing' # Libname

  'Testing2' #Libname2

  'Testing3' # Libname

  'Testing' #Libname4

And here is the after text in a same file:

Testing  Libname

  Testing2 Libname2

  Testing3  Libname

  Testing Libname4


问:
Get The Current Foreground Activity Name And The Package Name In Lollipop
there are lots of question about this topic but all are only about getting the package name.
what i want is get the activity name.

currently i am using the below method to get the activity name but as you know ActivityManager.getRunningTasks is now deprecated, so is there an alternative way to get this or i should stick with this and it won't do any harm?

```<code>ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);   //deprecated

//taskInfo.get(0).topActivity.getClassName() //this gets the activity name
</code>```

答:
Is Late, but maybe this can help someone else:</p>

```<code>String activityName = (String) activity.getTitle();
</code>```

Body:
there are lots of question about this topic but all are only about getting the package name.
what i want is get the activity name.

currently i am using the below method to get the activity name but as you know ActivityManager.getRunningTasks is now deprecated, so is there an alternative way to get this or i should stick with this and it won't do any harm?

ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
                    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);   //deprecated

//taskInfo.get(0).topActivity.getClassName() //this gets the activity name

Body:
Is Late, but maybe this can help someone else:

String activityName = (String) activity.getTitle();


问:
Entity Framework Core 2.0 on .NET 4.6.1
Microsoft just announced that Entity Framework Core 2.0 will now run on .NET Standard 2.0.

.Net Standard 2.0 is compatible (if that's the right term here) with .NET Framework 4.6.1.

However when I try add the latest NuGet package I get an error telling me that I'm using the wrong version:

```<code> Install-Package : Could not install package
 'Microsoft.EntityFrameworkCore.SqlServer 2.0.0-preview2-25332'. You are
 trying to install this package into a project that targets
 '.NETFramework,Version=v4.6.1', but
 the package does not contain any assembly references or content files
 that are compatible with that framework.
</code>```

If according to the announcement I can use EF Core 2.0 with .NET Framework 4.6.1, can someone please explain, and if possible give an example of what that would look like.

答:
In addition to installing the NETStandard.Library.NETFramework package, you may also have to tell older NuGet clients that it really is compatible by adding the following to your *.csproj file.

```<code><PropertyGroup>
  <PackageTargetFallback>netstandard2.0</PackageTargetFallback>
</PropertyGroup>
</code>```

Title: Entity Framework Core 2.0 on .NET 4.6.1

Body:
Microsoft just announced that Entity Framework Core 2.0 will now run on .NET Standard 2.0.

.Net Standard 2.0 is compatible (if that's the right term here) with .NET Framework 4.6.1.

However when I try add the latest NuGet package I get an error telling me that I'm using the wrong version:

 Install-Package : Could not install package
 'Microsoft.EntityFrameworkCore.SqlServer 2.0.0-preview2-25332'. You are
 trying to install this package into a project that targets
 '.NETFramework,Version=v4.6.1', but
 the package does not contain any assembly references or content files
 that are compatible with that framework.

If according to the announcement I can use EF Core 2.0 with .NET Framework 4.6.1, can someone please explain, and if possible give an example of what that would look like.

Body:
In addition to installing the NETStandard.Library.NETFramework package, you may also have to tell older NuGet clients that it really is compatible by adding the following to your *.csproj file.

<PropertyGroup>
  <PackageTargetFallback>netstandard2.0</PackageTargetFallback>
</PropertyGroup>


问:
What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?
I'm trying to store 5000 data elements on an array. This 5000 elements are stored on an existinng file (therefore it's not empty).

But I'm getting an error.

IN:

```<code>def array():

    name = 'puntos.df4'

    m = open(name, 'rb')
    v = []*5000

    m.seek(-5000, io.SEEK_END)
    fp = m.tell()
    sz = os.path.getsize(name)

    while fp < sz:
        pt = pickle.load(m)
        v.append(pt)

    m.close()
    return v
</code>```

OUT:

```<code>line 23, in array
pt = pickle.load(m)
_pickle.UnpicklingError: invalid load key, ''.
</code>```

答:
This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip.

For example if a compressed pickle archive is made like this,

```<code>import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
    pickle.dump([1,2,3], ofp)
</code>```

Trying to open it throws the errors

```<code> with open('test.pklz', 'rb') as ifp:
     print(pickle.load(ifp))
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.
</code>```

But, if the pickle file is opened using gzip all is harmonious

```<code>with gzip.open('test.pklz', 'rb') as ifp:
    print(pickle.load(ifp))

[1, 2, 3]
</code>```

Body:
I'm trying to store 5000 data elements on an array. This 5000 elements are stored on an existinng file (therefore it's not empty).

But I'm getting an error.

IN:

def array():

    name = 'puntos.df4'

    m = open(name, 'rb')
    v = []*5000

    m.seek(-5000, io.SEEK_END)
    fp = m.tell()
    sz = os.path.getsize(name)

    while fp < sz:
        pt = pickle.load(m)
        v.append(pt)

    m.close()
    return v

OUT:

line 23, in array
pt = pickle.load(m)
_pickle.UnpicklingError: invalid load key, ''.

Body:
This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip.

For example if a compressed pickle archive is made like this,

import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
    pickle.dump([1,2,3], ofp)

Trying to open it throws the errors

 with open('test.pklz', 'rb') as ifp:
     print(pickle.load(ifp))
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.

But, if the pickle file is opened using gzip all is harmonious

with gzip.open('test.pklz', 'rb') as ifp:
    print(pickle.load(ifp))

[1, 2, 3]


问:
How the "OK" message looks like?
I have a device that sends data to a server.

```<code>            Data
[ Client ]  == >  [ Server ]
</code>```

After the validation on the server I want to return a message:

```<code>            OK
[ Client ] < == [ Server ]
</code>```

Is there a standard "OK" message to return? And an "ERROR" message? How does it looks like? (e.g. ":0011", ":110F")

答:
You've got to design an application-level protocol.  TCP is a byte stream, so even the definition of "Data" in your client->server piece needs some protocol so that the receiver can know what bytes make up the data (when to stop reading).

A couple of common types of protocols are...

Length-delimited chunks.  Every message starts with a 16 or 32-bit length prefix.  Then that many bytes follow.  The length needs to be in a defined byte order (see htons, ntohs, etc).  Everyone who uses this protocol knows to read the length prefix then read that many bytes.  Having defined that "chunk" on the network, you might put a header on the contents of the chunk.  Maybe a message type (ACK, NAK, Data, etc) followed by some contents.

ASCII newline delimited.  Each message is a line of ASCII (or UTF8, etc) text.  It ends at a newline.  Newline endings for the lines play the same role as the length prefix for the chunks above.  You then define what's in each line (like space or comma-delimited ASCII/UTF8/whatever fields).  Somewhere in that you'd define what data looks like, ACK, etc.

I'm sure you could come up with other ideas, but that's the basic job: defining your application-level protocol on top of TCP's byte stream.

Title: How the "OK" message looks like?

Body:
I have a device that sends data to a server.

            Data
[ Client ]  == >  [ Server ]

After the validation on the server I want to return a message:

            OK
[ Client ] < == [ Server ]

Is there a standard "OK" message to return? And an "ERROR" message? How does it looks like? (e.g. ":0011", ":110F")


问:
NSUserDefaults: How to get value
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

```<code>-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];
</code>```

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

```<code>- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}
</code>```

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?

答:
Yes. valueForKey returns objects, not primitive data types like BOOL.
For NSUserDefaults, the shortest way to get a BOOL value is to use boolForKey instead.

Title: NSUserDefaults: How to get value

Body:
I am new in iOS, Object-C and I am trying to do a simple login/registerLogin using NSUserDefaults.

My problem is: How could I access/get the value saved in NSUserDefaults to verify if an user already exist?

This is the code for registering a new user:

-(void)registerNewUser {

// Getting username and the password
NSString *newUsername = self.usernameRegisterTextField.text;
NSString *newPassword = self.passwordRegisterTextField.text;

// Using NSUserDefaults to storage username and password
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

[newUser setObject:newUsername forKey:@"username"];
[newUser setObject:newPassword forKey:@"password"];
[newUser setBool:YES forKey:@"registered"];

[newUser synchronize];

[self performSegueWithIdentifier:@"registerSucessSegue" sender:nil];

}

And I am trying to get the value saved in NSUserDefaults to verify if an user already exist instead of calling the login screen again:

- (IBAction)productTableButton:(id)sender {
// Verification if an user exist
NSUserDefaults *newUser = [NSUserDefaults standardUserDefaults];

BOOL newUserExist = [newUser valueForKey:@"registered"];

if (newUserExist == YES) {
    [self performSegueWithIdentifier:@"productSegue" sender:nil];
} else {
    [self performSegueWithIdentifier:@"loginSegue" sender:nil];
}

}

Is there something that I am doing wrong when I am trying to access the value of an user saved in NSUserDefaults?


问:
SymPy substition with scalars doesn't work?
```
from sympy import *

x,y,s = symbols('xys')

z = (1 - 2*x*x)
w = (1 + 2*x*x)
q = 2*x*x*2*y*y

sub = {2*x*x: s}
print w.subs(sub)
print z.subs(sub)

print q
print q.subs(sub)
```

The output I get:

```
1 + s
1 - 2*x**2
4*x**2*y**2
4*x**2*y**2
```

The output I expect:

```
1 + s
1 - s
4*x**2*y**2
2*y**2*s
```

Do I do something wrong?

答: Sympy seems to be inconsistent in what it matches. For instance, changing the sign on the matching substitution expression allows z to be matched with. I would consider adding this example to this issue. I would also try the Sympy mailing list. Remember, this project isn't even to version number 1.0 yet so things aren't going to be perfect just yet with it (or probably ever as with any software). </p>

Body:
from sympy import *

x,y,s = symbols('xys')

z = (1 - 2*x*x)
w = (1 + 2*x*x)
q = 2*x*x*2*y*y

sub = {2*x*x: s}
print w.subs(sub)
print z.subs(sub)

print q
print q.subs(sub)

The output I get:

1 + s
1 - 2*x**2
4*x**2*y**2
4*x**2*y**2

The output I expect:

1 + s
1 - s
4*x**2*y**2
2*y**2*s

Do I do something wrong?


问:
How to check if all of the elements in an array are the same, in matlab?
There must be a simple matlab way of doing this.  I have a row vector and I want to check if all of the elements are equal.  Brute forcing this in a loop is easy, but looking for a more efficient approach :)  The elements are integers</p>

答: How about: max(v) == min(v)? :-)

Body: How about: max(v) == min(v)? :-)


问:
sql query to format the parent child in a hierarchical list
I want to have the data displayed in the below parent child like relationship, where the first row should be parent row, and every subsequent row should be for child with null in all parent specific columns.

[![Here is the example][2]][2]

In the above the consumer 99999999 has 2 dependents 22222222 and 33333333.

I tried doing this with Lead and lag but that will need an order by in the CTE.
I was thinking of looking at the previous ApplicationroductID, and would flag whenever I see that it has changed. So by doing that my I can flag the parent and Child.
I could potentially get away with the order by problem by using a temp table, but that doesnt sound like a very good solution.
Is there a better way of doing this that you guys can think of. I want to have the data to be in the above format.

```<code>select
de.ID as ConsumerID
,dd.ID as DependentID,
f.ApplicationroductID,
LEAD(f.ApplicationroductID) OVER (Order by fep.ApplicationroductID) Lead,
LAG(f.ApplicationroductID) OVER (Order by fep.ApplicationroductID) Lag
 from Fact f
INNER JOIN DimEmp de ON fep.DimEmp_FK = de.ID
INNER JOIN DimDep dd ON fep.DimDep_FK = dd.ID
</code>```

答:
Try something like this:

```<code>;with cte as
(
    select
        de.ID as ConsumerID,
        null  as DependentID,
        de.ConsumerName,
        null  as ParticipantName,
        f.ApplicationroductID
     from Fact f
    INNER JOIN DimEmp de ON f.DimEmp_FK = de.ID

    union

    select
        de.ID as ConsumerID,
        dd.ID as DependentID,
        null  as ConsumerName,
        dd.ParticipantName,
        f.ApplicationroductID
     from Fact f
    INNER JOIN DimEmp de ON f.DimEmp_FK = de.ID
    INNER JOIN DimDep dd ON f.DimDep_FK = dd.ID
)
select case
        when DependentID is null then ConsumerID
        else null
       end as ConsumerID,
       DependentID,
       ConsumerName,
       ParticipantName,
       ApplicationroductID
  from cte
 order by ConsumerId,
          DependentId
</code>```

The two SELECTS + UNION will get you all rows, with NULL or real value for each row type. We get the ConsumerId in both SELECTs in order to use it in the outer SELECT's ORDER BY expression. The outer SELECT switches NULL or ConsumerId, depending on the row type.

Body:
I want to have the data displayed in the below parent child like relationship, where the first row should be parent row, and every subsequent row should be for child with null in all parent specific columns.

[![Here is the example][2]][2]

In the above the consumer 99999999 has 2 dependents 22222222 and 33333333.

I tried doing this with Lead and lag but that will need an order by in the CTE.
I was thinking of looking at the previous ApplicationroductID, and would flag whenever I see that it has changed. So by doing that my I can flag the parent and Child.
I could potentially get away with the order by problem by using a temp table, but that doesnt sound like a very good solution.
Is there a better way of doing this that you guys can think of. I want to have the data to be in the above format.

select
de.ID as ConsumerID
,dd.ID as DependentID,
f.ApplicationroductID,
LEAD(f.ApplicationroductID) OVER (Order by fep.ApplicationroductID) Lead,
LAG(f.ApplicationroductID) OVER (Order by fep.ApplicationroductID) Lag
 from Fact f
INNER JOIN DimEmp de ON fep.DimEmp_FK = de.ID
INNER JOIN DimDep dd ON fep.DimDep_FK = dd.ID

Body:
Try something like this:

;with cte as
(
    select
        de.ID as ConsumerID,
        null  as DependentID,
        de.ConsumerName,
        null  as ParticipantName,
        f.ApplicationroductID
     from Fact f
    INNER JOIN DimEmp de ON f.DimEmp_FK = de.ID

    union

    select
        de.ID as ConsumerID,
        dd.ID as DependentID,
        null  as ConsumerName,
        dd.ParticipantName,
        f.ApplicationroductID
     from Fact f
    INNER JOIN DimEmp de ON f.DimEmp_FK = de.ID
    INNER JOIN DimDep dd ON f.DimDep_FK = dd.ID
)
select case
        when DependentID is null then ConsumerID
        else null
       end as ConsumerID,
       DependentID,
       ConsumerName,
       ParticipantName,
       ApplicationroductID
  from cte
 order by ConsumerId,
          DependentId

The two SELECTS + UNION will get you all rows, with NULL or real value for each row type. We get the ConsumerId in both SELECTs in order to use it in the outer SELECT's ORDER BY expression. The outer SELECT switches NULL or ConsumerId, depending on the row type.


问:
Crash when sending exception through RxJava
I'm starting to use RXAndroid and I've released my first beta with it and I got an exception I wasn't expecting. I'm certain it comes from my lack of understanding of the how the onError method works.

My code is like this:

```<code>disposables.add(Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                        if (e.isDisposed()) {
                            return;
                        }
                        //do stuff
                        if (stuff didn't fail) {
                            e.onNext(myString);
                        } else {
                            e.onError(new Exception("stuff failed"));
                        }
                        e.onComplete();
                    }

                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(new DisposableObserver<String>() {
                            @Override
                            public void onNext(@NonNull String myString) {
                                //do stuff

                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                //handle the error
                            }

                            @Override
                            public void onComplete() {
                            }
                        })
        );
</code>```

I am getting a crash here:

e.onError(new Exception("stuff failed"));

But personally I thought this would handle that case?

```<code>public void onError(@NonNull Throwable e) {
    //handle the error
}
</code>```

I've already changed my code to handle this in a different way but I would still like to know how onError is supposed to work.

Thank you.

EDIT: The exception:

```<code>java.lang.Exception: stuff failed
       at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
       at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
       at MyClass$4.subscribe(MyClass.java:295)
       at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
       at io.reactivex.Observable.subscribe(Observable.java:10842)
       at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
       at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
       at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
       at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:762)
Caused by java.lang.Exception: stuff failed
       at MyClass$4.subscribe(MyClass.java:295)
       at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
       at io.reactivex.Observable.subscribe(Observable.java:10842)
       at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
       at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
       at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
       at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:762)
</code>```

答:
Between checking e.isDisposed() and your call to e.onError() the emitter ends up being disposed somehow. This causes the call to onError to fall back on the global error handler.

You need to check e.isDisposed() again or if you're willing to use experimental features RxJava 2.1.1 adds the e.tryOnError method which does not fall back if it is disposed already.

Body:
I'm starting to use RXAndroid and I've released my first beta with it and I got an exception I wasn't expecting. I'm certain it comes from my lack of understanding of the how the onError method works.

My code is like this:

disposables.add(Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    public void subscribe(@NonNull ObservableEmitter<String> e) throws Exception {
                        if (e.isDisposed()) {
                            return;
                        }
                        //do stuff
                        if (stuff didn't fail) {
                            e.onNext(myString);
                        } else {
                            e.onError(new Exception("stuff failed"));
                        }
                        e.onComplete();
                    }

                })
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribeWith(new DisposableObserver<String>() {
                            @Override
                            public void onNext(@NonNull String myString) {
                                //do stuff

                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                //handle the error
                            }

                            @Override
                            public void onComplete() {
                            }
                        })
        );

I am getting a crash here:

e.onError(new Exception("stuff failed"));

But personally I thought this would handle that case?

public void onError(@NonNull Throwable e) {
    //handle the error
}

I've already changed my code to handle this in a different way but I would still like to know how onError is supposed to work.

Thank you.

EDIT: The exception:

java.lang.Exception: stuff failed
       at io.reactivex.plugins.RxJavaPlugins.onError(RxJavaPlugins.java:349)
       at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onError(ObservableCreate.java:83)
       at MyClass$4.subscribe(MyClass.java:295)
       at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
       at io.reactivex.Observable.subscribe(Observable.java:10842)
       at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
       at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
       at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
       at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:762)
Caused by java.lang.Exception: stuff failed
       at MyClass$4.subscribe(MyClass.java:295)
       at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
       at io.reactivex.Observable.subscribe(Observable.java:10842)
       at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
       at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:452)
       at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:61)
       at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:52)
       at java.util.concurrent.FutureTask.run(FutureTask.java:237)
       at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
       at java.lang.Thread.run(Thread.java:762)


问:
Javascript change Typeof
I am new in JavaScript.

My code allows me to list the elements of a JSON document as well as their types, and concatenate all its in a string donnees_types.

The problem is that the typeof in JavaScript returns only number for a number and string for a string. I want to return double instead of number and varchar instead of string in order to get:

temperature double, humidite double, built varchar, fire varchar

I know I can replace in my string using replace, but is there any other method to change the typeof?

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

donnees_types = "";

for(var i= 0; i < keys.length -1; i++)
donnees_types +=  keys[i] + " " +  typeof(event[keys[i]]) + ", ";

var donnees_t = donnees_types.substring(0, donnees_types.length - 2);
console.log(donnees_t);
 ```

答:
You might be able to get the functionality that you want by doing some additional a work to further classify the value based on what typeof returns and some custom logic, but you cannot change the functionality of typeof itself.

Pseudocode:

```<code>if `typeof` foo is `number`
    if `<insert integer rules here>`
        then foo is an integer
    else if `<insert float rules here>`
        then foo is a float
    else if . . .
</code>```

The reason why you are running into this is that JavaScript is a "loosely typed" language . . . it does not recognize data types at a detailed level, but rather groups them into broader categories.  These categories are the basis for the values that typeof returns.

You can read more about typeof here and JavaScript typing here, for a quick list of what you can expect, here are the values that typeof will return to you:

```<code>Type                                           Result

Undefined                                      "undefined"
Null                                           "object"
Boolean                                        "boolean"
Number                                         "number"
String                                         "string"
Symbol                                         "symbol"
Host object (provided by the JS environment)   Implementation-dependent
Function object                                "function"
Any other object                               "object"
</code>```

Title: Javascript change Typeof

Body:
You might be able to get the functionality that you want by doing some additional a work to further classify the value based on what typeof returns and some custom logic, but you cannot change the functionality of typeof itself.

Pseudocode:

if `typeof` foo is `number`
    if `<insert integer rules here>`
        then foo is an integer
    else if `<insert float rules here>`
        then foo is a float
    else if . . .

The reason why you are running into this is that JavaScript is a "loosely typed" language . . . it does not recognize data types at a detailed level, but rather groups them into broader categories.  These categories are the basis for the values that typeof returns.

You can read more about typeof here and JavaScript typing here, for a quick list of what you can expect, here are the values that typeof will return to you:

Type                                           Result

Undefined                                      "undefined"
Null                                           "object"
Boolean                                        "boolean"
Number                                         "number"
String                                         "string"
Symbol                                         "symbol"
Host object (provided by the JS environment)   Implementation-dependent
Function object                                "function"
Any other object                               "object"


问:
Why don't variables upload in a loop?
I want to make a program that tracks how many apples apples I have and takes an apple away when I eat one.

```<code>apples=3

while apples>0:
    try:
        print("You have {} a left".format(apples))

        Action=input('Action:')
        if action == "eat":
            apples=apples-1
        else:
            print("invalid")
    except:
        pass
</code>```

However this code doesn't update apples when I write eat as user input.

You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

答:
The problem is that you defined Action but tried to use action (the case matters!). Without the try and except you may have noticed that yourself. That's one reason you should (almost) never use a bare except. Always catch specific exceptions like ValueError and similar.

If I remove these and use this code, the exception is shown:

```<code>apples=3

while apples>0:
    print("You have {} a left".format(apples))

    Action=input('Action:')
    if action == "eat":
        apples=apples-1
    else:
        print("invalid")

# ...

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
      4     print("You have {} a left".format(apples))
      5     Action=input('Action:')
----> 6     if action == "eat":
      7         apples=apples-1
      8     else:

NameError: name 'action' is not defined
</code>```

You may also need to strip the input because it sometimes contains a trailing newline:

```<code>apples=3

while apples > 0:
    print("You have {} apples left".format(apples))
    action=input('Action:')
    if action.strip() == "eat":  # here is the strip that removes all leading and trailing whitespaces
        apples=apples-1
    else:
        print("invalid")
</code>```

Title: Why don't variables upload in a loop?

Body:
I want to make a program that tracks how many apples apples I have and takes an apple away when I eat one.

apples=3

while apples>0:
    try:
        print("You have {} a left".format(apples))

        Action=input('Action:')
        if action == "eat":
            apples=apples-1
        else:
            print("invalid")
    except:
        pass

However this code doesn't update apples when I write eat as user input.

You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

  Action:eat

  You have 3 apples left

Body:
The problem is that you defined Action but tried to use action (the case matters!). Without the try and except you may have noticed that yourself. That's one reason you should (almost) never use a bare except. Always catch specific exceptions like ValueError and similar.

If I remove these and use this code, the exception is shown:

apples=3

while apples>0:
    print("You have {} a left".format(apples))

    Action=input('Action:')
    if action == "eat":
        apples=apples-1
    else:
        print("invalid")

# ...

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
      4     print("You have {} a left".format(apples))
      5     Action=input('Action:')
----> 6     if action == "eat":
      7         apples=apples-1
      8     else:

NameError: name 'action' is not defined

You may also need to strip the input because it sometimes contains a trailing newline:

apples=3

while apples > 0:
    print("You have {} apples left".format(apples))
    action=input('Action:')
    if action.strip() == "eat":  # here is the strip that removes all leading and trailing whitespaces
        apples=apples-1
    else:
        print("invalid")


问:
execute a command by switching to root user in ansible
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

```<code>david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install
</code>```

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I don't see my GNU library getting installed at all.

```<code>- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
</code>```

Now my question is how can I switch to root user and execute a particular command. I am running Ansible 1.5.4 and looks like I cannot upgrade. I even tried with below but still it doesn't work:

```<code>- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  sudo: true
  sudo_user: root
</code>```

I am running my playbook using below command:

```<code>ansible-playbook -e 'host_key_checking=False' setup.yml -u david --ask-pass --sudo -U root --ask-sudo-pass
</code>```

答:
You need the become directive.

For example, to start a service as root:

```<code>- name: Ensure the httpd service is running
  service:
    name: httpd
    state: started
  become: true
</code>```

you can also become another user, such as the apache user:

```<code>- name: Run a command as the apache user
  command: somecommand
  become: true
  become_user: apache
</code>```

For your case, it will be:

```<code>- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  become: true
</code>```

Body:
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I don't see my GNU library getting installed at all.

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install

Now my question is how can I switch to root user and execute a particular command. I am running Ansible 1.5.4 and looks like I cannot upgrade. I even tried with below but still it doesn't work:

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  sudo: true
  sudo_user: root

I am running my playbook using below command:

ansible-playbook -e 'host_key_checking=False' setup.yml -u david --ask-pass --sudo -U root --ask-sudo-pass

Body:
You need the become directive.

For example, to start a service as root:

- name: Ensure the httpd service is running
  service:
    name: httpd
    state: started
  become: true

you can also become another user, such as the apache user:

- name: Run a command as the apache user
  command: somecommand
  become: true
  become_user: apache

For your case, it will be:

- name: install gnu parallel
  command: chdir=/tmp/parallel-20140422 sudo ./configure && make && make install
  become: true


问:
Point out the maker and speed of the laptops having hard drive capacity more or equal to 10 Gb
I tried this in two ways (I think they are the same):

```<code>select product.maker,speed from product,laptop
where product.model=laptop.model and hd>='10'
</code>```

and

```<code>select product.maker, speed from laptop
join product
on (product.model=laptop.model)
where hd>='10'
</code>```

and I receive this in the simulator:

"Your query produced correct result set on main database, but it failed test on second, checking database. * Wrong number of records (more by 1)
  This exercise has FAQ"

The relevant tables are:

Table Laptop

```<code>code    model   speed   ram hd      price       screen
------------------------------------------------------
1       1298    350     32  4.0     700.0000    11
2       1321    500     64  8.0     970.0000    12
3       1750    750     128 12.0    1200.0000   14
4       1298    600     64  10.0    1050.0000   15
5       1752    750     128 10.0    1150.0000   14
6       1298    450     64  10.0    950.0000    12
</code>```

Table Product:

```<code>maker   model   Type
-----------------------
A       1232    PC
A       1233    PC
A       1276    Printer
A       1298    Laptop
A       1401    Printer
A       1408    Printer
A       1752    Laptop
B       1121    PC
B       1750    Laptop
C       1321    Laptop
D       1288    Printer
D       1433    Printer
E       1260    PC
E       1434    Printer
E       2112    PC
E       2113    PC
</code>```

答:
You forgot to filter for the laptops:</p>

```<code>SELECT Product.maker, Laptop.speed
FROM Product INNER JOIN Laptop ON Laptop.model = Product.model
WHERE Laptop.hd >= 10 AND Product.type = 'Laptop'
</code>```

Body:
I tried this in two ways (I think they are the same):

select product.maker,speed from product,laptop
where product.model=laptop.model and hd>='10'

and

select product.maker, speed from laptop
join product
on (product.model=laptop.model)
where hd>='10'

and I receive this in the simulator:

"Your query produced correct result set on main database, but it failed test on second, checking database. * Wrong number of records (more by 1)
  This exercise has FAQ"

The relevant tables are:

Table Laptop

code    model   speed   ram hd      price       screen
------------------------------------------------------
1       1298    350     32  4.0     700.0000    11
2       1321    500     64  8.0     970.0000    12
3       1750    750     128 12.0    1200.0000   14
4       1298    600     64  10.0    1050.0000   15
5       1752    750     128 10.0    1150.0000   14
6       1298    450     64  10.0    950.0000    12

Table Product:

maker   model   Type
-----------------------
A       1232    PC
A       1233    PC
A       1276    Printer
A       1298    Laptop
A       1401    Printer
A       1408    Printer
A       1752    Laptop
B       1121    PC
B       1750    Laptop
C       1321    Laptop
D       1288    Printer
D       1433    Printer
E       1260    PC
E       1434    Printer
E       2112    PC
E       2113    PC

Body:
You forgot to filter for the laptops:

SELECT Product.maker, Laptop.speed
FROM Product INNER JOIN Laptop ON Laptop.model = Product.model
WHERE Laptop.hd >= 10 AND Product.type = 'Laptop'


问:
Regex to allow a pattern of chars but not an individual char from that pattern
I am trying to create a regex that will do the following

Match the String if:

The String is between 4-35 chars

The String must contain the $ as the last char in the String

The String does not contain any $ anywhere else unless the dollar sign is wrapped within a bracket, i.e. [$]

I currently have the following regex: [^\$]{3,34}\$$

You can see the example here

This catches not allowing $ except at the end, however I still need to allow the dollar sign if it is wrapped within brackets [$]. How can I add a way to "allow" the [$]?

Some Positive examples:

ABCD$

ABC[$]D$

[$]ABCDEFG$

!@#%^&*[$]^%$

Some Negative examples:

AB$CD

ABCD

$$ABCD$

AB$[$]CD$

答:
You may use

```<code>^(?=.{4,35}$)(?:\[\$]|[^$])*\$$
</code>```

See the regex demo

Details:

^ - start of string (can be omitted if the pattern is used with matches())

(?=.{4,35}$)  - a positive lookahead requiring 4 to 35 chars in the string

(?:\[\$]|[^$])* - 0+ [$] substrings or any chars other than $

\$ - a literal $

$ - end of string (may be omitted if used with matches()).

Java demo:

```<code>String lines[]  = {"ABCD$","ABC[$]D$","[$]ABCDEFG$","!@#%^&*[$]^%$","AB$CD","ABCD","$$ABCD$","AB$[$]CD$"};
String pat = "(?=.{4,35}$)(?:\\[\\$]|[^$])*\\$";
for(String line : lines)
{
    System.out.println(line + ": " + line.matches(pat));
}
</code>```

Result:

```<code>ABCD$: true
ABC[$]D$: true
[$]ABCDEFG$: true
!@#%^&*[$]^%$: true
AB$CD: false
ABCD: false
$$ABCD$: false
AB$[$]CD$: false
</code>```

Body:
You may use

^(?=.{4,35}$)(?:\[\$]|[^$])*\$$

See the regex demo

Details:

^ - start of string (can be omitted if the pattern is used with matches())

(?=.{4,35}$)  - a positive lookahead requiring 4 to 35 chars in the string

(?:\[\$]|[^$])* - 0+ [$] substrings or any chars other than $

\$ - a literal $

$ - end of string (may be omitted if used with matches()).

Java demo:

String lines[]  = {"ABCD$","ABC[$]D$","[$]ABCDEFG$","!@#%^&*[$]^%$","AB$CD","ABCD","$$ABCD$","AB$[$]CD$"};
String pat = "(?=.{4,35}$)(?:\\[\\$]|[^$])*\\$";
for(String line : lines)
{
    System.out.println(line + ": " + line.matches(pat));
}

Result:

ABCD$: true
ABC[$]D$: true
[$]ABCDEFG$: true
!@#%^&*[$]^%$: true
AB$CD: false
ABCD: false
$$ABCD$: false
AB$[$]CD$: false


问:
Java: Printing ALL Args as single string
Ok, I want a line of code That will allow me to print all args as one string.

Example of what i need: lets say arg[0] = "Hi"; and lets say arg[1] =
"there";

i want it to print "Hi there", not something like [Hi, there] when you use
Array.toString()

Thanks - Jay (0-0)/

答: Override the Array toString method? You'd have to use a loop in there to get the desired result though.</p>


问:
sort excel file based on first column
I Have a excel file as follow (with 2 columns - UserID and one varible):

```<code>variable                UserID
---------------------------------------
0.999999999999901       A3PPXVR5J6U2JD
7.16184317895728e-10    A3RTKL9KB8KLID
1.49736349513394e-16    AJVVATHEYX7L9
5.57811370169348e-25    AOL7V6D4AL3KO
1.49736349513394e-16    A214RU9GS37U2T
0                       A2KJFH1F69U5R
4.45695014171021e-07    A38LAIK2N83NH0
1.49736349513394e-16    A2P9YDRHZTJMC3
1.49736349513394e-16    A1G2W2C669C8GC
.........
.
.
.
</code>```

I want read this file in C# and sort based on column(1). I wrote this code:

```<code>Excel.Workbook xlWorkbook = myExcelApp.Workbooks.Open(Filename:
@"D:\test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlrange.Sort(xlrange.Columns[1], Excel.XlSortOrder.xlAscending);
</code>```

I want take this result: (sort file based on column(1) in ascending)

```<code>0                       A2KJFH1F69U5R
5.57811370169348e-25    AOL7V6D4AL3KO
....
.
.
</code>```

but this take columns as string and sort based on string . this mean that Code take column (1) as string and sort It. this answer is result of code:

```<code>0                       A2KJFH1F69U5R
0.999999999999901       A3PPXVR5J6U2JD
1.49736349513394e-16    AJVVATHEYX7L9
.
.
.
</code>```

I want correct code that this code take first column as a double and sort file.

答:
I think this should work for you:

```<code>using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
        var excelApp = new Excel.Application();
        excelApp.Workbooks.Add();
        // VBA code goes here:
        excelApp.Columns["A:B"].Select
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Clear
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Add Key:=Range["A:B"], _
                SortOn:=Excel.XlSortOn.xlSortOnValues, Order:=Excel.XlSortOrder.xlAscending, _
                DataOption:=Excel.XlSortDataOption.xlSortNormal

            excelApp.ActiveWorkbook.Worksheets("test").Sort.SetRange Range["A:B"]
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Header = Excel.XlYesNoGuess.xlGuess
            excelApp.ActiveWorkbook.Worksheets("test").Sort.MatchCase = False
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Orientation = Excel.Constants.xlTopToBottom
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortMethod = Excel.XlSortMethod.xlPinYin
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Apply

        excelApp.Visible = true;
    }
}
</code>```

You can find more information here.

Title: sort excel file based on first column

Body:
I Have a excel file as follow (with 2 columns - UserID and one varible):

variable                UserID
---------------------------------------
0.999999999999901       A3PPXVR5J6U2JD
7.16184317895728e-10    A3RTKL9KB8KLID
1.49736349513394e-16    AJVVATHEYX7L9
5.57811370169348e-25    AOL7V6D4AL3KO
1.49736349513394e-16    A214RU9GS37U2T
0                       A2KJFH1F69U5R
4.45695014171021e-07    A38LAIK2N83NH0
1.49736349513394e-16    A2P9YDRHZTJMC3
1.49736349513394e-16    A1G2W2C669C8GC
.........
.
.
.

I want read this file in C# and sort based on column(1). I wrote this code:

Excel.Workbook xlWorkbook = myExcelApp.Workbooks.Open(Filename:
@"D:\test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
xlrange.Sort(xlrange.Columns[1], Excel.XlSortOrder.xlAscending);

I want take this result: (sort file based on column(1) in ascending)

0                       A2KJFH1F69U5R
5.57811370169348e-25    AOL7V6D4AL3KO
....
.
.

but this take columns as string and sort based on string . this mean that Code take column (1) as string and sort It. this answer is result of code:

0                       A2KJFH1F69U5R
0.999999999999901       A3PPXVR5J6U2JD
1.49736349513394e-16    AJVVATHEYX7L9
.
.
.

I want correct code that this code take first column as a double and sort file.

Body:
I think this should work for you:

using Excel = Microsoft.Office.Interop.Excel;
class Program
{
    static void Main(string[] args)
    {
        var excelApp = new Excel.Application();
        excelApp.Workbooks.Add();
        // VBA code goes here:
        excelApp.Columns["A:B"].Select
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Clear
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortFields.Add Key:=Range["A:B"], _
                SortOn:=Excel.XlSortOn.xlSortOnValues, Order:=Excel.XlSortOrder.xlAscending, _
                DataOption:=Excel.XlSortDataOption.xlSortNormal

            excelApp.ActiveWorkbook.Worksheets("test").Sort.SetRange Range["A:B"]
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Header = Excel.XlYesNoGuess.xlGuess
            excelApp.ActiveWorkbook.Worksheets("test").Sort.MatchCase = False
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Orientation = Excel.Constants.xlTopToBottom
            excelApp.ActiveWorkbook.Worksheets("test").Sort.SortMethod = Excel.XlSortMethod.xlPinYin
            excelApp.ActiveWorkbook.Worksheets("test").Sort.Apply

        excelApp.Visible = true;
    }
}

You can find more information here.


问:
Deleting from array javascript
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

```<code>var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}
</code>```

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

答:
You seem to be close. You have removed the element from the array but not from the DOM, that is the reason why you cannot see the updated in the html.</p>

```<code>for(let i = 0; i < array.length; i++){
var p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){
    array.splice(i, 1);
    this.remove();//also remove from the DOM
    console.log(array);
}

}
</code>```

Title: Deleting from array javascript

Body:
I am looping through an array and displaying it on the screen. I have a problem, though. I tried to add a function that when you click on the text, it deletes that clicked text. Here is my code:

var div = document.querySelector('div');
var array = [
"Banana",
"Chocolate",
"Oranges"
];

for(let i = 0; i < array.length; i++){

var p = document.createElement('p');
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){

    array.splice(array[i], 1);
    console.log(array);
}

}

When I click on it, it deletes the item from the array and logs it to the console. But it doesn't show on the screen. Any help?

Thank you,
Scratch Cat

Body:
You seem to be close. You have removed the element from the array but not from the DOM, that is the reason why you cannot see the updated in the html.

for(let i = 0; i < array.length; i++){
var p = document.createElement('p');//note the block scoping
p.textContent = array[i];
div.appendChild(p);

p.onclick = function(){
    array.splice(i, 1);
    this.remove();//also remove from the DOM
    console.log(array);
}

}


问:
VBA Val Function Changing Value?
An equation produces this value as Variant/Double X: 36.0418746812314

But:

X <> Val(X) is true

X <> CStr(X) is false

X <> CDdl(X) is false

How is Val() changing the value?

When viewed in the watch list applying X = Val(X) does not appear to change the value or type of X.  But somehow it is different.

For instance:

A = X - Val(X) is very small, but not zero (2.1316282072803E-14).

B = X - CStr(X) is very small, but not zero (2.1316282072803E-14).

C = X - CDbl(X) is zero.

Update:
Thanks everyone for your replies and answers.  Here is some additional background.

Formula for dividend adjusted close price.  Reportedly used by Yahoo Finance.

A1 = A0 + A0 * (((P1 / S) - P0 - D) / P0)

Split and Dividend Adjusted Close Price

Ticker Symbol: INTC

Date: Friday, August 29, 1980

0.306757021582758 (Yahoo Finance calculated)

0.306757021582704 (My VBA calculation)

Converting A1 to string CStr(A1) or applying Val(A1), then my VBA result matches the Yahoo Finance calculated value.

It's not really a material difference but nice to understand why and how to make it match for purpose of formula validation.

Formula source, components details and explanation.

"How Yahoo Calculates the Adjusted Closing Price"

http://marubozu.blogspot.com/2006/09/how-yahoo-calculates-adjusted-closing.html

答:
The CDbl function is relative to your regional settings. The Val function is relative to US regional settings.

If you provide a value in your local regional settings to the Val function, it will be interpreted as if it is in US format (period for decimal separator, comma for thousands separator etc).

My PC is set to EN-AU settings (which are similar to EN-US settings), and Val(36.0418746812314) = 36.0418746812314 returns True, or in your syntax, Val(36.0418746812314) <> 36.0418746812314 returns False

Title: VBA Val Function Changing Value?


问:
number guessing game not working
Apparently my code is not working according to an automated test and doesn't give me a pass for my solution, however when I run it it seems to work fine. I'm wondering what's wrong with my code?:

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

public class GuessingNumberGame {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int numberDrawn = drawNumber();

        int i = 1;
        boolean correct = false;

        while (correct == false) {

        System.out.print("Guess a number: ");
        int guess = Integer.parseInt(reader.nextLine());

        if (guess == numberDrawn) {
            System.out.println("Congratulations, your guess is correct!");
            correct = true;

        } else if (guess < numberDrawn) {
                    System.out.println("The number is lesser, guesses made: " + i);
                                i++;
                    } else if (guess > numberDrawn) {
                        System.out.println("The number is greater, guess made: " + i);
                                    i++;
        }
        }
    }

    // DO NOT MODIFY THIS!
    private static int drawNumber() {
        return new Random().nextInt(101);
    }
}
</code>```

It is exercise 41 on the University of Helsinki online Java course, the exercise details are here: http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-2?noredirect=1#e41

The errors that I get are:

If guess is too small, program should print "The number is greater".

If guess is too large, program should print "The number is lesser".

If the drawn number is 1 and user input is 0, 1, program should at first print
"The number is greater", and after that "Congratulations, your guess is correct!"

If the drawn number is 1 and user input is 2, 1, program should at first print
"The number is lesser", and after that "Congratulations, your guess is correct!"

Thank you

答:
You have simple logic mistake

When the number is lesser condition should be guess > numberDrawn or the number is greater it should be guess < numberDrawn:

```<code>    if (guess == numberDrawn) {
         System.out.println("Congratulations, your guess is correct!");
         correct = true;
    } else if (guess > numberDrawn) {
                System.out.println("The number is lesser, guesses made: " + i);
                i++;
    } else if (guess < numberDrawn) {
                System.out.println("The number is greater, guess made: " + i);
                i++;
    }
</code>```

Title: number guessing game not working

Body:
Apparently my code is not working according to an automated test and doesn't give me a pass for my solution, however when I run it it seems to work fine. I'm wondering what's wrong with my code?:

import java.util.Random;
import java.util.Scanner;

public class GuessingNumberGame {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        int numberDrawn = drawNumber();

        int i = 1;
        boolean correct = false;

        while (correct == false) {

        System.out.print("Guess a number: ");
        int guess = Integer.parseInt(reader.nextLine());

        if (guess == numberDrawn) {
            System.out.println("Congratulations, your guess is correct!");
            correct = true;

        } else if (guess < numberDrawn) {
                    System.out.println("The number is lesser, guesses made: " + i);
                                i++;
                    } else if (guess > numberDrawn) {
                        System.out.println("The number is greater, guess made: " + i);
                                    i++;
        }
        }
    }

    // DO NOT MODIFY THIS!
    private static int drawNumber() {
        return new Random().nextInt(101);
    }
}

It is exercise 41 on the University of Helsinki online Java course, the exercise details are here: http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-2?noredirect=1#e41

The errors that I get are:

If guess is too small, program should print "The number is greater".

If guess is too large, program should print "The number is lesser".

If the drawn number is 1 and user input is 0, 1, program should at first print
"The number is greater", and after that "Congratulations, your guess is correct!"

If the drawn number is 1 and user input is 2, 1, program should at first print
"The number is lesser", and after that "Congratulations, your guess is correct!"

Thank you

Body:
You have simple logic mistake

When the number is lesser condition should be guess > numberDrawn or the number is greater it should be guess < numberDrawn:

    if (guess == numberDrawn) {
         System.out.println("Congratulations, your guess is correct!");
         correct = true;
    } else if (guess > numberDrawn) {
                System.out.println("The number is lesser, guesses made: " + i);
                i++;
    } else if (guess < numberDrawn) {
                System.out.println("The number is greater, guess made: " + i);
                i++;
    }


问:
React-native change stack navigator title based on what is selected from nested drawer navigation
I have a drawer navigator nested inside a stack navigator like so

```<code>const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      drawerLabel: 'Home',
      drawerIcon: () => (
        <MaterialCommunityIcons name={'home'} size={25} />
        )
    },
  },
  Customers: {
    screen: Customers,
    navigationOptions: {
      drawerLabel: 'Customers',
      drawerIcon: () => (
        <MaterialCommunityIcons name={'account-switch'} size={25} />
        )
    },
  },
}, {
  drawerPosition: 'right',
})

const Navigation = StackNavigator({
  Home: {
    screen : DrawerNavigation,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.routeName, // Always 'Home'
    }),
  },
})
</code>```

This gave me the layout I desired, with a "title bar" that displays on both IOS and android, and makes the drawer navigation the main method of navigating the application. However, I would like the title prop for the stack navigator to display the name of whatever screen is selected from the drawer navigator rather than a static string. Is this possible with this current setup? Perhaps this is the incorrect approach - I am new to react-native's navigation.

答:
You can add title for each screen in the navigationOptions for each screen.

```<code>const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      drawerLabel: 'Home',
      title: 'Home, sweet home!' // <=== add this
      drawerIcon: () => (
        <MaterialCommunityIcons name={'home'} size={25} />
        )
    },
  },
  Customers: {
    screen: Customers,
    navigationOptions: {
      drawerLabel: 'Customers',
      title: 'Dear customers', // <=== and this
      drawerIcon: () => (
        <MaterialCommunityIcons name={'account-switch'} size={25} />
        )
    },
  },
}, {
  drawerPosition: 'right',
})

const Navigation = StackNavigator({
  Home: {
    screen : DrawerNavigation,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.routeName, // <=== remove this
    }),
  },
})
</code>```

Also, you can set title on each screen component, more details here

Body:
I have a drawer navigator nested inside a stack navigator like so

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      drawerLabel: 'Home',
      drawerIcon: () => (
        <MaterialCommunityIcons name={'home'} size={25} />
        )
    },
  },
  Customers: {
    screen: Customers,
    navigationOptions: {
      drawerLabel: 'Customers',
      drawerIcon: () => (
        <MaterialCommunityIcons name={'account-switch'} size={25} />
        )
    },
  },
}, {
  drawerPosition: 'right',
})

const Navigation = StackNavigator({
  Home: {
    screen : DrawerNavigation,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.routeName, // Always 'Home'
    }),
  },
})

This gave me the layout I desired, with a "title bar" that displays on both IOS and android, and makes the drawer navigation the main method of navigating the application. However, I would like the title prop for the stack navigator to display the name of whatever screen is selected from the drawer navigator rather than a static string. Is this possible with this current setup? Perhaps this is the incorrect approach - I am new to react-native's navigation.

Body:
You can add title for each screen in the navigationOptions for each screen.

const DrawerNavigation = DrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: {
      drawerLabel: 'Home',
      title: 'Home, sweet home!' // <=== add this
      drawerIcon: () => (
        <MaterialCommunityIcons name={'home'} size={25} />
        )
    },
  },
  Customers: {
    screen: Customers,
    navigationOptions: {
      drawerLabel: 'Customers',
      title: 'Dear customers', // <=== and this
      drawerIcon: () => (
        <MaterialCommunityIcons name={'account-switch'} size={25} />
        )
    },
  },
}, {
  drawerPosition: 'right',
})

const Navigation = StackNavigator({
  Home: {
    screen : DrawerNavigation,
    navigationOptions: ({ navigation }) => ({
      title: navigation.state.routeName, // <=== remove this
    }),
  },
})

Also, you can set title on each screen component, more details here


答:
Assuming you are using Java 8+, you can use a Stream and a Collector. Like,

```<code>String[] arg = { "Hi", "there" };
System.out.println(Stream.of(arg).collect(Collectors.joining(" ")));
</code>```

which outputs (as I think you wanted)

```<code>Hi there
</code>```

Title: Java: Printing ALL Args as single string

Body:
Ok, I want a line of code That will allow me to print all args as one string.

Example of what i need: lets say arg[0] = "Hi"; and lets say arg[1] =
"there";

i want it to print "Hi there", not something like [Hi, there] when you use
Array.toString()

Thanks - Jay (0-0)/

Body:
Assuming you are using Java 8+, you can use a Stream and a Collector. Like,

String[] arg = { "Hi", "there" };
System.out.println(Stream.of(arg).collect(Collectors.joining(" ")));

which outputs (as I think you wanted)

Hi there