问:
JAVA - SCANNER to get user input
I have the following block code:

```<code>    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }
</code>```

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

```<code>Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next
</code>```

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

答:
First thing: You need to move both scanner initialization line and its close() method outside the loop.

Second thing: In the checking condition add fF to let your program exit loop if one of these letters are typed while (!scanner.hasNext("[YyNnFf]")).

```<code>public static void main(String[] args) {
    boolean run = true;
    Scanner scanner = new Scanner(System.in);
    while (run) {
        // do something
        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNnFf]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f")) {
            run = false;
        }
    }
    scanner.close();
}
</code>```

Title: JAVA - SCANNER to get user input

Body:
I have the following block code:

    boolean run = true;
    while (run) {
        Scanner scanner = new Scanner(System.in);
        // do something

        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNn]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f"))
            run = false;

        scanner.close();
    }

I want to perform something until the user types 'N'.
Currently, I'm able to run the while loop only one time.
The second time I'm not able to type my choice and I have the following error:

Another action? [Y/N]     <--- here no chance to type choice
Incorrect input
java.util.NoSuchElementException
    at java.util.Scanner.throwFor
    at java.util.Scanner.next

What is wrong?
Thanks

EDIT: I think my problem is in "do something". It is in turn a sequence of user input where i close the scanner.

Body:
First thing: You need to move both scanner initialization line and its close() method outside the loop.

Second thing: In the checking condition add fF to let your program exit loop if one of these letters are typed while (!scanner.hasNext("[YyNnFf]")).

public static void main(String[] args) {
    boolean run = true;
    Scanner scanner = new Scanner(System.in);
    while (run) {
        // do something
        System.out.println("Another action? [Y/N]");
        while (!scanner.hasNext("[YyNnFf]")) {
            System.out.println("Incorrect input");
            scanner.next();
        }
        String choice = scanner.next();
        if (choice.toLowerCase().equals("f")) {
            run = false;
        }
    }
    scanner.close();
}


来源: stackexchange

问:
How to call on destroy() method without being called onPause & onStop
I want to call onDestroy() method without calling other method of lifecycle apart from onCreate() method.

答:
You need to call finish() in your onCreate() method

void finish ()

Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

ContentLicense: CC BY-SA 3.0


问:
Synchronous way of handling asynchronous function, two level deep
I am looping over an array to update its values using returned value from called function which internally calls an asynchronous function.

I need to handle asynchronous function in synchronous way which is not being directly called. This is replication of scenario.

```<code>function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

async function delayIncrease(value){
    var choice = await condition();

    if(choice) { return ++value; }
    else { return --value; }
}

// Start calling functions
dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i]);
}
</code>```

If possible, I would like to have the solution in above structure mentioned.

I have achieved the desired result by adding other function and passing "index" + "new_value" as parameters. This function directly modifies original array and produces desired result. Working example.

```<code>function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

function delayIncrease(value, index){
    condition().then(
        function(){ updateData(++value, index) },
        function(){ updateData(--value, index) }
    )
}

function updateData(value, index){
    dataArr[index] = value;
}

dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i], i);
}
</code>```

Please provide solution for this requirement in best possible way. Possible solution in Angular 4 way is also appriciated. I thought of writing it in normal JavaScript form as Observables behave nearly same.

I followed this Medium page and http://exploringjs.com

答:
Your condition function does not really fulfill the promise with either true or false, it does randomly fulfill or reject the promise. Instead of branching on a boolean, you will need to catch that "error":

```<code>async function delayIncrease(value) {
    try {
        await condition();
        return ++value;
    } catch(e) {
        return --value;
    }
}
</code>```

Body:
I am looping over an array to update its values using returned value from called function which internally calls an asynchronous function.

I need to handle asynchronous function in synchronous way which is not being directly called. This is replication of scenario.

function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

async function delayIncrease(value){
    var choice = await condition();

    if(choice) { return ++value; }
    else { return --value; }
}

// Start calling functions
dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i]);
}

If possible, I would like to have the solution in above structure mentioned.

I have achieved the desired result by adding other function and passing "index" + "new_value" as parameters. This function directly modifies original array and produces desired result. Working example.

function condition(){
    // Code of this function is not accessible to me.
    return new Promise(function(resolve, reject){
        setTimeout(function(){
            if(parseInt(Math.random() * 100) % 2){
                resolve(true);
            }
            else{
                reject(false)
            }
        }, 1000)
    });
}

function delayIncrease(value, index){
    condition().then(
        function(){ updateData(++value, index) },
        function(){ updateData(--value, index) }
    )
}

function updateData(value, index){
    dataArr[index] = value;
}

dataArr = [1,2,3,4,5];
for(var i in dataArr){
    dataArr[i] = delayIncrease(dataArr[i], i);
}

Please provide solution for this requirement in best possible way. Possible solution in Angular 4 way is also appriciated. I thought of writing it in normal JavaScript form as Observables behave nearly same.

I followed this Medium page and http://exploringjs.com

Body:
Your condition function does not really fulfill the promise with either true or false, it does randomly fulfill or reject the promise. Instead of branching on a boolean, you will need to catch that "error":

async function delayIncrease(value) {
    try {
        await condition();
        return ++value;
    } catch(e) {
        return --value;
    }
}


问:
Removing outer parentheses of a string not working
I am trying to search a string with a value and then get the value I want and then search for it again until I find nothing else.

All did run well until a part of my code where i remove the outer parentheses of my string does not execute what I want. It does not give an error, it simply does nothing.

To summarize:

valGrep = "lights"

SecVal = "#define lights()(broad())"

What I'm trying to do is set TempGrep = broad(), but until the end of the function it is still (broad()) , the parentheses still exists.

This is my code. I put comment 'This is the part where it does not work - on the line not working

```<code>Sub SearchExt()

Dim FirstAddress As String
Dim MyArr As Variant
Dim Rng As Range
Dim Rcount As Long
Dim I As Long
Dim TempGrep As String

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Fill in the search Value
MyArr = Array(valGrep)

With Sheets("Extension").UsedRange

    Rcount = 0

    For I = LBound(MyArr) To UBound(MyArr)

        ' If you use LookIn:=xlValues it will also work with a
        ' formula cell that evaluates to tmpAnaly
        ' Note : I use xlPart in this example and not xlWhole
        Set Rng = .Find(What:=MyArr(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            FirstAddress = Rng.Address
            SecVal = Rng.Value
                ' get grep result
                TempGrep = Trim(Replace(SecVal, valGrep, " "))
                If InStr(SecVal, "#define") <> 0 Then
                    TempGrep = Trim(Replace(TempGrep, "#define", " "))
                End If
                ' Delete comment
                If InStr(1, TempGrep, "/*") <> 0 Then
                    TempGrep = Left(TempGrep, InStr(1, TempGrep, "/*") - 1)
                End If
                ' When type is included
                If InStr(1, TempGrep, "U1") <> 0 Or InStr(1, TempGrep, "U2") <> 0 Or InStr(1, TempGrep, "U4") <> 0 Or _
                InStr(1, TempGrep, "S1") <> 0 Or InStr(1, TempGrep, "S2") <> 0 Or InStr(1, TempGrep, "S4") <> 0 Then
                    searchFlg = False

                End If
                If InStr(1, TempGrep, " ") <> 0 Then
                    TempGrep = Trim(Replace(TempGrep, " ", ""))
                End If

                ' Edit the Grep result and get the value in parentheses
                TempGrep = Mid(TempGrep, 2, Len(TempGrep) - 2) 'This is the part where it does not work

                ' In the case of forced type conversion
                If InStr(1, TempGrep, "U1)") <> 0 Or InStr(1, TempGrep, "U2)") <> 0 Or InStr(1, TempGrep, "U4)") <> 0 Or InStr(1, TempGrep, "S1)") <> 0 Or _
                InStr(1, TempGrep, "S2)") <> 0 Or InStr(1, TempGrep, "S4)") <> 0 Then
                    TempGrep = Right(TempGrep, Len(TempGrep) - InStr(1, TempGrep, ")"))
                End If

            Do
                Rcount = Rcount + 1

                valGrep = TempGrep

                Set Rng = .FindNext(Rng)
            Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
        End If
    Next I
End With

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub
</code>```

答:
@jsotola should receive credit if he posts an answer, as he is the one who solved the issue. This post is only meant to expand on the solution to the underlying problem.

As pointed out in comments by jsotola and verified by OP, the problem is invisible characters.

Your code already uses the trim function, which removes surplus spaces at the start and end of the given string. But this function doesn't affect spaces in the middle of a string or non-printable characters.

Using the clean function however, is a good way to remove a good part of non-printables (note that it won't remove all of them). To access it, you'll use WorksheetFunction.Clean(string)

If you have other invisible characters, like unicode characters not covered by clean, there's no native way to handle these in Excel 2013 at least. Some time ago I had a similar problem and hacked together a very ugly and un-optimized (but fully functional) solution:

```<code>Function cleanSpecialCharacters(str As String)
    Dim spaceChars As String, bannedChars As String
    bannedChars = Chr(127) & "," & Chr(129) & "," & Chr(141) & "," & Chr(143) & "," & Chr(144) & "," & Chr(157) & "," & Chr(160)
    Application.ScreenUpdating = False

    spaceChars = Chr(32) & Chr(32)

    Dim tVal As String, bChar As Variant
    tVal = str

    tVal = Application.WorksheetFunction.Clean(tVal)
    tVal = Application.WorksheetFunction.Trim(tVal)

    For Each bChar In Split(bannedChars, ",")
        tVal = Replace(tVal, bChar, "")
    Next

    tVal = Replace(tVal, spaceChars, Chr(32), 1)

    cleanSpecialCharacters = tVal
    Application.ScreenUpdating = True
End Function
</code>```

Usage: TempGrep = cleanSpecialCharacters(TempGrep)

Should be easy enough to modify if you have any other needs.

Body:
I am trying to search a string with a value and then get the value I want and then search for it again until I find nothing else.

All did run well until a part of my code where i remove the outer parentheses of my string does not execute what I want. It does not give an error, it simply does nothing.

To summarize:

valGrep = "lights"

SecVal = "#define lights()(broad())"

What I'm trying to do is set TempGrep = broad(), but until the end of the function it is still (broad()) , the parentheses still exists.

This is my code. I put comment 'This is the part where it does not work - on the line not working

Sub SearchExt()

Dim FirstAddress As String
Dim MyArr As Variant
Dim Rng As Range
Dim Rcount As Long
Dim I As Long
Dim TempGrep As String

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

' Fill in the search Value
MyArr = Array(valGrep)

With Sheets("Extension").UsedRange

    Rcount = 0

    For I = LBound(MyArr) To UBound(MyArr)

        ' If you use LookIn:=xlValues it will also work with a
        ' formula cell that evaluates to tmpAnaly
        ' Note : I use xlPart in this example and not xlWhole
        Set Rng = .Find(What:=MyArr(I), _
                        After:=.Cells(.Cells.Count), _
                        LookIn:=xlFormulas, _
                        LookAt:=xlPart, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlNext, _
                        MatchCase:=False)
        If Not Rng Is Nothing Then
            FirstAddress = Rng.Address
            SecVal = Rng.Value
                ' get grep result
                TempGrep = Trim(Replace(SecVal, valGrep, " "))
                If InStr(SecVal, "#define") <> 0 Then
                    TempGrep = Trim(Replace(TempGrep, "#define", " "))
                End If
                ' Delete comment
                If InStr(1, TempGrep, "/*") <> 0 Then
                    TempGrep = Left(TempGrep, InStr(1, TempGrep, "/*") - 1)
                End If
                ' When type is included
                If InStr(1, TempGrep, "U1") <> 0 Or InStr(1, TempGrep, "U2") <> 0 Or InStr(1, TempGrep, "U4") <> 0 Or _
                InStr(1, TempGrep, "S1") <> 0 Or InStr(1, TempGrep, "S2") <> 0 Or InStr(1, TempGrep, "S4") <> 0 Then
                    searchFlg = False

                End If
                If InStr(1, TempGrep, " ") <> 0 Then
                    TempGrep = Trim(Replace(TempGrep, " ", ""))
                End If

                ' Edit the Grep result and get the value in parentheses
                TempGrep = Mid(TempGrep, 2, Len(TempGrep) - 2) 'This is the part where it does not work

                ' In the case of forced type conversion
                If InStr(1, TempGrep, "U1)") <> 0 Or InStr(1, TempGrep, "U2)") <> 0 Or InStr(1, TempGrep, "U4)") <> 0 Or InStr(1, TempGrep, "S1)") <> 0 Or _
                InStr(1, TempGrep, "S2)") <> 0 Or InStr(1, TempGrep, "S4)") <> 0 Then
                    TempGrep = Right(TempGrep, Len(TempGrep) - InStr(1, TempGrep, ")"))
                End If

            Do
                Rcount = Rcount + 1

                valGrep = TempGrep

                Set Rng = .FindNext(Rng)
            Loop While Not Rng Is Nothing And Rng.Address <> FirstAddress
        End If
    Next I
End With

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub

Body:
@jsotola should receive credit if he posts an answer, as he is the one who solved the issue. This post is only meant to expand on the solution to the underlying problem.

As pointed out in comments by jsotola and verified by OP, the problem is invisible characters.

Your code already uses the trim function, which removes surplus spaces at the start and end of the given string. But this function doesn't affect spaces in the middle of a string or non-printable characters.

Using the clean function however, is a good way to remove a good part of non-printables (note that it won't remove all of them). To access it, you'll use WorksheetFunction.Clean(string)

If you have other invisible characters, like unicode characters not covered by clean, there's no native way to handle these in Excel 2013 at least. Some time ago I had a similar problem and hacked together a very ugly and un-optimized (but fully functional) solution:

Function cleanSpecialCharacters(str As String)
    Dim spaceChars As String, bannedChars As String
    bannedChars = Chr(127) & "," & Chr(129) & "," & Chr(141) & "," & Chr(143) & "," & Chr(144) & "," & Chr(157) & "," & Chr(160)
    Application.ScreenUpdating = False

    spaceChars = Chr(32) & Chr(32)

    Dim tVal As String, bChar As Variant
    tVal = str

    tVal = Application.WorksheetFunction.Clean(tVal)
    tVal = Application.WorksheetFunction.Trim(tVal)

    For Each bChar In Split(bannedChars, ",")
        tVal = Replace(tVal, bChar, "")
    Next

    tVal = Replace(tVal, spaceChars, Chr(32), 1)

    cleanSpecialCharacters = tVal
    Application.ScreenUpdating = True
End Function

Usage: TempGrep = cleanSpecialCharacters(TempGrep)

Should be easy enough to modify if you have any other needs.


问:
Do users have problems adopting Silverlight?
My group is thinking about switching our platform for web UI from ASP.net to Silverlight for several reasons. To be clear, these are business websites that provide a service to our users, we develop and host them ourselves.

Has anyone switched their business / intranet web site from a traditional server-based web technology such as ASP.net to Silverlight? Or have you added Silverlight to your website? If so...

Have your users complained or resisted installing Silverlight?

Have any significant number of users been unable to install Silverlight?

Have they commented on the look or responsiveness of Silverlight UI?

What other comments have they had?

In short, are my web site's users gonna freak if I start using Silverlight on my page?

If your answer is "It depends" then please give an idea of what the determining factors are.

As an aside, is there an easy way to detect how many of your users install / have already installed Silverlight?

Edit:

Thanks for the answers so far! I may be reaching, but has anyone yet had concrete experience with deploying a Silverlight app?  I was wondering if anyone had gone through this and if their users had any major issues.

答:
I'm not sure whether with "business web UI platform" you refer to your own website or to some web application you are selling.

If you mean your own website, I agree with Samuel that you will
currently limit your user base as not
many "ordinary users" have
Silverlight installed yet.

If you
are talking about a software you're
selling, I think the most important
fact to take into regard is whether
your clients will find it problematic
that they have to roll out software
(the Silverlight framework) in comparison to buying an application that they only need to install on the server. We also had this discussion in my company (whether to switch from ASP.net with lots of JavaScript code on the client to either Silverlight or Flex), and we didn't do it because we thought the customers will not like that extra deployment effort. In addition, users (e.g. working in a bank, insurenace company etc.) are not allowed to install browser plug-ins due to company policies, so you would have a harder time selling to such clients when Silverlight is required.

Edit: Actually the fact that users who are surfing from their workplace are often not allowed to install browser plug-ins applies to both scenarios. It seems that an ever increasing number of employers put strict poicies into place where users can only use the software that is preinstalled or on a "whitelist", and do not have sufficient operating system rights to install anything on their own.

OwnerDisplayName: TJB

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: TJB

OwnerDisplayName: ISW

LastEditorDisplayName: ISW


问:
I want to send a push notification IOS, hub azure
I have an azure notification hub built for Android. And I'm building for IOS.

These are the data I need to send in the notification, they are already sent to Android:

```<code>// Android payload
            JObject data = new JObject();

            data.Add("Id", notification.Id);
            data.Add("Descricao", notification.Descricao);
            data.Add("Tipo", notification.Tipo);
            data.Add("Id_usuario", notification.Id_usuario);
            //data.Add("Informacao", notification.Informacao);
            data.Add("Informacao", notification.Informacao);
            data.Add("Status", notification.Status);
</code>```

How to put this data to push notifications for IOS?

```<code>var apnsNotification = "{\"aps\":{\"alert\":\"" + "Some Title"+": " + "\"}}";
</code>```

答:
This method works for me:</p>

```<code>public static async void sendPushNotificationApns(ApiController controller, DataObjects.Notification notification)
{
    // Get the settings for the server project.
    HttpConfiguration config = controller.Configuration;

    MobileAppSettingsDictionary settings =
        controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

    // Get the Notification Hubs credentials for the Mobile App.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

    // Create a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

    var apnsNotification = "{\"aps\":{\"alert\":\"" + notification.Descricao + "\"},\"Id\":\"" + notification.Id +
        "\",\"Tipo\":\"" + notification.Tipo + "\",\"Id_usuario\":\"" + notification.Id_usuario +
        "\",\"Informacao\":\"" + notification.Informacao +
        "\",\"Status\":\"" + notification.Status + "\"}";

    try
    {
        // Send the push notification and log the results.
        String tag = "_UserId:" + notification.Id_usuario;
        var result = await hub.SendAppleNativeNotificationAsync(apnsNotification, tag);

        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
    }
}
</code>```

Body:
I have an azure notification hub built for Android. And I'm building for IOS.

These are the data I need to send in the notification, they are already sent to Android:

// Android payload
            JObject data = new JObject();

            data.Add("Id", notification.Id);
            data.Add("Descricao", notification.Descricao);
            data.Add("Tipo", notification.Tipo);
            data.Add("Id_usuario", notification.Id_usuario);
            //data.Add("Informacao", notification.Informacao);
            data.Add("Informacao", notification.Informacao);
            data.Add("Status", notification.Status);

How to put this data to push notifications for IOS?

var apnsNotification = "{\"aps\":{\"alert\":\"" + "Some Title"+": " + "\"}}";

Body:
This method works for me:

public static async void sendPushNotificationApns(ApiController controller, DataObjects.Notification notification)
{
    // Get the settings for the server project.
    HttpConfiguration config = controller.Configuration;

    MobileAppSettingsDictionary settings =
        controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();

    // Get the Notification Hubs credentials for the Mobile App.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;

    // Create a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

    var apnsNotification = "{\"aps\":{\"alert\":\"" + notification.Descricao + "\"},\"Id\":\"" + notification.Id +
        "\",\"Tipo\":\"" + notification.Tipo + "\",\"Id_usuario\":\"" + notification.Id_usuario +
        "\",\"Informacao\":\"" + notification.Informacao +
        "\",\"Status\":\"" + notification.Status + "\"}";

    try
    {
        // Send the push notification and log the results.
        String tag = "_UserId:" + notification.Id_usuario;
        var result = await hub.SendAppleNativeNotificationAsync(apnsNotification, tag);

        // Write the success result to the logs.
        config.Services.GetTraceWriter().Info(result.State.ToString());
    }
    catch (System.Exception ex)
    {
        // Write the failure result to the logs.
        config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
    }
}

ContentLicense: CC BY-SA 4.0


问:
Function to get data type of class member
I want a function which accepts the class member name and returns its type.

For e.g.

there is a class A

```<code>class A {
    private String fieldOne;
    private String fieldTwo;
    private Integer fieldThree;
    private Integer fieldFour;

}
</code>```

I need to write a function which accepts one of the above fileds name and returns its corresponding data type. like if I pass "fieldFour" it should return Integer as type. How can I write such a function. Thank you.

答:
You got to use reflection. E.g.</p>

```<code>A.class.getDeclaredField("fieldOne").getType()
</code>```

Body:
I want a function which accepts the class member name and returns its type.

For e.g.

there is a class A

class A {
    private String fieldOne;
    private String fieldTwo;
    private Integer fieldThree;
    private Integer fieldFour;

}

I need to write a function which accepts one of the above fileds name and returns its corresponding data type. like if I pass "fieldFour" it should return Integer as type. How can I write such a function. Thank you.

Body:
You got to use reflection. E.g.

A.class.getDeclaredField("fieldOne").getType()


问:
Netlogo: move turtles in a planned way and visualize their paths
I need some help here on a crucial topic in my master's thesis.

Imagine 2 types of turtles, turtle cars and houses turtles.
So the turtle cars are placed in a specific region of the world and the turtle houses are placed at random.

The main objective is for turtle cars to visit all the houses and return to the starting position.

Example of a case study:
2 cars and 5 houses

So imagine that I define the following route vector:
route: [0 2 3 1 4, 5 5 6 5 6]

in the first part are placed randomly the houses to visit, then the respective car that will make the visit, ie the car 5 visits the homes 0 2 and 1 and the car 6 visits the house 3 and 4.

I use the IDs of each turtles, depending on the total number of turtles used.
That is, using a given route vector, my cars could automatically be viewed to visit all their respective houses (in the order they are inserted into the vector, as explained above).

My question is, knowing the vector route, how do I make the car choose where to go and return to the starting point.

If someone can help me, I really appreciate it.

答:
Here is some code to take an input route-vector and create a route for each car. The pairing of the car and house is taken from NetLogo: How to filter a list using a criterion which refers on a corresponding list?. This is the form with the clearest interpretation, if you can construct the filter version from that answer, it would be more elegant.

```<code>globals [ route-vector ]
breed [cars car]
cars-own [ route ]

to setup
  clear-all
  set route-vector [ 5 10 15 20 25 0 1 2 0 1 ]
  create-turtles 3 [ setxy random-xcor random-ycor ]
  make-routes
  reset-ticks
end

to make-routes
  let houses sublist route-vector 0 (length route-vector / 2 )
  let carlist sublist route-vector (length route-vector / 2 ) (length route-vector)
  ask cars [ set route [] ]
  (foreach carlist houses
    [ [the-car the-house] ->
      ask cars with [who = the-car] [ set route lput the-house route ]
    ]
  )
end
</code>```

Please ask a separate question about using the route variable to actually move along the path. But make an attempt to do it yourself so you can show your code and describe what needs to be fixed.

Body:
Here is some code to take an input route-vector and create a route for each car. The pairing of the car and house is taken from NetLogo: How to filter a list using a criterion which refers on a corresponding list?. This is the form with the clearest interpretation, if you can construct the filter version from that answer, it would be more elegant.

globals [ route-vector ]
breed [cars car]
cars-own [ route ]

to setup
  clear-all
  set route-vector [ 5 10 15 20 25 0 1 2 0 1 ]
  create-turtles 3 [ setxy random-xcor random-ycor ]
  make-routes
  reset-ticks
end

to make-routes
  let houses sublist route-vector 0 (length route-vector / 2 )
  let carlist sublist route-vector (length route-vector / 2 ) (length route-vector)
  ask cars [ set route [] ]
  (foreach carlist houses
    [ [the-car the-house] ->
      ask cars with [who = the-car] [ set route lput the-house route ]
    ]
  )
end

Please ask a separate question about using the route variable to actually move along the path. But make an attempt to do it yourself so you can show your code and describe what needs to be fixed.


问:
Checking a voucher code on a Demandware online store
I'm working for a startup and we have a customer who uses Demandware for their online store.

Our company provides vouchers which are worth a specific amount of money. So customers on the retail site can enter the voucher number near the end of the checkout experience and if it's worth, say, 10 dollars, their shopping cart is updated (-10).

I have the CTO saying we just need to "drop a few lines of javascript" onto the retailer online store. But I think this requires a Demandware plugin (especially updating a shopping cart), which involves signing up for a developer or partnership account (which takes some time), learning Demand Script and building the plugin, then releasing it to Saleforce's app store. Am I correct? Is this the only way to achieve this?

Just to be clear, the functionality is: the voucher code box needs to take a voucher number, an API request is made to our service to check what it's worth, then update the cart.

答:
That's a pretty broad question but I'll try to explain.

First off, Demandware has gone all JavaScript.
But yeah, it has a huge API so the process sounds about right the way you've described it.

Ask your client whether they have a service integrator they're working with, because that would be their job. Your job would be to provide an API so that Demandware can check whether the voucher code is valid.

Demandware is a closed community so it's unlikely to learn it unless you're working in a company that is doing Demandware development.

Oh, and if it somehow ends up being your job to develop this, a tip from me - you probably need to get access to their site's files and use the LineItemCtnr class to createPriceAdjustment() :)


问:
MySQL and R, inserting more than 1000 rows at a time
I'm using R to insert a data.frame into a MySQL database. I have this code below that inserts 1000 rows at a time successfully. However, it's not practical if I have a data.frame with tens of thousands of rows. How would you do a bulk insert using R? is it even possible? </p>

```<code>## R and MySQL
library(RMySQL)

### create sql connection object
mydb = dbConnect(MySQL(), dbname="db", user='xxx', password='yyy', host='localhost', unix.sock="/Applications/MAMP/mysql/mysql.sock")

# get data ready for mysql
df = data.format

# chunks
df1 <- df[1:1000,]
df2 <- df[1001:2000,]
df3 <- df[2001:nrow(df),]

## SQL insert for data.frame, limit 1000 rows
dbWriteTable(mydb, "table_name", df1, append=TRUE, row.names=FALSE)
dbWriteTable(mydb, "table_name", df2, append=TRUE, row.names=FALSE)
dbWriteTable(mydb, "table_name", df3, append=TRUE, row.names=FALSE)
</code>```

答:
For completeness, as the link suggests, write the df to a temp table and insert into the destination table as follows:</p>

```<code>dbWriteTable(mydb, name = 'temp_table', value = df, row.names = F, append = F)
dbGetQuery(mydb, "insert into table select * from temp_table")
</code>```

Body:
I'm using R to insert a data.frame into a MySQL database. I have this code below that inserts 1000 rows at a time successfully. However, it's not practical if I have a data.frame with tens of thousands of rows. How would you do a bulk insert using R? is it even possible?

## R and MySQL
library(RMySQL)

### create sql connection object
mydb = dbConnect(MySQL(), dbname="db", user='xxx', password='yyy', host='localhost', unix.sock="/Applications/MAMP/mysql/mysql.sock")

# get data ready for mysql
df = data.format

# chunks
df1 <- df[1:1000,]
df2 <- df[1001:2000,]
df3 <- df[2001:nrow(df),]

## SQL insert for data.frame, limit 1000 rows
dbWriteTable(mydb, "table_name", df1, append=TRUE, row.names=FALSE)
dbWriteTable(mydb, "table_name", df2, append=TRUE, row.names=FALSE)
dbWriteTable(mydb, "table_name", df3, append=TRUE, row.names=FALSE)

Body:
For completeness, as the link suggests, write the df to a temp table and insert into the destination table as follows:

dbWriteTable(mydb, name = 'temp_table', value = df, row.names = F, append = F)
dbGetQuery(mydb, "insert into table select * from temp_table")


问:
search in POP-UP LOV in APEX 5
Good day guys,
   I just want to know if the search in a pop-up LOV in ORACLE ApEx 5 does a "query search" directly to the database or does it search in the results shown in the pop-up?TIA</p>

答: It performs a database query.  You can verify this by using the browser's Inspect tool, Network tab and see the server request and response.</p>

Title: search in POP-UP LOV in APEX 5


问:
AttributeError with Django Rest nested serializer
I'm following the Django Rest documentation for writing nested serializer but it is giving me attribute error.

Here are my models:

```<code>class Objects(TimeStampModel):
    projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE)
    object_name = models.CharField(max_length=50)
    object_description = models.TextField()
    object_main_table = models.CharField(max_length=50)
    object_primary_key = models.CharField(max_length=50)
    object_age_field = models.CharField(max_length=50)
    date_format = models.CharField(max_length=50)

    def __str__(self):
        return self.object_name

class ObjectDefinition(TimeStampModel):
    ATTRIBUTE = 'Attribute'
    RELATION = 'Relation'
    TYPE_CHOICES = (
        (ATTRIBUTE, 'Attribute'),
        (RELATION, 'Relation'),
    )
    obj = models.ForeignKey(Objects,related_name='obj_def',on_delete=models.CASCADE)
    from_table = models.CharField(max_length=50)
    from_table_field = models.CharField(max_length=50)
    to_table = models.CharField(max_length=50)
    to_table_field = models.CharField(max_length=50)
    relation_type = models.CharField(max_length=50,choices=TYPE_CHOICES)
    relation_sequence = models.CharField(max_length=50)
    value_field = models.CharField(max_length=50, blank=True, null=True)
</code>```

Here is my serializers.py snippet:

```<code>class ObjectDefinitionSerializer(serializers.ModelSerializer):

    class Meta:
        model = ObjectDefinition
        fields = ('from_table','from_table_field','to_table','to_table_field','relation_type','value_field')

class ObjectSerializer(serializers.ModelSerializer):
    definition = ObjectDefinitionSerializer(many=True)
    object_description = serializers.CharField(required=False, allow_null=True, allow_blank=True
        )

    class Meta:
        model = Objects
        fields = ('projects','object_name','object_description','object_main_table','object_primary_key','object_age_field','date_format','definition')

    def validate(self, data, *args, **kwargs):
        date_format = data.get('date_format')
        if date_format not in ['YYYYMMDD', 'DDMMYYYY']:
            msg = ('Date format is incorrect')
            raise serializers.ValidationError({'error_msg': msg})
        return super(ObjectSerializer, self).validate(data, *args, **kwargs)

    def create(self, validated_data):
        definition_data = validated_data.pop('definition')
        obj = Objects.objects.create(**validated_data)
        for data in definition_data:
            ObjectDefinition.objects.create(obj=obj, **data)
        return obj
</code>```

My views.py:

```<code>class CreateObject(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = ObjectSerializer
</code>```

After hitting POST, objects.create works fine for both the models but at return obj, it throws me this error:

Exception Value:

Got AttributeError when attempting to get a value for field definition on serializer ObjectSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Objects instance.
Original exception text was: 'Objects' object has no attribute 'definition'.

What am I missing?

答:
The ObjectDefinition.obj's related_name is obj_def which doesn't match your serializer.

You can fix that by providing the source argument:

```<code>definition = ObjectDefinitionSerializer(source='obj_def', many=True)
</code>```

Body:
I'm following the Django Rest documentation for writing nested serializer but it is giving me attribute error.

Here are my models:

class Objects(TimeStampModel):
    projects = models.ForeignKey(Projects,related_name='proj_obj',on_delete=models.CASCADE)
    object_name = models.CharField(max_length=50)
    object_description = models.TextField()
    object_main_table = models.CharField(max_length=50)
    object_primary_key = models.CharField(max_length=50)
    object_age_field = models.CharField(max_length=50)
    date_format = models.CharField(max_length=50)

    def __str__(self):
        return self.object_name

class ObjectDefinition(TimeStampModel):
    ATTRIBUTE = 'Attribute'
    RELATION = 'Relation'
    TYPE_CHOICES = (
        (ATTRIBUTE, 'Attribute'),
        (RELATION, 'Relation'),
    )
    obj = models.ForeignKey(Objects,related_name='obj_def',on_delete=models.CASCADE)
    from_table = models.CharField(max_length=50)
    from_table_field = models.CharField(max_length=50)
    to_table = models.CharField(max_length=50)
    to_table_field = models.CharField(max_length=50)
    relation_type = models.CharField(max_length=50,choices=TYPE_CHOICES)
    relation_sequence = models.CharField(max_length=50)
    value_field = models.CharField(max_length=50, blank=True, null=True)

Here is my serializers.py snippet:

class ObjectDefinitionSerializer(serializers.ModelSerializer):

    class Meta:
        model = ObjectDefinition
        fields = ('from_table','from_table_field','to_table','to_table_field','relation_type','value_field')

class ObjectSerializer(serializers.ModelSerializer):
    definition = ObjectDefinitionSerializer(many=True)
    object_description = serializers.CharField(required=False, allow_null=True, allow_blank=True
        )

    class Meta:
        model = Objects
        fields = ('projects','object_name','object_description','object_main_table','object_primary_key','object_age_field','date_format','definition')

    def validate(self, data, *args, **kwargs):
        date_format = data.get('date_format')
        if date_format not in ['YYYYMMDD', 'DDMMYYYY']:
            msg = ('Date format is incorrect')
            raise serializers.ValidationError({'error_msg': msg})
        return super(ObjectSerializer, self).validate(data, *args, **kwargs)

    def create(self, validated_data):
        definition_data = validated_data.pop('definition')
        obj = Objects.objects.create(**validated_data)
        for data in definition_data:
            ObjectDefinition.objects.create(obj=obj, **data)
        return obj

My views.py:

class CreateObject(CreateAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = ObjectSerializer

After hitting POST, objects.create works fine for both the models but at return obj, it throws me this error:

Exception Value:

Got AttributeError when attempting to get a value for field definition on serializer ObjectSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Objects instance.
Original exception text was: 'Objects' object has no attribute 'definition'.

What am I missing?

Body:
The ObjectDefinition.obj's related_name is obj_def which doesn't match your serializer.

You can fix that by providing the source argument:

definition = ObjectDefinitionSerializer(source='obj_def', many=True)


问:
Closing a RandomAccessFile sometimes takes exactly 45 seconds
In my program, closing a java.util.RandomAccessFile sometimes takes exactly 45 seconds (well, almost exactly: between 44.998 and 45.003 seconds). The program creates and closes lots of small files. Usually closing the file is very quick (between 0 and 0.1 seconds). If I debug the program, it's stuck in the native method RandomAccessFile.close0.

The same problem also occurs when using FileOutputStream instead of RandomAccessFile (in which case the program is blocked in the native method FileOutputStream.close0).

Has somebody an idea what that could be? Can you reproduce the problem on your system (I can reproduce it only on a Mac, not on Windows XP; I didn't test yet on Linux)?

Update 2:

This only seems to happend on Mac OS X. I use JDK 1.6.0_22-b04. It happens on both 32-bit and 64-bit. On Windows XP it doesn't seem to occur.

My test case is:

```<code>import java.io.File;
import java.io.RandomAccessFile;
public class TestFileClose {
    public static void main(String... args) throws Exception {
        for (int i = 0; i < 100000; i++) {
            String name = "test" + i;
            RandomAccessFile r = new RandomAccessFile(name, "rw");
            r.write(0);
            long t = System.currentTimeMillis();
            r.close();
            long close = System.currentTimeMillis() - t;
            if (close > 200) {
                System.out.println("closing " + name +
                        " took " + close + " ms!");
            }
            if (i % 2000 == 0) {
                System.out.println("test " + i + "/100000");
            }
            new File(name).delete();
        }
    }
}
</code>```

Example output on my machine:

```<code>test 0/100000
test 2000/100000
test 4000/100000
test 6000/100000
test 8000/100000
test 10000/100000
closing test10030 took 44998 ms!
test 12000/100000
test 14000/100000
test 16000/100000
closing test16930 took 44998 ms!
test 18000/100000
test 20000/100000
</code>```

答:
In my case, it turned out to be McAfee antivirus installed on my machine. I had to install it (company policy)...

The problem also showed up if I disabled the on-access scan.

Body:
In my program, closing a java.util.RandomAccessFile sometimes takes exactly 45 seconds (well, almost exactly: between 44.998 and 45.003 seconds). The program creates and closes lots of small files. Usually closing the file is very quick (between 0 and 0.1 seconds). If I debug the program, it's stuck in the native method RandomAccessFile.close0.

The same problem also occurs when using FileOutputStream instead of RandomAccessFile (in which case the program is blocked in the native method FileOutputStream.close0).

Has somebody an idea what that could be? Can you reproduce the problem on your system (I can reproduce it only on a Mac, not on Windows XP; I didn't test yet on Linux)?

Update 2:

This only seems to happend on Mac OS X. I use JDK 1.6.0_22-b04. It happens on both 32-bit and 64-bit. On Windows XP it doesn't seem to occur.

My test case is:

import java.io.File;
import java.io.RandomAccessFile;
public class TestFileClose {
    public static void main(String... args) throws Exception {
        for (int i = 0; i < 100000; i++) {
            String name = "test" + i;
            RandomAccessFile r = new RandomAccessFile(name, "rw");
            r.write(0);
            long t = System.currentTimeMillis();
            r.close();
            long close = System.currentTimeMillis() - t;
            if (close > 200) {
                System.out.println("closing " + name +
                        " took " + close + " ms!");
            }
            if (i % 2000 == 0) {
                System.out.println("test " + i + "/100000");
            }
            new File(name).delete();
        }
    }
}

Example output on my machine:

test 0/100000
test 2000/100000
test 4000/100000
test 6000/100000
test 8000/100000
test 10000/100000
closing test10030 took 44998 ms!
test 12000/100000
test 14000/100000
test 16000/100000
closing test16930 took 44998 ms!
test 18000/100000
test 20000/100000


问:
How to check for changes in form controls using Angular5
Im using reactive forms, I have multiple inputs, I want display a single error for de three inputs, the validatons are; fields are required and blank spaces should not be entered.

component.html:

```<code>    <form [formGroup]="contratoForm" class="campo-form">
        <div class="campoFormulario">
            <label class="etiquetaFormulario" for="txtCodigoContrato">Código contrato</label>
            <div style="display:inline-block; position: relative;"  class="control">
                <input [formControl]="txtCodigoContrato" type="text" id="txtCodigoContrato" name="txtCodigoContrato" class="cajaTexto ancho80" />
                <span>/</span>
            </div>
            <div style="display:inline-block; position: relative;" class="control">
                <input [formControl]="txtCodigoContrato2" type="text" id="txtCodigoContrato2" name="txtCodigoContrato2" class="cajaTexto ancho80" />
            </div>
        </div>
        <div class="campoFormulario">
            <label class="etiquetaFormulario" for="txtContrato">Contrato</label>
            <div style="display:inline-block; position: relative;" class="control">
                <input [formControl]="txtContrato" type="text" id="txtContrato" name="txtContrato" class="cajaTexto ancho350" />

            </div>
        </div>
         <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty || txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') || txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty || txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') || txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched)) && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

            <span>check the fields in red, they are required</span>
        </div>
        <div class="buttons">
            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                <span class="glyphicon glyphicon-off"></span> Cancel
            </button>

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                <span class="glyphicon glyphicon-trash"></span> Clean
            </button>
            <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                <span class="glyphicon glyphicon-floppy-disk"></span> Save
            </button>
        </div>
    </form>
</code>```

component.ts:

```<code>    import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
    import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl} from '@angular/forms';
    import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';

    @Component({
        selector: 'app-formulario-contrato',
        templateUrl: './contrato.component.html',
        styleUrls: ['./contrato.component.css']
    })
    export class FormularioContratoComponent  {

        contratoForm: FormGroup;

        constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef) {
            this.createForm();
        }

        txtCodigoContrato = new FormControl('', [
            Validators.required
            ,this.hasNotWhites
        ]);
        txtCodigoContrato2 = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);
        txtContrato = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);

        createForm() {
            this.contratoForm = this.formBuilder.group({
                txtCodigoContrato: this.txtCodigoContrato
                ,txtCodigoContrato2: this.txtCodigoContrato2
                ,txtContrato: this.txtContrato
            });
        }

        hasNotWhites(fieldControl: FormControl) {
            if (fieldControl.value.trim() != '') {
                return null
            }
            else {
               return { hasWhites: true };
            }
        }

        ngAfterViewChecked() {
            this.cdRef.detectChanges();
        }

        limpiar() {
        }

        onClick() {
            return null;
        }
</code>```

component.css:

```<code>/* some stuff...*/
:host /deep/ .control input.ng-invalid.ng-touched {
  border-color: #ff8080;
}
</code>```

The validations work correctly, that is, they jump when the field stays empty or when I enter blank spaces. My problem is that I have to add more form controls and the if it contains the message can be made illegible:

```<code>  <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty ||
  txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') ||
  txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty ||
  txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') ||
  txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched))
  && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">
</code>```

Is there any way to control these values by typescript, that is, each time a value in the control changes it is controlled by a function in typeScript that returns true or false and if only ask for the value of that function in my div?

答:
You can do something like

```<code>this.contratoForm.valueChanges.subscribe(value = > //do something)
</code>```

If you want you can add a map function before to get just the values from the form you care about that are changing

```<code>this.contratoForm.valueChanges
.map(values => values.txtCodigoContrato)
.subscribe(txtCodigoContrato = > //do something)
</code>```

Body:
Im using reactive forms, I have multiple inputs, I want display a single error for de three inputs, the validatons are; fields are required and blank spaces should not be entered.

component.html:

    <form [formGroup]="contratoForm" class="campo-form">

            Código contrato

                <input [formControl]="txtCodigoContrato" type="text" id="txtCodigoContrato" name="txtCodigoContrato" class="cajaTexto ancho80" />
                /

                <input [formControl]="txtCodigoContrato2" type="text" id="txtCodigoContrato2" name="txtCodigoContrato2" class="cajaTexto ancho80" />

            Contrato

                <input [formControl]="txtContrato" type="text" id="txtContrato" name="txtContrato" class="cajaTexto ancho350" />

         <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty || txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') || txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty || txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') || txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched)) && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

            check the fields in red, they are required

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="onCloseLink()">
                 Cancel
            </button>

            <button class="btn btn-primary boton" type="button" style="float:right;" (click)="limpiar()">
                 Clean
            </button>
            <button type="submit" [disabled]="!contratoForm.valid" class="btn btn-primary boton" style="float:right;" (click)="onClick()">
                 Save
            </button>

    </form>

component.ts:

    import { Component, HostBinding, OnDestroy, OnInit, Input, Output, EventEmitter, ElementRef, NgModule, ViewChild, ChangeDetectorRef  } from '@angular/core';
    import { Validators, FormBuilder, FormControl, FormGroup, AbstractControl} from '@angular/forms';
    import { AfterViewChecked } from '@angular/core/src/metadata/lifecycle_hooks';

    @Component({
        selector: 'app-formulario-contrato',
        templateUrl: './contrato.component.html',
        styleUrls: ['./contrato.component.css']
    })
    export class FormularioContratoComponent  {

        contratoForm: FormGroup;

        constructor(private elRef: ElementRef, private formBuilder: FormBuilder, private cdRef: ChangeDetectorRef) {
            this.createForm();
        }

        txtCodigoContrato = new FormControl('', [
            Validators.required
            ,this.hasNotWhites
        ]);
        txtCodigoContrato2 = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);
        txtContrato = new FormControl('', [
            Validators.required
            , this.hasNotWhites
        ]);

        createForm() {
            this.contratoForm = this.formBuilder.group({
                txtCodigoContrato: this.txtCodigoContrato
                ,txtCodigoContrato2: this.txtCodigoContrato2
                ,txtContrato: this.txtContrato
            });
        }

        hasNotWhites(fieldControl: FormControl) {
            if (fieldControl.value.trim() != '') {
                return null
            }
            else {
               return { hasWhites: true };
            }
        }

        ngAfterViewChecked() {
            this.cdRef.detectChanges();
        }

        limpiar() {
        }

        onClick() {
            return null;
        }

component.css:

/* some stuff...*/
:host /deep/ .control input.ng-invalid.ng-touched {
  border-color: #ff8080;
}

The validations work correctly, that is, they jump when the field stays empty or when I enter blank spaces. My problem is that I have to add more form controls and the if it contains the message can be made illegible:

  <div *ngIf="((!txtCodigoContrato.valid && (txtCodigoContrato.dirty ||
  txtCodigoContrato.touched)) && (txtCodigoContrato.hasError('required') ||
  txtCodigoContrato.hasError('hasWhites')))
                ||
                ((!txtCodigoContrato2.valid && (txtCodigoContrato2.dirty ||
  txtCodigoContrato2.touched)) && (txtCodigoContrato2.hasError('required') ||
  txtCodigoContrato2.hasError('hasWhites')))
                ||
         ((!txtContrato.valid && (txtContrato.dirty || txtContrato.touched))
  && (txtContrato.hasError('required') || txtContrato.hasError('hasWhites')))
                ">

Is there any way to control these values by typescript, that is, each time a value in the control changes it is controlled by a function in typeScript that returns true or false and if only ask for the value of that function in my div?

Body:
You can do something like

this.contratoForm.valueChanges.subscribe(value = > //do something)

If you want you can add a map function before to get just the values from the form you care about that are changing

this.contratoForm.valueChanges
.map(values => values.txtCodigoContrato)
.subscribe(txtCodigoContrato = > //do something)


问:
Get centroids from datapoints in pandas DF for each group
i have a dataframe

```<code>id    code    lat    long
1      100    22.6    42.3
1      200    23.6    45.3
1      400    21.6    46.3
2      300    22.6    42.3
2      500    22.6    42.3
2      800    22.6    42.3
3      100    22.6    42.3
</code>```

i want to find the centre points grouping on id column,
and return a dataframe :

```<code>id    centre_lat   centre_long
1      xx.xx        yy.yy
2      xx.xx        yy.yy
3      xx.xx        yy.yy
</code>```

Since id 3 has only 1 code, therefore the same lat long is the centroid for that id.

Body:
i have a dataframe

id    code    lat    long
1      100    22.6    42.3
1      200    23.6    45.3
1      400    21.6    46.3
2      300    22.6    42.3
2      500    22.6    42.3
2      800    22.6    42.3
3      100    22.6    42.3

i want to find the centre points grouping on id column,
and return a dataframe :

id    centre_lat   centre_long
1      xx.xx        yy.yy
2      xx.xx        yy.yy
3      xx.xx        yy.yy

Since id 3 has only 1 code, therefore the same lat long is the centroid for that id.

Body:
IIUC:

In [136]: df.groupby('id', as_index=False)['lat','long'].mean()
Out[136]:
   id   lat       long
0   1  22.6  44.633333
1   2  22.6  42.300000
2   3  22.6  42.300000


问:
at WebSocket.socket.onerror in LiveQueryClient.js when start app
I have a problem with my small demo for live query as in attached image.

To be honest, I have no idea why does it go wrong. Try to find some solutions around but not yet successfully. Please give me some ideas or solutions if you know this issue. Thanks so much.

Parse server example: 1.4.0

Parse JS SDK: 1.10.2

NodeJS: 8.9.1

npm: 5.5.1

P/S: I have added classes for supporting by Live Query already.

Here is the source which run successfully without using Live Query

Link to src with removed parse link:

```<code>var Parse = require('parse/node');

Parse.initialize("shetei5aeJ9Aequi6deejojiv7foh6Hieg2eesh9keingohw");
Parse.serverURL = 'serURLhere';

var Node = Parse.Object.extend('Node');
var q = new Parse.Query('Node');
var subscription = q.subscribe();

var procEventOpen = () => {
    console.log('subscription opened...');
};

subscription.on('open', procEventOpen);
</code>```

答:
This happened to me when I had a typo in server url.
Try to explicit specify liveQueryServerURL parameter:

```<code>Parse.liveQueryServerURL = 'ws://yourserverurl/parse';
</code>```

Note the ws instead of http(s)

Body:
I have a problem with my small demo for live query as in attached image.

To be honest, I have no idea why does it go wrong. Try to find some solutions around but not yet successfully. Please give me some ideas or solutions if you know this issue. Thanks so much.

Parse server example: 1.4.0

Parse JS SDK: 1.10.2

NodeJS: 8.9.1

npm: 5.5.1

P/S: I have added classes for supporting by Live Query already.

Here is the source which run successfully without using Live Query

Link to src with removed parse link:

var Parse = require('parse/node');

Parse.initialize("shetei5aeJ9Aequi6deejojiv7foh6Hieg2eesh9keingohw");
Parse.serverURL = 'serURLhere';

var Node = Parse.Object.extend('Node');
var q = new Parse.Query('Node');
var subscription = q.subscribe();

var procEventOpen = () => {
    console.log('subscription opened...');
};

subscription.on('open', procEventOpen);

Body:
This happened to me when I had a typo in server url.
Try to explicit specify liveQueryServerURL parameter:

Parse.liveQueryServerURL = 'ws://yourserverurl/parse';

Note the ws instead of http(s)


问:
php get value out of array with quotes

Hello! I have a few SQL statements and I need to split them, I need the first image tag that occurs in the statement, I have the code for it to split it, but the problem being all of the different quotes. Is there a way to get it out out?

Code I have now:

```<code>$array = array('INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120333,139,'Champ Cars 2007','champ-cars-2007','<table style=width: 429px; height: 74px height=74 width=429 border=0><tbody><tr><td><img title=champcar_logo_2007.jpg style=width: 200px; height: 79px height=79 alt=champcar_logo_2007.jpg hspace=5 src=images/stories/Store/champcar_logo_2007.jpg width=200 align=left vspace=5 border=0 /></td><td><div align=justify>Exclusieve toegangskaarten alleen hier te koop! Wilt u tijdens het evenement op 2 september aanwezig zijn? kijk in mijn <a class=undefined href=index.php?option=com_content&task=view&id=94&Itemid=>shop</a> en bestel snel!</div></td></tr></tbody></table><hr />','',0,8,'2007-08-10 16:21:48',367,'','2008-04-17 15:09:13',367,0,'0000-00-00 00:00:00','2007-08-10 00:00:00','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,0,'{"robots":"","author":"","rights":"","xreference":""}');,/* INSERT QUERY */INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120444,140,'Nieuwe helmen voor Nik en Koen','nieuwe-helmen-voor-nik-en-koen','<table border=0> <tbody> <tr> <td valign=top><img style=margin: 0px; width: 200px; height: 124px; border: 0px solid #000000; float: left; src=images/stories/Nieuws/helmen.jpg alt=helmen.jpg title=helmen.jpg height=124 width=200 /></td> <td valign=top>Speciaal uit Amerika zijn afgelopen winter twee nieuwe IRL Bell T6 Interceptors overgevlogen. Samen met de hoofdsponsor Eurogrip en Marcel Brouwers van Tjello Creations</td> </tr> </tbody> </table>','<p>is dit design tot stand gekomen en uiteindelijk super mooi gespoten op de helmen!<br /><br /></p>',1,8,'2008-04-17 15:08:48',367,'','2012-06-20 11:37:19',367,0,'0000-00-00 00:00:00','2008-04-17 14:23:23','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,2088,'{"robots":"","author":"","rights":"","xreference":""}');');

foreach($array as $item) {

$split = preg_split('/src=/', $item);
$split = explode(' ', $split[1]);

echo $split[0] . "\n";
}
</code>```

I have a few statements in a array:

```<code>INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120333,139,'Champ Cars 2007','champ-cars-2007','<table style=width: 429px; height: 74px height=74 width=429 border=0><tbody><tr><td><img title=champcar_logo_2007.jpg style=width: 200px; height: 79px height=79 alt=champcar_logo_2007.jpg hspace=5 src=images/stories/Store/champcar_logo_2007.jpg width=200 align=left vspace=5 border=0 /></td><td><div align=justify>Exclusieve toegangskaarten alleen hier te koop! Wilt u tijdens het evenement op 2 september aanwezig zijn? kijk in mijn <a class=undefined href=index.php?option=com_content&task=view&id=94&Itemid=>shop</a> en bestel snel!</div></td></tr></tbody></table><hr />','',0,8,'2007-08-10 16:21:48',367,'','2008-04-17 15:09:13',367,0,'0000-00-00 00:00:00','2007-08-10 00:00:00','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,0,'{"robots":"","author":"","rights":"","xreference":""}');,/* INSERT QUERY */
INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120444,140,'Nieuwe helme en en','nieuwe-helmn','<table border=0> <tbody> <tr> <td valign=top><img style=margin: 0px; width: 200px; height: 124px; border: 0px solid #000000; float: left; src=images/stories/Nieuws/helmen.jpg alt=helmen.jpg title=helmen.jpg height=124 width=200 /></td> <td valign=top>Speciaal uit Amerika zijn afgelopen winter twee niIRL Bell T6 Interceptors overgevlogen. Samen met de hoofip en Mers van Tjeions</td> </tr> </tbody> </table>','<p>is dit design tot stand gekomen en uiteindelijk super mooi gespoten op de helmen!<br /><br /></p>',1,8,'2008-04-17 15:08:48',367,'','2012-06-20 11:37:19',367,0,'0000-00-00 00:00:00','2008-04-17 14:23:23','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,2088,'{"robots":"","author":"","rights":"","xreference":""}');
</code>```

I just want

```<code><img style=margin: 0px; width: 200px; height: 124px; border: 0px solid #000000; float: left; src=images/stories/Nieuws/helmen.jpg alt=helmen.jpg title=helmen.jpg height=124 width=200 />
</code>```

I am getting now is errors because of the quotes that won't resemble a correct string, anyone know a way to do this?

答:
Parsing SQL is not trivial. (It's not hard either.) If this is a one-off job, you might get away with a few regex to pull out what you want. Otherwise you need to use a parser.

Regex /]+>/ will extract image tags. It will fail on a variety of edge cases so don't rely on this and verify the output. And you don't need PHP for this:

```<code>egrep -o '<img[^>]+>' < old_db.sql
</code>```

This is really putting the cart before the horse.  Why not use the tool intended for the job: Mysql? Run the inserts, then query the data. Done. If you don't have mysql handy, try sqlite. It looks like it should be able to read your SQL.

Title: php get value out of array with quotes

Body:
Hello! I have a few SQL statements and I need to split them, I need the first image tag that occurs in the statement, I have the code for it to split it, but the problem being all of the different quotes. Is there a way to get it out out?

Code I have now:

$array = array('INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120333,139,'Champ Cars 2007','champ-cars-2007','

Exclusieve toegangskaarten alleen hier te koop! Wilt u tijdens het evenement op 2 september aanwezig zijn? kijk in mijn shop en bestel snel!

','',0,8,'2007-08-10 16:21:48',367,'','2008-04-17 15:09:13',367,0,'0000-00-00 00:00:00','2007-08-10 00:00:00','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,0,'{"robots":"","author":"","rights":"","xreference":""}');,/* INSERT QUERY */INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120444,140,'Nieuwe helmen voor Nik en Koen','nieuwe-helmen-voor-nik-en-koen','

 	 Speciaal uit Amerika zijn afgelopen winter twee nieuwe IRL Bell T6 Interceptors overgevlogen. Samen met de hoofdsponsor Eurogrip en Marcel Brouwers van Tjello Creations

','
is dit design tot stand gekomen en uiteindelijk super mooi gespoten op de helmen!

',1,8,'2008-04-17 15:08:48',367,'','2012-06-20 11:37:19',367,0,'0000-00-00 00:00:00','2008-04-17 14:23:23','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,2088,'{"robots":"","author":"","rights":"","xreference":""}');');

foreach($array as $item) {

$split = preg_split('/src=/', $item);
$split = explode(' ', $split[1]);

echo $split[0] . "\n";
}

I have a few statements in a array:

INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120333,139,'Champ Cars 2007','champ-cars-2007','

Exclusieve toegangskaarten alleen hier te koop! Wilt u tijdens het evenement op 2 september aanwezig zijn? kijk in mijn shop en bestel snel!

','',0,8,'2007-08-10 16:21:48',367,'','2008-04-17 15:09:13',367,0,'0000-00-00 00:00:00','2007-08-10 00:00:00','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,0,'{"robots":"","author":"","rights":"","xreference":""}');,/* INSERT QUERY */
INSERT INTO ba793_content(`id`,`asset_id`,`title`,`alias`,`introtext`,`fulltext`,`state`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`checked_out`,`checked_out_time`,`publish_up`,`publish_down`,`images`,`urls`,`attribs`,`access`,`hits`,`metadata`) VALUES( 120444,140,'Nieuwe helme en en','nieuwe-helmn','

 	 Speciaal uit Amerika zijn afgelopen winter twee niIRL Bell T6 Interceptors overgevlogen. Samen met de hoofip en Mers van Tjeions

','
is dit design tot stand gekomen en uiteindelijk super mooi gespoten op de helmen!

',1,8,'2008-04-17 15:08:48',367,'','2012-06-20 11:37:19',367,0,'0000-00-00 00:00:00','2008-04-17 14:23:23','0000-00-00 00:00:00','{"image_intro":"images\/headers\/zonderdeur.jpg","float_intro":"","image_intro_alt":"","image_intro_caption":"","image_fulltext":"images\/headers\/zonderdeur.jpg","float_fulltext":"","image_fulltext_alt":"","image_fulltext_caption":""}','{"urla":false,"urlatext":"","targeta":"","urlb":false,"urlbtext":"","targetb":"","urlc":false,"urlctext":"","targetc":""}','{"article_layout":"","show_title":"","link_titles":"","show_tags":"","show_intro":"","info_block_position":"","info_block_show_title":"","show_category":"","link_category":"","show_parent_category":"","link_parent_category":"","show_associations":"","show_author":"","link_author":"","show_create_date":"","show_modify_date":"","show_publish_date":"","show_item_navigation":"","show_icons":"","show_print_icon":"","show_email_icon":"","show_vote":"","show_hits":"","show_noauth":"","urls_position":"","alternative_readmore":"","article_page_title":"","show_publishing_options":"","show_article_options":"","show_urls_images_backend":"","show_urls_images_frontend":""}',1,2088,'{"robots":"","author":"","rights":"","xreference":""}');

I just want

I am getting now is errors because of the quotes that won't resemble a correct string, anyone know a way to do this?

Body:
Parsing SQL is not trivial. (It's not hard either.) If this is a one-off job, you might get away with a few regex to pull out what you want. Otherwise you need to use a parser.

Regex /<img[^>]+>/ will extract image tags. It will fail on a variety of edge cases so don't rely on this and verify the output. And you don't need PHP for this:

egrep -o '<img[^>]+>' < old_db.sql

This is really putting the cart before the horse.  Why not use the tool intended for the job: Mysql? Run the inserts, then query the data. Done. If you don't have mysql handy, try sqlite. It looks like it should be able to read your SQL.


问:
Error while pasting object from Clipboard
This is my code for copying and pasting an object to the clipboard:

```<code>private void CopyObject()
{
    Clipboard.SetData(ClipboardDataFormats.SampleData, this.SelectedSampleObject);
}

private void PasteObject()
{
    if (Clipboard.ContainsData(ClipboardDataFormats.SampleData) == true)
    {
        var sampleObject = (SampleClass)Clipboard.GetData(ClipboardDataFormats.SampleData); // exception
    }
}
</code>```

I receive following exception when I call Clipboard.GetData()

System.Runtime.InteropServices.COMException Data on clipboard is invalid.

HRESULT 0x800401D3 (CLIPBRD_E_BAD_DATA)

Maybe the reason for the error is that SelectedSampleObject is an entity framework proxy object, when calling Clipboard.SetData(). Is this possible? Do you have any other idea? Unfortunately i really don't understand this exception.

答: Not sure about this specific exception, but your code will not work with EF proxy objects anyway, because objects you put to clipboard must be serializable (for example marked with Serializable attribute), and EF proxy classes are not. You can of course disable proxy creation and mark all your entity classes with [Serialiable] but I doubt you want to do this. Instead, create some another class with only required properties, mark it with Serialiable and use that for clipboard operations. Or serialize your object to json\xml whatever yourself and set that to clipboard.

Body:
This is my code for copying and pasting an object to the clipboard:

private void CopyObject()
{
    Clipboard.SetData(ClipboardDataFormats.SampleData, this.SelectedSampleObject);
}

private void PasteObject()
{
    if (Clipboard.ContainsData(ClipboardDataFormats.SampleData) == true)
    {
        var sampleObject = (SampleClass)Clipboard.GetData(ClipboardDataFormats.SampleData); // exception
    }
}

I receive following exception when I call Clipboard.GetData()

System.Runtime.InteropServices.COMException Data on clipboard is invalid.

HRESULT 0x800401D3 (CLIPBRD_E_BAD_DATA)

Maybe the reason for the error is that SelectedSampleObject is an entity framework proxy object, when calling Clipboard.SetData(). Is this possible? Do you have any other idea? Unfortunately i really don't understand this exception.


问:
trying to use ngClass instead ngIf
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?</p>

```<code>The long Version:

 <div *ngIf="sp.outboundWeeks[i].status=='GREEN'">
                                        <div class="green">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='RED'">
                                        <div class="red">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>
                                    <div *ngIf="sp.outboundWeeks[i].status=='YELLOW'">
                                        <div class="yellow">
                                            {{sp.outboundWeeks[i].utilizationRate}}
                                        </div>
                                    </div>

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}
     </div>
</code>```

答:
Abdul Rafay solutions is nice, my solution is in my opinion more explicit and readable :)</p>

```<code><div>
   <div [class.green]=" sp.outboundWeeks[i].status=='GREEN' "
        [class.red]=" sp.outboundWeeks[i].status=='RED' "
        [class.yellow]=" sp.outboundWeeks[i].status=='YELLOW' ">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>
</code>```

Title: trying to use ngClass instead ngIf

Body:
I would rewrite this NgIf over ngClass for a shorter code. Unfortunately, the class is not accepted. Can the problem be solved?

The long Version:

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

                                            {{sp.outboundWeeks[i].utilizationRate}}

the short version should be like the code below:

[ngClass]="{'green':cw.status[i]=='GREEN','yellow':cw.status=='YELLOW','red':cw.status=='RED'}">{{cw.utilizationRate}}

Body:
Abdul Rafay solutions is nice, my solution is in my opinion more explicit and readable :)

<div>
   <div [class.green]=" sp.outboundWeeks[i].status=='GREEN' "
        [class.red]=" sp.outboundWeeks[i].status=='RED' "
        [class.yellow]=" sp.outboundWeeks[i].status=='YELLOW' ">
      {{sp.outboundWeeks[i].utilizationRate}}
   </div>
</div>


问:
NGINX redirect to AMP, wordpress pagination rules
I have an issue with nginx AMP redirect in WordPress. My code is bellow and its works fine TILL I need to change page in post at AMP version (should be viewed at mobile device or viewed as mobile in developer tool)
https://viralty.net/test222/

if you go from mobile or as mobile to that page it will work fine, but u cant go on the second page, because of rewrite rule. it will always redirect to /amp  version, but when there is second page it look like this:

https://viralty.net/test222/2/?amp

how can I manage my rewrite settings to include this as 2,3,4 page?

```<code>rewrite ^(.*(?<!/amp))/$ https://viralty.net$1/*?amp/ redirect;
</code>```

```<code>if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") {
  set $mobile_rewrite perform;
}

if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)") {
  set $mobile_rewrite perform;
}

if ($mobile_rewrite = perform) {
  rewrite ^(.*(?<!/amp))/$ https://viralty.net$1/*?amp/ redirect;

  break;
}
</code>```

答:
```<code> if ($mobile_rewrite = perform) {

 rewrite ^(.+)/+$ $1?amp break;

 }
</code>```

I have found this solution working for me, on the second page and if you go back. only not redirect from home page. so maybe someone has an idea.

Body:
I have an issue with nginx AMP redirect in WordPress. My code is bellow and its works fine TILL I need to change page in post at AMP version (should be viewed at mobile device or viewed as mobile in developer tool)
https://viralty.net/test222/

if you go from mobile or as mobile to that page it will work fine, but u cant go on the second page, because of rewrite rule. it will always redirect to /amp  version, but when there is second page it look like this:

https://viralty.net/test222/2/?amp

how can I manage my rewrite settings to include this as 2,3,4 page?

rewrite ^(.*(?<!/amp))/$ https://viralty.net$1/*?amp/ redirect;

if ($http_user_agent ~* "(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino") {
  set $mobile_rewrite perform;
}

if ($http_user_agent ~* "^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)") {
  set $mobile_rewrite perform;
}

if ($mobile_rewrite = perform) {
  rewrite ^(.*(?<!/amp))/$ https://viralty.net$1/*?amp/ redirect;

  break;
}

Body:
 if ($mobile_rewrite = perform) {

 rewrite ^(.+)/+$ $1?amp break;

 }

I have found this solution working for me, on the second page and if you go back. only not redirect from home page. so maybe someone has an idea.


问:
Is it safe to compare DOM nodes with "==="?
My prerequisite is, that I work with just one DOM and use just the DOM API like getElementById or querySelector or event references. Is it in this case safe to use the following condition

```<code>if (document.body === event.currentTarget) { }
</code>```

to check if the event has been bubbled to the body of the document?

I know that this will not work with cloned objects. But I do not clone any objects by myself. Does the the DOM API clone objects anywhere?

答:
This is not a direct answer since it has already been given but rather a reminder, in case you use jQ already in project. It might come useful to someone reading this cause it's shorter to write and fairly more powerful in ways you can use it.

Just a note, in jQuery, since 1.6 you can use is().
Lets say you have:

```<code><div id="parent">
    <p>drek</p>
    <p id="target">kmek</p>
    <div>mrr</div>
</div>
</code>```

You can compare jq select result to another:

```<code>$("#target").is($("#target"));
</code>```

You can compare it to DOM object:

```<code>$("#target").is(document.getElementById("target"));
</code>```

You can use it with callbacks cause it doesn't create new jq object:

```<code>$( "#target" ).click(function( event ) {
  var target = $( event.target );
  if ( target.is( "li" ) ) {
    target.css( "background-color", "red" );
  }
});
</code>```

You can use it on a set: (true if it matches at least one element in set):

```<code>$('#parent').children().is("p");
</code>```

Probably has a couple of other clever uses possible:
API description

Body:
My prerequisite is, that I work with just one DOM and use just the DOM API like getElementById or querySelector or event references. Is it in this case safe to use the following condition

if (document.body === event.currentTarget) { }

to check if the event has been bubbled to the body of the document?

I know that this will not work with cloned objects. But I do not clone any objects by myself. Does the the DOM API clone objects anywhere?

Body:
This is not a direct answer since it has already been given but rather a reminder, in case you use jQ already in project. It might come useful to someone reading this cause it's shorter to write and fairly more powerful in ways you can use it.

Just a note, in jQuery, since 1.6 you can use is().
Lets say you have:

<div id="parent">
    <p>drek</p>
    <p id="target">kmek</p>
    <div>mrr</div>
</div>

You can compare jq select result to another:

$("#target").is($("#target"));

You can compare it to DOM object:

$("#target").is(document.getElementById("target"));

You can use it with callbacks cause it doesn't create new jq object:

$( "#target" ).click(function( event ) {
  var target = $( event.target );
  if ( target.is( "li" ) ) {
    target.css( "background-color", "red" );
  }
});

You can use it on a set: (true if it matches at least one element in set):

$('#parent').children().is("p");

Probably has a couple of other clever uses possible:
API description