问:
Eclipse Neon Tomcat plugin download error
I am trying to download tomcat plugin in Eclipse Neon. Some how I managed to download it. But when I try to set preferences for tomcat using Windows-> Preferences -> Tomcat. It is giving me below error. I think some plugin activator is missing in Eclipse. if you can take a look at it.

```<code>java.lang.ClassNotFoundException: An error occurred while automatically activating bundle org.uqbar.eclipse.tomcat.xt (706).
at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:116)
at org.eclipse.osgi.internal.loader.classpath.ClasspathManager.findLocalClass(ClasspathManager.java:529)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.findLocalClass(ModuleClassLoader.java:325)
at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:345)
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:423)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:161)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.eclipse.osgi.internal.framework.EquinoxBundle.loadClass(EquinoxBundle.java:564)
at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
at org.eclipse.ui.internal.WorkbenchPlugin$1.run(WorkbenchPlugin.java:291)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
at org.eclipse.ui.internal.WorkbenchPlugin.createExtension(WorkbenchPlugin.java:286)
at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceNode.createPage(WorkbenchPreferenceNode.java:48)
at org.eclipse.jface.preference.PreferenceDialog.createPage(PreferenceDialog.java:1280)
at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.createPage(FilteredPreferenceDialog.java:355)
at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1167)
at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:608)
at org.eclipse.jface.preference.PreferenceDialog$5.lambda$0(PreferenceDialog.java:656)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
at org.eclipse.jface.preference.PreferenceDialog$5.selectionChanged(PreferenceDialog.java:653)
at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:878)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50)
at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173)
at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:875)
at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1244)
at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1270)
at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:265)
at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:259)
at org.eclipse.jface.util.OpenStrategy$1.lambda$1(OpenStrategy.java:431)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4203)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3819)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
at org.eclipse.jface.window.Window.open(Window.java:794)
at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:211)
at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:63)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4228)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3816)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:687)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:604)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)
</code>```

Caused by: org.osgi.framework.BundleException: Error loading bundle activator.
    at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:716)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:932)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:309)
    at org.eclipse.osgi.container.Module.doStart(Module.java:581)
    at org.eclipse.osgi.container.Module.start(Module.java:449)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:470)
    at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:107)
    ... 71 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.internal.compatibility.PluginActivator cannot be found by org.uqbar.eclipse.tomcat.xt_2.0.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:461)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.loadBundleActivator(BundleContextImpl.java:757)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:711)
    ... 77 more

答:
By trying to download it from eclipse market place did not help me. I downloaded the plugin manually from here and installed in eclipse. and it worked for me.

Thanks

Body:
I am trying to download tomcat plugin in Eclipse Neon. Some how I managed to download it. But when I try to set preferences for tomcat using Windows-> Preferences -> Tomcat. It is giving me below error. I think some plugin activator is missing in Eclipse. if you can take a look at it.

java.lang.ClassNotFoundException: An error occurred while automatically activating bundle org.uqbar.eclipse.tomcat.xt (706).
at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:116)
at org.eclipse.osgi.internal.loader.classpath.ClasspathManager.findLocalClass(ClasspathManager.java:529)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.findLocalClass(ModuleClassLoader.java:325)
at org.eclipse.osgi.internal.loader.BundleLoader.findLocalClass(BundleLoader.java:345)
at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:423)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372)
at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364)
at org.eclipse.osgi.internal.loader.ModuleClassLoader.loadClass(ModuleClassLoader.java:161)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.eclipse.osgi.internal.framework.EquinoxBundle.loadClass(EquinoxBundle.java:564)
at org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI.createExecutableExtension(RegistryStrategyOSGI.java:174)
at org.eclipse.core.internal.registry.ExtensionRegistry.createExecutableExtension(ExtensionRegistry.java:905)
at org.eclipse.core.internal.registry.ConfigurationElement.createExecutableExtension(ConfigurationElement.java:243)
at org.eclipse.core.internal.registry.ConfigurationElementHandle.createExecutableExtension(ConfigurationElementHandle.java:55)
at org.eclipse.ui.internal.WorkbenchPlugin$1.run(WorkbenchPlugin.java:291)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
at org.eclipse.ui.internal.WorkbenchPlugin.createExtension(WorkbenchPlugin.java:286)
at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceNode.createPage(WorkbenchPreferenceNode.java:48)
at org.eclipse.jface.preference.PreferenceDialog.createPage(PreferenceDialog.java:1280)
at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.createPage(FilteredPreferenceDialog.java:355)
at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1167)
at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:608)
at org.eclipse.jface.preference.PreferenceDialog$5.lambda$0(PreferenceDialog.java:656)
at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
at org.eclipse.jface.preference.PreferenceDialog$5.selectionChanged(PreferenceDialog.java:653)
at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:878)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50)
at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:173)
at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:875)
at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1244)
at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1270)
at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:265)
at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:259)
at org.eclipse.jface.util.OpenStrategy$1.lambda$1(OpenStrategy.java:431)
at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:182)
at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4203)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3819)
at org.eclipse.jface.window.Window.runEventLoop(Window.java:818)
at org.eclipse.jface.window.Window.open(Window.java:794)
at org.eclipse.ui.internal.dialogs.WorkbenchPreferenceDialog.open(WorkbenchPreferenceDialog.java:211)
at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:63)
at org.eclipse.jface.action.Action.runWithEvent(Action.java:473)
at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:565)
at org.eclipse.jface.action.ActionContributionItem.lambda$4(ActionContributionItem.java:397)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4410)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1079)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4228)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3816)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1121)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1022)
at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:150)
at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:687)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:336)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:604)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:148)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:138)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:388)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:243)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:673)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:610)
at org.eclipse.equinox.launcher.Main.run(Main.java:1519)

Caused by: org.osgi.framework.BundleException: Error loading bundle activator.
    at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:716)
    at org.eclipse.osgi.internal.framework.EquinoxBundle.startWorker0(EquinoxBundle.java:932)
    at org.eclipse.osgi.internal.framework.EquinoxBundle$EquinoxModule.startWorker(EquinoxBundle.java:309)
    at org.eclipse.osgi.container.Module.doStart(Module.java:581)
    at org.eclipse.osgi.container.Module.start(Module.java:449)
    at org.eclipse.osgi.framework.util.SecureAction.start(SecureAction.java:470)
    at org.eclipse.osgi.internal.hooks.EclipseLazyStarter.postFindLocalClass(EclipseLazyStarter.java:107)
    ... 71 more
Caused by: java.lang.ClassNotFoundException: org.eclipse.core.internal.compatibility.PluginActivator cannot be found by org.uqbar.eclipse.tomcat.xt_2.0.0
    at org.eclipse.osgi.internal.loader.BundleLoader.findClassInternal(BundleLoader.java:461)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:372)
    at org.eclipse.osgi.internal.loader.BundleLoader.findClass(BundleLoader.java:364)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.loadBundleActivator(BundleContextImpl.java:757)
    at org.eclipse.osgi.internal.framework.BundleContextImpl.start(BundleContextImpl.java:711)
    ... 77 more


来源: stackexchange

问:
How do I stop a script loaded with CSScript?
I run user defined scripts in my WPF application using CS-Script library. How can I cancel a script if it runs endless? As my users write the script I can't rely on a cancel flag that is checked inside the script.

Here is a simplified code snippet showing the problem:

```<code>public partial class MainWindow : Window
{
    public string MessageFromScript
    {
        get { return (string)GetValue(MessageFromScriptProperty); }
        set { SetValue(MessageFromScriptProperty, value); }
    }
    public static readonly DependencyProperty MessageFromScriptProperty =
        DependencyProperty.Register("MessageFromScript", typeof(string), typeof(MainWindow), new PropertyMetadata(null));

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    BackgroundWorker worker = null;
    private void OnStart(object sender, RoutedEventArgs e)
    {
        if(worker != null)
        {
            return;
        }
        worker = new BackgroundWorker();
        worker.DoWork += RunScript;
        worker.RunWorkerCompleted += ScriptCompleted;
        worker.WorkerSupportsCancellation = true;
        worker.RunWorkerAsync();
    }

    private void ScriptCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)
            MessageFromScript = "Script cancelled";
        else
            MessageFromScript = e.Result.ToString();
    }

    private void RunScript(object sender, DoWorkEventArgs e)
    {
        dynamic script = CSScript.Evaluator.LoadCode(@"using System;
                                using System.Threading;
                                 public class Script
                                 {
                                     public string Test()
                                     {
                                        {int count=0; while(true) { count++; Console.WriteLine(count.ToString()); Thread.Sleep(200); }}

                                        return ""Message from script"";
                                     }
                                 }");

        e.Result = script.Test();
    }

    private void OnStop(object sender, RoutedEventArgs e)
    {
        if(worker == null)
        {
            return;
        }

        //TODO: How do I stop the script here?

        worker = null;
    }
}
</code>```

答: In your Test() method add a parameter where you pass a CancellationToken to the script. Then design the loops in your script to check the canellation token if abort has been requested and break out. To stop the script just call the Cancel() method of your CancellationTokenSource which token you passed to the script on invocation.</p>

ContentLicense: CC BY-SA 3.0

Body:
I run user defined scripts in my WPF application using CS-Script library. How can I cancel a script if it runs endless? As my users write the script I can't rely on a cancel flag that is checked inside the script.

Here is a simplified code snippet showing the problem:

public partial class MainWindow : Window
{
    public string MessageFromScript
    {
        get { return (string)GetValue(MessageFromScriptProperty); }
        set { SetValue(MessageFromScriptProperty, value); }
    }
    public static readonly DependencyProperty MessageFromScriptProperty =
        DependencyProperty.Register("MessageFromScript", typeof(string), typeof(MainWindow), new PropertyMetadata(null));

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    BackgroundWorker worker = null;
    private void OnStart(object sender, RoutedEventArgs e)
    {
        if(worker != null)
        {
            return;
        }
        worker = new BackgroundWorker();
        worker.DoWork += RunScript;
        worker.RunWorkerCompleted += ScriptCompleted;
        worker.WorkerSupportsCancellation = true;
        worker.RunWorkerAsync();
    }

    private void ScriptCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)
            MessageFromScript = "Script cancelled";
        else
            MessageFromScript = e.Result.ToString();
    }

    private void RunScript(object sender, DoWorkEventArgs e)
    {
        dynamic script = CSScript.Evaluator.LoadCode(@"using System;
                                using System.Threading;
                                 public class Script
                                 {
                                     public string Test()
                                     {
                                        {int count=0; while(true) { count++; Console.WriteLine(count.ToString()); Thread.Sleep(200); }}

                                        return ""Message from script"";
                                     }
                                 }");

        e.Result = script.Test();
    }

    private void OnStop(object sender, RoutedEventArgs e)
    {
        if(worker == null)
        {
            return;
        }

        //TODO: How do I stop the script here?

        worker = null;
    }
}


问:
Iterative procedure with nested loops in functional paradigm
I'm learning functional programming (in Haskell) by re-writing some of my old C++ code. One example I'm working on involves the Floyd-Warshall graph search which runs on a 2D NxN adjacency matrix to find the shortest path between all pairs. It uses three nested for loops to scan the 2D array and iteratively reach a solution.

The C++ code would typically be:

```<code>int size = adjacencyMatrix.size();
for ( int k = 0; k < size; k++)
{
    for ( int i = 0; i < size; i++)
    {
        for ( int j = 0; j < size; j++)
        {
            double sum = adjacencyMatrix[i][k] + adjacencyMatrix[k][j];
            if ( sum < adjacencyMatrix[i][j] )
            {
                    adjacencyMatrix[i][j] = sum;
            }
        }
    }
}
</code>```

The key to such a graph search is its iterative method. For example the code above is very sequential; it can only be parallelised to a moderate extent as some calculations can't be done till others have completed.

Furthermore, having access to the index of the matrix means some clever manipulations within the array can be done. The innermost loop of the above graph search uses adjacencyMatrix[i][k], adjacencyMatrix[k][j] and adjacencyMatrix[i][j]. I'm aware of the map function in Haskell, but that doesn't seem to have the same power and flexibility as using array indices.

Aside from trying to simulate an imperative procedure in Haskell I can't work out how re-write the above code in a 'pure' functional style.

How does an iterative procedure that uses complex nested loops to access array indices, such as the graph search above, translate to the functional paradigm?

答:
The best option is to use Data.Vector package and use ifoldl with nested imaps which will look like this:

```<code>{-# LANGUAGE OverloadedLists #-}

import Data.Vector

type Matrix a = Vector (Vector a)

floydwarshall mat = ifoldl (\m k _ ->
                               imap (\i row ->
                                       imap (\j v ->
                                               (m!i!k + m!k!j) `min` v) row) m) mat mat
</code>```

Ifoldl and imap alongside values stored inside vector maps using their indices, which allows you to call values at specific index. The foldl is needed to accumulate all the changes in iterations of k while keeping structure immutable. Inside of imaps you must index inside matrix m which is our accumulator for foldr and which keeps all changes.

If you don't want to import packages, you may always implement imap and ifoldl for stock prelude lists

```<code>imap :: (Int -> a -> b) -> [a] -> [b]
imap f = map (uncurry f) . zip [0,1..]

ifoldl :: (b -> Int -> a -> b) -> b -> [a] -> b
ifoldl f acc = foldl (\ac -> uncurry (f ac)) acc . zip [0,1..]
</code>```

EDITED: According to suggestion by @chi

Body:
I'm learning functional programming (in Haskell) by re-writing some of my old C++ code. One example I'm working on involves the Floyd-Warshall graph search which runs on a 2D NxN adjacency matrix to find the shortest path between all pairs. It uses three nested for loops to scan the 2D array and iteratively reach a solution.

The C++ code would typically be:

int size = adjacencyMatrix.size();
for ( int k = 0; k < size; k++)
{
    for ( int i = 0; i < size; i++)
    {
        for ( int j = 0; j < size; j++)
        {
            double sum = adjacencyMatrix[i][k] + adjacencyMatrix[k][j];
            if ( sum < adjacencyMatrix[i][j] )
            {
                    adjacencyMatrix[i][j] = sum;
            }
        }
    }
}

The key to such a graph search is its iterative method. For example the code above is very sequential; it can only be parallelised to a moderate extent as some calculations can't be done till others have completed.

Furthermore, having access to the index of the matrix means some clever manipulations within the array can be done. The innermost loop of the above graph search uses adjacencyMatrix[i][k], adjacencyMatrix[k][j] and adjacencyMatrix[i][j]. I'm aware of the map function in Haskell, but that doesn't seem to have the same power and flexibility as using array indices.

Aside from trying to simulate an imperative procedure in Haskell I can't work out how re-write the above code in a 'pure' functional style.

How does an iterative procedure that uses complex nested loops to access array indices, such as the graph search above, translate to the functional paradigm?

Body:
The best option is to use Data.Vector package and use ifoldl with nested imaps which will look like this:

{-# LANGUAGE OverloadedLists #-}

import Data.Vector

type Matrix a = Vector (Vector a)

floydwarshall mat = ifoldl (\m k _ ->
                               imap (\i row ->
                                       imap (\j v ->
                                               (m!i!k + m!k!j) `min` v) row) m) mat mat

Ifoldl and imap alongside values stored inside vector maps using their indices, which allows you to call values at specific index. The foldl is needed to accumulate all the changes in iterations of k while keeping structure immutable. Inside of imaps you must index inside matrix m which is our accumulator for foldr and which keeps all changes.

If you don't want to import packages, you may always implement imap and ifoldl for stock prelude lists

imap :: (Int -> a -> b) -> [a] -> [b]
imap f = map (uncurry f) . zip [0,1..]

ifoldl :: (b -> Int -> a -> b) -> b -> [a] -> b
ifoldl f acc = foldl (\ac -> uncurry (f ac)) acc . zip [0,1..]

EDITED: According to suggestion by @chi


问:
Icon of the notification is different
I get a push notification from FCM. When my application is minimized or screen is locked, I see a title of notification : Here is your notification and different icon.

How I can change this? This is my code and how I create and display a notification I don't have this:

```<code>private void createNotification( String messageBody) {
    Intent intent = new Intent( this , NotificationActivity. class );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Wiadomosc z serwera")
            .setContentText(messageBody)
            .setAutoCancel( true )
            .setSound(notificationSoundURI)
            .setContentIntent(resultIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, mNotificationBuilder.build());
}
</code>```

答:
Modified createNotification method .

1 . Add setLargeIcon() method to set large icon .

2 . Put your own title in setTitle() method .

```<code>private void createNotification( String messageBody) {
        Intent intent = new Intent( this , NotificationActivity. class );
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
                .setSmallIcon(R.mipmap.ic_launcher) /*Icon to display in the Notification Bar */
                .setLargeIcon(R.mipmap.largeicon) /*Icon to display when you scroll down notification tray */
                .setContentTitle("Your own Title") /*Notification Title which will display when you scroll down Notification tray */
                .setContentText(messageBody)
                .setAutoCancel( true )
                .setSound(notificationSoundURI)
                .setContentIntent(resultIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

 notificationManager.notify(0, mNotificationBuilder.build());
    }
</code>```

Title: Icon of the notification is different

Body:
I get a push notification from FCM. When my application is minimized or screen is locked, I see a title of notification : Here is your notification and different icon.

How I can change this? This is my code and how I create and display a notification I don't have this:

private void createNotification( String messageBody) {
    Intent intent = new Intent( this , NotificationActivity. class );
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

    Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("Wiadomosc z serwera")
            .setContentText(messageBody)
            .setAutoCancel( true )
            .setSound(notificationSoundURI)
            .setContentIntent(resultIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, mNotificationBuilder.build());
}

Body:
Modified createNotification method .

1 . Add setLargeIcon() method to set large icon .

2 . Put your own title in setTitle() method .

private void createNotification( String messageBody) {
        Intent intent = new Intent( this , NotificationActivity. class );
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent resultIntent = PendingIntent.getActivity( this , 0, intent, PendingIntent.FLAG_ONE_SHOT);

        Uri notificationSoundURI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder( this)
                .setSmallIcon(R.mipmap.ic_launcher) /*Icon to display in the Notification Bar */
                .setLargeIcon(R.mipmap.largeicon) /*Icon to display when you scroll down notification tray */
                .setContentTitle("Your own Title") /*Notification Title which will display when you scroll down Notification tray */
                .setContentText(messageBody)
                .setAutoCancel( true )
                .setSound(notificationSoundURI)
                .setContentIntent(resultIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

 notificationManager.notify(0, mNotificationBuilder.build());
    }


问:
UITextView - Scrolling to selected place
I have a Notes view controller with a large UITextView in it. When the keyboard is active, I've made sure the contentInset is adjusted so that the user can see what's being typed. This works well.

However, if the textView already has a large amount of text in it and the keyboard isn't active yet, when the user taps on text in the lower portion of the textView, the textView doesn't automatically scroll up to show their cursor. As soon as they start typing, the textView scrolls to the appropriate position, but I'd like the textView to scroll to the position of the cursor as soon as they tap in the textView.

Here's my code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(_ notification: Notification) {
    let mainViewY = self.view.frame.origin.y
    let textViewY = self.textView.frame.origin.y
    let oneLineHeight = self.textView.font.lineHeight
    let delta = (textViewY - mainViewY) - oneLineHeight
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    let keyboardHeight = (keyboardSize?.height)!
    self.textView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight + delta, 0)
    self.textView.scrollIndicatorInsets = textView.contentInset
}

func keyboardWillBeHidden(_ notification: Notification) {
    self.textView.contentInset = UIEdgeInsets.zero
    self.textView.scrollIndicatorInsets = UIEdgeInsets.zero
}
</code>```

I searched for people asking this question but couldn't find anyone experiencing my particular issue.

How can I ensure that when the user taps the textView to begin typing in a portion of the textView that would be covered by the keyboard, the textView scrolls to show their cursor even before they actually type?

答: You can achieve this by calling scrollRangeToVisible (docs here) using the text view's selectedRange. That method scrolls the text view to any range of text, and the selectedRange should be at the position of the cursor.

Body:
I have a Notes view controller with a large UITextView in it. When the keyboard is active, I've made sure the contentInset is adjusted so that the user can see what's being typed. This works well.

However, if the textView already has a large amount of text in it and the keyboard isn't active yet, when the user taps on text in the lower portion of the textView, the textView doesn't automatically scroll up to show their cursor. As soon as they start typing, the textView scrolls to the appropriate position, but I'd like the textView to scroll to the position of the cursor as soon as they tap in the textView.

Here's my code:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(_ notification: Notification) {
    let mainViewY = self.view.frame.origin.y
    let textViewY = self.textView.frame.origin.y
    let oneLineHeight = self.textView.font.lineHeight
    let delta = (textViewY - mainViewY) - oneLineHeight
    let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    let keyboardHeight = (keyboardSize?.height)!
    self.textView.contentInset = UIEdgeInsetsMake(0, 0, keyboardHeight + delta, 0)
    self.textView.scrollIndicatorInsets = textView.contentInset
}

func keyboardWillBeHidden(_ notification: Notification) {
    self.textView.contentInset = UIEdgeInsets.zero
    self.textView.scrollIndicatorInsets = UIEdgeInsets.zero
}

I searched for people asking this question but couldn't find anyone experiencing my particular issue.

How can I ensure that when the user taps the textView to begin typing in a portion of the textView that would be covered by the keyboard, the textView scrolls to show their cursor even before they actually type?


问:
How to do while loop with if exist in SQL Server stored procedure?
I'm just learning to use while loop in stored procedure I'm not sure why the stored procedure does not return any value.

I'm using the if exist to check whether the id exist in the table or not.
And if there is more than 1 id I need to execute again the same query.

I tried using while loop and its not working.

I declare the @keyValue as Varchar and it causes an error

Conversion failed when converting the varchar value 'c29dc109b310479fa5c281eb20c61656' to data type int.

That is why I use COUNT at the WHILE

```<code>IF EXISTS (SELECT t1.ref_id
           FROM pbosproinvoiceitem t1
           WHERE t1.ref_id = @keyValue)
    WHILE COUNT(@keyValue) > 1
    BEGIN
        --need to do for loop
        SELECT @balWghtSso = (SELECT t1.act_wght
                              FROM ccossoitem t1
                              WHERE t1.master_id = @keyValue) -
                             (SELECT t1.wght
                              FROM ccossoitem t1
                              WHERE t1.master_id = @keyValue)
        SELECT @balWghtBl = (SELECT t1.act_wght
                             FROM ccosblitem t1
                             WHERE t1.master_id = @keyValue) -
                            (SELECT t1.wght
                             FROM ccosblitem t1
                             WHERE t1.master_id = @keyValue)

        SELECT DISTINCT
            t1.debtor_code AS customer_code, t1.tml_code, t1.scn,
            t2.cg_type, t3.qty, @balWghtSso AS mea, t3.vol,
            CASE
               WHEN t3.from_loc = 'DL' THEN 1 ELSE 0
            END AS ex_wharf,
            t2.dg_flg, 0 AS conveyor_ind, t1.sso_num AS ref_doc_num,
            t1.id AS ref_id
        FROM
            ccosso t1
        INNER JOIN
            ccossoitem t2 ON t1.id = t2.master_id
        INNER JOIN
            ccosgodown t3 ON t3.blso_id = t1.id AND t3.blso_item_id = t2.id
        WHERE
            t3.move_type = 'LOAD'
            AND t1.id = @keyValue

        UNION ALL

        SELECT DISTINCT
            t1.debtor_code AS customer_code, t1.tml_code, t1.scn,
            t2.cg_type, t3.qty,
            @balWghtBl AS mea, t3.vol,
            CASE
               WHEN t3.from_loc = 'DD' THEN 1 ELSE 0
            END AS ex_wharf,
            t2.dg_flg, 0 AS conveyor_ind, t1.bl_num AS ref_doc_num,
            t1.id AS ref_id
        FROM
            ccosbl t1
        INNER JOIN
            ccosblitem t2 ON t1.id = t2.master_id
        INNER JOIN
            ccosgodown t3 ON t3.blso_id = t1.id AND t3.blso_item_id = t2.id
        WHERE
            t3.move_type = 'DELV'
            AND t1.id = @keyValue
    END;
</code>```

答:
You have to re-write your while loop like below, and remove the IF exists condition.</p>

```<code>WHILE( SELECT COUNT(1)
FROM pbosproinvoiceitem t1
WHERE t1.ref_id = @keyValue > 1)
</code>```

Body:
I'm just learning to use while loop in stored procedure I'm not sure why the stored procedure does not return any value.

I'm using the if exist to check whether the id exist in the table or not.
And if there is more than 1 id I need to execute again the same query.

I tried using while loop and its not working.

I declare the @keyValue as Varchar and it causes an error

Conversion failed when converting the varchar value 'c29dc109b310479fa5c281eb20c61656' to data type int.

That is why I use COUNT at the WHILE

IF EXISTS (SELECT t1.ref_id
           FROM pbosproinvoiceitem t1
           WHERE t1.ref_id = @keyValue)
    WHILE COUNT(@keyValue) > 1
    BEGIN
        --need to do for loop
        SELECT @balWghtSso = (SELECT t1.act_wght
                              FROM ccossoitem t1
                              WHERE t1.master_id = @keyValue) -
                             (SELECT t1.wght
                              FROM ccossoitem t1
                              WHERE t1.master_id = @keyValue)
        SELECT @balWghtBl = (SELECT t1.act_wght
                             FROM ccosblitem t1
                             WHERE t1.master_id = @keyValue) -
                            (SELECT t1.wght
                             FROM ccosblitem t1
                             WHERE t1.master_id = @keyValue)

        SELECT DISTINCT
            t1.debtor_code AS customer_code, t1.tml_code, t1.scn,
            t2.cg_type, t3.qty, @balWghtSso AS mea, t3.vol,
            CASE
               WHEN t3.from_loc = 'DL' THEN 1 ELSE 0
            END AS ex_wharf,
            t2.dg_flg, 0 AS conveyor_ind, t1.sso_num AS ref_doc_num,
            t1.id AS ref_id
        FROM
            ccosso t1
        INNER JOIN
            ccossoitem t2 ON t1.id = t2.master_id
        INNER JOIN
            ccosgodown t3 ON t3.blso_id = t1.id AND t3.blso_item_id = t2.id
        WHERE
            t3.move_type = 'LOAD'
            AND t1.id = @keyValue

        UNION ALL

        SELECT DISTINCT
            t1.debtor_code AS customer_code, t1.tml_code, t1.scn,
            t2.cg_type, t3.qty,
            @balWghtBl AS mea, t3.vol,
            CASE
               WHEN t3.from_loc = 'DD' THEN 1 ELSE 0
            END AS ex_wharf,
            t2.dg_flg, 0 AS conveyor_ind, t1.bl_num AS ref_doc_num,
            t1.id AS ref_id
        FROM
            ccosbl t1
        INNER JOIN
            ccosblitem t2 ON t1.id = t2.master_id
        INNER JOIN
            ccosgodown t3 ON t3.blso_id = t1.id AND t3.blso_item_id = t2.id
        WHERE
            t3.move_type = 'DELV'
            AND t1.id = @keyValue
    END;

Body:
You have to re-write your while loop like below, and remove the IF exists condition.

WHILE( SELECT COUNT(1)
FROM pbosproinvoiceitem t1
WHERE t1.ref_id = @keyValue > 1)


问:
Escape characters in Matlab
I am reading a file using fileread() which returns me the entire file. Now I need to read line by line and convert them into process the data. Can I know how I would be able to detect the newline character in Matlab? I tried '\n' and '\r\n' and it doesn't work.

Thanks in advance

答:
For special acharacters either use the char function with the character code (http://www.asciitable.com/) or sprintf (my preferred way for better readability.
For example you are looking for sprintf('\n') or sprintf('\r\n')

char(13) is carriage return \r
char(10) is new line \n

Title: Escape characters in Matlab


问:
SQL Count on multiple joins with dynamic WHERE
My issue is that I have a Select statement that has a where clause that is generated on the fly.  It is joined across 5 tables.

I basically need a Count of each DISTINCT instance of a USER ID in table 1 that falls into the scope of the WHERE.  This has to be able to be executed in one statement as well. So, Esentially, I can't do a global GROUP BY because of the other 4 tables data I need returned.

If I could get a column that had the count that was duplicated where the primary key column is that would be perfect.  Right now this is what I'm looking at as my query:

```<code>SELECT  *
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column
        , 3.Column
        , 3.Column2
        , 1.Date_Time_In DESC
</code>```

So instead of selecting all columns, I will be filtering it down to about 5 or 6 but with that I need something like a Total column that is the Distinct count of TBL1's Primary Key that applies the WHERE clause that has a possibility of growing and shrinking in size.

I almost wish there was a way to apply the same WHERE clause to a subselect because I realize that would work but don't know of a way other than creating a variable and just placing it in both places which I can't do either.

答:
something like adding:  </p>

```<code>inner join (select pk, count(distinct user_id) from tbl1 WHERE Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00') as tbl1too on 1.PK = tbl1too.PK
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My issue is that I have a Select statement that has a where clause that is generated on the fly.  It is joined across 5 tables.

I basically need a Count of each DISTINCT instance of a USER ID in table 1 that falls into the scope of the WHERE.  This has to be able to be executed in one statement as well. So, Esentially, I can't do a global GROUP BY because of the other 4 tables data I need returned.

If I could get a column that had the count that was duplicated where the primary key column is that would be perfect.  Right now this is what I'm looking at as my query:

SELECT  *
FROM    TBL1 1
        INNER JOIN TBL2 2 On 2.FK = 1.FK
        INNER JOIN TBL3 3 On 3.PK = 2.PK INNER JOIN TBL4 4 On 4.PK = 3.PK
        LEFT OUTER JOIN TBL5 5 ON 4.PK = 5.PK
WHERE   1.Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00'
ORDER BY
        4.Column
        , 3.Column
        , 3.Column2
        , 1.Date_Time_In DESC

So instead of selecting all columns, I will be filtering it down to about 5 or 6 but with that I need something like a Total column that is the Distinct count of TBL1's Primary Key that applies the WHERE clause that has a possibility of growing and shrinking in size.

I almost wish there was a way to apply the same WHERE clause to a subselect because I realize that would work but don't know of a way other than creating a variable and just placing it in both places which I can't do either.

Body:
something like adding:

inner join (select pk, count(distinct user_id) from tbl1 WHERE Date_Time_In BETWEEN '2010-11-15 12:00:00' AND '2010-11-30 12:00:00') as tbl1too on 1.PK = tbl1too.PK


问:
Check if the string contains all the characters from a to z
I have to write a C# code to check if a string contains all the alphabets from a to z ."this is a test" (without quotes). It doesn't contain all alphabets from a to z so the  output is no.
 "abcdefghijklmnopqrstuvwxyz". It contains all alphabets from a to z so the  output is yes.</p>

答:
I would do it with HashSets:

```<code>bool HasAllLeters(string input)
{
    var lettersInInput = new HashSet<char>(input); // or `input.ToLower()` for case insensitiveness
    var alphabet = new HashSet<char>("abcdefghijklmnopqrstuvwxyz"); // you can actually store this as a `private static readonly` field for performance
    return alphabet.IsSubsetOf(lettersInInput);
}
</code>```

I used IsSubsetOf and not Equals because the input may contain characters that are not letters, like punctuation.

Edit: I just noticed that input.ToLower() allocates a whole string. So use input.Select(ch => char.ToLower(ch)) instead.

Body:
I would do it with HashSets:

bool HasAllLeters(string input)
{
    var lettersInInput = new HashSet<char>(input); // or `input.ToLower()` for case insensitiveness
    var alphabet = new HashSet<char>("abcdefghijklmnopqrstuvwxyz"); // you can actually store this as a `private static readonly` field for performance
    return alphabet.IsSubsetOf(lettersInInput);
}

I used IsSubsetOf and not Equals because the input may contain characters that are not letters, like punctuation.

Edit: I just noticed that input.ToLower() allocates a whole string. So use input.Select(ch => char.ToLower(ch)) instead.


问:
Pandas: Multiplying two columns of same dataframe thats dependent on third column
How can I multiply two columns of within a same dataframe? My dataframe looks like below image and I want to output like this. However, I cannot find how to multiply two columns that are dependent on first row of same dataframe. I would really appreciate some help on this.

```<code>request                            totalbytes
/login                              8520
/shuttle/countdown/                 7970
/shuttle/countdown/liftoff.html     0
</code>```

So far my output is below, but how can I get unique rows.

答:
Short way to get your posted expected results</p>

```<code>df.drop_duplicates().set_index('request').prod(1).reset_index(name='totalbytes')

                           request  totalbytes
0               /shuttle/countdown        7970
1                           /login        8520
2  /shuttle/countdown/liftoff.html           0
</code>```

Body:
How can I multiply two columns of within a same dataframe? My dataframe looks like below image and I want to output like this. However, I cannot find how to multiply two columns that are dependent on first row of same dataframe. I would really appreciate some help on this.

request                            totalbytes
/login                              8520
/shuttle/countdown/                 7970
/shuttle/countdown/liftoff.html     0

So far my output is below, but how can I get unique rows.

Body:
Short way to get your posted expected results

df.drop_duplicates().set_index('request').prod(1).reset_index(name='totalbytes')

                           request  totalbytes
0               /shuttle/countdown        7970
1                           /login        8520
2  /shuttle/countdown/liftoff.html           0


问:
Reading xml ref attribute in .NET
I can do this in Xpath, but unfortunately for this particular project I am unable to use xpath.

I have the following node selected:

```<code><client href="http://somewebsitehere.com" rel="needthisdata"></client>

clientnode.Attributes["href"].Value
</code>```

correctly returns "http://somewebsitehere.com", but

```<code>clientnode.Attributes["rel"].Value
</code>```

does not work?

What am I doing wrong here?

Full Usage:

```<code>foreach (XmlNode clientnode in clientnodelist)
{
    MessageBox.Show(clientnode.Attributes["rel"].Value);
}
</code>```

The above gives a NullReferenceException, whereas replacing "rel" with "href" works fine.

I'm sure i've selected the correct node as well as innertext matches, as well as attribute.count returning 2.

答:
Read your code. You are using clientnode as the loop variable, but you are referencing selectednode.

What if one particular node doesn't have a "rel" attribute? NullReferenceException.

Title: Reading xml ref attribute in .NET

Body:
I can do this in Xpath, but unfortunately for this particular project I am unable to use xpath.

I have the following node selected:

<client href="http://somewebsitehere.com" rel="needthisdata"></client>

clientnode.Attributes["href"].Value

correctly returns "http://somewebsitehere.com", but

clientnode.Attributes["rel"].Value

does not work?

What am I doing wrong here?

Full Usage:

foreach (XmlNode clientnode in clientnodelist)
{
    MessageBox.Show(clientnode.Attributes["rel"].Value);
}

The above gives a NullReferenceException, whereas replacing "rel" with "href" works fine.

I'm sure i've selected the correct node as well as innertext matches, as well as attribute.count returning 2.


问:
How to write laravel model based in this query with pagination?
```<code>for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }
</code>```

Hear my Query is

```<code>$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");
</code>```

How to write laravel model based in this query with pagination???

答:
Below is the Eloquent Query considering Post as your Model Name and Page Size 50.

```<code>$posts = \App\Post::where('skills','like','%javascript%')
                  ->orWhere('skills','like','%php%')
                  ->where('status',1)
                  ->orderBy('id','desc')
                  ->paginate(50);
</code>```

Loading records

```<code>$posts->items();
</code>```

Rendering Pagination on Blade

```<code>{!! $posts->render() !!}
</code>```

Just a recommendation
Your table name should be posts instead or post then Laravel can manage it implicitly but in your case currently you will have to  mention the table name in your model with code protected $table = 'post'; in your app/post.php file, read more here.

Body:
for ($i = 0; $i < count($keyskill); $i++) {
                    if ($i == count($keyskill) - 1) {
                        $key .= "skills like '%" . $keyskill[$i] . "%' ";
                    } else {
                        $key .= "skills like '%" . $keyskill[$i] . "%' or ";
                    }
                }

Hear my Query is

$jobs = DB::select("SELECT * from post where ( $key ) and status=1 order by id desc");

How to write laravel model based in this query with pagination???

Body:
Below is the Eloquent Query considering Post as your Model Name and Page Size 50.

$posts = \App\Post::where('skills','like','%javascript%')
                  ->orWhere('skills','like','%php%')
                  ->where('status',1)
                  ->orderBy('id','desc')
                  ->paginate(50);

Loading records

$posts->items();

Rendering Pagination on Blade

{!! $posts->render() !!}

Just a recommendation
Your table name should be posts instead or post then Laravel can manage it implicitly but in your case currently you will have to  mention the table name in your model with code protected $table = 'post'; in your app/post.php file, read more here.


问:
Implementing vungle in corona sdk
How do i implement vungle in to corona sdk for only one scene. I followed the docs on corona site to implement vungle to my game. I implemented in only one scene of my game but it shows in every scene randomly, my question is how do i keep the vungle in only one scene.

I use also inmobi ads in game.

Here is the code i used.

I used this code in only one scene of my game.

```<code> local provider = "vungle"
 local appId = "vungleTest"
 local ads = require "ads"

 local function adListener( event )
    if event.type == "adStart" and event.isError then
        -- cached video ad not available for display
    end
 end

 ads.init( provider, appId, adListener )
 local wasAdShown = ads.show( "interstitial", { isAnimated = false, isBackButtonEnabled = true } )
</code>```

答:
do it like this

if (ads.isAdAvailable()) then
local adShown = ads.show("interstitial", { isAnimated = false })
end

otherwise when ad get cached(loaded) it come to screen.

Title: Implementing vungle in corona sdk

Body:
How do i implement vungle in to corona sdk for only one scene. I followed the docs on corona site to implement vungle to my game. I implemented in only one scene of my game but it shows in every scene randomly, my question is how do i keep the vungle in only one scene.

I use also inmobi ads in game.

Here is the code i used.

I used this code in only one scene of my game.

 local provider = "vungle"
 local appId = "vungleTest"
 local ads = require "ads"

 local function adListener( event )
    if event.type == "adStart" and event.isError then
        -- cached video ad not available for display
    end
 end

 ads.init( provider, appId, adListener )
 local wasAdShown = ads.show( "interstitial", { isAnimated = false, isBackButtonEnabled = true } )


问:
Code copied one-to-one from the textbook does absolutely nothing
I wrote the following code from a tutorial textbook:

```<code>#include <opencv/highgui.h>
#include <opencv/cv.h>
using namespace cv;

/*

Displays a video with a trackbar

*/

int         g_slider_position = 0;
CvCapture*  g_capture         = NULL;

void onTrackbarSlide(int pos){
    cvSetCaptureProperty(
        g_capture,
        CV_CAP_PROP_POS_FRAMES,
        pos
    );

}

int main( int argc, char** argv){
    cvNamedWindow( "Example 3", CV_WINDOW_AUTOSIZE);
    g_capture = cvCreateFileCapture( argv[1] );
    int frames = (int) cvGetCaptureProperty(
        g_capture,
        CV_CAP_PROP_FRAME_COUNT
    );
    if( frames!= 0 ){
        cvCreateTrackbar(
            "Position",
            "Example 3",
            &g_slider_position,
            frames,
            onTrackbarSlide
        );
    }
    IplImage* frame;
    return (0);
}
</code>```

and except for the using namespace cv; and the comment, It's one-to-one for every character. I compiled it with this:

```<code>g++ CVB--02-TrackBarVid.cpp -o CVB--02-TrackBarVid  `pkg-config --cflags --libs opencv`
</code>```

and when I ran it with a short animated video clip... Absolutely nothing happened. It's supposed to display a video with a scroll bar, and what makes it even more strange is that an earlier program that did nothing but play a video worked fine, even when I changed it so that the video was only 640x480.

What could be going wrong here?

答:
The code you provided actually does something, but not much - it displays an empty window named "Example 3" and immediately exits.

What it does it checks the number of frames in your video and puts it into the frames variable. If there are any frames in the provided video file it creates a trackbar. But after that nothing happens. this code lacks video processing like taking frames from the video file. You can see that there is a pointer declared IplImage* frame; which is left uninitialized and the program ends with return (0);. There at least should be a loop going from 0 (first frame) to frames-1 (last frame) taking each frame from the video and putting it to the "Example 3" window.

This code looks like a bad "copy-paste" or something...

Body:
I wrote the following code from a tutorial textbook:

#include <opencv/highgui.h>
#include <opencv/cv.h>
using namespace cv;

/*

Displays a video with a trackbar

*/

int         g_slider_position = 0;
CvCapture*  g_capture         = NULL;

void onTrackbarSlide(int pos){
    cvSetCaptureProperty(
        g_capture,
        CV_CAP_PROP_POS_FRAMES,
        pos
    );

}

int main( int argc, char** argv){
    cvNamedWindow( "Example 3", CV_WINDOW_AUTOSIZE);
    g_capture = cvCreateFileCapture( argv[1] );
    int frames = (int) cvGetCaptureProperty(
        g_capture,
        CV_CAP_PROP_FRAME_COUNT
    );
    if( frames!= 0 ){
        cvCreateTrackbar(
            "Position",
            "Example 3",
            &g_slider_position,
            frames,
            onTrackbarSlide
        );
    }
    IplImage* frame;
    return (0);
}

and except for the using namespace cv; and the comment, It's one-to-one for every character. I compiled it with this:

g++ CVB--02-TrackBarVid.cpp -o CVB--02-TrackBarVid  `pkg-config --cflags --libs opencv`

and when I ran it with a short animated video clip... Absolutely nothing happened. It's supposed to display a video with a scroll bar, and what makes it even more strange is that an earlier program that did nothing but play a video worked fine, even when I changed it so that the video was only 640x480.

What could be going wrong here?


问:
Migrate oracle data (.dmp file) to mongodb
I have installed MongoDB on my Linux machine. Now i want to migrate my oracle DB to MongoDB. I have .dmp file of my oracle user which need to be imported in Mongodb.
I am not sure whether i can directly use mongoimport to import it or there is any tool available for this migration.

Any help will be appreciated.
Thank you!

答:
We can import the oracle data with mongoimport. Just we need the table to be exported in .csv format.
We can export oracle table in .csv format wih the help of toad or SQL developer.
Once we have .csv file ready, we can import it into our mongodb with mongoimport command.</p>


问:
How to store values in MONGO DB using JAVA?
I want to make a blog post in my web application. Initially I was using mysql as DB. In which i will get the post entered in the text area of blog as an object in JS and send that object to java server side. There I will write mysql query and get the object in resultset and save in database. But now i want to use mongoDB for the same. I am able to understand the basic stuff through many tutorials which I learnt. But I am unable to implement that in my application. I want to know how the object that comes from the JS will be sent inside the loop and how I should query to save the object also similarly if I need to send a object from server side to JS. How should i do.?

My Server side code:

```<code>    public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("myblog");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

   //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");

      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
     while(cursor.hasNext()){
        System.out.println(cursor.next());
    }
</code>```

In the above code i understood everything such as how a mongo connection, documents, collections and cursor's work. Now how should i save the value coming as an object from JS and save in mongoDB. Any Suggestions Please?

答:
Use method save of DBCollection class something like that:

```<code>while(cursor.hasNext()){
    DBObject doc = cursor.next();

    doc.put("name", "Leo-vin");

    items.save(doc);
}
</code>```

method cursor.next() returns object of type DBObject. It is your BSONObject.

Update:

to modify document (BSON) use method put of class BSONObject

Body:
I want to make a blog post in my web application. Initially I was using mysql as DB. In which i will get the post entered in the text area of blog as an object in JS and send that object to java server side. There I will write mysql query and get the object in resultset and save in database. But now i want to use mongoDB for the same. I am able to understand the basic stuff through many tutorials which I learnt. But I am unable to implement that in my application. I want to know how the object that comes from the JS will be sent inside the loop and how I should query to save the object also similarly if I need to send a object from server side to JS. How should i do.?

My Server side code:

    public DB MongoConnection(Blog blog) throws UnknownHostException, MongoException{
    Mongo m = new Mongo("localhost" , 27017); //mongo object
    DB db = m.getDB("myblog");
    System.out.println("Connected");
    //making a collection object which is table when compared to sql
    DBCollection items = db.getCollection("items");
    System.out.println("items got");

   //to work with document we need basicDbObject
    BasicDBObject query = new BasicDBObject();
    System.out.println("Created mongoObject");

      //Cursor, which is like rs in sql
    DBCursor cursor = items.find();
    System.out.println("items got");
     while(cursor.hasNext()){
        System.out.println(cursor.next());
    }

In the above code i understood everything such as how a mongo connection, documents, collections and cursor's work. Now how should i save the value coming as an object from JS and save in mongoDB. Any Suggestions Please?

Body:
Use method save of DBCollection class something like that:

while(cursor.hasNext()){
    DBObject doc = cursor.next();

    doc.put("name", "Leo-vin");

    items.save(doc);
}

method cursor.next() returns object of type DBObject. It is your BSONObject.

Update:

to modify document (BSON) use method put of class BSONObject


问:
How to optimize this query with large data
```<code>select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT * FROM (
        --Get all the latest rows for each ticket
        SELECT ticket_id,final_remaining_uses AS remaining_uses,final_status AS status,action_when
        FROM TicketHistory th
        INNER JOIN (SELECT max(th.id) AS id FROM TicketHistory GROUP BY ticket_id) maxid ON th.id = maxid.id
    ) latest_rows
    WHERE remaining_uses > 0 AND status = 1 --and (action_when < current_date and action_when > current_date -30)
) f_rows
INNER JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1 and source in (0,1,2,6,7,8) and (created_date < current_date and created_date > current_date - 30)

GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;
</code>```

What I'm doing here is getting the latest rows for each ticket from history table.
then filtering rows for tickets which are not active and there is not usage left on that ticket.
then filtering the data with expiry date and other checks

Is there is a way to optimize this query? currently this query take a very long time and postgresql crashes before it returns any data.

both ticket and ticket history has more than 11M rows each.

EDIT

```<code>CREATE TABLE ticket
(
  id serial NOT NULL,
  source integer NOT NULL,
  status integer NOT NULL,
  ticket_type integer NOT NULL,
  remaining_uses integer NOT NULL,
  expiry_date timestamp with time zone NOT NULL,
  price numeric(20,2) NOT NULL,
  created_date timestamp with time zone NOT NULL,
  pax_type integer NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  client_id character varying(50),
  CONSTRAINT skybus_ticket_pkey PRIMARY KEY (id),
  CONSTRAINT skybus_ticket_sale_id_fkey FOREIGN KEY (sale_id)
      REFERENCES skybus_sale (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE ticket
  OWNER TO umd;

-- Index: ticket_client_id_idx

-- DROP INDEX ticket_client_id_idx;

CREATE INDEX ticket_client_id_idx
  ON ticket
  USING btree
  (client_id COLLATE pg_catalog."default");

-- Index: ticket_profile_id_idx

-- DROP INDEX ticket_profile_id_idx;

CREATE INDEX ticket_profile_id_idx
  ON ticket
  USING btree
  (profile_id);

-- Index: ticket_sale_id

-- DROP INDEX ticket_sale_id;

CREATE INDEX skybus_ticket_sale_id
  ON ticket
  USING btree
  (sale_id);

-- Index: ticket_ticket_number

-- DROP INDEX ticket_ticket_number;

CREATE INDEX ticket_ticket_number
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default");

-- Index: ticket_ticket_number_like

-- DROP INDEX ticket_ticket_number_like;

CREATE INDEX ticket_ticket_number_like
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default" varchar_pattern_ops);

-- Index: ticket_topup_for_idx

-- DROP INDEX ticket_topup_for_idx;

CREATE INDEX ticket_topup_for_idx
  ON ticket
  USING btree
  (topup_for COLLATE pg_catalog."default");
</code>```

--===============================

```<code>CREATE TABLE tickethistory
(
  id serial NOT NULL,
  ticket_id integer,
  action integer NOT NULL,
  action_result integer NOT NULL,
  initial_status integer NOT NULL,
  final_status integer NOT NULL,
  final_remaining_uses integer NOT NULL,
  ticket_type integer NOT NULL,
  action_when timestamp with time zone NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  CONSTRAINT tickethistory_pkey PRIMARY KEY (id),
  CONSTRAINT tickethistory_ticket_id_fkey FOREIGN KEY (ticket_id)
      REFERENCES ticket (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE tickethistory
  OWNER TO umd;

-- Index: tickethistory_ticket_id

-- DROP INDEX tickethistory_ticket_id;

CREATE INDEX tickethistory_ticket_id
  ON tickethistory
  USING btree
  (ticket_id);
</code>```

--===== Execution plan -- this is with row_number() change

```<code>    "HashAggregate  (cost=4526158.63..4526158.64 rows=1 width=16) (actual time=382849.323..382849.376 rows=41 loops=1)"
"  ->  Nested Loop  (cost=3880592.94..4526158.62 rows=1 width=16) (actual time=380338.613..382825.688 rows=11745 loops=1)"
"        ->  Subquery Scan on sub  (cost=3880592.94..4463424.47 rows=6563 width=8) (actual time=126346.043..258837.523 rows=293717 loops=1)"
"              Filter: ((sub.remaining_uses > 0) AND (sub.rn = 1) AND (sub.status = 1))"
"              Rows Removed by Filter: 15244064"
"              ->  WindowAgg  (cost=3880592.94..4191436.42 rows=15542174 width=203) (actual time=126345.775..237172.180 rows=15537781 loops=1)"
"                    ->  Sort  (cost=3880592.94..3919448.38 rows=15542174 width=203) (actual time=126345.757..180461.191 rows=15537781 loops=1)"
"                          Sort Key: th.ticket_id, th.*"
"                          Sort Method: external merge  Disk: 3050616kB"
"                          ->  Seq Scan on skybus_tickethistory th  (cost=0.00..483544.74 rows=15542174 width=203) (actual time=14.091..53312.782 rows=15537781 loops=1)"
"        ->  Index Scan using skybus_ticket_pkey on skybus_ticket t  (cost=0.00..9.55 rows=1 width=12) (actual time=0.418..0.418 rows=0 loops=293717)"
"              Index Cond: (id = sub.ticket_id)"
"              Filter: ((source = ANY ('{0,1,2,6,7,8}'::integer[])) AND (created_date < ('now'::cstring)::date) AND (expiry_date >= (('now'::cstring)::date - 1)) AND (created_date > (('now'::cstring)::date - 30)) AND (ticket_type = ANY ('{2,3,4,5,6,7,16,17, (...)"
"              Rows Removed by Filter: 1"
"Total runtime: 383045.381 ms"
</code>```

答:
distinct on () is typically the fastest way of solving greatest-n-per-group problems in Postgres:

```<code>select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT *
    FROM (
        --Get all the latest rows for each ticket
        SELECT <b>distinct on (ticket_id)</b>
               ticket_id,
               final_remaining_uses AS remaining_uses,
               final_status AS status, action_when
        FROM TicketHistory th
        <b>order by ticket_id, id desc</b>
    ) latest_rows
    WHERE remaining_uses > 0
      AND status = 1 --and (action_when  current_date -30)
) f_rows
  JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1
  and source in (0,1,2,6,7,8)
  and created_date  current_date - 30
GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;</code>```

distinct on() together with the order by returns the row with the highest value of tickethistory.id for each ticket_id.

An index on tickethistory (ticket_id, id desc) would probably help. Maybe even one on tickethistory (ticket_id, id desc, final_remaining_uses, final_status, action_when) to enable an index only scan.

However, a timestamp column that stores the moment of creation might be more accurate. If tickethistory.id is e.g. generated id through sequence (because it's a serial) then those values might not reflect that actual order of insertion.

Body:
select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT * FROM (
        --Get all the latest rows for each ticket
        SELECT ticket_id,final_remaining_uses AS remaining_uses,final_status AS status,action_when
        FROM TicketHistory th
        INNER JOIN (SELECT max(th.id) AS id FROM TicketHistory GROUP BY ticket_id) maxid ON th.id = maxid.id
    ) latest_rows
    WHERE remaining_uses > 0 AND status = 1 --and (action_when < current_date and action_when > current_date -30)
) f_rows
INNER JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1 and source in (0,1,2,6,7,8) and (created_date < current_date and created_date > current_date - 30)

GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;

What I'm doing here is getting the latest rows for each ticket from history table.
then filtering rows for tickets which are not active and there is not usage left on that ticket.
then filtering the data with expiry date and other checks

Is there is a way to optimize this query? currently this query take a very long time and postgresql crashes before it returns any data.

both ticket and ticket history has more than 11M rows each.

EDIT

CREATE TABLE ticket
(
  id serial NOT NULL,
  source integer NOT NULL,
  status integer NOT NULL,
  ticket_type integer NOT NULL,
  remaining_uses integer NOT NULL,
  expiry_date timestamp with time zone NOT NULL,
  price numeric(20,2) NOT NULL,
  created_date timestamp with time zone NOT NULL,
  pax_type integer NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  client_id character varying(50),
  CONSTRAINT skybus_ticket_pkey PRIMARY KEY (id),
  CONSTRAINT skybus_ticket_sale_id_fkey FOREIGN KEY (sale_id)
      REFERENCES skybus_sale (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE ticket
  OWNER TO umd;

-- Index: ticket_client_id_idx

-- DROP INDEX ticket_client_id_idx;

CREATE INDEX ticket_client_id_idx
  ON ticket
  USING btree
  (client_id COLLATE pg_catalog."default");

-- Index: ticket_profile_id_idx

-- DROP INDEX ticket_profile_id_idx;

CREATE INDEX ticket_profile_id_idx
  ON ticket
  USING btree
  (profile_id);

-- Index: ticket_sale_id

-- DROP INDEX ticket_sale_id;

CREATE INDEX skybus_ticket_sale_id
  ON ticket
  USING btree
  (sale_id);

-- Index: ticket_ticket_number

-- DROP INDEX ticket_ticket_number;

CREATE INDEX ticket_ticket_number
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default");

-- Index: ticket_ticket_number_like

-- DROP INDEX ticket_ticket_number_like;

CREATE INDEX ticket_ticket_number_like
  ON ticket
  USING btree
  (ticket_number COLLATE pg_catalog."default" varchar_pattern_ops);

-- Index: ticket_topup_for_idx

-- DROP INDEX ticket_topup_for_idx;

CREATE INDEX ticket_topup_for_idx
  ON ticket
  USING btree
  (topup_for COLLATE pg_catalog."default");

--===============================

CREATE TABLE tickethistory
(
  id serial NOT NULL,
  ticket_id integer,
  action integer NOT NULL,
  action_result integer NOT NULL,
  initial_status integer NOT NULL,
  final_status integer NOT NULL,
  final_remaining_uses integer NOT NULL,
  ticket_type integer NOT NULL,
  action_when timestamp with time zone NOT NULL,
  last_updated timestamp with time zone NOT NULL,
  service integer,
  CONSTRAINT tickethistory_pkey PRIMARY KEY (id),
  CONSTRAINT tickethistory_ticket_id_fkey FOREIGN KEY (ticket_id)
      REFERENCES ticket (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
  OIDS=FALSE
);
ALTER TABLE tickethistory
  OWNER TO umd;

-- Index: tickethistory_ticket_id

-- DROP INDEX tickethistory_ticket_id;

CREATE INDEX tickethistory_ticket_id
  ON tickethistory
  USING btree
  (ticket_id);

--===== Execution plan -- this is with row_number() change

    "HashAggregate  (cost=4526158.63..4526158.64 rows=1 width=16) (actual time=382849.323..382849.376 rows=41 loops=1)"
"  ->  Nested Loop  (cost=3880592.94..4526158.62 rows=1 width=16) (actual time=380338.613..382825.688 rows=11745 loops=1)"
"        ->  Subquery Scan on sub  (cost=3880592.94..4463424.47 rows=6563 width=8) (actual time=126346.043..258837.523 rows=293717 loops=1)"
"              Filter: ((sub.remaining_uses > 0) AND (sub.rn = 1) AND (sub.status = 1))"
"              Rows Removed by Filter: 15244064"
"              ->  WindowAgg  (cost=3880592.94..4191436.42 rows=15542174 width=203) (actual time=126345.775..237172.180 rows=15537781 loops=1)"
"                    ->  Sort  (cost=3880592.94..3919448.38 rows=15542174 width=203) (actual time=126345.757..180461.191 rows=15537781 loops=1)"
"                          Sort Key: th.ticket_id, th.*"
"                          Sort Method: external merge  Disk: 3050616kB"
"                          ->  Seq Scan on skybus_tickethistory th  (cost=0.00..483544.74 rows=15542174 width=203) (actual time=14.091..53312.782 rows=15537781 loops=1)"
"        ->  Index Scan using skybus_ticket_pkey on skybus_ticket t  (cost=0.00..9.55 rows=1 width=12) (actual time=0.418..0.418 rows=0 loops=293717)"
"              Index Cond: (id = sub.ticket_id)"
"              Filter: ((source = ANY ('{0,1,2,6,7,8}'::integer[])) AND (created_date < ('now'::cstring)::date) AND (expiry_date >= (('now'::cstring)::date - 1)) AND (created_date > (('now'::cstring)::date - 30)) AND (ticket_type = ANY ('{2,3,4,5,6,7,16,17, (...)"
"              Rows Removed by Filter: 1"
"Total runtime: 383045.381 ms"

Body:
distinct on () is typically the fastest way of solving greatest-n-per-group problems in Postgres:

select ticket_type,f_rows.remaining_uses,t.source,count(t.id) as total
FROM (
    -- Filter rows to get those where remaining_uses > 0 and status = 1
    SELECT *
    FROM (
        --Get all the latest rows for each ticket
        SELECT distinct on (ticket_id)
               ticket_id,
               final_remaining_uses AS remaining_uses,
               final_status AS status, action_when
        FROM TicketHistory th
        order by ticket_id, id desc
    ) latest_rows
    WHERE remaining_uses > 0
      AND status = 1 --and (action_when  current_date -30)
) f_rows
  JOIN Ticket t ON f_rows.ticket_id = t.id
WHERE t.expiry_date >= current_date -1
  and source in (0,1,2,6,7,8)
  and created_date  current_date - 30
GROUP BY ticket_type, f_rows.remaining_uses, t.source
order by source, ticket_type, remaining_uses;

distinct on() together with the order by returns the row with the highest value of tickethistory.id for each ticket_id.

An index on tickethistory (ticket_id, id desc) would probably help. Maybe even one on tickethistory (ticket_id, id desc, final_remaining_uses, final_status, action_when) to enable an index only scan.

However, a timestamp column that stores the moment of creation might be more accurate. If tickethistory.id is e.g. generated id through sequence (because it's a serial) then those values might not reflect that actual order of insertion.


问:
How to refresh a page or refresh ngOnInit() in ionic 2
i'm wondering if there is a way to refresh the ngOnInit() function or refresh the component. i don't wanna use the pull to refresh method. i want to do it on button click or tap. Thank you

home.ts file

```<code>  checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }
    let alert = this.alertCtrl.create({
        title: "Connection Status",
        subTitle: <string> this.network.type,
        buttons: ["OK"]
    });
  alert.present();
});
}
</code>```

home.html file

```<code><ion-card [hidden]="shouldHide">
<ion-card-header>
  <img src="img/sad.png" />
</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    No INTERNET!
  </ion-card-title>
  <button ion-button full (click)="refreshPage($event)">Retry</button>
</ion-card-content>
</code>```

when the connection will be available i want the page to refresh

答:
You may need to refactor your code structure that so it doesn't need the page refresh, using an init method or Rx's subscriptions.

In case if you need the page reload, why don't you use reload method?

window.location.reload();```
</div>
</div>
</p>

<p>Edited:</p>

<p>Are you using network.onConnect subscription?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');

  // We just got a connection but we need to wait briefly
   // before we determine the connection type.  Might need to wait

  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});</code>```

Body:
i'm wondering if there is a way to refresh the ngOnInit() function or refresh the component. i don't wanna use the pull to refresh method. i want to do it on button click or tap. Thank you

home.ts file

  checkNetwork() {
  console.log("check internet");
this.platform.ready().then(() => {
  if(this.network.type == "none"){
    this.shouldHide = false;
    this.dividerHide = true;
  }
    let alert = this.alertCtrl.create({
        title: "Connection Status",
        subTitle: <string> this.network.type,
        buttons: ["OK"]
    });
  alert.present();
});
}

home.html file

<ion-card [hidden]="shouldHide">
<ion-card-header>

</ion-card-header>
<ion-card-content>
  <ion-card-title style="text-align:center">
    No INTERNET!
  </ion-card-title>
  <button ion-button full (click)="refreshPage($event)">Retry</button>
</ion-card-content>

when the connection will be available i want the page to refresh

Body:
You may need to refactor your code structure that so it doesn't need the page refresh, using an init method or Rx's subscriptions.

In case if you need the page reload, why don't you use reload method?

window.location.reload();

Edited:

Are you using network.onConnect subscription?

// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');

  // We just got a connection but we need to wait briefly
   // before we determine the connection type.  Might need to wait

  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});


问:
Checkboxes behave like Radiobutton
I have got 4 checkboxes ad they should act like checkboxes, but they don't.
I just can select one. Can somebody please help me with my problem?

My second question is, is it possible that they are all selected from the beginning?

Thanks!

I think i descriped my question wrong, I can click for example two checkboxes, but then nothing is shown.

Eg.: if i click green and red, then both colors should be shown.

    <input type="checkbox" id="stat1" ng-true-value="'black'" ng-model="statusblack"/>
    black

    <input type="checkbox" id="stat2" ng-true-value="'red'" ng-model="statusred"/>
    red

    <input type="checkbox" id="stat3" ng-true-value="'yellow'" ng-model="statusyellow"/>
    yellowt

    <input type="checkbox" id="stat4" ng-true-value="'green'" ng-model="statusgreen"/>
    green

            Number
            Color
            Info

            {{ co.no }}
            {{ co.color }}
            {{ co.info }}

```

答:
All checkbox can be selected.

Second question:

If you want to make it selected from the start of page, just put checked="true"

example:

```<code> <input type="checkbox" id="stat1" ng-true-value="'black'" checked="true" />
</code>```

Title: Checkboxes behave like Radiobutton

Body:
All checkbox can be selected.

Second question:

If you want to make it selected from the start of page, just put checked="true"

example:

 <input type="checkbox" id="stat1" ng-true-value="'black'" checked="true" />


问:
PHP parsing html post array problems
I have problem with parsing post array from html. It's work on one server, but not work on another (public server).
I user data from one array (make in javascript) to use other posts and populate database. Code made from frontend with var data[]; JSON.stringify(data);

```<code>        $predmeti = json_decode($_POST['predmeti']);
        foreach($predmeti as $predmet)
        {
            $podaci = array(
                'id_pohadja' => $_POST['pohadja'],
                'id_predmet' => $predmet,
                'prvo_polugodiste' => $_POST[$predmet . '-prvo_polugodiste'],
                'prvo_zakljucna' => $_POST[$predmet . '-prvo_zakljucna'],
                'drugo_polugodiste' => $_POST[$predmet . '-drugo_polugodiste'],
                'drugo_zakljucna' => $_POST[$predmet . '-drugo_zakljucna']
            );

            try {
                $database->snimiOcene($podaci);
            } catch(Exception $ex) {
                die($ex->getMessage());
            }
        }
</code>```

Recived error:

```<code>PHP Warning:  Invalid argument supplied for foreach()
</code>```

HTML:

```<code>                        <input type="hidden" name="predmeti" id="frmOcenePredmeti" />
</code>```

JavaScript:

```<code>var predmeti = [];
                    $.each(data, function(key, value) {
                        $("#tblOcene tbody").append("<tr>");
                        $("#tblOcene tbody").append("<td>" + key + "</td>");
                        $("#tblOcene tbody").append("<td>" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-prvo_polugodiste" + "\"" +
                            "   value=\"" + value["prvo_polugodiste"] + "\"" +
                            "   />" +
                        "</td>");
                        $("#tblOcene tbody").append("<td>" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-prvo_zakljucna" + "\"" +
                            "   value=\"" + value["prvo_zakljucna"] + "\"" +
                            "   size=\"2\" />" +
                        "</td>");
                        $("#tblOcene tbody").append("<td>" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-drugo_polugodiste" + "\"" +
                            "   value=\"" + value["drugo_polugodiste"] + "\"" +
                            "   />" +
                        "</td>");
                        $("#tblOcene tbody").append("<td>" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-drugo_zakljucna" + "\"" +
                            "   value=\"" + value["drugo_zakljucna"] + "\"" +
                            "   size=\"2\" />" +
                        "</td>");
                        $("#tblOcene tbody").append("</tr>");
                        predmeti.push(value['id_predmet']);
                    });
                    $("#frmOcenePredmeti").val(JSON.stringify(predmeti));
</code>```

Working server print_r($predmeti):

```<code>Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 7 [5] => 11 [6] => 19 [7] => 20 [8] => 21 [9] => 22 [10] => 23 [11] => 13 )
</code>```

Not working server print_r($predmeti): Print nothing

答:
Javascript:

```<code>var predmeti = [];
$.each(data, function(key, value) {
    var row = "";
    row += "<tr>";
    row += "<td>" + key + "</td>";
    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-prvo_polugodiste" + "\"" +
        "   value=\"" + value["prvo_polugodiste"] + "\"" +
        "   />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-prvo_zakljucna" + "\"" +
        "   value=\"" + value["prvo_zakljucna"] + "\"" +
        "   size=\"2\" />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-drugo_polugodiste" + "\"" +
        "   value=\"" + value["drugo_polugodiste"] + "\"" +
        "   />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-drugo_zakljucna" + "\"" +
        "   value=\"" + value["drugo_zakljucna"] + "\"" +
        "   size=\"2\" />" + "</td>";

    row += "</tr>";

    $("#tblOcene tbody").append(row);
    predmeti.push(value['id_predmet']);
});
$("#frmOcenePredmeti").val(JSON.stringify(predmeti));
</code>```

Try this server side code:

```<code>$predmeti = json_decode($_POST['predmeti'], true);
if(is_array($predmeti)) {
    foreach($predmeti as $predmet)
    {
        $podaci = array(
            'id_pohadja' => $_POST['pohadja'],
            'id_predmet' => $predmet,
            'prvo_polugodiste' => $_POST[$predmet . '-prvo_polugodiste'],
            'prvo_zakljucna' => $_POST[$predmet . '-prvo_zakljucna'],
            'drugo_polugodiste' => $_POST[$predmet . '-drugo_polugodiste'],
            'drugo_zakljucna' => $_POST[$predmet . '-drugo_zakljucna']
        );

        try {
            $database->snimiOcene($podaci);
        } catch(Exception $ex) {
            die($ex->getMessage());
        }
    }
}
</code>```

Title: PHP parsing html post array problems

Body:
I have problem with parsing post array from html. It's work on one server, but not work on another (public server).
I user data from one array (make in javascript) to use other posts and populate database. Code made from frontend with var data[]; JSON.stringify(data);

        $predmeti = json_decode($_POST['predmeti']);
        foreach($predmeti as $predmet)
        {
            $podaci = array(
                'id_pohadja' => $_POST['pohadja'],
                'id_predmet' => $predmet,
                'prvo_polugodiste' => $_POST[$predmet . '-prvo_polugodiste'],
                'prvo_zakljucna' => $_POST[$predmet . '-prvo_zakljucna'],
                'drugo_polugodiste' => $_POST[$predmet . '-drugo_polugodiste'],
                'drugo_zakljucna' => $_POST[$predmet . '-drugo_zakljucna']
            );

            try {
                $database->snimiOcene($podaci);
            } catch(Exception $ex) {
                die($ex->getMessage());
            }
        }

Recived error:

PHP Warning:  Invalid argument supplied for foreach()

HTML:

                        <input type="hidden" name="predmeti" id="frmOcenePredmeti" />

JavaScript:

var predmeti = [];
                    $.each(data, function(key, value) {
                        $("#tblOcene tbody").append("
");
                        $("#tblOcene tbody").append("" + key + "	");
                        $("#tblOcene tbody").append("" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-prvo_polugodiste" + "\"" +
                            "   value=\"" + value["prvo_polugodiste"] + "\"" +
                            "   />" +
                        "	");
                        $("#tblOcene tbody").append("" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-prvo_zakljucna" + "\"" +
                            "   value=\"" + value["prvo_zakljucna"] + "\"" +
                            "   size=\"2\" />" +
                        "	");
                        $("#tblOcene tbody").append("" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-drugo_polugodiste" + "\"" +
                            "   value=\"" + value["drugo_polugodiste"] + "\"" +
                            "   />" +
                        "	");
                        $("#tblOcene tbody").append("" +
                            "<input type=\"text\" class=\"form-control\"" +
                            "   name=\"" + value["id_predmet"] + "-drugo_zakljucna" + "\"" +
                            "   value=\"" + value["drugo_zakljucna"] + "\"" +
                            "   size=\"2\" />" +
                        "	");
                        $("#tblOcene tbody").append("
");
                        predmeti.push(value['id_predmet']);
                    });
                    $("#frmOcenePredmeti").val(JSON.stringify(predmeti));

Working server print_r($predmeti):

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 7 [5] => 11 [6] => 19 [7] => 20 [8] => 21 [9] => 22 [10] => 23 [11] => 13 )

Not working server print_r($predmeti): Print nothing

Body:
Javascript:

var predmeti = [];
$.each(data, function(key, value) {
    var row = "";
    row += "<tr>";
    row += "<td>" + key + "</td>";
    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-prvo_polugodiste" + "\"" +
        "   value=\"" + value["prvo_polugodiste"] + "\"" +
        "   />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-prvo_zakljucna" + "\"" +
        "   value=\"" + value["prvo_zakljucna"] + "\"" +
        "   size=\"2\" />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-drugo_polugodiste" + "\"" +
        "   value=\"" + value["drugo_polugodiste"] + "\"" +
        "   />" + "</td>";

    row += "<td>" + "<input type=\"text\" class=\"form-control\"" +
        "   name=\"" + value["id_predmet"] + "-drugo_zakljucna" + "\"" +
        "   value=\"" + value["drugo_zakljucna"] + "\"" +
        "   size=\"2\" />" + "</td>";

    row += "</tr>";

    $("#tblOcene tbody").append(row);
    predmeti.push(value['id_predmet']);
});
$("#frmOcenePredmeti").val(JSON.stringify(predmeti));

Try this server side code:

$predmeti = json_decode($_POST['predmeti'], true);
if(is_array($predmeti)) {
    foreach($predmeti as $predmet)
    {
        $podaci = array(
            'id_pohadja' => $_POST['pohadja'],
            'id_predmet' => $predmet,
            'prvo_polugodiste' => $_POST[$predmet . '-prvo_polugodiste'],
            'prvo_zakljucna' => $_POST[$predmet . '-prvo_zakljucna'],
            'drugo_polugodiste' => $_POST[$predmet . '-drugo_polugodiste'],
            'drugo_zakljucna' => $_POST[$predmet . '-drugo_zakljucna']
        );

        try {
            $database->snimiOcene($podaci);
        } catch(Exception $ex) {
            die($ex->getMessage());
        }
    }
}


问:
Close modal on AJAX Sucess(ASP.NET MVC)
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

```<code><script src="~/Scripts/jquery-3.1.1.js"></script>
</code>```

For AJAX I using this code

```<code><script>
   $(document).ready(function () {
       $('#save_quest').click(function () {
        savequestion();
    });
});
    function savequestion() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                Question_new: $('#question').val(),
                Answer: $('#answer').val(),
                Preparing: $('#prepare').val(),
                Retries: $('#retries').val(),
                  },
            url: '@Url.Action("CreateNewQuestion", "Questions")',
            success: function (da) {
                if (da.Result === "Success") {
                    $('#myModal').modal('hide')
                    //window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }
</code>```

I need to hide modal when AJAX call is Successful

I try this $('#myModal').modal('hide')

Here is my modal on Primary View

```<code><div class="modal fade" id="myModal" role="dialog" data-backdrop="false">
<div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
            @Html.Partial("~/Views/Questions/CreateQuestion.cshtml")
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>

</div>
</code>```

How I can hide it on AJAX Success?

答:
I found solution

Just need to write

$('#myModal').hide();

Title: Close modal on AJAX Sucess(ASP.NET MVC)

Body:
I have Modal in view for making new record in Database.

View for it in Partial View

Here is code of view

For AJAX I using this code


问:
JPA - Cannot refresh database immediately after merge() - getEntityManager().refresh() has no effect
Im editing a value of a list from a list view page and meeting an issue that I can not refresh database immediately after calling getEntityManager().merge().
So, I have to refresh one more time so that the system returns accurate data result that I've edited even called getEntityManager().refresh() but still no effect.

```<code>getEntityManager().merge(transactions);
getEntityManager().flush();
getEntityManager().refresh(transactions);
</code>```

I've researched so many posts of this problem before posting this and it took me plenty of time.
Sorry for either my bad English or bad coding. I'm a newbie.
Thanks alot !

答:
I found my solution already..This's a little related to Jboss Seam framework i'm using

To display list page view, i used getEntityManage() of EntityQuery of Seam.
 Meanwhile in Editing it, i was using getEntityManage() of EntityHome.

This leads to refresh() or clear() in EntityHome have no effect anyway and still stored cache until i reloaded the page.

I should have cleared cache in getEntityManage of EntityQuery rather than clearing the one of EntityHome by recalling the list searching query or simply calling getEntityManage.clear() in EntityQuery

Hope this 's useful ! thanks

Body:
Im editing a value of a list from a list view page and meeting an issue that I can not refresh database immediately after calling getEntityManager().merge().
So, I have to refresh one more time so that the system returns accurate data result that I've edited even called getEntityManager().refresh() but still no effect.

getEntityManager().merge(transactions);
getEntityManager().flush();
getEntityManager().refresh(transactions);

I've researched so many posts of this problem before posting this and it took me plenty of time.
Sorry for either my bad English or bad coding. I'm a newbie.
Thanks alot !