问:
Chat App - How to stop push notifications when Chat Activity is in foreground?
newbie here.

I have developed a chat app using firebase database and android studio and used firebase functions as well as firebase messaging service to send notifications to users when they receive a  new message.
Everything is working fine. My only problem is that I want to stop notifications service when the two users are already chatting (have the ChatActivity already running).

I have looked everywhere but cannot find a solution
Thanks in advance!

```<code>@Override
public void onMessageReceived( RemoteMessage remoteMessage ) {

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){

                super.onMessageReceived ( remoteMessage );

                String notification_title = remoteMessage.getData ().get ( "title" );
                String notification_message = remoteMessage.getData ().get ( "body" );

                String click_action = remoteMessage.getData ().get ( "click_action" );
                String visit_user_id = remoteMessage.getData ().get ( "from_user_id" );
                String visit_user_name = remoteMessage.getData ().get ( "userName" );

                Uri alarmSound = Uri.parse ("android.resource://"+getApplicationContext ().getPackageName()+"/"+R.raw.dog  );

                Intent resultIntent = new Intent ( click_action );
                resultIntent.putExtra ( "visit_user_id", visit_user_id );
                resultIntent.putExtra ( "userName", visit_user_name );

                PendingIntent resultPendingIntent =
                        PendingIntent.getActivity (
                                this,
                                0,
                                resultIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                OreoNotification oreoNotification = new OreoNotification ( this );

                Notification.Builder builder = oreoNotification.getOreoNotification ( notification_title, notification_message,resultPendingIntent ).setSmallIcon ( R.drawable.finalpawslogofour )
                        .setVibrate ( new long[]{500, 500} ).setAutoCancel ( true ).setSound ( alarmSound );

                int mNotificationId = ( int ) System.currentTimeMillis ();

                oreoNotification.getManager().notify ( mNotificationId, builder.build ());

        }else{

                super.onMessageReceived ( remoteMessage );

                String notification_title = remoteMessage.getData ().get ( "title" );
                String notification_message = remoteMessage.getData ().get ( "body" );

                String click_action = remoteMessage.getData ().get ( "click_action" );
                String visit_user_id = remoteMessage.getData ().get ( "from_user_id" );
                String visit_user_name = remoteMessage.getData ().get ( "userName" );

                Uri alarmSound = Uri.parse ("android.resource://"+getApplicationContext ().getPackageName()+"/"+R.raw.dog  );

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder ( this ).setSmallIcon ( R.drawable.finalpawslogofour ).setContentTitle ( notification_title ).setContentText ( notification_message )
                        .setVibrate ( new long[]{500, 500} ).setAutoCancel ( true ).setSound ( alarmSound );

                Intent resultIntent = new Intent ( click_action );
                resultIntent.putExtra ( "visit_user_id", visit_user_id );
                resultIntent.putExtra ( "userName", visit_user_name );

                PendingIntent resultPendingIntent =
                        PendingIntent.getActivity (
                                this,
                                0,
                                resultIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                mBuilder.setContentIntent ( resultPendingIntent );

                int mNotificationId = ( int ) System.currentTimeMillis ();

                NotificationManager mNotifyMgr = ( NotificationManager ) getSystemService ( NOTIFICATION_SERVICE );

                mNotifyMgr.notify ( mNotificationId, mBuilder.build ());

        }

}
</code>```

答:
As answered by Mr. Rabbit here you could implement the isAppIsBackgrounded() method in your class which extends FirebaseMessagingService:

```<code>private boolean isAppIsInBackground(Context context) {
            boolean isInBackground = true;

            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
                List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        for (String activeProcess : processInfo.pkgList) {
                            if (activeProcess.equals(context.getPackageName())) {
                                isInBackground = false;
                            }
                        }
                    }
                }
            }
            else
            {
                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                ComponentName componentInfo = taskInfo.get(0).topActivity;
                if (componentInfo.getPackageName().equals(context.getPackageName())) {
                    isInBackground = false;
                }
            }
            return isInBackground;
        }
</code>```

Another, yet crude, method would be to use  SharedPreferences to know if a ChatActivity is active or not.

Body:
newbie here.

I have developed a chat app using firebase database and android studio and used firebase functions as well as firebase messaging service to send notifications to users when they receive a  new message.
Everything is working fine. My only problem is that I want to stop notifications service when the two users are already chatting (have the ChatActivity already running).

I have looked everywhere but cannot find a solution
Thanks in advance!

@Override
public void onMessageReceived( RemoteMessage remoteMessage ) {

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){

                super.onMessageReceived ( remoteMessage );

                String notification_title = remoteMessage.getData ().get ( "title" );
                String notification_message = remoteMessage.getData ().get ( "body" );

                String click_action = remoteMessage.getData ().get ( "click_action" );
                String visit_user_id = remoteMessage.getData ().get ( "from_user_id" );
                String visit_user_name = remoteMessage.getData ().get ( "userName" );

                Uri alarmSound = Uri.parse ("android.resource://"+getApplicationContext ().getPackageName()+"/"+R.raw.dog  );

                Intent resultIntent = new Intent ( click_action );
                resultIntent.putExtra ( "visit_user_id", visit_user_id );
                resultIntent.putExtra ( "userName", visit_user_name );

                PendingIntent resultPendingIntent =
                        PendingIntent.getActivity (
                                this,
                                0,
                                resultIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                OreoNotification oreoNotification = new OreoNotification ( this );

                Notification.Builder builder = oreoNotification.getOreoNotification ( notification_title, notification_message,resultPendingIntent ).setSmallIcon ( R.drawable.finalpawslogofour )
                        .setVibrate ( new long[]{500, 500} ).setAutoCancel ( true ).setSound ( alarmSound );

                int mNotificationId = ( int ) System.currentTimeMillis ();

                oreoNotification.getManager().notify ( mNotificationId, builder.build ());

        }else{

                super.onMessageReceived ( remoteMessage );

                String notification_title = remoteMessage.getData ().get ( "title" );
                String notification_message = remoteMessage.getData ().get ( "body" );

                String click_action = remoteMessage.getData ().get ( "click_action" );
                String visit_user_id = remoteMessage.getData ().get ( "from_user_id" );
                String visit_user_name = remoteMessage.getData ().get ( "userName" );

                Uri alarmSound = Uri.parse ("android.resource://"+getApplicationContext ().getPackageName()+"/"+R.raw.dog  );

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder ( this ).setSmallIcon ( R.drawable.finalpawslogofour ).setContentTitle ( notification_title ).setContentText ( notification_message )
                        .setVibrate ( new long[]{500, 500} ).setAutoCancel ( true ).setSound ( alarmSound );

                Intent resultIntent = new Intent ( click_action );
                resultIntent.putExtra ( "visit_user_id", visit_user_id );
                resultIntent.putExtra ( "userName", visit_user_name );

                PendingIntent resultPendingIntent =
                        PendingIntent.getActivity (
                                this,
                                0,
                                resultIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT
                        );

                mBuilder.setContentIntent ( resultPendingIntent );

                int mNotificationId = ( int ) System.currentTimeMillis ();

                NotificationManager mNotifyMgr = ( NotificationManager ) getSystemService ( NOTIFICATION_SERVICE );

                mNotifyMgr.notify ( mNotificationId, mBuilder.build ());

        }

}

Body:
As answered by Mr. Rabbit here you could implement the isAppIsBackgrounded() method in your class which extends FirebaseMessagingService:

private boolean isAppIsInBackground(Context context) {
            boolean isInBackground = true;

            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
                List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
                for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        for (String activeProcess : processInfo.pkgList) {
                            if (activeProcess.equals(context.getPackageName())) {
                                isInBackground = false;
                            }
                        }
                    }
                }
            }
            else
            {
                List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                ComponentName componentInfo = taskInfo.get(0).topActivity;
                if (componentInfo.getPackageName().equals(context.getPackageName())) {
                    isInBackground = false;
                }
            }
            return isInBackground;
        }

Another, yet crude, method would be to use  SharedPreferences to know if a ChatActivity is active or not.


来源: stackexchange

问:
How to delete the first row
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

```<code>DB::table('ahah')->first()->delete().
</code>```

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

答:
ModelName: Change with your model</p>

```<code>$item = ModelName::orderBy('id', 'ASC')->first();
$item->delete();
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to delete the first row

Body:
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

DB::table('ahah')->first()->delete().

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

Body:
ModelName: Change with your model

$item = ModelName::orderBy('id', 'ASC')->first();
$item->delete();


问:
gets() problem in C
I wrote the following code:

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

答:
Always use fgets() instead of gets. Also there are lots of stuff to fix. You shouldnt use standard library functions for creating user interface. Standard library is really not designed for that. Instead you should use curses library or something similar. You could also write the program to accept arguments as input.

Short example of proper use of the standard library. This version does not have any error checking so it assumes that user input is correct.

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

int main(int artc, char *argv[])
{
    /* arguments are strings so assign only the first characte of the
     * third argument string. Remember that the first argument ( argv[0] )
     * is the name of the program.
     */
    char  mychar = argv[2][0];
    char *string = argv[1];
    int i, count = 0;

    /* count the occurences of the given character */
    for(; *string != '\0'; ++string)
        if(*string == mychar) ++count;

    printf("The char ‘%c’ appears %d times.\n", mychar, count);

    return 0;
}
</code>```

Usage: ./count "Hello, World!" l

Output: The char ‘l’ appears 3 times.

EDIT: As for the original code. Change == to !=.

```<code>for (i=0 ; (string[i] == '\0') ; i++ )
</code>```

to:

```<code>for (i=0 ; (string[i] != '\0') ; i++ )
</code>```

The comparison was wrong.

ContentLicense: CC BY-SA 3.0

Title: gets() problem in C

Body:
I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

Body:
Always use fgets() instead of gets. Also there are lots of stuff to fix. You shouldnt use standard library functions for creating user interface. Standard library is really not designed for that. Instead you should use curses library or something similar. You could also write the program to accept arguments as input.

Short example of proper use of the standard library. This version does not have any error checking so it assumes that user input is correct.

#include <stdio.h>

int main(int artc, char *argv[])
{
    /* arguments are strings so assign only the first characte of the
     * third argument string. Remember that the first argument ( argv[0] )
     * is the name of the program.
     */
    char  mychar = argv[2][0];
    char *string = argv[1];
    int i, count = 0;

    /* count the occurences of the given character */
    for(; *string != '\0'; ++string)
        if(*string == mychar) ++count;

    printf("The char ‘%c’ appears %d times.\n", mychar, count);

    return 0;
}

Usage: ./count "Hello, World!" l

Output: The char ‘l’ appears 3 times.

EDIT: As for the original code. Change == to !=.

for (i=0 ; (string[i] == '\0') ; i++ )

to:

for (i=0 ; (string[i] != '\0') ; i++ )

The comparison was wrong.


问:
How to place a static button in the bottom rigth corner?
I need to place a button in the bottom right corner of the page and make it static. It needs to keep in its place in case of scroll.

I have tried to place it vía css but i don't have enough level.

```<code><input type="button" onclick="delegar.php" id="delegar" value="Delegar">

#delegar {
    position:relative;
    rigth: 100%;
    bottom: 100%;
}
</code>```

答:
Change your CSS</p>

```<code>#delegar {
    position:fixed;
    right: 10px;
    bottom: 10px;
}
</code>```

Body:
I need to place a button in the bottom right corner of the page and make it static. It needs to keep in its place in case of scroll.

I have tried to place it vía css but i don't have enough level.

<input type="button" onclick="delegar.php" id="delegar" value="Delegar">

#delegar {
    position:relative;
    rigth: 100%;
    bottom: 100%;
}

Body:
Change your CSS

#delegar {
    position:fixed;
    right: 10px;
    bottom: 10px;
}


问:
Nested Grouping in XSLT 1.0 with multiple nodes
I am working on Grouping using XSLT 1.0 but output is not as expected.

I need to sum the quantity in MovementLine for respective Movement, but instead the sum is happening for all Movement instead.
Here the key should work for each  Movement but not for all

Source XML :

```<code>`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MovementFileFlowRequest>
    <Movement>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>129</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>50</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
</MovementFileFlowRequest>`
</code>```

XSLT :

```<code>`<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="Movements" match="MovementLine" use="concat(ArticleNumber, '|', LogisticVariety, '|' , Status)"/>

    <xsl:template match="/">
        <xsl:for-each select="MovementFileFlowRequest">

        <MovementFileFlowRequest >
            <xsl:for-each select="Movement">
                <!-- Apply "group" template to the first Record Line in group -->
                <Movement>
                    <xsl:for-each select="MovementLine[generate-id() = generate-id(key('Movements', concat(ArticleNumber, '|', LogisticVariety, '|' , Status))[1])]">
                        <xsl:variable name="Quantity" select="sum(key('Movements', concat(ArticleNumber, '|', LogisticVariety, '|' , Status))/Quantity)"/>
                        <MovementLine>
                            <xsl:copy-of select="./*[not(name()='Quantity')]"/>
                            <Quantity>
                                <xsl:value-of select="$Quantity" />
                            </Quantity>
                        </MovementLine>
                    </xsl:for-each>
                </Movement>
            </xsl:for-each>
        </MovementFileFlowRequest>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>`
</code>```

Current Output :

```<code>`<?xml version="1.0" encoding="UTF-8"?>
<MovementFileFlowRequest>
<Movement>
      <MovementLine>
         <ArticleNumber>355</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>60</Quantity>
      </MovementLine>
      <MovementLine>
         <ArticleNumber>129</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>10</Quantity>
      </MovementLine>
   </Movement>
   <Movement>
      <MovementLine>
         <ArticleNumber>359</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>20</Quantity>
      </MovementLine>
   </Movement>
   <Movement/>
</MovementFileFlowRequest>
`
</code>```

Desired Output :

```<code>`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MovementFileFlowRequest>
    <Movement>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>60</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>129</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
</MovementFileFlowRequest>`
</code>```

答: Change the key use or selection expression to include the generated id of the parent element e.g. use="concat(generated-id(..), '|', ArticleNumber, '|', LogisticVariety, '|' , Status)", make sure you adapt all expressions in the XSLT code where you use the key function as well to adapt the expression the same way.

Body:
I am working on Grouping using XSLT 1.0 but output is not as expected.

I need to sum the quantity in MovementLine for respective Movement, but instead the sum is happening for all Movement instead.
Here the key should work for each  Movement but not for all

Source XML :

`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MovementFileFlowRequest>
    <Movement>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>129</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>50</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
</MovementFileFlowRequest>`

XSLT :

`<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
    <xsl:output method="xml" indent="yes"/>
    <xsl:key name="Movements" match="MovementLine" use="concat(ArticleNumber, '|', LogisticVariety, '|' , Status)"/>

    <xsl:template match="/">
        <xsl:for-each select="MovementFileFlowRequest">

        <MovementFileFlowRequest >
            <xsl:for-each select="Movement">

                <Movement>
                    <xsl:for-each select="MovementLine[generate-id() = generate-id(key('Movements', concat(ArticleNumber, '|', LogisticVariety, '|' , Status))[1])]">
                        <xsl:variable name="Quantity" select="sum(key('Movements', concat(ArticleNumber, '|', LogisticVariety, '|' , Status))/Quantity)"/>
                        <MovementLine>
                            <xsl:copy-of select="./*[not(name()='Quantity')]"/>
                            <Quantity>
                                <xsl:value-of select="$Quantity" />
                            </Quantity>
                        </MovementLine>
                    </xsl:for-each>
                </Movement>
            </xsl:for-each>
        </MovementFileFlowRequest>
        </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>`

Current Output :

`<?xml version="1.0" encoding="UTF-8"?>
<MovementFileFlowRequest>
<Movement>
      <MovementLine>
         <ArticleNumber>355</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>60</Quantity>
      </MovementLine>
      <MovementLine>
         <ArticleNumber>129</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>10</Quantity>
      </MovementLine>
   </Movement>
   <Movement>
      <MovementLine>
         <ArticleNumber>359</ArticleNumber>
         <LogisticVariety>2</LogisticVariety>
         <Status>12</Status>
         <DateFormatted>20190516</DateFormatted>
         <Content/>
         <LineReference/>
         <Quantity>20</Quantity>
      </MovementLine>
   </Movement>
   <Movement/>
</MovementFileFlowRequest>
`

Desired Output :

`<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MovementFileFlowRequest>
    <Movement>
        <MovementLine>
            <ArticleNumber>355</ArticleNumber>
            <Quantity>60</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
        <MovementLine>
            <ArticleNumber>129</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
    <Movement>
        <MovementLine>
            <ArticleNumber>359</ArticleNumber>
            <Quantity>10</Quantity>
            <LogisticVariety>2</LogisticVariety>
            <Status>12</Status>
            <DateFormatted>20190516</DateFormatted>
            <Content/>
            <LineReference/>
        </MovementLine>
    </Movement>
</MovementFileFlowRequest>`


问:
White svg icons are not visible when background-color is black
I have two icons:

bell - icon

Setting icon

They are presented in navbar, as you can see in right corner on screenshot:

When I put on icons wrapper background color on black, that icons are not visible more.

Need help to understand why.

Check the code:

HTML CODE:

```<code><div className="container">
  <header className="header">
    <nav className="user-nav">
      <div className="user-nav-item">
        <Link href="/">
          <a className="user-nav-item-link">Overview</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/search">
          <a className="user-nav-item-link">Search</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/feed">
          <a className="user-nav-item-link">Feed</a>
        </Link>
      </div>
      <h3 className="logo">Logo</h3>
    </nav>

    <div className="user-nav-icon">
      <div className="user-nav-icon-box">
        <img src={bellIcon} alt="notify icon" />
      </div>
      <div className="user-nav-icon-box">
        <img src={settingsIcon} alt="settings icon" />
      </div>
    </div>
  </header>
</div>
</code>```

CSS CODE:

```<code>.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}
</code>```

答: Problem is with overriding SVG fill property with color property. The color property doesn't work with SVG's. Your SVG fill is black. Either use Inline SVG or create another SVG file having property fill: white.

Body:
I have two icons:

bell - icon

Setting icon

They are presented in navbar, as you can see in right corner on screenshot:

When I put on icons wrapper background color on black, that icons are not visible more.

Need help to understand why.

Check the code:

HTML CODE:

        <Link href="/">
          Overview
        </Link>

        <Link href="/search">
          Search
        </Link>

        <Link href="/feed">
          Feed
        </Link>

Logo

CSS CODE:

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}


问:
SPA RSA 2048 authentication
I am developing SPA in angular and the specific requirement from customer to use RSA 2048 for authentication. I am a bit skeptical how the authentication token would get generated.  I believe the token would generate at the server side and it's server's responsibility to verify against the encrypted credentials.

Am I wrong in my thinking? Has anyone tried with 2048 RSA authentication earlier?

答:
So this is how it will work,

Generated a public & private key using a salt key & 2048 bits.

Public key is kept within the source code to generate a cipher text.

Private key is kept on server to decrypt the cipher text.

Server will decrypt both the stored password ( already encrypted) with the login password ( encrypted).

If both decrypted cypher texts are equal , server will send the auth-key otherwise request is failed.

Title: SPA RSA 2048 authentication


问:
dojo wrapper or adapter classes
I have recently started using dojo, I was wondering if there is anyway to implement a wrapper/adapter class. In pure javascript I would do the following

```<code>function Person(name){
    this.name=name;
}

function Employee(name,ID){
    this.Person=Person;
    this.Person(name);
    this.ID=ID;

    this.PromotedEmployee=PromotedEmployee;
}

function PromotedEmployee(employees){
    this.employees=employees;  //number of people working for him/her
}

var employee=new Employee("John Stamos",123);
employee.PromotedEmployee(10);   //promote to manage 10 people
</code>```

How do I do this with dojo. Something as such does not work

```<code>dojo.declare("Person",null,{
    constructor: function(name){
        this.name=name;
    }
});

dojo.declare("PromotedEmployee",null,{
    constructor: function(employees){
        this.employees=employees;
    }
});

dojo.declare("Employee",[Person],{
    constructor: function(name,ID){
        this.ID=ID;
    },
    PromotedEmployee=PromotedEmployee;
});

var employee=new Employee("John Stamos",123);
employee.PromotedEmployee(10);   //promote to manage 10 people
</code>```

答:
```<code>dojo.declare("PromotedEmployee",null,{
    employees: 0,
    constructor: function(){

    },
    promoteEmployees: function(employees){
         this.employees = employees;
    }
});
dojo.declare("Employee",[Person],{
    constructor: function(name,ID){
        this.ID=ID;
        this.promotedEmployee = new PromotedEmployee();
    }
});

var employee=new Employee("John Stamos",123);
employee.promotedEmployee.promoteEmployees(10);
</code>```

<p>//OR</p>

```<code>dojo.declare("PromotedEmployee",null,{
        constructor: function(employees){
           this.employees = employees;
        }
    });
    dojo.declare("Employee",[Person],{
        constructor: function(name,ID,employees){
            this.ID=ID;
            this.promotedEmployee = new PromotedEmployee(employees);
        }
    });
     var employee=new Employee("John Stamos",123, 10);

//alert(employee.promotedEmployee.employees);
</code>```

Title: dojo wrapper or adapter classes

Body:
I have recently started using dojo, I was wondering if there is anyway to implement a wrapper/adapter class. In pure javascript I would do the following

function Person(name){
    this.name=name;
}

function Employee(name,ID){
    this.Person=Person;
    this.Person(name);
    this.ID=ID;

    this.PromotedEmployee=PromotedEmployee;
}

function PromotedEmployee(employees){
    this.employees=employees;  //number of people working for him/her
}

var employee=new Employee("John Stamos",123);
employee.PromotedEmployee(10);   //promote to manage 10 people

How do I do this with dojo. Something as such does not work

dojo.declare("Person",null,{
    constructor: function(name){
        this.name=name;
    }
});

dojo.declare("PromotedEmployee",null,{
    constructor: function(employees){
        this.employees=employees;
    }
});

dojo.declare("Employee",[Person],{
    constructor: function(name,ID){
        this.ID=ID;
    },
    PromotedEmployee=PromotedEmployee;
});

var employee=new Employee("John Stamos",123);
employee.PromotedEmployee(10);   //promote to manage 10 people

Body:
dojo.declare("PromotedEmployee",null,{
    employees: 0,
    constructor: function(){

    },
    promoteEmployees: function(employees){
         this.employees = employees;
    }
});
dojo.declare("Employee",[Person],{
    constructor: function(name,ID){
        this.ID=ID;
        this.promotedEmployee = new PromotedEmployee();
    }
});

var employee=new Employee("John Stamos",123);
employee.promotedEmployee.promoteEmployees(10);

//OR

dojo.declare("PromotedEmployee",null,{
        constructor: function(employees){
           this.employees = employees;
        }
    });
    dojo.declare("Employee",[Person],{
        constructor: function(name,ID,employees){
            this.ID=ID;
            this.promotedEmployee = new PromotedEmployee(employees);
        }
    });
     var employee=new Employee("John Stamos",123, 10);

//alert(employee.promotedEmployee.employees);


答:
You need to set the position of element to fixed. see example below:</p>

```<code>.fixed {
position: fixed;
bottom: 10px;
right: 10px;
}
</code>```

Title: How to place a static button in the bottom rigth corner?

Body:
You need to set the position of element to fixed. see example below:

.fixed {
position: fixed;
bottom: 10px;
right: 10px;
}


问:
Unable to read out config file while iterating
I am having trouble accessing an iterator when trying to read from a config file. My code is:

```<code>void requestPLC::write(QMap <QString, QVariant> map)
{

QMap<QString, QVariant>::iterator i;

for (i = map.begin(); i != map.end(); ++i)
    {
        mConfig->reqPLC->datatype.value(map[i]);
        // do something here
    }
}
</code>```

What I want to do is iterate over my map and pick the corresponding value from the config file. My error looks like this:

no match for ‘operator[]’ (operand types are ‘QMap’
  and ‘QMap::iterator’)
               mConfig->reqPLC->datatype.value(map[i]);
                                                     ^

I know this is caused by datatype.value(map[i]) being an iterator but I can't figure out a way to avoid this. Do I need to cast my iterator here or something?

答:
Accessing the key, value of the QMap using an iterator
can be done via the iterator class

In your case:

```<code>void requestPLC::write(QMap <QString, QVariant> map)
{

    QMap<QString, QVariant>::iterator i;

    for (i = map.begin(); i != map.end(); ++i)
    {
        auto map_value = i.value();
        mConfig->reqPLC->datatype.value(map_value);
        // do something here
    }
}
</code>```

Body:
I am having trouble accessing an iterator when trying to read from a config file. My code is:

void requestPLC::write(QMap <QString, QVariant> map)
{

QMap<QString, QVariant>::iterator i;

for (i = map.begin(); i != map.end(); ++i)
    {
        mConfig->reqPLC->datatype.value(map[i]);
        // do something here
    }
}

What I want to do is iterate over my map and pick the corresponding value from the config file. My error looks like this:

no match for ‘operator[]’ (operand types are ‘QMap’
  and ‘QMap::iterator’)
               mConfig->reqPLC->datatype.value(map[i]);
                                                     ^

I know this is caused by datatype.value(map[i]) being an iterator but I can't figure out a way to avoid this. Do I need to cast my iterator here or something?

Body:
Accessing the key, value of the QMap using an iterator
can be done via the iterator class

In your case:

void requestPLC::write(QMap <QString, QVariant> map)
{

    QMap<QString, QVariant>::iterator i;

    for (i = map.begin(); i != map.end(); ++i)
    {
        auto map_value = i.value();
        mConfig->reqPLC->datatype.value(map_value);
        // do something here
    }
}


问:
How to utilize the Django URL tag?
Sorry for such a beginner question but I have a TemplateSyntaxError on my URL line in my HTML that links to the HTML that allows user to update the article details and I cannot seem to debug it.

Below is article_detail.html where it would have a link to article_update.html

```<code>{% extends 'base.html' %}

{% block content %}

<h3>Title: {{object.title}}</h3>

<p>Caption: {{object.caption}}</p>
<p>Activeness: {{object.active}}</p>

<a href="{% url 'articleupdate' id:article_id %}">Update this Article</a>

{% endblock %}
</code>```

In the views.py, I have created an article_update_view function as seen below

```<code>def article_update_view(request, article_id):
    obj = get_object_or_404(Article, id=article_id)
    form = ArticleForm(request.POST or None, instance=obj)
    if form.is_valid():
        form.save()
        form = ArticleForm()
    context = {
        'form': form
    }
    return render(request, 'article_update.html', context)
</code>```

and in my app.urls.py, I have written

```<code>urlpatterns = [
    path('<int:article_id>/update/', article_update_view, name='articleupdate'),
]
</code>```

答:
Your issue is the way you're passing the object id.

template.html

{% extends 'base.html' %}

{% block content %}

Title: {{object.title}}

Caption: {{object.caption}}

Activeness: {{object.active}}

Update this Article # or object.article_id

{% endblock %}
```

Title: How to utilize the Django URL tag?

Body:
Sorry for such a beginner question but I have a TemplateSyntaxError on my URL line in my HTML that links to the HTML that allows user to update the article details and I cannot seem to debug it.

Below is article_detail.html where it would have a link to article_update.html

{% extends 'base.html' %}

{% block content %}

Title: {{object.title}}

Caption: {{object.caption}}

Activeness: {{object.active}}

Update this Article

{% endblock %}

In the views.py, I have created an article_update_view function as seen below

def article_update_view(request, article_id):
    obj = get_object_or_404(Article, id=article_id)
    form = ArticleForm(request.POST or None, instance=obj)
    if form.is_valid():
        form.save()
        form = ArticleForm()
    context = {
        'form': form
    }
    return render(request, 'article_update.html', context)

and in my app.urls.py, I have written

urlpatterns = [
    path('<int:article_id>/update/', article_update_view, name='articleupdate'),
]

Body:
Your issue is the way you're passing the object id.

template.html

{% extends 'base.html' %}

{% block content %}

<h3>Title: {{object.title}}</h3>

<p>Caption: {{object.caption}}</p>
<p>Activeness: {{object.active}}</p>

<a href="{% url 'articleupdate' object.id %}">Update this Article</a> # or object.article_id

{% endblock %}


答: You need to give key from the iterator, not the iterator itself. In STL i would have done i->first for an iterator to map, in order to access the key, and i use the key to access the map using [] operator.</p>

Title: Unable to read out config file while iterating


问:
react-native command not found in mac os
I have tried everything, but still not able to create react native app in my mac os

I have reinstall every step.

```<code>CLI installed successfully
/Users/prashantrana/.npm-global/bin/react-native -> /Users/prashantrana/.npm-global/lib/node_modules/react-native-cli/index.js
</code>```

-bash: react-native command not found

I expected that app should be created but command is not working at all

答:
install React native globaly </p>

```<code>npm i react-native-cli -g
</code>```

Body:
I have tried everything, but still not able to create react native app in my mac os

I have reinstall every step.

CLI installed successfully
/Users/prashantrana/.npm-global/bin/react-native -> /Users/prashantrana/.npm-global/lib/node_modules/react-native-cli/index.js

-bash: react-native command not found

I expected that app should be created but command is not working at all

Body:
install React native globaly

npm i react-native-cli -g


问:
php fatal error: class sqlite3 is not found in
Im using ubuntu 12.04, and php 5.x I need to use sqlite3 in it but Im getting an error of

```<code>php fatal error: class sqlite3 not found
</code>```

I done all the installation processes,

like

```<code>$ sudo apt-get install php5-cli php5-dev make
$ sudo apt-get install libsqlite3-0 libsqlite3-dev
$ sudo apt-get install php5-sqlite3
$ sudo apt-get remove php5-sqlite3
$ cd ~
$ wget http://pecl.php.net/get/sqlite3-0.6.tgz
$ tar -zxf sqlite3-0.6.tgz
$ cd sqlite3-0.6/
$ sudo phpize
$ sudo ./configure
$ sudo make
$ sudo make install
$ sudo apache2ctl restart
</code>```

and

```<code>cd /etc/php5/conf.d

cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D

sudo /etc/init.d/apache2 restart
</code>```

Now what else I want to do?

Can anyone please help me to fix this?

答:
For php5.6 use:</p>

```<code>sudo apt-get install php5.6-sqlite3
</code>```

Body:
Im using ubuntu 12.04, and php 5.x I need to use sqlite3 in it but Im getting an error of

php fatal error: class sqlite3 not found

I done all the installation processes,

like

$ sudo apt-get install php5-cli php5-dev make
$ sudo apt-get install libsqlite3-0 libsqlite3-dev
$ sudo apt-get install php5-sqlite3
$ sudo apt-get remove php5-sqlite3
$ cd ~
$ wget http://pecl.php.net/get/sqlite3-0.6.tgz
$ tar -zxf sqlite3-0.6.tgz
$ cd sqlite3-0.6/
$ sudo phpize
$ sudo ./configure
$ sudo make
$ sudo make install
$ sudo apache2ctl restart

and

cd /etc/php5/conf.d

cat > sqlite3.ini
# configuration for php SQLite3 module
extension=sqlite3.so
^D

sudo /etc/init.d/apache2 restart

Now what else I want to do?

Can anyone please help me to fix this?

Body:
For php5.6 use:

sudo apt-get install php5.6-sqlite3


问:
Logger prints only the log message and not the exception
```<code>try {
   // some code
}
catch (Exception e) {
   Logger.log(Level.WARN, "Unable to complete the job. ID: " + id, e);
}
</code>```

So, obviously a developer expects if something goes wrong, it would log the exception (exception type & stacktrace)

Here is the log print which I got

```<code>[27 May 2019 13:30:07][http-nio-8080-exec-13][WARN]: Unable to complete the job. ID: 123457890
</code>```

Here is the Log4j config

```<code>log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=debug.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d{dd MMM yyyy HH:mm:ss}][%t][%p]: %m%n
</code>```

I know ways to get the exception details, I want to understand this behavior. How does this happen? Does the logger ignore the passed on parameters?

答:
My only guess would be that this happens due to hotspot optimization:

The compiler in the server VM now provides correct stack backtraces for all "cold" built-in exceptions. For performance purposes, when such an exception is thrown a few times, the method may be recompiled. After recompilation, the compiler may choose a faster tactic using preallocated exceptions that do not provide a stack trace. To disable completely the use of preallocated exceptions, use this new flag: -XX:-OmitStackTraceInFastThrow.

This was borrowed from this answer to a related question:

log4j not printing the stacktrace for exceptions

Body:
try {
   // some code
}
catch (Exception e) {
   Logger.log(Level.WARN, "Unable to complete the job. ID: " + id, e);
}

So, obviously a developer expects if something goes wrong, it would log the exception (exception type & stacktrace)

Here is the log print which I got

[27 May 2019 13:30:07][http-nio-8080-exec-13][WARN]: Unable to complete the job. ID: 123457890

Here is the Log4j config

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=debug.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%d{dd MMM yyyy HH:mm:ss}][%t][%p]: %m%n

I know ways to get the exception details, I want to understand this behavior. How does this happen? Does the logger ignore the passed on parameters?


答:
You can use position fixed to do such task.It will keep your button at bottom .</p>

```<code>#delegar {
    position:fixed;
    rigth: 0;
    bottom: 0;
}
</code>```

Body:
You can use position fixed to do such task.It will keep your button at bottom .

#delegar {
    position:fixed;
    rigth: 0;
    bottom: 0;
}


问:
How to decode special character in Xamarin forms?
How to decode spacial character in xamairn forms

Inside my label text = "Sample & Text"
instead of showing original text, its showing "Sample & Text"

so how to solve this?

答:
Try this:

```<code><Label Text="Sample &Text"/>
</code>```

This will display "Sample & Text"

Body:
Try this:

<Label Text="Sample &amp;Text"/>

This will display "Sample & Text"


问:
Genymotion - /usr/lib64/libX11.so.6: undefined symbol: xcb_wait_for_reply64
I installed Genymotion on openSUSE Leap 42.1 and don't have success to execute.
I'm getting the following error:

```<code>genymotion/genymotion: symbol lookup error: /usr/lib64/libX11.so.6: undefined symbol: xcb_wait_for_reply64
</code>```

I have no idea what may have caused the problem. Anyone else seen this?

答: In my case, I'm using Debian Stretch, I had to remove from the genymotion directory the following files: libxcb.so.1 and libdrm.so.2.

Body:
I installed Genymotion on openSUSE Leap 42.1 and don't have success to execute.
I'm getting the following error:

genymotion/genymotion: symbol lookup error: /usr/lib64/libX11.so.6: undefined symbol: xcb_wait_for_reply64

I have no idea what may have caused the problem. Anyone else seen this?


问:
How to display input Form Horizontally in CSS?
i am trying to style form in flask python..instead of vertical i want to show form in horizontal manner..i tried display:inline in CSS but doesn't work for me..how to show form input in horizontal manner..any help would be appreciated ..thanks in advance..

```<code>    <div class="container">
    <div class="jumbotron">
    <form class="form-signin" action="/validateLogin" method="post">
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
    <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    </div>

    <footer class="footer">
    </footer>

    </div>
</code>```

CSS:

```<code>.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signint .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
        box-sizing: border-box;
padding: 10px;
font-size: 16px;
}

.form-signin .form-control: focus {
z-index: 2;
}
.form-signin {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-siginin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
</code>```

答:
keep that style change html code like following

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<form class="form-signin row" action="/validateLogin" method="post">

    Email address
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>

    Password
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">

  <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>

</form>```

Body:
i am trying to style form in flask python..instead of vertical i want to show form in horizontal manner..i tried display:inline in CSS but doesn't work for me..how to show form input in horizontal manner..any help would be appreciated ..thanks in advance..

    <form class="form-signin" action="/validateLogin" method="post">
    Email address
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
    Password
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
    <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>

CSS:

.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signint .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
        box-sizing: border-box;
padding: 10px;
font-size: 16px;
}

.form-signin .form-control: focus {
z-index: 2;
}
.form-signin {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-siginin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}

Body:
keep that style change html code like following

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet"/>
<form class="form-signin row" action="/validateLogin" method="post">
  <div class="col-sm-4">
    <label for="inputEmail" class="sr-only">Email address</label>
    <input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
  </div>

  <div class="col-sm-4">
    <label for="inputPassword" class="sr-only">Password</label>
    <input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password">
  </div>
<div class="col-sm-4">
  <button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</div>
</form>


答:
ERROR level is used to log the stacktrace of an error in log file.

Try using.

```<code>    try {
        // some code
    } catch (Exception e) {
       Logger.log(Level.ERROR, "Unable to complete the job. ID: " + id, e);
    }
</code>```

if it still don't work, please share your logging library. Will check with that.

Title: Logger prints only the log message and not the exception

Body:
ERROR level is used to log the stacktrace of an error in log file.

Try using.

    try {
        // some code
    } catch (Exception e) {
       Logger.log(Level.ERROR, "Unable to complete the job. ID: " + id, e);
    }

if it still don't work, please share your logging library. Will check with that.


问:
what to use in asp.net webapi 2 instead of print or echo in php
I am trying to write an api that returns some text to a phone system that reads the text.
print with php works but return of type string with asp webapi does not work.
is there anithing like print of php for asp web api?</p>

答:
you can use this command

Response.Write("some text");


问:
Azure Cloud Services: maintaining object references across different requests
I have a (classic) cloud service that needs to create an expensive object that I want to be reused in subsequent requests. It takes a long time to create so creating it each time slows down the requests unacceptably.

```<code>public class MyService : IHttpHandler
{
    public static ExpensiveObject MyObject;

    public void ProcessRequest(HttpContext context)
    {
        if (MyObject == null)
            MyObject = new ExpensiveObject();  // very time consuming operation

        // do stuff with MyObject
    }
}
</code>```

(I realise the lack of consideration for multiple concurrent requests running, please disregard that) When I post two requests, one after the other, it creates a new MyObject each time. How can I ensure that it reuses the same object created for each request?

Setting IsReusable to return true in the MyService seemingly makes no difference.

答:
To achieve this easily (without dealing with arcane Azure crap) I just made a separate executable that hosts the ExpensiveObject in a Nancy localhost server (started in a startup script).

In my case this has no significant drawbacks as I just need to request the object to consume a string and return another string. This might not be the right solution for everyone however.

Body:
I have a (classic) cloud service that needs to create an expensive object that I want to be reused in subsequent requests. It takes a long time to create so creating it each time slows down the requests unacceptably.

public class MyService : IHttpHandler
{
    public static ExpensiveObject MyObject;

    public void ProcessRequest(HttpContext context)
    {
        if (MyObject == null)
            MyObject = new ExpensiveObject();  // very time consuming operation

        // do stuff with MyObject
    }
}

(I realise the lack of consideration for multiple concurrent requests running, please disregard that) When I post two requests, one after the other, it creates a new MyObject each time. How can I ensure that it reuses the same object created for each request?

Setting IsReusable to return true in the MyService seemingly makes no difference.


问:
Session Affinity Settings for multiple Pods exposed by a single service
I have a setup Metallb as LB with Nginx Ingress installed on K8S cluster.
I have read about session affinity and its significance but so far I do not have a clear picture.

How can I create a single service exposing multiple pods of the same application?
After creating the single service entry point, how to map the specific client IP to Pod abstracted by the service?

Is there any blog explaining this concept in terms of how the mapping between Client IP and POD is done in kubernetes?

But I do not see Client's IP in the YAML. Then, How is this service going to map the traffic to respective clients to its endpoints? this is the question I have.

```<code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10000
</code>```

答:
follow the service reference for session affinity</p>

```<code>kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10000
</code>```

Body:
I have a setup Metallb as LB with Nginx Ingress installed on K8S cluster.
I have read about session affinity and its significance but so far I do not have a clear picture.

How can I create a single service exposing multiple pods of the same application?
After creating the single service entry point, how to map the specific client IP to Pod abstracted by the service?

Is there any blog explaining this concept in terms of how the mapping between Client IP and POD is done in kubernetes?

But I do not see Client's IP in the YAML. Then, How is this service going to map the traffic to respective clients to its endpoints? this is the question I have.

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10000

Body:
follow the service reference for session affinity

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: my-app
  ports:
  - name: http
    protocol: TCP
    port: 80
    targetPort: 80
  sessionAffinity: ClientIP
  sessionAffinityConfig:
    clientIP:
      timeoutSeconds: 10000


问:
WKWebview - Complex communication between Javascript & native code
In WKWebView we can call ObjectiveC/swift code using webkit message handlers
eg: webkit.messageHandlers.<handler>.pushMessage(message)

It works well for simple javascript functions without parameters. But;

Is it possible to call native code with JS callback function as parameters?

Is it possible to return a value to JS function from native code?

答:
I managed to solve this problem - to achieve two-way communication between the native app and the WebView (JS) - using postMessage in the JS and evaluateJavaScript in the Native code.

The solution from high-level was:

WebView (JS) code:

Create a general function to get data from Native (I called it getDataFromNative for Native, which calls another callback function (I called it callbackForNative), which can be reassigned

When wanting to call Native with some data and requiring a response, do the following:

Reassign callbackForNative to whatever function you want

Call Native from the WebView using postMessage

Native code:

Use the userContentController to listen to incoming messages from the WebView (JS)

Use evaluateJavaScript to call your getDataFromNative JS function with whatever params you want

Here is the code:

JS:

```<code>// Function to get data from Native
window.getDataFromNative = function(data) {
    window.callbackForNative(data)
}

// Empty callback function, which can be reassigned later
window.callbackForNative = function(data) {}

// Somewhere in your code where you want to send data to the native app and have it call a JS callback with some data:
window.callbackForNative = function(data) {
    // Do your stuff here with the data returned from the native app
}
webkit.messageHandlers.YOUR_NATIVE_METHOD_NAME.postMessage({ someProp: 'some value' })
</code>```

Native (Swift):

```<code>// Call this function from `viewDidLoad()`
private func setupWebView() {
    let contentController = WKUserContentController()
    contentController.add(self, name: "YOUR_NATIVE_METHOD_NAME")
    // You can add more methods here, e.g.
    // contentController.add(self, name: "onComplete")

    let config = WKWebViewConfiguration()
    config.userContentController = contentController
    self.webView = WKWebView(frame: self.view.bounds, configuration: config)
}

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Received message from JS")

    if message.name == "YOUR_NATIVE_METHOD_NAME" {
        print("Message from webView: \(message.body)")
        sendToJavaScript(params: [
            "foo": "bar"
        ])
    }

    // You can add more handlers here, e.g.
    // if message.name == "onComplete" {
    //     print("Message from webView from onComplete: \(message.body)")
    // }
}

func sendToJavaScript(params: JSONDictionary) {
    print("Sending data back to JS")
    let paramsAsString = asString(jsonDictionary: params)
    self.webView.evaluateJavaScript("getDataFromNative(\(paramsAsString))", completionHandler: nil)
}

func asString(jsonDictionary: JSONDictionary) -> String {
    do {
        let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
        return String(data: data, encoding: String.Encoding.utf8) ?? ""
    } catch {
        return ""
    }
}
</code>```

P.S. I'm a Front-end Developer, so I'm very skilled in JS, but have very little experience in Swift.

P.S.2 Make sure your WebView is not cached, or you might get frustrated when the WebView doesn't change despite changes to the HTML/CSS/JS.

References:

This guide helped me a lot: https://medium.com/@JillevdWeerd/creating-links-between-wkwebview-and-native-code-8e998889b503

Body:
I managed to solve this problem - to achieve two-way communication between the native app and the WebView (JS) - using postMessage in the JS and evaluateJavaScript in the Native code.

The solution from high-level was:

WebView (JS) code:

Create a general function to get data from Native (I called it getDataFromNative for Native, which calls another callback function (I called it callbackForNative), which can be reassigned

When wanting to call Native with some data and requiring a response, do the following:

Reassign callbackForNative to whatever function you want

Call Native from the WebView using postMessage

Native code:

Use the userContentController to listen to incoming messages from the WebView (JS)

Use evaluateJavaScript to call your getDataFromNative JS function with whatever params you want

Here is the code:

JS:

// Function to get data from Native
window.getDataFromNative = function(data) {
    window.callbackForNative(data)
}

// Empty callback function, which can be reassigned later
window.callbackForNative = function(data) {}

// Somewhere in your code where you want to send data to the native app and have it call a JS callback with some data:
window.callbackForNative = function(data) {
    // Do your stuff here with the data returned from the native app
}
webkit.messageHandlers.YOUR_NATIVE_METHOD_NAME.postMessage({ someProp: 'some value' })

Native (Swift):

// Call this function from `viewDidLoad()`
private func setupWebView() {
    let contentController = WKUserContentController()
    contentController.add(self, name: "YOUR_NATIVE_METHOD_NAME")
    // You can add more methods here, e.g.
    // contentController.add(self, name: "onComplete")

    let config = WKWebViewConfiguration()
    config.userContentController = contentController
    self.webView = WKWebView(frame: self.view.bounds, configuration: config)
}

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Received message from JS")

    if message.name == "YOUR_NATIVE_METHOD_NAME" {
        print("Message from webView: \(message.body)")
        sendToJavaScript(params: [
            "foo": "bar"
        ])
    }

    // You can add more handlers here, e.g.
    // if message.name == "onComplete" {
    //     print("Message from webView from onComplete: \(message.body)")
    // }
}

func sendToJavaScript(params: JSONDictionary) {
    print("Sending data back to JS")
    let paramsAsString = asString(jsonDictionary: params)
    self.webView.evaluateJavaScript("getDataFromNative(\(paramsAsString))", completionHandler: nil)
}

func asString(jsonDictionary: JSONDictionary) -> String {
    do {
        let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: .prettyPrinted)
        return String(data: data, encoding: String.Encoding.utf8) ?? ""
    } catch {
        return ""
    }
}

P.S. I'm a Front-end Developer, so I'm very skilled in JS, but have very little experience in Swift.

P.S.2 Make sure your WebView is not cached, or you might get frustrated when the WebView doesn't change despite changes to the HTML/CSS/JS.

References:

This guide helped me a lot: https://medium.com/@JillevdWeerd/creating-links-between-wkwebview-and-native-code-8e998889b503


问:
jquery slide toggle iframe overriding hide or show
I've got this code that hides/shows a div depending on whether the user clicks a button to do so. It also sets a cookie to remember the state, so that if the user refreshes the page the div state stays the same. All is working fine, until I add the code to show a DFP ad, and for some reason the iframe it uses is overriding the hidden state when the page is refreshed - it still shows the ad, even though the containing div is hidden?

Here is my code, I would appreciate any help to get this sorted :-)

Thanks

As it is now http://jsfiddle.net/jamesisapayne/xhzes/

```<code><style>
#billboardButton {
    background-color:#f1f1f1;
    color:#666;
    padding:3px;
    width:100px;
    cursor:pointer;
    text-align:center;
    margin:0 auto;
}
</style>

<!-- Load the latest version of jQuery -->
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<!-- Load the jquery.cookie.js plugin -->
<script src="https://googledrive.com/host/0B7ZDS1Dob8_8WXhpUVdtNjVNdWc/"></script>

<script type='text/javascript'>
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
    var gads = document.createElement('script');
    gads.async = true;
    gads.type = 'text/javascript';
    var useSSL = 'https:' == document.location.protocol;
    gads.src = (useSSL ? 'https:' : 'http:') +
    '//www.googletagservices.com/tag/js/gpt.js';
    var node = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(gads, node);
})();
</script>
<script type='text/javascript'>
googletag.cmd.push(function() {
    googletag.defineSlot('/4856165/Forum_Billboard_970x250', [970, 250], 'billboard').addService(googletag.pubads());
    googletag.pubads().setTargeting('SiteType', 'giraffetest');
    googletag.enableServices();
});
</script>

<script>
$(document).ready(function(){
    // Check to see if the billboardStatus cookie has been set
    if($.cookie('billboardStatus')) {
        // If yes, define the variable
        var cook = $.cookie('billboardStatus');
    } else {
        // Else set it as true by default and with an expiry date of 1 day = 24 hours
        var cook = $.cookie('billboardStatus', 'true', {expires: 1});
    }
    // On refresh, if the cookie value is false i.e. the ad spot is closed
    if(cook=='false') {
        // hide the billboard ad spot
        $('#billboard').hide();
        // Change the open/close button settings
        $("#billboardButton").css("backgroundColor", "#e1e1e1").text('Open Ad');
    } else { // Else if the value is set as true i.e. open
    // Show the ad spot
    $('#billboard').show();
        // Change the open/close button settings
        $("#billboardButton").text('Close Ad');
    }
    // When the user clciks on the open/close button…
    $('#billboardButton').on('click', function() {
        // Toggle the opening/closing of the ad spot
        $('#billboard').stop().slideToggle('slow', function(){
            // Set the background colour and the text value of the button depending on what state the button is currently in
            $("#billboardButton").css("backgroundColor", $(this).is(':not(:visible)') ? "#e1e1e1" : "").text($(this).is(':visible') ? 'Close Ad' : 'Open Ad');
            // Set the cookie value to false i.e. closed
            $.cookie('billboardStatus', $(this).is(':visible'), {expires:1});
        }); // End slideToggle
    }); // End on click
}); // End document ready
</script>
<div style="width:970px;margin:20px auto;">
    <div id="billboardButton">Close Ad</div>
    <div id='billboard' style='width:970px; height:250px; background-color:#0C9;'>
        <script type='text/javascript'>
            //googletag.cmd.push(function() { googletag.display('billboard'); });
        </script>
    </div>
</div>
</code>```

答:
Simply use </p>

```<code>onClick="funtionName()"

funtion funtionName(){
  $('#iframeID').toggle();
}
</code>```

Body:
I've got this code that hides/shows a div depending on whether the user clicks a button to do so. It also sets a cookie to remember the state, so that if the user refreshes the page the div state stays the same. All is working fine, until I add the code to show a DFP ad, and for some reason the iframe it uses is overriding the hidden state when the page is refreshed - it still shows the ad, even though the containing div is hidden?

Here is my code, I would appreciate any help to get this sorted :-)

Thanks

As it is now http://jsfiddle.net/jamesisapayne/xhzes/

Close Ad

Body:
Simply use

onClick="funtionName()"

funtion funtionName(){
  $('#iframeID').toggle();
}


问:
Bootstrap 4 Validation reCaptcha
Since Bootstrap 4 has their own form validation i like to add the Google Invisible reCaptcha to it. But how can i activate grecaptcha.execute(); in the javascript to make it work? It should execute the reCaptcha after Bootstrap Validation was successfull and not before.

Here is my code:

```<code><?php
if($_SERVER["REQUEST_METHOD"] === "POST") {

    // Google reCaptcha
    $ip = $_SERVER['REMOTE_ADDR'];
    $api_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$ip);
    $api_response = json_decode($api_response, true);

    if($api_response["success"] === true) {
        echo "Success";
    } else {
        print_r($api_response);
    }
}
?>
<div class="container py-6">

    <form class="needs-validation" novalidate action="" method="POST">

        <div class="form-group">
            <label for="City">City</label>
            <input type="text" class="form-control" id="City" required>
            <div class="invalid-feedback">Please provide a valid city.</div>
        </div>

        <div id="recaptcha" class="g-recaptcha" data-sitekey="WhateverSiteKey" data-callback="onSubmit" data-size="invisible"></div>

        <button class="btn btn-dark">Send</button>

    </form>

</div>

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

<script>
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>
</code>```

答: You need an onclick for the form itself to excecute the captcha and return false on that onclick. Then within your reCaptcha Execute callback you need to submit your form with Javascript. or promise</p>

Title: Bootstrap 4 Validation reCaptcha

Body:
Since Bootstrap 4 has their own form validation i like to add the Google Invisible reCaptcha to it. But how can i activate grecaptcha.execute(); in the javascript to make it work? It should execute the reCaptcha after Bootstrap Validation was successfull and not before.

Here is my code:

<?php
if($_SERVER["REQUEST_METHOD"] === "POST") {

    // Google reCaptcha
    $ip = $_SERVER['REMOTE_ADDR'];
    $api_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$ip);
    $api_response = json_decode($api_response, true);

    if($api_response["success"] === true) {
        echo "Success";
    } else {
        print_r($api_response);
    }
}
?>

    <form class="needs-validation" novalidate action="" method="POST">

            City
            <input type="text" class="form-control" id="City" required>

Please provide a valid city.

        <button class="btn btn-dark">Send</button>

    </form>


问:
How to extract matching keywords from two columns in a pandas dataframe?
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

```<code>df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]
</code>```

I am expecting the output something like this

```<code>column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color
</code>```

答:
using np.intersect1d

```<code>df['column3'] = df.apply(lambda x: ' '.join(np.intersect1d(x['column1'].split(),x['column2'].split())), axis=1)
</code>```

Output

```<code>                     column1                    column2         column3
0  A girl is going to market         girl market school     girl market
1  A girl is going to school         girl market school     girl school
2   The sky is blue in color      sky blue orange color  blue color sky
</code>```

if order matters

```<code> df['column3'] = df.apply(lambda x: ' '.join(np.array(x['column1'].split())[np.in1d(x['column1'].split(),x['column2'].split())]), axis=1)
</code>```

Output

```<code>                     column1                    column2         column3
0  A girl is going to market         girl market school     girl market
1  A girl is going to school         girl market school     girl school
2   The sky is blue in color      sky blue orange color  sky blue color
</code>```

Body:
I have two columns in a dataframe both are strings where column1 have some matching keywords in column2. I want to extract those matching keyword from column1 and column2 in a new column.

df['column3']=df.column1.apply(lambda x : df.column2[df.column2.str.contains(x)]

I am expecting the output something like this

column1                     column2                 column3
A girl is going to market   girl market school      girl market
A girl is going to school   girl market school      girl school
The sky is blue in color    sky blue orange color   sky blue color

Body:
using np.intersect1d

df['column3'] = df.apply(lambda x: ' '.join(np.intersect1d(x['column1'].split(),x['column2'].split())), axis=1)

Output

                     column1                    column2         column3
0  A girl is going to market         girl market school     girl market
1  A girl is going to school         girl market school     girl school
2   The sky is blue in color      sky blue orange color  blue color sky

if order matters

 df['column3'] = df.apply(lambda x: ' '.join(np.array(x['column1'].split())[np.in1d(x['column1'].split(),x['column2'].split())]), axis=1)

Output

                     column1                    column2         column3
0  A girl is going to market         girl market school     girl market
1  A girl is going to school         girl market school     girl school
2   The sky is blue in color      sky blue orange color  sky blue color


问:
Position imageView between two views and dynamically resize it to fit?
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

```<code>____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------
</code>```

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

```<code><ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>
</code>```

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.

答:
Set  Imageview

```<code>android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/buttonTop"
app:layout_constraintBottom_toTopOf="@id/buttonBottom"
</code>```

height will be adjust based on devices size

Body:
I have a simple layout with two buttons and a image view contained in a ConstraintLayout. The image view shows a vector graphic and is position between the two buttons horizontally.

____________
| Button    |
------------
____________
| ImageView |
------------
____________
| Button    |
------------

The problem is that I cant seem to figure out how to properly constrain the image view vertically between the two buttons.

As long as I have layout_width and layout_height for the image view set to wrap_content the result will vary depending on the aspect ratio of the device display. I could set hardcoded height and width values but that also seems like a bad idea.

Isnt there some way to dynamically resize the ImageView based on the constraints?

<ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/buttonTop"
    app:layout_constraintBottom_toTopOf="@id/buttonBottom"/>

This works on tall aspect ratio devices but on small ones the bottom and/or top buttons overlap the imageView.

Body:
Set  Imageview

android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/buttonTop"
app:layout_constraintBottom_toTopOf="@id/buttonBottom"

height will be adjust based on devices size


问:
Bind sweet alert to dynamically added elements
Sweet alert is not triggered on elements i inject in DOM.

I am using sweet alert 2 gem (https://github.com/nicolasblanco/sweet-alert2-rails) in my rails 5 application, and it works great until I add elements with js response. I understand that I have to bind sweet alert event listeners by invoking them after adding elements, but I don't know how.

Somewhere the gem is initializing sweet alert and binding events on my HTML elements with data-confirm attribute turning them into data-sweet-alert-confirm. I guess I'll have to call that init function after injecting new elements.

答:
In view file:

```<code><link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet" type="text/css">

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

<div id="append_div" style="margin:20px;"></div>

<button id="add_element">Add Element</button>
</code>```

In js code:

```<code><script>
    $(document).ready(function(){

        $(document).on('click', '#add_element', function(){
            $(document).find('#append_div').append(
                '<button class="_appended_btn" style="margin:10px;">Open sweet alert</button>'
            );
        });

        $(document).on('click', '._appended_btn', function(){
            Swal.fire({
               type: 'success',
               title: 'Your work has been done',
               showConfirmButton: false,
               timer: 1500
            })
        });

    });
</script>

</code>```

Body:
In view file:

<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.css" rel="stylesheet" type="text/css">

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.js"></script>

<div id="append_div" style="margin:20px;"></div>

<button id="add_element">Add Element</button>

In js code:

<script>
    $(document).ready(function(){

        $(document).on('click', '#add_element', function(){
            $(document).find('#append_div').append(
                '<button class="_appended_btn" style="margin:10px;">Open sweet alert</button>'
            );
        });

        $(document).on('click', '._appended_btn', function(){
            Swal.fire({
               type: 'success',
               title: 'Your work has been done',
               showConfirmButton: false,
               timer: 1500
            })
        });

    });
</script>


问:
Load ICollection from ICollection Entity Framework Core
I have these models which all of them are a one to many relation in succession.

ListaAbastecimento > ReferenciaAbastecimento > EtiquetaAbastecimento

```<code>[Table(name: "hListasAbastecimento")]
public class ListaAbastecimento
{
    public int Id { get; set; }
    public int ColaboradorId { get; set; }
    [ForeignKey("ColaboradorId")]
    public virtual Colaborador Colaborador { get; set; }

    public string UAP { get; set; }
    public DateTime DataCriacao { get; set; }

    public virtual ICollection<ReferenciaAbastecimento> Referencias { get; set; }
}

    [Table(name: "hReferenciasAbastecimento")]
    public class ReferenciaAbastecimento
    {
        public int Id { get; set; }

        [MaxLength(15)]
        public string Referencia { get; set; }
        public int? QtdAbastecimento { get; set; }
        public int? QtdCaixas { get; set; }
        public int? QtdPecasPorCaixa { get; set; }

        public virtual ICollection<EtiquetaAbastecimento> Etiquetas { get; set; }
    }

[Table(name: "hEtiquetasAbastecimento")]
    public class EtiquetaAbastecimento
    {
        public int Id { get; set; }
        public int? EtiquetaFIFO { get; set; }
        public int? Qtd { get; set; }

        [MaxLength(20)]
        public string Localizacao { get; set; }

        public int ReferenciaAbstecimentoId { get; set; }
        [ForeignKey("ReferenciaAbstecimentoId")]
        public virtual ReferenciaAbastecimento ReferenciaAbastecimento { get; set; }
    }
</code>```

Here is what i have tried, however the theninclude does not find the properties

```<code>   var abastecimentosList = await _context.ListasAbastecimento
            .Include(la => la.Referencias)
            .ThenInclude(r => r.Etiquetas) // can't find Etiquetas property
            .ToListAsync();
</code>```

this does not work

答: Using ThenInclude on Many-to-Many relations is supported by Entity Framework Core itself, and compiler should be able to cope with the presented code. However, there is/was a bug in Intellisense and Visual Studio(s), which didn't properly display properties you can use. (in your case Etiquetas). Can confirm, it is fixed in VS 2019 (16.2.0 Preview 1.0) version.

Body:
I have these models which all of them are a one to many relation in succession.

ListaAbastecimento > ReferenciaAbastecimento > EtiquetaAbastecimento

[Table(name: "hListasAbastecimento")]
public class ListaAbastecimento
{
    public int Id { get; set; }
    public int ColaboradorId { get; set; }
    [ForeignKey("ColaboradorId")]
    public virtual Colaborador Colaborador { get; set; }

    public string UAP { get; set; }
    public DateTime DataCriacao { get; set; }

    public virtual ICollection<ReferenciaAbastecimento> Referencias { get; set; }
}

    [Table(name: "hReferenciasAbastecimento")]
    public class ReferenciaAbastecimento
    {
        public int Id { get; set; }

        [MaxLength(15)]
        public string Referencia { get; set; }
        public int? QtdAbastecimento { get; set; }
        public int? QtdCaixas { get; set; }
        public int? QtdPecasPorCaixa { get; set; }

        public virtual ICollection<EtiquetaAbastecimento> Etiquetas { get; set; }
    }

[Table(name: "hEtiquetasAbastecimento")]
    public class EtiquetaAbastecimento
    {
        public int Id { get; set; }
        public int? EtiquetaFIFO { get; set; }
        public int? Qtd { get; set; }

        [MaxLength(20)]
        public string Localizacao { get; set; }

        public int ReferenciaAbstecimentoId { get; set; }
        [ForeignKey("ReferenciaAbstecimentoId")]
        public virtual ReferenciaAbastecimento ReferenciaAbastecimento { get; set; }
    }

Here is what i have tried, however the theninclude does not find the properties

   var abastecimentosList = await _context.ListasAbastecimento
            .Include(la => la.Referencias)
            .ThenInclude(r => r.Etiquetas) // can't find Etiquetas property
            .ToListAsync();

this does not work


问:
Submit multiple tabs within one view ASP.NET MVC
I have an ASP .NET application with multiple tabs on a view, each tab containing several inputs for each course attendee (name, phone number, job title, etc).

I created a jquery function to collect data from views and generate the JSON accordingly:

```<code> function getAttendees() {
            var sections = [];

            $(".divWithInputs").each(function (i, val) {
                var tab = $(val).serializeArray();
                sections.push(tab);
            });

            return sections;
        }
</code>```

And the submit function:

```<code>$("#checkoutAttendees").click(function () {
                var formData = new FormData();
                formData.append("Attendees", JSON.stringify(getAttendees()));

                $.ajax({
                    url: "/controllerURL",
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: formData,
                    success: function (response) {
                        alert(response);
                    }
                });
            });
</code>```

I have an issue when reading the JSON, because I need an IEnumerable of Attendee objects to populate with this sort of data:

```<code>[
   [
      {
         "name":"first-name-attendee-0",
         "value":"Jon"
      },
      {
         "name":"last-name-attendee-0",
         "value":"Stark"
      },
      {
         "name":"email-attendee-0",
         "value":"jon.stark@northwall.com"
      },
      {
         "name":"phone-attendee-0",
         "value":"0181042981029840"
      },
      {
         "name":"company-attendee-0",
         "value":"Nightwatch"
      },
      {
         "name":"job-title-attendee-0",
         "value":"King"
      }
   ],
   [
      {
         "name":"first-name-attendee-1",
         "value":"Aria"
      },
      {
         "name":"last-name-attendee-1",
         "value":"Stark"
      },
      {
         "name":"email-attendee-1",
         "value":"noemail@nodomain.com"
      },
      {
         "name":"phone-attendee-1",
         "value":"000000000000000"
      },
      {
         "name":"company-attendee-1",
         "value":"No organization"
      },
      {
         "name":"job-title-attendee-1",
         "value":"Killer"
      }
   ],
   [
      {
         "name":"first-name-attendee-2",
         "value":"Mad"
      },
      {
         "name":"last-name-attendee-2",
         "value":"King"
      },
      {
         "name":"email-attendee-2",
         "value":"mad.king@yahoo.com"
      },
      {
         "name":"phone-attendee-2",
         "value":"019209840921840219"
      },
      {
         "name":"company-attendee-2",
         "value":"Kingdom"
      },
      {
         "name":"job-title-attendee-2",
         "value":"King"
      }
   ]
]
</code>```

Any advise on how to properly transform data from JSON into  a list of Attendees ?

Thank you.

答:
Solution: in backend I had to create a list of lists of NameValuePair

The Action method looks like this:

```<code>[HttpPost]
        public ActionResult TrainingBook(FormCollection formCollection)
        var viewModel = new TrainingFormViewModel();

        var attendeesListJSON = formCollection["Attendees"];

        var attendeesJson = JsonConvert.DeserializeObject<List<List<KeyValuePair<string, string>>>>(attendeesListJSON);

        List<Attendees> attendees = new List<Attendees>();

        foreach (var item in attendeesJson)
        {
            attendees.Add(new Attendees {
                FirstName = item[0].Value,
                LastName = item[1].Value,
                WorkEmailAddress = item[2].Value,
                PhoneNumber = item[3].Value,
                Organization = item[4].Value,
                JobTitle = item[5].Value
            });
        }
</code>```

A key value pair is name and value for an input, the first list of key value pairs is one attendee, the the list of lists, ofc, all the attendees.

Body:
I have an ASP .NET application with multiple tabs on a view, each tab containing several inputs for each course attendee (name, phone number, job title, etc).

I created a jquery function to collect data from views and generate the JSON accordingly:

 function getAttendees() {
            var sections = [];

            $(".divWithInputs").each(function (i, val) {
                var tab = $(val).serializeArray();
                sections.push(tab);
            });

            return sections;
        }

And the submit function:

$("#checkoutAttendees").click(function () {
                var formData = new FormData();
                formData.append("Attendees", JSON.stringify(getAttendees()));

                $.ajax({
                    url: "/controllerURL",
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: formData,
                    success: function (response) {
                        alert(response);
                    }
                });
            });

I have an issue when reading the JSON, because I need an IEnumerable of Attendee objects to populate with this sort of data:

[
   [
      {
         "name":"first-name-attendee-0",
         "value":"Jon"
      },
      {
         "name":"last-name-attendee-0",
         "value":"Stark"
      },
      {
         "name":"email-attendee-0",
         "value":"jon.stark@northwall.com"
      },
      {
         "name":"phone-attendee-0",
         "value":"0181042981029840"
      },
      {
         "name":"company-attendee-0",
         "value":"Nightwatch"
      },
      {
         "name":"job-title-attendee-0",
         "value":"King"
      }
   ],
   [
      {
         "name":"first-name-attendee-1",
         "value":"Aria"
      },
      {
         "name":"last-name-attendee-1",
         "value":"Stark"
      },
      {
         "name":"email-attendee-1",
         "value":"noemail@nodomain.com"
      },
      {
         "name":"phone-attendee-1",
         "value":"000000000000000"
      },
      {
         "name":"company-attendee-1",
         "value":"No organization"
      },
      {
         "name":"job-title-attendee-1",
         "value":"Killer"
      }
   ],
   [
      {
         "name":"first-name-attendee-2",
         "value":"Mad"
      },
      {
         "name":"last-name-attendee-2",
         "value":"King"
      },
      {
         "name":"email-attendee-2",
         "value":"mad.king@yahoo.com"
      },
      {
         "name":"phone-attendee-2",
         "value":"019209840921840219"
      },
      {
         "name":"company-attendee-2",
         "value":"Kingdom"
      },
      {
         "name":"job-title-attendee-2",
         "value":"King"
      }
   ]
]

Any advise on how to properly transform data from JSON into  a list of Attendees ?

Thank you.

Body:
Solution: in backend I had to create a list of lists of NameValuePair

The Action method looks like this:

[HttpPost]
        public ActionResult TrainingBook(FormCollection formCollection)
        var viewModel = new TrainingFormViewModel();

        var attendeesListJSON = formCollection["Attendees"];

        var attendeesJson = JsonConvert.DeserializeObject<List<List<KeyValuePair<string, string>>>>(attendeesListJSON);

        List<Attendees> attendees = new List<Attendees>();

        foreach (var item in attendeesJson)
        {
            attendees.Add(new Attendees {
                FirstName = item[0].Value,
                LastName = item[1].Value,
                WorkEmailAddress = item[2].Value,
                PhoneNumber = item[3].Value,
                Organization = item[4].Value,
                JobTitle = item[5].Value
            });
        }

A key value pair is name and value for an input, the first list of key value pairs is one attendee, the the list of lists, ofc, all the attendees.


问:
How to place a static button in the bottom rigth corner?
I need to place a button in the bottom right corner of the page and make it static. It needs to keep in its place in case of scroll.

I have tried to place it vía css but i don't have enough level.

```<code><input type="button" onclick="delegar.php" id="delegar" value="Delegar">

#delegar {
    position:relative;
    rigth: 100%;
    bottom: 100%;
}
</code>```

答:
```<code><div class="container-bottom">
    <input type="button" onclick="delegar.php" id="delegar" value="Delegar">
</div>

.container-bottom { position: relative; }

#delegar {
    position:relative;
    right: 10px;
    bottom: 10px;
}
</code>```

Body:
I need to place a button in the bottom right corner of the page and make it static. It needs to keep in its place in case of scroll.

I have tried to place it vía css but i don't have enough level.

<input type="button" onclick="delegar.php" id="delegar" value="Delegar">

#delegar {
    position:relative;
    rigth: 100%;
    bottom: 100%;
}