问:
Android fragment reutn null on getview() when OnTextMessage is triggered
I want to update text in a fragment when the messages come.

In the Main Activity I do the connection with wsuri. Every message that I received the callback onTextMessage is  triggered. The library I use is autoBahn.

```<code>public class MainActivity extends AppCompatActivity{

private   static  WebSocketConnection mConnection = new WebSocketConnection();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent_root_activity);

        if(savedInstanceState == null){
                frag_Home = new HomeFragment();
                fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
            }else{
                if(fragmentManager.findFragmentByTag(getString(R.string.TAG_HOME)) == null){
                    frag_Home = new HomeFragment();
                    fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
                }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Start Connection
        Connect(ipAdress);
        Log.i("ROOT ACTIVITY", "onResume");
    }

    // Function callback events
    private void Connect(String ipAddress){

    final String wsuri = "ws://" + ipAddress + ":" + port;

        try {
            // Handle Websocket Event
            mConnection.connect(wsuri, new WebSocketHandler() {

                @Override
                public void onOpen() {
                    Log.d("WIFI", "onOpen: Conneced to "+ wsuri);
                }

                @Override
                public void onTextMessage(String payload) {
                    HomeFragment home = (HomeFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.TAG_HOME));
                    ((TextView)home.getView().findViewById(R.id.txtMsg)).setText(payload);
                }

                Override
                public void onClose(int code, String reason) {
                }
            }
        }
    }
}
</code>```

All run fine the texts updates correctly but when I rotate my phone and when I receive a message I get an error

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View test.test.com.test.HomeFragment.getView()' on a null object reference
</code>```

And the texts never updates again.

答:
Short Answer

This can be fixed with adding android:configChanges="orientation" in the manifest of your activity but this can lead to UI bugs because you're left on your own to handle the changes of the orientation.

Long Answer

```<code>mConnection.connect(wsuri, new WebSocketHandler() {

            @Override
            public void onOpen() {
                Log.d("WIFI", "onOpen: Conneced to "+ wsuri);
            }
</code>```

This inner anonymous class WebSocketHandler contains an implicit reference to the current instance of your MainActivity on the point of creation but that instance will be trashed by the Android system on orientation change. So what you're seeing after the orientation change is now a different instance than what your WebSocketHandler class points to, resulting to having null returned in your findFragmentByTag call because the HomeFragment that you're trying to request for was already cleaned up in the old instance of your MainActivity. Also this causes a memory leak because your WebSocketHandler will prevent the old instance of MainActivity to be GC'ed.

What I suggest you to do is have an entirely separate class that will handle the websocket connection and is not an inner class of the any Activity. Or you can use android:configChanges="orientation" and make sure that you handle the orientation changes properly through

```<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //handle the orientation change, ex change/rearrange fragments
    }
}
</code>```

Body:
I want to update text in a fragment when the messages come.

In the Main Activity I do the connection with wsuri. Every message that I received the callback onTextMessage is  triggered. The library I use is autoBahn.

public class MainActivity extends AppCompatActivity{

private   static  WebSocketConnection mConnection = new WebSocketConnection();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent_root_activity);

        if(savedInstanceState == null){
                frag_Home = new HomeFragment();
                fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
            }else{
                if(fragmentManager.findFragmentByTag(getString(R.string.TAG_HOME)) == null){
                    frag_Home = new HomeFragment();
                    fragmentManager.beginTransaction().add(R.id.fragmentContent, frag_Home, getString(R.string.TAG_HOME)).commit();
                }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Start Connection
        Connect(ipAdress);
        Log.i("ROOT ACTIVITY", "onResume");
    }

    // Function callback events
    private void Connect(String ipAddress){

    final String wsuri = "ws://" + ipAddress + ":" + port;

        try {
            // Handle Websocket Event
            mConnection.connect(wsuri, new WebSocketHandler() {

                @Override
                public void onOpen() {
                    Log.d("WIFI", "onOpen: Conneced to "+ wsuri);
                }

                @Override
                public void onTextMessage(String payload) {
                    HomeFragment home = (HomeFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.TAG_HOME));
                    ((TextView)home.getView().findViewById(R.id.txtMsg)).setText(payload);
                }

                Override
                public void onClose(int code, String reason) {
                }
            }
        }
    }
}

All run fine the texts updates correctly but when I rotate my phone and when I receive a message I get an error

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View test.test.com.test.HomeFragment.getView()' on a null object reference

And the texts never updates again.

Body:
Short Answer

This can be fixed with adding android:configChanges="orientation" in the manifest of your activity but this can lead to UI bugs because you're left on your own to handle the changes of the orientation.

Long Answer

mConnection.connect(wsuri, new WebSocketHandler() {

            @Override
            public void onOpen() {
                Log.d("WIFI", "onOpen: Conneced to "+ wsuri);
            }

This inner anonymous class WebSocketHandler contains an implicit reference to the current instance of your MainActivity on the point of creation but that instance will be trashed by the Android system on orientation change. So what you're seeing after the orientation change is now a different instance than what your WebSocketHandler class points to, resulting to having null returned in your findFragmentByTag call because the HomeFragment that you're trying to request for was already cleaned up in the old instance of your MainActivity. Also this causes a memory leak because your WebSocketHandler will prevent the old instance of MainActivity to be GC'ed.

What I suggest you to do is have an entirely separate class that will handle the websocket connection and is not an inner class of the any Activity. Or you can use android:configChanges="orientation" and make sure that you handle the orientation changes properly through

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //handle the orientation change, ex change/rearrange fragments
    }
}


来源: stackexchange

问:
Android make view height 50% of screen width
I wish to make a view with the width to be match_parent, but the height to be 50% of the width.

How do I do it?

Is the only way to do it through java code inside the activity? I'll have to read the screen width and set the height that way.

答:
```<code>try it.
<Button
            android:id="@+id/button"
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_weight="1"

            />
        <TextView
            android:id="@+id/text"
            android:layout_width="0dp"
            android:layout_height="150dp"
            android:layout_weight="1"
            />
</code>```

ContentLicense: CC BY-SA 3.0


问:
How come when I push "up" on MongoDB's console, it doesn't cycle through my previous command?
Instead, it displays this:

^[[A^[[A

答:
Here is a link that may be of some use, though I have not yet gotten it to work:

http://www.mongodbadmin.com/node/149

This seems to assume you are installing mongo from source.

ContentLicense: CC BY-SA 2.5

Body:
Instead, it displays this:

^[[A^[[A


问:
Show enum values once with ng-repeat and merge values from json
JSON

```<code>{
    "SubQuestion": "A question",
    "AnswerValue": "2",
    "EnumValue": {
        "Name": "name",
        "SomeEnum": {"1": "option1", "2": "option2", "3": "option3"}
    }

    "SubQuestion": "A second question",
    "AnswerValue": "3",
    "EnumValue": {
        "Name": "name",
        "SomeEnum": {"1": "option1", "2": "option2", "3": "option3"}
    }

}
</code>```

In the JSON I have some questions with answers.
The stucture of the JSON cannot be changed.

In my frontend there are checkboxes with the questions and answers (checked if AnswerValue == SomeEnum )

All enum values must be shown on the front end.
The checkbox must be checked if AnswerValue == SomeEnum

The problem is if you use a repeat to loop trough the answers the enum list wil be dublicated if you have multiple answers (see below)

```<code>[ ] option1<br>
[x] option2<br>
[ ] option3<br>
[ ] option1<br>
[ ] option2<br>
[x] option3<br>
</code>```

What I need is this:

```<code>[ ] option1<br>
[x] option2<br>
[X] option3<br>
</code>```

HTML:

```<code><div ng-repeat="(key, answer) in somevalue.EnumValue.SomeEnum">
    <div ng-if="key==somevalue.AnswerValue">
        <input type="checkbox" ng-checked="true">{{answer}}<br>
    </div>
    <div ng-if="key!=somevalue.AnswerValue">
        <input type="checkbox">{{answer}}<br>
    </div>
</div>
</code>```

What I need is a generic solution because the questions have different sets of enums values the sub questions (within one question) have the same set of enum values

答:
When using ng-repeat, you can use the unique filter to avoid duplicates:

```<code><div ng-repeat="(key, answer) in somevalue.EnumValue.SomeEnum | unique: 'answer'">
    ...
</div>
</code>```

Body:
JSON

{
    "SubQuestion": "A question",
    "AnswerValue": "2",
    "EnumValue": {
        "Name": "name",
        "SomeEnum": {"1": "option1", "2": "option2", "3": "option3"}
    }

    "SubQuestion": "A second question",
    "AnswerValue": "3",
    "EnumValue": {
        "Name": "name",
        "SomeEnum": {"1": "option1", "2": "option2", "3": "option3"}
    }

}

In the JSON I have some questions with answers.
The stucture of the JSON cannot be changed.

In my frontend there are checkboxes with the questions and answers (checked if AnswerValue == SomeEnum )

All enum values must be shown on the front end.
The checkbox must be checked if AnswerValue == SomeEnum

The problem is if you use a repeat to loop trough the answers the enum list wil be dublicated if you have multiple answers (see below)

[ ] option1

[x] option2

[ ] option3

[ ] option1

[ ] option2

[x] option3

What I need is this:

[ ] option1

[x] option2

[X] option3

HTML:

        <input type="checkbox" ng-checked="true">{{answer}}

        <input type="checkbox">{{answer}}

What I need is a generic solution because the questions have different sets of enums values the sub questions (within one question) have the same set of enum values

Body:
When using ng-repeat, you can use the unique filter to avoid duplicates:

<div ng-repeat="(key, answer) in somevalue.EnumValue.SomeEnum | unique: 'answer'">
    ...
</div>


问:
Button and AJAX not responding
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great</p>

```<code><script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    $(".submit").click(function myCall() {
        var subdata = $("#form").serializeArray();
        var request = $.ajax({
            url: "construct_new.php",
            type: "GET",
            data: subdata
        });
        return false;
    });
    </script>
    <div>
        <form id="form">
            Name of Product: <input type="text" name="productName" value="Enter Here">
            <input type="button" name="submit" value="Submit" class="submit">
        </form>
    </div>
</code>```

答:
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).

You can use either $(function(){ }) or $(document).ready(function(){ });.

```<code>$(function(){
    $(".submit").click(function myCall() {
         var subdata = $("#form").serializeArray();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata
         });
         return false;
     });
});
</code>```

In this case, you don't need serializeArray() but simply serialize().

There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.

Also, using a form's submit event is preferred to the submit button's click event.

```<code>$(function(){
    $("#form").submit(function myCall() {
         var subdata = $(this).serialize();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata,
             success : function(response){
                 console.log("success!");
             }
         });
         return false;
     });
});
</code>```

Title: Button and AJAX not responding

Body:
Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great

        <form id="form">
            Name of Product: <input type="text" name="productName" value="Enter Here">
            <input type="button" name="submit" value="Submit" class="submit">
        </form>

Body:
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).

You can use either $(function(){ }) or $(document).ready(function(){ });.

$(function(){
    $(".submit").click(function myCall() {
         var subdata = $("#form").serializeArray();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata
         });
         return false;
     });
});

In this case, you don't need serializeArray() but simply serialize().

There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.

Also, using a form's submit event is preferred to the submit button's click event.

$(function(){
    $("#form").submit(function myCall() {
         var subdata = $(this).serialize();
         var request = $.ajax({
             url: "construct_new.php",
             type: "GET",
             data: subdata,
             success : function(response){
                 console.log("success!");
             }
         });
         return false;
     });
});


问:
typescript: value type to represent any of the primitive type
What is the best way to define a property which can take any of string,number and boolean primitive values. I need a property to accept any of these primitive type as value from an html input field (which can be text/int/bool). having any miss type safety I was looking for (specifically, it should not be object, function type).

答:
Since Typescript 1.4 you can create a union type like this:

```<code>type Primitive = string | boolean | number;
</code>```

And use it like this:

```<code>function acceptPrimitive(prim: Primitive) {
  // prim is of a primitive type
}
</code>```

Body:
Since Typescript 1.4 you can create a union type like this:

type Primitive = string | boolean | number;

And use it like this:

function acceptPrimitive(prim: Primitive) {
  // prim is of a primitive type
}


问:
how can I write a query (SQL Server) that, based on a table, it can return all the tables that it references?
I have a massive procedure which does a ton of deletes. The issue is that:

There are missing tables from this delete (that need to be deleted)

I'm having a hard time with the order of the deletes.

I'm wondering if there is a way to build a query in which I give it a table name and then it shows me all the tables I need to delete from before deleting this table. Anyone can give me a hand?

答:
One quick solution is to use the (deprecated) sp_depends stored procedure to return the dependencies of an object, eg:

```<code>exec sp_depends 'mySprocName';
</code>```

A better solution is to use the sys.dm_sql_referenced_entities table-valued function to returned all referenced entities. This offers more details than sp_depends. Like all table-valued functions, it can be part of a larger query:

```<code>select distinct referenced_entity_name
into #tables
from sys.dm_sql_referenced_entities ( 'mySproc','OBJECT')
</code>```

This article shows how you can use such methods to create a PlantUML graph from such system functions and views.

Body:
One quick solution is to use the (deprecated) sp_depends stored procedure to return the dependencies of an object, eg:

exec sp_depends 'mySprocName';

A better solution is to use the sys.dm_sql_referenced_entities table-valued function to returned all referenced entities. This offers more details than sp_depends. Like all table-valued functions, it can be part of a larger query:

select distinct referenced_entity_name
into #tables
from sys.dm_sql_referenced_entities ( 'mySproc','OBJECT')

This article shows how you can use such methods to create a PlantUML graph from such system functions and views.


问:
WPF Bind Checkbox IsChecked to other Checkboxes (IsChecked || !IsEnabled)
I have a select 'All' checkbox that I would like to be bound to the (IsChecked || !IsEnabled) of other checkboxes.

Checking 'All' checks all enabled checkboxes.

Unchecking 'All' unchecks all checkboxes.

Manually checking each enabled checkbox will check 'All'.

When all enabled checkboxes and 'All' are checked and user unchecks any checkbox, 'All' automatically unchecks.

I am new to WPF Databinding.  I was thinking maybe I just handle the click of 'All' to set the other checkboxes.  But I don't know how to bind to both properties of multiple sources.  When I click 'All' and manually uncheck another checkbox, 'All' needs to uncheck.

答:
Here's a way to do it in Xaml with Converters. This is assuming that all your CheckBox's are added directly as Controls in Xaml (it's not very dynamic, won't work for DataTemplate's etc). First we create three CheckBoxes (CheckBox1, CheckBox2, CheckBox3) that will be Checked/Unchecked when Checking the CheckAllCheckBox. It will also work in reverse.

Update

The last part (ignore disabled CheckBox) was a bit of a problem here and I'm not crazy about this solution but I can't see a better way. We store the values from Convert and re-use them in ConvertBack for the disabled CheckBox's. Doing this, we should also add the x:Shared="False" attribute for the CheckAllConverter since a new instance is required for every MultiBinding that would use it (unlikely in this case but still..)

```<code><Window.Resources>
    <local:CheckAllConverter x:Key="CheckAllConverter" x:Shared="False"/>
</Window.Resources>
<StackPanel>
    <CheckBox Content="Check All"
              Name="CheckAllCheckBox">
        <CheckBox.IsChecked>
            <MultiBinding Converter="{StaticResource CheckAllConverter}">
                <Binding ElementName="CheckBox1" Path="IsChecked" />
                <Binding ElementName="CheckBox1" Path="IsEnabled" Mode="OneWay"/>
                <Binding ElementName="CheckBox2" Path="IsChecked" />
                <Binding ElementName="CheckBox2" Path="IsEnabled" Mode="OneWay"/>
                <Binding ElementName="CheckBox3" Path="IsChecked" />
                <Binding ElementName="CheckBox3" Path="IsEnabled" Mode="OneWay"/>
            </MultiBinding>
        </CheckBox.IsChecked>
    </CheckBox>
    <CheckBox Content="CheckBox 1"
              Name="CheckBox1"/>
    <CheckBox Content="CheckBox 2"
              Name="CheckBox2"/>
    <CheckBox Content="CheckBox 3"
              Name="CheckBox3"/>
</StackPanel>
</code>```

The Converter for CheckAll

```<code>public class CheckAllConverter : IMultiValueConverter
{
    private object[] convertValues = null;
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        convertValues = new object[values.Length];
        for(int i = 0; i < values.Length; i++)
        {
            convertValues[i] = values[i];
        }

        for (int i = 0; i < values.Length; i += 2)
        {
            bool isChecked = (bool)values[i];
            bool isEnabled = (bool)values[i + 1];
            if (isEnabled == false)
            {
                continue;
            }
            if (isChecked == false)
            {
                return false;
            }
        }
        return true;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        object[] values = new object[targetTypes.Length];
        for (int i = 0; i < values.Length; i += 2)
        {
            if (convertValues != null && (bool)convertValues[i + 1] == false)
            {
                values[i] = convertValues[i];
            }
            else
            {
                values[i] = value;
            }
            // IsEnabled is OneWay and won't care about this value
            values[i + 1] = null;
        }
        return values;
    }
}
</code>```

Body:
Here's a way to do it in Xaml with Converters. This is assuming that all your CheckBox's are added directly as Controls in Xaml (it's not very dynamic, won't work for DataTemplate's etc). First we create three CheckBoxes (CheckBox1, CheckBox2, CheckBox3) that will be Checked/Unchecked when Checking the CheckAllCheckBox. It will also work in reverse.

Update

The last part (ignore disabled CheckBox) was a bit of a problem here and I'm not crazy about this solution but I can't see a better way. We store the values from Convert and re-use them in ConvertBack for the disabled CheckBox's. Doing this, we should also add the x:Shared="False" attribute for the CheckAllConverter since a new instance is required for every MultiBinding that would use it (unlikely in this case but still..)

<Window.Resources>
    <local:CheckAllConverter x:Key="CheckAllConverter" x:Shared="False"/>
</Window.Resources>
<StackPanel>
    <CheckBox Content="Check All"
              Name="CheckAllCheckBox">
        <CheckBox.IsChecked>
            <MultiBinding Converter="{StaticResource CheckAllConverter}">
                <Binding ElementName="CheckBox1" Path="IsChecked" />
                <Binding ElementName="CheckBox1" Path="IsEnabled" Mode="OneWay"/>
                <Binding ElementName="CheckBox2" Path="IsChecked" />
                <Binding ElementName="CheckBox2" Path="IsEnabled" Mode="OneWay"/>
                <Binding ElementName="CheckBox3" Path="IsChecked" />
                <Binding ElementName="CheckBox3" Path="IsEnabled" Mode="OneWay"/>
            </MultiBinding>
        </CheckBox.IsChecked>
    </CheckBox>
    <CheckBox Content="CheckBox 1"
              Name="CheckBox1"/>
    <CheckBox Content="CheckBox 2"
              Name="CheckBox2"/>
    <CheckBox Content="CheckBox 3"
              Name="CheckBox3"/>
</StackPanel>

The Converter for CheckAll

public class CheckAllConverter : IMultiValueConverter
{
    private object[] convertValues = null;
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        convertValues = new object[values.Length];
        for(int i = 0; i < values.Length; i++)
        {
            convertValues[i] = values[i];
        }

        for (int i = 0; i < values.Length; i += 2)
        {
            bool isChecked = (bool)values[i];
            bool isEnabled = (bool)values[i + 1];
            if (isEnabled == false)
            {
                continue;
            }
            if (isChecked == false)
            {
                return false;
            }
        }
        return true;
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        object[] values = new object[targetTypes.Length];
        for (int i = 0; i < values.Length; i += 2)
        {
            if (convertValues != null && (bool)convertValues[i + 1] == false)
            {
                values[i] = convertValues[i];
            }
            else
            {
                values[i] = value;
            }
            // IsEnabled is OneWay and won't care about this value
            values[i + 1] = null;
        }
        return values;
    }
}


问:
Splitting Ionic card in half. I want to show students on the right and the teachers on the left
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

```<code>    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>
          <h2>{{ group.name }}</h2>

              <div class="pic" *ngFor="let student of group.students">
                <img [src]="student.avatar" />
              </div>
              <h3>{{group.students.length}}  Leerlingen</h3>

              <div class="pic" *ngFor="let teacher of group.teachers">
                <img [src]="teacher.avatar" />
              </div>
              <h3>{{group.teachers.length}} leerkrachten</h3>

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>
</code>```

CSS

```<code>.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}
</code>```

答:
Use the grid system</p>

```<code><ion-card >
  <ion-item>
    <h2>{{ group.name }}</h2>

    <ion-row>
      <ion-col col-6>
        <div class="pic" *ngFor="let student of group.students">
          <img [src]="student.avatar" />
        </div>
        <h3>{{group.students.length}}  Leerlingen</h3>
      </ion-col>

      <ion-col col-6>
        <div class="pic" *ngFor="let teacher of group.teachers">
          <img [src]="teacher.avatar" />
        </div>
        <h3>{{group.teachers.length}} leerkrachten</h3>
      </ion-col>
    <ion-row>

  </ion-item>
</ion-card>
</code>```

Body:
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>

{{ group.name }}

{{group.students.length}}  Leerlingen

{{group.teachers.length}} leerkrachten

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>

CSS

.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}

Body:
Use the grid system

<ion-card >
  <ion-item>
    <h2>{{ group.name }}</h2>

    <ion-row>
      <ion-col col-6>
        <div class="pic" *ngFor="let student of group.students">
          <img [src]="student.avatar" />
        </div>
        <h3>{{group.students.length}}  Leerlingen</h3>
      </ion-col>

      <ion-col col-6>
        <div class="pic" *ngFor="let teacher of group.teachers">
          <img [src]="teacher.avatar" />
        </div>
        <h3>{{group.teachers.length}} leerkrachten</h3>
      </ion-col>
    <ion-row>

  </ion-item>
</ion-card>


问:
Why is there a NullPointerException in this method call?
When I call a method like this:

```<code>int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}
</code>```

Why is there a NullPointerException?

答:
Yes, if setValue() does access the object like this:

```<code>void setValue(Long lung) {
    this.val = lung.intValue();
}
</code>```

because it tries to dereference null. and no, if setValue() does treat the object like that:

```<code>void setValue(Long lung) {
    this.val = Optional.ofNullable(lung)
                       .map(Long::intValue)
                       .orElse(0L) ;
}
</code>```

because it is aware of how to handle null.

The point is: if the method which receives the null argument does dereference it inside the method body, or pass it to some method which does, a NullPointerException will be thrown. Otherwise not.

Body:
When I call a method like this:

int value1;
Integer value2 = null;

setValue(value2);

private void setValue(int value) {
    value1 = value;
}

Why is there a NullPointerException?

Body:
Yes, if setValue() does access the object like this:

void setValue(Long lung) {
    this.val = lung.intValue();
}

because it tries to dereference null. and no, if setValue() does treat the object like that:

void setValue(Long lung) {
    this.val = Optional.ofNullable(lung)
                       .map(Long::intValue)
                       .orElse(0L) ;
}

because it is aware of how to handle null.

The point is: if the method which receives the null argument does dereference it inside the method body, or pass it to some method which does, a NullPointerException will be thrown. Otherwise not.


问:
Spring Solr - Using multiple clients to different services
I am working with an application that aggregates data from multiple sources. In this case I need to connect to two different Solr services with unrelated data.  To this end I set up two different data repositories. I have defined the beans as follows:

```<code>@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.gcr"}, multicoreSupport=true)
public class GcrSolrContext {

    @Bean
    public SolrClient solrClient() {
        return new HttpSolrClient("http://foo:8086/solr/gcr");
    }

    @Bean
    public SolrTemplate solrTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}
</code>```

The problem I have is that I cannot figure out how to have two completely independent Solr clients, with each pointing at different urls. As the beans solrClient() and solrTemplate() are needed, and trying to create a new Context with different URLs simply gets the solrClient and solrTemplate bean overwritten with the beans created first. Each client works fine if they are the only Solr clients defined.

In short, how can I create two (or more) different Spring Solr clients, each connecting to different URLS?

Additional Information is response to comments...

I have attempted to simply recreate the SolrContext class with different configurations.Consider the following:

```<code>@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.different"}, multicoreSupport=true)
public class DifferentSolrContext {

    @Bean
    public SolrClient solrClient() {
        return new HttpSolrClient("http://SomethingDifferent:8086/solr/something");
    }

    @Bean
    public SolrTemplate solrTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}
</code>```

What happens here is that the @Bean's solrClient, and solrTemplate get overridden when the beans are created during startup.

```<code>INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'solrClient' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=yyySolrContext; factoryMethodName=solrClient; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.GcrSolrContext] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=xxxSolrContext; factoryMethodName=solrClient; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.XxxSolrContext]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'solrTemplate' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=yyySolrContext; factoryMethodName=solrTemplate; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.GcrSolrContext] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=haystackSolrContext; factoryMethodName=solrTemplate; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.XxxSolrContext]
</code>```

Testing shows that the URL is indeed only the first bean instantiated. I have also tried renaming the second context beans to something else, but then the Solr functionality can't locate/identify the beans.

Here is the error thrown when trying to define more than one SolrClient.

```<code>Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.apache.solr.client.solrj.SolrClient' available: expected single matching bean but found 2: solrClient2,solrClient
</code>```

In short it appears that only one URL is possible for the Spring Solr Data  library.  (note: using version 2.1.4) Does anyone have more than one URL (not just core) working under Spring Solr data?

答:
create another bean for spring to use solr, this is easy and clean : </p>

```<code>@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.xxx"}, multicoreSupport=true)
public class XXXSolrContext {

    @Bean
    public SolrClient getClient() {
        return new HttpSolrClient("http://foo:8086/solr/xxx");
    }

    @Bean
    public SolrTemplate getTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}
</code>```

Body:
I am working with an application that aggregates data from multiple sources. In this case I need to connect to two different Solr services with unrelated data.  To this end I set up two different data repositories. I have defined the beans as follows:

@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.gcr"}, multicoreSupport=true)
public class GcrSolrContext {

    @Bean
    public SolrClient solrClient() {
        return new HttpSolrClient("http://foo:8086/solr/gcr");
    }

    @Bean
    public SolrTemplate solrTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}

The problem I have is that I cannot figure out how to have two completely independent Solr clients, with each pointing at different urls. As the beans solrClient() and solrTemplate() are needed, and trying to create a new Context with different URLs simply gets the solrClient and solrTemplate bean overwritten with the beans created first. Each client works fine if they are the only Solr clients defined.

In short, how can I create two (or more) different Spring Solr clients, each connecting to different URLS?

Additional Information is response to comments...

I have attempted to simply recreate the SolrContext class with different configurations.Consider the following:

@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.different"}, multicoreSupport=true)
public class DifferentSolrContext {

    @Bean
    public SolrClient solrClient() {
        return new HttpSolrClient("http://SomethingDifferent:8086/solr/something");
    }

    @Bean
    public SolrTemplate solrTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}

What happens here is that the @Bean's solrClient, and solrTemplate get overridden when the beans are created during startup.

INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'solrClient' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=yyySolrContext; factoryMethodName=solrClient; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.GcrSolrContext] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=xxxSolrContext; factoryMethodName=solrClient; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.XxxSolrContext]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Overriding bean definition for bean 'solrTemplate' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=yyySolrContext; factoryMethodName=solrTemplate; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.GcrSolrContext] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=haystackSolrContext; factoryMethodName=solrTemplate; initMethodName=null; destroyMethodName=(inferred); defined in foo.utilities.solr.XxxSolrContext]

Testing shows that the URL is indeed only the first bean instantiated. I have also tried renaming the second context beans to something else, but then the Solr functionality can't locate/identify the beans.

Here is the error thrown when trying to define more than one SolrClient.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.apache.solr.client.solrj.SolrClient' available: expected single matching bean but found 2: solrClient2,solrClient

In short it appears that only one URL is possible for the Spring Solr Data  library.  (note: using version 2.1.4) Does anyone have more than one URL (not just core) working under Spring Solr data?

Body:
create another bean for spring to use solr, this is easy and clean :

@Configuration
@EnableSolrRepositories(basePackages={"foo.utilities.solr.repos.xxx"}, multicoreSupport=true)
public class XXXSolrContext {

    @Bean
    public SolrClient getClient() {
        return new HttpSolrClient("http://foo:8086/solr/xxx");
    }

    @Bean
    public SolrTemplate getTemplate(SolrClient client) throws Exception {
        return new SolrTemplate(client);
    }
}


问:
Convert Perl regex to PHP
I have the following Perl code:

```<code>$url=~s/\W//g;
</code>```

I'd like to translate this to PHP preg_replace.

```<code>preg_replace("/[\W]/", "", $url);
</code>```

I'm not sure this is correct. I don't really know what it does.

It comes from this function, which formats a URL to a canonical format:

```<code>sub formatcanonical {
    my $url = lc(shift);

    $url =~ s/-/ /g;
    $url =~ s/\s+/_/g;
    $url =~ s/\W//g;

    return $url;
}
</code>```

答:
Always try before asking, you could figure this out if you got this far.

Outside of that you don't need the []'s. The regex itself doesn't change when moving to php (or at least for the common things, when it looks like it has too php has a page that lists all differences). However from what I can see it should work correct either way. Character sets are only useful if they have more then one character. In text the regexes do this:

Replaces dashes with spaces.

Replaces any continues length of spaces with a single underscore.

Replaces any non word characters with nothing. These include a-z, A-Z, 0-9, _ and some other special/unicode chars like eg ëè etc. Capital \W negates where as \w matches word characters.

Secondly don't change the order its very confusing (and if you actually do it in the code it won't come back as expected).

Thirdly PHP allows arrays as arguments for preg_replace.

All together one could do something like:

```<code>$string = 'Hello im a test-able string!';
echo preg_replace(
    [
        '/-/',
        '/\s+/',
        '/\W/',
    ],
    [
        ' ',
        '_',
        '',
    ],
    $string
);
</code>```

Although the readability is still somewhat dubious. And one might just go for the three preg_replace functions instead, especially once they get lengthy.

Finally if you ever need a playground for regex testing give regex101 a try, its awesome.

Also you made 3 edits during me typing this which I'm going to ignore for now.

Title: Convert Perl regex to PHP

Body:
I have the following Perl code:

$url=~s/\W//g;

I'd like to translate this to PHP preg_replace.

preg_replace("/[\W]/", "", $url);

I'm not sure this is correct. I don't really know what it does.

It comes from this function, which formats a URL to a canonical format:

sub formatcanonical {
    my $url = lc(shift);

    $url =~ s/-/ /g;
    $url =~ s/\s+/_/g;
    $url =~ s/\W//g;

    return $url;
}

Body:
Always try before asking, you could figure this out if you got this far.

Outside of that you don't need the []'s. The regex itself doesn't change when moving to php (or at least for the common things, when it looks like it has too php has a page that lists all differences). However from what I can see it should work correct either way. Character sets are only useful if they have more then one character. In text the regexes do this:

Replaces dashes with spaces.

Replaces any continues length of spaces with a single underscore.

Replaces any non word characters with nothing. These include a-z, A-Z, 0-9, _ and some other special/unicode chars like eg ëè etc. Capital \W negates where as \w matches word characters.

Secondly don't change the order its very confusing (and if you actually do it in the code it won't come back as expected).

Thirdly PHP allows arrays as arguments for preg_replace.

All together one could do something like:

$string = 'Hello im a test-able string!';
echo preg_replace(
    [
        '/-/',
        '/\s+/',
        '/\W/',
    ],
    [
        ' ',
        '_',
        '',
    ],
    $string
);

Although the readability is still somewhat dubious. And one might just go for the three preg_replace functions instead, especially once they get lengthy.

Finally if you ever need a playground for regex testing give regex101 a try, its awesome.

Also you made 3 edits during me typing this which I'm going to ignore for now.


问:
Unexpected binding in Angular 2
I'm having a very weird problem in my Angular 2 application using the PrimeNG DataTable. It's possible to change data in my DataTable, using the [editable]"true" syntax.

The data in the DataTable is called = inschrijvingen.
I'm doing this.originalInschrijvingen = this.inschrijvingen to create a 'copy' before the user can change the data so I can compare the changes in a later stage. But for some reason is the DataTable data binding to both originalInschrijvingen and inschrijvingen.

Here is my code:

```<code>onRowSelectUser(event) { //This is a different DataTable than the editable DataTable
    this.getGebruikerZijnInschrijvingen(res => {
      this.createRoleID(res => {
        let selectedIds = this.gebruikerZijnInschrijvingen.map(it => it.DefUnitID);
        this.selectedInschrijvingen = this.inschrijvingen.filter(inv => selectedIds.indexOf(inv.ID) != -1);
        this.originalInschrijvingen = this.selectedInschrijvingen;
      })
    })
  }
</code>```

答:
this.selectedInschrijvingen seems to be an array and in Javascript when you assign one array to another using = operator they are copied by reference, hence they represent same array.

You can do below,

```<code>this.originalInschrijvingen = this.selectedInschrijvingen.slice();
</code>```

The slice() method returns a shallow copy of a portion of an array
  into a new array object selected from begin to end (end not included).
  The original array will not be modified.

Hope this helps!!

Title: Unexpected binding in Angular 2

Body:
I'm having a very weird problem in my Angular 2 application using the PrimeNG DataTable. It's possible to change data in my DataTable, using the [editable]"true" syntax.

The data in the DataTable is called = inschrijvingen.
I'm doing this.originalInschrijvingen = this.inschrijvingen to create a 'copy' before the user can change the data so I can compare the changes in a later stage. But for some reason is the DataTable data binding to both originalInschrijvingen and inschrijvingen.

Here is my code:

onRowSelectUser(event) { //This is a different DataTable than the editable DataTable
    this.getGebruikerZijnInschrijvingen(res => {
      this.createRoleID(res => {
        let selectedIds = this.gebruikerZijnInschrijvingen.map(it => it.DefUnitID);
        this.selectedInschrijvingen = this.inschrijvingen.filter(inv => selectedIds.indexOf(inv.ID) != -1);
        this.originalInschrijvingen = this.selectedInschrijvingen;
      })
    })
  }

Body:
this.selectedInschrijvingen seems to be an array and in Javascript when you assign one array to another using = operator they are copied by reference, hence they represent same array.

You can do below,

this.originalInschrijvingen = this.selectedInschrijvingen.slice();

The slice() method returns a shallow copy of a portion of an array
  into a new array object selected from begin to end (end not included).
  The original array will not be modified.

Hope this helps!!


问:
Convert string to multiline/raw string in LUA
Is there a way to convert a quoted string to a multiline string?

Something like "This string \66 here" to [[This string \66 here]] since I would like to ignore the interpretation of escaped characters.

答:
Do you look for something like this?</p>

```<code>local db = "google"
local tbl = "accounts"
local where = "field = 'VALUE' AND TRUE"
local order = "id DESC"

local query = string.format([[
    SELECT *
    FROM `%s`.`%s`
    WHERE %s
    ORDER BY %s
]], db, tbl, where, order)
</code>```

Body:
Do you look for something like this?

local db = "google"
local tbl = "accounts"
local where = "field = 'VALUE' AND TRUE"
local order = "id DESC"

local query = string.format([[
    SELECT *
    FROM `%s`.`%s`
    WHERE %s
    ORDER BY %s
]], db, tbl, where, order)


问:
How can I get int values from the change dictionary in KVO method observeValueForKeyPath:ofObject:change:context:?
I am observing changes in the rate property of an AVPlayer by calling the following method on it like so:

```<code>addObserver:sharedPlayerManagerInstance
 forKeyPath:@"rate"
    options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
    context:0];
</code>```

The change dictionary I get back from observeValueForKeyPath:ofObject:change:context: is therefore:

```<code>change = { kind: 1,
            new: 1,
            old: 0 }
</code>```

I checked the class of each value, and it turns out to be __NSCFNumber. However, when I try to convert [change objectForKey:@"new"] or [change objectForKey:@"old"] into an int, NSInteger, NSNumber, even tried NSString, etc, it works for "old", but it gives me a parsing error for the "new":

```<code>error: expected a type
error: 1 errors parsing expression
</code>```

I really need to compare them, and I can't figure it out. Could this be a bug in iOS?

答:
Swift 3:

```<code>if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
     // Do stuff
}
</code>```

Body:
I am observing changes in the rate property of an AVPlayer by calling the following method on it like so:

addObserver:sharedPlayerManagerInstance
 forKeyPath:@"rate"
    options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
    context:0];

The change dictionary I get back from observeValueForKeyPath:ofObject:change:context: is therefore:

change = { kind: 1,
            new: 1,
            old: 0 }

I checked the class of each value, and it turns out to be __NSCFNumber. However, when I try to convert [change objectForKey:@"new"] or [change objectForKey:@"old"] into an int, NSInteger, NSNumber, even tried NSString, etc, it works for "old", but it gives me a parsing error for the "new":

error: expected a type
error: 1 errors parsing expression

I really need to compare them, and I can't figure it out. Could this be a bug in iOS?

Body:
Swift 3:

if let newValue = change?[NSKeyValueChangeKey.newKey] as? NSNumber {
     // Do stuff
}


问:
how to display the maximum value in the array?
```<code>int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }
</code>```

How do I then tell the program to display the max value of the array??
Thank you

答:
```<code>#include <iostream>

std::cout << greatest << '\n';
</code>```

On a sidenote, you might want to call srand() before your call rand() (and might want to supply a more meaningful parameter).

Body:
int main()
{
   int numbers[30];
   int i;

   // making array of 30 random numbers under 100
   for(i=0;i<30;i++)
   {
       numbers[i] = rand() % 100;
   }

   // finding the greatest number in the array
   int greatest = 0;
   srand(1);
   for(i=0;i<30;i++)
   {
        if ( numbers[i] > greatest)
            greatest = numbers[i];
   }

How do I then tell the program to display the max value of the array??
Thank you

Body:
#include <iostream>

std::cout << greatest << '\n';

On a sidenote, you might want to call srand() before your call rand() (and might want to supply a more meaningful parameter).


问:
I want to redirect a url having multiple query string using rewriterule apache
abc.com/xyz/nx/crm?eId=1a&oid=A3E4B-9477-A1D2&g_fid=5BDC-6C223C8332E1&n_id=xyz

I want that if there is n number of (&)query string it will redirect to the same page irrespective of number of query string in url like if I want to redirect this to /abc/en-us/xyz/nx/crm_eId_%1.html [PT,L]

Used below but it didnt work

```<code>RewriteCond %{QUERY_STRING} ^eId=(.*)?(&.*)? [NC]
RewriteRule ^/xyz/nx/crm /abc/en-us/xyz/nx/crm_eId_%1.html [PT,L]
</code>```

答:
RewriteCond %{QUERY_STRING} ^eId=([^&]+)(.*)

RewriteRule ^/xyz/nx/crm /abc/en-us/xyz/nx/crm_eId_%1.html [QSA,PT,L]

This works for multiple query string in the urls.

Body:
abc.com/xyz/nx/crm?eId=1a&oid=A3E4B-9477-A1D2&g_fid=5BDC-6C223C8332E1&n_id=xyz

I want that if there is n number of (&)query string it will redirect to the same page irrespective of number of query string in url like if I want to redirect this to /abc/en-us/xyz/nx/crm_eId_%1.html [PT,L]

Used below but it didnt work

RewriteCond %{QUERY_STRING} ^eId=(.*)?(&.*)? [NC]
RewriteRule ^/xyz/nx/crm /abc/en-us/xyz/nx/crm_eId_%1.html [PT,L]


问:
CSS background image make darker
I have the following: www.thewhozoo.com

As you can see, it has a background image.

```<code>.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }
</code>```

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

```<code>.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}
</code>```

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

答:
You can use below css for get the same</p>

```<code>.top-container {
 position:relative;
}

.top-container::before {
 content:'';
 background:rgba(0,0,0,0.5);
 width:100%;
 height:100%;
 position:absolute;
 left:0px;
 top:0px;
 z-index:-1;
}
</code>```

Title: CSS background image make darker

Body:
I have the following: www.thewhozoo.com

As you can see, it has a background image.

.top-container {
    float: left;
    width: 100%;
    background: url('../images/background1.jpg') no-repeat center center fixed;
       -webkit-background-size: cover;
       -moz-background-size: cover;
       -o-background-size: cover;
       background-size: cover;
  }

The background image has white text on top of it, which may be a little difficult to read.

I have added a text-shadow to the text, which has helped make the text stand out more.

.text-description-header {
    font-size: 250%;
    color: white;
    text-shadow: 0px 1px 14px rgba(0,0,0,1.0);
}

However, I would like the text to stand out even more.

Question

Are there suggestions how I can make the text-shadow even darker?

Or, make the background image a little darker?

Thanks

Body:
You can use below css for get the same

.top-container {
 position:relative;
}

.top-container::before {
 content:'';
 background:rgba(0,0,0,0.5);
 width:100%;
 height:100%;
 position:absolute;
 left:0px;
 top:0px;
 z-index:-1;
}


问:
NotifyDataSetChanged refreshes RecyclerView but scrolls as well.
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.</p>

```<code>// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );
</code>```

答:
It's better to use the other notify methods from the RecyclerView.

For your usecase only swap out one item in your Adapter instead of all items and use notifyItemChanged(position).

This will be faster, the View won't scroll and if you ever will add an animation this will only work if you don't use notifyDataSetChanged

Body:
I have a RecyclerView and one item row needs to be updated like every second (SeekBar). So I call NotifyDataSetChanged once I update the data in the list. UI gets updated but the issue is that the RecyclerView scrolls so that this particular item is either at top or bottom of the screen.
I don't want RecyclerView to scroll.

// Update Data
    mData.set(mData.indexOf(cardData), cardData);
    // RefreshView
    refreshView() {
       runOnUiThread(new Runnable(){
          notifyDataSetChanged();
         }
     );


问:
Force Youtube embed to play in HD (2016 edition)
OK, this has been asked many times before – but Youtube seems to change things up every other day. I can't find a way to force a Youtube embed to start playing a HD source from the beginning. The switch to HD always happens after 5-10 seconds.

Methods that don't work (anymore):

Adding &hd=1 parameter to the iframe src

Adding &vd=hd720 or &vd=hd1080 parameters to the iframe src. Described here: Force youtube embed to start in 720p

Changing the iframe dimenstions to width="1280" heigh="720" in the html embed code and then using CSS to scale the iframe back down/up to the parent div. Described here: http://thenewcode.com/717/Force-Embedded-YouTube-Videos-To-Play-In-HD and here: How to force youtube to play HD videos

The only possible way would be using the Youtube JavaScript API, as described here:
http://biostall.com/the-100-guaranteed-method-to-get-youtube-iframe-embeds-playing-in-hd-by-default/

// 1. This code loads the IFrame Player API code asynchronously.
 var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 2. This function creates an  (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '1280',
        width: '720',
        videoId: 'E37YNMYlKvo',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    player.setPlaybackQuality('hd1080'); // Here we set the quality (yay!)
    event.target.playVideo(); // Optional. Means video autoplays
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="player"></div>  </code>```

But: I want to use a simple iframe embed since videos will be embeded through the wordpress oembed feature.

Is there any way to run the player.setPlaybackQuality('hd1080'); function for a simple iframe embed?

答:
You can also set your playerVars

```<code>            vq: 'hd1080',
</code>```

144p: &vq=tiny

240p: &vq=small

360p: &vq=medium

480p: &vq=large

720p: &vq=hd720

1080p: &vq=hd1080

Body:
OK, this has been asked many times before – but Youtube seems to change things up every other day. I can't find a way to force a Youtube embed to start playing a HD source from the beginning. The switch to HD always happens after 5-10 seconds.

Methods that don't work (anymore):

Adding &hd=1 parameter to the iframe src

Adding &vd=hd720 or &vd=hd1080 parameters to the iframe src. Described here: Force youtube embed to start in 720p

Changing the iframe dimenstions to width="1280" heigh="720" in the html embed code and then using CSS to scale the iframe back down/up to the parent div. Described here: http://thenewcode.com/717/Force-Embedded-YouTube-Videos-To-Play-In-HD and here: How to force youtube to play HD videos

The only possible way would be using the Youtube JavaScript API, as described here:
http://biostall.com/the-100-guaranteed-method-to-get-youtube-iframe-embeds-playing-in-hd-by-default/

// 1. This code loads the IFrame Player API code asynchronously.
 var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 2. This function creates an  (and YouTube player) after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '1280',
        width: '720',
        videoId: 'E37YNMYlKvo',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
    player.setPlaybackQuality('hd1080'); // Here we set the quality (yay!)
    event.target.playVideo(); // Optional. Means video autoplays
}

But: I want to use a simple iframe embed since videos will be embeded through the wordpress oembed feature.

Is there any way to run the player.setPlaybackQuality('hd1080'); function for a simple iframe embed?

Body:
You can also set your playerVars

            vq: 'hd1080',

144p: &vq=tiny

240p: &vq=small

360p: &vq=medium

480p: &vq=large

720p: &vq=hd720

1080p: &vq=hd1080


问:
Catch Geolocation Error - Async Await
How can I catch the geolocation specific error to notify the user that they must have geolocation turned on?

The catch logs an error called PositionError as referenced here in the Mozilla docs "https://developer.mozilla.org/en-US/docs/Web/API/PositionError".

*Note: my code does not catch the error, it simply displays:

```<code>Uncaught (in promise) ReferenceError: PositionError is not defined
</code>```

Code

```<code>getCurrentLocation() {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        });
    });
},
async inout() {
    try {
        let location = await this.getCurrentLocation();
        let response = await axios.post(API.URL, {});
    } catch (e) {
        if(e instanceof PositionError) {
            console.log('position error')
        }
    }
}
</code>```

答:
The getCurrentPosition() API was poorly designed, assuming users would test errors immediately in the callback, instead of passing them up.

Since PositionError has no public constructor, window.PositionError is not defined.

As Fabian mentions in comments, you can test for the error like this:

```<code>if (e.toString() == '[object PositionError]') {
  console.log('position error')
}
</code>```

or use his version if you're calling any API likely to throw non-object errors (hopefully rare).

However, instead of littering your code, I recommend throwing a better error from your new async getCurrentLocation() API instead (use fiddle to get around SO code snippet sandbox):

function getCurrentLocation(options) {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, ({code, message}) =>
      reject(Object.assign(new Error(message), {name: "PositionError", code})),
      options);
    });
};
async function inout() {
  try {
    console.log(await this.getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    }));
  } catch (e) {
    if (e.name == 'PositionError') {
      console.log(e.message + ". code = " + e.code);
    }
  }
}
inout().catch(e => console.log(e)); // User denied geolocation prompt. code = 1```

Title: Catch Geolocation Error - Async Await

Body:
How can I catch the geolocation specific error to notify the user that they must have geolocation turned on?

The catch logs an error called PositionError as referenced here in the Mozilla docs "https://developer.mozilla.org/en-US/docs/Web/API/PositionError".

*Note: my code does not catch the error, it simply displays:

Uncaught (in promise) ReferenceError: PositionError is not defined

Code

getCurrentLocation() {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        });
    });
},
async inout() {
    try {
        let location = await this.getCurrentLocation();
        let response = await axios.post(API.URL, {});
    } catch (e) {
        if(e instanceof PositionError) {
            console.log('position error')
        }
    }
}

Body:
The getCurrentPosition() API was poorly designed, assuming users would test errors immediately in the callback, instead of passing them up.

Since PositionError has no public constructor, window.PositionError is not defined.

As Fabian mentions in comments, you can test for the error like this:

if (e.toString() == '[object PositionError]') {
  console.log('position error')
}

or use his version if you're calling any API likely to throw non-object errors (hopefully rare).

However, instead of littering your code, I recommend throwing a better error from your new async getCurrentLocation() API instead (use fiddle to get around SO code snippet sandbox):

function getCurrentLocation(options) {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, ({code, message}) =>
      reject(Object.assign(new Error(message), {name: "PositionError", code})),
      options);
    });
};
async function inout() {
  try {
    console.log(await this.getCurrentLocation({
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    }));
  } catch (e) {
    if (e.name == 'PositionError') {
      console.log(e.message + ". code = " + e.code);
    }
  }
}
inout().catch(e => console.log(e)); // User denied geolocation prompt. code = 1


问:
Query to find the FIRST AND SECOND largest value from a group
i have a query like this:

```<code>SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)
</code>```

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

答:
to do this without joins ( I'll show the Oracle... you'll just use CASE instead of DECODES)</p>

```<code>with ranks as (
        select
            year(entrydate) as [year],
            month(entrydate) as [month],
            views,
            rank() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
        from product
    )
SELECT [year], [month], Max([best]), Max([second best])
 FROM
    ( select
        t1.year,
        t1.month,
        Decode([rank],1,t1.views,0) as [best],
        Decode([rank],2,t1.views,0)  as [second best]
    from ranks t1
    where t1.rank <= 2 ) x
GROUP BY [year], [month]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have a query like this:

SELECT
 DATEPART(year,some_date),
 DATEPART(month,some_date),
 MAX(some_value) max_value
FROM
 some_table
GROUP BY
    DATEPART(year,some_date),
    DATEPART(month,some_date)

This returns a table with: year, month, the largest value for the month.

I would like to modify the query so that i could obtain:
year, month, the largest value for the month, the second largest value for the month in each row.

It seems to me that the well-known solutions like "TOP 2", "NOT IN TOP 1" or a subselect won't work here.

(To be really specific - i am using SQL Server 2008.)

Body:
to do this without joins ( I'll show the Oracle... you'll just use CASE instead of DECODES)

with ranks as (
        select
            year(entrydate) as [year],
            month(entrydate) as [month],
            views,
            rank() over (partition by year(entrydate), month(entrydate) order by views desc) as [rank]
        from product
    )
SELECT [year], [month], Max([best]), Max([second best])
 FROM
    ( select
        t1.year,
        t1.month,
        Decode([rank],1,t1.views,0) as [best],
        Decode([rank],2,t1.views,0)  as [second best]
    from ranks t1
    where t1.rank <= 2 ) x
GROUP BY [year], [month]


问:
Drupal 8 issue: InvalidArgumentException: The URI '' is invalid
I am struggling with this issue:

```<code>InvalidArgumentException: The URI '' is invalid.
You must use a valid URI scheme. in Drupal\Core\Url::fromUri()
(line 284 of core/lib/Drupal/Core/Url.php).
</code>```

How can I fix this?

答:
You are passing a blank uri into the method. It is complaining about missing a scheme (eg. http:// or https://, or an internal scheme eg: internal:/)

So either you are explicitly passing a blank, or something isn't being set correctly. However, it does not seem to be null.

Body:
I am struggling with this issue:

InvalidArgumentException: The URI '' is invalid.
You must use a valid URI scheme. in Drupal\Core\Url::fromUri()
(line 284 of core/lib/Drupal/Core/Url.php).

How can I fix this?


问:
How can I compress images,so that google pagespeed test won't recommend to compress that image again?
Whenever I run pagespeed test , it gives possible optimization of images in bytes & percentage like,

  Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

Compressing https://example.com/…AMP.png?12287830358450898504 could save 4.4KiB (31% reduction).

I am using ImageMagick to compress the images.

I have tried  convert AMP.gif_or_png -strip  [-alpha Remove] OUTPUT.png  for png images  and

```<code> convert INPUT.jpg -sampling-factor 4:2:0 -strip [-quality 85] [-interlace JPEG] [-colorspace RGB] OUTPUT.jpg
</code>```

for jpg images, but none of the above commands gives me the same reduction as suggested by google pagespeed.
 So, let me know if i am missing any parameters or I have passed wrong values of parameters.

The pack of compressed contents are available on google pagespeed page but,I want to compress images using ImageMagick
 or any other sources .

答: You can download a compression pack from that page with your images and code optimized to their liking...it is pretty much the best image compression available.</p>

Body:
Whenever I run pagespeed test , it gives possible optimization of images in bytes & percentage like,

  Compressing and resizing https://example.com/…ts/AMP.jpg?6750368613317441460 could save 530KiB (91% reduction).

Compressing https://example.com/…AMP.png?12287830358450898504 could save 4.4KiB (31% reduction).

I am using ImageMagick to compress the images.

I have tried  convert AMP.gif_or_png -strip  [-alpha Remove] OUTPUT.png  for png images  and

 convert INPUT.jpg -sampling-factor 4:2:0 -strip [-quality 85] [-interlace JPEG] [-colorspace RGB] OUTPUT.jpg

for jpg images, but none of the above commands gives me the same reduction as suggested by google pagespeed.
 So, let me know if i am missing any parameters or I have passed wrong values of parameters.

The pack of compressed contents are available on google pagespeed page but,I want to compress images using ImageMagick
 or any other sources .


问:
Is it possible to lock a file programmatically? (IBM Connections 5.0)
I am working with the IBM Connection APIs and I didn't find anything about the question of locking a file programmatically in the documentation. There is no way to do it?

I have seen that when a file is locked the metadata is changed:

When it is not locked we have

When it is locked (manually) we have something like that:

     <name>Jane Doe</name>
     <snx:userid>20[...]6E</snx:userid>
     <email>heloise.chauvel@chanel-corp.com</email>
     <snx:userState>active</snx:userState>

     2017-05-17T13:05:03.990Z

So I could programmatically modify this metadata but is there an easier way to do it?

答:
It is not possible to lock a file programmatically. There is no option in the API documentation and it is unauthorized to submit new metadata like I was explaining in my question. </p>

<p>So what I decided to do was to add a tag "locked" programmatically. No other solution. </p>

Body:
It is not possible to lock a file programmatically. There is no option in the API documentation and it is unauthorized to submit new metadata like I was explaining in my question.

So what I decided to do was to add a tag "locked" programmatically. No other solution.


问:
Highlight images on page when the user clicks on them
I want to add CSS style with JavaScript: "padding", "background", and "border" to the image clicked by the user, when the user clicks again on that image, the highlight effect is removed.</p>

```<code>var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightimages() {
  var allimages = document.getElementsByid('images');
//How do i start from here
}
</code>```

答:
Create a css class

```<code>  highlighted {
   padding: '3px';
   backgroundColor: '#eded01';
   borderSize: '1ps';
   borderStyle: 'dashed';
   borderColor: '#0001fe'
 }
</code>```

Using jQuery:

```<code>var $element = $('#elementid');
$element.click(function () {
     $(this).toogleClass('highligted');
});
</code>```

Body:
I want to add CSS style with JavaScript: "padding", "background", and "border" to the image clicked by the user, when the user clicks again on that image, the highlight effect is removed.

var imagesProp = {
  'padding': '3px',
  'backgroundColor': '#eded01',
  'borderSize': '1ps',
  'borderStyle': 'dashed',
  'borderColor': '#0001fe'
};

function highlightimages() {
  var allimages = document.getElementsByid('images');
//How do i start from here
}

Body:
Create a css class

  highlighted {
   padding: '3px';
   backgroundColor: '#eded01';
   borderSize: '1ps';
   borderStyle: 'dashed';
   borderColor: '#0001fe'
 }

Using jQuery:

var $element = $('#elementid');
$element.click(function () {
     $(this).toogleClass('highligted');
});


问:
Multiple MAX values in a single query
I'm taking this data and inserting it into another table as part of a conversion process. Unfortunately I'm not able to modify the table schema in either my source or target location.

Schema is as follows (super simplified but the data types can't be modified, just obviously cast)

```<code>CREATE TABLE [dbo].[TestScores](
    [id] [INT] NOT NULL,
    [EXAMNE_ID] [VARCHAR](40) NULL,
    [TestName] VARCHAR(30) NULL,
    [PASS_STA] [VARCHAR](5) NULL,
    [TST_DTE] [VARCHAR](8) NULL,
    [STD_SCOR] [VARCHAR](3) NULL,
) ON [PRIMARY]
</code>```

I have the following source data: (Obviously just a snapshot of the data but for a single person)

```<code>+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
|  1 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  2 |     00001 | Science         | Fail     | 20160608 |        8 |
|  3 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  4 |     00001 | Math            | Fail     | 20160608 |        8 |
|  5 |     00001 | Writing         | Fail     | 20160608 |        7 |
|  6 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  7 |     00001 | Science         | Fail     | 20160608 |        8 |
|  8 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  9 |     00001 | Math            | Fail     | 20160608 |        8 |
| 10 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 11 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 12 |     00001 | Science         | Fail     | 20160608 |        8 |
| 13 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 14 |     00001 | Math            | Fail     | 20160608 |        8 |
| 15 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 16 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 17 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 18 |     00001 | Science         | Fail     | 20160608 |        8 |
| 19 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 20 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 21 |     00001 | Math            | Fail     | 20160608 |        8 |
| 22 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 23 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 24 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 25 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 26 |     00001 | Science         | Fail     | 20160608 |        8 |
| 27 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 28 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 29 |     00001 | Math            | Fail     | 20160608 |        8 |
| 30 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 31 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 32 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 33 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 34 |     00001 | Science         | Fail     | 20160608 |        8 |
| 35 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 36 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 37 |     00001 | Math            | Fail     | 20160608 |        8 |
| 38 |     00001 | Writing         | Pass     | 20160608 |        7 |
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 40 |     00001 | Social Studies  | Pass     | 20160608 |        7 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 43 |     00001 | Reading         | Pass     | 20160608 |        2 |
| 44 |     00001 | Reading         | Pass     | 20160930 |        5 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+
</code>```

My end result target data should look like this:

```<code>+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+
</code>```

I know I gave a ton of extra data since I'm really only looking for results that have a PASS_STA of 'Pass', but I wanted to give more of a complete picture.

Essentially the logic that occurs is that for a given person, when the exam is passed, pull out the greatest value of the TST_DTE and STD_SCOR columns. I'm trying this with what seems like multiple variants of max but it's heading in the wrong direction.

Currently this query isn't giving me what I'm looking for.

```<code>SELECT DISTINCT
EXAMNE_ID, PASS_STA, TestName, MAX(TST_DTE) AS 'TST_DTE', MAX(STD_SCOR) AS 'STD_SCOR'
FROM dbo.TestScores
GROUP BY EXAMNE_ID, PASS_STA, TestName, STD_SCOR
HAVING PASS_STA = 'Pass'
</code>```

Part of me is thinking I need to nest the query since I'm looking for two max values (plus one is a date - well, a date-ish, since it's in a varchar) and the other is a number (but again, stored in a varchar) or maybe somehow the RANK functionality?

I'd rather not have to do aggregate CASE statements for each of the five subject areas. There are actually a few dozen subject areas total, it's just this one test type that I'm showing here has five. So while I think aggregate case statements may work, it may be too cumbersome.

Any ideas?

Thanks in advance

答:
Rank your records per student and test by date with ROW_NUMBER. Then keep only the record with the latest date per student and test (i.e. the records ranked #1).

```<code>select examne_id, pass_sta, testname, tst_dte, std_scor
from
(
  select
    ts.*,
    row_number() over (partition by examne_id, testname order by tst_dte desc) as rn
  from dbo.testscores ts
  where pass_sta = 'Pass'
)
where rn = 1;
</code>```

Title: Multiple MAX values in a single query

Body:
I'm taking this data and inserting it into another table as part of a conversion process. Unfortunately I'm not able to modify the table schema in either my source or target location.

Schema is as follows (super simplified but the data types can't be modified, just obviously cast)

CREATE TABLE [dbo].[TestScores](
    [id] [INT] NOT NULL,
    [EXAMNE_ID] [VARCHAR](40) NULL,
    [TestName] VARCHAR(30) NULL,
    [PASS_STA] [VARCHAR](5) NULL,
    [TST_DTE] [VARCHAR](8) NULL,
    [STD_SCOR] [VARCHAR](3) NULL,
) ON [PRIMARY]

I have the following source data: (Obviously just a snapshot of the data but for a single person)

+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
|  1 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  2 |     00001 | Science         | Fail     | 20160608 |        8 |
|  3 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  4 |     00001 | Math            | Fail     | 20160608 |        8 |
|  5 |     00001 | Writing         | Fail     | 20160608 |        7 |
|  6 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
|  7 |     00001 | Science         | Fail     | 20160608 |        8 |
|  8 |     00001 | Reading         | Fail     | 20160608 |        2 |
|  9 |     00001 | Math            | Fail     | 20160608 |        8 |
| 10 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 11 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 12 |     00001 | Science         | Fail     | 20160608 |        8 |
| 13 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 14 |     00001 | Math            | Fail     | 20160608 |        8 |
| 15 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 16 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 17 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 18 |     00001 | Science         | Fail     | 20160608 |        8 |
| 19 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 20 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 21 |     00001 | Math            | Fail     | 20160608 |        8 |
| 22 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 23 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 24 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 25 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 26 |     00001 | Science         | Fail     | 20160608 |        8 |
| 27 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 28 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 29 |     00001 | Math            | Fail     | 20160608 |        8 |
| 30 |     00001 | Writing         | Fail     | 20160608 |        7 |
| 31 |     00001 | Writing         | Fail     | 20160930 |       10 |
| 32 |     00001 | Social Studies  | Fail     | 20160608 |        7 |
| 33 |     00001 | Social Studies  | Fail     | 20160930 |       10 |
| 34 |     00001 | Science         | Fail     | 20160608 |        8 |
| 35 |     00001 | Reading         | Fail     | 20160608 |        2 |
| 36 |     00001 | Reading         | Fail     | 20160930 |        5 |
| 37 |     00001 | Math            | Fail     | 20160608 |        8 |
| 38 |     00001 | Writing         | Pass     | 20160608 |        7 |
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 40 |     00001 | Social Studies  | Pass     | 20160608 |        7 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 43 |     00001 | Reading         | Pass     | 20160608 |        2 |
| 44 |     00001 | Reading         | Pass     | 20160930 |        5 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+

My end result target data should look like this:

+----+-----------+-----------------+----------+----------+----------+
| id | EXAMNE_ID |    TestName     | PASS_STA | TST_DTE  | STD_SCOR |
+----+-----------+-----------------+----------+----------+----------+
| 39 |     00001 | Writing         | Pass     | 20160930 |       10 |
| 41 |     00001 | Social Studies  | Pass     | 20160930 |       10 |
| 42 |     00001 | Science         | Pass     | 20160608 |        8 |
| 45 |     00001 | Reading         | Pass     | 20161202 |        9 |
| 46 |     00001 | Math            | Pass     | 20160608 |        8 |
+----+-----------+-----------------+----------+----------+----------+

I know I gave a ton of extra data since I'm really only looking for results that have a PASS_STA of 'Pass', but I wanted to give more of a complete picture.

Essentially the logic that occurs is that for a given person, when the exam is passed, pull out the greatest value of the TST_DTE and STD_SCOR columns. I'm trying this with what seems like multiple variants of max but it's heading in the wrong direction.

Currently this query isn't giving me what I'm looking for.

SELECT DISTINCT
EXAMNE_ID, PASS_STA, TestName, MAX(TST_DTE) AS 'TST_DTE', MAX(STD_SCOR) AS 'STD_SCOR'
FROM dbo.TestScores
GROUP BY EXAMNE_ID, PASS_STA, TestName, STD_SCOR
HAVING PASS_STA = 'Pass'

Part of me is thinking I need to nest the query since I'm looking for two max values (plus one is a date - well, a date-ish, since it's in a varchar) and the other is a number (but again, stored in a varchar) or maybe somehow the RANK functionality?

I'd rather not have to do aggregate CASE statements for each of the five subject areas. There are actually a few dozen subject areas total, it's just this one test type that I'm showing here has five. So while I think aggregate case statements may work, it may be too cumbersome.

Any ideas?

Thanks in advance

Body:
Rank your records per student and test by date with ROW_NUMBER. Then keep only the record with the latest date per student and test (i.e. the records ranked #1).

select examne_id, pass_sta, testname, tst_dte, std_scor
from
(
  select
    ts.*,
    row_number() over (partition by examne_id, testname order by tst_dte desc) as rn
  from dbo.testscores ts
  where pass_sta = 'Pass'
)
where rn = 1;


问:
unable to set private key file: './cert.pem' type PEM
I am using curl to download data from a https site using public certificate files.

System information:

OS: fedora 14

curl: curl 7.30.0

openssl: OpenSSL 1.0.0a-fips

The command is,

```<code>curl -v "https://<ip:<port>" --cert "./cert.pem" --cacert "./cacert.pem" --cert-type PEM
* About to connect() to kng.com port 443 (#0)
*   Trying 11.19.37.123...
* Adding handle: conn: 0x8189e68
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x8189e68) send_pipe: 1, recv_pipe: 0
* Connected to fkng.com (11.19.37.123) port 443 (#0)
* unable to set private key file: './cert.pem' type PEM
* Closing connection 0
curl: (58) unable to set private key file: './cert.pem' type PEM
</code>```

I have have given all the permission to the .pem file, still curl is throwing an error.

答: Im not sure If this will help anyone but I was getting this error (although I was using php to create it instead of the command line) and to fix it I had to ensure that no old .key or .pem files were in the directory I was looking at. By deleting them and making fresh files with the authentication it worked perfectly!</p>

Body:
I am using curl to download data from a https site using public certificate files.

System information:

OS: fedora 14

curl: curl 7.30.0

openssl: OpenSSL 1.0.0a-fips

The command is,

curl -v "https://<ip:<port>" --cert "./cert.pem" --cacert "./cacert.pem" --cert-type PEM
* About to connect() to kng.com port 443 (#0)
*   Trying 11.19.37.123...
* Adding handle: conn: 0x8189e68
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x8189e68) send_pipe: 1, recv_pipe: 0
* Connected to fkng.com (11.19.37.123) port 443 (#0)
* unable to set private key file: './cert.pem' type PEM
* Closing connection 0
curl: (58) unable to set private key file: './cert.pem' type PEM

I have have given all the permission to the .pem file, still curl is throwing an error.


问:
Use asp.net identity with geography authorize
I used Asp.net Identity in an enterprise web application (mvc) with role and group based permissions management. Now I have to add a new entity as geography to divided users in different provinces or regions to authorized users access. I mean every user can fetch his/her province or region data in pages. Is there a best practice for this purpose? Or can any one guide me about this subject?

thanks.

Update:
I have a simple design in my mind like this.(I could not attached the image here.)

答:
I've developed a claims based security framework for covering all my needs in security layer as user, group and claim manager with row level security also. I could cover geo authorize with rls concept in my project.
You can find it in GitHub to check the source and use it.</p>


问:
Partitioning Strategy For Complete Graph In Spark GraphX
I have created a graph using Spark graphX in which every vertex is directly connected to every other vertex of graph i.e Complete graph.
Please if anyone can suggest good partitioning strategy for this type of situation or any ideas to implement custom partition strategy.

I have 1 million vertices and 500 million edges.

Any ideas or suggestions related to this will be greatly appreciated.
Thanks in advance.

答:
If you have a complete graph, you do not have to care about sophisticated partitioning algorithms. Just take the random partitioning method which is already implemented by GraphX.

If you have n graph vertices and k partitions, any balanced (edge-cut) partitioning strategy will assign about n/k vertices to each partition which results in (n-n/k) outgoing edges per partition to other partitions: each vertex is connected to each other vertex on each other partition.


问:
Accessing old and new values in WHERE clause of CREATE RULE
I'm trying to merge two dump files as outlined in this answer. In working through creating the rule I keep having issues trying to access both the OLD and NEW values of my account table.

The account schema is just a table with a single column of type jsonb called value. Inside the value column are two fields off which I want to create the skip_unique rule. Following is the latest query I've tried and the ensuing response:

```<code>CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE NEW.value->>'opCo' = OLD.value->>'opCo' AND NEW.value->>'customerId' = OLD.value->>'customerId' DO INSTEAD NOTHING;

ERROR:  invalid reference to FROM-clause entry for table "old"
LINE 1: ...S ON INSERT TO account WHERE NEW.value->>'opCo' = OLD.value-...
                                                             ^
HINT:  There is an entry for table "old", but it cannot be referenced from this part of the query.
</code>```

I've tried numerous permutations of the same general query including:

```<code>CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE (EXISTS (SELECT 1 FROM account WHERE NEW.value->>'opCo' = OLD.value->>'opCo' AND NEW.value->>'customerId' = OLD.value->>'customerId')) DO INSTEAD NOTHING;
CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE (EXISTS (SELECT 1 FROM account AS b WHERE b.value->>'opCo' = account.value->>'opCo' AND b.value->>'customerId' = account.value->>'customerId')) DO INSTEAD NOTHING;
CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account old WHERE (NEW.value->>'opCo' = old.value->>'opCo' AND NEW.value->>'customerId' = old.value->>'customerId') DO INSTEAD NOTHING;
</code>```

None of them have worked for various reasons.

Thanks in advance for your help!

答:
There is no OLD variable (or rather it's unassigned) on an INSERT trigger. After all, with an INSERT you're inserting something new, so what would you expect OLD to hold?

OLD

Data type RECORD; variable holding the old database row for
  UPDATE/DELETE operations in row-level triggers. This variable is
  unassigned in statement-level triggers and for INSERT operations.

https://www.postgresql.org/docs/current/static/plpgsql-trigger.html

You should be looking for the value in the table rather than OLD.

Body:
I'm trying to merge two dump files as outlined in this answer. In working through creating the rule I keep having issues trying to access both the OLD and NEW values of my account table.

The account schema is just a table with a single column of type jsonb called value. Inside the value column are two fields off which I want to create the skip_unique rule. Following is the latest query I've tried and the ensuing response:

CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE NEW.value->>'opCo' = OLD.value->>'opCo' AND NEW.value->>'customerId' = OLD.value->>'customerId' DO INSTEAD NOTHING;

ERROR:  invalid reference to FROM-clause entry for table "old"
LINE 1: ...S ON INSERT TO account WHERE NEW.value->>'opCo' = OLD.value-...
                                                             ^
HINT:  There is an entry for table "old", but it cannot be referenced from this part of the query.

I've tried numerous permutations of the same general query including:

CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE (EXISTS (SELECT 1 FROM account WHERE NEW.value->>'opCo' = OLD.value->>'opCo' AND NEW.value->>'customerId' = OLD.value->>'customerId')) DO INSTEAD NOTHING;
CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account WHERE (EXISTS (SELECT 1 FROM account AS b WHERE b.value->>'opCo' = account.value->>'opCo' AND b.value->>'customerId' = account.value->>'customerId')) DO INSTEAD NOTHING;
CREATE OR REPLACE RULE skip_unique AS ON INSERT TO account old WHERE (NEW.value->>'opCo' = old.value->>'opCo' AND NEW.value->>'customerId' = old.value->>'customerId') DO INSTEAD NOTHING;

None of them have worked for various reasons.

Thanks in advance for your help!


问:
Satellizer providers login in Chrome browser, AngularJS
I have a problem with Satellizer and Google Chrome browser.

At first, I think I have implemented and configured well all the authorization providers, both with the corresponding redirectUri and with the API url that are dedicated to the authorization.

My problem is the following and it only happens to me with Google Chrome and is that 70% of the times I intend to log in with Facebook or Google, I get in console the following error:

Error: OAuth redirect has occurred but no query or hash parameters were > found. They were either set during the redirect, or were removed-typically by a routing library-before Satellizer could read it.

I also attached the configuration I have of the providers:

```<code>$authProvider.facebook({
    clientId : 'myFabecookClientId(already defined)',
    responseType: 'token',
    name: 'facebook',
    url: 'endPoint auth/facebook del API del backend',
    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog  /oauth',
    redirectUri: window.location.origin +'/',
    requiredUrlParams: ['display', 'scope'],
    scope: ['email'],
    scopeDelimiter: ',',
    display: 'popup',
    oauthType: '2.0',
    popupOptions: { width: 580, height: 400 }
});

$authProvider.google({
    clientId: 'myGoogleClientId(already defined)',
    responseType : 'code',
    name: 'google',
    url : 'Endpoint auth/google del API del backend',
    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
    redirectUri : window.location.origin + ','
});
</code>```

I have backend on a remote server running and the frontend in local since it has divided the work in two, in case it could affect in something.

It is curious, since in Firefox for example authorizes me without problems.

答: Try running frontend on remote (public) server instead of local server. Chrome may have some CORS issues</p>

Body:
I have a problem with Satellizer and Google Chrome browser.

At first, I think I have implemented and configured well all the authorization providers, both with the corresponding redirectUri and with the API url that are dedicated to the authorization.

My problem is the following and it only happens to me with Google Chrome and is that 70% of the times I intend to log in with Facebook or Google, I get in console the following error:

Error: OAuth redirect has occurred but no query or hash parameters were > found. They were either set during the redirect, or were removed-typically by a routing library-before Satellizer could read it.

I also attached the configuration I have of the providers:

$authProvider.facebook({
    clientId : 'myFabecookClientId(already defined)',
    responseType: 'token',
    name: 'facebook',
    url: 'endPoint auth/facebook del API del backend',
    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog  /oauth',
    redirectUri: window.location.origin +'/',
    requiredUrlParams: ['display', 'scope'],
    scope: ['email'],
    scopeDelimiter: ',',
    display: 'popup',
    oauthType: '2.0',
    popupOptions: { width: 580, height: 400 }
});

$authProvider.google({
    clientId: 'myGoogleClientId(already defined)',
    responseType : 'code',
    name: 'google',
    url : 'Endpoint auth/google del API del backend',
    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
    redirectUri : window.location.origin + ','
});

I have backend on a remote server running and the frontend in local since it has divided the work in two, in case it could affect in something.

It is curious, since in Firefox for example authorizes me without problems.


问:
Remote database management from local development server
I am looking for a way to access and query my remote databases from my local server.
Something like PhpMyAdmin, but little more versatile.

So that I can feed it with databases I would like to see, store my queries (or better, if it has ways to access simple queries built in itself)

Can someone help me with such a PHP Script (or Class)?

Regards
Nikhil Gupta

答: PHP has full support for mysql databases. See http://www.php.net/manual/en/ref.msql.php. Just use the address for your remote server when opening the connection.</p>