问:
Input and Store names in array - Java
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

```<code>  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy
</code>```

Output a hello message to greet each player.

```<code>Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy
</code>```

Answer:

```<code>  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}
</code>```

}

答:
Instead of starting index from 1, you need to start the array index to 0 and while displaying "Enter Name of player", just display incremented value of i by 1</p>

```<code> import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 0; i < pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + (i+1) + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}
</code>```

Title: Input and Store names in array - Java

Body:
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy

Output a hello message to greet each player.

Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy

Answer:

  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}

}

Body:
Instead of starting index from 1, you need to start the array index to 0 and while displaying "Enter Name of player", just display incremented value of i by 1

 import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 0; i < pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + (i+1) + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}


来源: stackexchange

问:
TFSDeleteProject - Deleting a branch, any issue?
In TFS 2010, if I use TFSDeleteProject to delete a branch, will that affect the main project?  Anything to be concerned about there?

Thanks.

答:
You should not use TFSDeleteProject to delete a branch.  That will remove the entire project.  Unless you mean that you branched into a different project, and that's the project that you're removing.

If that's the case, TFSDeleteProject will mark all of the source as deleted in the project, but will not remove it from source control.  Your only risk would be if someone was able to merge all of those deletes down into the main project, which, once the TFSDeleteProject is completed, they should be unable to do from within the Source Code Explorer.

ContentLicense: CC BY-SA 2.5


问:
Xcode 9.1 (9B55) Crashes every time I open the migration assistant
This is crashing Xcode every time:

Edit > Convert > To Current Swift Syntax ...

Has anyone else seen this issue? Should I file a bug report with apple?

答:
Had the same issue, and it seems that the crash happens when any Xcode project on the workspace has a sub-project.
Removing the references to any such sub-project made the migration assistant not crash on open. But note that if a target doesn't build, the migration won't succeed, so you'll likely have to re-add the sub-project as a workspace top-level item or link to a copy of the sub-project framework that you build separately.</p>

ContentLicense: CC BY-SA 3.0


问:
How to query 2 seperate things within the same SQL query
I would like to return the values of both Metric 447 and 615 however because the 447 will return in the QSA.NumValue and the 615 will return in the QSA.DateTimeValue. I need it return when they are populated so if it is 615 then don't allow DateTimeValue to be NULL and if 447 then don't allow NumValue to be NULL because a simple OR statement will not work when included in the WHERE statement.

Is this possible?

```<code>  SELECT
  Q.ID
  ,Q.Title
  ,QS.ID
  ,QSA.QMID
  ,QSA.NumValue
  ,QSA.DateTimeValue
  ,QM.MetricID
  ,S.Date
FROM
  QSA
  INNER JOIN QM
    ON QSA.QMID = QM.ID
  INNER JOIN QS
    ON QSA.SessionID = QS.ID
  INNER JOIN Q
    ON QS.ID = Q.ID
  INNER JOIN SQ
    ON Q.ID = SQ.ID
  INNER JOIN S
    ON SQ.ID = S.ID
WHERE
  QM.MetricID IN (447, 615)
  AND QSA.DateTimeValue IS NOT NULL
</code>```

Thank you in advance.

答:
You may looking for this</p>

```<code>WHERE
    1=CASE WHEN QM.MetricID = 447 AND QSA.NumValue NOT NULL THEN 1
           WHEN QM.MetricID = 615 AND QSA.DateTimeValue IS NOT NULL THEN 1
           ELSE 0
      END
</code>```

Body:
I would like to return the values of both Metric 447 and 615 however because the 447 will return in the QSA.NumValue and the 615 will return in the QSA.DateTimeValue. I need it return when they are populated so if it is 615 then don't allow DateTimeValue to be NULL and if 447 then don't allow NumValue to be NULL because a simple OR statement will not work when included in the WHERE statement.

Is this possible?

  SELECT
  Q.ID
  ,Q.Title
  ,QS.ID
  ,QSA.QMID
  ,QSA.NumValue
  ,QSA.DateTimeValue
  ,QM.MetricID
  ,S.Date
FROM
  QSA
  INNER JOIN QM
    ON QSA.QMID = QM.ID
  INNER JOIN QS
    ON QSA.SessionID = QS.ID
  INNER JOIN Q
    ON QS.ID = Q.ID
  INNER JOIN SQ
    ON Q.ID = SQ.ID
  INNER JOIN S
    ON SQ.ID = S.ID
WHERE
  QM.MetricID IN (447, 615)
  AND QSA.DateTimeValue IS NOT NULL

Thank you in advance.

Body:
You may looking for this

WHERE
    1=CASE WHEN QM.MetricID = 447 AND QSA.NumValue NOT NULL THEN 1
           WHEN QM.MetricID = 615 AND QSA.DateTimeValue IS NOT NULL THEN 1
           ELSE 0
      END


问:
ERROR: Syntax error at or near ","
Please resolve this query

```<code>select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(create_time),'HH24:mi') as login_time where login_status = 1,
    to_char(max(create_time),'HH24:mi') as login_out where login_status = 0
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)
</code>```

getting an error at or near ","

Don't know how to write where condition in to_char function.

答:
You need a CASE expression, not a WHERE:</p>

```<code>select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    case when login_status = 1 then to_char(min(create_time),'HH24:mi') end as login_time,
    case when login_status = 0 then to_char(max(create_time),'HH24:mi') end as login_out
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)
</code>```

Title: ERROR: Syntax error at or near ","

Body:
Please resolve this query

select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    to_char(min(create_time),'HH24:mi') as login_time where login_status = 1,
    to_char(max(create_time),'HH24:mi') as login_out where login_status = 0
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)

getting an error at or near ","

Don't know how to write where condition in to_char function.

Body:
You need a CASE expression, not a WHERE:

select
    to_char(date_trunc('day',create_time),'DD Month YYYY') as date,
    case when login_status = 1 then to_char(min(create_time),'HH24:mi') end as login_time,
    case when login_status = 0 then to_char(max(create_time),'HH24:mi') end as login_out
from
    users.access_log
where
    user_id = 1010
group by
    user_id, actionlink_id, date_trunc('day', create_time)


问:
The keystroke command in applescript can't identify case
```<code>tell application "iTerm" to activate
delay 0.1
tell application "System Events" to tell process "iTerm"
   keystroke "Lsj!"
end tell
</code>```

I want know how can i get the right way to enter some character. keystroke command can't identify case.

答:
That should work</p>

```<code>tell application "iTerm" to activate
delay 0.1
tell application "System Events" to tell process "iTerm"
key code 37 using {shift down}
key code 1
key code 38
end tell
</code>```

Body:
tell application "iTerm" to activate
delay 0.1
tell application "System Events" to tell process "iTerm"
   keystroke "Lsj!"
end tell

I want know how can i get the right way to enter some character. keystroke command can't identify case.

Body:
That should work

tell application "iTerm" to activate
delay 0.1
tell application "System Events" to tell process "iTerm"
key code 37 using {shift down}
key code 1
key code 38
end tell


问:
Button that updates number on all sessions
I've tried a lot of ways, like for example the fs module, but I just can't find out how to implement this. I need a button that:

Updates by one whenever any user presses the button

Persists on the server

Does anyone know how to do this?

答:
If you are new and need to build something that stores stuff on the server you have a lot to learn. If you just need to solve this simple problem and get things working you could make huge progress using a hosted backend service. If you do this you can write a couple of lines in JS and the job will be done. Most offer a free account.

One such service is built.io see link below:

https://docs.built.io/api-reference

```<code>var project = Built.App('blt5d4sample2633b').Class('score').Object();
project = project.increment('points',10); //Increases points field value by 10
</code>```

That code above would update the score by 10 and store it , you can then retreive it when you show the page. All users would see the score update.

There are realtime backend services too which are very good.

An example is:

www.firebase.com

You would need to decide which one is best for you, add their script to your page add a button, hook the click event upto a function that you would then add the simple code to update the score. See above.

It a nutshell that would be it. You can probably get it working in under 1 hour if you follow the guides on the vendors site.

Firebase is backed by google and has a huge online community.

Body:
If you are new and need to build something that stores stuff on the server you have a lot to learn. If you just need to solve this simple problem and get things working you could make huge progress using a hosted backend service. If you do this you can write a couple of lines in JS and the job will be done. Most offer a free account.

One such service is built.io see link below:

https://docs.built.io/api-reference

var project = Built.App('blt5d4sample2633b').Class('score').Object();
project = project.increment('points',10); //Increases points field value by 10

That code above would update the score by 10 and store it , you can then retreive it when you show the page. All users would see the score update.

There are realtime backend services too which are very good.

An example is:

www.firebase.com

You would need to decide which one is best for you, add their script to your page add a button, hook the click event upto a function that you would then add the simple code to update the score. See above.

It a nutshell that would be it. You can probably get it working in under 1 hour if you follow the guides on the vendors site.

Firebase is backed by google and has a huge online community.


问:
System.ComponentModel.InotifyPropertyChanging error
I am developing a windows form app that will need to run on a production machine that is only running .net 2.0.

in this project i am, however, using some 3.0+ related classes (ie linq) , therefore even know i have set the target framework to 2.0 in visual studio, i have copied all 3.0+ related dlls to to production server but i am getting the following error when i am working with multi threating  any idea why ?

```<code>System.ComponentModel.INotifyPropertyChanging' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
</code>```

here are the list of dlls i have copied to release folder

System.dll

System.Core.dll

System.Data.dll

System.Data.Linq.dll

System.Deployment.dll

System.Windows.Forms.dll

as you can see i have copied the latest version of System.dll to the target folder but the app seems to be using the one installed on machine and ignore mine

any help would greatly be appreciated

thanks

答:
That interface was added to System.dll in a service pack; 2.0 SP 1 (also shipped with .Net 3.5); http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanging(v=VS.90).aspx

It cannot work on vanilla 2.0.

Either install the 2.0 SP 1 service pack (or 3.5), or live without it.

Body:
I am developing a windows form app that will need to run on a production machine that is only running .net 2.0.

in this project i am, however, using some 3.0+ related classes (ie linq) , therefore even know i have set the target framework to 2.0 in visual studio, i have copied all 3.0+ related dlls to to production server but i am getting the following error when i am working with multi threating  any idea why ?

System.ComponentModel.INotifyPropertyChanging' from assembly 'System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

here are the list of dlls i have copied to release folder

System.dll

System.Core.dll

System.Data.dll

System.Data.Linq.dll

System.Deployment.dll

System.Windows.Forms.dll

as you can see i have copied the latest version of System.dll to the target folder but the app seems to be using the one installed on machine and ignore mine

any help would greatly be appreciated

thanks


问:
How are order line items exposed?
In the restbucks project, an order has a private list of line items. I can't figure out how this field is exposed via rest api when getting a single order. It has no public getter or anything. Is it the mixins?</p>

答:
@Data, @NoArgsConstructor, @AllArgsConstructor, @EqualsAndHashCode are Lombok annotations, that are used to auto-generate a boilerplate code.

@Data
@Entity
@NoArgsConstructor(force = true)
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class LineItem extends AbstractEntity {

  private final String name;
  private final int quantity;
  private final Milk milk;
  private final Size size;
  private final MonetaryAmount price;

  public LineItem(String name, MonetaryAmount price) {
    this(name, 1, Milk.SEMI, Size.LARGE, price);
  }
}
```

<p>You can compare this code with delomboked one (welcome to Lombok-funs club )):</p>

<pre class="lang-java prettyprint-override"><code>@Entity
public class LineItem extends AbstractEntity {

    private final String name;
    private final int quantity;
    private final Milk milk;
    private final Size size;
    private final MonetaryAmount price;

    public LineItem(String name, MonetaryAmount price) {
        this(name, 1, Milk.SEMI, Size.LARGE, price);
    }

    public LineItem(String name, int quantity, Milk milk, Size size, MonetaryAmount price) {
        this.name = name;
        this.quantity = quantity;
        this.milk = milk;
        this.size = size;
        this.price = price;
    }

    public LineItem() {
        this.name = null;
        this.quantity = 0;
        this.milk = null;
        this.size = null;
        this.price = null;
    }

    public String getName() {
        return this.name;
    }

    public int getQuantity() {
        return this.quantity;
    }

    public Milk getMilk() {
        return this.milk;
    }

    public Size getSize() {
        return this.size;
    }

    public MonetaryAmount getPrice() {
        return this.price;
    }

    public String toString() {
        return "LineItem(name=" + this.getName() + ", quantity=" + this.getQuantity() + ", milk=" + this.getMilk() + ", size=" + this.getSize() + ", price=" + this.getPrice() + ")";
    }

    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof LineItem)) return false;
        final LineItem other = (LineItem) o;
        if (!other.canEqual((Object) this)) return false;
        final Object this$name = this.getName();
        final Object other$name = other.getName();
        if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
        if (this.getQuantity() != other.getQuantity()) return false;
        final Object this$milk = this.getMilk();
        final Object other$milk = other.getMilk();
        if (this$milk == null ? other$milk != null : !this$milk.equals(other$milk)) return false;
        final Object this$size = this.getSize();
        final Object other$size = other.getSize();
        if (this$size == null ? other$size != null : !this$size.equals(other$size)) return false;
        final Object this$price = this.getPrice();
        final Object other$price = other.getPrice();
        if (this$price == null ? other$price != null : !this$price.equals(other$price)) return false;
        return true;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        result = result * PRIME + this.getQuantity();
        final Object $milk = this.getMilk();
        result = result * PRIME + ($milk == null ? 43 : $milk.hashCode());
        final Object $size = this.getSize();
        result = result * PRIME + ($size == null ? 43 : $size.hashCode());
        final Object $price = this.getPrice();
        result = result * PRIME + ($price == null ? 43 : $price.hashCode());
        return result;
    }

    protected boolean canEqual(Object other) {
        return other instanceof LineItem;
    }
}
</code>```

Title: How are order line items exposed?

Body:
@Data, @NoArgsConstructor, @AllArgsConstructor, @EqualsAndHashCode are Lombok annotations, that are used to auto-generate a boilerplate code.

@Data
@Entity
@NoArgsConstructor(force = true)
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class LineItem extends AbstractEntity {

  private final String name;
  private final int quantity;
  private final Milk milk;
  private final Size size;
  private final MonetaryAmount price;

  public LineItem(String name, MonetaryAmount price) {
    this(name, 1, Milk.SEMI, Size.LARGE, price);
  }
}

You can compare this code with delomboked one (welcome to Lombok-funs club )):

@Entity
public class LineItem extends AbstractEntity {

    private final String name;
    private final int quantity;
    private final Milk milk;
    private final Size size;
    private final MonetaryAmount price;

    public LineItem(String name, MonetaryAmount price) {
        this(name, 1, Milk.SEMI, Size.LARGE, price);
    }

    public LineItem(String name, int quantity, Milk milk, Size size, MonetaryAmount price) {
        this.name = name;
        this.quantity = quantity;
        this.milk = milk;
        this.size = size;
        this.price = price;
    }

    public LineItem() {
        this.name = null;
        this.quantity = 0;
        this.milk = null;
        this.size = null;
        this.price = null;
    }

    public String getName() {
        return this.name;
    }

    public int getQuantity() {
        return this.quantity;
    }

    public Milk getMilk() {
        return this.milk;
    }

    public Size getSize() {
        return this.size;
    }

    public MonetaryAmount getPrice() {
        return this.price;
    }

    public String toString() {
        return "LineItem(name=" + this.getName() + ", quantity=" + this.getQuantity() + ", milk=" + this.getMilk() + ", size=" + this.getSize() + ", price=" + this.getPrice() + ")";
    }

    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof LineItem)) return false;
        final LineItem other = (LineItem) o;
        if (!other.canEqual((Object) this)) return false;
        final Object this$name = this.getName();
        final Object other$name = other.getName();
        if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
        if (this.getQuantity() != other.getQuantity()) return false;
        final Object this$milk = this.getMilk();
        final Object other$milk = other.getMilk();
        if (this$milk == null ? other$milk != null : !this$milk.equals(other$milk)) return false;
        final Object this$size = this.getSize();
        final Object other$size = other.getSize();
        if (this$size == null ? other$size != null : !this$size.equals(other$size)) return false;
        final Object this$price = this.getPrice();
        final Object other$price = other.getPrice();
        if (this$price == null ? other$price != null : !this$price.equals(other$price)) return false;
        return true;
    }

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        result = result * PRIME + this.getQuantity();
        final Object $milk = this.getMilk();
        result = result * PRIME + ($milk == null ? 43 : $milk.hashCode());
        final Object $size = this.getSize();
        result = result * PRIME + ($size == null ? 43 : $size.hashCode());
        final Object $price = this.getPrice();
        result = result * PRIME + ($price == null ? 43 : $price.hashCode());
        return result;
    }

    protected boolean canEqual(Object other) {
        return other instanceof LineItem;
    }
}


问:
Spark job getting stuck at 99% and doesn't continue
I have a basic spark job that does a couple of joins. The 3 data frames that get joined are somewhat big, nearly 2 billion records in each of them. I have a spark infrastructure that automatically scales up nodes whenever necessary. It seems like a very simple spark SQL query whose results I write to disk. But the job always gets stuck at 99% when I look at from Spark UI.

Bunch of things I have tried are:

Increase the number of executors and executor memory.

Use repartition while writing the file.

Use the native spark join  instead of spark SQL join etc

However, none of these things have worked. It would be great if somebody can share the experience of solving this problem. Thanks in advance.

答:
Because of the join operations, all records with the same key are shuffled to the same executor. If you data is skewed, which means that there is one or a few keys which are very dominant in terms of the number of rows. Then this single executor which has to process all these rows. Essentially your Spark job becomes single threaded since this single key needs to be processed by a single thread.

Repartitioning will not help since your join operation will shuffle the data again by hashing the join key. You could try to increase the number of partitions in case of an unlucky hash.

This video explains the problems, and suggests a solution:
https://www.youtube.com/watch?v=6zg7NTw-kTQ

Cheers, Fokko


问:
Can we hide/show Relative Layout when Recycleview list is scrolling?
This is my XML Layout in which I want to Show/Hide relative layout (@+id/room_header_rl) not actiob_bar.Please any one has idea how to do it?
I try using CoordinatorLayout but not get success.
Thank you in advance.

My XML Layout :

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar"/>

    <RelativeLayout
        android:id="@+id/room_header_rl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:padding="10dp"
        android:layout_below="@+id/app_bar"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <RelativeLayout
            android:id="@+id/room_details_rl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/room_img"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_marginRight="10dp"
                android:scaleType="centerCrop"
                android:layout_centerVertical="true"/>

            <RelativeLayout
                android:id="@+id/rooom_rl"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/room_img"
                android:layout_centerVertical="true">

                <TextView
                    android:id="@+id/roomname_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:textSize="15sp"
                    android:textStyle="bold"
                    android:maxLines="2"
                    android:drawablePadding="5dp"/>

                <TextView
                    android:id="@+id/roomdate_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:layout_below="@+id/roomname_tv"
                    android:layout_marginTop="10dp"/>

                <EditText
                    android:id="@+id/roommembers_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:textSize="14sp"
                    android:layout_below="@+id/roomdate_tv"
                    android:focusable="false"/>

            </RelativeLayout>

        </RelativeLayout>

        <TextView
            android:id="@+id/welcome_msg_txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="4"
            android:padding="5dp"
            android:gravity="center"
            android:textStyle="bold"
            android:background="@color/light_gray"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/room_details_rl"
            android:layout_centerHorizontal="true" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:background="@color/gray"
            android:layout_below="@+id/welcome_msg_txt"/>

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/roomchat_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="20dp"
        android:layout_above="@+id/divider"
        android:layout_below="@+id/room_header_rl"/>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/gray"
        android:layout_above="@+id/entertext_rl"/>

<RelativeLayout
    android:id="@+id/entertext_rl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">

    <EditText
        android:id="@+id/entertext_ed"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:maxLines="3"
        android:textSize="16sp"
        android:capitalize="sentences"
        android:hint="@string/entertext"
        android:layout_toLeftOf="@id/attech_btn"
        android:background="@android:color/transparent"
        android:layout_centerVertical="true"/>

    <Button
        android:id="@+id/attech_btn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:layout_toLeftOf="@+id/send_btn"
        android:background="@drawable/attach"/>

    <Button
        android:id="@+id/send_btn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:background="@drawable/send_btn"/>

</RelativeLayout>
</code>```

I am trying https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling%28part3%29/ but it's show/hide only actionBar.

答:
did you try to hide it programatically ?</p>

```<code>recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            my_relative_layout.setVisibility(View.GONE);
        }
    });
</code>```

Body:
This is my XML Layout in which I want to Show/Hide relative layout (@+id/room_header_rl) not actiob_bar.Please any one has idea how to do it?
I try using CoordinatorLayout but not get success.
Thank you in advance.

My XML Layout :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar"/>

    <RelativeLayout
        android:id="@+id/room_header_rl"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:padding="10dp"
        android:layout_below="@+id/app_bar"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <RelativeLayout
            android:id="@+id/room_details_rl"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/room_img"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:layout_marginRight="10dp"
                android:scaleType="centerCrop"
                android:layout_centerVertical="true"/>

            <RelativeLayout
                android:id="@+id/rooom_rl"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_toRightOf="@+id/room_img"
                android:layout_centerVertical="true">

                <TextView
                    android:id="@+id/roomname_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:textSize="15sp"
                    android:textStyle="bold"
                    android:maxLines="2"
                    android:drawablePadding="5dp"/>

                <TextView
                    android:id="@+id/roomdate_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:layout_below="@+id/roomname_tv"
                    android:layout_marginTop="10dp"/>

                <EditText
                    android:id="@+id/roommembers_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textColor="@color/black"
                    android:textSize="14sp"
                    android:layout_below="@+id/roomdate_tv"
                    android:focusable="false"/>

            </RelativeLayout>

        </RelativeLayout>

        <TextView
            android:id="@+id/welcome_msg_txt"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="4"
            android:padding="5dp"
            android:gravity="center"
            android:textStyle="bold"
            android:background="@color/light_gray"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="10dp"
            android:layout_below="@+id/room_details_rl"
            android:layout_centerHorizontal="true" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:background="@color/gray"
            android:layout_below="@+id/welcome_msg_txt"/>

    </RelativeLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/roomchat_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginTop="20dp"
        android:layout_above="@+id/divider"
        android:layout_below="@+id/room_header_rl"/>

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/gray"
        android:layout_above="@+id/entertext_rl"/>

<RelativeLayout
    android:id="@+id/entertext_rl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">

    <EditText
        android:id="@+id/entertext_ed"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:maxLines="3"
        android:textSize="16sp"
        android:capitalize="sentences"
        android:hint="@string/entertext"
        android:layout_toLeftOf="@id/attech_btn"
        android:background="@android:color/transparent"
        android:layout_centerVertical="true"/>

    <Button
        android:id="@+id/attech_btn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:layout_toLeftOf="@+id/send_btn"
        android:background="@drawable/attach"/>

    <Button
        android:id="@+id/send_btn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:background="@drawable/send_btn"/>

</RelativeLayout>

I am trying https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling%28part3%29/ but it's show/hide only actionBar.

Body:
did you try to hide it programatically ?

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            my_relative_layout.setVisibility(View.GONE);
        }
    });


问:
Clicking on radio button
I have following rendered HTML

```<code><div class="col-xs-8 no-padding">
    <label class="radio-inline gender-label">
        <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        <label for="male-signup">Male</label>
    </label>
    <label class="radio-inline gender-label">
        <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        <label for="female-signup">Female</label>
    </label>
</div>
</code>```

So, to select Male radio button I did the following

```<code>element(by.id('male-signup')).click();
</code>```

It complained Element not visible

Then i did

```<code>var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();
</code>```

It complained Failed: Wait timed out after 5005ms

What is wrong with code?
I simply want to click on Gender male radio button

Update:

As per one of the answer below from 'Ernst Zwingli' I tried following. However, It still complains Failed: Wait timed out after 5005ms

```<code>var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();
</code>```

答:
Try this for your timeout error .

Delete setTimeout 10000 until setTimeout 35000 If you dont need it.

```<code>$(document).ready(function() {
var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
    setTimeout(gender, 2000);
    setTimeout(gender, 5000);
    setTimeout(gender, 10000);
    setTimeout(gender, 15000);
    setTimeout(gender, 20000);
    setTimeout(gender, 25000);
    setTimeout(gender, 30000);
    setTimeout(gender, 35000);
gender.click();

})
</code>```

Title: Clicking on radio button

Body:
I have following rendered HTML

        <input type="radio" name="gender" id="male-signup" value="MALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        Male

        <input type="radio" name="gender" id="female-signup" value="FEMALE" ng-model="signup.gender" required="" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required">
        Female

So, to select Male radio button I did the following

element(by.id('male-signup')).click();

It complained Element not visible

Then i did

var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();

It complained Failed: Wait timed out after 5005ms

What is wrong with code?
I simply want to click on Gender male radio button

Update:

As per one of the answer below from 'Ernst Zwingli' I tried following. However, It still complains Failed: Wait timed out after 5005ms

var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
browser.wait(EC.visibilityOf(gender), 5000);
gender.click();

Body:
Try this for your timeout error .

Delete setTimeout 10000 until setTimeout 35000 If you dont need it.

$(document).ready(function() {
var EC = protractor.ExpectedConditions;
var gender = element(by.id('male-signup')).element(by.xpath('//*[@id="top"]/div[2]/div/div/div/form/div[8]/div[2]/label[1]/label'));
    setTimeout(gender, 2000);
    setTimeout(gender, 5000);
    setTimeout(gender, 10000);
    setTimeout(gender, 15000);
    setTimeout(gender, 20000);
    setTimeout(gender, 25000);
    setTimeout(gender, 30000);
    setTimeout(gender, 35000);
gender.click();

})


问:
How to show comments dynamically like Stack overflow using Asp.net and Jquery?
I made one small web application using Asp.net and C#, I can get the comments by refreshing the entire page. But I don't want to show like that.

For example

There are Client A,B,C. All are in same page. When Client A do comment for the post, It has to appear on Client B and C with out refreshing, Exactly same like Stackoverflow

What kind of thing I should use for this Technics. Thanks

答:
You should use SignalR library based on websocket technology
And SQLDependency to trigger db changes</p>


问:
Check variable equality against a list of values
I'm checking a variable, say foo, for equality to a number of values. For example,

```<code>if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}
</code>```

The point is that it is rather much code for such a trivial task. I came up with the following:

```<code>if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}
</code>```

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

答:
```<code>var a = [1,2,3];

if ( a.indexOf( 1 ) !== -1 ) { }
</code>```

Note that indexOf is not in the core ECMAScript. You'll need to have a snippet for IE and possibly other browsers that dont support Array.prototype.indexOf.

```<code>if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
</code>```

Body:
I'm checking a variable, say foo, for equality to a number of values. For example,

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

The point is that it is rather much code for such a trivial task. I came up with the following:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

but also this does not completely appeal to me, because I have to give redundant values to the items in the object.

Does anyone know a decent way of doing an equality check against multiple values?

Body:
var a = [1,2,3];

if ( a.indexOf( 1 ) !== -1 ) { }

Note that indexOf is not in the core ECMAScript. You'll need to have a snippet for IE and possibly other browsers that dont support Array.prototype.indexOf.

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}


答:
Try this instead:

Start the for from 0 and use sc.Next(); instead of sc.nextLine();:

```<code>  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String [] pNames = new String[4];

for(int i = 0; i < pNames.length; i++) {

    int a = i+1;
    System.out.print("Enter name of Player" + " " + a + " > ");

    pNames[i] = sc.next();
}

System.out.println("Hello" + " " + pNames[0]);
System.out.println("Hello" + " " + pNames[1]);
System.out.println("Hello" + " " + pNames[2]);
System.out.println("Hello" + " " + pNames[3]);
}
</code>```

}

Title: Input and Store names in array - Java

Body:
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy

Output a hello message to greet each player.

Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy

Answer:

  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}

}

Body:
Try this instead:

Start the for from 0 and use sc.Next(); instead of sc.nextLine();:

  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

String [] pNames = new String[4];

for(int i = 0; i < pNames.length; i++) {

    int a = i+1;
    System.out.print("Enter name of Player" + " " + a + " > ");

    pNames[i] = sc.next();
}

System.out.println("Hello" + " " + pNames[0]);
System.out.println("Hello" + " " + pNames[1]);
System.out.println("Hello" + " " + pNames[2]);
System.out.println("Hello" + " " + pNames[3]);
}

}


问:
RegisterResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
Using new android studio with new 3.0.0 Gradle pluging.

When building some warning happened:

```<code>registerResGeneratingTask is deprecated, use
registerGeneratedFolders(FileCollection)
</code>```

答: For me this warning disappeared when I turned off fabric gradle plugin, o please check if you use fabric or another plugin that i responsible for this warning.</p>

ContentLicense: CC BY-SA 4.0

Body:
Using new android studio with new 3.0.0 Gradle pluging.

When building some warning happened:

registerResGeneratingTask is deprecated, use
registerGeneratedFolders(FileCollection)


问:
Negation of %in% in R
Is there a short negation of %in% in R like !%in% or %!in%?

Of course I can negate c("A", "B") %in% c("B", "C") by !(c("A", "B") %in% c("B", "C")) (cf. this question) but I would prefere a more straight forward approach and save a pair of brackets (alike presumably most people would prefer c("A", "B") != c("B", "C") over !(c("A", "B") == c("B", "C"))).

答: The    %!in% function is now available in the    library(operators)

Title: Negation of %in% in R


问:
Why does the GridLayout cover the whole screen?
I have the following HTML code:

```<code><GridLayout>
  <GridLayout #background class="background">
  </GridLayout>

  <StackLayout #initialContainer class="initial-container">
    <Image src="res://logo_login">
    </Image>
    ....
    ....
  </StackLayout>
</GridLayout>
</code>```

My question is about the GridLayout with the background class.

This is the CSS for the class:

```<code>.background {
  background-image: url("res://apple");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}
</code>```

Apparently it's the actual background (the orange background here, not the logo!).

Question
I don't understand why the GridLayout covers the whole screen. And even if it does, I was expecting the StackLayout to be after the GridLayout. I already know that background-size:cover covers the whole space, but why does the GridLayout cover the whole screen as well? And why does the logo and title display as if they are absolutely positioned when they are not in my CSS?

答: Your outer layout is a GridLayout, if you dont specify rows and columns, any layout or item inside the layout will be stacked on top of each other in the top-left-most grid cell, layered in order that they are in the html. To get around this, swap your outer layout to a StackLayout</p>

Body:
I have the following HTML code:

<GridLayout>
  <GridLayout #background class="background">
  </GridLayout>

  <StackLayout #initialContainer class="initial-container">
    <Image src="res://logo_login">
    </Image>
    ....
    ....
  </StackLayout>
</GridLayout>

My question is about the GridLayout with the background class.

This is the CSS for the class:

.background {
  background-image: url("res://apple");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

Apparently it's the actual background (the orange background here, not the logo!).

Question
I don't understand why the GridLayout covers the whole screen. And even if it does, I was expecting the StackLayout to be after the GridLayout. I already know that background-size:cover covers the whole space, but why does the GridLayout cover the whole screen as well? And why does the logo and title display as if they are absolutely positioned when they are not in my CSS?


问:
Firebase (web) creating/updating users different from current
I'd like to know if it's possible, from website, to create/update firebase users different from the one signed-in: in other words without using console.

Firebase docs seems to mention creating/updating only for the current user; if that's possible for other users too can anybody kindly address me to some docs.
Thanks.

答:
Technically, a web-based application could create and update a different user's profile, but the user performing these actions would need to authenticate as the user they want to manipulate.

It sounds like you're looking for the Firebase Admin Auth SDK though:

You can use the Admin SDK to manage your users or to manage authentication tokens. [...]

User Management

It is not always convenient to have to visit the Firebase console in order to manage your Firebase users. The admin user management API provides programmatic access to those same users. It even allows you to do things the Firebase console cannot, such as retrieving a user's full data and changing a user's password, email address or phone number.

This SDK does however need to be developed on a Node.js, Java or Python server or through Firebase Cloud Functions in order to be secure, but you could write a web frontend that then integrates with this server.

By way of example, creating a user through the Admin SDK in Node.js, you can:

```<code>admin.auth().createUser({
  email: "user@example.com",
  emailVerified: false,
  phoneNumber: "+11234567890",
  password: "secretPassword",
  displayName: "John Doe",
  photoURL: "http://www.example.com/12345678/photo.png",
  disabled: false
});
</code>```

Body:
Technically, a web-based application could create and update a different user's profile, but the user performing these actions would need to authenticate as the user they want to manipulate.

It sounds like you're looking for the Firebase Admin Auth SDK though:

You can use the Admin SDK to manage your users or to manage authentication tokens. [...]

User Management

It is not always convenient to have to visit the Firebase console in order to manage your Firebase users. The admin user management API provides programmatic access to those same users. It even allows you to do things the Firebase console cannot, such as retrieving a user's full data and changing a user's password, email address or phone number.

This SDK does however need to be developed on a Node.js, Java or Python server or through Firebase Cloud Functions in order to be secure, but you could write a web frontend that then integrates with this server.

By way of example, creating a user through the Admin SDK in Node.js, you can:

admin.auth().createUser({
  email: "user@example.com",
  emailVerified: false,
  phoneNumber: "+11234567890",
  password: "secretPassword",
  displayName: "John Doe",
  photoURL: "http://www.example.com/12345678/photo.png",
  disabled: false
});


问:
Is there a quick way to convert all values in a column to True/False values?
For example I have the following table

```<code>+--------+-----------------------+--+
|   Id   |    BuyingAttribute    |  |
+--------+-----------------------+--+
| 1      |    Low Price          |  |
| 1      |    Good Communication |  |
| 1      |    English Speaker    |  |
| 2      |    Low Price          |  |
| ...etc | ...etc                |  |
+--------+-----------------------+--+
</code>```

Is there a way that I could transfer all the values automatically to yes/No values. I know that I can use case statement  like so

```<code>SELECT
    Id,
    CASE WHEN BuyingAttribute = 'Low Price' THEN True ELSE False END AS Buying Attribute
FROM
    myTable
</code>```

However, is there an automated  method, because it will be time consuming if I have 50 values and write 50 case statement to generate results like below

```<code>+----+-----------------------+---------------+-------------------------+----------------------+
| Id |  BuyingAttribute      | BA(Low Price) |  BA(Good Communication) |  BA(English Speaker) |
+----+-----------------------+---------------+-------------------------+----------------------+
|  1 |    Low Price          |   True        |   False                 |   False              |
|  1 |    Good Communication |   False       |   True                  |   False              |
|  1 |    English Speaker    |   False       |   False                 |   True               |
|  2 |    Low Price          |   True        |   False                 |   False              |
|    |                       |               |                         |                      |
+----+-----------------------+---------------+-------------------------+----------------------+
</code>```

答:
```<code>    Create table #tmp (Id int, BuyingAttribute VARCHAR(30))

    insert into #tmp values(1,'Low Price')
    insert into #tmp values(1,'Good Communication')
    insert into #tmp values(1,'English Speaker')
    insert into #tmp values(2,'Low Price')

    SELECT * FROM #tmp

    SELECT * ,
        CASE  BuyingAttribute WHEN 'Low Price' THEN 'True' ELSE 'False' END [BA(Low Price)],
        CASE  BuyingAttribute WHEN 'Good Communication' THEN 'True' ELSE 'False' END [BA(Good Communication)],
        CASE  BuyingAttribute WHEN 'English Speaker' THEN 'True' ELSE 'False' END [BA(English Speaker)]

    FROM #tmp
    Drop table #tmp
</code>```

Body:
For example I have the following table

+--------+-----------------------+--+
|   Id   |    BuyingAttribute    |  |
+--------+-----------------------+--+
| 1      |    Low Price          |  |
| 1      |    Good Communication |  |
| 1      |    English Speaker    |  |
| 2      |    Low Price          |  |
| ...etc | ...etc                |  |
+--------+-----------------------+--+

Is there a way that I could transfer all the values automatically to yes/No values. I know that I can use case statement  like so

SELECT
    Id,
    CASE WHEN BuyingAttribute = 'Low Price' THEN True ELSE False END AS Buying Attribute
FROM
    myTable

However, is there an automated  method, because it will be time consuming if I have 50 values and write 50 case statement to generate results like below

+----+-----------------------+---------------+-------------------------+----------------------+
| Id |  BuyingAttribute      | BA(Low Price) |  BA(Good Communication) |  BA(English Speaker) |
+----+-----------------------+---------------+-------------------------+----------------------+
|  1 |    Low Price          |   True        |   False                 |   False              |
|  1 |    Good Communication |   False       |   True                  |   False              |
|  1 |    English Speaker    |   False       |   False                 |   True               |
|  2 |    Low Price          |   True        |   False                 |   False              |
|    |                       |               |                         |                      |
+----+-----------------------+---------------+-------------------------+----------------------+


问:
Count distinct values
I have a data set asking a customer how many pets they have for example. Is there a way with one query I can count the distinct values (1,2,3, etc)?
Thanks!

```<code>+----------+------+
| Customer | Pets |
+----------+------+
|       20 |    2 |
|       21 |    3 |
|       22 |    3 |
|       23 |    2 |
|       24 |    4 |
+----------+------+
</code>```

What I want is a list saying:

2 had 2 Pets

2 had 3 Pets

1 had 4 Pets

答:
Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

```<code>+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+
</code>```

then

```<code>SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets
</code>```

would return:

```<code>+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+
</code>```

as you need.

Title: Count distinct values

Body:
I have a data set asking a customer how many pets they have for example. Is there a way with one query I can count the distinct values (1,2,3, etc)?
Thanks!

+----------+------+
| Customer | Pets |
+----------+------+
|       20 |    2 |
|       21 |    3 |
|       22 |    3 |
|       23 |    2 |
|       24 |    4 |
+----------+------+

What I want is a list saying:

2 had 2 Pets

2 had 3 Pets

1 had 4 Pets

Body:
Ok, I deleted my previous answer because finally it was not what willlangford was looking for, but I made my point that maybe we were all misunderstanding the question.

I also thought of the SELECT DISTINCT... thing at first, but it seemed too weird to me that someone needed to know how many people had a different number of pets than the rest... thats why I thought that maybe the question was not clear enough.

So, now that the real question meaning is clarified, making a subquery for this its quite an overhead, I would preferably use a GROUP BY clause.

Imagine you have the table customer_pets like this:

+-----------------------+
|  customer  |   pets   |
+------------+----------+
| customer1  |    2     |
| customer2  |    3     |
| customer3  |    2     |
| customer4  |    2     |
| customer5  |    3     |
| customer6  |    4     |
+------------+----------+

then

SELECT count(customer) AS num_customers, pets FROM customer_pets GROUP BY pets

would return:

+----------------------------+
|  num_customers  |   pets   |
+-----------------+----------+
|        3        |    2     |
|        2        |    3     |
|        1        |    4     |
+-----------------+----------+

as you need.


问:
resolving promise from another function
How does promise chaining inside a function works?
In the following code:

```<code>     promiseA() {
            return anotherPromise().then( res => {
                   // resolution of promise A
             })
     };

      promiseB() {
             promiseA().then( res => {
                     // resolution of promise B
              })
      }
</code>```

I tested this code and I get that resolution of B is always done after A is resolved. However, I can't find any documentation. Will resolution of promise B always happens after resolution of Promise A done, or is my test just one case of race condition?

答:
Yes, it will always resolve A first before B. If you re-wrote your code without the indirection of separate methods what you have is simply:

```<code>anotherPromise().then(...A...).then(...B...)
</code>```

And that should make it clear that the code inside the A then must always run before the code inside the B then.

A simple test confirms. You can run this a million times and A will always resolve before B:

function anotherPromise(){
  return new Promise((resolve,reject) => {
   setTimeout(resolve,1000);
  });
}

function promiseA(){
   return anotherPromise().then( res => {
      console.log("Resolve promiseA");
      return res;
  });
}

function promiseB(){
    return promiseA().then(res => {
     console.log("Resolve promiseB");
      return res;
    })
}

promiseB();```

Title: resolving promise from another function

Body:
How does promise chaining inside a function works?
In the following code:

     promiseA() {
            return anotherPromise().then( res => {
                   // resolution of promise A
             })
     };

      promiseB() {
             promiseA().then( res => {
                     // resolution of promise B
              })
      }

I tested this code and I get that resolution of B is always done after A is resolved. However, I can't find any documentation. Will resolution of promise B always happens after resolution of Promise A done, or is my test just one case of race condition?

Body:
Yes, it will always resolve A first before B. If you re-wrote your code without the indirection of separate methods what you have is simply:

anotherPromise().then(...A...).then(...B...)

And that should make it clear that the code inside the A then must always run before the code inside the B then.

A simple test confirms. You can run this a million times and A will always resolve before B:

function anotherPromise(){
  return new Promise((resolve,reject) => {
   setTimeout(resolve,1000);
  });
}

function promiseA(){
   return anotherPromise().then( res => {
      console.log("Resolve promiseA");
      return res;
  });
}

function promiseB(){
    return promiseA().then(res => {
     console.log("Resolve promiseB");
      return res;
    })
}

promiseB();


问:
Input and Store names in array - Java
I have been trying out this questions however I still cannot find the solution to it. Any help is appreciated! Thanks

Question - Declare and create an array to store the names of four players.  Call the array pNames.

Ask the user to input the names of the four players and store their names in the pNames array.

```<code>  Enter Name of Player 1 > Johnny
  Enter Name of Player 2 > Jackie
  Enter Name of Player 3 > Jessie
  Enter Name of Player 4 > Jeremy
</code>```

Output a hello message to greet each player.

```<code>Hello Johnny
Hello Jackie
Hello Jessie
Hello Jeremy
</code>```

Answer:

```<code>  import java.util.Scanner;
  public class Q2 {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    String [] pNames = new String[4];

    for(int i = 1; i <= pNames.length; i++) {

        System.out.print("Enter name of Player" + " " + i + " > ");

        pNames[i] = sc.nextLine();
    }

    System.out.println("Hello" + " " + pNames[0]);
    System.out.println("Hello" + " " + pNames[1]);
    System.out.println("Hello" + " " + pNames[2]);
    System.out.println("Hello" + " " + pNames[3]);
}
</code>```

}

答:
Simply change this line:

```<code>pNames[i] = sc.nextLine();
</code>```

to this:

```<code>pNames[i-1] = sc.nextLine();
</code>```

Since you are accessing 1 to 4, your array is actually on the range 0-3, so you need to subtract one.

Title: Input and Store names in array - Java

Body:
Simply change this line:

pNames[i] = sc.nextLine();

to this:

pNames[i-1] = sc.nextLine();

Since you are accessing 1 to 4, your array is actually on the range 0-3, so you need to subtract one.


问:
NSAttributedString - add writing direction for Arabic Language
I have an html content that i want to show on UILabel.

```<code>NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
return attrStr;
</code>```

This works good for English Language (LTR semantic), but since i want to support arabic as well the above method keeps the attributed string LTR.
Inspite of using this code : self.view.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

I've tried

```<code>NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc]initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[mutableAttributedString addAttribute:NSWritingDirectionAttributeName value:@[@(NSWritingDirectionRightToLeft | NSWritingDirectionOverride)] range:NSMakeRange(0, string.length)];
return mutableAttributedString;
</code>```

Still the same. Any suggestions are welcome.
Thanks

答:
Hope will helpful to you for right side alignment!!

```<code>NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentRight;

NSDictionary *attr = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                   NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};

NSError *error = nil;

NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc]initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:attr documentAttributes:nil error:&error];

[attributedText addAttribute:NSParagraphStyleAttributeName
                   value:paragraphStyle
                   range:NSMakeRange(0, attributedText.length)];
return attributedText;
</code>```

Body:
I have an html content that i want to show on UILabel.

NSAttributedString *attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}
documentAttributes:nil error:nil];
return attrStr;

This works good for English Language (LTR semantic), but since i want to support arabic as well the above method keeps the attributed string LTR.
Inspite of using this code : self.view.semanticContentAttribute = UISemanticContentAttributeForceRightToLeft;

I've tried

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc]initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
[mutableAttributedString addAttribute:NSWritingDirectionAttributeName value:@[@(NSWritingDirectionRightToLeft | NSWritingDirectionOverride)] range:NSMakeRange(0, string.length)];
return mutableAttributedString;

Still the same. Any suggestions are welcome.
Thanks

Body:
Hope will helpful to you for right side alignment!!

NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentRight;

NSDictionary *attr = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                   NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)};

NSError *error = nil;

NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc]initWithData:[text dataUsingEncoding:NSUTF8StringEncoding] options:attr documentAttributes:nil error:&error];

[attributedText addAttribute:NSParagraphStyleAttributeName
                   value:paragraphStyle
                   range:NSMakeRange(0, attributedText.length)];
return attributedText;


问:
Javascript/Jquery won't change URL parameters in Safari but it will in Chrome
I have this JQuery/JS script that changes $_GET parameters of URL depending on which option from select element is selected. It works fine in Chrome but it won't change $_GET parameters or refresh in Safari 6.1.6.</p>

```<code> $("#promjena").change(function () {
    var v = $("#promjena").val();
    var href = window.location.href;

    if (v === "1") {
        if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=default");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=default");
        } else {
            window.location.href = window.location.href + "?akcija=default";
        }
    }
    if (v === "2") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=kontrola");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=kontrola");
        } else {
            window.location.href = window.location.href + "?akcija=kontrola";
        }
    }
    if (v === "3") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=signal");
        } else if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=signal");
        } else {
            window.location.href = window.location.href + "?akcija=signal";
        }
    }

});
</code>```

答:
try the following

```<code>     var v = $("#promjena").attr("value");
</code>```

OR

```<code>     var v = parseInt($("#promjena").attr("value")).toString();
</code>```

OR

```<code>    var v = parseInt($("#promjena").val()).toString();
</code>```

Body:
I have this JQuery/JS script that changes $_GET parameters of URL depending on which option from select element is selected. It works fine in Chrome but it won't change $_GET parameters or refresh in Safari 6.1.6.

 $("#promjena").change(function () {
    var v = $("#promjena").val();
    var href = window.location.href;

    if (v === "1") {
        if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=default");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=default");
        } else {
            window.location.href = window.location.href + "?akcija=default";
        }
    }
    if (v === "2") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=kontrola");
        } else if (href.includes("?akcija=signal")) {
            window.location.href = href.replace("?akcija=signal", "?akcija=kontrola");
        } else {
            window.location.href = window.location.href + "?akcija=kontrola";
        }
    }
    if (v === "3") {
        if (href.includes("?akcija=default")) {
            window.location.href = href.replace("?akcija=default", "?akcija=signal");
        } else if (href.includes("?akcija=kontrola")) {
            window.location.href = href.replace("?akcija=kontrola", "?akcija=signal");
        } else {
            window.location.href = window.location.href + "?akcija=signal";
        }
    }

});

Body:
try the following

     var v = $("#promjena").attr("value");

OR

     var v = parseInt($("#promjena").attr("value")).toString();

OR

    var v = parseInt($("#promjena").val()).toString();


问:
Assign one model value to another
I have a model DropDownConfiguration which is fetching values from database and populating the dropdown list.

Model:

```<code>public class DropDownConfiguration
    {
        public int ID { get; set; }
        public int Quarter { get; set; }
        public int Year { get; set; }
        public string Project { get; set; }
        public string LineID { get; set; }

    }
</code>```

html:

```<code> @Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, @class = "form-control" })
</code>```

I have another model DetailsConfiguration which has all the fields which need be saved into the database.

```<code> public class DetailsConfiguration
    {

        public int Quarter { get; set; }
        public int Year { get; set; }
        public string Project { get; set; }
        public string ItemModel { get; set; }

    }
</code>```

Controller HttpPost:

```<code>  [ActionName("DetailsForm")]
        [HttpPost]

        public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
        {

            DetailsConfiguration detailsConfig = new DetailsConfiguration();
            detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
            detailsConfig.Year = Convert.ToInt32(form["Year"]);
            detailsConfig.Project = model.detailsConfig.Project;
            detailsConfig.ItemModel = model.detailsConfig.ItemModel;
            detailsConfig.LineID = model.detailsConfig.LineID;

            floorService.SaveDetails(detailsConfig);

            ModelState.Clear();
            ViewBag.message = "Success";
            return View("DetailsForm");

        }
</code>```

Is there anyway to do something like:

```<code>model.detailsConfig.Project = model.dropConfig.Project
</code>```

I need the selection of Project to be posted back to database through DetailsConfiguration.

答:
You could create a mapper which sets the values of the properties in DropDownConfiguration to DetailsConfiguration.

When you change the dropdown you send the selected DropDownConfiguration to the server. You know exactly what properties you can expect here so you can do something like this:

```<code>[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
   //check here if values in parameter are set

   var detailsConfiguration = new DetailsConfiguration {
        Quarter = parameter.Quarter,
        Year = parameter.Year,
        Project = parameter.Project
   }

   //Insert detailsConfiguration to database

   Return Ok();
}
</code>```

Note that you have to make sure you send a DropDownConfiguration object on selecting a dropdown item. You could also only send the values you need like this:

```<code>[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
    //Check here if values in parameter are set and if values are correct

    var detailsConfiguration = new DetailsConfiguration
    {
         Quarter = quarter,
         Year = year,
         Project = project
    }

    //Insert detailsConfiguration to database

    Return Ok();
}
</code>```

Title: Assign one model value to another

Body:
I have a model DropDownConfiguration which is fetching values from database and populating the dropdown list.

Model:

public class DropDownConfiguration
    {
        public int ID { get; set; }
        public int Quarter { get; set; }
        public int Year { get; set; }
        public string Project { get; set; }
        public string LineID { get; set; }

    }

html:

 @Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, @class = "form-control" })

I have another model DetailsConfiguration which has all the fields which need be saved into the database.

 public class DetailsConfiguration
    {

        public int Quarter { get; set; }
        public int Year { get; set; }
        public string Project { get; set; }
        public string ItemModel { get; set; }

    }

Controller HttpPost:

  [ActionName("DetailsForm")]
        [HttpPost]

        public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
        {

            DetailsConfiguration detailsConfig = new DetailsConfiguration();
            detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
            detailsConfig.Year = Convert.ToInt32(form["Year"]);
            detailsConfig.Project = model.detailsConfig.Project;
            detailsConfig.ItemModel = model.detailsConfig.ItemModel;
            detailsConfig.LineID = model.detailsConfig.LineID;

            floorService.SaveDetails(detailsConfig);

            ModelState.Clear();
            ViewBag.message = "Success";
            return View("DetailsForm");

        }

Is there anyway to do something like:

model.detailsConfig.Project = model.dropConfig.Project

I need the selection of Project to be posted back to database through DetailsConfiguration.

Body:
You could create a mapper which sets the values of the properties in DropDownConfiguration to DetailsConfiguration.

When you change the dropdown you send the selected DropDownConfiguration to the server. You know exactly what properties you can expect here so you can do something like this:

[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
   //check here if values in parameter are set

   var detailsConfiguration = new DetailsConfiguration {
        Quarter = parameter.Quarter,
        Year = parameter.Year,
        Project = parameter.Project
   }

   //Insert detailsConfiguration to database

   Return Ok();
}

Note that you have to make sure you send a DropDownConfiguration object on selecting a dropdown item. You could also only send the values you need like this:

[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
    //Check here if values in parameter are set and if values are correct

    var detailsConfiguration = new DetailsConfiguration
    {
         Quarter = quarter,
         Year = year,
         Project = project
    }

    //Insert detailsConfiguration to database

    Return Ok();
}


问:
digital signature
All,

I need to digitally sign a zip file. I am not sure how to do that. What does the digital signature do for me? And just as importantly, how do i verify the digital signature?

答: You can get a great reading on JAR signing (http://www.cs.princeton.edu/introcs/85application/jar/sign.html) and having in mind that JAR is a ZIP with a MANIFEST, I'd say you go with JAR signing and that's it.</p>

Title: digital signature


问:
Bootstrap image stretch to border on mobile only
With BS4, how can I stretch images to the screen border on mobile, while keeping the container in tact for all other elements (e.g. divs, h1, etc.)?

My problem is that I can easily change the container width with a media query, however that would affect all elements. Also, the images should not stretch to the border on desktop, which is why I cannot just use a generic container-fluid.

I also tried using negative margins like so:

@media (max-width: 575px) {
  .mobile-stretch {
    margin-left: -15px;
    margin-right: -15px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

<div class="container">
  <div class="row">
    <div class="col-12">
      <img src="http://via.placeholder.com/850x120" class="img-fluid mobile-stretch" />
     </div>
  </div>
</div></code>```

Not sure why but it only stretches to the left border, while maintaining the border on the right side. What am I missing?

答:
Cant you add container-fluid class in place of container, and the other stuff in container class centered?

.no-gutters {
  margin-right: 0;
  margin-left: 0;
  > .col,
  > [class*="col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="container-fluid">
  <div class="row no-gutters">
    <div class="col-12">
      <img src="http://via.placeholder.com/850x120" class="img-fluid mobile-stretch" />
     </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-12">
      <img src="http://via.placeholder.com/850x120" class="img-fluid mobile-stretch" />
     </div>
  </div>
</div></code>```

Body:
With BS4, how can I stretch images to the screen border on mobile, while keeping the container in tact for all other elements (e.g. divs, h1, etc.)?

My problem is that I can easily change the container width with a media query, however that would affect all elements. Also, the images should not stretch to the border on desktop, which is why I cannot just use a generic container-fluid.

I also tried using negative margins like so:

@media (max-width: 575px) {
  .mobile-stretch {
    margin-left: -15px;
    margin-right: -15px;
  }
}

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"  integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">

Not sure why but it only stretches to the left border, while maintaining the border on the right side. What am I missing?

Body:
Cant you add container-fluid class in place of container, and the other stuff in container class centered?

.no-gutters {
  margin-right: 0;
  margin-left: 0;
  > .col,
  > [class*="col-"] {
    padding-right: 0;
    padding-left: 0;
  }
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="container-fluid">
  <div class="row no-gutters">
    <div class="col-12">
      <img src="http://via.placeholder.com/850x120" class="img-fluid mobile-stretch" />
     </div>
  </div>
</div>
<div class="container">
  <div class="row">
    <div class="col-12">
      <img src="http://via.placeholder.com/850x120" class="img-fluid mobile-stretch" />
     </div>
  </div>
</div>


问:
Check if apps are installed
I am creating an app that should allow the user to check which apps (also belonging to me) are installed.

I have read a post that explains that the URL scheme of each app has to be declared on LSApplicationQueriesSchemes in order to be able to check if the app is installed or not. The post is relatively old and I was wondering if other solutions currently exist to check if a list of apps are installed on the device.
I also found an article on the apple website explaining how to update a property-list data.

Is it possible to use this to update LSApplicationQueriesSchemes in info.plist and add new URL scheme?

答:
The article on apple explains editing plist files but the plist you want to edit is in the app bundle which is read only.

The only way to edit it is to copy it over to the documents directory of you app and but that will not suffice your requirement to add additional url-schemes

For Question1: LSApplicationQueriesSchemes is the right way to query for installed apps when you already know the url scheme.

Title: Check if apps are installed


问:
Open a local PDF file on  tag
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

```<code><a href="../file.pdf" target="_blank">
    <button name="Click here" />
</a>
</code>```

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?

答:
You have to host your local pdf file to make it open inside your application.

Use SimpleHTTPServer for installing a server and run it wherever your pdf file is located.

After successfully running the SimpleHTTPServer, you can check it by opening the pdf file inside your web browser. If the pdf file is getting opened inside your current browser than hurray your file has been hosted and now it can be opened inside your application.

Regards

Ajay

Title: Open a local PDF file on <a> tag

Body:
I'm running create-react-app, and I want to open a local PDF file stored inside my repo with a relative path.

    <button name="Click here" />

After I click it, it takes me to localhost:3000/file.pdf. How do I open up a new window with a PDF?


问:
Introducing New Services in Runtime by Admin
I'm using ASP.Net MVC with Identity,

In the Registration page, there are some categories

Under each category there are some services, may be 3 or 4

The Admin wants to add new categories from admin panel and also add the services under each category he adds.

How can I map that with ASP MVC and SQL Server so that these categories can be shown in registration page as soon as the admin add them.

答:
Try the following approach

Create a table to store the Category and Services

So, Whenever a new category or service is added, the above tables are populated.

Pull the details for the above tables on the user dashboard

So as soon as the details are added to the table the users can view the same


问:
How to speed up my code? Python
I need my code to work faster, this one I currently have sometimes even takes up to 5 seconds to print an answer.

```<code>import math

n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)

answer_list = []
q = 0
w = 1
e = 2

for l in range(range_is):
    o = myList[q]+myList[w]+myList[e]
    answer_list.append(o)
    if e == n-1 and w == n-2  and q != n-3:
        q = q+1
        w = q+1
        e = w+1

    elif e == n-1 and w != n-2:
        w = w+1
        e = w+1

    elif e != n:
        e = e+1

answer_list.sort()
print(answer_list[k-1])
</code>```

How can I make it run faster? And what is the problem in this code, so I can avoid this problem in the future?

答:
Some advice:

1，Using python 2 instead of python 3.

2,When calculating large numbers，
Using "xrange" instead of "range";
Using "ifilter" instead of "filter".

3,If you use iterative algorithms, try to use "yield".

Title: How to speed up my code? Python

Body:
I need my code to work faster, this one I currently have sometimes even takes up to 5 seconds to print an answer.

import math

n, k = [int(x) for x in input().split()]
myList = [int(i) for i in input().split()]
range_is = math.factorial(n) / (math.factorial(3) * math.factorial(n-3))
range_is = int(range_is)

answer_list = []
q = 0
w = 1
e = 2

for l in range(range_is):
    o = myList[q]+myList[w]+myList[e]
    answer_list.append(o)
    if e == n-1 and w == n-2  and q != n-3:
        q = q+1
        w = q+1
        e = w+1

    elif e == n-1 and w != n-2:
        w = w+1
        e = w+1

    elif e != n:
        e = e+1

answer_list.sort()
print(answer_list[k-1])

How can I make it run faster? And what is the problem in this code, so I can avoid this problem in the future?


问:
Yii2 BootstrapAsset is not loading bootstrap.js
yii\bootstrap\BootstrapAsset is not loading bootstrap.js, and such elements as "modal" and others are not working.

```<code>class AppAsset extends AssetBundle {
    public $basePath = '@webroot';

    public $baseUrl = '@web';

    public $css = [
        /* theme */
        'css/site.css',

        /* jasny bootstrap */
        'public/jasny/css/jasny-bootstrap.min.css',

        /* font awesome */
        'public/font-awesome-430/css/font-awesome.min.css',

        /* font roboto */
        'public/fonts/roboto/roboto.css',

        /* Data Tables */
        'public/datatables/extensions/integration/bootstrap/3/dataTables.bootstrap.css',
    ];

    public $js = [
        /* jasny bootstrap  */
        'public/jasny/js/jasny-bootstrap.min.js',

        /* Data Tables  */
        'public/datatables/datajs.js',
        'public/datatables/media/js/jquery.dataTables.min.js',
        'public/datatables/extensions/integration/bootstrap/3/dataTables.bootstrap.js',
    ];

    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}
</code>```

Here is screen of libraries, bootstrap.js is missing there.

答:
You can try this in AppAsset.php

```<code>class AppAsset extends AssetBundle{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
  'css/mystyle.css',
];
public $js = [

];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}
</code>```

and also change in you config/main.php

```<code>'components' => [
'assetManager' => [
    'bundles' => [
        'yii\bootstrap\BootstrapAsset' => [
            'js' => ['js/bootstrap.min.js'],
        ],
    ],
],
],
</code>```

I have tried these steps that will solve my problem thats to all for your comment

Body:
yii\bootstrap\BootstrapAsset is not loading bootstrap.js, and such elements as "modal" and others are not working.

class AppAsset extends AssetBundle {
    public $basePath = '@webroot';

    public $baseUrl = '@web';

    public $css = [
        /* theme */
        'css/site.css',

        /* jasny bootstrap */
        'public/jasny/css/jasny-bootstrap.min.css',

        /* font awesome */
        'public/font-awesome-430/css/font-awesome.min.css',

        /* font roboto */
        'public/fonts/roboto/roboto.css',

        /* Data Tables */
        'public/datatables/extensions/integration/bootstrap/3/dataTables.bootstrap.css',
    ];

    public $js = [
        /* jasny bootstrap  */
        'public/jasny/js/jasny-bootstrap.min.js',

        /* Data Tables  */
        'public/datatables/datajs.js',
        'public/datatables/media/js/jquery.dataTables.min.js',
        'public/datatables/extensions/integration/bootstrap/3/dataTables.bootstrap.js',
    ];

    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

Here is screen of libraries, bootstrap.js is missing there.

Body:
You can try this in AppAsset.php

class AppAsset extends AssetBundle{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
  'css/mystyle.css',
];
public $js = [

];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapPluginAsset',
];
}

and also change in you config/main.php

'components' => [
'assetManager' => [
    'bundles' => [
        'yii\bootstrap\BootstrapAsset' => [
            'js' => ['js/bootstrap.min.js'],
        ],
    ],
],
],

I have tried these steps that will solve my problem thats to all for your comment


问:
How to align the input fields?

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

答:
Swellar has a good solution in his answer. However, if you are looking for an alternative, you can put a dummy label element and then set its CSS property as visibility: hidden;. So, you don't have to take out your label element from second field, and this label will be hidden.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      LName
      <input class="form-control" id="ex1" placeholder="Last name" type="text">

```

Title: How to align the input fields?

Body:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Contact Person

      Name
      <input class="form-control" id="ex1" placeholder="First name" type="text">

      <input class="form-control" id="ex1" placeholder="Last name" type="text">

The two input fields do not align in the same line when i take the label off the second field how can this be corrected ?

Body:
Swellar has a good solution in his answer. However, if you are looking for an alternative, you can put a dummy label element and then set its CSS property as visibility: hidden;. So, you don't have to take out your label element from second field, and this label will be hidden.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<section class="section-component">
  <h1>Contact Person</h1>
  <div class="form-group row">
    <div class="col-xs-6 form-field">
      <label for="ex1">Name</label>
      <input class="form-control" id="ex1" placeholder="First name" type="text">
    </div>
    <div class="col-xs-6 form-field">
      <label for="ex1" style="visibility: hidden;">LName</label>
      <input class="form-control" id="ex1" placeholder="Last name" type="text">
    </div>
  </div>
</section>