问:
Trying to show custom group in Home tab Outlook VSTO Add-in when deploying solution
I am writing a VSTO Outlook Add-In and in the machine I am developing, I can add a custom ribbon group to the home tab but when I deploy the add-in through a VS installer, the home tab group does not show. I have set the controlID to TabMail and I have checked the previous answers to no avail. Using Visual Studio 2015 and Outlook 2013.

The following is the auto-generated designer class definition for this ribbon:

```<code>Partial Class Ribbon3
Inherits Microsoft.Office.Tools.Ribbon.RibbonBase

<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New(ByVal container As System.ComponentModel.IContainer)
    MyClass.New()
    InitializeComponent()
    'Required for Windows.Forms Class Composition Designer support
    If (container IsNot Nothing) Then
        container.Add(Me)
    End If

End Sub

<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
    MyBase.New(Globals.Factory.GetRibbonFactory())

    'This call is required by the Component Designer.
    InitializeComponent()

End Sub

'Component overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

'Required by the Component Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Component Designer
'It can be modified using the Component Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
    Dim RibbonDialogLauncherImpl1 As Microsoft.Office.Tools.Ribbon.RibbonDialogLauncher = Me.Factory.CreateRibbonDialogLauncher
    Me.Tab1 = Me.Factory.CreateRibbonTab
    Me.EIP = Me.Factory.CreateRibbonGroup
    Me.Button1 = Me.Factory.CreateRibbonButton
    Me.Button3 = Me.Factory.CreateRibbonButton
    Me.Button2 = Me.Factory.CreateRibbonButton
    Me.Label1 = Me.Factory.CreateRibbonLabel
    Me.EditBox1 = Me.Factory.CreateRibbonEditBox
    Me.Button4 = Me.Factory.CreateRibbonButton
    Me.Tab1.SuspendLayout()
    Me.EIP.SuspendLayout()
    Me.SuspendLayout()
    '
    'Tab1
    '
    Me.Tab1.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office
    Me.Tab1.ControlId.OfficeId = "TabMail"
    Me.Tab1.Groups.Add(Me.EIP)
    Me.Tab1.Label = "TabMail"
    Me.Tab1.Name = "Tab1"
    '
    'EIP
    '
    Me.EIP.DialogLauncher = RibbonDialogLauncherImpl1
    Me.EIP.Items.Add(Me.Button1)
    Me.EIP.Items.Add(Me.Button3)
    Me.EIP.Items.Add(Me.Button2)
    Me.EIP.Items.Add(Me.Label1)
    Me.EIP.Items.Add(Me.EditBox1)
    Me.EIP.Items.Add(Me.Button4)
    Me.EIP.KeyTip = "O"
    Me.EIP.Label = "EIP"
    Me.EIP.Name = "EIP"
    Me.EIP.Position = Me.Factory.RibbonPosition.AfterOfficeId("Find")
    '
    'Button1
    '
    Me.Button1.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button1.Label = "Archive to EIP"
    Me.Button1.Name = "Button1"
    Me.Button1.OfficeImageId = "FileOpenRecentFile"
    Me.Button1.ShowImage = True
    '
    'Button3
    '
    Me.Button3.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button3.Label = "Update EIP List"
    Me.Button3.Name = "Button3"
    Me.Button3.OfficeImageId = "ChangeFolderDownloadSettings"
    Me.Button3.ScreenTip = "Rebuild the internal list matching EIP numbers to EIP directories"
    Me.Button3.ShowImage = True
    '
    'Button2
    '
    Me.Button2.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button2.Label = "Open EIP Folder"
    Me.Button2.Name = "Button2"
    Me.Button2.OfficeImageId = "AlwaysMoveToFolder"
    Me.Button2.ShowImage = True
    '
    'Label1
    '
    Me.Label1.Label = "Active EIP"
    Me.Label1.Name = "Label1"
    '
    'EditBox1
    '
    Me.EditBox1.Label = "Active EIP"
    Me.EditBox1.Name = "EditBox1"
    Me.EditBox1.ScreenTip = "EIP number to associate with message if none found"
    Me.EditBox1.ShowLabel = False
    Me.EditBox1.Text = Nothing
    '
    'Button4
    '
    Me.Button4.Label = "Clear"
    Me.Button4.Name = "Button4"
    Me.Button4.OfficeImageId = "Clear"
    Me.Button4.ShowImage = True
    '
    'Ribbon3
    '
    Me.Name = "Ribbon3"
    Me.RibbonType = "Microsoft.Outlook.Explorer"
    Me.Tabs.Add(Me.Tab1)
    Me.Tab1.ResumeLayout(False)
    Me.Tab1.PerformLayout()
    Me.EIP.ResumeLayout(False)
    Me.EIP.PerformLayout()
    Me.ResumeLayout(False)

End Sub
Friend WithEvents EIP As Microsoft.Office.Tools.Ribbon.RibbonGroup
Friend WithEvents Button1 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents Button3 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents Tab1 As Microsoft.Office.Tools.Ribbon.RibbonTab
Friend WithEvents Button2 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents EditBox1 As Microsoft.Office.Tools.Ribbon.RibbonEditBox
Friend WithEvents Label1 As Microsoft.Office.Tools.Ribbon.RibbonLabel
Friend WithEvents Button4 As Microsoft.Office.Tools.Ribbon.RibbonButton
End Class
</code>```

答: A Ribbon group will not show if any of the controls that it uses is not installed on the host machine. I had to set the vsto runtime as a prerequisite and then it all worked well. Select the installer project, then after selecting  prerequisites in the properties window, select the vsto runtime as a prerequisite.</p>

Body:
I am writing a VSTO Outlook Add-In and in the machine I am developing, I can add a custom ribbon group to the home tab but when I deploy the add-in through a VS installer, the home tab group does not show. I have set the controlID to TabMail and I have checked the previous answers to no avail. Using Visual Studio 2015 and Outlook 2013.

The following is the auto-generated designer class definition for this ribbon:

Partial Class Ribbon3
Inherits Microsoft.Office.Tools.Ribbon.RibbonBase

<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New(ByVal container As System.ComponentModel.IContainer)
    MyClass.New()
    InitializeComponent()
    'Required for Windows.Forms Class Composition Designer support
    If (container IsNot Nothing) Then
        container.Add(Me)
    End If

End Sub

<System.Diagnostics.DebuggerNonUserCode()> _
Public Sub New()
    MyBase.New(Globals.Factory.GetRibbonFactory())

    'This call is required by the Component Designer.
    InitializeComponent()

End Sub

'Component overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        MyBase.Dispose(disposing)
    End Try
End Sub

'Required by the Component Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Component Designer
'It can be modified using the Component Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
    Dim RibbonDialogLauncherImpl1 As Microsoft.Office.Tools.Ribbon.RibbonDialogLauncher = Me.Factory.CreateRibbonDialogLauncher
    Me.Tab1 = Me.Factory.CreateRibbonTab
    Me.EIP = Me.Factory.CreateRibbonGroup
    Me.Button1 = Me.Factory.CreateRibbonButton
    Me.Button3 = Me.Factory.CreateRibbonButton
    Me.Button2 = Me.Factory.CreateRibbonButton
    Me.Label1 = Me.Factory.CreateRibbonLabel
    Me.EditBox1 = Me.Factory.CreateRibbonEditBox
    Me.Button4 = Me.Factory.CreateRibbonButton
    Me.Tab1.SuspendLayout()
    Me.EIP.SuspendLayout()
    Me.SuspendLayout()
    '
    'Tab1
    '
    Me.Tab1.ControlId.ControlIdType = Microsoft.Office.Tools.Ribbon.RibbonControlIdType.Office
    Me.Tab1.ControlId.OfficeId = "TabMail"
    Me.Tab1.Groups.Add(Me.EIP)
    Me.Tab1.Label = "TabMail"
    Me.Tab1.Name = "Tab1"
    '
    'EIP
    '
    Me.EIP.DialogLauncher = RibbonDialogLauncherImpl1
    Me.EIP.Items.Add(Me.Button1)
    Me.EIP.Items.Add(Me.Button3)
    Me.EIP.Items.Add(Me.Button2)
    Me.EIP.Items.Add(Me.Label1)
    Me.EIP.Items.Add(Me.EditBox1)
    Me.EIP.Items.Add(Me.Button4)
    Me.EIP.KeyTip = "O"
    Me.EIP.Label = "EIP"
    Me.EIP.Name = "EIP"
    Me.EIP.Position = Me.Factory.RibbonPosition.AfterOfficeId("Find")
    '
    'Button1
    '
    Me.Button1.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button1.Label = "Archive to EIP"
    Me.Button1.Name = "Button1"
    Me.Button1.OfficeImageId = "FileOpenRecentFile"
    Me.Button1.ShowImage = True
    '
    'Button3
    '
    Me.Button3.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button3.Label = "Update EIP List"
    Me.Button3.Name = "Button3"
    Me.Button3.OfficeImageId = "ChangeFolderDownloadSettings"
    Me.Button3.ScreenTip = "Rebuild the internal list matching EIP numbers to EIP directories"
    Me.Button3.ShowImage = True
    '
    'Button2
    '
    Me.Button2.ControlSize = Microsoft.Office.Core.RibbonControlSize.RibbonControlSizeLarge
    Me.Button2.Label = "Open EIP Folder"
    Me.Button2.Name = "Button2"
    Me.Button2.OfficeImageId = "AlwaysMoveToFolder"
    Me.Button2.ShowImage = True
    '
    'Label1
    '
    Me.Label1.Label = "Active EIP"
    Me.Label1.Name = "Label1"
    '
    'EditBox1
    '
    Me.EditBox1.Label = "Active EIP"
    Me.EditBox1.Name = "EditBox1"
    Me.EditBox1.ScreenTip = "EIP number to associate with message if none found"
    Me.EditBox1.ShowLabel = False
    Me.EditBox1.Text = Nothing
    '
    'Button4
    '
    Me.Button4.Label = "Clear"
    Me.Button4.Name = "Button4"
    Me.Button4.OfficeImageId = "Clear"
    Me.Button4.ShowImage = True
    '
    'Ribbon3
    '
    Me.Name = "Ribbon3"
    Me.RibbonType = "Microsoft.Outlook.Explorer"
    Me.Tabs.Add(Me.Tab1)
    Me.Tab1.ResumeLayout(False)
    Me.Tab1.PerformLayout()
    Me.EIP.ResumeLayout(False)
    Me.EIP.PerformLayout()
    Me.ResumeLayout(False)

End Sub
Friend WithEvents EIP As Microsoft.Office.Tools.Ribbon.RibbonGroup
Friend WithEvents Button1 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents Button3 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents Tab1 As Microsoft.Office.Tools.Ribbon.RibbonTab
Friend WithEvents Button2 As Microsoft.Office.Tools.Ribbon.RibbonButton
Friend WithEvents EditBox1 As Microsoft.Office.Tools.Ribbon.RibbonEditBox
Friend WithEvents Label1 As Microsoft.Office.Tools.Ribbon.RibbonLabel
Friend WithEvents Button4 As Microsoft.Office.Tools.Ribbon.RibbonButton
End Class


来源: stackexchange

问:
Allocate record with variable at negative offset
When allocating memory for a pointer to a record I also need space for an integer pointer located just before the allocated record. This pointer cannot be part of the record itself and it cannot be placed after the record. My current approach is the following:

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

static int n;
struct { int f; } *p;

p = malloc(sizeof (int *) + sizeof *p);
if (p != NULL) {
    p = (void *) ((int **) p + 1);
    *((int **) p - 1) = &n;
}
</code>```

Are the casts well defined? If not, what should I do instead?

Edit:

What I'm trying to achieve is to implement extensible records (OOP) and the integer pointer represent a type ID. An extended record should be compatible with its base type. However, I only need type ID:s for pointer to records. Here is a complete example:

```<code>#include <assert.h>
#include <stdlib.h>

struct T0 {
    int f;
};
int T0ID;

struct T1 {
    struct T0 base;
    int g;
};
int T1ID;

int main(void)
{
    struct T0 *x;
    struct T1 *y;

    y = malloc(sizeof (int *) + sizeof *y);
    if (y != NULL) {
        *((int **) y) = &T1ID;
        y = (void *) ((int **) y + 1);
        ((struct T0 *) y)->f = 1;
        y->g = 2;
    }
    x = (struct T0 *) y;
    assert(x->f == 1);
    return 0;
}
</code>```

答:
Your code, in which you cast (arbitrary) memory addresses to particular object types, is might yield undefined behaviour due to incorrect alignment (cf.
C standard draft):

6.3.2.3 Pointers

(7) A pointer to an object type may be converted to a pointer to a
  different object type. If the resulting pointer is not correctly
  aligned for the referenced type, the behavior is undefined.

You are having a pointer declared to be of type struct{int}* pointing to a (larger memory block), and then casting the pointer and doing arithmetic operations on the (casted) pointer. As it is not guaranteed that int * and struct{int}* are aligned the same way, it is not guaranteed that the behaviour is defined.

To avoid this, encapsulate your structure and the preceeding integer in another structure, e.g. as follows:

```<code>static int n;

struct data_struct {
    int f;
};

struct enclosing_struct {
    int *nPtr;
    struct data_struct data;
};

int main() {

    struct enclosing_struct *e = malloc (sizeof(struct enclosing_struct));
    e->nPtr = &n;
    struct data_struct *dataPtr = &e->data;

    return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When allocating memory for a pointer to a record I also need space for an integer pointer located just before the allocated record. This pointer cannot be part of the record itself and it cannot be placed after the record. My current approach is the following:

#include <stdlib.h>

static int n;
struct { int f; } *p;

p = malloc(sizeof (int *) + sizeof *p);
if (p != NULL) {
    p = (void *) ((int **) p + 1);
    *((int **) p - 1) = &n;
}

Are the casts well defined? If not, what should I do instead?

Edit:

What I'm trying to achieve is to implement extensible records (OOP) and the integer pointer represent a type ID. An extended record should be compatible with its base type. However, I only need type ID:s for pointer to records. Here is a complete example:

#include <assert.h>
#include <stdlib.h>

struct T0 {
    int f;
};
int T0ID;

struct T1 {
    struct T0 base;
    int g;
};
int T1ID;

int main(void)
{
    struct T0 *x;
    struct T1 *y;

    y = malloc(sizeof (int *) + sizeof *y);
    if (y != NULL) {
        *((int **) y) = &T1ID;
        y = (void *) ((int **) y + 1);
        ((struct T0 *) y)->f = 1;
        y->g = 2;
    }
    x = (struct T0 *) y;
    assert(x->f == 1);
    return 0;
}

Body:
Your code, in which you cast (arbitrary) memory addresses to particular object types, is might yield undefined behaviour due to incorrect alignment (cf.
C standard draft):

6.3.2.3 Pointers

(7) A pointer to an object type may be converted to a pointer to a
  different object type. If the resulting pointer is not correctly
  aligned for the referenced type, the behavior is undefined.

You are having a pointer declared to be of type struct{int}* pointing to a (larger memory block), and then casting the pointer and doing arithmetic operations on the (casted) pointer. As it is not guaranteed that int * and struct{int}* are aligned the same way, it is not guaranteed that the behaviour is defined.

To avoid this, encapsulate your structure and the preceeding integer in another structure, e.g. as follows:

static int n;

struct data_struct {
    int f;
};

struct enclosing_struct {
    int *nPtr;
    struct data_struct data;
};

int main() {

    struct enclosing_struct *e = malloc (sizeof(struct enclosing_struct));
    e->nPtr = &n;
    struct data_struct *dataPtr = &e->data;

    return 0;
}


问:
I want Odoo 9 no hide wizard on button click
Is it possible disable close wizard on button click in odoo 9, only allow close on X in right corner of wizard. I want on button call function and populate field in wizard!</p>

答:
```<code>@api.multi
def my_button_method(self):
    # my logic
    return {
        'type': "ir.actions.do_nothing",
    }
</code>```

Clean and simple solution. After clicking button, wizard will stay opened (without reloading) and button will be still active (clickable).

Body:
@api.multi
def my_button_method(self):
    # my logic
    return {
        'type': "ir.actions.do_nothing",
    }

Clean and simple solution. After clicking button, wizard will stay opened (without reloading) and button will be still active (clickable).


问:
Explanation of haarcascade xml files in opencv
I'm working on a project for which I require high accuracy for face detection. For detection I'm using opencv with python.

I'm still not able to achieve my target so I was thinking of manipulating the fields/data in the xml files - haarcascade_frontalface_default.xml and haarcascade_frontalface_alt2.xml.

However, I was unable to understand the tags in it. I want a brief explanation of the major tags only.

答:
Personally I used in more than one occasion the standard opencv's classifiers and they worked fine for me.

But there are a lot of features that could make this classifiers not the best choice for you, like for example the pose of the face (common problem), the
excessive luminosity in the captured frame, etc.

You can try to create your own classifier (http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html):

with an existing dataset (here you can choose the best one that fits for your goal based on the explanations http://www.face-rec.org/databases/)

or with a custom dataset with pictures (a lot of) taken by you  in similar conditions of when your application has to detect the face


问:
Create global object in Azure WCF project
I believe this is a WCF question, but perhaps it's also related to Azure.  I have a WCF project that executes some iron python scripts.  I'd like to keep a cache of the compiled scripts, so they will not need recompiled each time.

When these scripts run the first time, they can sometimes take 2 or 3 seconds.  However, the next time they run, they will execute in just a few milliseconds.  I would like to cache the script source so it is only compiled once, then reused for anyone who uses my service.  Currently, my entire service behavior is instantiated each time someone connects to my service.  Is there a way to have my ScriptCache object be persistant for the life of the Application?

Below is some sample code that I'm playing with.

```<code>[ServiceBehavior]
public class Foo: IFoo {
    ScriptEngine engine = Python.CreateEngine();
    Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>();
    public fooBar doSomething() {
         ...
         for (int editIndex = 0; editIndex < Edits.Count; editIndex++) {
            ScriptHost mCurrentScript;
            if (!ScriptCache.TryGetValue(Edits[editIndex], out mCurrentScript)) {
               mCurrentScript = new ScriptHost(LoadScriptFromStorage(Edits[editIndex]), Edits[editIndex], engine);
               ScriptCache.Add(Edits[editIndex], mCurrentScript);
            }
            mEditTimer.Start();
            mCurrentScript.runScript(mCurrentObj);
            mEditTimer.Stop();
            WriteToLog(mJobID, "Edit: {0}\tTime: {1}", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds);
            mEditTimer.Reset();
            mEditTimer.Start();
            mCurrentScript.runScript(mCurrentObj);
            mEditTimer.Stop();
            WriteToLog(mJobID, "Edit: {0}\tTime: {1}\t2nd run", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds);
            mEditTimer.Reset();
            }
    }
</code>```

答:
The simplest solution is to simply mark the properties as static.  I'm going to guess that is's possible that this code could be call in parallel, so you'll need to make sure that the adding to the dictionary is thread safe.  I've included a code snippet below.  I'd replace the call to ScriptCache.Add with a call to something like the AddToCache function below

```<code>[ServiceBehavior]
public class Foo : IFoo
{
    static ScriptEngine engine = Python.CreateEngine();
    static Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>();
    static object _dictionaryLock = new object();

    static void AddToCache(string edit, ScriptHost host)
    {
        lock (_dictionaryLock)
        {
            if (!ScriptCache.ContainsKey(edit))
            {
                ScriptCache.Add(edit, host);
            }
        }
    }

    ...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I believe this is a WCF question, but perhaps it's also related to Azure.  I have a WCF project that executes some iron python scripts.  I'd like to keep a cache of the compiled scripts, so they will not need recompiled each time.

When these scripts run the first time, they can sometimes take 2 or 3 seconds.  However, the next time they run, they will execute in just a few milliseconds.  I would like to cache the script source so it is only compiled once, then reused for anyone who uses my service.  Currently, my entire service behavior is instantiated each time someone connects to my service.  Is there a way to have my ScriptCache object be persistant for the life of the Application?

Below is some sample code that I'm playing with.

[ServiceBehavior]
public class Foo: IFoo {
    ScriptEngine engine = Python.CreateEngine();
    Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>();
    public fooBar doSomething() {
         ...
         for (int editIndex = 0; editIndex < Edits.Count; editIndex++) {
            ScriptHost mCurrentScript;
            if (!ScriptCache.TryGetValue(Edits[editIndex], out mCurrentScript)) {
               mCurrentScript = new ScriptHost(LoadScriptFromStorage(Edits[editIndex]), Edits[editIndex], engine);
               ScriptCache.Add(Edits[editIndex], mCurrentScript);
            }
            mEditTimer.Start();
            mCurrentScript.runScript(mCurrentObj);
            mEditTimer.Stop();
            WriteToLog(mJobID, "Edit: {0}\tTime: {1}", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds);
            mEditTimer.Reset();
            mEditTimer.Start();
            mCurrentScript.runScript(mCurrentObj);
            mEditTimer.Stop();
            WriteToLog(mJobID, "Edit: {0}\tTime: {1}\t2nd run", Edits[editIndex], mEditTimer.Elapsed.TotalMilliseconds);
            mEditTimer.Reset();
            }
    }

Body:
The simplest solution is to simply mark the properties as static.  I'm going to guess that is's possible that this code could be call in parallel, so you'll need to make sure that the adding to the dictionary is thread safe.  I've included a code snippet below.  I'd replace the call to ScriptCache.Add with a call to something like the AddToCache function below

[ServiceBehavior]
public class Foo : IFoo
{
    static ScriptEngine engine = Python.CreateEngine();
    static Dictionary<string, ScriptHost> ScriptCache = new Dictionary<string, ScriptHost>();
    static object _dictionaryLock = new object();

    static void AddToCache(string edit, ScriptHost host)
    {
        lock (_dictionaryLock)
        {
            if (!ScriptCache.ContainsKey(edit))
            {
                ScriptCache.Add(edit, host);
            }
        }
    }

    ...
}


问:
Postgres: Query that returns percentage
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

```<code>articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046
</code>```

I was able to get the raw counts like this, but not sure how to get the percentage

```<code>SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;
</code>```

答:
What you need is conditional aggregation.

Form PostgreSQL 9.4, there is an explicit syntax (agg_func(...) FILTER (WHERE <predicate>)) for it:

```<code>SELECT   date_trunc('day', time) "day",
         COUNT(*) FILTER (WHERE status = '404 NOT FOUND')::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1
</code>```

For earlier versions, you can simulate that with the CASE expression (you just need to make sure, that the CASE expression's THEN branch always be non-NULL; leaving out the ELSE branch will generate NULLs in all the other cases, so COUNT() won't count them):

```<code>SELECT   date_trunc('day', time) "day",
         COUNT(CASE WHEN status = '404 NOT FOUND' THEN status END)::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1
</code>```

Title: Postgres: Query that returns percentage

Body:
My SQL is rusty. I have a table that logs all HTTP requests and their status. What I am wanting to do is create a query that shows the percentage of the results where status='404 NOT FOUND' PER DAY

here is what the table looks like

articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046

I was able to get the raw counts like this, but not sure how to get the percentage

SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE
status='404 NOT FOUND' group by 1 ORDER BY 1;

Body:
What you need is conditional aggregation.

Form PostgreSQL 9.4, there is an explicit syntax (agg_func(...) FILTER (WHERE <predicate>)) for it:

SELECT   date_trunc('day', time) "day",
         COUNT(*) FILTER (WHERE status = '404 NOT FOUND')::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1

For earlier versions, you can simulate that with the CASE expression (you just need to make sure, that the CASE expression's THEN branch always be non-NULL; leaving out the ELSE branch will generate NULLs in all the other cases, so COUNT() won't count them):

SELECT   date_trunc('day', time) "day",
         COUNT(CASE WHEN status = '404 NOT FOUND' THEN status END)::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1


问:
Activiti 6.0.0 Unable to get the Form properties while completing task
I am new to Activiti 6.0.0 I have created one process with user task and second user task has two form properties but when I have completed first user task and try to complete second user task then form properties not display and I am unable to complete the user task..

Below the is my bpm process:

```<code><?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
  <process id="test-issue-workflow" name="Test Issue Workflow" isExecutable="true">
    <startEvent id="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E"></startEvent>
    <userTask id="task-1" name="User Task 1" activiti:candidateGroups="development">
    </userTask>
    <sequenceFlow id="sid-809C5257-C1D3-4B64-8258-8C5B4F5DCD4A" sourceRef="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E" targetRef="start-progress"></sequenceFlow>
    <userTask id="task-2" name="User Task 2" activiti:candidateGroups="qa">
      <extensionElements>
        <activiti:formProperty id="workRequired" name="Work Required" type="boolean"></activiti:formProperty>
      </extensionElements>
    </userTask>
    <sequenceFlow id="sid-53297083-66C8-4FB3-A5BF-0672E68D0FA7" sourceRef="start-progress" targetRef="initiate-review"></sequenceFlow>
    <sequenceFlow id="sid-34C91FDF-757A-4676-A42C-E4FDC4F3549A" sourceRef="initiate-review" targetRef="sid-2E9F7CFB-5DAE-425D-9B86-7DE000E66627"></sequenceFlow>
    <endEvent id="sid-040D6C5C-BA05-44B4-98BF-AB2672C4ABE3"></endEvent>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_test-issue-workflow">
    <bpmndi:BPMNPlane bpmnElement="test-flow" id="BPMNPlane_test-flow">
      <bpmndi:BPMNShape bpmnElement="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E" id="BPMNShape_sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E">
        <omgdc:Bounds height="30.0" width="30.0" x="105.0" y="130.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="start-progress" id="BPMNShape_start-progress">
        <omgdc:Bounds height="80.0" width="100.0" x="270.0" y="105.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="initiate-review" id="BPMNShape_initiate-review">
</definitions>
</code>```

Can any one please help me.

答: The new Activiti 6 UI uses a different way do display forms. It includes a Form Designer that enables designing forms by dragging and dropping fields. Forms are then referenced using the activiti:formKey attribute in start events and user tasks.</p>

Body:
I am new to Activiti 6.0.0 I have created one process with user task and second user task has two form properties but when I have completed first user task and try to complete second user task then form properties not display and I am unable to complete the user task..

Below the is my bpm process:

<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:omgdi="http://www.omg.org/spec/DD/20100524/DI" typeLanguage="http://www.w3.org/2001/XMLSchema" expressionLanguage="http://www.w3.org/1999/XPath" targetNamespace="http://www.activiti.org/processdef">
  <process id="test-issue-workflow" name="Test Issue Workflow" isExecutable="true">
    <startEvent id="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E"></startEvent>
    <userTask id="task-1" name="User Task 1" activiti:candidateGroups="development">
    </userTask>
    <sequenceFlow id="sid-809C5257-C1D3-4B64-8258-8C5B4F5DCD4A" sourceRef="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E" targetRef="start-progress"></sequenceFlow>
    <userTask id="task-2" name="User Task 2" activiti:candidateGroups="qa">
      <extensionElements>
        <activiti:formProperty id="workRequired" name="Work Required" type="boolean"></activiti:formProperty>
      </extensionElements>
    </userTask>
    <sequenceFlow id="sid-53297083-66C8-4FB3-A5BF-0672E68D0FA7" sourceRef="start-progress" targetRef="initiate-review"></sequenceFlow>
    <sequenceFlow id="sid-34C91FDF-757A-4676-A42C-E4FDC4F3549A" sourceRef="initiate-review" targetRef="sid-2E9F7CFB-5DAE-425D-9B86-7DE000E66627"></sequenceFlow>
    <endEvent id="sid-040D6C5C-BA05-44B4-98BF-AB2672C4ABE3"></endEvent>
  </process>
  <bpmndi:BPMNDiagram id="BPMNDiagram_test-issue-workflow">
    <bpmndi:BPMNPlane bpmnElement="test-flow" id="BPMNPlane_test-flow">
      <bpmndi:BPMNShape bpmnElement="sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E" id="BPMNShape_sid-5A259606-C7C4-4A8E-95F0-F2E8B9D0301E">
        <omgdc:Bounds height="30.0" width="30.0" x="105.0" y="130.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="start-progress" id="BPMNShape_start-progress">
        <omgdc:Bounds height="80.0" width="100.0" x="270.0" y="105.0"></omgdc:Bounds>
      </bpmndi:BPMNShape>
      <bpmndi:BPMNShape bpmnElement="initiate-review" id="BPMNShape_initiate-review">
</definitions>

Can any one please help me.


问:
@media not working below 980px width
I'm trying to add full responsiveness to my website. But, for some reason, it won't read parts below 980px of width. Here's my CSS:

```<code>@media screen and (max-width:1029px){
    h1{
        font-size: 75px;
    }
    h2{
        font-size: 25px;
    }
}
@media screen and (max-width:980px){
    h1{
        font-size: 70px;
    }
    h2{
        font-size: 20px;
    }
}
@media screen and (max-width:954px){
    h1{
        font-size: 65px;
    }
    h2{
        font-size: 15px;
    }
}
</code>```

The 980px part is the last that can be read, if I change it to 979px it stops reading it, as if it wasn't there. !important doesn't change anything. What can I do? Why is there a magical barrier of 980px?

答:
I think you should realigned your media, it will be work for you may be.

I make a fiddle and it's working as you want with media query

working fiddle

```<code>@media screen and (max-width:954px) {
  h1 {
    font-size: 65px;
  }
  h2 {
    font-size: 15px;
  }
}

@media screen and (max-width:1029px) {
  h1 {
    font-size: 75px;
  }
  h2 {
    font-size: 25px;
  }
  @media screen and (max-width:980px) {
    h1 {
      font-size: 70px;
    }
    h2 {
      font-size: 20px;
    }
  }
}
</code>```

Title: @media not working below 980px width

Body:
I'm trying to add full responsiveness to my website. But, for some reason, it won't read parts below 980px of width. Here's my CSS:

@media screen and (max-width:1029px){
    h1{
        font-size: 75px;
    }
    h2{
        font-size: 25px;
    }
}
@media screen and (max-width:980px){
    h1{
        font-size: 70px;
    }
    h2{
        font-size: 20px;
    }
}
@media screen and (max-width:954px){
    h1{
        font-size: 65px;
    }
    h2{
        font-size: 15px;
    }
}

The 980px part is the last that can be read, if I change it to 979px it stops reading it, as if it wasn't there. !important doesn't change anything. What can I do? Why is there a magical barrier of 980px?

Body:
I think you should realigned your media, it will be work for you may be.

I make a fiddle and it's working as you want with media query

working fiddle

@media screen and (max-width:954px) {
  h1 {
    font-size: 65px;
  }
  h2 {
    font-size: 15px;
  }
}

@media screen and (max-width:1029px) {
  h1 {
    font-size: 75px;
  }
  h2 {
    font-size: 25px;
  }
  @media screen and (max-width:980px) {
    h1 {
      font-size: 70px;
    }
    h2 {
      font-size: 20px;
    }
  }
}


问:
How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?
I need to change the group box text to a specific color without changing the color of what is inside the group box.

The following code sets the ForeColor of the GroupBox to pink but this settings cascades to all the child controls as well:

```<code>groupbox.ForeColor = Color.Pink
</code>```

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

答:
```<code>form_load()
{
    ...
    foreach (Control ctl in groupbox.Controls)
    {
        // load color value from parent and explicitly set it to control level
        ctl.ForeColor = ctl.ForeColor;
    }
    ...
}

some_click()
{
    groupbox.ForeColor = Color.Pink;
}

someother_click()
{
    groupbox.ForeColor = Color.Green;
}
</code>```

Color is not set for childcontrol until it done explicitly, and when childcontrol color requested it taken from the parent. Changing parent's color will refresh all it's content and childcontrol will take color from the parent.

If you set (explicitly) child color then child will not "asking" parent.

Child color can be set in designer too, but if color is the same as parent's color, designer will reduce this setting. Code in load event force child to have own color.

OwnerDisplayName: Dhanapal

Body:
I need to change the group box text to a specific color without changing the color of what is inside the group box.

The following code sets the ForeColor of the GroupBox to pink but this settings cascades to all the child controls as well:

groupbox.ForeColor = Color.Pink

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

LastEditorDisplayName: Andrew Hare

Body:
form_load()
{
    ...
    foreach (Control ctl in groupbox.Controls)
    {
        // load color value from parent and explicitly set it to control level
        ctl.ForeColor = ctl.ForeColor;
    }
    ...
}

some_click()
{
    groupbox.ForeColor = Color.Pink;
}

someother_click()
{
    groupbox.ForeColor = Color.Green;
}

Color is not set for childcontrol until it done explicitly, and when childcontrol color requested it taken from the parent. Changing parent's color will refresh all it's content and childcontrol will take color from the parent.

If you set (explicitly) child color then child will not "asking" parent.

Child color can be set in designer too, but if color is the same as parent's color, designer will reduce this setting. Code in load event force child to have own color.


问:
Can't resolve module (not found) in React.js
I can't believe that I'm asking an obvious question, but I still get the error in console log.

Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.

I want to render Header in root

```<code>import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (
      <Header/>
    );
  }
}

export default App;
</code>```

This is the Header component

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'

class Header extends Component {
    render() {
        return {
            <div>
             <div id="particles-js"></div>
             <navBar/>
             <Title/>
          </div>
        };
    }
}

ReactDOM.render(<Header/>, document.getElementById('header'));
</code>```

I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder "header" contains "header.js").

Yet, React still throws this error:

Failed to compile

./src/App.js
Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

npm test says the same thing.

答:
The way we usually use import is based on relative path.

. and .. are similar to how we use to navigate in terminal like cd .. to go out of directory and mv ~/file . to move a file to current directory.

```<code>my-app/
  node_modules/
  package.json
  src/
    containers/card.js
    components/header.js
    App.js
    index.js
</code>```

In your case, App.js is in src/ directory while header.js is in src/components. To import you would do import Header from './components/header'. This roughly translate to in my current directory, find the components folder that contain a header file.

Now, if from header.js, you need to import something from card, you would do this. import Card from '../containers/card'. This translate to, move out of my current directory, look for a folder name containers that have a card file.

As for import React, { Component } from 'react', this does not start with a ./ or ../ or / therefore node will start looking for the module in the node_modules in a specific order till react is found. For a more detail understanding, it can be read here.

ContentLicense: CC BY-SA 4.0

Body:
I can't believe that I'm asking an obvious question, but I still get the error in console log.

Console says that it can't find the module in the directory, but I've checked at least 10 times for typos. Anyways, here's the component code.

I want to render Header in root

import React, { Component } from 'react'
import Header from './src/components/header/header'
import logo from './logo.svg'
import './App.css'

class App extends Component {
  render() {
    return (

    );
  }
}

export default App;

This is the Header component

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import navBar from './src/components/header/navBar'
import './src/css/header.css'

class Header extends Component {
    render() {
        return {

             <navBar/>
             <Title/>

        };
    }
}

ReactDOM.render(, document.getElementById('header'));

I've checked at least 10 times that the module is at this location ./src/components/header/header, and it is (folder "header" contains "header.js").

Yet, React still throws this error:

Failed to compile

./src/App.js
Module not found: Can't resolve './src/components/header/header' in '/home/wiseman/Desktop/React_Components/github-portfolio/src'

npm test says the same thing.

Body:
The way we usually use import is based on relative path.

. and .. are similar to how we use to navigate in terminal like cd .. to go out of directory and mv ~/file . to move a file to current directory.

my-app/
  node_modules/
  package.json
  src/
    containers/card.js
    components/header.js
    App.js
    index.js

In your case, App.js is in src/ directory while header.js is in src/components. To import you would do import Header from './components/header'. This roughly translate to in my current directory, find the components folder that contain a header file.

Now, if from header.js, you need to import something from card, you would do this. import Card from '../containers/card'. This translate to, move out of my current directory, look for a folder name containers that have a card file.

As for import React, { Component } from 'react', this does not start with a ./ or ../ or / therefore node will start looking for the module in the node_modules in a specific order till react is found. For a more detail understanding, it can be read here.


问:
How to combine index arrays and slices in numpy
I have a problem with a combination of index arrays and slices. I have an image (A) and a vector with positions/indexes (pos). Now, I want to select  slices (here 3x) from A at different positions. Instead of looping over the positions array, I tried to use the indexer functions (o1), but I does not work.
Finally, all slices should be in one array (o2).
Can you help me with this problem ?

```<code>A = np.array([[0,0,0,0,0,0,3,3],
             [0,0,0,0,0,0,3,3],
             [0,0,0,1,1,0,0,0],
             [0,0,0,1,1,0,0,0],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,0,0],
             [0,0,0,0,0,0,0,0]])

# positions to select
# EDIT:
# pos = np.array([[2,6,7],
#                 [3,4,0]])
pos = np.array([[2,4,0],
                [3,6,6]])

# array with all selections
o1 = np.zeros((3,2,2)).astype(np.int)
# EDIT:
#o1 = A[pos[0]:pos[0]+1,pos[1]:pos[1]+1] ## this gives just one of the values in one area
o1 = A[pos[0]:pos[0] + 2,pos[1]:pos[1] + 2]
print(o1.shape)
print(o1)

# model result
o2 = np.array([[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]]])
print(o2.shape)
print(o2)
</code>```

Another example: With the following line I get the area with the ones. Starting from the position [2,3] choose the next two rows and cols:

```<code>print( A[pos[0,0] : pos[0,0] + 2 , pos[1,0] : pos[1,0] + 2]  )
</code>```

Isn't it possible to extend this to several position pairs (over the whole array pos[]) ?

Body:
I have a problem with a combination of index arrays and slices. I have an image (A) and a vector with positions/indexes (pos). Now, I want to select  slices (here 3x) from A at different positions. Instead of looping over the positions array, I tried to use the indexer functions (o1), but I does not work.
Finally, all slices should be in one array (o2).
Can you help me with this problem ?

A = np.array([[0,0,0,0,0,0,3,3],
             [0,0,0,0,0,0,3,3],
             [0,0,0,1,1,0,0,0],
             [0,0,0,1,1,0,0,0],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,2,2],
             [0,0,0,0,0,0,0,0],
             [0,0,0,0,0,0,0,0]])

# positions to select
# EDIT:
# pos = np.array([[2,6,7],
#                 [3,4,0]])
pos = np.array([[2,4,0],
                [3,6,6]])

# array with all selections
o1 = np.zeros((3,2,2)).astype(np.int)
# EDIT:
#o1 = A[pos[0]:pos[0]+1,pos[1]:pos[1]+1] ## this gives just one of the values in one area
o1 = A[pos[0]:pos[0] + 2,pos[1]:pos[1] + 2]
print(o1.shape)
print(o1)

# model result
o2 = np.array([[[1,1],[1,1]],[[2,2],[2,2]],[[3,3],[3,3]]])
print(o2.shape)
print(o2)

Another example: With the following line I get the area with the ones. Starting from the position [2,3] choose the next two rows and cols:

print( A[pos[0,0] : pos[0,0] + 2 , pos[1,0] : pos[1,0] + 2]  )

Isn't it possible to extend this to several position pairs (over the whole array pos[]) ?

Body:
You could use scikit's sliding window utility to extract such windows given the start indices from pos in a pretty straight forward way -

from skimage.util.shape import view_as_windows

out = view_as_windows(A, (2,2))[pos[0], pos[1]]

Sample run -

In [225]: A
Out[225]:
array([[0, 0, 0, 0, 0, 0, 3, 3],
       [0, 0, 0, 0, 0, 0, 3, 3],
       [0, 0, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 1, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 2, 2],
       [0, 0, 0, 0, 0, 0, 2, 2],
       [0, 0, 0, 0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0]])

In [226]: pos = np.array([[2,4,0],[3,6,6]])

In [227]: from skimage.util.shape import view_as_windows

In [228]: view_as_windows(A, (2,2))[pos[0], pos[1]]
Out[228]:
array([[[1, 1],
        [1, 1]],

       [[2, 2],
        [2, 2]],

       [[3, 3],
        [3, 3]]])


问:
MouseListener across several panels?
My user story is the following:

In order to upgrade a tower, the player has to drag a gun from the shop and drop it on the tower.

In practice, the GameView contains both the BattlefieldCanvas and the ShopView. Besides, the ShopView contains a GunSelector for each buyable gun. All those guys are sub-classes of JPanel.

I'm currently using a MousListener to handle several actions performed on the BattlefieldCanvas; I thought I could use the same stuff to handle a mouse trip from one of the GunSelector to the BattlefieldCanvas ( = across several panels ), so I tried to add the same MousListener to the gun selectors and the battlefield.

Problem: doesn't work. The getSource() method of the event object returns a reference to the gun selector while the mouse is actually released on the battlefield.

PS: Unlike gun selectors, towers are not swing components but images drawn by the paintComponent method.

答:
1) To answer to your original question as to why source is still the component mouse was clicked on. You just need to read the JavaDoc:

public Object getSource()

The object on which the Event initially occurred.

Returns:
      The object on which the Event initially occurred.

2) Now, how can we get the actual component that mouse is released on. You can try this approach:

```<code>@Override
public void mouseReleased(MouseEvent e) {
    Component theCOmponentMouseIsReleasedOn = frame.findComponentAt( e.getLocationOnScreen() );
}
</code>```

You don't need to always call findComponentAt on frame, you can call on the container that contains your BattlefieldCanvas.

Title: MouseListener across several panels?

Body:
1) To answer to your original question as to why source is still the component mouse was clicked on. You just need to read the JavaDoc:

public Object getSource()

The object on which the Event initially occurred.

Returns:
      The object on which the Event initially occurred.

2) Now, how can we get the actual component that mouse is released on. You can try this approach:

@Override
public void mouseReleased(MouseEvent e) {
    Component theCOmponentMouseIsReleasedOn = frame.findComponentAt( e.getLocationOnScreen() );
}

You don't need to always call findComponentAt on frame, you can call on the container that contains your BattlefieldCanvas.


问:
What is the correct vba to unfilter all columns in a table in excel and keep the filters in the column?
I have a table full of data that I have a drop down list that when you select the drop down item it filters the column in a table.

The problem I have is I want to have a simple reset button to unfilter the column. It's as simple as that. I don't want the filters to disappear though.

I have tried a boat load of solutions

For reference I used another submission to this site which did not work I got a "400" error message
VBA Unfilter range

```<code>Worksheets("Sheet1").ShowAllData
</code>```

Another solution I tried

```<code>With ActiveSheet
    .Cells.EntireColumn.Hidden = True
    .Cells.EntireRow.Hidden = True
    .AutoFilterMode = True
End With
</code>```

There has to be something super simple I'm not accouting for here.

答:
I was able to figure it out. I'm not sure of the exact science behind it but the range of the table has to be selected before anything. </p>

```<code>    Sub Unfilter()
'Unfilter all table columns
     ActiveSheet.Range("R15:BH1072").Select
        If ActiveSheet.FilterMode = True Then
            ActiveSheet.ShowAllData
        End If
End Sub
</code>```

Body:
I have a table full of data that I have a drop down list that when you select the drop down item it filters the column in a table.

The problem I have is I want to have a simple reset button to unfilter the column. It's as simple as that. I don't want the filters to disappear though.

I have tried a boat load of solutions

For reference I used another submission to this site which did not work I got a "400" error message
VBA Unfilter range

Worksheets("Sheet1").ShowAllData

Another solution I tried

With ActiveSheet
    .Cells.EntireColumn.Hidden = True
    .Cells.EntireRow.Hidden = True
    .AutoFilterMode = True
End With

There has to be something super simple I'm not accouting for here.

Body:
I was able to figure it out. I'm not sure of the exact science behind it but the range of the table has to be selected before anything.

    Sub Unfilter()
'Unfilter all table columns
     ActiveSheet.Range("R15:BH1072").Select
        If ActiveSheet.FilterMode = True Then
            ActiveSheet.ShowAllData
        End If
End Sub


问:
Liferay: how to prevent landing pages (login and logout) from being shown in the menu?
I'm trying to find a clean way so that the login and logout pages for my liferay portal aren't shown in my menu. For the login page I guess I could move the user to the private pages section but I have no clue how I can make the logout landing page not visible. And preferably the logout page would only be navigable to when you're effectively logged out so users can't accidentally go to it when they've got the url cached in their browser.

Any input would be appreciated.

答:
Regarding hiding the landing pages: Just create them and check "hidden" in "Manage Page" for that page. This will make the page accessible according to the permissions, but hide it in the navigation - e.g. if you know the page's name, you can go there - just as you requested.

If you display the currently logged in user on the logout landing page (e.g. through the "Sign In" portlet, you don't need to display a message like "you've been logged out", but display the current state of the user's session.

Of course you're free to not use the Sign-In opportunity on that page, in this case you'll have to display the current session state in a different portlet. It could be as simple as a templated WebContent portlet, accessing the currently logged in user.

Edit: If you set default.logout.page.path=/web/guest/logout and auth.forward.by.last.path=true but you're still not redirected on logout, chances are that changes made through the UI override your portal-ext.properties. If you've edited "Settings" in ControlPanel, this is most likely the case. You can set these values there, on the first page in settings.

As noted in your comment: You cannot make the first page hidden. This shouldn't be a problem: Just make any other page hidden. Even if you don't have more public content than this, you can have at least a public page stating that you need to login. Make this the first, so the logout page can be either a child page of this or a new toplevel page - but most importantly: It can be hidden.


问:
How did read an Ad delivery script the parameter?
I try to understand, how an Ad delivery script reads the given parameter:

```<code><ins data-revive-zoneid="4" data-revive-id="224492f55da08gg67b9eegh3006534r1"></ins>
<script async src="/www/delivery/asyncjs.php"></script>
</code>```

This code is from the Revive Ad server.
I try to look into the asyncjs.php file - but I can't find out, how the script reads the parameter like data-revive-zoneid and data-revive-id.

Can someone explain me, how that works? I need to try to develop an similar solution for an new project idea.

Thanks.

答:
Well asyncjs.php although named php, would output JavaScript, something that finds the element like:

```<code>var element = document.querySelector('ins[data-revive-id]');
console.log( element.getAttribute('data-revive-id') );
console.log( element.getAttribute('data-revive-zoneid') );
</code>```

Body:
I try to understand, how an Ad delivery script reads the given parameter:

This code is from the Revive Ad server.
I try to look into the asyncjs.php file - but I can't find out, how the script reads the parameter like data-revive-zoneid and data-revive-id.

Can someone explain me, how that works? I need to try to develop an similar solution for an new project idea.

Thanks.

Body:
Well asyncjs.php although named php, would output JavaScript, something that finds the element like:

var element = document.querySelector('ins[data-revive-id]');
console.log( element.getAttribute('data-revive-id') );
console.log( element.getAttribute('data-revive-zoneid') );


问:
Storing an integer array in a string variable using shell scripting
I have been trying to store an integer array in a variable as a string using Unix  shell scripting.

e.g.:

```<code>int array[2]={0,1,2}
</code>```

as

```<code>str="123"
</code>```

How may I accomplish this?

答:
Try with the following and at the end str will store the entire array as string:</p>

```<code>Arr=(1,2,3)
$ echo ${Arr}
1,2,3

str=`echo "${Arr//,}"`
$ echo $str
123
</code>```

Body:
I have been trying to store an integer array in a variable as a string using Unix  shell scripting.

e.g.:

int array[2]={0,1,2}

as

str="123"

How may I accomplish this?

Body:
Try with the following and at the end str will store the entire array as string:

Arr=(1,2,3)
$ echo ${Arr}
1,2,3

str=`echo "${Arr//,}"`
$ echo $str
123


问:
How can I get information from a select with angularjs and ionic1?
How can I get information from a select with angularjs and ionic1?

I'm trying to get the information from a JSON and put in the "select", until that part I got to do. But when I select the information from this "select" and try to get the id and the name that is in the "select", it is not showing.

My html -> igreja.html

```<code><ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">
      <div class="list list-inset">
        <ion-item class="item-input item-select--full">
          <div class="input-label">
            Selecione a sua igreja
          </div>
          <select ng-model="login" ng-options="y.Nome for (x,y) in igrejaEscolhida">
          </select>
          <h1> test: {{login.Nome}}</h1>
          <h1> id: {{login.Id}} </h1>
        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>
      </div>
    </form>
    </ion-content>
</ion-view>
</code>```

My routes.js

```<code>.state('app.igrejas', {
    url: '/igrejas',
    views: {
      'menuContent': {
        templateUrl: 'templates/igrejas.html',
        controller: 'igrejasController'
      }
    }
  })
</code>```

My controller.js

```<code>.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

    var dadosDoLogin = {
      params : {
        nome: $rootScope.login.nome
      }
    }

    $scope.selectUpdated = function(optionSelected) {

      console.log('Updated');
      console.log(optionSelected);

    };

    console.log($scope.selectUpdated);

    $scope.loginF.Nome;
    $scope.loginF.Id;

    console.log($scope.loginF.Nome);
    console.log($scope.loginF.Id);

     $rootScope.teste = $rootScope.login.nome;
     $scope.nomeIgreja = $rootScope.login.nome;
     $scope.idIgreja = $rootScope.login.Id;

     $rootScope.login.Id;

      console.log($scope.nomeIgreja);
      console.log($scope.idIgreja);

  };
})
</code>```

Could someone help me or show me what I'm doing wrong in the "select"?

答:
I changed my Igrejas.html and controller.js

Igrejas.html

```<code><ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">
      <div class="list list-inset">
        <ion-item class="item-input item-select--full">
          <div class="input-label">
            Selecione a sua igreja
          </div>
          <select ng-model="login.nome">
                  <option ng-repeat="igrejaEscolhidas in igrejaEscolhida">
                   {{ igrejaEscolhidas.Nome }}
                   {{ igrejaEscolhidas.Id }}
                  </option>
          </select>
        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>
      </div>
    </form>
    </ion-content>
</ion-view>
</code>```

My controller.js

```<code>.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

     $rootScope.teste = $rootScope.login.nome;

    console.log($rootScope.teste);

  };
})
</code>```

When I tested this way I managed to get the id and name, but they are together like this in this print, I need to get them separated, how do they separate them in angularjs?

My print :

http://prntscr.com/fhg4py

Or someone knows how I can get the id and separate name, being that I have this id and that name will come from the same select? I got them together.

Body:
How can I get information from a select with angularjs and ionic1?

I'm trying to get the information from a JSON and put in the "select", until that part I got to do. But when I select the information from this "select" and try to get the id and the name that is in the "select", it is not showing.

My html -> igreja.html

<ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">

        <ion-item class="item-input item-select--full">

            Selecione a sua igreja

          <select ng-model="login" ng-options="y.Nome for (x,y) in igrejaEscolhida">
          </select>

 test: {{login.Nome}}

 id: {{login.Id}}

        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>

    </form>
    </ion-content>
</ion-view>

My routes.js

.state('app.igrejas', {
    url: '/igrejas',
    views: {
      'menuContent': {
        templateUrl: 'templates/igrejas.html',
        controller: 'igrejasController'
      }
    }
  })

My controller.js

.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

    var dadosDoLogin = {
      params : {
        nome: $rootScope.login.nome
      }
    }

    $scope.selectUpdated = function(optionSelected) {

      console.log('Updated');
      console.log(optionSelected);

    };

    console.log($scope.selectUpdated);

    $scope.loginF.Nome;
    $scope.loginF.Id;

    console.log($scope.loginF.Nome);
    console.log($scope.loginF.Id);

     $rootScope.teste = $rootScope.login.nome;
     $scope.nomeIgreja = $rootScope.login.nome;
     $scope.idIgreja = $rootScope.login.Id;

     $rootScope.login.Id;

      console.log($scope.nomeIgreja);
      console.log($scope.idIgreja);

  };
})

Could someone help me or show me what I'm doing wrong in the "select"?

Body:
I changed my Igrejas.html and controller.js

Igrejas.html

<ion-view view-title="Igrejas">
    <ion-nav-buttons side="left">
            <button class="button button-icon button-clear ion-navicon" menu-toggle="left">
            </button>
    </ion-nav-buttons>
    <ion-content>
     <form ng-submit="realizarLogin()">
      <div class="list list-inset">
        <ion-item class="item-input item-select--full">
          <div class="input-label">
            Selecione a sua igreja
          </div>
          <select ng-model="login.nome">
                  <option ng-repeat="igrejaEscolhidas in igrejaEscolhida">
                   {{ igrejaEscolhidas.Nome }}
                   {{ igrejaEscolhidas.Id }}
                  </option>
          </select>
        </ion-item>

        <button class="button button-block button-positive" type="submit">Entrar</button>
      </div>
    </form>
    </ion-content>
</ion-view>

My controller.js

.controller('igrejasController', function($scope, $ionicModal, $timeout, $stateParams, $ionicPopup, $state, $rootScope, $http, $sce) {

  $http.get(linkIgrejas).then(function(data){

    $scope.igrejaEscolhida = data.data;

    console.log($scope.igrejaEscolhida);

    $scope.igrejaEscolhida.forEach(function(element, index, array){
      element.Id = element.Id;
      element.Nome = element.Nome;
      console.log(element.Id);
      console.log(element.Nome);
    })

  })

  $rootScope.login = {};

  $scope.realizarLogin = function() {

     $rootScope.teste = $rootScope.login.nome;

    console.log($rootScope.teste);

  };
})

When I tested this way I managed to get the id and name, but they are together like this in this print, I need to get them separated, how do they separate them in angularjs?

My print :

http://prntscr.com/fhg4py

Or someone knows how I can get the id and separate name, being that I have this id and that name will come from the same select? I got them together.


问:
Why is component function not being called when button is clicked
Any idea why console.log('hey'); is not logged in the browser console when I click the button?

I'm trying to show/hide the sub-component if <button (click)="hey">Click me!</button> is clicked.

app.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  public flag = false;
  public hey() {
    console.log('hey');
    this.flag = true;
  }
}
</code>```

app.component.html

```<code><button (click)="hey">Click me!</button>
<div *ngIf="flag">
  <sub-component></sub-component>
</div>
</code>```

index.html

```<code><body>
  <my-app>Loading...</my-app>
</body>
</code>```

答:
You need to call a method.

```<code><button (click)="logThis('hey')">Click me!</button>
<div *ngIf="flag">
  <sub-component></sub-component>
</div>
</code>```

And then in your component just:

```<code>logThis(msg) {
  console.log(msg);
}
</code>```

The thing is that (click) is the clicking event. And you have to tell him what to do when that event triggers. In this case, we are calling logThis().

Update:

I didn't see that you actually declared a hey() method and that you just forgot your ().

I thought you were trying to pass a string directly. My bad!

Anyways, this could be useful for others! :D

Body:
Any idea why console.log('hey'); is not logged in the browser console when I click the button?

I'm trying to show/hide the sub-component if <button (click)="hey">Click me!</button> is clicked.

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  public flag = false;
  public hey() {
    console.log('hey');
    this.flag = true;
  }
}

app.component.html

<button (click)="hey">Click me!</button>

index.html

  <my-app>Loading...</my-app>

Body:
You need to call a method.

<button (click)="logThis('hey')">Click me!</button>
<div *ngIf="flag">
  <sub-component></sub-component>
</div>

And then in your component just:

logThis(msg) {
  console.log(msg);
}

The thing is that (click) is the clicking event. And you have to tell him what to do when that event triggers. In this case, we are calling logThis().

Update:

I didn't see that you actually declared a hey() method and that you just forgot your ().

I thought you were trying to pass a string directly. My bad!

Anyways, this could be useful for others! :D


问:
Elasticsearch upsert based on query
Two years ago someone asked how to do upserts when you don't know a document's id. The (unaccepted) answer referenced the feature request
that resulted in the _update_by_query API.

However _update_by_query does not allow insertion if no hits exist, so it is not really an upsert, but just another way to do update.

Is there a way to do an upsert without an _id yet? I know that my query will always return one or zero results. Or am I forced to do multiple requests (and maintain the uniqueness myself)?

答:
This doesn't seem to be possible right now. _update provides an upsert attribute, but this doesn't work with _update_by_query unfortunately. The following just gives you an error around Unknown key for a START_OBJECT in [upsert].

```<code>POST website/doc/_update_by_query?conflicts=proceed
{
  "query": {
    "term": {
      "url": "http://foo.com"
    }
  },
  "script": {
    "inline": "ctx._source.views+=1",
    "lang": "painless"
  },
   "upsert": {
       "views": 1,
       "url": "http://foo.com"
   }
}
</code>```

Title: Elasticsearch upsert based on query

Body:
This doesn't seem to be possible right now. _update provides an upsert attribute, but this doesn't work with _update_by_query unfortunately. The following just gives you an error around Unknown key for a START_OBJECT in [upsert].

POST website/doc/_update_by_query?conflicts=proceed
{
  "query": {
    "term": {
      "url": "http://foo.com"
    }
  },
  "script": {
    "inline": "ctx._source.views+=1",
    "lang": "painless"
  },
   "upsert": {
       "views": 1,
       "url": "http://foo.com"
   }
}


问:
How to highlight row table using jQuery and cookie?
I'm using this code for highlighting multi select row in table when click on row in my page.

```<code>$(".tbl tr").click(function() {
    $(this).toggleClass("select_rw");
});
</code>```

It's Ok!
But I want to save multi selected row in cookie for highlighting row when I go to another page and back to my page.

答:
According to hasan proposal,

Here is a kind of implementation that should do the work

I assume you put ids on your  tags

```<code>$(".tbl tr").click(function(item, i) {

    // get the cookie value
    var selected = $.cookie("store_line");

    // check if is an array and declare it
    if(! Array.isArray(selected)){
      selected = [];
    }

    // push selected id tr
    selected.push($(this).attr('id'));

    // save cookie with new values
    $.cookie("store_line", selected);

    // toogle your class
    $(this).toggleClass("select_rw");
});

// when the page is load, read the cookie and activate row
var selected = $.cookie("store_line");
$.each(selected, function(id){
    $('#' + id).toggleClass("select_rw");
})
</code>```

Body:
I'm using this code for highlighting multi select row in table when click on row in my page.

$(".tbl tr").click(function() {
    $(this).toggleClass("select_rw");
});

It's Ok!
But I want to save multi selected row in cookie for highlighting row when I go to another page and back to my page.

Body:
According to hasan proposal,

Here is a kind of implementation that should do the work

I assume you put ids on your  tags

$(".tbl tr").click(function(item, i) {

    // get the cookie value
    var selected = $.cookie("store_line");

    // check if is an array and declare it
    if(! Array.isArray(selected)){
      selected = [];
    }

    // push selected id tr
    selected.push($(this).attr('id'));

    // save cookie with new values
    $.cookie("store_line", selected);

    // toogle your class
    $(this).toggleClass("select_rw");
});

// when the page is load, read the cookie and activate row
var selected = $.cookie("store_line");
$.each(selected, function(id){
    $('#' + id).toggleClass("select_rw");
})


问:
Gradle: Changing configuration of external dependency
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

```<code>compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")
</code>```

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

答:
See here where they use replacedBy to tell gradle that com.google.collections:google-collections was replaced by com.google.guava:guava. Gradle will now consider the two modules as a single module in dependency resolution and will never include both.

```<code>dependencies {
    modules {
        module("com.google.collections:google-collections") {
            replacedBy("com.google.guava:guava")
        }
    }
}
</code>```

Body:
We're in the situation where we update commons-collections from version 3 to version 4. As they've changed the group id to commons-collections4 we will end up having 2 versions of commons-collection in the classpath. The version 3 and version 4.
For our development the version 4 should be used. The version 3 will come in through external dependencies so if we have like:

compile ("org.hibernate:hibernate-entitymanager:3.5.6-Final")

the version 3, which will come in through hibernate-entitymanager, will also be available at compile time. So the developers could use it.

Is there a way to say "commons-collections 3 should now be considered as runtime dependency when it comes through hibernate-entitymanager"?

We're using Gradle 3.5.

Body:
See here where they use replacedBy to tell gradle that com.google.collections:google-collections was replaced by com.google.guava:guava. Gradle will now consider the two modules as a single module in dependency resolution and will never include both.

dependencies {
    modules {
        module("com.google.collections:google-collections") {
            replacedBy("com.google.guava:guava")
        }
    }
}


问:
Spring mvc: Best paractices for software architecture
I develop rest Web services using spring mvc.

I know that the application should contains 3 layers:

persistence layer: classes annotated with @Repository

service layer: classes annotated with @Service

controller layer: classes annotated with @Controller

For my case, Data are loaded first from a restful ws (a backend) then stored into database and after a laps time, my project reload it from the rest ws (backend) to refresh the data and use it to offer some services.

So the java  classes which call backend ws should be annotated with @Service ?
and then called directly from controller?
How to arrange the project architecture in this case?
Is it the same architecture as those using data from database ?

thanks

答:
From my understanding your database is some kind of cache for the webservice data right?

So I would implement some @Service bean(s) that is/are responsible to retrieving data from the WS, lets call it "WSAccessBean".

Now two approaches come to my mind:

Eager loading: Your Spring servlet will use scheduled-tasks to periodically call the WSAccessBean and store the retrieved data in the database. You controller beans will use @Repository beans as usual to access this data.

Lazy loading: You implement another @Service bean(s) that is a facade for the data access, lets call it "DataAccessBean". This one will use both: @Repository beans to check if up-to-date data is in our local database and if not it will use the WSAccessBean to first retrieve the data and then return it from the database to the caller.

edit after comment:

So if your data needs to be loaded on demand the following snippet would show the basic architecture using a "Book" POJO as example:

```<code>@Service
public class BookWebservice {
    // Load books from remote webservice
    List<Book> retrieveBooks();
}

@Repository
public class BookDAO {
    List<Book> getBooks();
    void storeBooks(List<Book> books);
    boolean uptodate();
}

@Service
public class BookService {

    @Autowired
    BookDAO bookDAO;

    @Autowired
    BookWebservice bookWebservice;

    // Checks if local data is up-to-date. If not load via Webservice and store in the local DB, then return content from DB
    List<Book> getBooks() {

        if (!bookDAO.uptodate()) {
            bookDAO.storeBooks(bookWebservice.retrieveBooks());
        }
        return bookDAO.getBooks();
    }
}

@Controller
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping("/books")
    public List<Book> books() {
        return bookService.getBooks();
    }
}
</code>```

Body:
From my understanding your database is some kind of cache for the webservice data right?

So I would implement some @Service bean(s) that is/are responsible to retrieving data from the WS, lets call it "WSAccessBean".

Now two approaches come to my mind:

Eager loading: Your Spring servlet will use scheduled-tasks to periodically call the WSAccessBean and store the retrieved data in the database. You controller beans will use @Repository beans as usual to access this data.

Lazy loading: You implement another @Service bean(s) that is a facade for the data access, lets call it "DataAccessBean". This one will use both: @Repository beans to check if up-to-date data is in our local database and if not it will use the WSAccessBean to first retrieve the data and then return it from the database to the caller.

edit after comment:

So if your data needs to be loaded on demand the following snippet would show the basic architecture using a "Book" POJO as example:

@Service
public class BookWebservice {
    // Load books from remote webservice
    List<Book> retrieveBooks();
}

@Repository
public class BookDAO {
    List<Book> getBooks();
    void storeBooks(List<Book> books);
    boolean uptodate();
}

@Service
public class BookService {

    @Autowired
    BookDAO bookDAO;

    @Autowired
    BookWebservice bookWebservice;

    // Checks if local data is up-to-date. If not load via Webservice and store in the local DB, then return content from DB
    List<Book> getBooks() {

        if (!bookDAO.uptodate()) {
            bookDAO.storeBooks(bookWebservice.retrieveBooks());
        }
        return bookDAO.getBooks();
    }
}

@Controller
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping("/books")
    public List<Book> books() {
        return bookService.getBooks();
    }
}


问:
Parse log file using grep or awk
I have a log file. Example of output looks like this:

...
10-MAY-95 14:16:21*(CONNECT_DATA=(SID=reltest)(CID=(PROGRAM=C:\ORAWIN\BIN\PLUS31.EXE) (HOST=WINDOWSPC)(USER=CCLOW))*(ADDRESS=(PROTOCOL=tcp)(HOST=144.25.23.246)(PORT=3366))*establish*reltest*0
...

Log parameters are entered in the appropriate component configuration files in the form:
log_parameter_component = value

So, goal is to parse the above output and display result only with key=value, key=value, etc:
log_parameter_component = value, log_parameter_component = value, etc.

The result should look as following after parsing:

...
SID=reltest, USER=CCLOW, HOST=144.25.23.246
...

How to solve this task?

答:
This should work in perl but I admit the second part could probably be avoided:

```<code>perl -p -e 's/.*?\(([^()]+?)=([^()]+?)\).*?/$1=$2,/g' myfile.log | perl -p -e 's/(.*),.*/$1/'
</code>```

Title: Parse log file using grep or awk

Body:
This should work in perl but I admit the second part could probably be avoided:

perl -p -e 's/.*?\(([^()]+?)=([^()]+?)\).*?/$1=$2,/g' myfile.log | perl -p -e 's/(.*),.*/$1/'


问:
sending an email in VBA code
I'm pretty basic with VBA & I found the below code for sending an email when a cell value has been exceeded. I am trying to alter the code so the email is sent when either a date is entered into a blank cell (so as to complete an action) or when a cells text goes from "Ongoing" to "Complete" following the population of a cell with a date. Any help would be much appreciated.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
        If Not Application.Intersect(Range("J1:J3000"), Target) Is Nothing Then
            If IsNumeric(Target.Value) And Target.Value > 1 Then
                Call Mail_small_Text_Outlook
            End If
        End If
    End If
End Sub
</code>```

答:
This is to give you a perspective how things work:

Suppose that date is in cell B2 and status is in cell C2.

Enter =IFERROR(IF(DAY(B2)<>0,"Completed","Ongoing"),"Invalid Date") to Cell C2  as shown below:

Enter a date (or anything) to Cell B2 and see how the status changes:

Now, insert the following code in your sheet module:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("B2"), Target) Is Nothing Then
        If Range("C2").Value = "Completed" Then
            Call Mail_small_Text_Outlook
        End If
    End If
End Sub
</code>```

When you enter a date to Cell B2 and have the value changed to "Completed" in Cell C2, it will call your sub.

EDIT:

If you would like to do this for a range of cell you can use the following:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("B2:B200"), Target) Is Nothing Then
        If Target.Offset(0, 1).Value = "Completed" Then
            Call Mail_small_Text_Outlook
        End If
    End If
End Sub
</code>```

Title: sending an email in VBA code

Body:
I'm pretty basic with VBA & I found the below code for sending an email when a cell value has been exceeded. I am trying to alter the code so the email is sent when either a date is entered into a blank cell (so as to complete an action) or when a cells text goes from "Ongoing" to "Complete" following the population of a cell with a date. Any help would be much appreciated.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
        If Not Application.Intersect(Range("J1:J3000"), Target) Is Nothing Then
            If IsNumeric(Target.Value) And Target.Value > 1 Then
                Call Mail_small_Text_Outlook
            End If
        End If
    End If
End Sub

Body:
This is to give you a perspective how things work:

Suppose that date is in cell B2 and status is in cell C2.

Enter =IFERROR(IF(DAY(B2)<>0,"Completed","Ongoing"),"Invalid Date") to Cell C2  as shown below:

Enter a date (or anything) to Cell B2 and see how the status changes:

Now, insert the following code in your sheet module:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("B2"), Target) Is Nothing Then
        If Range("C2").Value = "Completed" Then
            Call Mail_small_Text_Outlook
        End If
    End If
End Sub

When you enter a date to Cell B2 and have the value changed to "Completed" in Cell C2, it will call your sub.

EDIT:

If you would like to do this for a range of cell you can use the following:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If Not Application.Intersect(Range("B2:B200"), Target) Is Nothing Then
        If Target.Offset(0, 1).Value = "Completed" Then
            Call Mail_small_Text_Outlook
        End If
    End If
End Sub


问:
What is the most efficient way to find amicable numbers in python?
I've written code in Python to calculate sum of amicable numbers below 10000:

```<code>def amicable(a, b):
   total = 0
   result = 0
   for i in range(1, a):
      if a % i == 0:
        total += i
   for j in range(1, b):
      if b % j == 0:
        result += j
   if total == b and result == a:
        return True
   return False

sum_of_amicables = 0
for m in range (1, 10001):
    for n in range (1, 10001):
        if amicable(m, n) == True and m != n:
            sum_of_amicables = sum_of_amicables + m + n
</code>```

Code is running more than 20 minutes in Python 2.7.11. Is it ok? How can I improve it?

答:
Adding to the answer:

```<code>def sum_factors(self, n):
    s = 1
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            s += i
            s += n/i
    return s

def amicable_pair(self, number):
    result = 0
    for x in range(1,number+1):
        y = self.sum_factors(x)
        if self.sum_factors(y) == x and x != y:
            result += x
    return result
</code>```

No need for sets or arrays. Improvinging storage and clarity.

Body:
I've written code in Python to calculate sum of amicable numbers below 10000:

def amicable(a, b):
   total = 0
   result = 0
   for i in range(1, a):
      if a % i == 0:
        total += i
   for j in range(1, b):
      if b % j == 0:
        result += j
   if total == b and result == a:
        return True
   return False

sum_of_amicables = 0
for m in range (1, 10001):
    for n in range (1, 10001):
        if amicable(m, n) == True and m != n:
            sum_of_amicables = sum_of_amicables + m + n

Code is running more than 20 minutes in Python 2.7.11. Is it ok? How can I improve it?

Body:
Adding to the answer:

def sum_factors(self, n):
    s = 1
    for i in range(2, int(math.sqrt(n))+1):
        if n % i == 0:
            s += i
            s += n/i
    return s

def amicable_pair(self, number):
    result = 0
    for x in range(1,number+1):
        y = self.sum_factors(x)
        if self.sum_factors(y) == x and x != y:
            result += x
    return result

No need for sets or arrays. Improvinging storage and clarity.


问:
Using Microsoft Bot Framework, when I write on Messenger channel, how to push the result to a specific Slack channel ? (with Node)
Currently my users are using a Messenger channel.

Here is what it goes: my users type "Talk to a coach" in my bot, then they can write whatever they want, and then the result should be pushed to a specific private channel using Slack.

How can I achieve that ?

EDIT: The private channel is a list of users request that can be processed when coaches are available, so users don't have to be in a waiting list

答:
I achieved it using directly Slack API. I tried with .sourceEvent, and it nearly worked: the bot only talked to me in private on Slack, he didn't accept any channel ID / name (private or not).

Here is how I made it to work (a bit factorized):
It starts with the user wanting to change anything in his planning (which has to be done manually by a coach), so it starts in dialog "/select_modify_planning"

app.js:

```<code>...

bot.dialog("/select_modify_planning", require("./dialogs/modifyPlanning").select);
bot.dialog("/ask_for_request", require("./dialogs/modifyPlanning).askForRequest);

...
</code>```

modifyPlanning.js:

```<code>const builder = require('botbuilder');
const rp = require('request-promise');

...

exports.select = [
 (session, args) => {
   session.sendTyping();
   builder.Prompts.choice(session, "What do you want to declare ? :)", "Internal hours|Update rendezvous");
 },
 (session, results) => {
  if (results.response) {
    switch (results.response.entity) {
      case "Internal hours":
        session.beginDialog("/ask_for_request");
        break;
      case "Update rendezvous":
        ...
    }
  }
]

...

exports.askForRequest = [
 (session, args) => {
   session.sendTyping();
   builder.Prompts.text(session, "Type your demand please:");
 },
 async (session, results) => {
   try {
     if (results.response)
       await sendRequestToSlack(results.response);
       session.endDialog("Your demand has been sent successfully, thank you ;)");
   }
   .catch(err) {
     console.error(err);
     session.endDialog("There was a problem while sending your demand to a coach, sorry :(");
   }
 }
]

...

const sendRequestToSlack = (textToSend) => {
  var options = {
    uri: "https://slack.com/api/chat.postMessage",
    form: {
      "token": "xoxb-XXXXXX-XXXXXX", // Your bot slack token
      "channel": "XXXXXXXXX", // Your channel id (or name)
      "text": textToSend
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }
  return rp.post(options);
}

...
</code>```

And here it is.

If you want to know your channels ID (using name is a bad practice because they can be changed), you can use this method: https://api.slack.com/methods/channels.list for public channels, or this one: https://api.slack.com/methods/groups.list for private channels.

If it's for private channels, you have to add good permissions in your bot scope settings ( groups.xxx ), and reinstall it (you have a green button dedicated to in bots settings)

Hope everything is clear :)

Body:
I achieved it using directly Slack API. I tried with .sourceEvent, and it nearly worked: the bot only talked to me in private on Slack, he didn't accept any channel ID / name (private or not).

Here is how I made it to work (a bit factorized):
It starts with the user wanting to change anything in his planning (which has to be done manually by a coach), so it starts in dialog "/select_modify_planning"

app.js:

...

bot.dialog("/select_modify_planning", require("./dialogs/modifyPlanning").select);
bot.dialog("/ask_for_request", require("./dialogs/modifyPlanning).askForRequest);

...

modifyPlanning.js:

const builder = require('botbuilder');
const rp = require('request-promise');

...

exports.select = [
 (session, args) => {
   session.sendTyping();
   builder.Prompts.choice(session, "What do you want to declare ? :)", "Internal hours|Update rendezvous");
 },
 (session, results) => {
  if (results.response) {
    switch (results.response.entity) {
      case "Internal hours":
        session.beginDialog("/ask_for_request");
        break;
      case "Update rendezvous":
        ...
    }
  }
]

...

exports.askForRequest = [
 (session, args) => {
   session.sendTyping();
   builder.Prompts.text(session, "Type your demand please:");
 },
 async (session, results) => {
   try {
     if (results.response)
       await sendRequestToSlack(results.response);
       session.endDialog("Your demand has been sent successfully, thank you ;)");
   }
   .catch(err) {
     console.error(err);
     session.endDialog("There was a problem while sending your demand to a coach, sorry :(");
   }
 }
]

...

const sendRequestToSlack = (textToSend) => {
  var options = {
    uri: "https://slack.com/api/chat.postMessage",
    form: {
      "token": "xoxb-XXXXXX-XXXXXX", // Your bot slack token
      "channel": "XXXXXXXXX", // Your channel id (or name)
      "text": textToSend
    },
    headers: {
      'content-type': 'application/x-www-form-urlencoded'
    }
  }
  return rp.post(options);
}

...

And here it is.

If you want to know your channels ID (using name is a bad practice because they can be changed), you can use this method: https://api.slack.com/methods/channels.list for public channels, or this one: https://api.slack.com/methods/groups.list for private channels.

If it's for private channels, you have to add good permissions in your bot scope settings ( groups.xxx ), and reinstall it (you have a green button dedicated to in bots settings)

Hope everything is clear :)


问:
C# - Selenium - Retry Attribute not working with Selenium timeout
I have the following custom RetryAttribute taken from this post: NUnit retry dynamic attribute. It works fine but when I get a timeout error in Selenium it doesn´t work.

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            wait.Until(ExpectedConditions.ElementToBeClickable(element));
</code>```

Retry custom attribute:

```<code>/// <summary>
/// RetryDynamicAttribute may be applied to test case in order
/// to run it multiple times based on app setting.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryDynamicAttribute : RetryAttribute {
    private const int DEFAULT_TRIES = 1;
    static Lazy<int> numberOfRetries = new Lazy<int>(() => {
        int count = 0;
        return int.TryParse(ConfigurationManager.AppSettings["retryTest"], out count) ? count : DEFAULT_TRIES;
    });

    public RetryDynamicAttribute() :
        base(numberOfRetries.Value) {
    }
}
</code>```

And then apply the custom attribute.

```<code>[Test]
[RetryDynamic]
public void Test() {
    //....
}
</code>```

How can this be solved?

答:
Another solution would be to implement your own RetryAttribute to catch the WebDriver exception. This way you won't have to alter the test:

```<code>[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryAttributeEx : PropertyAttribute, IWrapSetUpTearDown
{
    private int _count;

    public RetryAttributeEx(int count) : base(count) {
        _count = count;
    }

    public TestCommand Wrap(TestCommand command) {
        return new RetryCommand(command, _count);
    }

    public class RetryCommand : DelegatingTestCommand {

        private int _retryCount;

        public RetryCommand(TestCommand innerCommand, int retryCount)
            : base(innerCommand) {
            _retryCount = retryCount;
        }

        public override TestResult Execute(TestExecutionContext context) {

            for (int count = _retryCount; count-- > 0; ) {

                try {
                    context.CurrentResult = innerCommand.Execute(context);
                }
                catch (WebDriverTimeoutException ex) {
                    if (count == 0)
                      throw;

                    continue;
                }

                if (context.CurrentResult.ResultState.Status != ResultState.Failure.Status)
                    break;

                if (count > 0)
                    context.CurrentResult = context.CurrentTest.MakeTestResult();
            }

            return context.CurrentResult;
        }
    }

}
</code>```

Body:
I have the following custom RetryAttribute taken from this post: NUnit retry dynamic attribute. It works fine but when I get a timeout error in Selenium it doesn´t work.

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
            wait.Until(ExpectedConditions.ElementToBeClickable(element));

Retry custom attribute:

///
/// RetryDynamicAttribute may be applied to test case in order
/// to run it multiple times based on app setting.
///
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryDynamicAttribute : RetryAttribute {
    private const int DEFAULT_TRIES = 1;
    static Lazy<int> numberOfRetries = new Lazy<int>(() => {
        int count = 0;
        return int.TryParse(ConfigurationManager.AppSettings["retryTest"], out count) ? count : DEFAULT_TRIES;
    });

    public RetryDynamicAttribute() :
        base(numberOfRetries.Value) {
    }
}

And then apply the custom attribute.

[Test]
[RetryDynamic]
public void Test() {
    //....
}

How can this be solved?

Body:
Another solution would be to implement your own RetryAttribute to catch the WebDriver exception. This way you won't have to alter the test:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class RetryAttributeEx : PropertyAttribute, IWrapSetUpTearDown
{
    private int _count;

    public RetryAttributeEx(int count) : base(count) {
        _count = count;
    }

    public TestCommand Wrap(TestCommand command) {
        return new RetryCommand(command, _count);
    }

    public class RetryCommand : DelegatingTestCommand {

        private int _retryCount;

        public RetryCommand(TestCommand innerCommand, int retryCount)
            : base(innerCommand) {
            _retryCount = retryCount;
        }

        public override TestResult Execute(TestExecutionContext context) {

            for (int count = _retryCount; count-- > 0; ) {

                try {
                    context.CurrentResult = innerCommand.Execute(context);
                }
                catch (WebDriverTimeoutException ex) {
                    if (count == 0)
                      throw;

                    continue;
                }

                if (context.CurrentResult.ResultState.Status != ResultState.Failure.Status)
                    break;

                if (count > 0)
                    context.CurrentResult = context.CurrentTest.MakeTestResult();
            }

            return context.CurrentResult;
        }
    }

}


问:
executing method on remote machine with sshpass shell script
How to execute a method on remote machine connecting with sshpass
Following is the code:

```<code>#!/bin/bash
checkfunctioncall() {
cd "/home/user"
mkdir "remotecalltest"

}

sshpass -p "$serverpwd" ssh "$serveruser"@"$serverip" checkfunctioncall
</code>```

but I am getting below error:

bash: checkfunctioncall: command not found

Please suggest

I am specifically looking for solution with sshpass, as I need to login to remote server with a password

答:
I think this will remove the above error.</p>

```<code>sshpass -p "$serverpwd" ssh "$serveruser"@"$serverip" << EOSSH
checkfunctioncall(){
cd "/home/user"
mkdir "remotecalltest"
}
checkfunctioncall
EOSSH
</code>```

Body:
How to execute a method on remote machine connecting with sshpass
Following is the code:

#!/bin/bash
checkfunctioncall() {
cd "/home/user"
mkdir "remotecalltest"

}

sshpass -p "$serverpwd" ssh "$serveruser"@"$serverip" checkfunctioncall

but I am getting below error:

bash: checkfunctioncall: command not found

Please suggest

I am specifically looking for solution with sshpass, as I need to login to remote server with a password

Body:
I think this will remove the above error.

sshpass -p "$serverpwd" ssh "$serveruser"@"$serverip" << EOSSH
checkfunctioncall(){
cd "/home/user"
mkdir "remotecalltest"
}
checkfunctioncall
EOSSH


问:
Auto incrementing ID as primary key on all tables
I am designing a database for an e-Commerce website which uses MySQL. I have made the list of tables necessary and all the fields necessary for the table. I have a total of 9 tables.

What I have done is include an auto incrementing ID as primary key on all the tables.

All my tables except 2 are normalized to 3NF. Two tables 'users' and 'outlets' are not normalized to 2NF.

Along the way I realized that normalization is cumbersome when using auto incrementing ID as a primary key. As normalization is not strictly required, I want to know if there are any downsides of using auto incrementing ID as primary key on all the tables?

答:
Your question is tagged for MySQL, so I'll point out that MySQL's InnoDB storage engine uses the primary key as its clustered index for all tables.

It's more efficient to query by the clustered index when possible. But if you have an arbitrary rule that all tables must use an auto-increment primary key even if there is another column or set of columns that could serve as the primary key, and you always run queries searching by those columns and not by the auto-increment column, then you'll never gain the advantage of querying by the clustered index.