问:
ViewHolders for ListViews with different item layouts
I have ListView with 2 different types of layout: one with image and another without image. I try to do something like this. I override getView of BaseAdapter:

```<code>public View getView(int position, View convertView, ViewGroup parent) {
        Map<String, String> item = mData.get(position);
        if(item.get("image_location").equals("") == true){
            ViewHolderWithoutImage holder = new ViewHolderWithoutImage();
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.row_without_image, null);
                holder.title = (TextView)convertView.findViewById(R.id.title);
                holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolderWithoutImage)convertView.getTag();
            }
            holder.title.setText(mData.get(position).get("title").toString());
            holder.firstParagraph.setText(item.get("first_paragraph").toString());

        }else{
            ViewHolderWithImage holder = new ViewHolderWithImage();
            Bitmap bm = null;
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.row_with_image, null);
                holder.title = (TextView)convertView.findViewById(R.id.title_image);
                holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph_image);
                holder.image = (ImageView)convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolderWithImage)convertView.getTag();
            }

            holder.title.setText(mData.get(position).get("title").toString());
            holder.firstParagraph.setText(item.get("first_paragraph").toString());
            String location = imageBaseUrl + item.get("image_location");
            bm = downloadImage(location);
            holder.image.setImageBitmap(bm);
        }
        return convertView;
    }
</code>```

My ViewHolders classes:

```<code>static class ViewHolderWithImage {
        TextView title;
        TextView firstParagraph;
        ImageView image;
    }

    static class ViewHolderWithoutImage {
        TextView title;
        TextView firstParagraph;
    }
</code>```

It works without the second part, but crashes when it going to

```<code>holder = (ViewHolderWithImage)convertView.getTag();
</code>```

in part when item.get("image_location").equals("") != true with java.lang.reflect.InvocationTargetException. Any ideas how can I fix that?

答:
I think it's happens because convertView's tag holds ViewHolder with different type. Try to check convertView type:

```<code>if(item.get("image_location").equals("") == true){
    ...
    if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithoutImage)){
    ...
}else{
    ...
    if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithImage)){
        convertView = mInflater.inflate(R.layout.row_with_image, null);
        ...
</code>```

P.S. It's better to use system methods for handling different layouts (override getItemViewType()). There is good article on this topic.

Body:
I have ListView with 2 different types of layout: one with image and another without image. I try to do something like this. I override getView of BaseAdapter:

public View getView(int position, View convertView, ViewGroup parent) {
        Map<String, String> item = mData.get(position);
        if(item.get("image_location").equals("") == true){
            ViewHolderWithoutImage holder = new ViewHolderWithoutImage();
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.row_without_image, null);
                holder.title = (TextView)convertView.findViewById(R.id.title);
                holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolderWithoutImage)convertView.getTag();
            }
            holder.title.setText(mData.get(position).get("title").toString());
            holder.firstParagraph.setText(item.get("first_paragraph").toString());

        }else{
            ViewHolderWithImage holder = new ViewHolderWithImage();
            Bitmap bm = null;
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.row_with_image, null);
                holder.title = (TextView)convertView.findViewById(R.id.title_image);
                holder.firstParagraph = (TextView)convertView.findViewById(R.id.first_paragraph_image);
                holder.image = (ImageView)convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolderWithImage)convertView.getTag();
            }

            holder.title.setText(mData.get(position).get("title").toString());
            holder.firstParagraph.setText(item.get("first_paragraph").toString());
            String location = imageBaseUrl + item.get("image_location");
            bm = downloadImage(location);
            holder.image.setImageBitmap(bm);
        }
        return convertView;
    }

My ViewHolders classes:

static class ViewHolderWithImage {
        TextView title;
        TextView firstParagraph;
        ImageView image;
    }

    static class ViewHolderWithoutImage {
        TextView title;
        TextView firstParagraph;
    }

It works without the second part, but crashes when it going to

holder = (ViewHolderWithImage)convertView.getTag();

in part when item.get("image_location").equals("") != true with java.lang.reflect.InvocationTargetException. Any ideas how can I fix that?

Body:
I think it's happens because convertView's tag holds ViewHolder with different type. Try to check convertView type:

if(item.get("image_location").equals("") == true){
    ...
    if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithoutImage)){
    ...
}else{
    ...
    if(convertView == null || !(convertView.getTag() instanceof ViewHolderWithImage)){
        convertView = mInflater.inflate(R.layout.row_with_image, null);
        ...

P.S. It's better to use system methods for handling different layouts (override getItemViewType()). There is good article on this topic.


来源: stackexchange

问:
How to find Icon names for Font Awesome to import with React?
I have added Font Awesome icon library to my react project.
As per the documentation, i am creating a library but not able to add icons as i dont know the icon name to import.

For eg - On website icon is "coffee". But to add to library i need to use -

library.add(faCoffee)

then i can use it as -

How do i find the icon React name i.e. faCoffee for coffee?

```<code>import ReactDOM from 'react-dom'
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee } from '@fortawesome/free-solid-svg-icons'

library.add(fab, faCheckSquare, faCoffee);

<FontAwesome icon="coffee" />
</code>```

答:
I would consider using react-icons over the @fortawesome package for popular icon packages.React-icons is nice because it provides ES6 support for various popular icons, allowing one to only include the icons actually being used within your react project. Some popular supported icon packages within react-icons are the following:

Font Awesome

Ionicons

Material Design Icons

Typicons

And many more for a complete list look here

For your particular case you could easily use Font Awesome icons and search for the exact name of the icon you're trying to use by doing the following:

Install the react-icons package

npm install react-icons --save

Search for your desired icon and exact import name here

Import and use the desired icon within your react project, for example the Font Awesome coffee icon:

import { FaCoffee } from 'react-icons/fa';
<FaCoffee />

The react-icons package is extremely easy to use and in my experience has been less complex than the other icon packages for react projects.

Hopefully that helps!

ContentLicense: CC BY-SA 4.0

Body:
I have added Font Awesome icon library to my react project.
As per the documentation, i am creating a library but not able to add icons as i dont know the icon name to import.

For eg - On website icon is "coffee". But to add to library i need to use -

library.add(faCoffee)

then i can use it as -

How do i find the icon React name i.e. faCoffee for coffee?

import ReactDOM from 'react-dom'
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { faCheckSquare, faCoffee } from '@fortawesome/free-solid-svg-icons'

library.add(fab, faCheckSquare, faCoffee);

<FontAwesome icon="coffee" />


问:
Embedding javascript into html in Vue
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

```<code>{{blogs[0].content}}
</code>```

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

```<code>{{blogs[0].content[:100]}}
</code>```

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

```<code><b-card
        title= blogs[0].title
        img-src="https://placekitten.com/g/400/450"
        img-alt="Image"
        img-top
      >
        <b-card-text>
          {{blogs[0].content[:10]}}
        </b-card-text>
</b-card>
</code>```

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

答:
I'd recommend creating a filter.

```<code>Vue.filter('ellipse', function (value, size) {
  if (!value) return ''
  if (value.length < size) return value;

  return `${value.substr(0, size)}...`;
})
</code>```

Then you can easily reuse throughout your code:

```<code>{{ message | ellipse(50) }}
<p v-text="message | ellipse(50)"></p>
</code>```

Title: Embedding javascript into html in Vue

Body:
So I've linked Firebase to my Vue project and now I want to display a portion of the content of a blog. I know that to display the entire blog content I can simple write the following within an html tag.

{{blogs[0].content}}

My question is, how do you display just a portion of it, for example the first 100 characters of the content? I've tried,

{{blogs[0].content[:100]}}

However that gives a compile error.

Also I have a second question, I have using bootstrap with Vue. More specifically the card cascade. Below shows a section of the bootstrap card cascade.

          {{blogs[0].content[:10]}}

I want the title to be the title of blogs[0] but the way I have done it above just prints out "blogs[0].title"

Body:
I'd recommend creating a filter.

Vue.filter('ellipse', function (value, size) {
  if (!value) return ''
  if (value.length < size) return value;

  return `${value.substr(0, size)}...`;
})

Then you can easily reuse throughout your code:

{{ message | ellipse(50) }}
<p v-text="message | ellipse(50)"></p>


问:
Java basics: a static function without a name, or return type
```<code>public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...
</code>```

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?

答: It is executed once when the class is loaded.  In this specific case it sets up a logger for the application.</p>

ContentLicense: CC BY-SA 3.0

Body:
public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class.getName());

    static {
        try {
             LOGGER.addHandler(new FileHandler("errors.log",true));
        }
        catch(IOException ex) {
             LOGGER.log(Level.WARNING,ex.toString(),ex);
        }
    }
...

I'm wondering what is this nameless static function about.

I never saw anything like this in java (which I'm currently learning).

What is it for ?

When is it typically used ?

When is this gonna be executed in the program ?


问:
How to retrieve company name from the selected contact
Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.

But instead of returning the company name it's returning the mobile number again.

The intent I use to select a specific phone number when there are multiple numbers

```<code>Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                    startActivityForResult(calContctPickerIntent, 1);
</code>```

here is the main code

```<code> @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (1):
            if (resultCode == Activity.RESULT_OK) {
                Uri contctDataVar = data.getData();

                Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
                if (contctCursorVar.getCount() > 0) {
                    while (contctCursorVar.moveToNext()) {
                        String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));

                        String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));

                        Log.i("Names", ContctNamVar);

                        if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            // Query phone here. Covered next
                            String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

                            mobile.setText(ContctMobVar);
                            custname.setText(ContctNamVar);
                            companyname.setText(Companyname2);

                            Log.i("Number", ContctMobVar);

                        }

                    }
                }
            }
            break;
    }
}
</code>```

I need to find a way to retrieve the company name saved under the selected contact.

答:
With the help of the solution provided by @Shiva Snape I was able to solve the problem.

Code for button to call contacts app and select the relevant number

```<code>        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(intent, 1);
</code>```

Code to collect Contact Number, Name and company name.

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Uri uri = data.getData();

        if (uri != null) {
            Cursor c = null;

            try {
                c = getContentResolver().query(uri, new String[]{
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                ContactsContract.CommonDataKinds.Phone.TYPE,
                                ContactsContract.CommonDataKinds.Phone.NUMBER,
                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                        null, null, null);
                ContentResolver mContentResolver = this.getContentResolver();

                if (c != null && c.moveToFirst()) {
                    String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String rawContactId = getRawContactId(contactId);
                    String companyName = getCompanyName(rawContactId);
                    int type = c.getInt(1);
                    showSelectedNumber(type, number);

                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}

private String getCompanyName(String rawContactId) {
    try {
        String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] orgWhereParams = new String[]{rawContactId,
                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                null, orgWhere, orgWhereParams, null);

        if (cursor == null) return null;
        String Vname = null;
        if (cursor.moveToFirst()) {
            Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

        }
        cursor.close();
        return Vname;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private String getRawContactId(String contactId) {
    String[] projection = new String[]{ContactsContract.RawContacts._ID};
    String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
    String[] selectionArgs = new String[]{contactId};
    Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
    if (c == null) return null;
    int rawContactId = -1;
    if (c.moveToFirst()) {
        rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
    }
    c.close();
    return String.valueOf(rawContactId);
}

public void showSelectedNumber(int type, String number) {
    Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}
</code>```

Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.

Body:
Using ContactsContract I am able to retrieve and display selected mobile number and the relevant contact name.

But instead of returning the company name it's returning the mobile number again.

The intent I use to select a specific phone number when there are multiple numbers

Intent calContctPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    calContctPickerIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
                    startActivityForResult(calContctPickerIntent, 1);

here is the main code

 @Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
    super.onActivityResult(reqCode, resultCode, data);

    switch (reqCode) {
        case (1):
            if (resultCode == Activity.RESULT_OK) {
                Uri contctDataVar = data.getData();

                Cursor contctCursorVar = getContentResolver().query(contctDataVar, null, null, null, null);
                if (contctCursorVar.getCount() > 0) {
                    while (contctCursorVar.moveToNext()) {
                        String ContctUidVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts._ID));

                        String ContctNamVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        String Companyname = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));

                        Log.i("Names", ContctNamVar);

                        if (Integer.parseInt(contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            // Query phone here. Covered next
                            String ContctMobVar = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String Companyname2 = contctCursorVar.getString(contctCursorVar.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

                            mobile.setText(ContctMobVar);
                            custname.setText(ContctNamVar);
                            companyname.setText(Companyname2);

                            Log.i("Number", ContctMobVar);

                        }

                    }
                }
            }
            break;
    }
}

I need to find a way to retrieve the company name saved under the selected contact.

Body:
With the help of the solution provided by @Shiva Snape I was able to solve the problem.

Code for button to call contacts app and select the relevant number

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
            startActivityForResult(intent, 1);

Code to collect Contact Number, Name and company name.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Uri uri = data.getData();

        if (uri != null) {
            Cursor c = null;

            try {
                c = getContentResolver().query(uri, new String[]{
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                ContactsContract.CommonDataKinds.Phone.TYPE,
                                ContactsContract.CommonDataKinds.Phone.NUMBER,
                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                        null, null, null);
                ContentResolver mContentResolver = this.getContentResolver();

                if (c != null && c.moveToFirst()) {
                    String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    String contactId = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    String rawContactId = getRawContactId(contactId);
                    String companyName = getCompanyName(rawContactId);
                    int type = c.getInt(1);
                    showSelectedNumber(type, number);

                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}

private String getCompanyName(String rawContactId) {
    try {
        String orgWhere = ContactsContract.Data.RAW_CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
        String[] orgWhereParams = new String[]{rawContactId,
                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI,
                null, orgWhere, orgWhereParams, null);

        if (cursor == null) return null;
        String Vname = null;
        if (cursor.moveToFirst()) {
            Vname = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));

        }
        cursor.close();
        return Vname;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private String getRawContactId(String contactId) {
    String[] projection = new String[]{ContactsContract.RawContacts._ID};
    String selection = ContactsContract.RawContacts.CONTACT_ID + "=?";
    String[] selectionArgs = new String[]{contactId};
    Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, selectionArgs, null);
    if (c == null) return null;
    int rawContactId = -1;
    if (c.moveToFirst()) {
        rawContactId = c.getInt(c.getColumnIndex(ContactsContract.RawContacts._ID));
    }
    c.close();
    return String.valueOf(rawContactId);
}

public void showSelectedNumber(int type, String number) {
    Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}
}

Thanks to the Stack Overflow community for helping me out. Hope this becomes helpful to others.


问:
How to select a link on microsoft edge using powershell?
I am writing a PowerShell script that requires the use of Microsoft Edge (internet explorer is blocked by admin) and needs to click on a link on a website. I was wondering what is the best approach on accomplishing this?

I have tried start using the start Microsoft edge process, but it does not allow me to interact with the site when opened.

start microsoft-edge:"https://google.com"

答:
I agree with the suggestion given by @ kuzimoto that you will not be able to click on link using PowerShell command.

You can try to download the selenium web driver from link below.

Download Selenium Web driver

This is the sample code to open specific web page and click on link on the page using Selenium C# code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Support.UI;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new EdgeDriver();

            driver.Navigate().GoToUrl(@"C:\Users\panchals\Desktop\tests\login_form.html");

            try
            {
                driver.FindElement(By.Name("demo_link")).Click();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();

            driver.Quit();
            driver.Close();
        }
    }
}
</code>```

HTML page code:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
<script>
function abc()
{
    alert("Logged in successfully.");
}

function xyz()
{
    alert("Link clicked by selenium code....");
}
</script>
</head>
<body>

<form action="">

  <div class="container">
    <label for="uname"><b>Username :</b></label>
    <input type="text" placeholder="Enter Username" name="uname"><br>

    <label for="psw"><b>Password : </b></label>
    <input type="password" placeholder="Enter Password" name="psw"><br>

    <button type="submit" name="signIn"  onclick="abc()">Login</button><br>
   <a href="" id="demo_link" name="demo_link" onclick="xyz()">Click me.......</a>
</form>

</body>
</html>
</code>```

Output in MS Edge:

Body:
I agree with the suggestion given by @ kuzimoto that you will not be able to click on link using PowerShell command.

You can try to download the selenium web driver from link below.

Download Selenium Web driver

This is the sample code to open specific web page and click on link on the page using Selenium C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Support.UI;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            IWebDriver driver = new EdgeDriver();

            driver.Navigate().GoToUrl(@"C:\Users\panchals\Desktop\tests\login_form.html");

            try
            {
                driver.FindElement(By.Name("demo_link")).Click();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();

            driver.Quit();
            driver.Close();
        }
    }
}

HTML page code:

<!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
<script>
function abc()
{
    alert("Logged in successfully.");
}

function xyz()
{
    alert("Link clicked by selenium code....");
}
</script>
</head>
<body>

<form action="">

  <div class="container">
    <label for="uname"><b>Username :</b></label>
    <input type="text" placeholder="Enter Username" name="uname"><br>

    <label for="psw"><b>Password : </b></label>
    <input type="password" placeholder="Enter Password" name="psw"><br>

    <button type="submit" name="signIn"  onclick="abc()">Login</button><br>
   <a href="" id="demo_link" name="demo_link" onclick="xyz()">Click me.......</a>
</form>

</body>
</html>

Output in MS Edge:


问:
How to reference every cell of another tab using indirect
I want to create a tab that will display all the cell values of another tab based on the tab name provided on a cell.

I have played around with the indirect function, but I cannot write a formula so that by dragging down and right it will access the cells.

```<code>=INDIRECT("'"&$A$1&"'!A1")
</code>```

This part &$A$1& is getting the name of the tab.
If I drag down this formula, the last A1 does not change though.

答:
You can use the formula ="Sheet2!A1" in Sheet1 Cell A1 and drag down, then across. I tried to find a faster way to paste it into every cell, but I had to force quit the application because it used all of my available memory. You might think about whether you actually need every cell to be duplicated into the second sheet. Good luck!

Edit: Just realized you were dead set on using Indirect. This should work.

```<code>=INDIRECT("'Sheet2'!"&CELL("address",A1))
</code>```

Body:
I want to create a tab that will display all the cell values of another tab based on the tab name provided on a cell.

I have played around with the indirect function, but I cannot write a formula so that by dragging down and right it will access the cells.

=INDIRECT("'"&$A$1&"'!A1")

This part &$A$1& is getting the name of the tab.
If I drag down this formula, the last A1 does not change though.

Body:
You can use the formula ="Sheet2!A1" in Sheet1 Cell A1 and drag down, then across. I tried to find a faster way to paste it into every cell, but I had to force quit the application because it used all of my available memory. You might think about whether you actually need every cell to be duplicated into the second sheet. Good luck!

Edit: Just realized you were dead set on using Indirect. This should work.

=INDIRECT("'Sheet2'!"&CELL("address",A1))


问:
Azure Graph API 2.0 error in refreshing token: Provided grant is invalid or malformed (AADSTS70000)
I'm following step by step guide on Microsoft's site (https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token), everything is working correctly but every time I try to refresh the access token, I get this error: AADSTS70000: Provided grant is invalid or malformed. error_codes: 70000.

I've created a Postman collection for testing, also downloaded the official postman collection from the Microsoft's site, everything is working correctly until the access token does not expire. When it expire, trying to refresh the token always lead to an error and I'm pretty stuck with it. I've double and triple checked correspondence between redirect_url, permission, grant, copy/paste errors, waited for the access_token to expire before trying to refresh... I've done almost 100 tests, and every time I'm stuck at the refresh part!

I start with doing the normal call to Microsoft Login API in my browser, and getting the code in query string from the browser (no problems here) (please note that client_id is URL encoded because, in my test environment, client id is an URL due to the configuration of the Drupal portan we're using, I'm truing to recreate the same behaviour in postman)

```<code>https://login.microsoftonline.com/{tenant_guid}/oauth2/v2.0/authorize?client_id={myclient_id_urlencoded}&response_type=code&redirect_uri={redirect_uri_urlencoded}&scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&state=12345
</code>```

Then with the code in query string, i POST to the token endpoint:

```<code>POST /{tenant_guid}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com

Content-Type: application/x-www-url-form-urlencoded
cache-control: no-cache
Postman-Token: a0456a8d-6979-491f-b61e-86b5d614c577

client_id={myclient_id_urlencoded}
scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
redirect_uri={redirect_uri_urlencoded}
grant_type=authorization_code
client_secret={client_secret_urlencoded}
code=OAQABAAIAAADCoMpjJXrxTq9VG9te-7FXujKZhF...
</code>```

I receive back an accesso token (that is working like a charm in accessing https://graph.microsoft.com/v1.0/me for an hour) and a refresh token. I would love to get a new pair of access/refresh token when the original access token expires, using the refresh_token grant_type

```<code>POST /tenant_guid/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com

Content-Type: application/x-www-url-form-urlencoded
cache-control: no-cache
Postman-Token: 5d71f813-768e-476c-a97f-c109fba3165e

client_id={myclient_id_urlencoded}
scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
redirect_uri={redirect_uri_urlencoded}
grant_type=refresh_token
cclient_secret={client_secret_urlencoded}
refresh_token=OAQABAAAAAADCoMpjJXrxTq9VG9te-7FX8m6YMg-.....
</code>```

But no matter if I try before access token expiration or after, closing and reopening postman, I always receive that error back.  I've done almost 50 tests (always with the full round of login/authorization to use always a fresh refresh token) with no luck.

Seems like I'm missing something really stupid here because I can't imagine that everybody else is behaving correctly... but really can't find a way out!

答:
So I just got mine working!  Here are the required parameters I needed:

```<code>client_id = your client id
refresh_token = the refresh token here
grant_type = refresh_token,
client_secret = secret
</code>```

NOTE:  Everything I read told me to URLEncode the values.  I found it worked with them UNENCODED - no idea if it will really make a difference or not.  Since it is going in the body of the post, which means it is TLS encrypted.

The other important thing was the url I posted to.  There seem to be so many examples and none seem to be consistent.  I used this format:

```<code>https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token
</code>```

The last thing is to be sure you are using the correct app id.  In my case I was using the appId for the wrong app and it didnt have consent.  Hope this helps.  I do wish Microsoft would make a concerted effort to spell out things consistently and think like someone who doesn't do security for a living.

Body:
I'm following step by step guide on Microsoft's site (https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#refresh-the-access-token), everything is working correctly but every time I try to refresh the access token, I get this error: AADSTS70000: Provided grant is invalid or malformed. error_codes: 70000.

I've created a Postman collection for testing, also downloaded the official postman collection from the Microsoft's site, everything is working correctly until the access token does not expire. When it expire, trying to refresh the token always lead to an error and I'm pretty stuck with it. I've double and triple checked correspondence between redirect_url, permission, grant, copy/paste errors, waited for the access_token to expire before trying to refresh... I've done almost 100 tests, and every time I'm stuck at the refresh part!

I start with doing the normal call to Microsoft Login API in my browser, and getting the code in query string from the browser (no problems here) (please note that client_id is URL encoded because, in my test environment, client id is an URL due to the configuration of the Drupal portan we're using, I'm truing to recreate the same behaviour in postman)

https://login.microsoftonline.com/{tenant_guid}/oauth2/v2.0/authorize?client_id={myclient_id_urlencoded}&response_type=code&redirect_uri={redirect_uri_urlencoded}&scope=offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&state=12345

Then with the code in query string, i POST to the token endpoint:

POST /{tenant_guid}/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com

Content-Type: application/x-www-url-form-urlencoded
cache-control: no-cache
Postman-Token: a0456a8d-6979-491f-b61e-86b5d614c577

client_id={myclient_id_urlencoded}
scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
redirect_uri={redirect_uri_urlencoded}
grant_type=authorization_code
client_secret={client_secret_urlencoded}
code=OAQABAAIAAADCoMpjJXrxTq9VG9te-7FXujKZhF...

I receive back an accesso token (that is working like a charm in accessing https://graph.microsoft.com/v1.0/me for an hour) and a refresh token. I would love to get a new pair of access/refresh token when the original access token expires, using the refresh_token grant_type

POST /tenant_guid/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com

Content-Type: application/x-www-url-form-urlencoded
cache-control: no-cache
Postman-Token: 5d71f813-768e-476c-a97f-c109fba3165e

client_id={myclient_id_urlencoded}
scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
redirect_uri={redirect_uri_urlencoded}
grant_type=refresh_token
cclient_secret={client_secret_urlencoded}
refresh_token=OAQABAAAAAADCoMpjJXrxTq9VG9te-7FX8m6YMg-.....

But no matter if I try before access token expiration or after, closing and reopening postman, I always receive that error back.  I've done almost 50 tests (always with the full round of login/authorization to use always a fresh refresh token) with no luck.

Seems like I'm missing something really stupid here because I can't imagine that everybody else is behaving correctly... but really can't find a way out!

Body:
So I just got mine working!  Here are the required parameters I needed:

client_id = your client id
refresh_token = the refresh token here
grant_type = refresh_token,
client_secret = secret

NOTE:  Everything I read told me to URLEncode the values.  I found it worked with them UNENCODED - no idea if it will really make a difference or not.  Since it is going in the body of the post, which means it is TLS encrypted.

The other important thing was the url I posted to.  There seem to be so many examples and none seem to be consistent.  I used this format:

https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token

The last thing is to be sure you are using the correct app id.  In my case I was using the appId for the wrong app and it didnt have consent.  Hope this helps.  I do wish Microsoft would make a concerted effort to spell out things consistently and think like someone who doesn't do security for a living.


问:
How can I filter out specific columns in a ndarray?
If you want specific columns in NumPy, you can do data[:, columnslist]. For example, if you want columns 1 and 9

data[:, [1, 9]]
```

<p>How can I do this using Rust's ndarray? I have gone through <code>ndarray</code> for NumPy users, but they don't have any similar example. Below is what I tried.</p>

```let a = arr2(&[[1., 2., 3.], [4., 5., 6.]]);
let b = stack(Axis(0), &[a.column(1).view(), a.column(2).view()]).unwrap();
let b = Array::from_iter(b.iter());
let b = b.reshape((2, 2));
```

<p>which gives the error:</p>

<pre class="lang-none prettyprint-override"><code>error[E0277]: the trait bound `ndarray::OwnedRepr<&{float}>: ndarray::data_traits::DataShared` is not satisfied
   --> src/main.rs:143:15
    |
143 |     let b = b.reshape((2,2));
    |               ^^^^^^^ the trait `ndarray::data_traits::DataShared` is not implemented for `ndarray::OwnedRepr<&{float}>`
</code>```

答:
According to the ndarray docs, reshape can only be used on an ArcArray. For any other array, use into_shape:

```<code>let b = b.into_shape((2, 2));
</code>```

Body:
If you want specific columns in NumPy, you can do data[:, columnslist]. For example, if you want columns 1 and 9

data[:, [1, 9]]

How can I do this using Rust's ndarray? I have gone through ndarray for NumPy users, but they don't have any similar example. Below is what I tried.

let a = arr2(&[[1., 2., 3.], [4., 5., 6.]]);
let b = stack(Axis(0), &[a.column(1).view(), a.column(2).view()]).unwrap();
let b = Array::from_iter(b.iter());
let b = b.reshape((2, 2));

which gives the error:

error[E0277]: the trait bound `ndarray::OwnedRepr<&{float}>: ndarray::data_traits::DataShared` is not satisfied
   --> src/main.rs:143:15
    |
143 |     let b = b.reshape((2,2));
    |               ^^^^^^^ the trait `ndarray::data_traits::DataShared` is not implemented for `ndarray::OwnedRepr<&{float}>`

Body:
According to the ndarray docs, reshape can only be used on an ArcArray. For any other array, use into_shape:

let b = b.into_shape((2, 2));


问:
Are Javascript arrays sparse?
That is, if I use the current time as an index into the array:

```<code>array[Date.getTime()] = value;
</code>```

will the interpreter instantiate all the elements from 0 to now?  Do different browsers do it differently?

I remember there used to be a bug in the AIX kernel, which would create pseudo-ttys on request, but if you did, say, "echo > /dev/pty10000000000" it would create /dev/pty0, /dev/pty1, .... and then fall over dead.  It was fun at trade shows, but I don't want this to happen to my customers.

答:
The answer, as is usually true with JavaScript, is "it's a bit wierder...."

Memory usage is not defined and any implementation is allowed to be stupid.  In theory, const a = []; a[1000000]=0; could burn megabytes of memory, as could const a = [];.  In practice, even Microsoft avoids those implementations.

Justin Love points out, the length attribute is the highest index set.  BUT its only updated if the index is an integer.

So, the array is sparse.  BUT built-in functions like reduce(), Math.max(), and "for ... of" will walk through the entire range of possible integer indices form 0 to the length, visiting many that return 'undefined'.  BUT 'for ... in' loops might do as you expect, visiting only the defined keys.

Here's an example using Node.js:

```<code>"use strict";
const print = console.log;

let a = [0, 10];
// a[2] and a[3] skipped
a[4] = 40;
a[5] = undefined;  // which counts towards setting the length
a[31.4] = 'ten pi';  // doesn't count towards setting the length
a['pi'] = 3.14;
print(`a.length= :${a.length}:, a = :${a}:`);
print(`Math.max(...a) = :${Math.max(a)}: because of 'undefined values'`);
for (let v of a) print(`v of a; v=:${v}:`);
for (let i in a) print(`i in a; i=:${i}: a[i]=${a[i]}`);
</code>```

giving:

```<code>a.length= :6:, a = :0,10,,,40,:
Math.max(...a) = :NaN: because of 'undefined values'
v of a; v=:0:
v of a; v=:10:
v of a; v=:undefined:
v of a; v=:undefined:
v of a; v=:40:
v of a; v=:undefined:
i in a; i=:0: a[i]=0
i in a; i=:1: a[i]=10
i in a; i=:4: a[i]=40
i in a; i=:5: a[i]=undefined
i in a; i=:31.4: a[i]=ten pi
i in a; i=:pi: a[i]=3.14
</code>```

But.  There are more corner cases with Arrays not yet mentioned.

Title: Are Javascript arrays sparse?

Body:
That is, if I use the current time as an index into the array:

array[Date.getTime()] = value;

will the interpreter instantiate all the elements from 0 to now?  Do different browsers do it differently?

I remember there used to be a bug in the AIX kernel, which would create pseudo-ttys on request, but if you did, say, "echo > /dev/pty10000000000" it would create /dev/pty0, /dev/pty1, .... and then fall over dead.  It was fun at trade shows, but I don't want this to happen to my customers.

Body:
The answer, as is usually true with JavaScript, is "it's a bit wierder...."

Memory usage is not defined and any implementation is allowed to be stupid.  In theory, const a = []; a[1000000]=0; could burn megabytes of memory, as could const a = [];.  In practice, even Microsoft avoids those implementations.

Justin Love points out, the length attribute is the highest index set.  BUT its only updated if the index is an integer.

So, the array is sparse.  BUT built-in functions like reduce(), Math.max(), and "for ... of" will walk through the entire range of possible integer indices form 0 to the length, visiting many that return 'undefined'.  BUT 'for ... in' loops might do as you expect, visiting only the defined keys.

Here's an example using Node.js:

"use strict";
const print = console.log;

let a = [0, 10];
// a[2] and a[3] skipped
a[4] = 40;
a[5] = undefined;  // which counts towards setting the length
a[31.4] = 'ten pi';  // doesn't count towards setting the length
a['pi'] = 3.14;
print(`a.length= :${a.length}:, a = :${a}:`);
print(`Math.max(...a) = :${Math.max(a)}: because of 'undefined values'`);
for (let v of a) print(`v of a; v=:${v}:`);
for (let i in a) print(`i in a; i=:${i}: a[i]=${a[i]}`);

giving:

a.length= :6:, a = :0,10,,,40,:
Math.max(...a) = :NaN: because of 'undefined values'
v of a; v=:0:
v of a; v=:10:
v of a; v=:undefined:
v of a; v=:undefined:
v of a; v=:40:
v of a; v=:undefined:
i in a; i=:0: a[i]=0
i in a; i=:1: a[i]=10
i in a; i=:4: a[i]=40
i in a; i=:5: a[i]=undefined
i in a; i=:31.4: a[i]=ten pi
i in a; i=:pi: a[i]=3.14

But.  There are more corner cases with Arrays not yet mentioned.


问:
Which is the referenced object of an interface variable containing an object of a class which implements the interface?
I have created a Motor class which implements the Measurable interface.
Then I create a variable of type Measurable called motorTemperature.

If I...

```<code> Measurable motorTemperature = new Motor (x);
</code>```

which will be the object referenced by motorTemperature? (Motor or Measurable type?

答:
In this code:

```<code>Measurable motorTemperature = new Motor(x);
</code>```

we create an object of type Motor. It is a Motor and will remain a Motor.

The Motor implements the Measurable interface. We can therefore assign a reference to our Motor to a variable of type Measurable (and we in fact do so).  This does not change the fact that the Motor is a Motor.

However, since the only reference we have now got to our Motor is this Measurable, our only access to it can only speak in terms of what can be expressed via the Measurable interface.  We can't ask it about any Motor properties nor ask it to do Motor actions that are not defined as methods in Measurable.

P.S. whether or not motorTemperature is a good name for a Measurable is a separate question. If the only measurement available from a Motor is its temperature, that might make sense.  If we can call 'motorTemperature.getRPM()' then the name seems less appropriate.

Body:
I have created a Motor class which implements the Measurable interface.
Then I create a variable of type Measurable called motorTemperature.

If I...

 Measurable motorTemperature = new Motor (x);

which will be the object referenced by motorTemperature? (Motor or Measurable type?

Body:
In this code:

Measurable motorTemperature = new Motor(x);

we create an object of type Motor. It is a Motor and will remain a Motor.

The Motor implements the Measurable interface. We can therefore assign a reference to our Motor to a variable of type Measurable (and we in fact do so).  This does not change the fact that the Motor is a Motor.

However, since the only reference we have now got to our Motor is this Measurable, our only access to it can only speak in terms of what can be expressed via the Measurable interface.  We can't ask it about any Motor properties nor ask it to do Motor actions that are not defined as methods in Measurable.

P.S. whether or not motorTemperature is a good name for a Measurable is a separate question. If the only measurement available from a Motor is its temperature, that might make sense.  If we can call 'motorTemperature.getRPM()' then the name seems less appropriate.


问:
Compiler Warning C4251: Problem exporting a class in a *.dll
EDIT: Forgive my noobish-ness, I haven't ever implemented a wrapper .dll before! :S

I've been tinkering a bit with some of the recently released Kinect Sensor hacks (namely OpenKinect and OpenNI) and I'm now trying to wrap the functionality in a *.dll for use in various "test" programs that I hope to write.

So far I've set up a *.dll project and have got a lot of the library functionality in, however I'm getting C4251 compiler warnings all over the place.

In the project settings I've got the OpenNI.lib file statically linked, so far my library header looks like this:

```<code>#ifdef LIBKINECT_EXPORTS
#define LIBKINECT_API __declspec(dllexport)
#else
#define LIBKINECT_API __declspec(dllimport)
#endif

// This class is exported from the LibKinect.dll
class LIBKINECT_API CLibKinect
{
public:

    CLibKinect(void);
    ~CLibKinect(void);

    bool Init(void);

protected:

private:

    xn::Context                     m_xContext;
    xn::DepthGenerator              m_xDepthGen;
};
</code>```

And my stdafx.h file contains:

```<code>#pragma once

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
</code>```

Now I've attempted to create a windows console app to test the library and I get lots of error C2653: 'xn' : is not a class or namespace name errors. I was hoping that in the application I would only have to include and link to the wrapper *.dll not all of the OpenNI stuff as well, so as to hide the underlying implementation, is this incorrect?

答: Since you want to hide the fact you are using xn namespace in your implementation, you should not put that in the library header file. The simplest way to solve this problem is to use the pimpl idiom.

Body:
EDIT: Forgive my noobish-ness, I haven't ever implemented a wrapper .dll before! :S

I've been tinkering a bit with some of the recently released Kinect Sensor hacks (namely OpenKinect and OpenNI) and I'm now trying to wrap the functionality in a *.dll for use in various "test" programs that I hope to write.

So far I've set up a *.dll project and have got a lot of the library functionality in, however I'm getting C4251 compiler warnings all over the place.

In the project settings I've got the OpenNI.lib file statically linked, so far my library header looks like this:

#ifdef LIBKINECT_EXPORTS
#define LIBKINECT_API __declspec(dllexport)
#else
#define LIBKINECT_API __declspec(dllimport)
#endif

// This class is exported from the LibKinect.dll
class LIBKINECT_API CLibKinect
{
public:

    CLibKinect(void);
    ~CLibKinect(void);

    bool Init(void);

protected:

private:

    xn::Context                     m_xContext;
    xn::DepthGenerator              m_xDepthGen;
};

And my stdafx.h file contains:

#pragma once

#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>

Now I've attempted to create a windows console app to test the library and I get lots of error C2653: 'xn' : is not a class or namespace name errors. I was hoping that in the application I would only have to include and link to the wrapper *.dll not all of the OpenNI stuff as well, so as to hide the underlying implementation, is this incorrect?


问:
How to detect in iOS webapp when switching back to Safari from background?
How can I build a webpage which is able to monitor when the page gets the focus, especially when Safari is in the background and the user switches Safari back to the foreground.

The code below does not fire the event when switching to Safari on an iPhone

```<code><html>
  <head>
    <script type="text/javascript">
      window.onfocus = function() { alert("onfocus"); };
    </script>
  </head>
  <body>

    Main text

  </body>
</html>
</code>```

According http://www.quirksmode.org/dom/events/index.html : Safari iPhone does not fire the event when the window gains the focus.

So my question is still: how to detect by using Javascript on a web page within Safari for iPhone that the window receives the focus?

答:
I wrote a little test page to see what events are being sent to the window on iOS.

The page is "Apple web app capable", so you can save it to the home screen and test it in standalone mode.

Here's the page: Test of Window Events

The code:

// determine if this is a touch-capable device
const isTouchDevice = ('ontouchstart' in window) ||
  (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0);
console.log(`isTouchDevice: ${isTouchDevice ? 'TRUE' : 'FALSE'} `);

const button = document.getElementById('btnClear');
const divEvents = document.getElementById('divEvents');
const olEvents = document.getElementById('olEvents');
const divBottom = document.getElementById('divBottom');

// handle "clear history" button click
button.addEventListener('click', function() {
  if (isTouchDevice) {
    // simulate click on button using `focus` and `blur`
    button.focus();
    setTimeout(() => button.blur(), 500);
  }
  olEvents.innerHTML = '';
});

const eventNames = [
  'load',
  'focus',
  'blur',
  'change',
  'close',
  'error',
  'haschange',
  'message',
  'offline',
  'online',
  'pagehide',
  'pageshow',
  'popstate',
  'resize',
  'submit',
  'unload',
  'beforeunload'
];
eventNames.forEach(function(eventName) {
  window.addEventListener(eventName, function(evt) {
    const now = new Date();
    const timeStr = now.getHours().toString().padStart(2, '0') + ':' +
      now.getMinutes().toString().padStart(2, '0') + ':' +
      now.getSeconds().toString().padStart(2, '0') + '.' +
      now.getMilliseconds();
    let li = document.createElement('li');
    li.innerHTML = timeStr + ' - ' + `<code>${evt.type}</code>`;
    olEvents.appendChild(li);

    // scroll to bottom
    // window.scrollTo(0, divBottom.offsetTop);
    const bottomOffset = divBottom.offsetTop;
    divEvents.scrollTop = bottomOffset - 10;
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#divEvents {
  border: 1px solid rgba(0, 0, 0, 0.5);
  height: 400px;
  max-width: 60rem;
  padding: 1rem 0;
  overflow-y: auto;
}

#olEvents {
  font-size: 87.5%;
}

#divBottom {
  height: 0px;
}

code {
  font-size: 100%;
}

/* handle the sticky hover problem on touch devices */

@media (hover:none) {
  /* set button hover style to match non-hover */
  .btn-outline-primary:hover {
    color: #007bff;
    background-color: transparent;
    background-image: none;
    border-color: #007bff;
  }
  /* set button focus style to match hover */
  .btn-outline-primary:focus {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
  }
}</code>```

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, shrink-to-fit=no, user-scalable=no">

  <meta name="apple-mobile-web-app-title" content="WinEvents">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <title>Test of Window Events</title>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootsdark@latest/dist/bootsdark.min.css">

      Terry Morse
      Software

Test of Window Events

Displays all of the events (except for
      scroll) sent to document.window.

      <button id="btnClear" class="btn btn-sm btn-outline-primary"
      >Clear History</button>

Events Caught:

```

Body:
How can I build a webpage which is able to monitor when the page gets the focus, especially when Safari is in the background and the user switches Safari back to the foreground.

The code below does not fire the event when switching to Safari on an iPhone

    Main text

According http://www.quirksmode.org/dom/events/index.html : Safari iPhone does not fire the event when the window gains the focus.

So my question is still: how to detect by using Javascript on a web page within Safari for iPhone that the window receives the focus?

Body:
I wrote a little test page to see what events are being sent to the window on iOS.

The page is "Apple web app capable", so you can save it to the home screen and test it in standalone mode.

Here's the page: Test of Window Events

The code:

// determine if this is a touch-capable device
const isTouchDevice = ('ontouchstart' in window) ||
  (navigator.maxTouchPoints > 0) || (navigator.msMaxTouchPoints > 0);
console.log(`isTouchDevice: ${isTouchDevice ? 'TRUE' : 'FALSE'} `);

const button = document.getElementById('btnClear');
const divEvents = document.getElementById('divEvents');
const olEvents = document.getElementById('olEvents');
const divBottom = document.getElementById('divBottom');

// handle "clear history" button click
button.addEventListener('click', function() {
  if (isTouchDevice) {
    // simulate click on button using `focus` and `blur`
    button.focus();
    setTimeout(() => button.blur(), 500);
  }
  olEvents.innerHTML = '';
});

const eventNames = [
  'load',
  'focus',
  'blur',
  'change',
  'close',
  'error',
  'haschange',
  'message',
  'offline',
  'online',
  'pagehide',
  'pageshow',
  'popstate',
  'resize',
  'submit',
  'unload',
  'beforeunload'
];
eventNames.forEach(function(eventName) {
  window.addEventListener(eventName, function(evt) {
    const now = new Date();
    const timeStr = now.getHours().toString().padStart(2, '0') + ':' +
      now.getMinutes().toString().padStart(2, '0') + ':' +
      now.getSeconds().toString().padStart(2, '0') + '.' +
      now.getMilliseconds();
    let li = document.createElement('li');
    li.innerHTML = timeStr + ' - ' + `<code>${evt.type}</code>`;
    olEvents.appendChild(li);

    // scroll to bottom
    // window.scrollTo(0, divBottom.offsetTop);
    const bottomOffset = divBottom.offsetTop;
    divEvents.scrollTop = bottomOffset - 10;
  });
});

#divEvents {
  border: 1px solid rgba(0, 0, 0, 0.5);
  height: 400px;
  max-width: 60rem;
  padding: 1rem 0;
  overflow-y: auto;
}

#olEvents {
  font-size: 87.5%;
}

#divBottom {
  height: 0px;
}

code {
  font-size: 100%;
}

/* handle the sticky hover problem on touch devices */

@media (hover:none) {
  /* set button hover style to match non-hover */
  .btn-outline-primary:hover {
    color: #007bff;
    background-color: transparent;
    background-image: none;
    border-color: #007bff;
  }
  /* set button focus style to match hover */
  .btn-outline-primary:focus {
    color: #fff;
    background-color: #007bff;
    border-color: #007bff;
  }
}

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, shrink-to-fit=no, user-scalable=no">

  <!-- apple web app meta tags -->
  <meta name="apple-mobile-web-app-title" content="WinEvents">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">

  <title>Test of Window Events</title>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootsdark@latest/dist/bootsdark.min.css">

</head>

<body class="d-flex flex-column h-100">
  <header>
    <!-- Fixed navbar -->
    <nav class="navbar navbar-expand-md navbar-dark bg-dark">
      <a class="navbar-brand" href="https://terrymorse.com">Terry Morse
      Software</a>
    </nav>
  </header>

  <main role="main" class="flex-shrink-0 m-4">
    <h1>Test of Window Events</h1>

    <p>Displays all of the events (except for
      <code>scroll</code>) sent to <code>document.window</code>.</p>

    <p>
      <button id="btnClear" class="btn btn-sm btn-outline-primary"
      >Clear History</button>
    </p>

    <h4>Events Caught:</h4>
    <div id="divEvents">
      <ol id="olEvents" class="text-monospace"></ol>
      <div id="divBottom"></div>
    </div>
  </main>

</body>


问:
Cache Busting with Laravel
I've been developing a system and every time I update anything on the public folder, each computers must always clear their cache in order for it to take effect.

I've only been coding directly on to the public folder for the js and css files. When I push it to my git repository and pull it to our shared hosting through ssh after that I copy it to the public_html folder through ssh as well, all client computers still need to clear their caches manually in order for new public files to take effect. I've been studying a bit of laravel mix however I am still unsure how to actually use it in a live hosting.

I am unsure if cache busting is the right term at this time but I wanted my client computers to use the latest assets every time I update our system.

答:
Laravel has a built-in system for compiling assets like CSS and JavaScript, which includes a versioning system that ensures when you push a new version, users receive those updated assets.</p>

```<code>mix.js('resources/js/app.js', 'public/js')
   .version();
</code>```

Title: Cache Busting with Laravel

Body:
Laravel has a built-in system for compiling assets like CSS and JavaScript, which includes a versioning system that ensures when you push a new version, users receive those updated assets.

mix.js('resources/js/app.js', 'public/js')
   .version();


问:
Changing the backgroundColor of react mateial-ui Select MuiList
I would like to change the react material-ui Select MuiList backgroundColor containing the MenuItems.

This is without overriding the styles for all Select and MuiList's. (Changing only the Select name='first' from the below codesandbox.)

I have set the className and tried some classes for the Select element but am unable to see any changes to the MuiList wrapping the MenuItem's.

```<code><Select
  name='tag'
  classes=
    { {
      'root': 'thinger1',
      'selectMenu': 'thinger2',
      'MuiList': {root:  'thinger3'}
    } }
  onChange={this.handleChange}
  className={[classes.lightGreyBackground].join(' ')}
>

</code>```

How to override material-ui MenuItem selected background color? This changes only the selected. I would like to change the whole thing.

This is for material-ui 3.9.3.

```<code>      <div>
        <TextField select name="first" value={1} fullWidth>
          <MenuItem value={1}>1</MenuItem>
          <MenuItem value={2}>2</MenuItem>
        </TextField>
      </div>
</code>```

https://y5q03.codesandbox.io/

I am hoping to see the ul MuiList containing the MenuItem's (including the rounded top and bottom padding) backgroundColor #999.

答:
If you're doing it like that, you'll have to pass down props all the way to the Menu.

const styles = theme => ({
  menuBg: {
    backgroundColor: "#999" //or whatever you want it to be
  }
});

const YourComponent = props => (
  <TextField select name="first" value={1} fullWidth
    SelectProps={{
      MenuProps: {
        classes: { paper: props.classes.menuBg }
      }
    }}
  >
      <MenuItem value={1}>1</MenuItem>
      <MenuItem value={2}>2</MenuItem>
   </TextField>
);

YourComponent = withStyles(styles)(YourComponent);```

Body:
I would like to change the react material-ui Select MuiList backgroundColor containing the MenuItems.

This is without overriding the styles for all Select and MuiList's. (Changing only the Select name='first' from the below codesandbox.)

I have set the className and tried some classes for the Select element but am unable to see any changes to the MuiList wrapping the MenuItem's.

<Select
  name='tag'
  classes=
    { {
      'root': 'thinger1',
      'selectMenu': 'thinger2',
      'MuiList': {root:  'thinger3'}
    } }
  onChange={this.handleChange}
  className={[classes.lightGreyBackground].join(' ')}
>

How to override material-ui MenuItem selected background color? This changes only the selected. I would like to change the whole thing.

This is for material-ui 3.9.3.

        <TextField select name="first" value={1} fullWidth>
          <MenuItem value={1}>1</MenuItem>
          <MenuItem value={2}>2</MenuItem>
        </TextField>

https://y5q03.codesandbox.io/

I am hoping to see the ul MuiList containing the MenuItem's (including the rounded top and bottom padding) backgroundColor #999.


问:
LinkedList in swift with node as structure
Can anyone tell me how to create a linked-list in swift with node as structure and linked-list as class.

I tried to create a node Node with reference to itself and faced a error "value type 'Node' cannot have a stored property that references itself"

for resolving it i created one more class Next
and now I am unable to proceed further.

答:
Custom LinkedList Type

Xcode 10.2.1, Swift 5.0

My LinkedList type implements all of the following protocols:

CustomStringConvertible

ExpressibleByArrayLiteral

Sequence

Collection

MutableCollection

RangeReplaceableCollection

BidirectionalCollection

As well, it keeps its node type private so the user never needs to know anything of its existence.

This implementation is a doubly linked list so to efficiently enable bidirectional traversal.

Code:

public struct LinkedList<Element> {

    private var headNode: Node?
    private var tailNode: Node?
    public private(set) var count: Int = 0
    private var id = ID()
    public init() { }

    fileprivate class ID {
        init() { }
    }
}

//MARK: - LinkedList Node
extension LinkedList {

    fileprivate class Node {
        public var value: Element
        public var next: Node?
        public weak var previous: Node?

        public init(value: Element) {
            self.value = value
        }
    }

}

//MARK: - Initializers
public extension LinkedList {

    private init(_ nodeChain: (head: Node, tail: Node, count: Int)?) {
        guard let chain = nodeChain else {
            return
        }
        headNode = chain.head
        tailNode = chain.tail
        count = chain.count
    }

    init<S>(_ sequence: S) where S: Sequence, S.Element == Element {
        if let linkedList = sequence as? LinkedList<Element> {
            self = linkedList
        } else {
            self = LinkedList(chain(of: sequence))
        }
    }

}

//MARK: Chain of Nodes
extension LinkedList {
    // Creates a chain of nodes from a sequence. Returns `nil` if the sequence is empty.
    private func chain<S>(of sequence: S) -> (head: Node, tail: Node, count: Int)? where S: Sequence, S.Element == Element {
        var iterator = sequence.makeIterator()
        var head, tail: Node
        var count = 0
        guard let firstValue = iterator.next() else {
            return nil
        }

        var currentNode = Node(value: firstValue)
        head = currentNode
        count = 1

        while let nextElement = iterator.next() {
            let nextNode = Node(value: nextElement)
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            count += 1
        }
        tail = currentNode
        return (head: head, tail: tail, count: count)
    }
}

//MARK: - Copy Nodes
extension LinkedList {

    private mutating func copyNodes(settingNodeAt index: Index, to value: Element) {

        var currentIndex = startIndex
        var currentNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
        let newHeadNode = currentNode
        currentIndex = self.index(after: currentIndex)

        while currentIndex < endIndex {
            let nextNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            currentIndex = self.index(after: currentIndex)
        }
        headNode = newHeadNode
        tailNode = currentNode
    }

    @discardableResult
    private mutating func copyNodes(removing range: Range<Index>) -> Range<Index> {

        id = ID()
        var currentIndex = startIndex

        while range.contains(currentIndex) {
            currentIndex = index(after: currentIndex)
        }

        guard let headValue = currentIndex.node?.value else {
            self = LinkedList()
            return endIndex..<endIndex
        }

        var currentNode = Node(value: headValue)
        let newHeadNode = currentNode
        var newCount = 1

        var removedRange: Range<Index> = Index(node: currentNode, offset: 0, id: id)..<Index(node: currentNode, offset: 0, id: id)
        currentIndex = index(after: currentIndex)

        while currentIndex < endIndex {
            guard !range.contains(currentIndex) else {
                currentIndex = index(after: currentIndex)
                continue
            }

            let nextNode = Node(value: currentIndex.node!.value)
            if currentIndex == range.upperBound {
                removedRange = Index(node: nextNode, offset: newCount, id: id)..<Index(node: nextNode, offset: newCount, id: id)
            }
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            newCount += 1
            currentIndex = index(after: currentIndex)

        }
        if currentIndex == range.upperBound {
            removedRange = Index(node: nil, offset: newCount, id: id)..<Index(node: nil, offset: newCount, id: id)
        }
        headNode = newHeadNode
        tailNode = currentNode
        count = newCount
        return removedRange
    }

}

//MARK: - Computed Properties
public extension LinkedList {
    var head: Element? {
        return headNode?.value
    }

    var tail: Element? {
        return tailNode?.value
    }
}

//MARK: - Sequence Conformance
extension LinkedList: Sequence {

    public typealias Element = Element

    public __consuming func makeIterator() -> Iterator {
        return Iterator(node: headNode)
    }

    public struct Iterator: IteratorProtocol {

        private var currentNode: Node?

        fileprivate init(node: Node?) {
            currentNode = node
        }

        public mutating func next() -> Element? {
            guard let node = currentNode else {
                return nil
            }
            currentNode = node.next
            return node.value
        }

    }
}

//MARK: - Collection Conformance
extension LinkedList: Collection {

    public var startIndex: Index {
        return Index(node: headNode, offset: 0, id: id)
    }

    public var endIndex: Index {
        return Index(node: nil, offset: count, id: id)
    }

    public var first: Element? {
        return head
    }

    public var isEmpty: Bool {
        return count == 0
    }

    public func index(after i: Index) -> Index {
        precondition(i.listID === self.id, "LinkedList index is invalid")
        precondition(i.offset != endIndex.offset, "LinkedList index is out of bounds")
        return Index(node: i.node?.next, offset: i.offset + 1, id: id)
    }

    public struct Index: Comparable {
        fileprivate weak var node: Node?
        fileprivate var offset: Int
        fileprivate weak var listID: ID?

        fileprivate init(node: Node?, offset: Int, id: ID) {
            self.node = node
            self.offset = offset
            self.listID = id
        }

        public static func ==(lhs: Index, rhs: Index) -> Bool {
            return lhs.offset == rhs.offset
        }

        public static func <(lhs: Index, rhs: Index) -> Bool {
            return lhs.offset < rhs.offset
        }
    }

}

//MARK: - MutableCollection Conformance
extension LinkedList: MutableCollection {

    public subscript(position: Index) -> Element {
        get {
            precondition(position.listID === self.id, "LinkedList index is invalid")
            precondition(position.offset != endIndex.offset, "Index out of range")
            guard let node = position.node else {
                preconditionFailure("LinkedList index is invalid")
            }
            return node.value
        }
        set {
            precondition(position.listID === self.id, "LinkedList index is invalid")
            precondition(position.offset != endIndex.offset, "Index out of range")

            // Copy-on-write semantics for nodes
            if !isKnownUniquelyReferenced(&headNode) {
                copyNodes(settingNodeAt: position, to: newValue)
            } else {
                position.node?.value = newValue
            }
        }
    }
}

//MARK: LinkedList Specific Operations
public extension LinkedList {

    mutating func prepend(_ newElement: Element) {
        replaceSubrange(startIndex..<startIndex, with: CollectionOfOne(newElement))
    }

    mutating func prepend<S>(contentsOf newElements: __owned S) where S: Sequence, S.Element == Element {
        replaceSubrange(startIndex..<startIndex, with: newElements)
    }

    @discardableResult
    mutating func popFirst() -> Element? {
        if isEmpty {
            return nil
        }
        return removeFirst()
    }

    @discardableResult
    mutating func popLast() -> Element? {
        if isEmpty {
            return nil
        }
        return removeLast()
    }
}

//MARK: - BidirectionalCollection Conformance
extension LinkedList: BidirectionalCollection {
    public var last: Element? {
        return tail
    }

    public func index(before i: Index) -> Index {
        precondition(i.listID === self.id, "LinkedList index is invalid")
        precondition(i.offset != startIndex.offset, "LinkedList index is out of bounds")
        if i.offset == count {
            return Index(node: tailNode, offset: i.offset - 1, id: id)
        }
        return Index(node: i.node?.previous, offset: i.offset - 1, id: id)
    }

}

//MARK: - RangeReplaceableCollection Conformance
extension LinkedList: RangeReplaceableCollection {
    public mutating func append<S>(contentsOf newElements: __owned S) where S: Sequence, Element == S.Element {
        replaceSubrange(endIndex..<endIndex, with: newElements)
    }

    public mutating func replaceSubrange<S, R>(_ subrange: R, with newElements: __owned S) where S: Sequence, R: RangeExpression, Element == S.Element, Index == R.Bound {

        var range = subrange.relative(to: indices)
        precondition(range.lowerBound.listID === id && range.upperBound.listID === id, "LinkedList range of indices are invalid")
        precondition(range.lowerBound >= startIndex && range.upperBound <= endIndex, "Subrange bounds are out of range")

        // If range covers all elements and the new elements are a LinkedList then set references to it
        if range.lowerBound == startIndex, range.upperBound == endIndex, let linkedList = newElements as? LinkedList {
            self = linkedList
            return
        }

        var newElementsCount = 0

        // There are no new elements, so range indicates deletion
        guard let nodeChain = chain(of: newElements) else {

            // If there is nothing in the removal range
            // This also covers the case that the linked list is empty because this is the only possible range
            guard range.lowerBound != range.upperBound else {
                return
            }

            // Deletion range spans all elements
            if range.lowerBound == startIndex && range.upperBound == endIndex {
                headNode = nil
                tailNode = nil
                count = 0
                return
            }

            // Copy-on-write semantics for nodes and remove elements in range
            guard isKnownUniquelyReferenced(&headNode) else {
                copyNodes(removing: range)
                return
            }

            // Update count after mutation to preserve startIndex and endIndex validity
            defer {
                count = count - (range.upperBound.offset - range.lowerBound.offset)
            }

            // Move head up if deletion starts at start index
            if range.lowerBound == startIndex {
                // Can force unwrap node since the upperBound is not the end index
                headNode = range.upperBound.node!
                headNode!.previous = nil

                // Move tail back if deletion ends at end index
            } else if range.upperBound == endIndex {
                // Can force unwrap since lowerBound index must have an associated element
                tailNode = range.lowerBound.node!.previous
                tailNode!.next = nil

                // Deletion range is in the middle of the linked list
            } else {
                // Can force unwrap all bound nodes since they both must have elements
                range.upperBound.node!.previous = range.lowerBound.node!.previous
                range.lowerBound.node!.previous!.next = range.upperBound.node!
            }

            return
        }

        // Obtain the count of the new elements from the node chain composed from them
        newElementsCount = nodeChain.count

        // Replace entire content of list with new elements
        if range.lowerBound == startIndex && range.upperBound == endIndex {
            headNode = nodeChain.head
            tailNode = nodeChain.tail
            count = nodeChain.count
            return
        }

        // Copy-on-write semantics for nodes before mutation
        if !isKnownUniquelyReferenced(&headNode) {
            range = copyNodes(removing: range)
        }

        // Update count after mutation to preserve startIndex and endIndex validity
        defer {
            count += nodeChain.count - (range.upperBound.offset - range.lowerBound.offset)
        }

        // Prepending new elements
        guard range.upperBound != startIndex else {
            headNode?.previous = nodeChain.tail
            nodeChain.tail.next = headNode
            headNode = nodeChain.head
            return
        }

        // Appending new elements
        guard range.lowerBound != endIndex else {
            tailNode?.next = nodeChain.head
            nodeChain.head.previous = tailNode
            tailNode = nodeChain.tail
            return
        }

        if range.lowerBound == startIndex {
            headNode = nodeChain.head
        }
        if range.upperBound == endIndex {
            tailNode = nodeChain.tail
        }

        range.lowerBound.node!.previous!.next = nodeChain.head
        range.upperBound.node!.previous = nodeChain.tail
    }

}

//MARK: - ExpressibleByArrayLiteral Conformance
extension LinkedList: ExpressibleByArrayLiteral {
    public typealias ArrayLiteralElement = Element

    public init(arrayLiteral elements: ArrayLiteralElement...) {
        self.init(elements)
    }
}

//MARK: - CustomStringConvertible Conformance
extension LinkedList: CustomStringConvertible {
    public var description: String {
        return "[" + lazy.map { "\($0)" }.joined(separator: ", ") + "]"
    }
}

//MARK: - Equatable Conformance
extension LinkedList: Equatable where Element: Equatable {
    public static func ==(lhs: LinkedList<Element>, rhs: LinkedList<Element>) -> Bool {
        for (a, b) in zip(lhs, rhs) {
            guard a == b else {
                return false
            }
        }
        return true
    }
}

```

If you'd like to use this type fully-documented in your own project, feel free to download it or add it as a dependency with Swift PM by checking out my LinkedList GitHub repository.

Body:
Custom LinkedList Type

Xcode 10.2.1, Swift 5.0

My LinkedList type implements all of the following protocols:

CustomStringConvertible

ExpressibleByArrayLiteral

Sequence

Collection

MutableCollection

RangeReplaceableCollection

BidirectionalCollection

As well, it keeps its node type private so the user never needs to know anything of its existence.

This implementation is a doubly linked list so to efficiently enable bidirectional traversal.

Code:

public struct LinkedList<Element> {

    private var headNode: Node?
    private var tailNode: Node?
    public private(set) var count: Int = 0
    private var id = ID()
    public init() { }

    fileprivate class ID {
        init() { }
    }
}

//MARK: - LinkedList Node
extension LinkedList {

    fileprivate class Node {
        public var value: Element
        public var next: Node?
        public weak var previous: Node?

        public init(value: Element) {
            self.value = value
        }
    }

}

//MARK: - Initializers
public extension LinkedList {

    private init(_ nodeChain: (head: Node, tail: Node, count: Int)?) {
        guard let chain = nodeChain else {
            return
        }
        headNode = chain.head
        tailNode = chain.tail
        count = chain.count
    }

    init<S>(_ sequence: S) where S: Sequence, S.Element == Element {
        if let linkedList = sequence as? LinkedList<Element> {
            self = linkedList
        } else {
            self = LinkedList(chain(of: sequence))
        }
    }

}

//MARK: Chain of Nodes
extension LinkedList {
    // Creates a chain of nodes from a sequence. Returns `nil` if the sequence is empty.
    private func chain<S>(of sequence: S) -> (head: Node, tail: Node, count: Int)? where S: Sequence, S.Element == Element {
        var iterator = sequence.makeIterator()
        var head, tail: Node
        var count = 0
        guard let firstValue = iterator.next() else {
            return nil
        }

        var currentNode = Node(value: firstValue)
        head = currentNode
        count = 1

        while let nextElement = iterator.next() {
            let nextNode = Node(value: nextElement)
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            count += 1
        }
        tail = currentNode
        return (head: head, tail: tail, count: count)
    }
}

//MARK: - Copy Nodes
extension LinkedList {

    private mutating func copyNodes(settingNodeAt index: Index, to value: Element) {

        var currentIndex = startIndex
        var currentNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
        let newHeadNode = currentNode
        currentIndex = self.index(after: currentIndex)

        while currentIndex < endIndex {
            let nextNode = Node(value: currentIndex == index ? value : currentIndex.node!.value)
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            currentIndex = self.index(after: currentIndex)
        }
        headNode = newHeadNode
        tailNode = currentNode
    }

    @discardableResult
    private mutating func copyNodes(removing range: Range<Index>) -> Range<Index> {

        id = ID()
        var currentIndex = startIndex

        while range.contains(currentIndex) {
            currentIndex = index(after: currentIndex)
        }

        guard let headValue = currentIndex.node?.value else {
            self = LinkedList()
            return endIndex..<endIndex
        }

        var currentNode = Node(value: headValue)
        let newHeadNode = currentNode
        var newCount = 1

        var removedRange: Range<Index> = Index(node: currentNode, offset: 0, id: id)..<Index(node: currentNode, offset: 0, id: id)
        currentIndex = index(after: currentIndex)

        while currentIndex < endIndex {
            guard !range.contains(currentIndex) else {
                currentIndex = index(after: currentIndex)
                continue
            }

            let nextNode = Node(value: currentIndex.node!.value)
            if currentIndex == range.upperBound {
                removedRange = Index(node: nextNode, offset: newCount, id: id)..<Index(node: nextNode, offset: newCount, id: id)
            }
            currentNode.next = nextNode
            nextNode.previous = currentNode
            currentNode = nextNode
            newCount += 1
            currentIndex = index(after: currentIndex)

        }
        if currentIndex == range.upperBound {
            removedRange = Index(node: nil, offset: newCount, id: id)..<Index(node: nil, offset: newCount, id: id)
        }
        headNode = newHeadNode
        tailNode = currentNode
        count = newCount
        return removedRange
    }

}

//MARK: - Computed Properties
public extension LinkedList {
    var head: Element? {
        return headNode?.value
    }

    var tail: Element? {
        return tailNode?.value
    }
}

//MARK: - Sequence Conformance
extension LinkedList: Sequence {

    public typealias Element = Element

    public __consuming func makeIterator() -> Iterator {
        return Iterator(node: headNode)
    }

    public struct Iterator: IteratorProtocol {

        private var currentNode: Node?

        fileprivate init(node: Node?) {
            currentNode = node
        }

        public mutating func next() -> Element? {
            guard let node = currentNode else {
                return nil
            }
            currentNode = node.next
            return node.value
        }

    }
}

//MARK: - Collection Conformance
extension LinkedList: Collection {

    public var startIndex: Index {
        return Index(node: headNode, offset: 0, id: id)
    }

    public var endIndex: Index {
        return Index(node: nil, offset: count, id: id)
    }

    public var first: Element? {
        return head
    }

    public var isEmpty: Bool {
        return count == 0
    }

    public func index(after i: Index) -> Index {
        precondition(i.listID === self.id, "LinkedList index is invalid")
        precondition(i.offset != endIndex.offset, "LinkedList index is out of bounds")
        return Index(node: i.node?.next, offset: i.offset + 1, id: id)
    }

    public struct Index: Comparable {
        fileprivate weak var node: Node?
        fileprivate var offset: Int
        fileprivate weak var listID: ID?

        fileprivate init(node: Node?, offset: Int, id: ID) {
            self.node = node
            self.offset = offset
            self.listID = id
        }

        public static func ==(lhs: Index, rhs: Index) -> Bool {
            return lhs.offset == rhs.offset
        }

        public static func <(lhs: Index, rhs: Index) -> Bool {
            return lhs.offset < rhs.offset
        }
    }

}

//MARK: - MutableCollection Conformance
extension LinkedList: MutableCollection {

    public subscript(position: Index) -> Element {
        get {
            precondition(position.listID === self.id, "LinkedList index is invalid")
            precondition(position.offset != endIndex.offset, "Index out of range")
            guard let node = position.node else {
                preconditionFailure("LinkedList index is invalid")
            }
            return node.value
        }
        set {
            precondition(position.listID === self.id, "LinkedList index is invalid")
            precondition(position.offset != endIndex.offset, "Index out of range")

            // Copy-on-write semantics for nodes
            if !isKnownUniquelyReferenced(&headNode) {
                copyNodes(settingNodeAt: position, to: newValue)
            } else {
                position.node?.value = newValue
            }
        }
    }
}

//MARK: LinkedList Specific Operations
public extension LinkedList {

    mutating func prepend(_ newElement: Element) {
        replaceSubrange(startIndex..<startIndex, with: CollectionOfOne(newElement))
    }

    mutating func prepend<S>(contentsOf newElements: __owned S) where S: Sequence, S.Element == Element {
        replaceSubrange(startIndex..<startIndex, with: newElements)
    }

    @discardableResult
    mutating func popFirst() -> Element? {
        if isEmpty {
            return nil
        }
        return removeFirst()
    }

    @discardableResult
    mutating func popLast() -> Element? {
        if isEmpty {
            return nil
        }
        return removeLast()
    }
}

//MARK: - BidirectionalCollection Conformance
extension LinkedList: BidirectionalCollection {
    public var last: Element? {
        return tail
    }

    public func index(before i: Index) -> Index {
        precondition(i.listID === self.id, "LinkedList index is invalid")
        precondition(i.offset != startIndex.offset, "LinkedList index is out of bounds")
        if i.offset == count {
            return Index(node: tailNode, offset: i.offset - 1, id: id)
        }
        return Index(node: i.node?.previous, offset: i.offset - 1, id: id)
    }

}

//MARK: - RangeReplaceableCollection Conformance
extension LinkedList: RangeReplaceableCollection {
    public mutating func append<S>(contentsOf newElements: __owned S) where S: Sequence, Element == S.Element {
        replaceSubrange(endIndex..<endIndex, with: newElements)
    }

    public mutating func replaceSubrange<S, R>(_ subrange: R, with newElements: __owned S) where S: Sequence, R: RangeExpression, Element == S.Element, Index == R.Bound {

        var range = subrange.relative(to: indices)
        precondition(range.lowerBound.listID === id && range.upperBound.listID === id, "LinkedList range of indices are invalid")
        precondition(range.lowerBound >= startIndex && range.upperBound <= endIndex, "Subrange bounds are out of range")

        // If range covers all elements and the new elements are a LinkedList then set references to it
        if range.lowerBound == startIndex, range.upperBound == endIndex, let linkedList = newElements as? LinkedList {
            self = linkedList
            return
        }

        var newElementsCount = 0

        // There are no new elements, so range indicates deletion
        guard let nodeChain = chain(of: newElements) else {

            // If there is nothing in the removal range
            // This also covers the case that the linked list is empty because this is the only possible range
            guard range.lowerBound != range.upperBound else {
                return
            }

            // Deletion range spans all elements
            if range.lowerBound == startIndex && range.upperBound == endIndex {
                headNode = nil
                tailNode = nil
                count = 0
                return
            }

            // Copy-on-write semantics for nodes and remove elements in range
            guard isKnownUniquelyReferenced(&headNode) else {
                copyNodes(removing: range)
                return
            }

            // Update count after mutation to preserve startIndex and endIndex validity
            defer {
                count = count - (range.upperBound.offset - range.lowerBound.offset)
            }

            // Move head up if deletion starts at start index
            if range.lowerBound == startIndex {
                // Can force unwrap node since the upperBound is not the end index
                headNode = range.upperBound.node!
                headNode!.previous = nil

                // Move tail back if deletion ends at end index
            } else if range.upperBound == endIndex {
                // Can force unwrap since lowerBound index must have an associated element
                tailNode = range.lowerBound.node!.previous
                tailNode!.next = nil

                // Deletion range is in the middle of the linked list
            } else {
                // Can force unwrap all bound nodes since they both must have elements
                range.upperBound.node!.previous = range.lowerBound.node!.previous
                range.lowerBound.node!.previous!.next = range.upperBound.node!
            }

            return
        }

        // Obtain the count of the new elements from the node chain composed from them
        newElementsCount = nodeChain.count

        // Replace entire content of list with new elements
        if range.lowerBound == startIndex && range.upperBound == endIndex {
            headNode = nodeChain.head
            tailNode = nodeChain.tail
            count = nodeChain.count
            return
        }

        // Copy-on-write semantics for nodes before mutation
        if !isKnownUniquelyReferenced(&headNode) {
            range = copyNodes(removing: range)
        }

        // Update count after mutation to preserve startIndex and endIndex validity
        defer {
            count += nodeChain.count - (range.upperBound.offset - range.lowerBound.offset)
        }

        // Prepending new elements
        guard range.upperBound != startIndex else {
            headNode?.previous = nodeChain.tail
            nodeChain.tail.next = headNode
            headNode = nodeChain.head
            return
        }

        // Appending new elements
        guard range.lowerBound != endIndex else {
            tailNode?.next = nodeChain.head
            nodeChain.head.previous = tailNode
            tailNode = nodeChain.tail
            return
        }

        if range.lowerBound == startIndex {
            headNode = nodeChain.head
        }
        if range.upperBound == endIndex {
            tailNode = nodeChain.tail
        }

        range.lowerBound.node!.previous!.next = nodeChain.head
        range.upperBound.node!.previous = nodeChain.tail
    }

}

//MARK: - ExpressibleByArrayLiteral Conformance
extension LinkedList: ExpressibleByArrayLiteral {
    public typealias ArrayLiteralElement = Element

    public init(arrayLiteral elements: ArrayLiteralElement...) {
        self.init(elements)
    }
}

//MARK: - CustomStringConvertible Conformance
extension LinkedList: CustomStringConvertible {
    public var description: String {
        return "[" + lazy.map { "\($0)" }.joined(separator: ", ") + "]"
    }
}

//MARK: - Equatable Conformance
extension LinkedList: Equatable where Element: Equatable {
    public static func ==(lhs: LinkedList<Element>, rhs: LinkedList<Element>) -> Bool {
        for (a, b) in zip(lhs, rhs) {
            guard a == b else {
                return false
            }
        }
        return true
    }
}

If you'd like to use this type fully-documented in your own project, feel free to download it or add it as a dependency with Swift PM by checking out my LinkedList GitHub repository.


问:
Read file into std::vector<std::byte>
I'm trying to read a file in binary format into a std::vector<std::byte>

```<code>  std::ifstream fStream(fName, std::ios::binary);

  std::vector<std::byte> file_content((std::istreambuf_iterator<std::byte>(fStream)),
                                        std::istreambuf_iterator<std::byte>());
</code>```

but I'm getting this error (which to me looks like istreambuf_iterator is missing an overload for std::byte)

```<code>error: no matching function for call to ‘std::istreambuf_iterator<std::byte>::istreambuf_iterator(std::ifstream&)’
     std::vector<std::byte> file_content((std::istreambuf_iterator<std::byte>(fStream)),
</code>```

Am I doing something wrong ? And if yes what is the best way to do this ?

Thanks!

答:
you should be able to do it like this:

  std::basic_ifstream<std::byte> fStream{fName, std::ios::binary};

  std::vector<std::byte> file_content{ std::istreambuf_iterator<std::byte>(fStream), {} };
```

Title: Read file into std::vector<std::byte>

Body:
I'm trying to read a file in binary format into a std::vector<std::byte>

  std::ifstream fStream(fName, std::ios::binary);

  std::vector<std::byte> file_content((std::istreambuf_iterator<std::byte>(fStream)),
                                        std::istreambuf_iterator<std::byte>());

but I'm getting this error (which to me looks like istreambuf_iterator is missing an overload for std::byte)

error: no matching function for call to ‘std::istreambuf_iterator<std::byte>::istreambuf_iterator(std::ifstream&)’
     std::vector<std::byte> file_content((std::istreambuf_iterator<std::byte>(fStream)),

Am I doing something wrong ? And if yes what is the best way to do this ?

Thanks!