问:
sorting JSON table with javascript
I have this simple JSON table where the elements needs to be sorted in alpabetical order by value and the other alpabetical order by name. Could someone give me and example how would i do it so i can understand it?</p>

```<code>{

  "sortingTask": [

      {"sortAlpabeticallyByValue": [

      {"string":"äää"},

      {"string":"bee"},

      {"string":"aaa"},

      {"string":"öoöo"},

      {"string":"OöOö"},

  ]},

      {"sortAlpabeticallyByName": [

      {"stringB":"testi1"},

      {"stringÄ":"testi2"},

      {"stringA":"testi3"}

  ]},

  {"sortAlpabetically": [

      "äää","bee","baa"

  ]}

  ]

}
</code>```

答:
You need to implement custom sort method using switch case. For comparison between two words you can use localeCompare

var data = { "sortingTask": [ {"sortAlpabeticallyByValue": [ {"string":"äää"}, {"string":"bee"}, {"string":"aaa"}, {"string":"öoöo"}, {"string":"OöOö"}, ]}, {"sortAlpabeticallyByName": [{"stringB":"testi1"}, {"stringÄ":"testi2"}, {"stringA":"testi3"} ]}, {"sortAlpabetically":[ "äää","bee","baa" ]}]};

data.sortingTask.forEach(function(obj){
  Object.keys(obj).forEach(function(k){
    switch(k){
      case 'sortAlpabeticallyByValue' :
        obj[k].sort(function(a,b){
          return a.string.localeCompare(b.string, undefined, { sensitivity: 'variant' });
        });
        break;
       case 'sortAlpabetically':
        obj[k].sort(function(a,b){
          return a.localeCompare(b, undefined, {sensitivity: 'variant'});
        });
        break;
       case 'sortAlpabeticallyByName':
        obj[k].sort(function(a,b){
          return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
        });
        break;
    }
  });
});
console.log(data);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: sorting JSON table with javascript

Body:
I have this simple JSON table where the elements needs to be sorted in alpabetical order by value and the other alpabetical order by name. Could someone give me and example how would i do it so i can understand it?

{

  "sortingTask": [

      {"sortAlpabeticallyByValue": [

      {"string":"äää"},

      {"string":"bee"},

      {"string":"aaa"},

      {"string":"öoöo"},

      {"string":"OöOö"},

  ]},

      {"sortAlpabeticallyByName": [

      {"stringB":"testi1"},

      {"stringÄ":"testi2"},

      {"stringA":"testi3"}

  ]},

  {"sortAlpabetically": [

      "äää","bee","baa"

  ]}

  ]

}

Body:
You need to implement custom sort method using switch case. For comparison between two words you can use localeCompare

var data = { "sortingTask": [ {"sortAlpabeticallyByValue": [ {"string":"äää"}, {"string":"bee"}, {"string":"aaa"}, {"string":"öoöo"}, {"string":"OöOö"}, ]}, {"sortAlpabeticallyByName": [{"stringB":"testi1"}, {"stringÄ":"testi2"}, {"stringA":"testi3"} ]}, {"sortAlpabetically":[ "äää","bee","baa" ]}]};

data.sortingTask.forEach(function(obj){
  Object.keys(obj).forEach(function(k){
    switch(k){
      case 'sortAlpabeticallyByValue' :
        obj[k].sort(function(a,b){
          return a.string.localeCompare(b.string, undefined, { sensitivity: 'variant' });
        });
        break;
       case 'sortAlpabetically':
        obj[k].sort(function(a,b){
          return a.localeCompare(b, undefined, {sensitivity: 'variant'});
        });
        break;
       case 'sortAlpabeticallyByName':
        obj[k].sort(function(a,b){
          return Object.keys(a)[0].localeCompare(Object.keys(b)[0]);
        });
        break;
    }
  });
});
console.log(data);

.as-console-wrapper { max-height: 100% !important; top: 0; }


来源: stackexchange

问:
Android set permission inside list-view custom apdpater class
I am trying to set permission to make the phone call  inside custom list adapter class extends from BaseAdapter from getView method.

But when touching on icon image the application crash

```<code>public View getView(int position, View convertView, ViewGroup parent) {

        final TextView  phoneTxt  = (TextView)convertView.findViewById(R.id.phone);
        ImageView phoneImage = (ImageView)convertView.findViewById(R.id.phone_icon);
        phoneImage.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
               int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
               if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL);
               }
               else {
                 Intent intent = new Intent(Intent.ACTION_CALL);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.setData(Uri.parse("tel:" + phoneTxt.getText()));
                 context.startActivity(intent);
               }

        }
    });
    }

    return convertView;
}
</code>```

Here is the error log

```<code>11-13 11:54:05.297: E/AndroidRuntime(9530): FATAL EXCEPTION: main
11-13 11:54:05.297: E/AndroidRuntime(9530): Process: com.myapp.myApp, PID: 9530
11-13 11:54:05.297: E/AndroidRuntime(9530): java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.myapp.myApp.adapter.NavDrawerListAdapter$1.onClick(NavDrawerListAdapter.java:134)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View.performClick(View.java:5269)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View$PerformClick.run(View.java:21556)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.handleCallback(Handler.java:815)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.dispatchMessage(Handler.java:104)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Looper.loop(Looper.java:207)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.app.ActivityThread.main(ActivityThread.java:5769)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at java.lang.reflect.Method.invoke(Native Method)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
</code>```

Why this happening, is there any bug in above code?.

答:
declare global in your activity or fargment

```<code>private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 101;
</code>```

make checkAndRequestPermissions method and call in your list or before list.

```<code>public static boolean checkAndRequestPermissions(Context context) {

    int callphonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);

    List<String> listPermissionsNeeded = new ArrayList<>();

    if (callphonePermission != PackageManager.PERMISSION_GRANTED) {
       listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
    }

    if (!listPermissionsNeeded.isEmpty()) {
       ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
       return false;
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to set permission to make the phone call  inside custom list adapter class extends from BaseAdapter from getView method.

But when touching on icon image the application crash

public View getView(int position, View convertView, ViewGroup parent) {

        final TextView  phoneTxt  = (TextView)convertView.findViewById(R.id.phone);
        ImageView phoneImage = (ImageView)convertView.findViewById(R.id.phone_icon);
        phoneImage.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
               int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);
               if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                 ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL);
               }
               else {
                 Intent intent = new Intent(Intent.ACTION_CALL);
                 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                 intent.setData(Uri.parse("tel:" + phoneTxt.getText()));
                 context.startActivity(intent);
               }

        }
    });
    }

    return convertView;
}

Here is the error log

11-13 11:54:05.297: E/AndroidRuntime(9530): FATAL EXCEPTION: main
11-13 11:54:05.297: E/AndroidRuntime(9530): Process: com.myapp.myApp, PID: 9530
11-13 11:54:05.297: E/AndroidRuntime(9530): java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.myapp.myApp.adapter.NavDrawerListAdapter$1.onClick(NavDrawerListAdapter.java:134)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View.performClick(View.java:5269)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.view.View$PerformClick.run(View.java:21556)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.handleCallback(Handler.java:815)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Handler.dispatchMessage(Handler.java:104)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.os.Looper.loop(Looper.java:207)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at android.app.ActivityThread.main(ActivityThread.java:5769)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at java.lang.reflect.Method.invoke(Native Method)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-13 11:54:05.297: E/AndroidRuntime(9530):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

Why this happening, is there any bug in above code?.

Body:
declare global in your activity or fargment

private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 101;

make checkAndRequestPermissions method and call in your list or before list.

public static boolean checkAndRequestPermissions(Context context) {

    int callphonePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE);

    List<String> listPermissionsNeeded = new ArrayList<>();

    if (callphonePermission != PackageManager.PERMISSION_GRANTED) {
       listPermissionsNeeded.add(Manifest.permission.CALL_PHONE);
    }

    if (!listPermissionsNeeded.isEmpty()) {
       ActivityCompat.requestPermissions((Activity) context, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
       return false;
    }
    return true;
}


问:
How not to compile casting into enum type in C++?
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

```<code>class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};
</code>```

This allows me to write the following code:

```<code>Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws
</code>```

My problem is that a compiler allows constructs such as:

```<code>Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws
</code>```

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

答:
Potentially a crummy solution, but it would solve your immediate problem.  Rather than having an inner enum type, define a little helper class with a private constructor, and make the outer class a friend.  Then the "enum" values can be static const members in your outer class.  Something like this:

(DISCLAIMER: untested, so there may be various compilation issues, but you should get the idea)

```<code>class Symmetry
{
public:
    class Type
    {
    private:
        Type() {};
        friend class Symmetry;
    };

    static const Type GENERAL;
    static const Type SYMMETRIC;
    static const Type HERMITIAN;
};
</code>```

You will need some way of determining equality, but this should be fairly easy.

ContentLicense: CC BY-SA 2.5

Body:
I have this "better" enum class that

cannot contain invalid values, and

cannot be used until enum value is not set explicitly,

as follows:

class Symmetry
{
    public:
        enum Type {
            GENERAL, SYMMETRIC, HERMITIAN,
            SKEW_SYMMETRIC, SKEW_HERMITIAN, UNINITIALIZED
        };

        Symmetry() { t_ = UNINITIALIZED }
        explicit Symmetry(Type t) : t_(t) { checkArg(t); }
        Symmetry& operator=(Type t) { checkArg(t); t_ = t; return *this; }

        operator Type() const {
            if (t_ == UNINITIALIZED) throw runtime_error("error");
            return t_;
        }

    private:
        Type t_;

        void checkArg(Type t) {
            if ((unsigned)t >= (unsigned)UNINITIALIZED)
                throw runtime_error("error");
        }
};

This allows me to write the following code:

Symmetry s1(Symmetry::SYMMETRIC);
Symmetry s2;
s2 = Symmetry::HERMITIAN;
Symmetry s3;
if (Symmetry::GENERAL == s3) // throws

My problem is that a compiler allows constructs such as:

Symmetry s1((Symmetry::Type)18); // throws
Symmetry s2;
s2 = (Symmetry::Type)18; // throws

I solved this problem by throwing exceptions, but I would prefer such a code not to compile at all (a compile time error). Is there a way how to manage this?

Body:
Potentially a crummy solution, but it would solve your immediate problem.  Rather than having an inner enum type, define a little helper class with a private constructor, and make the outer class a friend.  Then the "enum" values can be static const members in your outer class.  Something like this:

(DISCLAIMER: untested, so there may be various compilation issues, but you should get the idea)

class Symmetry
{
public:
    class Type
    {
    private:
        Type() {};
        friend class Symmetry;
    };

    static const Type GENERAL;
    static const Type SYMMETRIC;
    static const Type HERMITIAN;
};

You will need some way of determining equality, but this should be fairly easy.


问:
React-Router only one child
I keep on getting the error:

A 'Router' may have only one child element

when using react-router.

I can't seem to figure out why this is not working, since it's exactly like the code they show in their example: Quick Start

Here is my code:

```<code>import React from 'react';
import Editorstore from './Editorstore';
import App from './components/editor/App';
import BaseLayer from './components/baselayer';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {render} from 'react-dom';

const root = document.createElement('div');
root.id = 'app';
document.body.appendChild(root);

const store = new Editorstore();
const stylelist = ['https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.33.1/mapbox-gl.css'];

stylelist.map((link) => {
    const a = document.createElement('link');
    a.rel = 'stylesheet';
    a.href = link;
    document.body.appendChild(a);
    return null;
});

render((
  <Router>
    <Route exact  path="/" component={BaseLayer} />
    <Route path="/editor" component={App} store={store} />
  </Router>
), document.querySelector('#app'));
</code>```

答:
This problem occurs when you don't have parent tag before <Route>inside <Router> so to resolve this problem keep the <Route>enclosed in a parent tag such as
 ,
 etc.
Example -

```<code><Router>
    <p>
       <Route path="/login" component={Login} />
       <Route path="/register" component={Register} />
    </p>
</Router>
</code>```

ContentLicense: CC BY-SA 4.0

Title: React-Router only one child

Body:
I keep on getting the error:

A 'Router' may have only one child element

when using react-router.

I can't seem to figure out why this is not working, since it's exactly like the code they show in their example: Quick Start

Here is my code:

import React from 'react';
import Editorstore from './Editorstore';
import App from './components/editor/App';
import BaseLayer from './components/baselayer';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import {render} from 'react-dom';

const root = document.createElement('div');
root.id = 'app';
document.body.appendChild(root);

const store = new Editorstore();
const stylelist = ['https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.2/semantic.min.css', 'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', 'https://api.tiles.mapbox.com/mapbox-gl-js/v0.33.1/mapbox-gl.css'];

stylelist.map((link) => {
    const a = document.createElement('link');
    a.rel = 'stylesheet';
    a.href = link;
    document.body.appendChild(a);
    return null;
});

render((
  <Router>
    <Route exact  path="/" component={BaseLayer} />
    <Route path="/editor" component={App} store={store} />
  </Router>
), document.querySelector('#app'));

Body:
This problem occurs when you don't have parent tag before <Route>inside <Router> so to resolve this problem keep the <Route>enclosed in a parent tag such as <div> , <p> etc.
Example -

<Router>
    <p>
       <Route path="/login" component={Login} />
       <Route path="/register" component={Register} />
    </p>
</Router>


问:
Run IntelliJ configuration from command line
I've configured various execution and test configurations in my Java IntelliJ project. Is it possible to execute IntelliJ on a given project and configuration from the command line? </p>

答:
Summary

You will need to define a command line build project to run your tests from the command line, as IntelliJ (or any graphical IDE) does not provide tools to do so.

Details for building running tests using Gradle

In the following directions I picked Gradle as command line build language, though some use Ant, or Maven as possible alternatives. The gradle syntax is based on Groovy, which is a JDK-based scripting language.

A sample configuration for a basic java project is here: http://www.vogella.com/tutorials/Gradle/article.html

Once your Gradle project is setup, you can run 'gw test' from command line.

I highly suggest to install gradle wrapper called 'gdub' from here: https://github.com/dougborg/gdub  -- this will save typing ./gradlew all the time.

Hope this helps!


问:
how to write a VSTS query that shows the teams discussion counts?
we want to write a query that displays the counts of users daily comments in VSTS tasks. How can we do that?

Which API should we use ?

答:
There is the Work Item Comments REST API that can query the comments, for example: https://[account].visualstudio.com/DefaultCollection/_apis/wit/workitems/[work item id]/comments?api-version=3.0-preview.

So, you can build a app to do report with this REST API, you also can custom extension to show data with this REST API: Write your first extension for VSTS


问:
How to combine the two request in which one give response for another api key which pass for request
I want to parse two api at the same time in which one api get a response of key that key has api link and pass in another StringRequest forget response.

This is my function for parsing in which I want to parse firstly one api and get a response in response href name of key use for another api parse link.
please help me as soon as.
I searched and I got this link but it is not proper code.
https://www.versti.eu/TranslateProxy/https/stackoverflow.com/questions/37584001/how-to-combine-the-two-request-url-from-json-to-get-output-in-volley

```<code>private void parseSmartPhone()
 {
  StringRequest stringRequest= new
  StringRequest(com.android.volley.Request.Method.GET,
                Config.HOMECTEGORY, new Response.Listener<String>() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onResponse(String response) {

            try {
                //getting the whole json Array from the response
                //   JSONObject jsonObject= new JSONObject(response);
                JSONArray jsonArray = new JSONArray(response);
                mylist=new ArrayList<>();
                for (int i = 0;i<=2;i++)
                {
                    latestsphone= new LatestSmartPhoneModel();

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JSONObject objtitle=jsonObject.getJSONObject("title");

                    title=objtitle.getString("rendered");

                    objtitle=jsonObject.getJSONObject("_links");

                    JSONArray imgJsonArray=objtitle.getJSONArray("wp:featuredmedia");

                    JSONObject objJsonImg=imgJsonArray.getJSONObject(0);

                    StringRequest request1= new StringRequest(com.android.volley.Request.Method.GET,objJsonImg.getString("href"), new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {

                                JSONObject jsonObject= new JSONObject(response);
                                JSONObject imggild=jsonObject.getJSONObject("guid");
                                String rendered=imggild.getString("rendered");

                                latestsphone.setLink(rendered);
                                latestsphone.setTitle(title);
                                mylist.add(latestsphone);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });

                    RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
                    requestQueue.add(request1);
                    request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                }

                UpcomingAdapter imgAdapter=new UpcomingAdapter(getActivity(),mylist);
                recyclerUpcoming.setAdapter(imgAdapter);
                recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(),2));
                recyclerUpcoming.setHasFixedSize(true);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}
</code>```

答:
This is your proper code, i corrected your posted code, Use these as global parameter.</p>

```<code>ArrayList<LatestSmartPhoneModel> mylist = new ArrayList<>();

String title,link;

private void parseSmartPhone() {

    final RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Config.HOMECTEGORY, new Response.Listener<String>() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onResponse(String response) {

            try {
                //getting the whole json Array from the response
                //   JSONObject jsonObject= new JSONObject(response);

                JSONArray jsonArray = new JSONArray(response);

                for (int i = 0; i <= 3; i++) {
                    if (i==3)
                    {
                        i=4;
                    }
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    JSONObject objtitle = jsonObject.getJSONObject("title");

                    title = objtitle.getString("rendered");
                    link=jsonObject.getString("link");
                    objtitle = jsonObject.getJSONObject("_links");
                    final LatestSmartPhoneModel latestsphone = new LatestSmartPhoneModel();
                    latestsphone.setTitle(title);
                    latestsphone.setLink(link);

                    JSONArray imgJsonArray = objtitle.getJSONArray("wp:featuredmedia");

                    JSONObject objJsonImg = imgJsonArray.getJSONObject(0);

                    StringRequest request1 = new StringRequest(com.android.volley.Request.Method.GET, objJsonImg.getString("href"), new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {

                                JSONObject jsonObject = new JSONObject(response);
                                JSONObject imggild = jsonObject.getJSONObject("guid");
                                String rendered = imggild.getString("rendered");

                                latestsphone.set_links(rendered);

                                mylist.add(latestsphone);

                                UpcomingAdapter imgAdapter = new UpcomingAdapter(getActivity(), mylist);

                                recyclerUpcoming.setAdapter(imgAdapter);
                                recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                                recyclerUpcoming.setHasFixedSize(true);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    requestQueue.add(request1);
                    request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    requestQueue.add(stringRequest);
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}
</code>```

Body:
I want to parse two api at the same time in which one api get a response of key that key has api link and pass in another StringRequest forget response.

This is my function for parsing in which I want to parse firstly one api and get a response in response href name of key use for another api parse link.
please help me as soon as.
I searched and I got this link but it is not proper code.
https://www.versti.eu/TranslateProxy/https/stackoverflow.com/questions/37584001/how-to-combine-the-two-request-url-from-json-to-get-output-in-volley

private void parseSmartPhone()
 {
  StringRequest stringRequest= new
  StringRequest(com.android.volley.Request.Method.GET,
                Config.HOMECTEGORY, new Response.Listener<String>() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onResponse(String response) {

            try {
                //getting the whole json Array from the response
                //   JSONObject jsonObject= new JSONObject(response);
                JSONArray jsonArray = new JSONArray(response);
                mylist=new ArrayList<>();
                for (int i = 0;i<=2;i++)
                {
                    latestsphone= new LatestSmartPhoneModel();

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JSONObject objtitle=jsonObject.getJSONObject("title");

                    title=objtitle.getString("rendered");

                    objtitle=jsonObject.getJSONObject("_links");

                    JSONArray imgJsonArray=objtitle.getJSONArray("wp:featuredmedia");

                    JSONObject objJsonImg=imgJsonArray.getJSONObject(0);

                    StringRequest request1= new StringRequest(com.android.volley.Request.Method.GET,objJsonImg.getString("href"), new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {

                                JSONObject jsonObject= new JSONObject(response);
                                JSONObject imggild=jsonObject.getJSONObject("guid");
                                String rendered=imggild.getString("rendered");

                                latestsphone.setLink(rendered);
                                latestsphone.setTitle(title);
                                mylist.add(latestsphone);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });

                    RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
                    requestQueue.add(request1);
                    request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                }

                UpcomingAdapter imgAdapter=new UpcomingAdapter(getActivity(),mylist);
                recyclerUpcoming.setAdapter(imgAdapter);
                recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(),2));
                recyclerUpcoming.setHasFixedSize(true);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
    requestQueue.add(stringRequest);
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}

Body:
This is your proper code, i corrected your posted code, Use these as global parameter.

ArrayList<LatestSmartPhoneModel> mylist = new ArrayList<>();

String title,link;

private void parseSmartPhone() {

    final RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

    StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.GET, Config.HOMECTEGORY, new Response.Listener<String>() {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onResponse(String response) {

            try {
                //getting the whole json Array from the response
                //   JSONObject jsonObject= new JSONObject(response);

                JSONArray jsonArray = new JSONArray(response);

                for (int i = 0; i <= 3; i++) {
                    if (i==3)
                    {
                        i=4;
                    }
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    JSONObject objtitle = jsonObject.getJSONObject("title");

                    title = objtitle.getString("rendered");
                    link=jsonObject.getString("link");
                    objtitle = jsonObject.getJSONObject("_links");
                    final LatestSmartPhoneModel latestsphone = new LatestSmartPhoneModel();
                    latestsphone.setTitle(title);
                    latestsphone.setLink(link);

                    JSONArray imgJsonArray = objtitle.getJSONArray("wp:featuredmedia");

                    JSONObject objJsonImg = imgJsonArray.getJSONObject(0);

                    StringRequest request1 = new StringRequest(com.android.volley.Request.Method.GET, objJsonImg.getString("href"), new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {

                                JSONObject jsonObject = new JSONObject(response);
                                JSONObject imggild = jsonObject.getJSONObject("guid");
                                String rendered = imggild.getString("rendered");

                                latestsphone.set_links(rendered);

                                mylist.add(latestsphone);

                                UpcomingAdapter imgAdapter = new UpcomingAdapter(getActivity(), mylist);

                                recyclerUpcoming.setAdapter(imgAdapter);
                                recyclerUpcoming.setLayoutManager(new GridLayoutManager(getActivity(), 2));
                                recyclerUpcoming.setHasFixedSize(true);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                    requestQueue.add(request1);
                    request1.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    requestQueue.add(stringRequest);
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

}


问:
How to cache "exists" validation in Yii2
I'm trying to cache the db calls for Yii2 exists validation, but can't work out where to initiate it.

Because I'm using a multi-model form with a lot of relations, the overhead is getting a little too much.

Any ideas?

答:
This is not supported by Yii, you either have to :

Extend the ExistValidator and implement your caching logic there

Add a custom ActiveQuery class to your model in question and override
the exists() and count() methods


答:
Looks like the context that you're using here:

```<code>ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL)
                                             ^^^^^^^
</code>```

is ApplicationContext and not an Activity's context, wherever you're passing the context to your adapter, try passing :

```<code>YourActivity.this; // in case your list view is in an activity
getActivity(); // in case it's in a fragment
</code>```

and not getApplicationContext(), which is possibly what you're doing right now.

Title: Android set permission inside list-view custom apdpater class

Body:
Looks like the context that you're using here:

ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.CALL_PHONE}, REQUEST__PHONE_CALL)
                                             ^^^^^^^

is ApplicationContext and not an Activity's context, wherever you're passing the context to your adapter, try passing :

YourActivity.this; // in case your list view is in an activity
getActivity(); // in case it's in a fragment

and not getApplicationContext(), which is possibly what you're doing right now.


问:
ASP.NET Dynamic Data - Globalization and Localization
Does anybody know how to create a multilingual web application using Dynamic Data and
be able to show any label or button in the correct language upon the selected culture?</p>

答:
You can implement your own ResourceProviderFactory to get your localisations from wherever you want. We use a string as a key to look up the localisations:

For instance:

```<code><asp:Literal Text="<%$ Resources: DBLanguageProvider, Module/Area/HelpMessage %>" runat="server" />
</code>```

OwnerDisplayName: Josue

Body:
You can implement your own ResourceProviderFactory to get your localisations from wherever you want. We use a string as a key to look up the localisations:

For instance:

<asp:Literal Text="<%$ Resources: DBLanguageProvider, Module/Area/HelpMessage %>" runat="server" />

OwnerDisplayName: Keith


问:
Is there a tool to analyse if a C# and WPF project can be ported to Silverlight?
I have a WPF and C# application, and I want to know if it can be ported to silverlight. Is there a tool to analyse the dependencies and tell me what I can't use, and what I can ?

Thanks.

答:
As far as I know there is not. The best way to find out is to create a Silverlight project and copy your code across, then start analysing all the build errors. It is not a great solution, but I don't know of any better way.

As an aside, there is a nice white paper that details the differences between WPF and Silverlight here:

http://wpfslguidance.codeplex.com/Release/ProjectReleases.aspx


问:
How to hide the sidebar using Sphinx RTD theme when making htmlhelp
Is it possible to hide the sidebar when using Sphinx with the ReadTheDocs theme?

Extending the question a bit more, can I have it include the sidebar when issuing a command:

$ make html

and not include it issuing a command:

$ make htmlhelp

without altering code? Maybe add something in the layout.html.

答:
First of all, it is poor form to ask two questions in one post.  Next time, create a separate question.

For your first question, I am not sure what the option collapse_navigation actually does, but its name implies that it does what you seek.  The default value is False, so toggle it to True and see what happens.  See other Read the Docs theme configuration options.

For your second question, there are at least two methods.

You can use the -D option of sphinx-build and override settings in your conf.py.

You can have multiple conf.py files (named as you see fit), and use the -c option to select the appropriate file for the output you want.


问:
A issue on Changing the Color of the Status Bar when switching apps on iPhone
I want to change the Status Bar color with the specific view controller.

According to StackOverFlow's answers , i achieved it.

There is an issue , when switching apps on iPhone, the color I have set fades, goes back to initial state.

It's OK. Please notice the status bar.

Not OK.  Please notice the status bar.

I can't figure it out. The code I tried:

set statusBar.backgroundColor,

```<code>UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
     statusBar.backgroundColor = [UIColor redColor ];
}
</code>```

2. insert subview to  statusBar.

```<code> UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
 UIView * backgroundColorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 20) ];
 backgroundColorView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
 backgroundColorView.backgroundColor = [UIColor redColor ];
 [statusBar.subviews.firstObject insertSubview: backgroundColorView atIndex:0];
</code>```

3.  So is to insert layer(CALayer).

And I tried to analyze it with breakpoints.

- When the app is a active, and double-click the Home button to Switch apps, the method is not called  - (void)viewWillDisappear:(BOOL)animated . It confuses me a little .

- I try to change the background color of status bar in the Application's method - (void)applicationWillResignActive:(UIApplication *)application,  It doesn't work. I don't know why.

While from Github's source code, It's OK through Runtime. My company don't like using Runtime.

Is there some other way without runtime ?

And I don't know how runtime interacts with  iPhone's switching apps mode.

The main question is to solve it without runtime. More explain is welcomed. i think it is easy , what do i miss ?

Many thanks in advances.

答:
Answer for Swift 4:

And it fits the situation of viewControllers managed by navigationViewController

```<code>class ViewController: UIViewController {

    let statusBarBgView = { () -> UIView in
        let statusBarWindow: UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBarBgView = UIView(frame: (statusBarWindow.statusBar?.bounds)!)
        return statusBarBgView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = .lightContent
        let navigationBar = self.navigationController?.navigationBar
        self.statusBarBgView.backgroundColor = UIColor.red
        navigationBar?.superview?.insertSubview(self.statusBarBgView, aboveSubview: navigationBar!)
    }

    override func viewWillDisappear(_ animated: Bool) {

        self.statusBarBgView.removeFromSuperview()
        super.viewWillDisappear(animated)
    }

}

extension UIView {
    var statusBar: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
}
</code>```

The Answer Of Objective-C version:

```<code>-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    self.statusBarBgView = [[UIView alloc ] initWithFrame: statusBar.bounds ];
    self.statusBarBgView.backgroundColor = [UIColor redColor ];
    [navigationBar.superview insertSubview: self.statusBarBgView aboveSubview: navigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.statusBarBgView removeFromSuperview ];
    [super viewWillDisappear:animated];
}
</code>```

The status bar which shows the OS infos，is UIWindow ,controlled by the OS when  in the app switcher window.

```<code>UIView *statusBar = [[[UIApplication sharedApplication]
valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
</code>```

So it's OK to adjust the background color of the status bar position by changing the View , when  in the app switcher window.

Body:
I want to change the Status Bar color with the specific view controller.

According to StackOverFlow's answers , i achieved it.

There is an issue , when switching apps on iPhone, the color I have set fades, goes back to initial state.

It's OK. Please notice the status bar.

Not OK.  Please notice the status bar.

I can't figure it out. The code I tried:

set statusBar.backgroundColor,

UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
     statusBar.backgroundColor = [UIColor redColor ];
}

2. insert subview to  statusBar.

 UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
 UIView * backgroundColorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375, 20) ];
 backgroundColorView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
 backgroundColorView.backgroundColor = [UIColor redColor ];
 [statusBar.subviews.firstObject insertSubview: backgroundColorView atIndex:0];

3.  So is to insert layer(CALayer).

And I tried to analyze it with breakpoints.

- When the app is a active, and double-click the Home button to Switch apps, the method is not called  - (void)viewWillDisappear:(BOOL)animated . It confuses me a little .

- I try to change the background color of status bar in the Application's method - (void)applicationWillResignActive:(UIApplication *)application,  It doesn't work. I don't know why.

While from Github's source code, It's OK through Runtime. My company don't like using Runtime.

Is there some other way without runtime ?

And I don't know how runtime interacts with  iPhone's switching apps mode.

The main question is to solve it without runtime. More explain is welcomed. i think it is easy , what do i miss ?

Many thanks in advances.

Body:
Answer for Swift 4:

And it fits the situation of viewControllers managed by navigationViewController

class ViewController: UIViewController {

    let statusBarBgView = { () -> UIView in
        let statusBarWindow: UIView = UIApplication.shared.value(forKey: "statusBarWindow") as! UIView
        let statusBarBgView = UIView(frame: (statusBarWindow.statusBar?.bounds)!)
        return statusBarBgView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        UIApplication.shared.statusBarStyle = .lightContent
        let navigationBar = self.navigationController?.navigationBar
        self.statusBarBgView.backgroundColor = UIColor.red
        navigationBar?.superview?.insertSubview(self.statusBarBgView, aboveSubview: navigationBar!)
    }

    override func viewWillDisappear(_ animated: Bool) {

        self.statusBarBgView.removeFromSuperview()
        super.viewWillDisappear(animated)
    }

}

extension UIView {
    var statusBar: UIView? {
        return value(forKey: "statusBar") as? UIView
    }
}

The Answer Of Objective-C version:

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear: animated];
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    self.statusBarBgView = [[UIView alloc ] initWithFrame: statusBar.bounds ];
    self.statusBarBgView.backgroundColor = [UIColor redColor ];
    [navigationBar.superview insertSubview: self.statusBarBgView aboveSubview: navigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.statusBarBgView removeFromSuperview ];
    [super viewWillDisappear:animated];
}

The status bar which shows the OS infos，is UIWindow ,controlled by the OS when  in the app switcher window.

UIView *statusBar = [[[UIApplication sharedApplication]
valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

So it's OK to adjust the background color of the status bar position by changing the View , when  in the app switcher window.


问:
how to send 2 parameter with datatables CI
My controller:

```<code>function json_survey()
{
    header('Content-Type: application/json');
    $this->load->library('Datatables');
    $this->load->helper('datatables_helper');
    $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
    $this->datatables->add_column('action',tombol_survey('$1','$2'), 'id_survey,status_survey');
    $this->datatables->FROM('survey');

    return print_r($this->datatables->generate('json',''));
}
</code>```

And my Helper for datatables:

```<code>function tombol_survey($id_survey,$status_survey)
{
    $ci = & get_instance();
    $html = '<span class="actions">';
    If($status_survey=='terbit'){
        $html .= '<a href="' . base_url() . 'subscriber/edit/' . $id_survey . '">Tutup</a>';
    }elseif($status_survey=='tertunda'){
        $html .= '<a href="' . base_url() . 'subscriber/edit/' . $id_survey . '">Tambah</a>';
    }else{
        $html .= 'Tutup | ';
    }
    $html .= '<a href="' . base_url() . 'subscriber/delete/' . $id_survey . '">Lihat | </a>';
    $html .= '<a href="' . base_url() . 'subscriber/delete/' . $id_survey . '">Hapus</a>';
    $html .= '</span>';

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

This is json not error, but parameter 2nd ($status_survey) not included, so function if always return false.

答:
You can achieve this by like below:

Your controller:

```<code>function json_survey()
    {
        header('Content-Type: application/json');
        $this->load->library('Datatables');
        $this->load->helper('datatables_helper');
        $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
        $dataids = array('id_survey'=> $1,'status_survey'=> $2);  //Make array and add params for survey and id and add it to the below function
        $this->datatables->add_column('action',tombol_survey($dataids), 'id_survey,status_survey');
        $this->datatables->FROM('survey');

        return print_r($this->datatables->generate('json',''));
    }

function tombol_survey($ids)
{
    $ci = & get_instance();
    if(!empty($ids)){
        $html = '<span class="actions">';
        if($ids['status_survey']=='terbit'){
            $html .= '<a href="' . base_url() . 'subscriber/edit/' . ($ids['id_survey']) ? ($ids['id_survey']) : ''. '">Tutup</a>';
        }elseif($ids['status_survey']=='tertunda'){
            $html .= '<a href="' . base_url() . 'subscriber/edit/' .($ids['id_survey']) ? ($ids['id_survey']) : ''. '">Tambah</a>';
        }else{
            $html .= 'Tutup | ';
        }
        $html .= '<a href="' . base_url() . 'subscriber/delete/' . ($ids['id_survey']) ? ($ids['id_survey']) : '' . '">Lihat | </a>';
        $html .= '<a href="' . base_url() . 'subscriber/delete/' . ($ids['id_survey']) ? ($ids['id_survey']) : '' . '">Hapus</a>';
        $html .= '</span>';

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

Body:
My controller:

function json_survey()
{
    header('Content-Type: application/json');
    $this->load->library('Datatables');
    $this->load->helper('datatables_helper');
    $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
    $this->datatables->add_column('action',tombol_survey('$1','$2'), 'id_survey,status_survey');
    $this->datatables->FROM('survey');

    return print_r($this->datatables->generate('json',''));
}

And my Helper for datatables:

function tombol_survey($id_survey,$status_survey)
{
    $ci = & get_instance();
    $html = '';
    If($status_survey=='terbit'){
        $html .= 'Tutup';
    }elseif($status_survey=='tertunda'){
        $html .= 'Tambah';
    }else{
        $html .= 'Tutup | ';
    }
    $html .= 'Lihat | ';
    $html .= 'Hapus';
    $html .= '';

    return $html;
}

This is json not error, but parameter 2nd ($status_survey) not included, so function if always return false.

Body:
You can achieve this by like below:

Your controller:

function json_survey()
    {
        header('Content-Type: application/json');
        $this->load->library('Datatables');
        $this->load->helper('datatables_helper');
        $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
        $dataids = array('id_survey'=> $1,'status_survey'=> $2);  //Make array and add params for survey and id and add it to the below function
        $this->datatables->add_column('action',tombol_survey($dataids), 'id_survey,status_survey');
        $this->datatables->FROM('survey');

        return print_r($this->datatables->generate('json',''));
    }

function tombol_survey($ids)
{
    $ci = & get_instance();
    if(!empty($ids)){
        $html = '<span class="actions">';
        if($ids['status_survey']=='terbit'){
            $html .= '<a href="' . base_url() . 'subscriber/edit/' . ($ids['id_survey']) ? ($ids['id_survey']) : ''. '">Tutup</a>';
        }elseif($ids['status_survey']=='tertunda'){
            $html .= '<a href="' . base_url() . 'subscriber/edit/' .($ids['id_survey']) ? ($ids['id_survey']) : ''. '">Tambah</a>';
        }else{
            $html .= 'Tutup | ';
        }
        $html .= '<a href="' . base_url() . 'subscriber/delete/' . ($ids['id_survey']) ? ($ids['id_survey']) : '' . '">Lihat | </a>';
        $html .= '<a href="' . base_url() . 'subscriber/delete/' . ($ids['id_survey']) ? ($ids['id_survey']) : '' . '">Hapus</a>';
        $html .= '</span>';

        return $html;
    }
}


问:
WARNING Error-prone use of @class
```<code>> WARNING 11_test1 odoo.addons.base.ir.ir_ui_view: Error-prone use of
> @class in view report_invoice_document
> (account_invoice_report.report_invoice_document): use the
> hasclass(*classes) function to filter elements by their classes
</code>```

Can someone explain me why i'm getting this warning. using class only in 2 places.

```<code><td class="text-right">
<span t-esc="', '.join(map(lambda x: (x.description or x.name), l.invoice_line_tax_ids))"/>
  </td>
</code>```

and

```<code><xpath expr="//div[@class='row mt32 mb32']/div[@t-if='o.name']" position="replace"/>
</code>```

答:
You can use hasclass() now. Example-

In case of one class in the inherited path:

xpath expr="//div[hasclass('dropdown')]" position="replace">

In case of multiple class in inherited path:

xpath expr="//div[hasclass('dropdown','btn-group','dropdown_sorty_by')]" position="replace">

In your case it should be:

```<code><xpath expr="//div[hasclass('row','mt32','mb32')]/div[@t-if='o.name']" position="replace"/>
</code>```

Title: WARNING Error-prone use of @class

Body:
> WARNING 11_test1 odoo.addons.base.ir.ir_ui_view: Error-prone use of
> @class in view report_invoice_document
> (account_invoice_report.report_invoice_document): use the
> hasclass(*classes) function to filter elements by their classes

Can someone explain me why i'm getting this warning. using class only in 2 places.

and

<xpath expr="//div[@class='row mt32 mb32']/div[@t-if='o.name']" position="replace"/>

Body:
You can use hasclass() now. Example-

In case of one class in the inherited path:

xpath expr="//div[hasclass('dropdown')]" position="replace">

In case of multiple class in inherited path:

xpath expr="//div[hasclass('dropdown','btn-group','dropdown_sorty_by')]" position="replace">

In your case it should be:

<xpath expr="//div[hasclass('row','mt32','mb32')]/div[@t-if='o.name']" position="replace"/>


问:
How to get path inside folder project in java spring mvc
I try to make web apps using java spring MVC.

I set my project folder on D: and the tomcat on C:.

I want to set the path folder for the upload purpose using this code :

```<code>String absoluteFilePath = request.getServletContext().getRealPath("/WEB-INF/uploads/");
</code>```

but the file always set on tomcat, not on project folder. please help me

答: Your Context is always set where your project is deployed thats the reason it is always set on Tomcat. if you want to set any other folder then please use Java File Handling. For Taking Path Dynamically you can use Java Environment Variable as well.</p>

Body:
I try to make web apps using java spring MVC.

I set my project folder on D: and the tomcat on C:.

I want to set the path folder for the upload purpose using this code :

String absoluteFilePath = request.getServletContext().getRealPath("/WEB-INF/uploads/");

but the file always set on tomcat, not on project folder. please help me


问:
Keep automatically searching for connection snap7
We want to autoconnect with the PLC through wifi. When the raspberry is starting up and runs his program automatically. It should be a stand alone raspberry so we don't have a keyboard or anything. We send the data via snap7.
This works, but if the wifi is disconnecting I get this error: "ISO: An error occurred during recv TCP: Connection timed out"
Sometimes in the beginning of the program we get this error: "Snap7Exception:  TCP : Unreachable peer"

My program stops but we should have something so our wifi is reconnected again without stopping the program. I guess we need something to catch our error and use this in a program with a try or something.

My program at this moment:

```<code>import snap7
import struct
import time
from snap7.snap7exceptions import Snap7Exception
import re
from ctypes import c_int, c_char_p, byref, sizeof, c_uint16, c_int32, c_byte
from ctypes import c_void_p

client = snap7.client.Client()

db_number = 109

print('Press Ctrl-C to quit.')

while True:

    if client.get_connected() == False:
        client.connect('192.168.5.2', 0, 1) #('IP-address', rack, slot)
        print('not connected')
        time.sleep(0.2)
    else:
        print('connected')
</code>```

答:
You could use try-exception for connecting and reading the PLC, such as below code:

```<code>from time import sleep
from snap7 import client as s7

def plc_connect(ip, rack, slot, stop_tries, freq):
    plc = s7.Client()
    tries = 1
    while tries < stop_tries and not plc.get_connected():
        try:
            print('trying for connecting to PLC ...')
            sleep(freq)
            plc.connect(ip, rack, slot)
            return True

        except Exception as e:
            logger.error("warning in PLC connection >>{}".format(e))
            sleep(freq)

            if tries == (stop_tries - 1):
                print('error in plc connection')
                return False

        tries += 1
    return False

def data_reader():
    plc = s7.Client()
    try:
        result, data_items = plc.read_multi_vars(data_items)
        return result, data_items
    except Exception as e:
        print('warning:>>{}'.format(e))
</code>```

Body:
We want to autoconnect with the PLC through wifi. When the raspberry is starting up and runs his program automatically. It should be a stand alone raspberry so we don't have a keyboard or anything. We send the data via snap7.
This works, but if the wifi is disconnecting I get this error: "ISO: An error occurred during recv TCP: Connection timed out"
Sometimes in the beginning of the program we get this error: "Snap7Exception:  TCP : Unreachable peer"

My program stops but we should have something so our wifi is reconnected again without stopping the program. I guess we need something to catch our error and use this in a program with a try or something.

My program at this moment:

import snap7
import struct
import time
from snap7.snap7exceptions import Snap7Exception
import re
from ctypes import c_int, c_char_p, byref, sizeof, c_uint16, c_int32, c_byte
from ctypes import c_void_p

client = snap7.client.Client()

db_number = 109

print('Press Ctrl-C to quit.')

while True:

    if client.get_connected() == False:
        client.connect('192.168.5.2', 0, 1) #('IP-address', rack, slot)
        print('not connected')
        time.sleep(0.2)
    else:
        print('connected')

Body:
You could use try-exception for connecting and reading the PLC, such as below code:

from time import sleep
from snap7 import client as s7

def plc_connect(ip, rack, slot, stop_tries, freq):
    plc = s7.Client()
    tries = 1
    while tries < stop_tries and not plc.get_connected():
        try:
            print('trying for connecting to PLC ...')
            sleep(freq)
            plc.connect(ip, rack, slot)
            return True

        except Exception as e:
            logger.error("warning in PLC connection >>{}".format(e))
            sleep(freq)

            if tries == (stop_tries - 1):
                print('error in plc connection')
                return False

        tries += 1
    return False

def data_reader():
    plc = s7.Client()
    try:
        result, data_items = plc.read_multi_vars(data_items)
        return result, data_items
    except Exception as e:
        print('warning:>>{}'.format(e))


问:
How to stretch header across the screen
I have banner image that stretches the screen. I was told that the best
way to stretch is to load an image at the appropriate width. So doesn't that
mean you need to use JavaScript to detect the screen resolution then load the appropriate image? However JS maybe disabled. Are there alternatives?</p>

答:
You can do this using pure css.

```<code>img.banner {position:absolute; z-index:1; width:100%; height:100%;}
</code>```

Here is a demo by stu nicholls.

Title: How to stretch header across the screen

Body:
You can do this using pure css.

img.banner {position:absolute; z-index:1; width:100%; height:100%;}

Here is a demo by stu nicholls.


问:
Error: Failed to lookup view "index"
I tried following various other threads but none of them helped.
I am trying to render ejs files, using express app. But on listening on the port it show the following error.

Error

```<code>Error: Failed to lookup view "login"
at Function.app.render (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\application.js:495:17)
at ServerResponse.res.render (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\response.js:756:7)
at C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\server.js:150:13
at callbacks (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.handle (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\connect-flash\lib\flash.js:21:5)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at SessionStrategy.strategy.pass (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:338:9)
at SessionStrategy.authenticate (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\strategies\session.js:75:10)
at attempt (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:361:16)
at Object.authenticate [as handle] (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:362:7)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)
</code>```

My File Structure

```<code>- Workspace
   - client
      - css
      - js
   - views
      - login.ejs
      - index.ejs
  - server.js
</code>```

Small snippet of Code:

```<code>var express = require('express');
var app = express();
var server = http.createServer(app);
app.set('views', path.resolve(__dirname, '/views'));
app.set('view engine', 'ejs'); // set up ejs for templating
app.listen(8080);

    app.get('/', function(req, res) {
        res.render('login.ejs'); // load the login.ejs file
    });

    app.get('/index', function(req, res) {
      res.render('index.ejs')
    });
</code>```

答:
You can use this one.</p>

```<code>var express = require('express')
var http = require('http')
var app = express()
var server = http.createServer(app)
app.set('view engine', 'ejs')
app.listen(8080)

app.get('/', (req, res) => {
   res.render('login')
})
</code>```

Title: Error: Failed to lookup view "index"

Body:
I tried following various other threads but none of them helped.
I am trying to render ejs files, using express app. But on listening on the port it show the following error.

Error

Error: Failed to lookup view "login"
at Function.app.render (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\application.js:495:17)
at ServerResponse.res.render (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\response.js:756:7)
at C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\server.js:150:13
at callbacks (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at Object.handle (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\connect-flash\lib\flash.js:21:5)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)
at SessionStrategy.strategy.pass (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:338:9)
at SessionStrategy.authenticate (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\strategies\session.js:75:10)
at attempt (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:361:16)
at Object.authenticate [as handle] (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\passport\lib\middleware\authenticate.js:362:7)
at next (C:\Users\darsh\Desktop\Semester_1\SSDI\Sprint 3\workspace\node_modules\express\node_modules\connect\lib\proto.js:190:15)

My File Structure

- Workspace
   - client
      - css
      - js
   - views
      - login.ejs
      - index.ejs
  - server.js

Small snippet of Code:

var express = require('express');
var app = express();
var server = http.createServer(app);
app.set('views', path.resolve(__dirname, '/views'));
app.set('view engine', 'ejs'); // set up ejs for templating
app.listen(8080);

    app.get('/', function(req, res) {
        res.render('login.ejs'); // load the login.ejs file
    });

    app.get('/index', function(req, res) {
      res.render('index.ejs')
    });

Body:
You can use this one.

var express = require('express')
var http = require('http')
var app = express()
var server = http.createServer(app)
app.set('view engine', 'ejs')
app.listen(8080)

app.get('/', (req, res) => {
   res.render('login')
})


问:
How to prevent a database search from running on an empty string?
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?</p>

```<code>    <form action="search.php" method="POST">
        <input type="text" name="search" placeholder="search site">
        <button type="submit" name="submit-search"><img src="../assets/search icon-05.png"></button>
    </form>

    <?php
        if (isset($_POST['submit-search'])){
            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
            $result = mysqli_query($conn, $sql);
            $queryResult = mysqli_num_rows($result);

            if ($queryResult > 0){
                echo $queryResult . " results found";

                while ($row = mysqli_fetch_assoc($result)){
                    echo "<div class='articleItem'>
                        <h2>".$row['title']."</h2>
                        <p>".$row['abstract']."</p>
                        <a href=".$row['link']." target='_blank'>".$row['link']."</a>
                    </div>";
                }
            }
            else {
                echo "There are no results matching your search.";
            }
        }
    ?>
</code>```

答:
Check if isset, then trim, then confirm it still has at least one character.

```<code>if ( isset( $_POST['submit-search'] ) ) {
    $search = trim( (string) $_POST['submit-search'] );

    if ( isset( $search[0] ) ) { // Has at least one character?
        // Run query.
    }
}
</code>```

If you have PHP 7+, here's a more terse syntax.

```<code>$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );

if ( isset( $search[0] ) ) { // Has at least one character?
    // Run query.
}
</code>```

Body:
With my current code when I enter an empty string or a string of one space in the search input field I get every item in the database as a result. How can i make it so that the search doesn't run when an empty string is entered?

    <form action="search.php" method="POST">
        <input type="text" name="search" placeholder="search site">
        <button type="submit" name="submit-search"></button>
    </form>

    <?php
        if (isset($_POST['submit-search'])){
            $search = mysqli_real_escape_string($conn, $_POST['search']);
            $sql = "SELECT * FROM articles WHERE title LIKE '%$search%' OR abstract LIKE '%$search%' OR keywords LIKE '%$search%'";
            $result = mysqli_query($conn, $sql);
            $queryResult = mysqli_num_rows($result);

            if ($queryResult > 0){
                echo $queryResult . " results found";

                while ($row = mysqli_fetch_assoc($result)){
                    echo "

".$row['title']."

".$row['abstract']."

                        ".$row['link']."

";
                }
            }
            else {
                echo "There are no results matching your search.";
            }
        }
    ?>

Body:
Check if isset, then trim, then confirm it still has at least one character.

if ( isset( $_POST['submit-search'] ) ) {
    $search = trim( (string) $_POST['submit-search'] );

    if ( isset( $search[0] ) ) { // Has at least one character?
        // Run query.
    }
}

If you have PHP 7+, here's a more terse syntax.

$search = trim( (string) ( $_POST['submit-search'] ?? '' ) );

if ( isset( $search[0] ) ) { // Has at least one character?
    // Run query.
}


问:
How to unpivot columns and GROUP BY based on values in SQL Server?
I want to calculate distinct PID and VID counts per year.

Condition:

```<code>1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)
</code>```

In the output I want a separate new column Alpha with the following values:

```<code>A_to_D, E, F and ALL_Null
</code>```

Current output of table:

```<code>PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL
</code>```

Here:

```<code>select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)
</code>```

Expected output:

```<code>Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL
</code>```

答:
I chose to use a common table expression (cte) to hold the basic counts which are formed using case expressions for each of 8 different conditions (4 for PIDs and 4 for VIDs). The cte is then used as a source of the year dimension needed for the final result which gets cross joined to the list of 4 alpha labels. Then the cte is used again (twice) - unpivoted - to enable left joining the counts into the requested final row structure. Nulls in that results are deliberate, but could be replaced with empty string if required by using coalesce() or isnull() in the final select clause. Note I prefer to "unpivot" using cross apply and values as it allows an almost WYSIWYG layout of the rows that get produced as it at least a equally efficient as the unpivot command (ref below).

Demo at: SQL Fiddle

```<code>CREATE TABLE Table1
    ([PID] int, [VID] varchar(3), [Flag] varchar(4), [Date] datetime, [A] varchar(4), [B] varchar(4), [C] varchar(4), [D] varchar(4), [E] varchar(4), [F] varchar(4))
;

INSERT INTO Table1
    ([PID], [VID], [Flag], [Date], [A], [B], [C], [D], [E], [F])
VALUES
    (1, 'A1', '0', '2013-10-17 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (2, 'A2', '1', '2014-05-27 00:00:00', '1', NULL, NULL, '1', NULL, NULL),
    (3, 'A3', NULL, '2015-02-23 00:00:00', NULL, NULL, NULL, NULL, '1', NULL),
    (4, 'A4', NULL, '2013-12-06 00:00:00', NULL, '0', NULL, NULL, NULL, NULL),
    (5, 'A5', NULL, '2016-07-14 00:00:00', NULL, NULL, NULL, NULL, NULL, '1'),
    (6, 'A6', NULL, '2015-04-29 00:00:00', NULL, '1', '1', NULL, NULL, NULL),
    (7, 'A7', '1', '2016-09-30 00:00:00', '1', NULL, NULL, NULL, NULL, NULL),
    (8, 'A8', NULL, '2016-06-28 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (9, 'A9', '1', '2013-11-20 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (10, 'A10', '2', '2015-10-08 00:00:00', NULL, '1', NULL, NULL, NULL, NULL)
;
</code>```

Proposed Query:

```<code>/* common table expression used so the results may be reused */
with cte as (
      select
            year([date]) [Year]
          , count(distinct pA_to_D) pA_to_D
          , count(distinct pE) pE
          , count(distinct pF) pF
          , count(distinct pALL_NULL) pALL_NULL
          , count(distinct vA_to_D) vA_to_D
          , count(distinct vE) vE
          , count(distinct vF) vF
          , count(distinct vALL_NULL) vALL_NULL
      from (
            select
                  pid, vid, flag, [date]
                , case when a = 1 or b = 1 or c = 1 or d = 1 then pid end pA_to_D
                , case when E = 1 then pid end pE
                , case when F = 1 then pid end pF
                , case when coalesce(a,b,c,d,e,f) IS NULL then pid end pALL_NULL
                , case when flag is not null and a = 1 or b = 1 or c = 1 or d = 1 then vid end vA_to_D
                , case when flag is not null and E = 1 then vid end vE
                , case when flag is not null and F = 1 then vid end vF
                , case when flag is not null and coalesce(a,b,c,d,e,f) IS NULL then vid end vALL_NULL
            from Table1
            ) t
      group by
           year([date])
  )
select
       y.[Year], p.count_pid, v.count_vid, a.alpha
from (select distinct [Year] from cte) y
cross join (
        select 'A_to_D' as Alpha union all
        select 'E'               union all
        select 'F'               union all
        select 'ALL_NULL'
        ) a
left join (
      select cte.Year, ca.alpha, ca.count_pid
      from cte
      cross apply (
          values
                ('A_to_D'  ,pA_to_D)
              , ('E'       ,pE)
              , ('F'       ,pF)
              , ('ALL_NULL',pALL_NULL)
            ) ca (alpha, count_pid)
       where ca.count_pid > 0
       ) p on y.[Year] = p.[Year] and a.alpha = p.alpha
left join (
      select cte.Year, ca.alpha, ca.count_vid
      from cte
      cross apply (
          values
                ('A_to_D'  ,vA_to_D)
              , ('E'       ,vE)
              , ('F'       ,vF)
              , ('ALL_NULL',vALL_NULL)
            ) ca (alpha, count_vid)
       where ca.count_vid > 0
       ) v on y.[Year] = v.[Year] and a.alpha = v.alpha
;
</code>```

Results:

```<code>| Year | count_pid | count_vid |    alpha |
|------|-----------|-----------|----------|
| 2013 |    (null) |    (null) |   A_to_D |
| 2013 |    (null) |    (null) |        E |
| 2013 |    (null) |    (null) |        F |
| 2013 |         2 |         2 | ALL_NULL |
| 2014 |         1 |         1 |   A_to_D |
| 2014 |    (null) |    (null) |        E |
| 2014 |    (null) |    (null) |        F |
| 2014 |    (null) |    (null) | ALL_NULL |
| 2015 |         2 |         2 |   A_to_D |
| 2015 |         1 |    (null) |        E |
| 2015 |    (null) |    (null) |        F |
| 2015 |    (null) |    (null) | ALL_NULL |
| 2016 |         1 |         1 |   A_to_D |
| 2016 |    (null) |    (null) |        E |
| 2016 |         1 |    (null) |        F |
| 2016 |         1 |    (null) | ALL_NULL |
</code>```

For details on using CROSS APPLY and VALUES to UNPIVOT, see Spotlight on UNPIVOT, Part 1 by Brad Schultz

Innermost Query:

It can be useful to see the initial results to help trace following actions. This is he innermost subquery within the cte as a separate query with the results below:

```<code>/* initial results, prior to unpivot */
           select
                  pid, vid, flag, [date]
                , case when a = 1 or b = 1 or c = 1 or d = 1 then pid end pA_to_D
                , case when E = 1 then pid end pE
                , case when F = 1 then pid end pF
                , case when coalesce(a,b,c,d,e,f) IS NULL then pid end pALL_NULL
                , case when flag is not null and a = 1 or b = 1 or c = 1 or d = 1 then vid end vA_to_D
                , case when flag is not null and E = 1 then vid end vE
                , case when flag is not null and F = 1 then vid end vF
                , case when flag is not null and coalesce(a,b,c,d,e,f) IS NULL then vid end vALL_NULL
            from Table1
            order by [date]
;
</code>```

Results:

```<code>| pid | vid |   flag |                 date | pA_to_D |     pE |     pF | pALL_NULL | vA_to_D |     vE |     vF | vALL_NULL |
|-----|-----|--------|----------------------|---------|--------|--------|-----------|---------|--------|--------|-----------|
|   1 |  A1 |      0 | 2013-10-17T00:00:00Z |  (null) | (null) | (null) |         1 |  (null) | (null) | (null) |        A1 |
|   9 |  A9 |      1 | 2013-11-20T00:00:00Z |  (null) | (null) | (null) |         9 |  (null) | (null) | (null) |        A9 |
|   4 |  A4 | (null) | 2013-12-06T00:00:00Z |  (null) | (null) | (null) |    (null) |  (null) | (null) | (null) |    (null) |
|   2 |  A2 |      1 | 2014-05-27T00:00:00Z |       2 | (null) | (null) |    (null) |      A2 | (null) | (null) |    (null) |
|   3 |  A3 | (null) | 2015-02-23T00:00:00Z |  (null) |      3 | (null) |    (null) |  (null) | (null) | (null) |    (null) |
|   6 |  A6 | (null) | 2015-04-29T00:00:00Z |       6 | (null) | (null) |    (null) |      A6 | (null) | (null) |    (null) |
|  10 | A10 |      2 | 2015-10-08T00:00:00Z |      10 | (null) | (null) |    (null) |     A10 | (null) | (null) |    (null) |
|   8 |  A8 | (null) | 2016-06-28T00:00:00Z |  (null) | (null) | (null) |         8 |  (null) | (null) | (null) |    (null) |
|   5 |  A5 | (null) | 2016-07-14T00:00:00Z |  (null) | (null) |      5 |    (null) |  (null) | (null) | (null) |    (null) |
|   7 |  A7 |      1 | 2016-09-30T00:00:00Z |       7 | (null) | (null) |    (null) |      A7 | (null) | (null) |    (null) |
</code>```

Body:
I want to calculate distinct PID and VID counts per year.

Condition:

1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)

In the output I want a separate new column Alpha with the following values:

A_to_D, E, F and ALL_Null

Current output of table:

PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL

Here:

select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)

Expected output:

Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL

Body:
I chose to use a common table expression (cte) to hold the basic counts which are formed using case expressions for each of 8 different conditions (4 for PIDs and 4 for VIDs). The cte is then used as a source of the year dimension needed for the final result which gets cross joined to the list of 4 alpha labels. Then the cte is used again (twice) - unpivoted - to enable left joining the counts into the requested final row structure. Nulls in that results are deliberate, but could be replaced with empty string if required by using coalesce() or isnull() in the final select clause. Note I prefer to "unpivot" using cross apply and values as it allows an almost WYSIWYG layout of the rows that get produced as it at least a equally efficient as the unpivot command (ref below).

Demo at: SQL Fiddle

CREATE TABLE Table1
    ([PID] int, [VID] varchar(3), [Flag] varchar(4), [Date] datetime, [A] varchar(4), [B] varchar(4), [C] varchar(4), [D] varchar(4), [E] varchar(4), [F] varchar(4))
;

INSERT INTO Table1
    ([PID], [VID], [Flag], [Date], [A], [B], [C], [D], [E], [F])
VALUES
    (1, 'A1', '0', '2013-10-17 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (2, 'A2', '1', '2014-05-27 00:00:00', '1', NULL, NULL, '1', NULL, NULL),
    (3, 'A3', NULL, '2015-02-23 00:00:00', NULL, NULL, NULL, NULL, '1', NULL),
    (4, 'A4', NULL, '2013-12-06 00:00:00', NULL, '0', NULL, NULL, NULL, NULL),
    (5, 'A5', NULL, '2016-07-14 00:00:00', NULL, NULL, NULL, NULL, NULL, '1'),
    (6, 'A6', NULL, '2015-04-29 00:00:00', NULL, '1', '1', NULL, NULL, NULL),
    (7, 'A7', '1', '2016-09-30 00:00:00', '1', NULL, NULL, NULL, NULL, NULL),
    (8, 'A8', NULL, '2016-06-28 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (9, 'A9', '1', '2013-11-20 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL),
    (10, 'A10', '2', '2015-10-08 00:00:00', NULL, '1', NULL, NULL, NULL, NULL)
;

Proposed Query:

/* common table expression used so the results may be reused */
with cte as (
      select
            year([date]) [Year]
          , count(distinct pA_to_D) pA_to_D
          , count(distinct pE) pE
          , count(distinct pF) pF
          , count(distinct pALL_NULL) pALL_NULL
          , count(distinct vA_to_D) vA_to_D
          , count(distinct vE) vE
          , count(distinct vF) vF
          , count(distinct vALL_NULL) vALL_NULL
      from (
            select
                  pid, vid, flag, [date]
                , case when a = 1 or b = 1 or c = 1 or d = 1 then pid end pA_to_D
                , case when E = 1 then pid end pE
                , case when F = 1 then pid end pF
                , case when coalesce(a,b,c,d,e,f) IS NULL then pid end pALL_NULL
                , case when flag is not null and a = 1 or b = 1 or c = 1 or d = 1 then vid end vA_to_D
                , case when flag is not null and E = 1 then vid end vE
                , case when flag is not null and F = 1 then vid end vF
                , case when flag is not null and coalesce(a,b,c,d,e,f) IS NULL then vid end vALL_NULL
            from Table1
            ) t
      group by
           year([date])
  )
select
       y.[Year], p.count_pid, v.count_vid, a.alpha
from (select distinct [Year] from cte) y
cross join (
        select 'A_to_D' as Alpha union all
        select 'E'               union all
        select 'F'               union all
        select 'ALL_NULL'
        ) a
left join (
      select cte.Year, ca.alpha, ca.count_pid
      from cte
      cross apply (
          values
                ('A_to_D'  ,pA_to_D)
              , ('E'       ,pE)
              , ('F'       ,pF)
              , ('ALL_NULL',pALL_NULL)
            ) ca (alpha, count_pid)
       where ca.count_pid > 0
       ) p on y.[Year] = p.[Year] and a.alpha = p.alpha
left join (
      select cte.Year, ca.alpha, ca.count_vid
      from cte
      cross apply (
          values
                ('A_to_D'  ,vA_to_D)
              , ('E'       ,vE)
              , ('F'       ,vF)
              , ('ALL_NULL',vALL_NULL)
            ) ca (alpha, count_vid)
       where ca.count_vid > 0
       ) v on y.[Year] = v.[Year] and a.alpha = v.alpha
;

Results:

| Year | count_pid | count_vid |    alpha |
|------|-----------|-----------|----------|
| 2013 |    (null) |    (null) |   A_to_D |
| 2013 |    (null) |    (null) |        E |
| 2013 |    (null) |    (null) |        F |
| 2013 |         2 |         2 | ALL_NULL |
| 2014 |         1 |         1 |   A_to_D |
| 2014 |    (null) |    (null) |        E |
| 2014 |    (null) |    (null) |        F |
| 2014 |    (null) |    (null) | ALL_NULL |
| 2015 |         2 |         2 |   A_to_D |
| 2015 |         1 |    (null) |        E |
| 2015 |    (null) |    (null) |        F |
| 2015 |    (null) |    (null) | ALL_NULL |
| 2016 |         1 |         1 |   A_to_D |
| 2016 |    (null) |    (null) |        E |
| 2016 |         1 |    (null) |        F |
| 2016 |         1 |    (null) | ALL_NULL |

For details on using CROSS APPLY and VALUES to UNPIVOT, see Spotlight on UNPIVOT, Part 1 by Brad Schultz

Innermost Query:

It can be useful to see the initial results to help trace following actions. This is he innermost subquery within the cte as a separate query with the results below:

/* initial results, prior to unpivot */
           select
                  pid, vid, flag, [date]
                , case when a = 1 or b = 1 or c = 1 or d = 1 then pid end pA_to_D
                , case when E = 1 then pid end pE
                , case when F = 1 then pid end pF
                , case when coalesce(a,b,c,d,e,f) IS NULL then pid end pALL_NULL
                , case when flag is not null and a = 1 or b = 1 or c = 1 or d = 1 then vid end vA_to_D
                , case when flag is not null and E = 1 then vid end vE
                , case when flag is not null and F = 1 then vid end vF
                , case when flag is not null and coalesce(a,b,c,d,e,f) IS NULL then vid end vALL_NULL
            from Table1
            order by [date]
;

Results:

| pid | vid |   flag |                 date | pA_to_D |     pE |     pF | pALL_NULL | vA_to_D |     vE |     vF | vALL_NULL |
|-----|-----|--------|----------------------|---------|--------|--------|-----------|---------|--------|--------|-----------|
|   1 |  A1 |      0 | 2013-10-17T00:00:00Z |  (null) | (null) | (null) |         1 |  (null) | (null) | (null) |        A1 |
|   9 |  A9 |      1 | 2013-11-20T00:00:00Z |  (null) | (null) | (null) |         9 |  (null) | (null) | (null) |        A9 |
|   4 |  A4 | (null) | 2013-12-06T00:00:00Z |  (null) | (null) | (null) |    (null) |  (null) | (null) | (null) |    (null) |
|   2 |  A2 |      1 | 2014-05-27T00:00:00Z |       2 | (null) | (null) |    (null) |      A2 | (null) | (null) |    (null) |
|   3 |  A3 | (null) | 2015-02-23T00:00:00Z |  (null) |      3 | (null) |    (null) |  (null) | (null) | (null) |    (null) |
|   6 |  A6 | (null) | 2015-04-29T00:00:00Z |       6 | (null) | (null) |    (null) |      A6 | (null) | (null) |    (null) |
|  10 | A10 |      2 | 2015-10-08T00:00:00Z |      10 | (null) | (null) |    (null) |     A10 | (null) | (null) |    (null) |
|   8 |  A8 | (null) | 2016-06-28T00:00:00Z |  (null) | (null) | (null) |         8 |  (null) | (null) | (null) |    (null) |
|   5 |  A5 | (null) | 2016-07-14T00:00:00Z |  (null) | (null) |      5 |    (null) |  (null) | (null) | (null) |    (null) |
|   7 |  A7 |      1 | 2016-09-30T00:00:00Z |       7 | (null) | (null) |    (null) |      A7 | (null) | (null) |    (null) |


问:
Accessing the scope inside the $timeout in angularjs
I have a directive  in AngularJS, with $timeout in link function.

.directive('setValueInColorSelectionBlock', function($timeout) {
    return {
        restrict:'A',
        scope:{
            setValueInColorSelectionBlock:"=setValueInColorSelectionBlock"
        },
        link:function(scope, element, attrs) {
           //able to access the scope
             $timeout(function() {
               //not able to access the scope
            });
        }
    };
});```
</div>
</div>
</p>

<p>My html :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid" set-value-in-color-selection-block="$tbCtrl.containers"></code>```

this in $time out access the window object. I am not able to access scope inside the $timeout.

How do we access the scope?

答:
According to the current scope configuration of your directive, you are telling angular to bind your scope to a variable in the parent scope. The name of the variable is set to be decided by the value of the element attribute setValueInColorSelectionBlock.

And your scope will have a single property - that is setValueInColorSelectionBlock.

Make sure all the variable and attribute requirements to satisfy these conditions are met.

If everything is set, the scope is available inside the timeout function through link functions scope argument.

```<code>link:function(scope, element, attrs) {

             $timeout(function() {
               console.log(scope);
            });

        }
</code>```

Edit

When the scope is referenced inside the timeout function, a closure is created. This closure makes sure that the local variables are still accessible even after the caller function is left.

Now, based on the comment, your problem seems to be that, even though the scope object is ensured by the closure, the properties of it may be deleted by the time the timeout function is executed.

You can probably take the copy of the scope object and save it to the local function scope for later access.

```<code>link:function(scope, element, attrs) {

             var savedScope = angular.copy(scope);

             $timeout(function() {
               console.log(savedScope);
            });

        }
</code>```

Body:
I have a directive  in AngularJS, with $timeout in link function.

.directive('setValueInColorSelectionBlock', function($timeout) {
    return {
        restrict:'A',
        scope:{
            setValueInColorSelectionBlock:"=setValueInColorSelectionBlock"
        },
        link:function(scope, element, attrs) {
           //able to access the scope
             $timeout(function() {
               //not able to access the scope
            });
        }
    };
});

My html :

this in $time out access the window object. I am not able to access scope inside the $timeout.

How do we access the scope?

Body:
According to the current scope configuration of your directive, you are telling angular to bind your scope to a variable in the parent scope. The name of the variable is set to be decided by the value of the element attribute setValueInColorSelectionBlock.

And your scope will have a single property - that is setValueInColorSelectionBlock.

Make sure all the variable and attribute requirements to satisfy these conditions are met.

If everything is set, the scope is available inside the timeout function through link functions scope argument.

link:function(scope, element, attrs) {

             $timeout(function() {
               console.log(scope);
            });

        }

Edit

When the scope is referenced inside the timeout function, a closure is created. This closure makes sure that the local variables are still accessible even after the caller function is left.

Now, based on the comment, your problem seems to be that, even though the scope object is ensured by the closure, the properties of it may be deleted by the time the timeout function is executed.

You can probably take the copy of the scope object and save it to the local function scope for later access.

link:function(scope, element, attrs) {

             var savedScope = angular.copy(scope);

             $timeout(function() {
               console.log(savedScope);
            });

        }


问:
Python :My generator is returning the passed list instead of a filtered output
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

```<code>def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()
</code>```

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.

答:
You were incrementing count while you should have been incrementing counter

```<code>def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        counter+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()
</code>```

Body:
The code filters the list in such a way that it only returns me the first three values of the list. I tried another generator as well to print only the even numbers but i'm getting the same problem i.e. the whole list is being printed.

def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        count+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()

This should print 2,6,5 but rather prints the  full list. Why???

EDIT : Sorry, i made a very silly error. The counter variable was to be incremented.

Body:
You were incrementing count while you should have been incrementing counter

def take(count, iterable):

    counter = 0
    for item in iterable:
        if counter==count:
            return
        counter+=1
        yield item

def run_take():
    items = [2,6,5,23,1,4,6,7]

    for item in take(3,items):
        print(item)

if __name__ == '__main__':
    run_take()