问:
Aggregating values in groups of irregular length using a stop values
I'm trying to create groups of values using keywords that have been manually entered. for example if I have a rollcall sheet with values that can be produced with the following code

```<code>df <- data.frame(name = c("Fred", "Victoria", "Jim", "Sally", "Ted", "Pamela", "end", "Victoria", "Fred", "Sally", "end", "Sally", "Pamela"),
                 sex = c("man", "woman", "man", "woman", "man", "woman", "neither", "woman", "man", "woman", "neither", "woman", "woman"))
</code>```

Is it possible to group these values into days such that I have three days, arranged so that one could ask the question, "On what day(s), was Sally present with a man" ?

答:
You can create day with cumsum:

```<code>df$day <- cumsum(df$name == 'end')
df <- df[df$day != 'end', ]
unique(df$day[df$sex == 'man' & df$day %in% df$day[df$name == 'Sally']])
# [1] 0 1
</code>```

So,  "On first two day(s), Sally was present with a man".

edit: I mistook the question at first. The error has been fixed.

Body:
I'm trying to create groups of values using keywords that have been manually entered. for example if I have a rollcall sheet with values that can be produced with the following code

df <- data.frame(name = c("Fred", "Victoria", "Jim", "Sally", "Ted", "Pamela", "end", "Victoria", "Fred", "Sally", "end", "Sally", "Pamela"),
                 sex = c("man", "woman", "man", "woman", "man", "woman", "neither", "woman", "man", "woman", "neither", "woman", "woman"))

Is it possible to group these values into days such that I have three days, arranged so that one could ask the question, "On what day(s), was Sally present with a man" ?

Body:
You can create day with cumsum:

df$day <- cumsum(df$name == 'end')
df <- df[df$day != 'end', ]
unique(df$day[df$sex == 'man' & df$day %in% df$day[df$name == 'Sally']])
# [1] 0 1

So,  "On first two day(s), Sally was present with a man".

edit: I mistook the question at first. The error has been fixed.


来源: stackexchange

问:
Postgresql trigger to insert a new record in table1 after an insert/update in table2
I have this database and I need to answer the following question:

"You need to create a trigger along with the function that will be executed when the trigger is fired. Every time that a patient is examined and there is a diagnosis (if the inserted appointment.diagnosis in not null), the patient's medical folder will be updated."

This is what I have come up with:

CREATE OR REPLACE FUNCTION appointmentsFunction()
    RETURNS TRIGGER AS $appointmentsfunction$
    DECLARE
        appointment_patientamka BIGINT := new.patientamka;
        appointment_cure TEXT := new.cure;
        appointment_drug_id INT := drug_id;
        appointment_diagnosis TEXT := new.diagnosis;
        BEGIN
        IF appointment_diagnosis is NOT NULL THEN
                INSERT INTO public.medicalfolder (patient,cure,drug_id) VALUES (appointment_patientamka,appointment_cure, appointment_drug_id);
        END IF;
        RETURN NEW;
    END
$appointmentsfunction$
LANGUAGE plpgsql;

Which is the best practice/best way to do it?

PS. The patientamka serves as an ID for the patient. It could as well be patientID, but it's not, per my teacher's guidelines.

PS2.The medicalfolder table can include duplicate records for the same patient. So, i don't have to update the record with the patient's id (patientamka), I just need to insert a new one.

答:
This is more of a Code Review question since I assume the above works, but anyway:

appointmentsFunction()

Naming convention in PG is snake_case rather than camelCase. Also no need to append the word "function" to your function. Call it something that describes what it does.

```<code>DECLARE
    appointment_patientamka BIGINT := new.patientamka;
    appointment_cure TEXT := new.cure;
    appointment_drug_id INT := drug_id;
    appointment_diagnosis TEXT := new.diagnosis;
</code>```

I have two issues with this.

First you're going through the cost of assigning values to four variables (the cost is small but it's not free). Then you check if one of them is NULL, and if so you don't use those values - so you wasted the effort of reading and assigning all those variables.

The second thing is none of these variables are necessary because you can check if NEW.diagnosis is NULL, and if not, then INSERT the values (read directly from NEW) into medicalfolder.

Finally it would be nice to have BEGIN on the same indent as DECLARE and END.

ContentLicense: CC BY-SA 3.0

Body:
This is more of a Code Review question since I assume the above works, but anyway:

appointmentsFunction()

Naming convention in PG is snake_case rather than camelCase. Also no need to append the word "function" to your function. Call it something that describes what it does.

DECLARE
    appointment_patientamka BIGINT := new.patientamka;
    appointment_cure TEXT := new.cure;
    appointment_drug_id INT := drug_id;
    appointment_diagnosis TEXT := new.diagnosis;

I have two issues with this.

First you're going through the cost of assigning values to four variables (the cost is small but it's not free). Then you check if one of them is NULL, and if so you don't use those values - so you wasted the effort of reading and assigning all those variables.

The second thing is none of these variables are necessary because you can check if NEW.diagnosis is NULL, and if not, then INSERT the values (read directly from NEW) into medicalfolder.

Finally it would be nice to have BEGIN on the same indent as DECLARE and END.


问:
How to represent a value from an object as boolean
The following object  is being returned from a SQL call:

```<code>#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>
</code>```

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?

答:
If Health is a model you can do something like:

```<code>def diabetic?
  value.upcase == 'Y'
end
</code>```

in the model's file.

Another more generic approach with a different function name (see comments) is:

```<code>def value?
  value.upcase == 'Y'
end
</code>```

Body:
The following object  is being returned from a SQL call:

#<Health:0x007fc8533f2de8 @type=:diabetic, @value="N", @data_source=nil, @measured_at=nil>

The value could be 'Y' or 'N' and can be accessed as health.value.

How do I represent this value as a boolean?

Body:
If Health is a model you can do something like:

def diabetic?
  value.upcase == 'Y'
end

in the model's file.

Another more generic approach with a different function name (see comments) is:

def value?
  value.upcase == 'Y'
end


问:
Foreign key constraint exception in basic table design
I'm using Entity Framework Core and have a simple 5 table design, but get an error and can't figure out why. What am I missing?

Exception:

Introducing FOREIGN KEY constraint
  'FK_GraphicItems_GraphicUploadTemplateItems_GraphicUploadTemplateItemId'
  on table 'GraphicItems' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Base:

```<code>public abstract class Base
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; } = DateTime.Now;
}
</code>```

Client:

```<code>public class Client : Base
{
    public Guid Key { get; set; }
    public string Name { get; set; }
}
</code>```

Graphic:

```<code>public class Graphic : Base
{
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
    public ICollection<GraphicItem> Items { get; set; } = new HashSet<GraphicItem>();
    public ICollection<Tag> Tags { get; set; } = new HashSet<Tag>();
}
</code>```

GraphicItem: (the property GraphicUploadTemplateId causes the exception)

```<code>public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplateItem { get; set; }
}
</code>```

GraphicUploadTemplate:

```<code>public class GraphicUploadTemplate : Base
{
    public int ClientId { get; set; }
    public virtual Client client { get; set; }
    public ICollection<GraphicUploadTemplateItem> Items { get; set; }
}
</code>```

GraphicUploadTemplateItem:

```<code>public class GraphicUploadTemplateItem : Base
{
    public int GraphicUploadTemplateId { get; set; }
    public virtual GraphicUploadTemplate UploadTemplate { get; set; }
}
</code>```

答: There will be a link to the corresponding GraphicUploadTemplateItem already through GraphicItem.UploadTemplateItem.Id, i think that causes the circular reference.</p>

Body:
I'm using Entity Framework Core and have a simple 5 table design, but get an error and can't figure out why. What am I missing?

Exception:

Introducing FOREIGN KEY constraint
  'FK_GraphicItems_GraphicUploadTemplateItems_GraphicUploadTemplateItemId'
  on table 'GraphicItems' may cause cycles or multiple cascade paths.
  Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other
  FOREIGN KEY constraints.

Base:

public abstract class Base
{
    public int Id { get; set; }
    public DateTime DateCreated { get; set; } = DateTime.Now;
}

Client:

public class Client : Base
{
    public Guid Key { get; set; }
    public string Name { get; set; }
}

Graphic:

public class Graphic : Base
{
    public int ClientId { get; set; }
    public virtual Client Client { get; set; }
    public ICollection<GraphicItem> Items { get; set; } = new HashSet<GraphicItem>();
    public ICollection<Tag> Tags { get; set; } = new HashSet<Tag>();
}

GraphicItem: (the property GraphicUploadTemplateId causes the exception)

public class GraphicItem : Base
{
    public int GraphicId { get; set; }
    public virtual Graphic Graphic { get; set; }
    public int GraphicUploadTemplateItemId { get; set; }
    public virtual GraphicUploadTemplateItem UploadTemplateItem { get; set; }
}

GraphicUploadTemplate:

public class GraphicUploadTemplate : Base
{
    public int ClientId { get; set; }
    public virtual Client client { get; set; }
    public ICollection<GraphicUploadTemplateItem> Items { get; set; }
}

GraphicUploadTemplateItem:

public class GraphicUploadTemplateItem : Base
{
    public int GraphicUploadTemplateId { get; set; }
    public virtual GraphicUploadTemplate UploadTemplate { get; set; }
}


问:
mod_rewrite ignore last directory if it's the third directory
How would you remove the last directory if the url contains three directories

```<code>For example this url
www.mysite.com/dir/removeMe
would map to
www.mysite.com/dir

However
www.mysite.com/dir
would still map to
www.mysite.com/dir
</code>```

I am trying to use prettier links instead of www.mysite.com/dir/?name=removeMe

Thanks.

答:
Something like this should do what you want:

```<code>RewriteRule ^([^/]*)/([^/]+)$ /$1
</code>```

You can also use $2 in the rewrite if you want to preserve the last directory name in a parameter or something. eg:

```<code>RewriteRule ^([^/]*)/([^/]+)$ /$1?foo=$2
</code>```

(Aside: I notice that by 3 directories you actually mean 2. That first thing is the hostname, not a directory.)

ContentLicense: CC BY-SA 2.5

Body:
How would you remove the last directory if the url contains three directories

For example this url
www.mysite.com/dir/removeMe
would map to
www.mysite.com/dir

However
www.mysite.com/dir
would still map to
www.mysite.com/dir

I am trying to use prettier links instead of www.mysite.com/dir/?name=removeMe

Thanks.

Body:
Something like this should do what you want:

RewriteRule ^([^/]*)/([^/]+)$ /$1

You can also use $2 in the rewrite if you want to preserve the last directory name in a parameter or something. eg:

RewriteRule ^([^/]*)/([^/]+)$ /$1?foo=$2

(Aside: I notice that by 3 directories you actually mean 2. That first thing is the hostname, not a directory.)


问:
Analyze Data in array, delete, then re-analyze VBA
As the code is now, I can analyze the DataSet and detect outliers according to values stored in LowConf and HighConf which are based on the size of DataSet. However, I can only determine one outlier in this. I want to expand the code or add to it so I can do the following:

Identify the MOST outlying element first

Determine if it is an outlier, if so, delete that element from DataSet, if not, end the program.

Alter the sample size (subtract 1) and analyze the DataSet again for the next MOST outlying element and loop that k times.

My idea is to make a new array that is the distance (absolute value) from each DataSet element from the mean and then find the UBound of that and analyze that in the If statements below. My question is that once i determine whether or not it is an outlier, how do I get back to the corresponding element in DataSet and delete that? If so, is there an easier way to go about this? Also, I am new to coding so any tips on acceptable format / how to clean up the code is also appreciated.

```<code>Sub CalculateOutliers()

    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim k As Integer
    Dim DataSet As Variant
    Dim LowConf As Single
    Dim HighConf As Single

'--------------------------------------------------------
    DataSet = Selection.Value
'Copies highlighted data into DataSet variable
'Cell A1 is (1,1) Because it starts at 0 which is out of range
'--------------------------------------------------------

'--------------------------------------------------------
    n = Selection.CountLarge
'Counts number of entries
'--------------------------------------------------------

'--------------------------------------------------------
 'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
 'SAMPLE SIZE

        If n <= 5 Then

            LowConf = 1.72
            HighConf = 1.76
    End If

        If n = 6 Then

            LowConf = 1.89
            HighConf = 1.97

    End If

        If n = 7 Then

            LowConf = 2.02
            HighConf = 2.14

    End If

        If n = 8 Then

            LowConf = 2.13
            HighConf = 2.28

    End If

        If n = 9 Then

            LowConf = 2.21
            HighConf = 2.39

    End If

        If n = 10 Then

            LowConf = 2.29
            HighConf = 2.48

    End If

        If n = 11 Then

            LowConf = 2.36
            HighConf = 2.56

    End If

        If n = 12 Then

            LowConf = 2.41
            HighConf = 2.64

    End If

        If n = 13 Then

            LowConf = 2.46
            HighConf = 2.7

    End If

        If n = 14 Then

            LowConf = 2.51
            HighConf = 2.75

    End If

        If n = 15 Then

            LowConf = 2.55
            HighConf = 2.81

    End If

        If n = 16 Then

            LowConf = 2.59
            HighConf = 2.85

    End If

        If n = 17 Then

            LowConf = 2.62
            HighConf = 2.9

    End If

        If n = 18 Then

            LowConf = 2.65
            HighConf = 2.93

    End If

        If n = 19 Then

            LowConf = 2.68
            HighConf = 2.97

    End If

        If n = 20 Then

            LowConf = 2.71
            HighConf = 3

    End If

        If n = 21 Then

            LowConf = 2.73
            HighConf = 3.03

    End If

        If n = 22 Then

            LowConf = 2.76
            HighConf = 3.06

    End If

        If n = 23 Then

            LowConf = 2.78
            HighConf = 3.08

    End If

        If n = 24 Then

            LowConf = 2.8
            HighConf = 3.11

    End If

        If n = 25 Then

            LowConf = 2.82
            HighConf = 3.14

    End If

        If n = 26 Then

            LowConf = 2.84
            HighConf = 3.16

    End If

        If n = 27 Then

            LowConf = 2.86
            HighConf = 3.18

    End If

        If n = 28 Then

            LowConf = 2.88
            HighConf = 3.2

    End If

        If n = 29 Then

            LowConf = 2.89
            HighConf = 3.22

    End If

        If n = 30 Then

            LowConf = 2.91
            HighConf = 3.24

    End If

        If n <= 35 And n > 30 Then

            LowConf = 2.98
            HighConf = 3.32

    End If

        If n <= 40 And n > 35 Then

            LowConf = 3.04
            HighConf = 3.38

    End If

        If n <= 45 And n > 40 Then

            LowConf = 3.09
            HighConf = 3.44

    End If

        If n <= 50 And n > 45 Then

            LowConf = 3.13
            HighConf = 3.48

    End If

        If n <= 60 And n > 50 Then

            LowConf = 3.2
            HighConf = 3.56

    End If

        If n <= 70 And n > 60 Then

            LowConf = 3.26
            HighConf = 3.62

    End If

        If n <= 80 And n > 70 Then

            LowConf = 3.31
            HighConf = 3.67

    End If

        If n <= 90 And n > 80 Then

            LowConf = 3.35
            HighConf = 3.72

    End If

        If n <= 100 And n > 90 Then

            LowConf = 3.38
            HighConf = 3.75

    End If

        If n <= 150 And n > 100 Then

            LowConf = 3.52
            HighConf = 3.89

    End If

        If n <= 200 And n > 150 Then

            LowConf = 3.61
            HighConf = 3.98

    End If

        If n <= 300 And n > 200 Then

            LowConf = 3.72
            HighConf = 4.09

    End If

        If n <= 400 And n > 300 Then

            LowConf = 3.8
            HighConf = 4.17

    End If

        If n <= 500 And n > 400 Then

            LowConf = 3.86
            HighConf = 4.32

    End If

        If n > 500 Then

            MsgBox "Sample size cannot exceed 500."

    End If
'--------------------------------------------------------

'--------------------------------------------------------
        If n < 50 Then

            k = Int(n / 10)

        Else

            k = 5

    End If
'determines k = number of possible outliers
'--------------------------------------------------------

'--------------------------------------------------------
    mean = Application.WorksheetFunction.Average(DataSet)
'Calculates mean of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    SD = Application.WorksheetFunction.StDev(DataSet)
'Calculates Standard Deviation of Data Set
'--------------------------------------------------------

'--------------------------------------------------------

        For Each element In DataSet

            If (Abs(element - mean) / SD) > LowConf Then

                MsgBox "95% outlier: " & element

        End If

            If (Abs(element - mean) / SD) > HighConf Then

                MsgBox "99% outlier: " & element

        End If

        Next element
'--------------------------------------------------------

End Sub
</code>```

UPDATE: I have figured out the following chunk of code. This loop should work  but now I just need to figure out how to delete Suspect from the DataSet. Once it is deleted it will loop back and recalculate mean and SD and Suspect. I realize I have no code for when UBound is equal to LBound but that is something I will deal with after this. With this code, Suspect keeps showing a value of 1. I am not sure why this is nor am I sure if the DataSet.Remove(Suspect) works.

```<code>Dim i As Long

    For i = 1 To k

'--------------------------------------------------------
    mean = Application.WorksheetFunction.Average(DataSet)
'Calculates mean of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    SD = Application.WorksheetFunction.StDev(DataSet)
'Calculates Standard Deviation of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    Dim Suspect As Double
        If (Abs(UBound(DataSet) - mean)) > (Abs(LBound(DataSet) - mean)) Then
            Suspect = UBound(DataSet)
        End If
        If (Abs(UBound(DataSet) - mean)) < (Abs(LBound(DataSet) - mean)) Then
            Suspect = LBound(DataSet)
        End If
'Defines what the most outlying value is
'--------------------------------------------------------

'--------------------------------------------------------
    Dim Retest As Boolean

            If (Abs(Suspect - mean) / SD) > LowConf Then

                MsgBox "95% outlier: " & Suspect
                Retest = True

        End If

            If (Abs(Suspect - mean) / SD) > HighConf Then

                MsgBox "99% outlier: " & Suspect
                Retest = True

        End If

            If Retest = True Then
                DataSet.Remove (Suspect)
            End If
   MsgBox Suspect
'--------------------------------------------------------
Next i
</code>```

UPDATE: I have changed the portion a bit. I can apply this to the minimum but How can i specify the position of Suspect and use that as the range for the delete and shift up?

```<code>                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If
                    Dim pos As Range

                        Set pos = Application.Match(Suspect, DataSet)
                        MsgBox pos
                        If Retest = True And Suspect = Application.WorksheetFunction.Max(DataSet) Then

                           Range(pos).Delete Shift:=xlUp

                        End If
</code>```

答:
This addresses the part of the question about how to clean up the code. Including white space, you have nearly 300 lines of code (determining the conf levels) which can be compressed into about a dozen or so. First, define a function:

```<code>Function ConfLevels(n As Long) As Variant
    Dim i As Long
    Dim cutpoints As Variant, lowconfs As Variant, highconfs As Variant

    cutpoints = Array(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 150, 200, 300, 400, 500)
    lowconfs = Array(1.72, 1.89, 2.02, 2.13, 2.21, 2.29, 2.36, 2.41, 2.46, 2.51, 2.55, 2.59, 2.62, 2.65, 2.68, 2.71, 2.73, 2.76, 2.78, 2.8, 2.82, 2.84, 2.86, 2.88, 2.89, 2.91, 2.98, 3.04, 3.09, 3.13, 3.2, 3.26, 3.31, 3.35, 3.38, 3.52, 3.61, 3.72, 3.8, 3.86)
    highconfs = Array(1.76, 1.97, 2.14, 2.28, 2.39, 2.48, 2.56, 2.64, 2.7, 2.75, 2.81, 2.85, 2.9, 2.93, 2.97, 3#, 3.03, 3.06, 3.08, 3.11, 3.14, 3.16, 3.18, 3.2, 3.22, 3.24, 3.32, 3.38, 3.44, 3.48, 3.56, 3.62, 3.67, 3.72, 3.75, 3.89, 3.98, 4.09, 4.17, 4.32)
    i = 0
    Do While n > cutpoints(i)
        i = i + 1
    Loop
    ConfLevels = Array(lowconfs(i), highconfs(i))
End Function
</code>```

Then in the main sub replace all that code by:

```<code>Dim levels As Variant 'in the declaration part, use a different name if you want

'if n > 500, handle error and exit sub
levels = ConfLevels(n)
LowConf = levels(0)
HignConf = levels(1)
</code>```

You could even skip the variables LowConf and HighConf and use levels(0) and levels(1) directly.

If you explained the heuristic you used, it might be able to shorten this even more by using worksheet functions such as T.Inv.2T. Where did these numbers come from?

As far as the rest of your code goes, a reasonable strategy would be to write a recursive function which is fed a VBA array and returns a VBA array with all outliers removed (with the basis case being one which returns the array unchanged because there are no more outliers to remove). The main sub (which actually interacts with the spreadsheet and the user) could be relatively small.

Body:
As the code is now, I can analyze the DataSet and detect outliers according to values stored in LowConf and HighConf which are based on the size of DataSet. However, I can only determine one outlier in this. I want to expand the code or add to it so I can do the following:

Identify the MOST outlying element first

Determine if it is an outlier, if so, delete that element from DataSet, if not, end the program.

Alter the sample size (subtract 1) and analyze the DataSet again for the next MOST outlying element and loop that k times.

My idea is to make a new array that is the distance (absolute value) from each DataSet element from the mean and then find the UBound of that and analyze that in the If statements below. My question is that once i determine whether or not it is an outlier, how do I get back to the corresponding element in DataSet and delete that? If so, is there an easier way to go about this? Also, I am new to coding so any tips on acceptable format / how to clean up the code is also appreciated.

Sub CalculateOutliers()

    Dim n As Integer
    Dim mean As Double
    Dim SD As Double
    Dim k As Integer
    Dim DataSet As Variant
    Dim LowConf As Single
    Dim HighConf As Single

'--------------------------------------------------------
    DataSet = Selection.Value
'Copies highlighted data into DataSet variable
'Cell A1 is (1,1) Because it starts at 0 which is out of range
'--------------------------------------------------------

'--------------------------------------------------------
    n = Selection.CountLarge
'Counts number of entries
'--------------------------------------------------------

'--------------------------------------------------------
 'DEFINES 95(LowConf) AND 99(HighConf) PERCENT CONFIDENCES BASED ON
 'SAMPLE SIZE

        If n <= 5 Then

            LowConf = 1.72
            HighConf = 1.76
    End If

        If n = 6 Then

            LowConf = 1.89
            HighConf = 1.97

    End If

        If n = 7 Then

            LowConf = 2.02
            HighConf = 2.14

    End If

        If n = 8 Then

            LowConf = 2.13
            HighConf = 2.28

    End If

        If n = 9 Then

            LowConf = 2.21
            HighConf = 2.39

    End If

        If n = 10 Then

            LowConf = 2.29
            HighConf = 2.48

    End If

        If n = 11 Then

            LowConf = 2.36
            HighConf = 2.56

    End If

        If n = 12 Then

            LowConf = 2.41
            HighConf = 2.64

    End If

        If n = 13 Then

            LowConf = 2.46
            HighConf = 2.7

    End If

        If n = 14 Then

            LowConf = 2.51
            HighConf = 2.75

    End If

        If n = 15 Then

            LowConf = 2.55
            HighConf = 2.81

    End If

        If n = 16 Then

            LowConf = 2.59
            HighConf = 2.85

    End If

        If n = 17 Then

            LowConf = 2.62
            HighConf = 2.9

    End If

        If n = 18 Then

            LowConf = 2.65
            HighConf = 2.93

    End If

        If n = 19 Then

            LowConf = 2.68
            HighConf = 2.97

    End If

        If n = 20 Then

            LowConf = 2.71
            HighConf = 3

    End If

        If n = 21 Then

            LowConf = 2.73
            HighConf = 3.03

    End If

        If n = 22 Then

            LowConf = 2.76
            HighConf = 3.06

    End If

        If n = 23 Then

            LowConf = 2.78
            HighConf = 3.08

    End If

        If n = 24 Then

            LowConf = 2.8
            HighConf = 3.11

    End If

        If n = 25 Then

            LowConf = 2.82
            HighConf = 3.14

    End If

        If n = 26 Then

            LowConf = 2.84
            HighConf = 3.16

    End If

        If n = 27 Then

            LowConf = 2.86
            HighConf = 3.18

    End If

        If n = 28 Then

            LowConf = 2.88
            HighConf = 3.2

    End If

        If n = 29 Then

            LowConf = 2.89
            HighConf = 3.22

    End If

        If n = 30 Then

            LowConf = 2.91
            HighConf = 3.24

    End If

        If n <= 35 And n > 30 Then

            LowConf = 2.98
            HighConf = 3.32

    End If

        If n <= 40 And n > 35 Then

            LowConf = 3.04
            HighConf = 3.38

    End If

        If n <= 45 And n > 40 Then

            LowConf = 3.09
            HighConf = 3.44

    End If

        If n <= 50 And n > 45 Then

            LowConf = 3.13
            HighConf = 3.48

    End If

        If n <= 60 And n > 50 Then

            LowConf = 3.2
            HighConf = 3.56

    End If

        If n <= 70 And n > 60 Then

            LowConf = 3.26
            HighConf = 3.62

    End If

        If n <= 80 And n > 70 Then

            LowConf = 3.31
            HighConf = 3.67

    End If

        If n <= 90 And n > 80 Then

            LowConf = 3.35
            HighConf = 3.72

    End If

        If n <= 100 And n > 90 Then

            LowConf = 3.38
            HighConf = 3.75

    End If

        If n <= 150 And n > 100 Then

            LowConf = 3.52
            HighConf = 3.89

    End If

        If n <= 200 And n > 150 Then

            LowConf = 3.61
            HighConf = 3.98

    End If

        If n <= 300 And n > 200 Then

            LowConf = 3.72
            HighConf = 4.09

    End If

        If n <= 400 And n > 300 Then

            LowConf = 3.8
            HighConf = 4.17

    End If

        If n <= 500 And n > 400 Then

            LowConf = 3.86
            HighConf = 4.32

    End If

        If n > 500 Then

            MsgBox "Sample size cannot exceed 500."

    End If
'--------------------------------------------------------

'--------------------------------------------------------
        If n < 50 Then

            k = Int(n / 10)

        Else

            k = 5

    End If
'determines k = number of possible outliers
'--------------------------------------------------------

'--------------------------------------------------------
    mean = Application.WorksheetFunction.Average(DataSet)
'Calculates mean of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    SD = Application.WorksheetFunction.StDev(DataSet)
'Calculates Standard Deviation of Data Set
'--------------------------------------------------------

'--------------------------------------------------------

        For Each element In DataSet

            If (Abs(element - mean) / SD) > LowConf Then

                MsgBox "95% outlier: " & element

        End If

            If (Abs(element - mean) / SD) > HighConf Then

                MsgBox "99% outlier: " & element

        End If

        Next element
'--------------------------------------------------------

End Sub

UPDATE: I have figured out the following chunk of code. This loop should work  but now I just need to figure out how to delete Suspect from the DataSet. Once it is deleted it will loop back and recalculate mean and SD and Suspect. I realize I have no code for when UBound is equal to LBound but that is something I will deal with after this. With this code, Suspect keeps showing a value of 1. I am not sure why this is nor am I sure if the DataSet.Remove(Suspect) works.

Dim i As Long

    For i = 1 To k

'--------------------------------------------------------
    mean = Application.WorksheetFunction.Average(DataSet)
'Calculates mean of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    SD = Application.WorksheetFunction.StDev(DataSet)
'Calculates Standard Deviation of Data Set
'--------------------------------------------------------

'--------------------------------------------------------
    Dim Suspect As Double
        If (Abs(UBound(DataSet) - mean)) > (Abs(LBound(DataSet) - mean)) Then
            Suspect = UBound(DataSet)
        End If
        If (Abs(UBound(DataSet) - mean)) < (Abs(LBound(DataSet) - mean)) Then
            Suspect = LBound(DataSet)
        End If
'Defines what the most outlying value is
'--------------------------------------------------------

'--------------------------------------------------------
    Dim Retest As Boolean

            If (Abs(Suspect - mean) / SD) > LowConf Then

                MsgBox "95% outlier: " & Suspect
                Retest = True

        End If

            If (Abs(Suspect - mean) / SD) > HighConf Then

                MsgBox "99% outlier: " & Suspect
                Retest = True

        End If

            If Retest = True Then
                DataSet.Remove (Suspect)
            End If
   MsgBox Suspect
'--------------------------------------------------------
Next i

UPDATE: I have changed the portion a bit. I can apply this to the minimum but How can i specify the position of Suspect and use that as the range for the delete and shift up?

                        Dim Retest As Boolean

                        If (Abs(Suspect - mean) / SD) > LowConf Then

                            MsgBox "95% outlier: " & Suspect
                            Retest = True

                    End If

                        If (Abs(Suspect - mean) / SD) > HighConf Then

                            MsgBox "99% outlier: " & Suspect
                            Retest = True

                    End If
                    Dim pos As Range

                        Set pos = Application.Match(Suspect, DataSet)
                        MsgBox pos
                        If Retest = True And Suspect = Application.WorksheetFunction.Max(DataSet) Then

                           Range(pos).Delete Shift:=xlUp

                        End If

Body:
This addresses the part of the question about how to clean up the code. Including white space, you have nearly 300 lines of code (determining the conf levels) which can be compressed into about a dozen or so. First, define a function:

Function ConfLevels(n As Long) As Variant
    Dim i As Long
    Dim cutpoints As Variant, lowconfs As Variant, highconfs As Variant

    cutpoints = Array(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 150, 200, 300, 400, 500)
    lowconfs = Array(1.72, 1.89, 2.02, 2.13, 2.21, 2.29, 2.36, 2.41, 2.46, 2.51, 2.55, 2.59, 2.62, 2.65, 2.68, 2.71, 2.73, 2.76, 2.78, 2.8, 2.82, 2.84, 2.86, 2.88, 2.89, 2.91, 2.98, 3.04, 3.09, 3.13, 3.2, 3.26, 3.31, 3.35, 3.38, 3.52, 3.61, 3.72, 3.8, 3.86)
    highconfs = Array(1.76, 1.97, 2.14, 2.28, 2.39, 2.48, 2.56, 2.64, 2.7, 2.75, 2.81, 2.85, 2.9, 2.93, 2.97, 3#, 3.03, 3.06, 3.08, 3.11, 3.14, 3.16, 3.18, 3.2, 3.22, 3.24, 3.32, 3.38, 3.44, 3.48, 3.56, 3.62, 3.67, 3.72, 3.75, 3.89, 3.98, 4.09, 4.17, 4.32)
    i = 0
    Do While n > cutpoints(i)
        i = i + 1
    Loop
    ConfLevels = Array(lowconfs(i), highconfs(i))
End Function

Then in the main sub replace all that code by:

Dim levels As Variant 'in the declaration part, use a different name if you want

'if n > 500, handle error and exit sub
levels = ConfLevels(n)
LowConf = levels(0)
HignConf = levels(1)

You could even skip the variables LowConf and HighConf and use levels(0) and levels(1) directly.

If you explained the heuristic you used, it might be able to shorten this even more by using worksheet functions such as T.Inv.2T. Where did these numbers come from?

As far as the rest of your code goes, a reasonable strategy would be to write a recursive function which is fed a VBA array and returns a VBA array with all outliers removed (with the basis case being one which returns the array unchanged because there are no more outliers to remove). The main sub (which actually interacts with the spreadsheet and the user) could be relatively small.


问:
Tableau json API WebConnector
I've written the following tableau webconnector to pull data from an internal API, using earthquakeUSGS.html as a guideline (https://github.com/tableau/webdataconnector). The API returns json (see code below). I've been using the "Web data connector simulator 2.0" and all has been going well. I get the correct Table, however, Im unable to "Fetch Table Data". As this is my first js script, Im very sure that is were the error is. To iterate through the data I used the answer from Korijn in this post Iterate through nested json object array

The Problem: Is probably with the js iterator over the json object. If anyone can take a look at the json (below), and have a look at my iterator, I would greatly appreciate it. This is what makes it impossible for me to fetch data.

test.js

```<code>(function() {
    // Create the connector object
    var myConnector = tableau.makeConnector();

    // Define the schema
    myConnector.getSchema = function(schemaCallback) {
        var cols = [{
            id: "prog",
            alias: "PrognosisTime",
            dataType: tableau.dataTypeEnum.string
        }, {
            id: "start",
            alias: "Start",
            dataType: tableau.dataTypeEnum.date
        }, {
            id: "val",
            alias: "Value",
            dataType: tableau.dataTypeEnum.float
        }];

        var tableSchema = {
            id: "table",
            alias: "187",
            columns: cols
        };

        schemaCallback([tableSchema]);
    };

    // Download the data
    myConnector.getData = function(table, doneCallback) {
        $.getJSON("http://myapi.com/119%2C7777/Flattened?start=today&end=today&timeZone=CET&asOf=now&aggregation=None", function(resp) {
            var feat = resp.features,
                tableData = [];
                tableData.push(
                    {"table":feat.properties.table}
                    );

            // Iterate over the JSON object
            //var SeriesId = feat.SeriesId
            for(var i = 0; i <feat.DataPoints.length; i++){
                var PrognosisTime = feat.DataPoints.PrognosisTime;
                var Start = feat.DataPoints.Start;
                var Value = feat.DataPoints.Value;
            }
            table.appendRows(tableData);
            doneCallback();
        });
    };

    tableau.registerConnector(myConnector);

    // Create event listeners for when the user submits the form
    $(document).ready(function() {
        $("#submitButton").click(function() {
            tableau.connectionName = "Neas"; // This will be the data source name in Tableau
            tableau.submit(); // This sends the connector object to Tableau
        });
    });
})();
</code>```

json from API

```<code>[
  {
    "SeriesId": 119,
    "DataPoints": [
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:00:00",
        "Value": 26.19
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T01:00:00",
        "Value": 23.9
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T02:00:00",
        "Value": 22.82
      }
    ]
  },
  {
    "SeriesId": 7777,
    "DataPoints": [
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:00:00",
        "Value": 36.39
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:15:00",
        "Value": 28.81
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:30:00",
        "Value": 24.28
      }
    ]
  }
]
</code>```

答:
The problem is this line:

```<code>var feat = resp.features
</code>```

resp is an array from your JSON, there is nothing called features. So, simply iterate over resp (or feat = resp) and pull out your DataPoints array.

Title: Tableau json API WebConnector

Body:
I've written the following tableau webconnector to pull data from an internal API, using earthquakeUSGS.html as a guideline (https://github.com/tableau/webdataconnector). The API returns json (see code below). I've been using the "Web data connector simulator 2.0" and all has been going well. I get the correct Table, however, Im unable to "Fetch Table Data". As this is my first js script, Im very sure that is were the error is. To iterate through the data I used the answer from Korijn in this post Iterate through nested json object array

The Problem: Is probably with the js iterator over the json object. If anyone can take a look at the json (below), and have a look at my iterator, I would greatly appreciate it. This is what makes it impossible for me to fetch data.

test.js

(function() {
    // Create the connector object
    var myConnector = tableau.makeConnector();

    // Define the schema
    myConnector.getSchema = function(schemaCallback) {
        var cols = [{
            id: "prog",
            alias: "PrognosisTime",
            dataType: tableau.dataTypeEnum.string
        }, {
            id: "start",
            alias: "Start",
            dataType: tableau.dataTypeEnum.date
        }, {
            id: "val",
            alias: "Value",
            dataType: tableau.dataTypeEnum.float
        }];

        var tableSchema = {
            id: "table",
            alias: "187",
            columns: cols
        };

        schemaCallback([tableSchema]);
    };

    // Download the data
    myConnector.getData = function(table, doneCallback) {
        $.getJSON("http://myapi.com/119%2C7777/Flattened?start=today&end=today&timeZone=CET&asOf=now&aggregation=None", function(resp) {
            var feat = resp.features,
                tableData = [];
                tableData.push(
                    {"table":feat.properties.table}
                    );

            // Iterate over the JSON object
            //var SeriesId = feat.SeriesId
            for(var i = 0; i <feat.DataPoints.length; i++){
                var PrognosisTime = feat.DataPoints.PrognosisTime;
                var Start = feat.DataPoints.Start;
                var Value = feat.DataPoints.Value;
            }
            table.appendRows(tableData);
            doneCallback();
        });
    };

    tableau.registerConnector(myConnector);

    // Create event listeners for when the user submits the form
    $(document).ready(function() {
        $("#submitButton").click(function() {
            tableau.connectionName = "Neas"; // This will be the data source name in Tableau
            tableau.submit(); // This sends the connector object to Tableau
        });
    });
})();

json from API

[
  {
    "SeriesId": 119,
    "DataPoints": [
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:00:00",
        "Value": 26.19
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T01:00:00",
        "Value": 23.9
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T02:00:00",
        "Value": 22.82
      }
    ]
  },
  {
    "SeriesId": 7777,
    "DataPoints": [
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:00:00",
        "Value": 36.39
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:15:00",
        "Value": 28.81
      },
      {
        "PrognosisTime": null,
        "Start": "2016-08-24T00:30:00",
        "Value": 24.28
      }
    ]
  }
]

Body:
The problem is this line:

var feat = resp.features

resp is an array from your JSON, there is nothing called features. So, simply iterate over resp (or feat = resp) and pull out your DataPoints array.


问:
SQL Call function foreach row on every record in other table
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

```<code>dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150
</code>```

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

答:
Select from both tables:</p>

```<code>SELECT
    *
FROM Table1 as item1,
Table2 as item2
WHERE dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150
</code>```

Body:
I have two tables; Table1 (name, latitude, longitude) with 400 records in and Table2 (name, latitude, longitude) with 10,000 records in.

I want to find all records in Table2 that are physically close to the 400 records in Table1. (excluding all the 400 records in Table1).

I have a function that works out the distance between two records. My problem is in SQL I can't figure out how to run it for every record in Table1, on every record in Table2. I am calling my function as below;

dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150

This gets the distance between the two coordinates and will only return the ones if it is within 150 metres. It works fine but I am struggling with running it for each record in Table1 over every record in Table2.

Any pointers would be greatly appriciated! I think this is fairly simple to do in SQL but my experience is lacking.

Body:
Select from both tables:

SELECT
    *
FROM Table1 as item1,
Table2 as item2
WHERE dbo.fnCalcDistanceKM(item1.lat, item2.lat, item1.long, item2.long) < 0.150


问:
Find the Key from multiple values array in PHP
I am trying to find the key of which one of the children items exists in. I have this array

```<code>$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);
</code>```

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

```<code>foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;
</code>```

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?

答:
You can use key function in combination with array_filter. The snippet:

```<code>$needle = 'αρθρο';
$pageKey = key(array_filter($stdCurl, function ($val) use ($needle) {
    return in_array($needle, $val);
}));
</code>```

Body:
I am trying to find the key of which one of the children items exists in. I have this array

$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?

Body:
You can use key function in combination with array_filter. The snippet:

$needle = 'αρθρο';
$pageKey = key(array_filter($stdCurl, function ($val) use ($needle) {
    return in_array($needle, $val);
}));


问:
Symfony Oauth2 with gard
I am trying to configure guard with an OAuth 2 connection.
I am trying to do this with a redirection in the getCredentials function to the Microsoft login website but I can't make it work. I don't know how I can make it worked.
It seems there is no redirection possible in this function.</p>

```<code>public function getCredentials(Request $request)
{
    $provider = new Microsoft([
            'clientId'          => '0000000032624',
            'clientSecret'      => 'my-secret',
            'redirectUri'       => 'https://mysite/oauthlogin'
    ]);

    if(!$request->query->has('code')){
        // If we don't have an authorization code then get one
        $authUrl = $provider->getAuthorizationUrl();
        $request->getSession()->set('oauth2state', $provider->getState());
        //This doesn't work
        return new RedirectResponse($authUrl);

    // Check given state against previously stored one to mitigate CSRF attack
    }elseif ( empty($request->query->get('state')) || ($request->query->get('state')!==$request->getSession()->get('oauth2state')) ){
        return null;
    }else{
        // Try to get an access token (using the authorization code grant)
        $token = $provider->getAccessToken('authorization_code', [
            'code' => $request->query->get('code')
        ]);
        try {
            //when log with microsoft, check if user is allowed
            // We got an access token, let's now get the user's details
            $user = $provider->getResourceOwner($token);
             } catch (Exception $e) {
            // Failed to get user details
        }
    }

}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    return $userProvider->loadUserByUsername($user->getEmail());
}

public function checkCredentials($credentials, UserInterface $user)
{
    // check credentials - e.g. make sure the password is valid
    // no credential check is needed in this case

    // return true to cause authentication success
    return true;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $url = $this->router->generate('homepage');
    return new RedirectResponse($url);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
            // or to translate this message
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );
    $request->getSession()->set(Security::AUTHENTICATION_ERROR, $data);
    $url = $this->router->generate('login');
    return new RedirectResponse($url);
}
</code>```

答:
Function getCredentials() is not supposed to return a Response, it provide the credentials used in getUser().

In the getUser() documentation :

The credentials are the return value from getCredentials()

You may throw an AuthenticationException if you wish. If you return
  null, then a UsernameNotFoundException is thrown for you.

In case of exception thrown, onAuthenticationFailure() is called and here you can return your RedirectResponse.

For more detailled informations, see the source code of the \Symfony\Component\Security\Guard\GuardAuthenticatorInterface which contains a lots of explanations in its methods.

Title: Symfony Oauth2 with gard

Body:
I am trying to configure guard with an OAuth 2 connection.
I am trying to do this with a redirection in the getCredentials function to the Microsoft login website but I can't make it work. I don't know how I can make it worked.
It seems there is no redirection possible in this function.

public function getCredentials(Request $request)
{
    $provider = new Microsoft([
            'clientId'          => '0000000032624',
            'clientSecret'      => 'my-secret',
            'redirectUri'       => 'https://mysite/oauthlogin'
    ]);

    if(!$request->query->has('code')){
        // If we don't have an authorization code then get one
        $authUrl = $provider->getAuthorizationUrl();
        $request->getSession()->set('oauth2state', $provider->getState());
        //This doesn't work
        return new RedirectResponse($authUrl);

    // Check given state against previously stored one to mitigate CSRF attack
    }elseif ( empty($request->query->get('state')) || ($request->query->get('state')!==$request->getSession()->get('oauth2state')) ){
        return null;
    }else{
        // Try to get an access token (using the authorization code grant)
        $token = $provider->getAccessToken('authorization_code', [
            'code' => $request->query->get('code')
        ]);
        try {
            //when log with microsoft, check if user is allowed
            // We got an access token, let's now get the user's details
            $user = $provider->getResourceOwner($token);
             } catch (Exception $e) {
            // Failed to get user details
        }
    }

}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    return $userProvider->loadUserByUsername($user->getEmail());
}

public function checkCredentials($credentials, UserInterface $user)
{
    // check credentials - e.g. make sure the password is valid
    // no credential check is needed in this case

    // return true to cause authentication success
    return true;
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    $url = $this->router->generate('homepage');
    return new RedirectResponse($url);
}

public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
    $data = array(
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())
            // or to translate this message
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );
    $request->getSession()->set(Security::AUTHENTICATION_ERROR, $data);
    $url = $this->router->generate('login');
    return new RedirectResponse($url);
}


问:
C# and Arduino Timing
Good day,

I am trying to work with C#, Arduino and a LED power supply. First, C# will send some code sequence to my Arduino to activate my motor. I use encoder on the motor to know its position. When my desired position is reached by the motor, C# will send another sequence to my LED power supply. How to make it work? Now when I send my code, C# will send sequence to my LED power supply when my desired position isn't reached yet. I hope someone can help me. Thank you.

C# code:

```<code>arduino.write("A175");
if(arduino.read=="G") {
  powersuppy.write("S100T000F000F000FC#");
} else { }
</code>```

Arduino Code:

```<code>if(serial.Available()>0) {
  data=Serial.read();
  if (data=='A') {
    int destination=parseInt(Serial.read());
    for(count; count<destination ;count++) {
      motorgo();
      encoder();
    }
    Serial.write("G");
  }
}
</code>```

答: You are sending "G" to the C# after the for-loop ends. You need to check if position is reached THEN send "G".</p>

Title: C# and Arduino Timing

Body:
Good day,

I am trying to work with C#, Arduino and a LED power supply. First, C# will send some code sequence to my Arduino to activate my motor. I use encoder on the motor to know its position. When my desired position is reached by the motor, C# will send another sequence to my LED power supply. How to make it work? Now when I send my code, C# will send sequence to my LED power supply when my desired position isn't reached yet. I hope someone can help me. Thank you.

C# code:

arduino.write("A175");
if(arduino.read=="G") {
  powersuppy.write("S100T000F000F000FC#");
} else { }

Arduino Code:

if(serial.Available()>0) {
  data=Serial.read();
  if (data=='A') {
    int destination=parseInt(Serial.read());
    for(count; count<destination ;count++) {
      motorgo();
      encoder();
    }
    Serial.write("G");
  }
}


问:
python alternative to the goto command?
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

```<code>counter=1
<drawing code here>
counter +=1
</code>```

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

```<code>from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)
</code>```

If you have an answer or alternative to this problem it would be greatly appreciated!

答:
Does this help?

```<code>import turtle   # don't pollute the namespace
import time

def getInt(msg):
    return int(raw_input(msg))

def drawBall():
    turtle.down()
    for i in range(96):
        turtle.right(105)
        turtle.forward(100)
    turtle.up()

def moveOver():
    turtle.goto(120,0)

def Done():
    turtle.goto(0,-50)
    turtle.write('Done!')
    time.sleep(5)

def main():
    turtle.color('red','blue')
    for i in range(getInt('How many balls do you want?')):
        drawBall()
        moveOver()
    Done()

if __name__=="__main__":
    main()
</code>```

Don't think in terms of a single long list of instructions. Think instead about breaking your problem apart into smaller actions, such as "drawing a ball", and write each of those actions as a procedure; then think about how to join those procedures together to accomplish your goal. Writing the same code repeatedly is a sign that you are doing it wrong.

Title: python alternative to the goto command?

Body:
I have a python program that is essentailly made up of turtle graphics, and it is basically asking the user how many squares to draw, and then after each square, it adds 1 to a counter using:

counter=1
<drawing code here>
counter +=1

And then after that I wanted to do a check to see if the number of squares is equal to the amount that the user typed in, and if it is, then I wanted to go to the bottom of the script where I would make it say something like done!!. but I dont know how to make it go to a certain part of the script as the goto command that I'm used to in batch isn't supported in python (i know, goto= spaghetti code)

I found an easy workaround is just to download a module that someone made that lets you import the goto command into python and use it just as you would in batch but I would like a native python solution if any!

my current code is:

from turtle import *
import time
counter=1
color("red", "blue")
down()

user=int(raw_input('how many balls do you want?'))
counter +=1
if user===counter:

# solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(120,0)
down()

counter +=1
if user==counter:

#solution goes here!

else:

for step in range(24):
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)
        right(105)
        forward(100)

up()
goto(0,-50)
write("Done!")

time.sleep(5)

If you have an answer or alternative to this problem it would be greatly appreciated!

Body:
Does this help?

import turtle   # don't pollute the namespace
import time

def getInt(msg):
    return int(raw_input(msg))

def drawBall():
    turtle.down()
    for i in range(96):
        turtle.right(105)
        turtle.forward(100)
    turtle.up()

def moveOver():
    turtle.goto(120,0)

def Done():
    turtle.goto(0,-50)
    turtle.write('Done!')
    time.sleep(5)

def main():
    turtle.color('red','blue')
    for i in range(getInt('How many balls do you want?')):
        drawBall()
        moveOver()
    Done()

if __name__=="__main__":
    main()

Don't think in terms of a single long list of instructions. Think instead about breaking your problem apart into smaller actions, such as "drawing a ball", and write each of those actions as a procedure; then think about how to join those procedures together to accomplish your goal. Writing the same code repeatedly is a sign that you are doing it wrong.


问:
Swift - Create a GIF from Images and turn it into NSData
This might be an amateur question, but although I have searched Stack Overflow extensibly, I haven't been able to get an answer for my specific problem.

I was successful in creating a GIF file from an array of images by following a Github example:

```<code>func createGIF(with images: [NSImage], name: NSURL, loopCount: Int = 0, frameDelay: Double) {

    let destinationURL = name
    let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)!

    // This dictionary controls the delay between frames
    // If you don't specify this, CGImage will apply a default delay
    let properties = [
        (kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]
    ]

    for img in images {
        // Convert an NSImage to CGImage, fitting within the specified rect
        let cgImage = img.CGImageForProposedRect(nil, context: nil, hints: nil)!

        // Add the frame to the GIF image
        CGImageDestinationAddImage(destinationGIF, cgImage, properties)
    }

    // Write the GIF file to disk
    CGImageDestinationFinalize(destinationGIF)
}
</code>```

Now, I would like to turn the actual GIF into NSData so I can upload it to Firebase, and be able to retrieve it on another device.

To achieve my goal, I have two options: Either to find how to use the code above to extract the GIF created (which seems to directly be created when creating the file), or to use the images on the function's parameters to create a new GIF but keep it on NSData format.

Does anybody have any ideas on how to do this?

答:
Since nobody went ahead for over six months I will just put the answer from @Sachin Vas' comment here:

You can get the data using NSData(contentsOf: URL)

Body:
This might be an amateur question, but although I have searched Stack Overflow extensibly, I haven't been able to get an answer for my specific problem.

I was successful in creating a GIF file from an array of images by following a Github example:

func createGIF(with images: [NSImage], name: NSURL, loopCount: Int = 0, frameDelay: Double) {

    let destinationURL = name
    let destinationGIF = CGImageDestinationCreateWithURL(destinationURL, kUTTypeGIF, images.count, nil)!

    // This dictionary controls the delay between frames
    // If you don't specify this, CGImage will apply a default delay
    let properties = [
        (kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]
    ]

    for img in images {
        // Convert an NSImage to CGImage, fitting within the specified rect
        let cgImage = img.CGImageForProposedRect(nil, context: nil, hints: nil)!

        // Add the frame to the GIF image
        CGImageDestinationAddImage(destinationGIF, cgImage, properties)
    }

    // Write the GIF file to disk
    CGImageDestinationFinalize(destinationGIF)
}

Now, I would like to turn the actual GIF into NSData so I can upload it to Firebase, and be able to retrieve it on another device.

To achieve my goal, I have two options: Either to find how to use the code above to extract the GIF created (which seems to directly be created when creating the file), or to use the images on the function's parameters to create a new GIF but keep it on NSData format.

Does anybody have any ideas on how to do this?


问:
Inserting parameters for a function as array
I have the following two arrays:

```<code>Sub ArrayLoop(array1, array2)

 Dim Students() As Variant
 Set myDocument = ActivePresentation.Slides(1)

 ENG1 = Array(423.5482, 425.6641, 425.6641)
 ENG2 = Array(224.0202, 222.5737, 222.5737)

 GER1 = Array(454.692, 454.0753, 454.0753)
 GER2 = Array(220.8373, 222.2446, 224.3517)

 For i = 0 To 40

   x1 = parameter1(i)
   x2 = parameter2(i)

   y1 = parameter1(i + 1)
   y2 = parameter2(i + 1)

   With myDocument.Shapes.AddLine(BeginX:=x1, BeginY:=x2, EndX:=y1, EndY:=y2).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = RGB(50, 0, 128)
   End With

  Next i
End Sub
</code>```

What I basically want to do now is fire the macro "ArrayLoop" with two parameters and then that array should be used. S0

```<code>ArrayLoop(ENG1, ENG2)
</code>```

Should work with the Array's ENG1 and ENG2

However when I do this

```<code>Call ArrayLoop(ENG1, ENG2)
</code>```

I get an error 13 that says, the items are not comparable. Any thoughts on how I should get this working?

答:
ENG1 and ENG2 need to be passed as paramaters to the sub. In your code, they are defined as local variables. When invoking a routine with parameters, these parameters need to be defined elsewhere and passed to the routine.

```<code>Sub ArrayLoop(array1, array2)
  Dim i As Long
  For i = LBound(array1) To UBound(array1) - 1
    With ActivePresentation.Slides(1).Shapes.AddLine(BeginX:=array1(i), BeginY:=array2(i), EndX:=array1(i + 1), EndY:=array2(i + 1)).Line
      .DashStyle = msoLineDashDotDot
      .ForeColor.RGB = RGB(50, 0, 128)
    End With
  Next
End Sub
</code>```

Now here's how you define parameters and call the routine:

```<code>Sub TestArrayLoop()
  Dim ENG1, ENG2, GER1, GER2
  ENG1 = Array(423.5482, 425.6641, 425.6641)
  ENG2 = Array(224.0202, 222.5737, 222.5737)

  GER1 = Array(454.692, 454.0753, 454.0753)
  GER2 = Array(220.8373, 222.2446, 224.3517)

  ArrayLoop ENG1, ENG2  ' <----- invoke the routine and pass it the parameters
End Sub
</code>```

Body:
I have the following two arrays:

Sub ArrayLoop(array1, array2)

 Dim Students() As Variant
 Set myDocument = ActivePresentation.Slides(1)

 ENG1 = Array(423.5482, 425.6641, 425.6641)
 ENG2 = Array(224.0202, 222.5737, 222.5737)

 GER1 = Array(454.692, 454.0753, 454.0753)
 GER2 = Array(220.8373, 222.2446, 224.3517)

 For i = 0 To 40

   x1 = parameter1(i)
   x2 = parameter2(i)

   y1 = parameter1(i + 1)
   y2 = parameter2(i + 1)

   With myDocument.Shapes.AddLine(BeginX:=x1, BeginY:=x2, EndX:=y1, EndY:=y2).Line
    .DashStyle = msoLineDashDotDot
    .ForeColor.RGB = RGB(50, 0, 128)
   End With

  Next i
End Sub

What I basically want to do now is fire the macro "ArrayLoop" with two parameters and then that array should be used. S0

ArrayLoop(ENG1, ENG2)

Should work with the Array's ENG1 and ENG2

However when I do this

Call ArrayLoop(ENG1, ENG2)

I get an error 13 that says, the items are not comparable. Any thoughts on how I should get this working?

Body:
ENG1 and ENG2 need to be passed as paramaters to the sub. In your code, they are defined as local variables. When invoking a routine with parameters, these parameters need to be defined elsewhere and passed to the routine.

Sub ArrayLoop(array1, array2)
  Dim i As Long
  For i = LBound(array1) To UBound(array1) - 1
    With ActivePresentation.Slides(1).Shapes.AddLine(BeginX:=array1(i), BeginY:=array2(i), EndX:=array1(i + 1), EndY:=array2(i + 1)).Line
      .DashStyle = msoLineDashDotDot
      .ForeColor.RGB = RGB(50, 0, 128)
    End With
  Next
End Sub

Now here's how you define parameters and call the routine:

Sub TestArrayLoop()
  Dim ENG1, ENG2, GER1, GER2
  ENG1 = Array(423.5482, 425.6641, 425.6641)
  ENG2 = Array(224.0202, 222.5737, 222.5737)

  GER1 = Array(454.692, 454.0753, 454.0753)
  GER2 = Array(220.8373, 222.2446, 224.3517)

  ArrayLoop ENG1, ENG2  ' <----- invoke the routine and pass it the parameters
End Sub


问:
Java - Possible to Package some external jars, keep others separate?
I'm using eclipse to package a program into a runnable jar (Export...>Java>Runnable JAR File). I select the option Package required libraries into generated jar, but one external jar can't be packaged.  Is it possible to package the rest of my external jar dependencies while keeping this one outside the main jar?  I'm not looking to use maven or ant or anything like that.

答:
You can, just add the library to the /lib/ext directory of your JRE.

But this basically means you have to have control of the JRE on the target environment.


问:
Change screen Title on page load
In Acumatica (AEF) is it possible to change the screen title programmatically. In my case, I want to change it on screen-load (based on a particular value). Example Change the Case screen title to Sub-Case at runtime, depending on a particular field of the case.</p>

答:
Edit:
Try setting the title of current SiteMap node in the graph constructor or graph extension initialize event:

```<code>PXSiteMap.CurrentNode.Title = "Test";
</code>```

To my knowledge page Title is coming from the SiteMap. There's always the possibility to use JavaScript to modify the page and link title. Note that usage of JavaScript in Acumatica is usually discouraged.

In ASPX page, add a script element inside the root ASP container, get the title link element by class ID and change it's innerText property:

```<code><asp:Content ID="cont1" ContentPlaceHolderID="phDS" runat="Server">
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            var title = document.getElementsByClassName("linkTitle")[0];
            title.innerText = "Test";
            document.title = "Test";
        }, false);
    </script>

[...]
</code>```

Title: Change screen Title on page load

Body:
Edit:
Try setting the title of current SiteMap node in the graph constructor or graph extension initialize event:

PXSiteMap.CurrentNode.Title = "Test";

To my knowledge page Title is coming from the SiteMap. There's always the possibility to use JavaScript to modify the page and link title. Note that usage of JavaScript in Acumatica is usually discouraged.

In ASPX page, add a script element inside the root ASP container, get the title link element by class ID and change it's innerText property:

<asp:Content ID="cont1" ContentPlaceHolderID="phDS" runat="Server">
    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function () {
            var title = document.getElementsByClassName("linkTitle")[0];
            title.innerText = "Test";
            document.title = "Test";
        }, false);
    </script>

[...]


问:
multiple repeating values, take the ones which are ticked

I need to see if all B column cells say yes for the specified column A number. If so I would like to print the value on a new table. If not ignore it.

In this particular case I would print A2 and A3.

Any advice would be appreciated

答:
You can aggregate on the A column and then check to make sure that the count of records having a 'No' value in the B column is zero.

```<code>SELECT [A]
FROM yourTable
GROUP BY [A]
HAVING SUM(IIF([B] = 'No', 1, 0)) = 0
</code>```

@JohnInk edit:

If you want to also move the matching A values into a new table which you could then view, etc., you could use SELECT ... INTO:

```<code>SELECT [A]
INTO newTable
FROM yourTable
GROUP BY [A]
HAVING SUM(IIF([B] = 'No', 1, 0)) = 0
</code>```

Body:
You can aggregate on the A column and then check to make sure that the count of records having a 'No' value in the B column is zero.

SELECT [A]
FROM yourTable
GROUP BY [A]
HAVING SUM(IIF([B] = 'No', 1, 0)) = 0

@JohnInk edit:

If you want to also move the matching A values into a new table which you could then view, etc., you could use SELECT ... INTO:

SELECT [A]
INTO newTable
FROM yourTable
GROUP BY [A]
HAVING SUM(IIF([B] = 'No', 1, 0)) = 0


问:
Purge old release from Nexus 3
I use Nexus 3 and I want to delete my old releases. In Nexus 2 there is a scheduled task called Remove Releases From Repository. It seems that this tasks is missing in Nexus 3.

How can we delete old release from Nexus 3 ?

Thanks

答:
See this script as a basis to work with:

https://gist.github.com/emexelem/bcf6b504d81ea9019ad4ab2369006e66 by emexelem

```<code>import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.Query;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

def fmt = DateTimeFormat.forPattern('yyyy-MM-dd HH:mm:ss');
// Get a repository
def repo = repository.repositoryManager.get('nuget-releases');
// Get a database transaction
def tx = repo.facet(StorageFacet).txSupplier().get();
// Begin the transaction
tx.begin();
// Search assets that havn't been downloaded for more than three months
tx.findAssets(Query.builder().where('last_downloaded <').param(DateTime.now().minusMonths(3).toString(fmt)).build(), [repo]).each { asset ->
  def component = tx.findComponent(asset.componentId());
  // Check if there is newer components of the same name
  def count = tx.countComponents(Query.builder().where('name').eq(component.name()).and('version >').param(component.version()).build(), [repo]);
  if (count > 0) {
    log.info("Delete asset ${asset.name()} as it has not been downloaded since 3 months and has a newer version")
    tx.deleteAsset(asset);
    tx.deleteComponent(component);
  }
}
// End the transaction
tx.commit();
</code>```

Title: Purge old release from Nexus 3

Body:
See this script as a basis to work with:

https://gist.github.com/emexelem/bcf6b504d81ea9019ad4ab2369006e66 by emexelem

import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.Query;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;

def fmt = DateTimeFormat.forPattern('yyyy-MM-dd HH:mm:ss');
// Get a repository
def repo = repository.repositoryManager.get('nuget-releases');
// Get a database transaction
def tx = repo.facet(StorageFacet).txSupplier().get();
// Begin the transaction
tx.begin();
// Search assets that havn't been downloaded for more than three months
tx.findAssets(Query.builder().where('last_downloaded <').param(DateTime.now().minusMonths(3).toString(fmt)).build(), [repo]).each { asset ->
  def component = tx.findComponent(asset.componentId());
  // Check if there is newer components of the same name
  def count = tx.countComponents(Query.builder().where('name').eq(component.name()).and('version >').param(component.version()).build(), [repo]);
  if (count > 0) {
    log.info("Delete asset ${asset.name()} as it has not been downloaded since 3 months and has a newer version")
    tx.deleteAsset(asset);
    tx.deleteComponent(component);
  }
}
// End the transaction
tx.commit();

ContentLicense: CC BY-SA 4.0


问:
How to debug a Gruntfile with breakpoints using node-inspector, Windows 7?
So I have spent the past couple days trying to get this to work with no luck. Most of the solutions I have found seem to work "okay" for debugging node applications. But I haven't had much luck debugging grunt stand alone. I would like to be able to set breakpoints in my gruntfile and either step through the code with either the browser or an IDE.

I have tried the following:

Debugging using intelliJ IDE Using Grunt Console (Process finished with exit code 6)

Debugging with Nodeeclipse (This sort of works okay but doesn't hit the breakpoints set in eclipse, not very intuitive)

Debugging using node-inspector (This one also sort of works. I can step through a little ways using F11 and F10 in chrome. But eventually it just crashes. Using F8 to skip to break point never works.)

ERROR MESSAGE USING NODE-INSPECTOR

So currently node-inspector feels like it has gotten me the closest to what I want. To get here I did the following:

From my grunt directory I ran the following commands:

```<code>grunt node-inspector
node --debug-brk Gruntfile.js
</code>```

And then from there I went to localhost:8080/debug?port=5858 to debug my Gruntfile.js. But like I mentioned above, as soon as I hit F8 to skip to breakpoint it crashes with the above error. Has anybody had any success using this method to try to debug a Gruntfile? So far from my search efforts I have not found a very well documented way of doing this. So hopefully this will be useful or beneficial information for future users. Also I am using Windows 7 by the way. Thanks in advance.

UPDATE:

I have tried the following suggested by @dylants with no luck so far.

Found the grunt.cmd file on windows machine located in C:\Users\khollenbeck\AppData\Roaming\npm. Opened up grunt.cmd file and found the following....

This lead me to C:\Users\khollenbeck\AppData\Roaming\npm\node_modules\grunt-cli\bin which contained a file called grunt. And from there at the top of the file. I changed this code #!/usr/bin/env node to #!/usr/bin/env node --debug-brk

After doing this command node-inspector C:\path\to\gruntfile grunt I got the following.

Node Inspector v0.7.3
 Visit http://localhost:8080/debug?port=5858 to start debugging

Next I ran the grunt command from grunt dir. (leaving the server running in original command prompt)

From here I expected Gruntfile.js to show up in the source of chrome dev tools. I also expected to be able to set breakpoints from there. This did not happen. Instead it just ran all the way through the Gruntfile without breaking or loading in the browser.

Edit:

Ah, I see what I did wrong. For some reason I did node --debug-brk
  with out adding the path
  C:\Users\khollenbeck\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt.
  Its working now, thanks so much. I apologize for dragging this on for
  so long. But hopefully this will be useful for other windows users in
  the future.

答:
In the newer Node versions (starting from 6.3 I think), there's an in-built debugger/inspector:

https://nodejs.org/en/docs/inspector/

Just start your Grunt app like this (on Windows):

```<code>node --inspect %APPDATA%\npm\node_modules\grunt-cli\bin\grunt
</code>```

If you install the Chrome extension Node Inspector Manager, the DevTools will open automatically.

Otherwise, you can open chrome://inspect and connect to the debugging session manually.

Body:
So I have spent the past couple days trying to get this to work with no luck. Most of the solutions I have found seem to work "okay" for debugging node applications. But I haven't had much luck debugging grunt stand alone. I would like to be able to set breakpoints in my gruntfile and either step through the code with either the browser or an IDE.

I have tried the following:

Debugging using intelliJ IDE Using Grunt Console (Process finished with exit code 6)

Debugging with Nodeeclipse (This sort of works okay but doesn't hit the breakpoints set in eclipse, not very intuitive)

Debugging using node-inspector (This one also sort of works. I can step through a little ways using F11 and F10 in chrome. But eventually it just crashes. Using F8 to skip to break point never works.)

ERROR MESSAGE USING NODE-INSPECTOR

So currently node-inspector feels like it has gotten me the closest to what I want. To get here I did the following:

From my grunt directory I ran the following commands:

grunt node-inspector
node --debug-brk Gruntfile.js

And then from there I went to localhost:8080/debug?port=5858 to debug my Gruntfile.js. But like I mentioned above, as soon as I hit F8 to skip to breakpoint it crashes with the above error. Has anybody had any success using this method to try to debug a Gruntfile? So far from my search efforts I have not found a very well documented way of doing this. So hopefully this will be useful or beneficial information for future users. Also I am using Windows 7 by the way. Thanks in advance.

UPDATE:

I have tried the following suggested by @dylants with no luck so far.

Found the grunt.cmd file on windows machine located in C:\Users\khollenbeck\AppData\Roaming\npm. Opened up grunt.cmd file and found the following....

This lead me to C:\Users\khollenbeck\AppData\Roaming\npm\node_modules\grunt-cli\bin which contained a file called grunt. And from there at the top of the file. I changed this code #!/usr/bin/env node to #!/usr/bin/env node --debug-brk

After doing this command node-inspector C:\path\to\gruntfile grunt I got the following.

Node Inspector v0.7.3
 Visit http://localhost:8080/debug?port=5858 to start debugging

Next I ran the grunt command from grunt dir. (leaving the server running in original command prompt)

From here I expected Gruntfile.js to show up in the source of chrome dev tools. I also expected to be able to set breakpoints from there. This did not happen. Instead it just ran all the way through the Gruntfile without breaking or loading in the browser.

Edit:

Ah, I see what I did wrong. For some reason I did node --debug-brk
  with out adding the path
  C:\Users\khollenbeck\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt.
  Its working now, thanks so much. I apologize for dragging this on for
  so long. But hopefully this will be useful for other windows users in
  the future.

Body:
In the newer Node versions (starting from 6.3 I think), there's an in-built debugger/inspector:

https://nodejs.org/en/docs/inspector/

Just start your Grunt app like this (on Windows):

node --inspect %APPDATA%\npm\node_modules\grunt-cli\bin\grunt

If you install the Chrome extension Node Inspector Manager, the DevTools will open automatically.

Otherwise, you can open chrome://inspect and connect to the debugging session manually.


问:
migrate to react-router v4
I try to migrate to the react-router v4, where should I start? For most paths I need authentication and redicert.  I  installed last react-router-dom@next and react-router@next. Now when user is not login redirect to login page,
also I have login-callback, but have an error
WebSocket connection to 'ws://localhost:9998/sockjs-node/472/gnanejj3/websocket' failed: WebSocket is closed before the connection is established.

application.js

```<code>      import React, {Component} from 'react'
import {connect} from 'react-redux'
import {IntlProvider} from 'react-intl'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import getMuiTheme from 'material-ui/styles/getMuiTheme'

import theme from './theme'

import * as AuthActions from './actions/auth'
import Routes from './routes'

export class Application extends Component {
    static propTypes = {
        locale: React.PropTypes.string.isRequired,
        messages: React.PropTypes.objectOf(React.PropTypes.string.isRequired).isRequired,
        login: React.PropTypes.func.isRequired,
        redirectToLoginPage: React.PropTypes.func.isRequired,
        isLoggedIn: React.PropTypes.bool.isRequired,
    };

    render = () =>
        <IntlProvider locale={this.props.locale} messages={this.props.messages}>
            <MuiThemeProvider muiTheme={getMuiTheme(theme)}>
                <Routes />
            </MuiThemeProvider>
        </IntlProvider>;
}

export default Application
</code>```

routes.js:

```<code>import React from 'react'
import {connect} from 'react-redux'
import {BrowserRouter, Route, Link ,Redirect, withRouter, Switch} from 'react-router-dom'

import Root from './components/root'
import Home from './components/homePage'
import Devices from './components/devices'
import Users from './components/users'
import AddOrEditUser from './components/users/addOrEdit'
import Plans from './components/plans'
import ServerSettings from './components/settings'
import About from './components/aboutPage'
import Patients from './components/patients'
import AddOrEditPatient from './components/patients/addOrEdit'
import Commissioning from './components/commissioning'
import * as AuthActions from './actions/auth'
import redirectToLoginPage from './api/auth'

const Routes = ({isLoggedIn, redirectToLoginPage, login}) =>
    <BrowserRouter>
        <Switch>
            <Route path='/' render={({location}) => {
                if (!isLoggedIn)
                    redirectToLoginPage()
                return (
                    <Root>
                        <Switch>
                            <Route path='/home' component={Home} />
                            <Route path='/devices' component={Devices} />
                            <Route path='/users' component={Users} />
                            <Route path='/users/add' component={AddOrEditUser}/>
                            <Route path='/users/edit/:personId' component={AddOrEditUser}/>

                            <Patients path='/patients' render={() =>
                                    <Switch>
                                        <Route path='/add' component={AddOrEditPatient} />
                                        <Route path='/edit/:personId' component={AddOrEditPatient} />
                                    </Switch>
                                }
                            />

                            <Route path='/plans' component={Plans} />
                            <Route path='/commissioning' component={Commissioning} />
                            <Route path='/server-settings' component={ServerSettings} />
                            <Route path='/about' component={About} />
                        </Switch>
                    </Root>)
            }}
            />
            <Route path='/login-callback' render={() => {
                if (isLoggedIn)
                    login()
                return <Root />
            }}
            />
        </Switch>
    </BrowserRouter>

Routes.propTypes = {
    // authenticate: React.PropTypes.func.isRequired,
    // processLoginCallback: React.PropTypes.func.isRequired,
    login: React.PropTypes.func.isRequired,
    redirectToLoginPage: React.PropTypes.func.isRequired,
    isLoggedIn: React.PropTypes.bool.isRequired,
}

export const mapDispatchToProps = dispatch => ({
    login: () => dispatch(AuthActions.login()),
    redirectToLoginPage: () => dispatch(AuthActions.redirectToLoginPage()),
})

export const mapStateToProps = state => ({
    isLoggedIn: state.auth.isLoggedIn,
    locale: state.intl.locale,
    messages: state.intl.messages,
})

export default connect(mapStateToProps, mapDispatchToProps)(Routes)
</code>```

答:
That's a complex question for which a StackOverflow response box is too limiting. I've written a lengthy migration guide. If you're comfortable with react-router v2:v3, this will be a good resource for your migration:

https://medium.com/@francoisz/react-router-v4-unofficial-migration-guide-5a370b8905a

Title: migrate to react-router v4

Body:
I try to migrate to the react-router v4, where should I start? For most paths I need authentication and redicert.  I  installed last react-router-dom@next and react-router@next. Now when user is not login redirect to login page,
also I have login-callback, but have an error
WebSocket connection to 'ws://localhost:9998/sockjs-node/472/gnanejj3/websocket' failed: WebSocket is closed before the connection is established.

application.js

      import React, {Component} from 'react'
import {connect} from 'react-redux'
import {IntlProvider} from 'react-intl'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import getMuiTheme from 'material-ui/styles/getMuiTheme'

import theme from './theme'

import * as AuthActions from './actions/auth'
import Routes from './routes'

export class Application extends Component {
    static propTypes = {
        locale: React.PropTypes.string.isRequired,
        messages: React.PropTypes.objectOf(React.PropTypes.string.isRequired).isRequired,
        login: React.PropTypes.func.isRequired,
        redirectToLoginPage: React.PropTypes.func.isRequired,
        isLoggedIn: React.PropTypes.bool.isRequired,
    };

    render = () =>
        <IntlProvider locale={this.props.locale} messages={this.props.messages}>
            <MuiThemeProvider muiTheme={getMuiTheme(theme)}>
                <Routes />
            </MuiThemeProvider>
        </IntlProvider>;
}

export default Application

routes.js:

import React from 'react'
import {connect} from 'react-redux'
import {BrowserRouter, Route, Link ,Redirect, withRouter, Switch} from 'react-router-dom'

import Root from './components/root'
import Home from './components/homePage'
import Devices from './components/devices'
import Users from './components/users'
import AddOrEditUser from './components/users/addOrEdit'
import Plans from './components/plans'
import ServerSettings from './components/settings'
import About from './components/aboutPage'
import Patients from './components/patients'
import AddOrEditPatient from './components/patients/addOrEdit'
import Commissioning from './components/commissioning'
import * as AuthActions from './actions/auth'
import redirectToLoginPage from './api/auth'

const Routes = ({isLoggedIn, redirectToLoginPage, login}) =>
    <BrowserRouter>
        <Switch>
            <Route path='/' render={({location}) => {
                if (!isLoggedIn)
                    redirectToLoginPage()
                return (
                    <Root>
                        <Switch>
                            <Route path='/home' component={Home} />
                            <Route path='/devices' component={Devices} />
                            <Route path='/users' component={Users} />
                            <Route path='/users/add' component={AddOrEditUser}/>
                            <Route path='/users/edit/:personId' component={AddOrEditUser}/>

                            <Patients path='/patients' render={() =>
                                    <Switch>
                                        <Route path='/add' component={AddOrEditPatient} />
                                        <Route path='/edit/:personId' component={AddOrEditPatient} />
                                    </Switch>
                                }
                            />

                            <Route path='/plans' component={Plans} />
                            <Route path='/commissioning' component={Commissioning} />
                            <Route path='/server-settings' component={ServerSettings} />
                            <Route path='/about' component={About} />
                        </Switch>
                    </Root>)
            }}
            />
            <Route path='/login-callback' render={() => {
                if (isLoggedIn)
                    login()
                return <Root />
            }}
            />
        </Switch>
    </BrowserRouter>

Routes.propTypes = {
    // authenticate: React.PropTypes.func.isRequired,
    // processLoginCallback: React.PropTypes.func.isRequired,
    login: React.PropTypes.func.isRequired,
    redirectToLoginPage: React.PropTypes.func.isRequired,
    isLoggedIn: React.PropTypes.bool.isRequired,
}

export const mapDispatchToProps = dispatch => ({
    login: () => dispatch(AuthActions.login()),
    redirectToLoginPage: () => dispatch(AuthActions.redirectToLoginPage()),
})

export const mapStateToProps = state => ({
    isLoggedIn: state.auth.isLoggedIn,
    locale: state.intl.locale,
    messages: state.intl.messages,
})

export default connect(mapStateToProps, mapDispatchToProps)(Routes)


问:
making line between 2 text regular
I have a class which has login /signup text. The text font-style is italic. I am wondering how I can make the line (|) between "login" and "sign up" regular but keep the remaining text italic. Also, can we get this by keeping the three things (login, |, Sign Up) in the same class?

At this moment, all three of things (login, |, Sign Up) are italic. The HTML and CSS codes which I have used are:

li.login-signup {
  font-style: italic;
  font-size: 12px;
  font-family: Adelle PE;
  letter-spacing: .30em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="login-signup">Log In | Sign up</li></code>```

答:
May I suggest the following:

.login-signup {
  list-style: none;
  font-style: italic;
  font-size: 12px;
  font-family: Adelle PE;
  letter-spacing: .30em;
}

.login-signup li {
  float: left;
  padding: 0.1em 0.8em;
}

.login-signup li:first-child {
  border-right: 1px solid #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="login-signup">
    <li>Log In</li>
    <li>Sign up</li>
</ul></code>```

Using two
 elements, as you seem to have two navigational options (even if they happen to do the same at the moment)

Using CSS (border-right) instead of content ("|") for the separator

This improves your markup semantically and gives you more flexibility regarding styling.

Title: making line between 2 text regular

Body:
I have a class which has login /signup text. The text font-style is italic. I am wondering how I can make the line (|) between "login" and "sign up" regular but keep the remaining text italic. Also, can we get this by keeping the three things (login, |, Sign Up) in the same class?

At this moment, all three of things (login, |, Sign Up) are italic. The HTML and CSS codes which I have used are:

li.login-signup {
  font-style: italic;
  font-size: 12px;
  font-family: Adelle PE;
  letter-spacing: .30em;
}

Log In | Sign up

Body:
May I suggest the following:

.login-signup {
  list-style: none;
  font-style: italic;
  font-size: 12px;
  font-family: Adelle PE;
  letter-spacing: .30em;
}

.login-signup li {
  float: left;
  padding: 0.1em 0.8em;
}

.login-signup li:first-child {
  border-right: 1px solid #000;
}

<ul class="login-signup">
    <li>Log In</li>
    <li>Sign up</li>
</ul>

Using two <li> elements, as you seem to have two navigational options (even if they happen to do the same at the moment)

Using CSS (border-right) instead of content ("|") for the separator

This improves your markup semantically and gives you more flexibility regarding styling.