问:
SSL Authentication/Authorization is part of handshake or not?
As per my understanding,
In case of Client Authentication,
Server request the certificate from the client and then after the certificate verification handshake happens.

I just want to know, what does Server do in the certificate verification:
1) It only verifies that the certificate is valid i.e. the user is the true owner of the certificate.
2) It verifies user is the true owner of the certificate and also check the authentication and authorization.

So 1 or 2 ?

In the simple ways my question is : SSLAuthentication is part of handshake or is something which comes into picture after handshake ?

答:
It is up to the peers if the full validation of the certificates is done before the handshake on the wire is finished or not. Usually server certificate validation is done before the handshake if finished and client certificate validation is done at least partially.

But especially in the case of client certificates it might be that the web application running at the server has additional requirements, for example that the certificate is not only signed by a specific CA but that the subject matches an existing use found in the database and maybe that the fingerprint of the certificate is as stored in the database. In this case the verification is usually only completed after the TLS handshake is finished since only then the web application specific logic is executed.

... what does Server do in the certificate verification: 1) It only verifies that the certificate is valid i.e. the user is the true owner of the certificate. 2) It verifies user is the true owner of the certificate and also check the authentication and authorization.

It is checked inside the TLS handshake that the client owns the private key to the public key in the certificate. It is commonly also checked that the certificate is signed by a trusted CA, although there might be scenarios where this check is not done and instead it is checked after the handshake that the certificate has the expected fingerprint. Authorization is usually not checked inside the TLS handshake since the TLS stack has usually no idea yet what kind of resource gets accessed and if the specific user authenticated by the certificate is authorized to access this resource.


来源: stackexchange

问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答:
Simplified and VB.Net, but i think you will get it:

```<code>Dim values As New List(Of String)(New String() {"1:Jeff", "2:Tom", "3:Michael"})
Dim result As String = "({" & String.Join(",", values.ToArray) & "})"
</code>```

If k is a Collection like Array,List etc.

ContentLicense: CC BY-SA 3.0

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

Body:
Simplified and VB.Net, but i think you will get it:

Dim values As New List(Of String)(New String() {"1:Jeff", "2:Tom", "3:Michael"})
Dim result As String = "({" & String.Join(",", values.ToArray) & "})"

If k is a Collection like Array,List etc.

ContentLicense: CC BY-SA 2.5


问:
Making form elements on the same line
I am currently make an app and I am trying to make 3 form element align (25/25/50) whoever, it seems like it has not been going smoothly. I will attach a picture at the end to show how it is looking right now. Also, if possible, is there anyway I can make the 3 form element have a space between them so that it is easier to be read and interpreted?

```<code>Between
<div class="ui-grid-e">
  <div class=ui-block-a><input type="text" name="between1" id="between1" required /></div>
  <div class=ui-block-b><input type="text" name="between2" id="between2" required /></div>
  Comment
  <div class=ui-block-c><input type="text" name="betweencomment" id="betweencomment" required /></div>
</div>
</code>```

https://imgur.com/a/vlpbi/

答:
I suggest to use for html as followed:

```<code><form class="ui-grid-e">
       <input type="text" name="between1" id="between1"  />
       <input type="text" name="between2" id="between2"  />
       <input type="text" name="betweencomment" id="betweencomment"/>
</form>
</code>```

and in your css :

```<code>.ui-grid-e{

display: inline;

float: left;

}
</code>```

Title: Making form elements on the same line

Body:
I am currently make an app and I am trying to make 3 form element align (25/25/50) whoever, it seems like it has not been going smoothly. I will attach a picture at the end to show how it is looking right now. Also, if possible, is there anyway I can make the 3 form element have a space between them so that it is easier to be read and interpreted?

Between

<input type="text" name="between1" id="between1" required />

<input type="text" name="between2" id="between2" required />

  Comment

<input type="text" name="betweencomment" id="betweencomment" required />

https://imgur.com/a/vlpbi/

Body:
I suggest to use for html as followed:

<form class="ui-grid-e">
       <input type="text" name="between1" id="between1"  />
       <input type="text" name="between2" id="between2"  />
       <input type="text" name="betweencomment" id="betweencomment"/>
</form>

and in your css :

.ui-grid-e{

display: inline;

float: left;

}


问:
Can you use a service worker with a self-signed certificate?
I have developer server that are used for testing. They have SSL self-signed certificates, which allow us to test the web application over HTTPS, but with prominent warnings that the certificates are not verifiable.

That's fine, but I have a Service Worker that throws an error with the navigator.serviceWorker.register

SecurityError: Failed to register a ServiceWorker: An SSL certificate error occurred when fetching the script.

How do I use a Service Worker with an intranet testing server which has a self-signed certificate?

答:
For local development we use self signed certs.  To overcome the problems relating to local dev on OSX.  We did the following:

Create your certificate and serve it up

Navigate to the https url

Open dev tools > security > view certificate

drag the certificate icon to the desktop and doubleclick on it, this will open up keychain access.

drag the certificate icon to login, open up log-in and double click on the certificate (it should be named with the dev domain or similar)
open up the trust dropdown and select always trust.  Go back to your app close the window and re-open with https, you should now have 'faux' https for your dev domain.


问:
recyclerView.setOnScrollChangeListener not working
this is my fragment code.
i m usimg this code for endless recycler view which is get the data from server when scroll the recycler view item. but the code is not working. in this code recyclerView.setOnScrollChangeListener() not working it shows error view cannot be applied to android.content .context.
how to use the setOnScrollChangeListener in fragment to load the data from server  when scroll the list.

```<code>    public class Fragment1 extends Fragment implements
    RecyclerView.OnScrollChangeListener{
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() {}

       @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        }

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
        container, Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container,
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar

    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}
</code>```

}

答:
Use recyclerView.addOnScrollListener(onScrollListener); instead.

```<code>RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
      super.onScrollStateChanged(recyclerView, newState);
 }

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);
 }
</code>```

Body:
this is my fragment code.
i m usimg this code for endless recycler view which is get the data from server when scroll the recycler view item. but the code is not working. in this code recyclerView.setOnScrollChangeListener() not working it shows error view cannot be applied to android.content .context.
how to use the setOnScrollChangeListener in fragment to load the data from server  when scroll the list.

    public class Fragment1 extends Fragment implements
    RecyclerView.OnScrollChangeListener{
    //Creating a List of superheroes
     private List<SuperHero> listSuperHeroes;

     //Creating Views
     private RecyclerView recyclerView;
     private RecyclerView.LayoutManager layoutManager;
     private RecyclerView.Adapter adapter;
     public ProgressBar progressBar;

     //Volley Request Queue
      private RequestQueue requestQueue;

       //The request counter to send ?page=1, ?page=2  requests
       private int requestCount = 1;

       public Fragment1() {}

       @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        }

      @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup
        container, Bundle savedInstanceState) {
         // Inflate the layout for this fragment
         View view= inflater.inflate(R.layout.activity_main, container,
       false);
       //Initializing Views
       recyclerView.setLayoutManager(layoutManager);

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(getContext());

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(getActivity());

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, getActivity());

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
 progressBar = (ProgressBar) view.findViewById(R.id.progressBar1);
    return view;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar

    //Displaying Progressbar
   // progressBar.setVisibility(View.VISIBLE);
    //setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Config.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response

                    Log.e("response",response.toString());
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(getActivity(), "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        //int a= array.length();
        //String s=String.valueOf(a);
        //Log.e("array",s);
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(Config.TAG_IMAGE_URL));
            //superHero.setName(json.getString(Config.TAG_NAME));
            //superHero.setPublisher(json.getString(Config.TAG_PUBLISHER));
            superHero.setMglId(json.getString(Config.TAG_MGLID));
            superHero.setAgeHeight(json.getString(Config.TAG_AGEHEIGHT));
            superHero.setCommunity(json.getString(Config.TAG_COMMUNITY));
            superHero.setOccupation(json.getString(Config.TAG_OCCUPATION));
            superHero.setIncome(json.getString(Config.TAG_INCOME));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}

}

Body:
Use recyclerView.addOnScrollListener(onScrollListener); instead.

RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
      super.onScrollStateChanged(recyclerView, newState);
 }

 @Override
 public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);
 }


问:
Convert CSV to HTML Table (Searchable & filterable)?
Is there is any alternative program/Project for converting CSV to Dynamic HTML Table along with search & filtration,which would be use for reporting on Client side.

Currently, I'm using CSV To HTML for this purpose.

答:
There's a Python tool called csvtotable which uses DataTables for the client-side. From their documentation:

Convert data.csv file to data.html file

csvtotable data.csv data.html


问:
Bot Framework without Azure possible?
If i'm building a bot with the Microsoft Bot Framework, do i need to deploy my bot to Azure in order to register my bot HERE in order to configure the channels for the bot?
Or can i simply deploy my bot to a normal (for example) IIS Server?

I couldnt find any information on this toppic and i dont want to use Azure.

答: Yes your bot is like an API that is consumed by a chat frontend like Facebook Messenger, Skype etc. Check out this medium blog explaining how to host on Heroku https://medium.com/@chinnatiptaemkaeo/create-fb-bot-with-heroku-nodejs-microsoft-bot-framework-687bd2893238 </p>

Title: Bot Framework without Azure possible?


问:
How to delete R.java identifier?

I can't delete that id. What should I do?

答:
R file is (or should be) re-generated automatically on every build. You should try some dependency-injection framework (Roboguice works well for Android programming) to clean up issues with handling Views

Can/should I edit the R.java file. If so, how?

Title: How to delete R.java identifier?


问:
Java Beginner: How do I link one linked list to another?
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

```<code> List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);
</code>```

OUTPUT:

```<code> [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]
</code>```

答:
The easiest way to achieve this is to have a proper class for your items and have instances of this class MyInt link to each other in stead of relying on LinkedList, i.e. add a MyInt next;  field to the custom class that holds your integers.
Then link them as described.
A change to one instance can then be done without even touching the list structure and is reflected accordingly when iterating over this list through the next references.

Body:
If I have: linkedlist1= 1,2,3,4; and   linkedlist2= 5,6,7;

Am I able to attach linkedlist2 to the end of linkedlist1 in such a way if I invoke: linkedlist2.set(0,9999)  it changes to linkedlist2 = [999,6,7] and  linkedlist1 becomes [1,2,3,4,9999,7,8]; ?

Is that possible ? Or I do need another structure ?

The following code didn't work:

 List<Double> l1 = new LinkedList<Double>(Arrays.asList(1.0,2.0));
 List<Double> l2 = new LinkedList<Double>(Arrays.asList(3.0,4.0));
 l1.addAll(l2);
 System.out.println(l1);
 l2.set(0, 9.0);
 System.out.println(l1);

OUTPUT:

 [1.0, 2.0, 3.0, 4.0]
 [1.0, 2.0, 3.0, 4.0]


问:
simplexml_load_string() StartTag: invalid element name
I use simplexml_load_string() to parse a XML API response.

```<code>$lien = "http://myresponseurl";
$page = simplexml_load_string($this->get_data($lien));
</code>```

Everythink is working good, except in this case:

```<code><libdivision><1500 Poule H</libdivision>
</code>```

Where the text to get back should be "<1500 Poule H" but, the "<" caractère is also in XML the symbol of an opening tag...

What should I do to get back "<1500 Poule H" without any errors ?

```<code>Warning: simplexml_load_string(): Entity: line 4: parser error : StartTag: invalid element name
Warning: simplexml_load_string(): <libdivision><1500 Poule G</libdivision>
Warning: simplexml_load_string(): ^
</code>```

Thanks for help

答:
```<code><libdivision><1500 Poule H</libdivision>
</code>```

This is invalid XML. The provider of the API should fix this, this is a clear bug in the API and a client is not responsible for working with malformed data. There are two options:

Wrap it in a CDATA field:

```<code><libdivision><![CDATA[<1500 Poule H]]></libdivision>
</code>```

Or encode the symbol:

```<code><libdivision><1500 Poule H</libdivision>
</code>```

Body:
I use simplexml_load_string() to parse a XML API response.

$lien = "http://myresponseurl";
$page = simplexml_load_string($this->get_data($lien));

Everythink is working good, except in this case:

<libdivision><1500 Poule H</libdivision>

Where the text to get back should be "<1500 Poule H" but, the "<" caractère is also in XML the symbol of an opening tag...

What should I do to get back "<1500 Poule H" without any errors ?

Warning: simplexml_load_string(): Entity: line 4: parser error : StartTag: invalid element name
Warning: simplexml_load_string(): <libdivision><1500 Poule G</libdivision>
Warning: simplexml_load_string(): ^

Thanks for help

Body:
<libdivision><1500 Poule H</libdivision>

This is invalid XML. The provider of the API should fix this, this is a clear bug in the API and a client is not responsible for working with malformed data. There are two options:

Wrap it in a CDATA field:

<libdivision><![CDATA[<1500 Poule H]]></libdivision>

Or encode the symbol:

<libdivision>&lt;1500 Poule H</libdivision>


问:
HIVE/Impala query: Count the number of rows between rows fulfilling certain conditions
I need to count the number of rows that fulfill certain conditions contained in intervals defined by other rows that fulfill other conditions. Examples: the number of rows N between 'Reference' having values 1 and 4 that fulfill the condition 'Other_condition' = b is N=1, the number of rows N between 'Reference' having values 2 and 5 that fulfill the condition 'Other_condition' = b is N=2 etc. </p>

```<code>  Date          Reference    Other_condition
20171111            1              a
20171112            2              a
20171113            3              b
20171114            4              b
20171115            5              b
</code>```

<p>I'm accessing the database through Hive/Impala SQL queries and unfortunately I have no idea where to start implementing such a window function. A half-pseudocode version of what I want would be something like: </p>

```<code>SELECT COUNT (DISTINCT database.Date) AS counter, Other_condition, reference
FROM database
WHERE database.Other_condition = a AND database.Reference BETWEEN
(window function condition 1: database.Reference = 2) AND
(window function condition 2: database.Reference = 5)
GROUP BY counter
</code>```

答:
Your question is rather hard to follow.  I get the first conditions, which is the number of rows between "1" and "4".

Here is one method that should be pretty easy to generalize:

```<code>select (max(case when reference = 4 then seqnum end) -
        max(case when reference = 1 then seqnum end)
       ) as num_rows_1_4
from (select t.*,
             row_number() over (order by date) as seqnum
      from t
     ) t;
</code>```

Body:
I need to count the number of rows that fulfill certain conditions contained in intervals defined by other rows that fulfill other conditions. Examples: the number of rows N between 'Reference' having values 1 and 4 that fulfill the condition 'Other_condition' = b is N=1, the number of rows N between 'Reference' having values 2 and 5 that fulfill the condition 'Other_condition' = b is N=2 etc.

  Date          Reference    Other_condition
20171111            1              a
20171112            2              a
20171113            3              b
20171114            4              b
20171115            5              b

I'm accessing the database through Hive/Impala SQL queries and unfortunately I have no idea where to start implementing such a window function. A half-pseudocode version of what I want would be something like:

SELECT COUNT (DISTINCT database.Date) AS counter, Other_condition, reference
FROM database
WHERE database.Other_condition = a AND database.Reference BETWEEN
(window function condition 1: database.Reference = 2) AND
(window function condition 2: database.Reference = 5)
GROUP BY counter

Body:
Your question is rather hard to follow.  I get the first conditions, which is the number of rows between "1" and "4".

Here is one method that should be pretty easy to generalize:

select (max(case when reference = 4 then seqnum end) -
        max(case when reference = 1 then seqnum end)
       ) as num_rows_1_4
from (select t.*,
             row_number() over (order by date) as seqnum
      from t
     ) t;


问:
GraphLab-Create Module not being installed on Python 3.5 (ubuntu)
I used this command:
pip install --upgrade --no-cache-dir https://get.graphlab.com/GraphLab-Create/2.1/email_address/token/GraphLab-Create-License.tar.gz

But got this error:
Could not find a version that satisfies the requirement graphlab-create>=2.1 (from GraphLab-Create-License==2.1) (from versions: )
No matching distribution found for graphlab-create>=2.1 (from GraphLab-Create-License==2.1)

I tried downloading the file and installing it manually but that also didn't solve the issue.

答:
As it was written in previous answers, you should use Python 2.7 instead of the 3.5 one.

Use pip2.7, because pip may be associated with the Python 3.5:

```<code>pip2.7 install --upgrade --no-cache-dir https://get.graphlab.com/GraphLab-Create/2.1/email_address/token/GraphLab-Create-License.tar.gz
</code>```

Body:
As it was written in previous answers, you should use Python 2.7 instead of the 3.5 one.

Use pip2.7, because pip may be associated with the Python 3.5:

pip2.7 install --upgrade --no-cache-dir https://get.graphlab.com/GraphLab-Create/2.1/email_address/token/GraphLab-Create-License.tar.gz


问:
looping the array of json object in reactjs
I am new in reactjs. I have problem while showing the result.Here is my code:

```<code>constructor (props) {
      super(props);
       this.state = {
         selectValue: '',
         yearsValue:'',
         months:''
       }
     this.setDataGroup = this.setDataGroup.bind(this);
   }

setDataGroup(e){
    var selectedType = e.target.value;
    if(selectedType == "quertly"){
       var quertlyData = [{
        data:"Jan-March",
        value:"1"
      },
      {
        data:"Apr-Jun",
        value:"2"
      },
      {
        data:"Jul-Sept",
        value:"3"
      },
      {
        data:"Oct-Dec",
        value:"4"
      }];
       this.setState({yearsValue:quertlyData});
</code>```

I am showing the data like:

```<code> render() {
 const data = JSON.stringify(this.state.yearsValue) || []
                  <div>
    {data.map((data, index) => {data})}
  </div>
}
</code>```

My json looks like:

[{"data":"Jan-March","value":"1"},{"data":"Apr-Jun","value":"2"},{"data":"Jul-Sept","value":"3"},{"data":"Oct-Dec","value":"4"}]

Getting error .map is not function

答:
Your data is in correct format. Initialize yearsValue as array in constructor like

```<code>this.state = {
  yearsValue: []
}
</code>```

And then you can use yearsValue state in render like below

```<code>render() {
  return (
     <div>
       {this.state.yearsValue.map((d, index) => {
          return (
             <div key={index}>{d.data}</div>
          )
       })}
     </div>
  )
}
</code>```

Body:
I am new in reactjs. I have problem while showing the result.Here is my code:

constructor (props) {
      super(props);
       this.state = {
         selectValue: '',
         yearsValue:'',
         months:''
       }
     this.setDataGroup = this.setDataGroup.bind(this);
   }

setDataGroup(e){
    var selectedType = e.target.value;
    if(selectedType == "quertly"){
       var quertlyData = [{
        data:"Jan-March",
        value:"1"
      },
      {
        data:"Apr-Jun",
        value:"2"
      },
      {
        data:"Jul-Sept",
        value:"3"
      },
      {
        data:"Oct-Dec",
        value:"4"
      }];
       this.setState({yearsValue:quertlyData});

I am showing the data like:

 render() {
 const data = JSON.stringify(this.state.yearsValue) || []

    {data.map((data, index) => {data})}

}

My json looks like:

[{"data":"Jan-March","value":"1"},{"data":"Apr-Jun","value":"2"},{"data":"Jul-Sept","value":"3"},{"data":"Oct-Dec","value":"4"}]

Getting error .map is not function

Body:
Your data is in correct format. Initialize yearsValue as array in constructor like

this.state = {
  yearsValue: []
}

And then you can use yearsValue state in render like below

render() {
  return (
     <div>
       {this.state.yearsValue.map((d, index) => {
          return (
             <div key={index}>{d.data}</div>
          )
       })}
     </div>
  )
}


问:
Pure CSS Collapse Accordion
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="wrapper">
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-five" type="radio" name="tabs2">
    <label for="tab-five">Label Two</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-six" type="radio" name="tabs2">
    <label for="tab-six">Label Three</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
</div></code>```

答: I think the radio type will cause the problem, because it has only 2 "data-way". </p>

Title: Pure CSS Collapse Accordion

Body:
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}

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

    <input id="tab-four" type="radio" name="tabs2">
    Label One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-five" type="radio" name="tabs2">
    Label Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-six" type="radio" name="tabs2">
    Label Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.


问:
Simplest way of mapping an index to a string in C++
Requirements:

Must be able to use C strings as well as C++ strings

Fast

No maps

No templates

No direct lookup, i.e. index might be out of bounds.

Index is not consecutive

Enums and strings contained in one header file

Only instantiate what you use.

This is what I have come up with so far:

```<code>- test.hh -

// Generic mapper
//
// The idea here is to create a map between an integer and a string.
// By including it inside a class we prevent every module which
// includes this include file from creating their own instance.
//
struct Mapper_s
{
   int Idx;
   const char *pStr;
};

// Status
enum State_t
{
   Running = 1,
   Jumping = 6,
   Singing = 12
};

struct State_s
{
   static const Mapper_s *GetpMap(void)
   {
       static Mapper_s Map[] =
       {
            { Running,   "Running" },
            { Jumping,   "Jumping" },
            { Singing,   "Singing" },
            { 0,   0}
        };
        return Map;
    };
};

- test.cc -
// This is a generic function
const char *MapEnum2Str(int Idx, const Mapper_s *pMap)
{
    int i;
    static const char UnknownStr[] = "Unknown";

    for (i = 0; pMap[i].pStr != 0; i++)
    {
        if (Idx == pMap[i].Idx)
        {
            return pMap[i].pStr;
        }
    }

    return UnknownStr;
}

int main()
{
   cout << "State: " << MapEnum2Str(State, State_s::GetpMap()) << endl;
   return 0;
}
</code>```

Any suggestions on how to improve this ?

I feel that the header file looks slightly cluttered...

答:
Here is what I settled on. Using this technique all you need to do is to include a header file. You will only instantiate what you use. You could also store a perfect hash table instead of just Idx & pStr. This approach does not work in C.

file: e2str.hh

```<code>struct Mapper_s
{
    int Idx;
    const char *pStr;
};

#define ENUM2STR_BEGIN(x) struct x { static const Mapper_s *GetpMap(void) {  static const Enum2StrMap_s Map[] =
#define ENUM2STR_END      return Map; }; }

const char *MapEnum2Str(int Idx, const Mapper_s *pMap);
</code>```

file: mapper.hh

```<code>#include "e2str.hh"

ENUM2STR_BEGIN(State_s)
{
        { Running,   "Running" },
        { Singing,   "Singing" },
        { Jumping,   "Jumping" },
        { 0, 0}
};
ENUM2STR_END;
</code>```

file: test.cc

```<code>#include "mapper.hh"
int main()
{
   cout << "State: " << MapEnum2Str(State, State_s::GetpMap()) << endl;
   return 0;
}
</code>```

OwnerDisplayName: tormod

Body:
Requirements:

Must be able to use C strings as well as C++ strings

Fast

No maps

No templates

No direct lookup, i.e. index might be out of bounds.

Index is not consecutive

Enums and strings contained in one header file

Only instantiate what you use.

This is what I have come up with so far:

- test.hh -

// Generic mapper
//
// The idea here is to create a map between an integer and a string.
// By including it inside a class we prevent every module which
// includes this include file from creating their own instance.
//
struct Mapper_s
{
   int Idx;
   const char *pStr;
};

// Status
enum State_t
{
   Running = 1,
   Jumping = 6,
   Singing = 12
};

struct State_s
{
   static const Mapper_s *GetpMap(void)
   {
       static Mapper_s Map[] =
       {
            { Running,   "Running" },
            { Jumping,   "Jumping" },
            { Singing,   "Singing" },
            { 0,   0}
        };
        return Map;
    };
};

- test.cc -
// This is a generic function
const char *MapEnum2Str(int Idx, const Mapper_s *pMap)
{
    int i;
    static const char UnknownStr[] = "Unknown";

    for (i = 0; pMap[i].pStr != 0; i++)
    {
        if (Idx == pMap[i].Idx)
        {
            return pMap[i].pStr;
        }
    }

    return UnknownStr;
}

int main()
{
   cout << "State: " << MapEnum2Str(State, State_s::GetpMap()) << endl;
   return 0;
}

Any suggestions on how to improve this ?

I feel that the header file looks slightly cluttered...

LastEditorDisplayName: tormod

Body:
Here is what I settled on. Using this technique all you need to do is to include a header file. You will only instantiate what you use. You could also store a perfect hash table instead of just Idx & pStr. This approach does not work in C.

file: e2str.hh

struct Mapper_s
{
    int Idx;
    const char *pStr;
};

#define ENUM2STR_BEGIN(x) struct x { static const Mapper_s *GetpMap(void) {  static const Enum2StrMap_s Map[] =
#define ENUM2STR_END      return Map; }; }

const char *MapEnum2Str(int Idx, const Mapper_s *pMap);

file: mapper.hh

#include "e2str.hh"

ENUM2STR_BEGIN(State_s)
{
        { Running,   "Running" },
        { Singing,   "Singing" },
        { Jumping,   "Jumping" },
        { 0, 0}
};
ENUM2STR_END;

file: test.cc

#include "mapper.hh"
int main()
{
   cout << "State: " << MapEnum2Str(State, State_s::GetpMap()) << endl;
   return 0;
}


答:
You can't but as an alternative you can have a list of list, but I don't know if that would work as you need:</p>

```<code>import java.util.*;
import static java.lang.System.out;
class ListOfLists {
  public static void main( String ... args ) {

    List<Integer> a = new LinkedList<Integer>(Arrays.asList(1,2,3,4));
    List<Integer> b = new LinkedList<Integer>(Arrays.asList(5,6,7));

    List<List> list = new LinkedList<List>();
    list.add( a );
    list.add( b );

    out.println("Before : " + list );
    b.set( 0, 999 );

    out.println("After  : " + list );

  }
}

Before : [[1, 2, 3, 4], [5, 6, 7]]
After  : [[1, 2, 3, 4], [999, 6, 7]]
</code>```

Title: Java Beginner: How do I link one linked list to another?

Body:
You can't but as an alternative you can have a list of list, but I don't know if that would work as you need:

import java.util.*;
import static java.lang.System.out;
class ListOfLists {
  public static void main( String ... args ) {

    List<Integer> a = new LinkedList<Integer>(Arrays.asList(1,2,3,4));
    List<Integer> b = new LinkedList<Integer>(Arrays.asList(5,6,7));

    List<List> list = new LinkedList<List>();
    list.add( a );
    list.add( b );

    out.println("Before : " + list );
    b.set( 0, 999 );

    out.println("After  : " + list );

  }
}

Before : [[1, 2, 3, 4], [5, 6, 7]]
After  : [[1, 2, 3, 4], [999, 6, 7]]


问:
Fetching details of a group user belongs to in firebase
Below is my database structure in firebase. I only have signed-in users Id.

User

```<code>-userId

    -Name
    -age
    -groups

        groupId1:true
        groupId2:true
</code>```

Group

```<code>-groupId

    -name
    -desc
    -UserId

        -UserId1:true
        -UserId2:true
</code>```

I want to list the details of all the groups that user belongs to.
My approach is,

Find all the groups my user belongs to by checking the index from User.

Using the list of groupid we got from step1, get details of group from Groups.

Is there any other better suggestions?

答:
Below method will retrieve the Group details which user belongs to.</p>

```<code>self.usersPerGroupRef = [_rootRef child:@"Group"];
  [_usersPerGroupRef observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    self.usersArray = [NSMutableArray new];
    for (snapshot in snapshot.children) {
      NSMutableDictionary *groupDict = [NSMutableDictionary new];
      groupDict = snapshot.value[@"UserId"];
      if ([groupDict objectForKey:@"userID"]) {
       NSLog(@"Group Name: %@",snapshot.value[@"name"]);
        [self.usersArray addObject:snapshot.key];
      }
    }
  }];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Below is my database structure in firebase. I only have signed-in users Id.

User

-userId

    -Name
    -age
    -groups

        groupId1:true
        groupId2:true

Group

-groupId

    -name
    -desc
    -UserId

        -UserId1:true
        -UserId2:true

I want to list the details of all the groups that user belongs to.
My approach is,

Find all the groups my user belongs to by checking the index from User.

Using the list of groupid we got from step1, get details of group from Groups.

Is there any other better suggestions?

Body:
Below method will retrieve the Group details which user belongs to.

self.usersPerGroupRef = [_rootRef child:@"Group"];
  [_usersPerGroupRef observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    self.usersArray = [NSMutableArray new];
    for (snapshot in snapshot.children) {
      NSMutableDictionary *groupDict = [NSMutableDictionary new];
      groupDict = snapshot.value[@"UserId"];
      if ([groupDict objectForKey:@"userID"]) {
       NSLog(@"Group Name: %@",snapshot.value[@"name"]);
        [self.usersArray addObject:snapshot.key];
      }
    }
  }];


问:
Expanding a constexpr array into a set of non-type template parameters
Suppose I have a compile-time constexpr array and a variadic class template with a set of non-type parameters of the same type as the elements of the array.

My objective is to instantiate the class template with the values from the array:

```<code>struct Container
{
    int containee[3];
};

constexpr Container makeContainer();

template <int... Elements> class Foo;

Foo<makeContainer().containee[0],
    makeContainer().containee[1],
    makeContainer().containee[2]> foo;
</code>```

The above code works well. However, I'm quite unhappy about having to manually index the array whenever I need to instantiate the Foo template. I would like the compiler to do that for me automatically:

```<code>Foo<Magic(makeContainer().containee)> foo;
</code>```

I did some RTFM at cppreference, but that didn't help. I'm aware of std::forward<>(), but it cannot be applied to template argument lists.

答:
Change makeContainer to a struct with a constexpr operator() or a constexpr lambda (C++17). A function pointer will not work here.

```<code>struct makeContainer
{
    constexpr auto operator()() const
    {
        return Container{/* ... */};
    }
};
</code>```

Use std::make_index_sequence and std::index_sequence to generate a compile-time sequence of the indices:

```<code>template <typename C>
constexpr auto fooFromContainer(const C& container)
{
    return fooFromContainerImpl(container, std::make_index_sequence<3>{});
}
</code>```

Create a new constexpr container instance through C, then expand the sequence to index the elements in a constant expression:

```<code>template <typename C, std::size_t... Is>
constexpr auto fooFromContainerImpl(const C& container, std::index_sequence<Is...>)
{
    constexpr auto c = container();
    return Foo<c.containee[Is]...>{};
}
</code>```

complete example on wandbox.org

Just for fun, here's a C++20 implementation:

```<code>struct container { int _data[3]; };

template <int... Is>
struct foo
{
    constexpr auto t() const { return std::tuple{Is...}; }
};

template <typename C>
constexpr auto foo_from_container(const C& c)
{
    return []<std::size_t... Is>(const auto& c, std::index_sequence<Is...>)
    {
        return foo<c()._data[Is]...>{};
    }(c, std::make_index_sequence<3>{});
}

int main()
{
    constexpr auto r = foo_from_container([]{ return container{42, 43, 44}; });
    static_assert(r.t() == std::tuple{42, 43, 44});
}
</code>```

live example on wandbox.org

Body:
Suppose I have a compile-time constexpr array and a variadic class template with a set of non-type parameters of the same type as the elements of the array.

My objective is to instantiate the class template with the values from the array:

struct Container
{
    int containee[3];
};

constexpr Container makeContainer();

template <int... Elements> class Foo;

Foo<makeContainer().containee[0],
    makeContainer().containee[1],
    makeContainer().containee[2]> foo;

The above code works well. However, I'm quite unhappy about having to manually index the array whenever I need to instantiate the Foo template. I would like the compiler to do that for me automatically:

Foo<Magic(makeContainer().containee)> foo;

I did some RTFM at cppreference, but that didn't help. I'm aware of std::forward<>(), but it cannot be applied to template argument lists.

Body:
Change makeContainer to a struct with a constexpr operator() or a constexpr lambda (C++17). A function pointer will not work here.

struct makeContainer
{
    constexpr auto operator()() const
    {
        return Container{/* ... */};
    }
};

Use std::make_index_sequence and std::index_sequence to generate a compile-time sequence of the indices:

template <typename C>
constexpr auto fooFromContainer(const C& container)
{
    return fooFromContainerImpl(container, std::make_index_sequence<3>{});
}

Create a new constexpr container instance through C, then expand the sequence to index the elements in a constant expression:

template <typename C, std::size_t... Is>
constexpr auto fooFromContainerImpl(const C& container, std::index_sequence<Is...>)
{
    constexpr auto c = container();
    return Foo<c.containee[Is]...>{};
}

complete example on wandbox.org

Just for fun, here's a C++20 implementation:

struct container { int _data[3]; };

template <int... Is>
struct foo
{
    constexpr auto t() const { return std::tuple{Is...}; }
};

template <typename C>
constexpr auto foo_from_container(const C& c)
{
    return []<std::size_t... Is>(const auto& c, std::index_sequence<Is...>)
    {
        return foo<c()._data[Is]...>{};
    }(c, std::make_index_sequence<3>{});
}

int main()
{
    constexpr auto r = foo_from_container([]{ return container{42, 43, 44}; });
    static_assert(r.t() == std::tuple{42, 43, 44});
}

live example on wandbox.org


问:
How to hard throw IndexOutOfBoundsException for RecyclerView?
I have small chance (0,5% users in day if trust fabric crashreport) catch IndexOutOfBoundsException: Inconsistency detected in two method for RecyclerView (i see crashlog in fabric ):

validateViewHolderForOffsetPosition()

tryGetViewHolderForPositionByDeadline()

I search same issue in other cases and i realized that this problem may occur when retrieving and updating data in the adapter from different threads. I fix this problem stupedly, but in theory this can work correctly:

```<code>    private fun setUpdates() {
                //...

                //fix code start
                if (Looper.getMainLooper().thread == Thread.currentThread()) {
                    log("thread is main")
                    adapter.notifyDataSetChanged()
                } else {
                    log("thread NOT is main")
                    notifyOnUi()
                }
                //fix code end

                //...
            }

    private fun notifyOnUi() {
        Handler(Looper.getMainLooper()).post {
            log("notify data set changes on UI")
            adapter.notifyDataSetChanged()
        }
    }
</code>```

And i don't know how Hard reproduce situation when this exception throws. I tried different options with multiple threads modify the list before/after/during adapter.notifyDataSetChanges() but this problem not reproduces (without fix code).

And mu question - what can we do that would throw IndexOutOfBoundsException: Inconsistency detected. ... for two methods in RecyclerView for test - fix my code this problem or not?:

validateViewHolderForOffsetPosition()

tryGetViewHolderForPositionByDeadline()

答:
First of all, it's the UI Thread that call getItemCount(), onCreateViewHolder, onBindViewHolder, etc... methods of the adapter.

So, if a different thread modify the data used by these methods, inconsistency can appear. Because, the data is not up-to-date with the notifications (notifyDataSetChanged, etc...).

For not having any inconsistencies, you have to modify the data and call notifyDataSetChanged in the same message posted on the main thread.

Something like:

```<code>private fun setUpdates(newData: Collection<Data>) {
    Handler(Looper.getMainLooper()).post {
        myData = newData // or whatever
        adapter.notifyDataSetChanged() // and notify within the same message
    }
}
</code>```

Body:
I have small chance (0,5% users in day if trust fabric crashreport) catch IndexOutOfBoundsException: Inconsistency detected in two method for RecyclerView (i see crashlog in fabric ):

validateViewHolderForOffsetPosition()

tryGetViewHolderForPositionByDeadline()

I search same issue in other cases and i realized that this problem may occur when retrieving and updating data in the adapter from different threads. I fix this problem stupedly, but in theory this can work correctly:

    private fun setUpdates() {
                //...

                //fix code start
                if (Looper.getMainLooper().thread == Thread.currentThread()) {
                    log("thread is main")
                    adapter.notifyDataSetChanged()
                } else {
                    log("thread NOT is main")
                    notifyOnUi()
                }
                //fix code end

                //...
            }

    private fun notifyOnUi() {
        Handler(Looper.getMainLooper()).post {
            log("notify data set changes on UI")
            adapter.notifyDataSetChanged()
        }
    }

And i don't know how Hard reproduce situation when this exception throws. I tried different options with multiple threads modify the list before/after/during adapter.notifyDataSetChanges() but this problem not reproduces (without fix code).

And mu question - what can we do that would throw IndexOutOfBoundsException: Inconsistency detected. ... for two methods in RecyclerView for test - fix my code this problem or not?:

validateViewHolderForOffsetPosition()

tryGetViewHolderForPositionByDeadline()

Body:
First of all, it's the UI Thread that call getItemCount(), onCreateViewHolder, onBindViewHolder, etc... methods of the adapter.

So, if a different thread modify the data used by these methods, inconsistency can appear. Because, the data is not up-to-date with the notifications (notifyDataSetChanged, etc...).

For not having any inconsistencies, you have to modify the data and call notifyDataSetChanged in the same message posted on the main thread.

Something like:

private fun setUpdates(newData: Collection<Data>) {
    Handler(Looper.getMainLooper()).post {
        myData = newData // or whatever
        adapter.notifyDataSetChanged() // and notify within the same message
    }
}


问:
Swift.print() vs print()
I have found that since Xcode will no longer digest println() I am
    left with either Swift.print() or print()   .   My question is,
    what is the difference between the two? I have not been able to
    find a conclusive answer online or in the
    Swift Prog. Lang. (Swift 3.0.1) from apple.

```<code>What prompted me to ask was that I noticed in the playground that
in the review area on the right Swift.print() showed no digested
data when passing a var whereas print() showed "example\n".
</code>```

Thank You.

答:
Not sure if println was good at that. but Swift.print
is pretty good at hanging runtime

If the outgoing println was not good at hanging the simuator here's
your difference right there.

Title: Swift.print() vs print()

Body:
I have found that since Xcode will no longer digest println() I am
    left with either Swift.print() or print()   .   My question is,
    what is the difference between the two? I have not been able to
    find a conclusive answer online or in the
    Swift Prog. Lang. (Swift 3.0.1) from apple.

What prompted me to ask was that I noticed in the playground that
in the review area on the right Swift.print() showed no digested
data when passing a var whereas print() showed "example\n".

Thank You.


问:
Get Firebase data from certain child
I'm starting to code Android Apps with the database connection. As IDE I use Android Studio and Firebase for the database. This is my data structure in Firebase:

In my app, I need to fill a ListView with all the names. So I want the data from three children from the child "Rezepte" from the UUID child. I hope this is understandable.

I've done a lot of googling and I just can't figure out how this works. My current version of the java code is this:

```<code>final FirebaseUser user = firebaseAuth.getCurrentUser();
    // trying to get the reference of the right path
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("Rezepte");
    ref.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // calling a method which should read the data from the snapshot and put it into the ListView
                    fillList((Map<String, Object>) dataSnapshot.child(user.getUid()).child("Rezepte").getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Toast.makeText(RezepteActivity.this, "Daten konnten nicht gelesen werden", Toast.LENGTH_SHORT).show();
                }
            });
}

private void fillList(Map<String, Object> entries) {

    // loop to cycle through every child of "Rezepte" and get the names
    for (Map.Entry<String, Object> entry : entries.entrySet()) {
        Map singleEntry = (Map) entry.getValue();
        // add the name to an ArrayList of all names
        Rezepte.add((String) singleEntry.get("name"));
    }
    // put the data into the ListView
    lvRezepte.addFooterView(lvRezepte, Rezepte, true);
}
</code>```

The app always crashes and I don't really understand a lot in the debugger. But the error occurs already in the onDataChange void.

I would be really happy if someone could help me.

答:
To get all those names and add them to an ArrayList, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rezepeteRef = rootRef.child(user.getUid()).child("Rezepte");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            list.add(name);
            Log.d("TAG", name);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
rezepeteRef.addListenerForSingleValueEvent(eventListener);
</code>```

Title: Get Firebase data from certain child

Body:
I'm starting to code Android Apps with the database connection. As IDE I use Android Studio and Firebase for the database. This is my data structure in Firebase:

In my app, I need to fill a ListView with all the names. So I want the data from three children from the child "Rezepte" from the UUID child. I hope this is understandable.

I've done a lot of googling and I just can't figure out how this works. My current version of the java code is this:

final FirebaseUser user = firebaseAuth.getCurrentUser();
    // trying to get the reference of the right path
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(user.getUid()).child("Rezepte");
    ref.addListenerForSingleValueEvent(
            new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // calling a method which should read the data from the snapshot and put it into the ListView
                    fillList((Map<String, Object>) dataSnapshot.child(user.getUid()).child("Rezepte").getValue());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Toast.makeText(RezepteActivity.this, "Daten konnten nicht gelesen werden", Toast.LENGTH_SHORT).show();
                }
            });
}

private void fillList(Map<String, Object> entries) {

    // loop to cycle through every child of "Rezepte" and get the names
    for (Map.Entry<String, Object> entry : entries.entrySet()) {
        Map singleEntry = (Map) entry.getValue();
        // add the name to an ArrayList of all names
        Rezepte.add((String) singleEntry.get("name"));
    }
    // put the data into the ListView
    lvRezepte.addFooterView(lvRezepte, Rezepte, true);
}

The app always crashes and I don't really understand a lot in the debugger. But the error occurs already in the onDataChange void.

I would be really happy if someone could help me.

Body:
To get all those names and add them to an ArrayList, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rezepeteRef = rootRef.child(user.getUid()).child("Rezepte");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String name = ds.child("name").getValue(String.class);
            list.add(name);
            Log.d("TAG", name);
        }
        Log.d("TAG", list);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
rezepeteRef.addListenerForSingleValueEvent(eventListener);


问:
Avoiding comma separator for the last value
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

```<code>Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");
</code>```

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

答:
One of my favorite fixes for this is to use a prepend instead and only set comma as the seperator value after the first item (sorry for the VB):</p>

```<code>    Dim seperator As String = ""

    For i As Integer = 0 To k.Length
        Response.Write(seperator + Convert.ToString(k.GetValue(i)))
        seperator = ","
    Next
</code>```

Body:
I am generating an output on a webpage in a format like this

({"1":"Jeff","2":"Tom","3":"Michael",})

For this, basically this is the code I am using

Response.Write("(" + "{");
//
for (Int32 i = 0; i < k.Length; i++)
{
  Response.Write(Convert.ToString(k.GetValue(i)) + ",");
}
//
Response.Write("}" + ")");

Notice my output, after Michael" there is a comma which I do not want since this is the last vaue but this is appearing since , is in the for loop. How to prevent this/remove this last comma from appearing?

My output should be ({"1":"Jeff","2":"Tom","3":"Michael"}) (There's no comma after last value here)

Body:
One of my favorite fixes for this is to use a prepend instead and only set comma as the seperator value after the first item (sorry for the VB):

    Dim seperator As String = ""

    For i As Integer = 0 To k.Length
        Response.Write(seperator + Convert.ToString(k.GetValue(i)))
        seperator = ","
    Next


问:
how to get Sun Rays from the middle of the object in threejs
I have an object where random open particles and others are solid. How do i place a fake sun inside of the object and get Rays through the open particles using threejs. When the object rotate either X,Y Rays should spreed through the open particles ( POST PROCESSING ) ?

SAMPLE VIDEO

My Object three.Js code is bellow

```<code>var camera, scene, renderer;
var geometry, material, mesh;

   init();
   animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 10, 10000);
  camera.position.z = 200;

  scene = new THREE.Scene();

  hemiLight = new THREE.HemisphereLight( 0x0000ff, 0x00ff00, 0.6 );
  scene.add(hemiLight);

  var geometry = new THREE.DodecahedronGeometry(80, 0);

  var material = new THREE.MeshPhongMaterial({
    color: 0xffffff,
    specular: 0xffffff,
    shininess: 1,
    shading: THREE.FlatShading,
    polygonOffset: true,
    polygonOffsetFactor: 1,
    wireframe:true

  });

  mesh = new THREE.Mesh(geometry, material);

  scene.add(mesh);

  var geo = new THREE.EdgesGeometry( mesh.geometry ); // or WireframeGeometry
  var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 } );
  var wireframe = new THREE.LineSegments( geo, mat );
  mesh.add( wireframe );

  //outer frame end

  //inner world like object start

  var sphere_material = [
      new THREE.MeshLambertMaterial( { color: 0xffff00, side: THREE.DoubleSide } ),
      new THREE.MeshBasicMaterial( { transparent: true, opacity: 0 } )
  ];

  var sphere_geometry = new THREE.OctahedronGeometry( 60, 3 );
  // assign material to each face
  for( var i = 0; i < sphere_geometry.faces.length; i++ ) {
      sphere_geometry.faces[ i ].materialIndex = THREE.Math.randInt( 0, 1 );
  }

  sphere_geometry.sortFacesByMaterialIndex();

  var sphere_mesh = new THREE.Mesh( sphere_geometry, sphere_material );
  sphere_mesh.position.set(0, 0, 0)
  mesh.add(sphere_mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });

  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}
renderer.gammaInput = true;
renderer.gammaOutput = true;

function animate() {

  requestAnimationFrame(animate);

  mesh.rotation.x += 0.003;
  mesh.rotation.y += 0.003;

  renderer.render(scene, camera);

}
</code>```

DEMO

答:
You're looking for volumetric lights. Check this code example below or maybe better look at it on jsfiddle (to see it in full dimensions not overplayed by console log).

It's based on this article. I slightly tweaked your code and updated the colors as well as some values and the code. It still needs some playing (e.g. number of faces, light color, shader properties etc.) but hopefully will help you. It all really depends how you wish to make it look like.

THREE.VolumetericLightShader = {
  uniforms: {
    tDiffuse: {value:null},
    lightPosition: {value: new THREE.Vector2(0.5, 0.5)},
    exposure: {value: 0.18},
    decay: {value: 0.95},
    density: {value: 0.8},
    weight: {value: 0.4},
    samples: {value: 50}
  },

  vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
      "vUv = uv;",
      "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
  ].join("\n"),

  fragmentShader: [
    "varying vec2 vUv;",
    "uniform sampler2D tDiffuse;",
    "uniform vec2 lightPosition;",
    "uniform float exposure;",
    "uniform float decay;",
    "uniform float density;",
    "uniform float weight;",
    "uniform int samples;",
    "const int MAX_SAMPLES = 100;",
    "void main()",
    "{",
      "vec2 texCoord = vUv;",
      "vec2 deltaTextCoord = texCoord - lightPosition;",
      "deltaTextCoord *= 1.0 / float(samples) * density;",
      "vec4 color = texture2D(tDiffuse, texCoord);",
      "float illuminationDecay = 1.0;",
      "for(int i=0; i < MAX_SAMPLES; i++)",
      "{",
        "if(i == samples){",
          "break;",
        "}",
        "texCoord -= deltaTextCoord;",
        "vec4 sample = texture2D(tDiffuse, texCoord);",
        "sample *= illuminationDecay * weight;",
        "color += sample;",
        "illuminationDecay *= decay;",
      "}",
      "gl_FragColor = color * exposure;",
    "}"
  ].join("\n")
};

THREE.AdditiveBlendingShader = {
  uniforms: {
    tDiffuse: { value:null },
    tAdd: { value:null }
  },

  vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
      "vUv = uv;",
      "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
  ].join("\n"),

  fragmentShader: [
    "uniform sampler2D tDiffuse;",
    "uniform sampler2D tAdd;",
    "varying vec2 vUv;",
    "void main() {",
      "vec4 color = texture2D( tDiffuse, vUv );",
      "vec4 add = texture2D( tAdd, vUv );",
      "gl_FragColor = color + add;",
    "}"
  ].join("\n")
};

THREE.PassThroughShader = {
 uniforms: {
  tDiffuse: { value: null }
 },

 vertexShader: [
  "varying vec2 vUv;",
    "void main() {",
    "vUv = uv;",
   "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  "}"
 ].join( "\n" ),

 fragmentShader: [
    "uniform sampler2D tDiffuse;",
    "varying vec2 vUv;",
    "void main() {",
   "gl_FragColor = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );",
  "}"
 ].join( "\n" )
};

(function(){
  var scene, camera, renderer, composer, box, pointLight,
      occlusionComposer, occlusionRenderTarget, occlusionBox, lightSphere,
      volumetericLightShaderUniforms,
      DEFAULT_LAYER = 0,
      OCCLUSION_LAYER = 1,
      renderScale = 0.5,
      angle = 0,
      sphere_mesh,
      mesh;

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  function setupScene(){
    var ambientLight,
        geometry,
        material;

    ambientLight = new THREE.AmbientLight(0x2c3e50);
    scene.add(ambientLight);

    pointLight = new THREE.PointLight(0xddddff);
    scene.add(pointLight);

    geometry = new THREE.SphereBufferGeometry( 1, 32, 32 );
    material = new THREE.MeshBasicMaterial( { color: 0x99ddff } );
    lightSphere = new THREE.Mesh( geometry, material );
    lightSphere.layers.set( OCCLUSION_LAYER );
    scene.add( lightSphere );

    camera.position.z = 6;
  }

  function addFragmentedSphere(){
    var geometry = new THREE.DodecahedronGeometry(2.9, 0);

  var material = new THREE.MeshPhongMaterial({
    color: 0x000000,
    specular: 0xffffff,
    shininess: 1,
    flatShading: THREE.FlatShading,
    polygonOffset: true,
    polygonOffsetFactor: 1,
    wireframe:true

  });

  mesh = new THREE.Mesh(geometry, material);

  scene.add(mesh);

  //outer frame end

  //inner world like object start

  var sphere_material = [
      new THREE.MeshLambertMaterial( { color: 0xffff00, side: THREE.DoubleSide } ),
      new THREE.MeshBasicMaterial( { transparent: true, opacity: 0 } )
  ];

  var sphere_geometry = new THREE.OctahedronGeometry( 2.7, 4 );
  // assign material to each face
  for( var i = 0; i < sphere_geometry.faces.length; i++ ) {
      sphere_geometry.faces[ i ].materialIndex = THREE.Math.randInt( 0, 1 );
  }

  sphere_geometry.sortFacesByMaterialIndex();

  sphere_mesh = new THREE.Mesh( sphere_geometry, sphere_material );
  sphere_mesh.position.set(0, 0, 0)
  mesh.add(sphere_mesh);
  sphere_mesh.layers.set( OCCLUSION_LAYER );
  }

  function setupPostprocessing(){
    var pass;

    occlusionRenderTarget = new THREE.WebGLRenderTarget( window.innerWidth * renderScale, window.innerHeight * renderScale );
    occlusionComposer = new THREE.EffectComposer( renderer, occlusionRenderTarget);
    occlusionComposer.addPass( new THREE.RenderPass( scene, camera ) );
    pass = new THREE.ShaderPass( THREE.VolumetericLightShader );
    pass.needsSwap = false;
    occlusionComposer.addPass( pass );

    volumetericLightShaderUniforms = pass.uniforms;
    volumetericLightShaderUniforms.exposure.value = 0.5;
    volumetericLightShaderUniforms.decay.value = 0.96;
    volumetericLightShaderUniforms.density.value = 0.95;
    volumetericLightShaderUniforms.weight.value = 0.59;
    volumetericLightShaderUniforms.samples.value = 100;

    composer = new THREE.EffectComposer( renderer );
    composer.addPass( new THREE.RenderPass( scene, camera ) );
    pass = new THREE.ShaderPass( THREE.AdditiveBlendingShader );
    pass.uniforms.tAdd.value = occlusionRenderTarget.texture;
    composer.addPass( pass );
    pass.renderToScreen = true;
  }

  function onFrame(){
    requestAnimationFrame( onFrame );
    update();
    render();
  }

  function update(){
    mesh.rotation.x += 0.003;
    mesh.rotation.y += 0.003;
  }

  function render(){
    camera.layers.set(OCCLUSION_LAYER);
    renderer.setClearColor(0x000000);
    occlusionComposer.render();

    camera.layers.set(DEFAULT_LAYER);
    renderer.setClearColor(0x090611);
    composer.render();
  }

  function addRenderTargetImage(){
    var material,
        mesh,
        folder;

    material = new THREE.ShaderMaterial( THREE.PassThroughShader );
    material.uniforms.tDiffuse.value = occlusionRenderTarget.texture;

    mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), material );
    composer.passes[1].scene.add( mesh );
    mesh.visible = false;
  }

  window.addEventListener( 'resize', function(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

    var pixelRatio = renderer.getPixelRatio(),
        newWidth  = Math.floor( window.innerWidth / pixelRatio ) || 1,
        newHeight = Math.floor( window.innerHeight / pixelRatio ) || 1;

    composer.setSize( newWidth, newHeight );
    occlusionComposer.setSize( newWidth * renderScale, newHeight * renderScale );

  }, false );

  setupScene();
  setupPostprocessing();
  addFragmentedSphere();//
  addRenderTargetImage();
  onFrame();
}())```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js"></script>
<script src="https://abberg.github.io/lib/shaders/CopyShader.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/EffectComposer.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/RenderPass.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/ShaderPass.js"></script></code>```

Body:
I have an object where random open particles and others are solid. How do i place a fake sun inside of the object and get Rays through the open particles using threejs. When the object rotate either X,Y Rays should spreed through the open particles ( POST PROCESSING ) ?

SAMPLE VIDEO

My Object three.Js code is bellow

var camera, scene, renderer;
var geometry, material, mesh;

   init();
   animate();

function init() {

  camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 10, 10000);
  camera.position.z = 200;

  scene = new THREE.Scene();

  hemiLight = new THREE.HemisphereLight( 0x0000ff, 0x00ff00, 0.6 );
  scene.add(hemiLight);

  var geometry = new THREE.DodecahedronGeometry(80, 0);

  var material = new THREE.MeshPhongMaterial({
    color: 0xffffff,
    specular: 0xffffff,
    shininess: 1,
    shading: THREE.FlatShading,
    polygonOffset: true,
    polygonOffsetFactor: 1,
    wireframe:true

  });

  mesh = new THREE.Mesh(geometry, material);

  scene.add(mesh);

  var geo = new THREE.EdgesGeometry( mesh.geometry ); // or WireframeGeometry
  var mat = new THREE.LineBasicMaterial( { color: 0xffffff, linewidth: 2 } );
  var wireframe = new THREE.LineSegments( geo, mat );
  mesh.add( wireframe );

  //outer frame end

  //inner world like object start

  var sphere_material = [
      new THREE.MeshLambertMaterial( { color: 0xffff00, side: THREE.DoubleSide } ),
      new THREE.MeshBasicMaterial( { transparent: true, opacity: 0 } )
  ];

  var sphere_geometry = new THREE.OctahedronGeometry( 60, 3 );
  // assign material to each face
  for( var i = 0; i < sphere_geometry.faces.length; i++ ) {
      sphere_geometry.faces[ i ].materialIndex = THREE.Math.randInt( 0, 1 );
  }

  sphere_geometry.sortFacesByMaterialIndex();

  var sphere_mesh = new THREE.Mesh( sphere_geometry, sphere_material );
  sphere_mesh.position.set(0, 0, 0)
  mesh.add(sphere_mesh);

  renderer = new THREE.WebGLRenderer({
    antialias: true
  });

  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

}
renderer.gammaInput = true;
renderer.gammaOutput = true;

function animate() {

  requestAnimationFrame(animate);

  mesh.rotation.x += 0.003;
  mesh.rotation.y += 0.003;

  renderer.render(scene, camera);

}

DEMO

Body:
You're looking for volumetric lights. Check this code example below or maybe better look at it on jsfiddle (to see it in full dimensions not overplayed by console log).

It's based on this article. I slightly tweaked your code and updated the colors as well as some values and the code. It still needs some playing (e.g. number of faces, light color, shader properties etc.) but hopefully will help you. It all really depends how you wish to make it look like.

THREE.VolumetericLightShader = {
  uniforms: {
    tDiffuse: {value:null},
    lightPosition: {value: new THREE.Vector2(0.5, 0.5)},
    exposure: {value: 0.18},
    decay: {value: 0.95},
    density: {value: 0.8},
    weight: {value: 0.4},
    samples: {value: 50}
  },

  vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
      "vUv = uv;",
      "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
  ].join("\n"),

  fragmentShader: [
    "varying vec2 vUv;",
    "uniform sampler2D tDiffuse;",
    "uniform vec2 lightPosition;",
    "uniform float exposure;",
    "uniform float decay;",
    "uniform float density;",
    "uniform float weight;",
    "uniform int samples;",
    "const int MAX_SAMPLES = 100;",
    "void main()",
    "{",
      "vec2 texCoord = vUv;",
      "vec2 deltaTextCoord = texCoord - lightPosition;",
      "deltaTextCoord *= 1.0 / float(samples) * density;",
      "vec4 color = texture2D(tDiffuse, texCoord);",
      "float illuminationDecay = 1.0;",
      "for(int i=0; i < MAX_SAMPLES; i++)",
      "{",
        "if(i == samples){",
          "break;",
        "}",
        "texCoord -= deltaTextCoord;",
        "vec4 sample = texture2D(tDiffuse, texCoord);",
        "sample *= illuminationDecay * weight;",
        "color += sample;",
        "illuminationDecay *= decay;",
      "}",
      "gl_FragColor = color * exposure;",
    "}"
  ].join("\n")
};

THREE.AdditiveBlendingShader = {
  uniforms: {
    tDiffuse: { value:null },
    tAdd: { value:null }
  },

  vertexShader: [
    "varying vec2 vUv;",
    "void main() {",
      "vUv = uv;",
      "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
    "}"
  ].join("\n"),

  fragmentShader: [
    "uniform sampler2D tDiffuse;",
    "uniform sampler2D tAdd;",
    "varying vec2 vUv;",
    "void main() {",
      "vec4 color = texture2D( tDiffuse, vUv );",
      "vec4 add = texture2D( tAdd, vUv );",
      "gl_FragColor = color + add;",
    "}"
  ].join("\n")
};

THREE.PassThroughShader = {
 uniforms: {
  tDiffuse: { value: null }
 },

 vertexShader: [
  "varying vec2 vUv;",
    "void main() {",
    "vUv = uv;",
   "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  "}"
 ].join( "\n" ),

 fragmentShader: [
    "uniform sampler2D tDiffuse;",
    "varying vec2 vUv;",
    "void main() {",
   "gl_FragColor = texture2D( tDiffuse, vec2( vUv.x, vUv.y ) );",
  "}"
 ].join( "\n" )
};

(function(){
  var scene, camera, renderer, composer, box, pointLight,
      occlusionComposer, occlusionRenderTarget, occlusionBox, lightSphere,
      volumetericLightShaderUniforms,
      DEFAULT_LAYER = 0,
      OCCLUSION_LAYER = 1,
      renderScale = 0.5,
      angle = 0,
      sphere_mesh,
      mesh;

  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  function setupScene(){
    var ambientLight,
        geometry,
        material;

    ambientLight = new THREE.AmbientLight(0x2c3e50);
    scene.add(ambientLight);

    pointLight = new THREE.PointLight(0xddddff);
    scene.add(pointLight);

    geometry = new THREE.SphereBufferGeometry( 1, 32, 32 );
    material = new THREE.MeshBasicMaterial( { color: 0x99ddff } );
    lightSphere = new THREE.Mesh( geometry, material );
    lightSphere.layers.set( OCCLUSION_LAYER );
    scene.add( lightSphere );

    camera.position.z = 6;
  }

  function addFragmentedSphere(){
    var geometry = new THREE.DodecahedronGeometry(2.9, 0);

  var material = new THREE.MeshPhongMaterial({
    color: 0x000000,
    specular: 0xffffff,
    shininess: 1,
    flatShading: THREE.FlatShading,
    polygonOffset: true,
    polygonOffsetFactor: 1,
    wireframe:true

  });

  mesh = new THREE.Mesh(geometry, material);

  scene.add(mesh);

  //outer frame end

  //inner world like object start

  var sphere_material = [
      new THREE.MeshLambertMaterial( { color: 0xffff00, side: THREE.DoubleSide } ),
      new THREE.MeshBasicMaterial( { transparent: true, opacity: 0 } )
  ];

  var sphere_geometry = new THREE.OctahedronGeometry( 2.7, 4 );
  // assign material to each face
  for( var i = 0; i < sphere_geometry.faces.length; i++ ) {
      sphere_geometry.faces[ i ].materialIndex = THREE.Math.randInt( 0, 1 );
  }

  sphere_geometry.sortFacesByMaterialIndex();

  sphere_mesh = new THREE.Mesh( sphere_geometry, sphere_material );
  sphere_mesh.position.set(0, 0, 0)
  mesh.add(sphere_mesh);
  sphere_mesh.layers.set( OCCLUSION_LAYER );
  }

  function setupPostprocessing(){
    var pass;

    occlusionRenderTarget = new THREE.WebGLRenderTarget( window.innerWidth * renderScale, window.innerHeight * renderScale );
    occlusionComposer = new THREE.EffectComposer( renderer, occlusionRenderTarget);
    occlusionComposer.addPass( new THREE.RenderPass( scene, camera ) );
    pass = new THREE.ShaderPass( THREE.VolumetericLightShader );
    pass.needsSwap = false;
    occlusionComposer.addPass( pass );

    volumetericLightShaderUniforms = pass.uniforms;
    volumetericLightShaderUniforms.exposure.value = 0.5;
    volumetericLightShaderUniforms.decay.value = 0.96;
    volumetericLightShaderUniforms.density.value = 0.95;
    volumetericLightShaderUniforms.weight.value = 0.59;
    volumetericLightShaderUniforms.samples.value = 100;

    composer = new THREE.EffectComposer( renderer );
    composer.addPass( new THREE.RenderPass( scene, camera ) );
    pass = new THREE.ShaderPass( THREE.AdditiveBlendingShader );
    pass.uniforms.tAdd.value = occlusionRenderTarget.texture;
    composer.addPass( pass );
    pass.renderToScreen = true;
  }

  function onFrame(){
    requestAnimationFrame( onFrame );
    update();
    render();
  }

  function update(){
    mesh.rotation.x += 0.003;
    mesh.rotation.y += 0.003;
  }

  function render(){
    camera.layers.set(OCCLUSION_LAYER);
    renderer.setClearColor(0x000000);
    occlusionComposer.render();

    camera.layers.set(DEFAULT_LAYER);
    renderer.setClearColor(0x090611);
    composer.render();
  }

  function addRenderTargetImage(){
    var material,
        mesh,
        folder;

    material = new THREE.ShaderMaterial( THREE.PassThroughShader );
    material.uniforms.tDiffuse.value = occlusionRenderTarget.texture;

    mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), material );
    composer.passes[1].scene.add( mesh );
    mesh.visible = false;
  }

  window.addEventListener( 'resize', function(){

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

    var pixelRatio = renderer.getPixelRatio(),
        newWidth  = Math.floor( window.innerWidth / pixelRatio ) || 1,
        newHeight = Math.floor( window.innerHeight / pixelRatio ) || 1;

    composer.setSize( newWidth, newHeight );
    occlusionComposer.setSize( newWidth * renderScale, newHeight * renderScale );

  }, false );

  setupScene();
  setupPostprocessing();
  addFragmentedSphere();//
  addRenderTargetImage();
  onFrame();
}())

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/101/three.min.js"></script>
<script src="https://abberg.github.io/lib/shaders/CopyShader.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/EffectComposer.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/RenderPass.js"></script>
<script src="https://abberg.github.io/lib/postprocessing/ShaderPass.js"></script>


问:
Group elements from an array with a new element containing group value
I have an array like this one:

```<code>$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];
</code>```

I need to transform this on something like:

```<code>[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]
</code>```

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

答:
You can foreach the array and build a new array with the structure you want.

```<code>$new =array();
Foreach($A as $item){
    If(!isset($new[$item['Categoria']])) $new[$item['Categoria']] = array(); // create array of not set
    $new[$item['Categoria']][] = $item['Servico']; // add servico item to array
}
</code>```

This loops each item if it does not find the subarray it will create it.

Then add the 'name' values in the subarray.

Edit, see now that you want your output array to be named B, just change 'new' to 'B' in the code.

Body:
I have an array like this one:

$array = [
     ['Categoria' => 'example', 'Servico' => 'name1'],
     ['Categoria' => 'example', 'Servico' => 'name2'],
     ['Categoria' => 'example', 'Servico' => 'name3'],
     ['Categoria' => 'example2', 'Servico' => 'name4'],
     ['Categoria' => 'example2', 'Servico' => 'name5'],
     ['Categoria' => 'example2', 'Servico' => 'name6'],
     ['Categoria' => 'example3', 'Servico' => 'name7'],
     ['Categoria' => 'example3', 'Servico' => 'name8'],
     ['Categoria' => 'example3', 'Servico' => 'name9']
];

I need to transform this on something like:

[
    [
        'Servico' => 'example',
        'children' => [
            ['Servico' => 'name1'],
            ['Servico' => 'name2'],
            ['Servico' => 'name3'],
        ]
    ],
    [
        'Servico' => 'example2',
        'children' => [
            ['Servico' => 'name4'],
            ['Servico' => 'name5'],
            ['Servico' => 'name6'],
        ]
    ],
    [
        'Servico' => 'example3',
        'children' => [
            ['Servico' => 'name7'],
            ['Servico' => 'name8'],
            ['Servico' => 'name9'],
        ]
    ],
]

I have read this topic and I successfully have grouped my array, but I couldn't find a way to format the array in a way I have Servico and children on each object.

Someone have any ideas?

Body:
You can foreach the array and build a new array with the structure you want.

$new =array();
Foreach($A as $item){
    If(!isset($new[$item['Categoria']])) $new[$item['Categoria']] = array(); // create array of not set
    $new[$item['Categoria']][] = $item['Servico']; // add servico item to array
}

This loops each item if it does not find the subarray it will create it.

Then add the 'name' values in the subarray.

Edit, see now that you want your output array to be named B, just change 'new' to 'B' in the code.


问:
Ruby if else statement
I am being asked to:

Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.

This is the code I have come up with:

```<code>def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end
</code>```

The calls I am making:

```<code>first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true
</code>```

For some reason on repl.it I only get the output false

And i get this error message on the platform I am actually meant to be completing this task on:

```<code>expected #<TrueClass:20> => true
     got #<FalseClass:0> => false

Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.

exercise_spec.rb:42:in `block (2 levels) in <top (required)>'
</code>```

Tried a number of things, but annoyingly stuck with something that seems should be simple...

答:
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.

Your code:

```<code>def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end
</code>```

First of all, your code doesn't follow the requirements. They ask to compare the lengths of the two arguments. The if condition should be:

```<code>if first.length >= second.length
</code>```

See the documentation of String#length.

Regarding the syntax of Ruby, the semicolons (;) after the statements are not needed. Like in Javascript, a Ruby statement can be terminated using a semicolon but also a newline. The semicolon is useful to separate two statements on the same line.

Next, the same as in Javascript (and many other languages), you can directly return the result of the comparison (and not put it into an if statement that returns true/false):

```<code>def first_longer_than_second(first, second)
  return first.length >= second.length
end
</code>```

One last improvement to make it look like Ruby (and not Javascript or PHP): a Ruby function returns the value of the last expression it computes; this makes the presence of the return keyword superfluous here.

Your code should be:

```<code>def first_longer_than_second(first, second)
  first.length >= second.length
end
</code>```

Title: Ruby if else statement

Body:
I am being asked to:

Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.

This is the code I have come up with:

def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end

The calls I am making:

first_longer_than_second('pneumonoultramicroscopicsilicovolcanoconiosis', 'k') #=> false
first_longer_than_second('apple', 'prune') #=> true

For some reason on repl.it I only get the output false

And i get this error message on the platform I am actually meant to be completing this task on:

expected #<TrueClass:20> => true
     got #<FalseClass:0> => false

Compared using equal?, which compares object identity,
but expected and actual are not the same object. Use
`expect(actual).to eq(expected)` if you don't care about
object identity in this example.

exercise_spec.rb:42:in `block (2 levels) in <top (required)>'

Tried a number of things, but annoyingly stuck with something that seems should be simple...

Body:
Define a method called first_longer_than_second with a parameter called first and another called second. The method will return true if the first word passed in is greater than or equal to the length of the second word. It returns false otherwise.

Your code:

def first_longer_than_second(first, second)
  if first >= second
      return true;
  else
      return false;
  end
end

First of all, your code doesn't follow the requirements. They ask to compare the lengths of the two arguments. The if condition should be:

if first.length >= second.length

See the documentation of String#length.

Regarding the syntax of Ruby, the semicolons (;) after the statements are not needed. Like in Javascript, a Ruby statement can be terminated using a semicolon but also a newline. The semicolon is useful to separate two statements on the same line.

Next, the same as in Javascript (and many other languages), you can directly return the result of the comparison (and not put it into an if statement that returns true/false):

def first_longer_than_second(first, second)
  return first.length >= second.length
end

One last improvement to make it look like Ruby (and not Javascript or PHP): a Ruby function returns the value of the last expression it computes; this makes the presence of the return keyword superfluous here.

Your code should be:

def first_longer_than_second(first, second)
  first.length >= second.length
end