问:
google-chrome: making the start page be an extension (not an app)?
Is there any way to start up the google-chrome browser so that an extension (not an app) gets launched as its start page?

I know I can do the following, but it only works if app-id refers to an installed app, not an installed extension ...

```<code>chrome --app-id=XXXXXXXXXXXXXXXXXXXXX
</code>```

If the specified app-id is the ID of an installed extension (not an app), then chrome doesn't launch it.

Is it even possible to launch an extension as chrome's start page?

Thank you in advance.

CORRECTION: I am referring to the start page, and I have clarified the wording of this question accordingly.

答:
I figured out how to do it, with the help of wOxxOm ...

```<code>chrome chome-extension://XXXXXXXXXXXXXXXXXXXXX/index.html
</code>```

This works for all extensions that have some sort of HTML page for their startup. For the extension I'm dealing with, this is index.html, but different extensions might have different HTML startup pages.

I see now that the URL with the reference to the HTML file is simply the extension ID followed by a slash, followied by the HTML file name. I was previously trying it incorrectly with the extension's version number as part of the path.

And to be clear, some extensions do not have HTML startup pages, and they therefore cannot be invoked in this manner.

Body:
Is there any way to start up the google-chrome browser so that an extension (not an app) gets launched as its start page?

I know I can do the following, but it only works if app-id refers to an installed app, not an installed extension ...

chrome --app-id=XXXXXXXXXXXXXXXXXXXXX

If the specified app-id is the ID of an installed extension (not an app), then chrome doesn't launch it.

Is it even possible to launch an extension as chrome's start page?

Thank you in advance.

CORRECTION: I am referring to the start page, and I have clarified the wording of this question accordingly.

Body:
I figured out how to do it, with the help of wOxxOm ...

chrome chome-extension://XXXXXXXXXXXXXXXXXXXXX/index.html

This works for all extensions that have some sort of HTML page for their startup. For the extension I'm dealing with, this is index.html, but different extensions might have different HTML startup pages.

I see now that the URL with the reference to the HTML file is simply the extension ID followed by a slash, followied by the HTML file name. I was previously trying it incorrectly with the extension's version number as part of the path.

And to be clear, some extensions do not have HTML startup pages, and they therefore cannot be invoked in this manner.


来源: stackexchange

问:
What is the most practical way of ensuring an AWS DynamoDB doesn't go over free limits or you getting charged?
I want to use a DynamoDB (specifically with boto3) but I want to avoid getting charged? Most practical way to do this? What sort of usage surpasses free limits?</p>

答:
The AWS free tier page has extensive information on the 60 or so services which provide a free tier, including DynamoDB. You can find the free tier services page here.

As far as avoiding going over DynamoDB free tier limits, there’s a number of potential ways you could handle this. One way might be to use CloudWatch alarms to notify you that you’re approaching the limits, and you could take action when you receive the notification. Another way would be to use CloudWatch events to trigger a Lambda function that sets read and write capacity to 1 when you’re near the limits and thus minimizing your potential overage. In any event, you’ll have to decide what you want to do when you hit those limits, and handle it accordingly.

ContentLicense: CC BY-SA 4.0


问:
limiting a search (python)
```<code>from shodan import WebAPI

SHODAN_API_KEY = "MY API KEY"
api = WebAPI(SHODAN_API_KEY)

results = api.exploitdb.search('PHP')

print 'Results found: %s' % results['total']
for exploit in results['matches']:
        print '%s:' % (exploit['description'])
</code>```

How can I limit the search to only print the first 5 results?

答:
```<code>for exploit in results['matches'][:5]:
        print '%s:' % (exploit['description'])
</code>```

ContentLicense: CC BY-SA 3.0

Title: limiting a search (python)

Body:
from shodan import WebAPI

SHODAN_API_KEY = "MY API KEY"
api = WebAPI(SHODAN_API_KEY)

results = api.exploitdb.search('PHP')

print 'Results found: %s' % results['total']
for exploit in results['matches']:
        print '%s:' % (exploit['description'])

How can I limit the search to only print the first 5 results?


问:
Extending the string prototype for easily selecting elements
Actually, I had done a small experiment few days before in jquery@javaScript. I modified the string prototype

I tried the following code. (Modified the String object prototype.)

```<code>Object.defineProperty(String.prototype, '$', {
  get: function() {
    return $(this.toString());
  }
});
</code>```

And now, when execute the following code, I get output: "Hi world";

    Hello World

```

```".lab".$.html("Hi World")
```

Actually my question is, is modifying the String.prototype, is it good?

I mean, does it hamper the performance of page. Because, until we access the '$' property/getter of initialized String object, it will not define the whole jQuery in String object every time it is initialized.

And rest of all I want to say is, this is my first post and I hope I have done good. Isn't it?

答:
I finally found my answer. Actually instead of defining the whole jQuery in a String every time it is initilized, what I do is,
Define a getter instead of property.
It means, until we access the '$' property, the function (jQuery.fn.init) that executes the string is not really executed.

That is why, its safe and easy to select element this way.

No need to worry. I think I need to feedback this to John Resig. Or in his website

Body:
Actually, I had done a small experiment few days before in jquery@javaScript. I modified the string prototype

I tried the following code. (Modified the String object prototype.)

Object.defineProperty(String.prototype, '$', {
  get: function() {
    return $(this.toString());
  }
});

And now, when execute the following code, I get output: "Hi world";

    Hello World

".lab".$.html("Hi World")

Actually my question is, is modifying the String.prototype, is it good?

I mean, does it hamper the performance of page. Because, until we access the '$' property/getter of initialized String object, it will not define the whole jQuery in String object every time it is initialized.

And rest of all I want to say is, this is my first post and I hope I have done good. Isn't it?


问:
Material-UI: Trigger hover effect programmatically
I am rendering the following Material-UI component in my app:

```<code>const handleSetActive = _spyOn => {
  linkEl.current.focus();
};

const linkEl = useRef(null);

return (
    <ListItem
      button
      component={SmoothScrollLink}
      to={cutTo}
      spy
      smooth
      offset={(phone ? -theme.mixins.toolbar.minHeightPhone : -theme.mixins.toolbar.minHeightDesktop) - 20}
      duration={500}
      onSetActive={handleSetActive}
      // className={classNames(spyOn === cutTo && classes.hover)}
      ref={linkEl}
      {...other}
    />
)
</code>```

It is using the react-scroll package which fires onSetActive whenever one scrolls past that particular ListItem.

I would like, in the simplest way possible, to make ListItem (from Material-UI) enable its hover effect when handleSetActive fires.

How would I best accomplish that?

答:
Here are the portions of the default styles related to the ListItem hover state:

```<code>export const styles = theme => ({
  /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
  root: {
    '&$selected, &$selected:hover': {
      backgroundColor: theme.palette.action.selected,
    },
  },
  /* Styles applied to the inner `component` element if `button={true}`. */
  button: {
    transition: theme.transitions.create('background-color', {
      duration: theme.transitions.duration.shortest,
    }),
    '&:hover': {
      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
  /* Styles applied to the root element if `selected={true}`. */
  selected: {},
});
</code>```

Since in your case you have button={true}, the styling you want can be achieved by a CSS class that applies the following:

```<code>      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,
</code>```

Here's a sandbox that shows using the activeClass property for react-scroll's Link to apply a class with this styling: https://codesandbox.io/s/reactscroll-gppym.

Here's another sandbox using a ref to apply the class directly on the DOM node: https://codesandbox.io/s/reactscroll-using-ref-9w8ki; however you shouldn't use this approach (showing it for learning purposes only) since it does more work (would perform worse) than the activeClass approach and is very brittle since a re-render for other reasons could wipe out the class applied via the DOM.

Body:
I am rendering the following Material-UI component in my app:

const handleSetActive = _spyOn => {
  linkEl.current.focus();
};

const linkEl = useRef(null);

return (
    <ListItem
      button
      component={SmoothScrollLink}
      to={cutTo}
      spy
      smooth
      offset={(phone ? -theme.mixins.toolbar.minHeightPhone : -theme.mixins.toolbar.minHeightDesktop) - 20}
      duration={500}
      onSetActive={handleSetActive}
      // className={classNames(spyOn === cutTo && classes.hover)}
      ref={linkEl}
      {...other}
    />
)

It is using the react-scroll package which fires onSetActive whenever one scrolls past that particular ListItem.

I would like, in the simplest way possible, to make ListItem (from Material-UI) enable its hover effect when handleSetActive fires.

How would I best accomplish that?

Body:
Here are the portions of the default styles related to the ListItem hover state:

export const styles = theme => ({
  /* Styles applied to the (normally root) `component` element. May be wrapped by a `container`. */
  root: {
    '&$selected, &$selected:hover': {
      backgroundColor: theme.palette.action.selected,
    },
  },
  /* Styles applied to the inner `component` element if `button={true}`. */
  button: {
    transition: theme.transitions.create('background-color', {
      duration: theme.transitions.duration.shortest,
    }),
    '&:hover': {
      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,
      // Reset on touch devices, it doesn't add specificity
      '@media (hover: none)': {
        backgroundColor: 'transparent',
      },
    },
  },
  /* Styles applied to the root element if `selected={true}`. */
  selected: {},
});

Since in your case you have button={true}, the styling you want can be achieved by a CSS class that applies the following:

      textDecoration: 'none',
      backgroundColor: theme.palette.action.hover,

Here's a sandbox that shows using the activeClass property for react-scroll's Link to apply a class with this styling: https://codesandbox.io/s/reactscroll-gppym.

Here's another sandbox using a ref to apply the class directly on the DOM node: https://codesandbox.io/s/reactscroll-using-ref-9w8ki; however you shouldn't use this approach (showing it for learning purposes only) since it does more work (would perform worse) than the activeClass approach and is very brittle since a re-render for other reasons could wipe out the class applied via the DOM.


问:
The listview in my Fragment is not showing any data
I am creating a CategoryFragment that will display all the data that is added from my activity. The code is working fine, the data is added in the database, I have checked the data in Device File Explorer and the data that I added are there but they are not showing in my listview. Here are the codes:

CategoriesFragment.java

```<code>package com.example.devcash.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

import com.example.devcash.ADD_UI.AddCategoryActivity;
import com.example.devcash.CustomAdapters.CategoryAdapter;
import com.example.devcash.Database.DatabaseHelper;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoriesFragment extends Fragment implements SearchView.OnQueryTextListener {

    DatabaseHelper db;
    ListView lv;
    CategoryAdapter categoryAdapter;

    public CategoriesFragment() {
        // Required empty public constructor
    }

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

        setHasOptionsMenu(true);

    }

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

        //add floating action button
        FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
        categories_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // when add fab is pressed, go to add product activity
                Intent addcategory = new Intent(getActivity(), AddCategoryActivity.class);
                startActivity(addcategory);
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //handles listview
        ListView lvcategories = (ListView) view.findViewById(R.id.categorylist_listview);
        db = new DatabaseHelper(getActivity());

        ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();

        lvcategories.setAdapter(categoryAdapter);

        categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
        categoryListArrayList = db.getAllCategory();

        getActivity().setTitle("Categories");
    }

    //handles the search menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.searchmenu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(this);
        searchView.setQueryHint("Search..");

        super.onCreateOptionsMenu(menu, inflater);
    }
    }
</code>```

fragmentcategories.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.CategoriesFragment"
    android:padding="@dimen/text_padding">

        <ListView
            android:id="@+id/categorylist_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="1dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/addcategories_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add"
        android:tint="@color/whiteBG"
        android:backgroundTint="@color/colorPrimary"/>

</FrameLayout>
</code>```

CategoryAdapter.java

```<code> package com.example.devcash.CustomAdapters;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.example.devcash.Lists.CategoryList;
    import com.example.devcash.R;

    import java.util.ArrayList;

    public class CategoryAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<CategoryList> categoryListArrayList;

    public CategoryAdapter(Context context, ArrayList<CategoryList> categoryListArrayList) {
        this.context = context;
        this.categoryListArrayList = categoryListArrayList;
    }

    @Override
    public int getCount() {
        return categoryListArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return categoryListArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        ViewHolder holder;

        if(convertView == null){
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.category_customlayout, null, true);

            holder.textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        //display the data into the CategoryFragment
        holder.textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());

        return convertView;
    }

    private class ViewHolder{
        protected TextView textCategoryName;
    }
}
</code>```

答:
the problem is you are setting the adapter with an empty list and before instantiating it at the first time check if your list is not empty and then call notifyDataSetChanged()

```<code>ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);
categoryListArrayList = db.getAllCategory();
categoryAdapter.notifyDataSetChanged();
</code>```

edit

First, you should passe a context and not an activity in your adapter constructor

```<code>categoryAdapter = new CategoryAdapter(getActivity().getApplicationContext(), categoryListArrayList);
</code>```

then in your adapter try to change getview() to this

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

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.category_customlayout, parent, true);

        TextView textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);
        textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());
    return convertView;
}
</code>```

Body:
I am creating a CategoryFragment that will display all the data that is added from my activity. The code is working fine, the data is added in the database, I have checked the data in Device File Explorer and the data that I added are there but they are not showing in my listview. Here are the codes:

CategoriesFragment.java

package com.example.devcash.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

import com.example.devcash.ADD_UI.AddCategoryActivity;
import com.example.devcash.CustomAdapters.CategoryAdapter;
import com.example.devcash.Database.DatabaseHelper;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoriesFragment extends Fragment implements SearchView.OnQueryTextListener {

    DatabaseHelper db;
    ListView lv;
    CategoryAdapter categoryAdapter;

    public CategoriesFragment() {
        // Required empty public constructor
    }

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

        setHasOptionsMenu(true);

    }

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

        //add floating action button
        FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
        categories_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // when add fab is pressed, go to add product activity
                Intent addcategory = new Intent(getActivity(), AddCategoryActivity.class);
                startActivity(addcategory);
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //handles listview
        ListView lvcategories = (ListView) view.findViewById(R.id.categorylist_listview);
        db = new DatabaseHelper(getActivity());

        ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();

        lvcategories.setAdapter(categoryAdapter);

        categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
        categoryListArrayList = db.getAllCategory();

        getActivity().setTitle("Categories");
    }

    //handles the search menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.searchmenu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(this);
        searchView.setQueryHint("Search..");

        super.onCreateOptionsMenu(menu, inflater);
    }
    }

fragmentcategories.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.CategoriesFragment"
    android:padding="@dimen/text_padding">

        <ListView
            android:id="@+id/categorylist_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="1dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/addcategories_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add"
        android:tint="@color/whiteBG"
        android:backgroundTint="@color/colorPrimary"/>

</FrameLayout>

CategoryAdapter.java

 package com.example.devcash.CustomAdapters;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.example.devcash.Lists.CategoryList;
    import com.example.devcash.R;

    import java.util.ArrayList;

    public class CategoryAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<CategoryList> categoryListArrayList;

    public CategoryAdapter(Context context, ArrayList<CategoryList> categoryListArrayList) {
        this.context = context;
        this.categoryListArrayList = categoryListArrayList;
    }

    @Override
    public int getCount() {
        return categoryListArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return categoryListArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

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

        ViewHolder holder;

        if(convertView == null){
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.category_customlayout, null, true);

            holder.textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        //display the data into the CategoryFragment
        holder.textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());

        return convertView;
    }

    private class ViewHolder{
        protected TextView textCategoryName;
    }
}

Body:
the problem is you are setting the adapter with an empty list and before instantiating it at the first time check if your list is not empty and then call notifyDataSetChanged()

ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);
categoryListArrayList = db.getAllCategory();
categoryAdapter.notifyDataSetChanged();

edit

First, you should passe a context and not an activity in your adapter constructor

categoryAdapter = new CategoryAdapter(getActivity().getApplicationContext(), categoryListArrayList);

then in your adapter try to change getview() to this

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

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.category_customlayout, parent, true);

        TextView textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);
        textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());
    return convertView;
}


问:
Error "converting string to float" when using model.predict()
When I use model.predict(), the following error occurs,

ValueError: could not convert string to float:

One-hot encoding was used in my code as follows,

```<code>features_df = pd.get_dummies(df, columns=['garage_type', 'city'])
</code>```

The predict code used is given below.

```<code>sample = [["attached"], ["Richardport"]]
predictedvalue = model.predict(sample)'
</code>```

Any suggestions to solve this error? Thank you.

答:
You'll need to convert your sample to separate columns also, That means, you have to check the new dummy columns, and convert your sample to a boolean list L, where L[i]=True if column[i]=='attached' or column[i]=='Richardport' and False for all other list elements, before calling the .predict(L) method.

 This response might be helpful:

How to use Pandas get_dummies on predict data?

Body:
When I use model.predict(), the following error occurs,

ValueError: could not convert string to float:

One-hot encoding was used in my code as follows,

features_df = pd.get_dummies(df, columns=['garage_type', 'city'])

The predict code used is given below.

sample = [["attached"], ["Richardport"]]
predictedvalue = model.predict(sample)'

Any suggestions to solve this error? Thank you.


问:
Polymorphism OOP : Instance of 'child' has no 'basic_attack' memberpylint (no-member)
I'm trying to understand Polymorphism in OOP, i've built a monster parent class, from this main class you can inherit oarcs, wizards and giants..but the main attack method is coded in the parent monster class, and have only a string that is put in a variable name basic_attack

The problem is when i call this attack variable in oarcs, wizards or giants in the child classes, i get this error Instance of 'oarc' has no 'basic_attack' memberpylint(no-member)

please go easy on me and feel free to review my code below.

```<code>class monster:
    def __init__(self, damage, speed, skill):
        self.damage = damage
        self.speed = speed
        self.skill = skill

    def attack(self):
        basic_attack = "you've been attacked by "
        return basic_attack

class oarc(monster):
    def __init__(self, damage, speed, skill, oarc_data):
        super().__init__(damage, speed, skill)
        self.oarc_data = oarc_data

    def attack(self):
        return self.basic_attack + self.oarc_data

class wizard(monster):
    def __init__(self, damage, speed, skill, wizard_data):
        super().__init__(damage, speed, skill)
        self.wizard_data = wizard_data

    def attack(self):
        return self.basic_attack + self.wizard_data

class giant(monster):
    def __init__(self, damage, speed, skill, giant_data):
        super().__init__(damage, speed, skill)
        self.giant_data = giant_data

    def attack(self):
        return self.basic_attack + self.giant_data

oarc_object = oarc(56, 150, 'ugly', 'Oarc')
wizard_object = wizard(20, 100, 'fast', 'Wizard')
giant_object = giant(100, 20, 'strong', 'Giant')

list = [oarc_object, wizard_object, giant_object]

for each in list:
    print(each.attack)

print(oarc_object.attack())
</code>```

答:
Ok, basically looks like self.basic_attack is never set. Could probably fix with self.basic_attack = basic_attack in def __init__() of class Monster.

The basic_attack = "you've been attacked by " under def attack() in class Monster is not the same as setting basic_attack. That basic_attack is constrained to the attack() function.

For example, let's abstract at non-OOP code;

```<code># define a
a = 0

def test():
  # define out
  a = 2
  # output out
  return a

print(test())
>> 2

print(a)
>> 0
</code>```

Now, if we did not redefine a in test():

```<code># set a
a = 0

# define test
def test():
  return a

print(test())
>> 0

print(a)
>> 0
</code>```

Now if a was only defined within test();

```<code># define test
def test():
  # set a
  a = 2
  # output
  return a

print(test())
>> 2

print(a)
>> NameError: name 'a' is not defined
</code>```

Here's a short Intro to OOP in Python;
Quick & easy; Object-oriented Programming from the ground up with Examples from Pikachu and Bay Area Rapid Transit (BART)

And here's a bit more in-depth application of OOP to post to LinkedIn;
LinkedOut

Body:
I'm trying to understand Polymorphism in OOP, i've built a monster parent class, from this main class you can inherit oarcs, wizards and giants..but the main attack method is coded in the parent monster class, and have only a string that is put in a variable name basic_attack

The problem is when i call this attack variable in oarcs, wizards or giants in the child classes, i get this error Instance of 'oarc' has no 'basic_attack' memberpylint(no-member)

please go easy on me and feel free to review my code below.

class monster:
    def __init__(self, damage, speed, skill):
        self.damage = damage
        self.speed = speed
        self.skill = skill

    def attack(self):
        basic_attack = "you've been attacked by "
        return basic_attack

class oarc(monster):
    def __init__(self, damage, speed, skill, oarc_data):
        super().__init__(damage, speed, skill)
        self.oarc_data = oarc_data

    def attack(self):
        return self.basic_attack + self.oarc_data

class wizard(monster):
    def __init__(self, damage, speed, skill, wizard_data):
        super().__init__(damage, speed, skill)
        self.wizard_data = wizard_data

    def attack(self):
        return self.basic_attack + self.wizard_data

class giant(monster):
    def __init__(self, damage, speed, skill, giant_data):
        super().__init__(damage, speed, skill)
        self.giant_data = giant_data

    def attack(self):
        return self.basic_attack + self.giant_data

oarc_object = oarc(56, 150, 'ugly', 'Oarc')
wizard_object = wizard(20, 100, 'fast', 'Wizard')
giant_object = giant(100, 20, 'strong', 'Giant')

list = [oarc_object, wizard_object, giant_object]

for each in list:
    print(each.attack)

print(oarc_object.attack())

Body:
Ok, basically looks like self.basic_attack is never set. Could probably fix with self.basic_attack = basic_attack in def __init__() of class Monster.

The basic_attack = "you've been attacked by " under def attack() in class Monster is not the same as setting basic_attack. That basic_attack is constrained to the attack() function.

For example, let's abstract at non-OOP code;

# define a
a = 0

def test():
  # define out
  a = 2
  # output out
  return a

print(test())
>> 2

print(a)
>> 0

Now, if we did not redefine a in test():

# set a
a = 0

# define test
def test():
  return a

print(test())
>> 0

print(a)
>> 0

Now if a was only defined within test();

# define test
def test():
  # set a
  a = 2
  # output
  return a

print(test())
>> 2

print(a)
>> NameError: name 'a' is not defined

Here's a short Intro to OOP in Python;
Quick & easy; Object-oriented Programming from the ground up with Examples from Pikachu and Bay Area Rapid Transit (BART)

And here's a bit more in-depth application of OOP to post to LinkedIn;
LinkedOut


问:
Improve response speed Google sheet script
I have written a form for user to enter. I used code to guide them through the form. For example, after entering Cell A4, it jumps to D4, after D4 it jumps to A5, etc. Even though the execution time (as viewed in execution transcript) is not large (close to 0.1 seconds most of the time) the Google sheet response time is generally about 1 second. It feels quite laggy. Is there a way to improve the responsiveness of Google sheet of this action?

答:
Using Apps Script to try to move the user around the spreadsheet is probably not something you will be able to make feel comfortable.

Instead, see the guide on dialogs and sidebars, and consider if building a form in HTML/Javascript would be a more appropriate solution (assuming simply building a Google Form is not).


问:
Best way to remove an event handler in jQuery?
I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.

My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.

```<code>$('#myimage').click(function { return false; });
</code>```

答:
If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:

```<code>// add the listener
$(document).on('click','.element',function(){
    // stuff
});

// remove the listener
$(document).off("click", ".element");

</code>```

Body:
I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.

My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.

$('#myimage').click(function { return false; });

Body:
If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:

// add the listener
$(document).on('click','.element',function(){
    // stuff
});

// remove the listener
$(document).off("click", ".element");


问:
Show / hide columns dynamically using JavaScript does not function
My mission is to appear toggle JavaScript in my DataTables but it seems not function not only the button even the functions.

Here is my Code

HTML

```<code>  <div class="col-lg-12 col-md-12 col-sm-12 mb-30">
    <table class="data-table stripe hover multiple-select-row nowrap" id="example">
      <thead>
        <tr>
          <th class="table-plus datatable-nosort">No</th>
          <th>Name</th>
          <th>Phone</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="table-plus">1</td>
          <td>Michael</td>
          <td>123456789</td>
          <td>michael@gmail.com</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
</code>```

JS

```<code><script>
    $(function(){
        $.fn.bootstrapSwitch.defaults.onColor = 'success';
        $.fn.bootstrapSwitch.defaults.offColor = 'danger';
        $.fn.bootstrapSwitch.defaults.size = 'mini';
        $.fn.bootstrapSwitch.defaults.state = 'false';
        $.fn.bootstrapSwitch.defaults.inverse = 'true';
        $(".toggle-vis").bootstrapSwitch();
            var table = $('#example').DataTable();
        $('.toggle-vis').on('switchChange.bootstrapSwitch', function(event, state) {
            event.preventDefault();
            var column = table.column($(this).attr('data-column'));
            column.visible( ! column.visible() );
        });
    });
</script>
</code>```

I am trying to replicate someones code here JSFiddle unfortunately the toggle is not appear.

答:
There are 3 reasons that I see on why it isn't running like the one you're copying.

first: The original author included links that needed for it to works. He added it in the jsfiddle left side Resources url.

second: The original author included input elements in his codes that became the toggle buttons.

third: In the original author input:checkbox he included data-label-text="Position" which the value should be equal to your column number that starts with 0.

so if you wish to used the whole functions of the author's code, You need to see every details on how it is going to work.
You can check this jsfiddle https://jsfiddle.net/u9h5k048/10/

this is the link you need to add in jsfiddle resources

https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js

https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.js

https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/css/bootstrap2/bootstrap-switch.min.css

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.2/js/bootstrap-switch.min.js

Body:
My mission is to appear toggle JavaScript in my DataTables but it seems not function not only the button even the functions.

Here is my Code

HTML

          No
          Name
          Phone
          Email

          1
          Michael
          123456789
          michael@gmail.com

JS

I am trying to replicate someones code here JSFiddle unfortunately the toggle is not appear.


问:
Trouble sending selected information to next screen
I am trying to build a pokedex application in flutter. Currently I have created the first screen, with all 151 pokemon, their image, name, and # from a json api call. I am trying to make functionality where when you tap on a specific pokemon from the first screen, a new screen will appear with more details about the pokemon you tapped on. Currently having difficulties setting up my navigation to carry that information over.

Here is my project

```<code>import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

Map _data;
List _pokemon = [];

void main() async {
  _data = await fetchData();

  _pokemon = _data['pokemon'];

  runApp(
    MaterialApp(
      title: 'Poke App',
      home: new HomePage(),
      debugShowCheckedModeBanner: false,
    ),
  );
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();

    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Poke App'),
          centerTitle: true,
          backgroundColor: Colors.cyan,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          backgroundColor: Colors.cyan,
          child: Icon(Icons.search),
        ),
        body: GridView.count(
          crossAxisCount: 2,
          children: List.generate(_pokemon.length, (index) {
            return Padding(
              padding: const EdgeInsets.fromLTRB(1.0, 5.0, 1.0, 5.0),
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => new PokeDetails(_pokemon[index]
                          ),
                    ),
                  );
                },
                child: Card(
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10.0),
                        child: Container(
                          height: 100.0,
                          width: 100.0,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage('${_pokemon[index]['img']}'),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 2.0),
                        child: Text(
                          '${_pokemon[index]['name']}',
                          style: TextStyle(
                              fontSize: 16.0,
                              fontFamily: 'Chivo',
                              fontStyle: FontStyle.italic),
                        ),
                      ),
                      Text(
                        '${_pokemon[index]['num']}',
                        style: TextStyle(
                            fontFamily: 'Indie Flower',
                            fontWeight: FontWeight.w400,
                            fontSize: 20.0),
                      )
                    ],
                  ),
                ),
              ),
            );
          }),
        ));
  }
}

Future<Map> fetchData() async {
  String url =
      "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";
  http.Response response = await http.get(url);
  return json.decode(response.body);
}

class PokeDetails extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.cyan,
      appBar: AppBar(
        title: Text('${_pokemon[index]['name']}'),
        centerTitle: true,
        backgroundColor: Colors.cyan,
      ),
    );
  }
}
</code>```

I am expecting the correct pokemon to appear on screen 2 (PokeDetails) but i have yet to be able to achieve this

答:
I think you may benefit from reading through some more of the documentation on flutter. Though, to get you moving forward, your PokeDetails class has no way of knowing what to look for when you're sending over the pokemon data... You should create a pokemon class so you can map the api results over to something a little easier to work with. Then you can do something like:

```<code>class PokeDetails extends StatelessWidget{
    final Pokemon pokemon;

PokeDetails({
    @required this.pokemon
});

//now display the pokemon details

}
</code>```

Side-note, you'll want to avoid using those global variables and functions (such as fetchData, _data, and _pokemon). Those should be in their own classes. Maybe a class containing your fetch function along with a map of the data that you received. This is all kind of the bare minimum to get your feet wet. Happy coding!

Body:
I am trying to build a pokedex application in flutter. Currently I have created the first screen, with all 151 pokemon, their image, name, and # from a json api call. I am trying to make functionality where when you tap on a specific pokemon from the first screen, a new screen will appear with more details about the pokemon you tapped on. Currently having difficulties setting up my navigation to carry that information over.

Here is my project

import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';

Map _data;
List _pokemon = [];

void main() async {
  _data = await fetchData();

  _pokemon = _data['pokemon'];

  runApp(
    MaterialApp(
      title: 'Poke App',
      home: new HomePage(),
      debugShowCheckedModeBanner: false,
    ),
  );
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();

    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Poke App'),
          centerTitle: true,
          backgroundColor: Colors.cyan,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {},
          backgroundColor: Colors.cyan,
          child: Icon(Icons.search),
        ),
        body: GridView.count(
          crossAxisCount: 2,
          children: List.generate(_pokemon.length, (index) {
            return Padding(
              padding: const EdgeInsets.fromLTRB(1.0, 5.0, 1.0, 5.0),
              child: InkWell(
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => new PokeDetails(_pokemon[index]
                          ),
                    ),
                  );
                },
                child: Card(
                  child: Column(
                    children: <Widget>[
                      Padding(
                        padding: const EdgeInsets.only(bottom: 10.0),
                        child: Container(
                          height: 100.0,
                          width: 100.0,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage('${_pokemon[index]['img']}'),
                            ),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(bottom: 2.0),
                        child: Text(
                          '${_pokemon[index]['name']}',
                          style: TextStyle(
                              fontSize: 16.0,
                              fontFamily: 'Chivo',
                              fontStyle: FontStyle.italic),
                        ),
                      ),
                      Text(
                        '${_pokemon[index]['num']}',
                        style: TextStyle(
                            fontFamily: 'Indie Flower',
                            fontWeight: FontWeight.w400,
                            fontSize: 20.0),
                      )
                    ],
                  ),
                ),
              ),
            );
          }),
        ));
  }
}

Future<Map> fetchData() async {
  String url =
      "https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json";
  http.Response response = await http.get(url);
  return json.decode(response.body);
}

class PokeDetails extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.cyan,
      appBar: AppBar(
        title: Text('${_pokemon[index]['name']}'),
        centerTitle: true,
        backgroundColor: Colors.cyan,
      ),
    );
  }
}

I am expecting the correct pokemon to appear on screen 2 (PokeDetails) but i have yet to be able to achieve this

Body:
I think you may benefit from reading through some more of the documentation on flutter. Though, to get you moving forward, your PokeDetails class has no way of knowing what to look for when you're sending over the pokemon data... You should create a pokemon class so you can map the api results over to something a little easier to work with. Then you can do something like:

class PokeDetails extends StatelessWidget{
    final Pokemon pokemon;

PokeDetails({
    @required this.pokemon
});

//now display the pokemon details

}

Side-note, you'll want to avoid using those global variables and functions (such as fetchData, _data, and _pokemon). Those should be in their own classes. Maybe a class containing your fetch function along with a map of the data that you received. This is all kind of the bare minimum to get your feet wet. Happy coding!


问:
Why private variables in a class are accessible here?
I have just started to use D language and I was trying out some object-oriented code.

I am trying following code:

```<code>import std.stdio;

class Testclass{
    private int intvar = 5;
    private string strvar = "testing";
}

void main(){
    auto tc = new Testclass();

    // check if private variables are accessible:
    writeln(tc.intvar);
    writeln(tc.strvar);
}
</code>```

Running above code has following output:

```<code>$ rdmd soq_private.d
5
testing
</code>```

I find that intvar and strvar variables are accessible from main fn. Should they not be inaccessible if they are declared private in their class?

答:
See the "D Lang" Wiki:

"Private means that only members of the enclosing class can access the member, or members and functions in the same module as the enclosing class. Private members cannot be overridden."

https://wiki.dlang.org/Access_specifiers_and_visibility

Since you are in the same module as the enclosing class, this is allowed.

Body:
I have just started to use D language and I was trying out some object-oriented code.

I am trying following code:

import std.stdio;

class Testclass{
    private int intvar = 5;
    private string strvar = "testing";
}

void main(){
    auto tc = new Testclass();

    // check if private variables are accessible:
    writeln(tc.intvar);
    writeln(tc.strvar);
}

Running above code has following output:

$ rdmd soq_private.d
5
testing

I find that intvar and strvar variables are accessible from main fn. Should they not be inaccessible if they are declared private in their class?


问:
Node dependency/permission errors when installing expo-cli
I am trying to install expo to use react native, using npm install -g expo-cli but I get huge error logs.

I tried to chown /usr/local using sudo chown -R $(whoami) $(brew --prefix)/* /usr/local and sudo chown -R $USER /usr/local  but I get chown: /usr/local: Operation not permitted. I tried updating node and npm, deleting them, reinstalling them, updating with homebrew, installing expo-cli with homebrew. I tried sudo installing. I get similar errors. I tried yarn add global expo-cli and I got almost the exact same output that I got from  npm install -g expo-cli about the dependencies.

Here's the output I get in terminal from running npm install -g expo-cli:

```<code>npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.

npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).
</code>```

When I try to use yarn add I get the same errors about dependencies but instead of the "npm ERR!" part I get:

```<code>[2/4]   Fetching packages...
info @expo/traveling-fastlane-linux@1.9.4: The platform "darwin" is incompatible with this module.
info "@expo/traveling-fastlane-linux@1.9.4" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-darwin-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info "@expo/ngrok-bin-darwin-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-arm64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm64@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-freebsd-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-sunos-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-sunos-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-ia32@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-win32-x64@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-x64@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
[3/4]   Linking dependencies...
warning "expo-cli > @expo/dev-tools@0.5.14" has incorrect peer dependency "@expo/xdl@^53.8.0".
error An unexpected error occurred: "EACCES: permission denied, unlink '/Users/<username>/node_modules/.bin/detect-libc'".
info If you think this is a bug, please open a bug report with the information provided in "/Users/<username>/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.
</code>```

When I run sudo npm install -g expo-cli I get the following:

```<code>npm WARN deprecated joi@14.0.4: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

> @expo/traveling-fastlane-darwin@1.9.4 preinstall /usr/local/lib/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin
> node platform.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
/usr/local/bin/expo-cli -> /usr/local/lib/node_modules/expo-cli/bin/expo.js
/usr/local/bin/expo -> /usr/local/lib/node_modules/expo-cli/bin/expo.js

> fsevents@1.2.9 install /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
> node install

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

> iltorb@2.4.3 install /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
> node ./scripts/install.js || node-gyp rebuild

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

> sharp@0.22.1 install /usr/local/lib/node_modules/expo-cli/node_modules/sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-linux@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/traveling-fastlane-linux@1.9.4: wanted {"os":"win32,linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-x64@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-x64@2.2.8-beta.1: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-ia32@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-sunos-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-sunos-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-sunos-x64@2.2.8: wanted {"os":"sunos","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-x64@2.2.8: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-ia32@2.2.8: wanted {"os":"linux","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm64@2.2.8: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm@2.2.8: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-ia32@2.2.8: wanted {"os":"freebsd","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-x64@2.2.8: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-darwin-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-darwin-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-darwin-ia32@2.2.8: wanted {"os":"darwin","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 preinstall: `node platform.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/expo-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 (node_modules/expo-cli/node_modules/iltorb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 install: `node ./scripts/install.js || node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: spawn ENOENT

npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! sharp@0.22.1 install: `(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the sharp@0.22.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

I expected the output to say something like expo installed ok but instead it gives me the error logs about dependencies and permissions.

答:
You can use npx alternative of npm install.
I can't fix the error, but
    $ npx expo init Awesomeproject
works.

The only disadvantage of using npx is taking more time than using preinstalled expo.
Try npx!

Body:
I am trying to install expo to use react native, using npm install -g expo-cli but I get huge error logs.

I tried to chown /usr/local using sudo chown -R $(whoami) $(brew --prefix)/* /usr/local and sudo chown -R $USER /usr/local  but I get chown: /usr/local: Operation not permitted. I tried updating node and npm, deleting them, reinstalling them, updating with homebrew, installing expo-cli with homebrew. I tried sudo installing. I get similar errors. I tried yarn add global expo-cli and I got almost the exact same output that I got from  npm install -g expo-cli about the dependencies.

Here's the output I get in terminal from running npm install -g expo-cli:

npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.

npm ERR! path /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR!  { [Error: EACCES: permission denied, access '/usr/local/lib/node_modules']
npm ERR!   stack:
npm ERR!    'Error: EACCES: permission denied, access \'/usr/local/lib/node_modules\'',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules' }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator (though this is not recommended).

When I try to use yarn add I get the same errors about dependencies but instead of the "npm ERR!" part I get:

[2/4]   Fetching packages...
info @expo/traveling-fastlane-linux@1.9.4: The platform "darwin" is incompatible with this module.
info "@expo/traveling-fastlane-linux@1.9.4" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-darwin-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info "@expo/ngrok-bin-darwin-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-arm64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-arm64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-arm64@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-freebsd-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-freebsd-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-freebsd-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-linux-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-sunos-x64@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-sunos-x64@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-ia32@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: The CPU architecture "x64" is incompatible with this module.
info @expo/ngrok-bin-win32-x64@2.2.8-beta.1: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-win32-x64@2.2.8-beta.1" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The platform "darwin" is incompatible with this module.
info "@expo/ngrok-bin-linux-ia32@2.2.8" is an optional dependency and failed compatibility check. Excluding it from installation.
info @expo/ngrok-bin-linux-ia32@2.2.8: The CPU architecture "x64" is incompatible with this module.
[3/4]   Linking dependencies...
warning "expo-cli > @expo/dev-tools@0.5.14" has incorrect peer dependency "@expo/xdl@^53.8.0".
error An unexpected error occurred: "EACCES: permission denied, unlink '/Users/<username>/node_modules/.bin/detect-libc'".
info If you think this is a bug, please open a bug report with the information provided in "/Users/<username>/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

When I run sudo npm install -g expo-cli I get the following:

npm WARN deprecated joi@14.0.4: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated joi@11.4.0: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@2.0.2: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated hoek@4.2.1: This version has been deprecated in accordance with the hapi support policy (hapi.im/support). Please upgrade to the latest version to get the best features, bug fixes, and security patches. If you are unable to upgrade at this time, paid support is available for older versions (hapi.im/commercial).
npm WARN deprecated topo@3.0.3: This module has moved and is now available at @hapi/topo. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.
npm WARN deprecated hoek@6.1.3: This module has moved and is now available at @hapi/hoek. Please update your dependencies as this version is no longer maintained an may contain bugs and security issues.

> @expo/traveling-fastlane-darwin@1.9.4 preinstall /usr/local/lib/node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin
> node platform.js

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
/usr/local/bin/expo-cli -> /usr/local/lib/node_modules/expo-cli/bin/expo.js
/usr/local/bin/expo -> /usr/local/lib/node_modules/expo-cli/bin/expo.js

> fsevents@1.2.9 install /usr/local/lib/node_modules/expo-cli/node_modules/fsevents
> node install

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)

> iltorb@2.4.3 install /usr/local/lib/node_modules/expo-cli/node_modules/iltorb
> node ./scripts/install.js || node-gyp rebuild

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied

> sharp@0.22.1 install /usr/local/lib/node_modules/expo-cli/node_modules/sharp
> (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)

shell-init: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
path.js:1077
        path = process.cwd();
                       ^

Error: EACCES: permission denied, uv_cwd
    at Object.resolve (path.js:1077:24)
    at startup (internal/bootstrap/node.js:269:32)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
sh: node-gyp: command not found
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
job-working-directory: error retrieving current directory: getcwd: cannot access parent directories: Permission denied
npm WARN @expo/dev-tools@0.5.14 requires a peer of @expo/xdl@^53.8.0 but none is installed. You must install peer dependencies yourself.
npm WARN ts-pnp@1.1.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-linux@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-linux):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/traveling-fastlane-linux@1.9.4: wanted {"os":"win32,linux","arch":"any"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-x64@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-x64@2.2.8-beta.1: wanted {"os":"win32","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-win32-ia32@2.2.8-beta.1 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-win32-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-win32-ia32@2.2.8-beta.1: wanted {"os":"win32","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-sunos-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-sunos-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-sunos-x64@2.2.8: wanted {"os":"sunos","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-x64@2.2.8: wanted {"os":"linux","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-ia32@2.2.8: wanted {"os":"linux","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm64@2.2.8: wanted {"os":"linux","arch":"arm64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-linux-arm@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-linux-arm):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-linux-arm@2.2.8: wanted {"os":"linux","arch":"arm"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-ia32@2.2.8: wanted {"os":"freebsd","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-freebsd-x64@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-freebsd-x64):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-freebsd-x64@2.2.8: wanted {"os":"freebsd","arch":"x64"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/ngrok-bin-darwin-ia32@2.2.8 (node_modules/expo-cli/node_modules/@expo/ngrok-bin-darwin-ia32):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for @expo/ngrok-bin-darwin-ia32@2.2.8: wanted {"os":"darwin","arch":"ia32"} (current: {"os":"darwin","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 (node_modules/expo-cli/node_modules/@expo/traveling-fastlane-darwin):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: @expo/traveling-fastlane-darwin@1.9.4 preinstall: `node platform.js`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/expo-cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 (node_modules/expo-cli/node_modules/iltorb):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: iltorb@2.4.3 install: `node ./scripts/install.js || node-gyp rebuild`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: spawn ENOENT

npm ERR! file sh
npm ERR! code ELIFECYCLE
npm ERR! errno ENOENT
npm ERR! syscall spawn
npm ERR! sharp@0.22.1 install: `(node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)`
npm ERR! spawn ENOENT
npm ERR!
npm ERR! Failed at the sharp@0.22.1 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

I expected the output to say something like expo installed ok but instead it gives me the error logs about dependencies and permissions.


问:
How to get Joining an IQueryable with model any types sql c#
I have this model ExpenseReport

```<code>public class ExpenseReport
    {
        public Guid Id { get; set; }
        public Guid InternalId { get; set; }
        public Guid AccountId { get; set; }
        public string Alias { get; set; }
        public bool IsDraft { get; set; }
        public int BaseCurrencyId { get; set; }
        public Guid ContactId { get; set; }
        public Contact Contact { get; set; }
        public Guid? JobId { get; set; }
        public Job Job { get; set; }
        public Customer Customer { get; set; }
        public Guid CustomerId { get; set; }
        public DateTime? PublishedOn { get; set; }
        public DateTime? ExpectedPayDate { get; set; }
        public ExpenseReportStatus Status { get; set; }
        public ExpenseReportStatusEnum StatusId { get; set; }
        public string OriginReference { get; set; }
        public decimal AdvanceValue { get; set; }
        public decimal TotalValue { get; set; }
        public string CreatedBy { get; set; }
        public DateTime CreatedOn { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime UpdatedOn { get; set; }
    }
</code>```

I Need to Join to get JOB, CUSTOMER, and Contact from another table

when I use LINQ to get these values it returns me null them. What would be the junction of this return

My query

```<code>  public IQueryable<ExpenseReport> ExpenseReports => (from exReport in _dataContext.ExpenseReport
                                                            join job in _dataContext.Job on exReport.JobId equals job.Id
                                                            join contact in _dataContext.Contact on exReport.ContactId equals contact.Id
                                                            join customer in _dataContext.Customer on exReport.CustomerId equals customer.Id
                                                            select exReport );
</code>```

答:
You can simply do the following in your business class</p>

```<code>var results = from report in _context.ExpenseReport
              select new { Report = report, JobName = report.Job.Name };
foreach(var x in results)
{
    Console.WriteLine($"Got job {x.JobName} with { x.Report }");
}
</code>```

Body:
I have this model ExpenseReport

public class ExpenseReport
    {
        public Guid Id { get; set; }
        public Guid InternalId { get; set; }
        public Guid AccountId { get; set; }
        public string Alias { get; set; }
        public bool IsDraft { get; set; }
        public int BaseCurrencyId { get; set; }
        public Guid ContactId { get; set; }
        public Contact Contact { get; set; }
        public Guid? JobId { get; set; }
        public Job Job { get; set; }
        public Customer Customer { get; set; }
        public Guid CustomerId { get; set; }
        public DateTime? PublishedOn { get; set; }
        public DateTime? ExpectedPayDate { get; set; }
        public ExpenseReportStatus Status { get; set; }
        public ExpenseReportStatusEnum StatusId { get; set; }
        public string OriginReference { get; set; }
        public decimal AdvanceValue { get; set; }
        public decimal TotalValue { get; set; }
        public string CreatedBy { get; set; }
        public DateTime CreatedOn { get; set; }
        public string UpdatedBy { get; set; }
        public DateTime UpdatedOn { get; set; }
    }

I Need to Join to get JOB, CUSTOMER, and Contact from another table

when I use LINQ to get these values it returns me null them. What would be the junction of this return

My query

  public IQueryable<ExpenseReport> ExpenseReports => (from exReport in _dataContext.ExpenseReport
                                                            join job in _dataContext.Job on exReport.JobId equals job.Id
                                                            join contact in _dataContext.Contact on exReport.ContactId equals contact.Id
                                                            join customer in _dataContext.Customer on exReport.CustomerId equals customer.Id
                                                            select exReport );

Body:
You can simply do the following in your business class

var results = from report in _context.ExpenseReport
              select new { Report = report, JobName = report.Job.Name };
foreach(var x in results)
{
    Console.WriteLine($"Got job {x.JobName} with { x.Report }");
}


问:
How to use groupby on the following dataset
I have this dataset,

```<code>sender          team_id     receiver
John Cena         1           Margaret
Genghis Khan      2           Mahathma
Mahathma Gandhi   1           John
John Doe          2           Genghis
Margaret Thatcher 1           John
</code>```

Each sender has a team id and receiver's name is only their first name. I want to find out if each message is between team members or not. The result would look something like this.

```<code>sender          team_id     receiver       btwn_teammates
John Cena         1           Margaret          Yes
Genghis Khan      2           Mahathma          No
Mahathma Gandhi   1           John              Yes
John Doe          2           Genghis           Yes
Margaret Thatcher 1           John              Yes
</code>```

答:
Merge on the first part of the name + team_id, then map the indicator values:

```<code>df2 = df[['sender', 'team_id']].rename(columns={'sender': 'receiver'})
df2['receiver'] = df2.receiver.str.split().str[0]
df2 = df2.drop_duplicates()  # So left merge preserves size.

df = df.merge(df2, how='left', indicator='btwn_team')
df['btwn_team'] = df.btwn_team.map({'both': 'Yes', 'left_only': 'No'})
</code>```

Output:

```<code>              sender  team_id  receiver btwn_team
0          John Cena        1  Margaret       Yes
1       Genghis Khan        2  Mahathma        No
2    Mahathma Gandhi        1      John       Yes
3           John Doe        2   Genghis       Yes
4  Margaret Thatcher        1      John       Yes
</code>```

Body:
I have this dataset,

sender          team_id     receiver
John Cena         1           Margaret
Genghis Khan      2           Mahathma
Mahathma Gandhi   1           John
John Doe          2           Genghis
Margaret Thatcher 1           John

Each sender has a team id and receiver's name is only their first name. I want to find out if each message is between team members or not. The result would look something like this.

sender          team_id     receiver       btwn_teammates
John Cena         1           Margaret          Yes
Genghis Khan      2           Mahathma          No
Mahathma Gandhi   1           John              Yes
John Doe          2           Genghis           Yes
Margaret Thatcher 1           John              Yes

Body:
Merge on the first part of the name + team_id, then map the indicator values:

df2 = df[['sender', 'team_id']].rename(columns={'sender': 'receiver'})
df2['receiver'] = df2.receiver.str.split().str[0]
df2 = df2.drop_duplicates()  # So left merge preserves size.

df = df.merge(df2, how='left', indicator='btwn_team')
df['btwn_team'] = df.btwn_team.map({'both': 'Yes', 'left_only': 'No'})

Output:

              sender  team_id  receiver btwn_team
0          John Cena        1  Margaret       Yes
1       Genghis Khan        2  Mahathma        No
2    Mahathma Gandhi        1      John       Yes
3           John Doe        2   Genghis       Yes
4  Margaret Thatcher        1      John       Yes


问:
vRA Windows machine creation does not return host name/addr before moving to chef provisioner block
When creating a Windows machine in vRA, Terraform will move on to the Chef Provisioner block before it has acquired the IP/FQDN of the new machine to pass into the provisioner.

Terraform v0.11.14
+ provider.vra7 v0.2.0

I've tried everything I can get my hands on from the internet; loca-exec'ing knife bootstrap, using a depends_on attribute, setting a sleep timer, nothing seems to work.

```<code>resource "vra7_deployment" "terraform-1" {
  count             = "${var.server_count}"
  description       = "deployment via terraform"
  reasons           = "because it's awesome"
  catalog_item_name = "${var.vra_cat_item_name}"
  wait_timeout      = "1800"

  provisioner "chef" {
    # This is for chef_server to talk to the node
    connection {
      type = "winrm"
      user = "${var.KT_USER}"
      password = "${var.KT_PASS}"
      insecure = true
    }

    # This is for TF to talk to the chef_server
    server_url = "${var.chef_server_url}"
    node_name  = "terraform-chef-test"
    run_list   = [ ]
    user_name  = "${var.chef_user_name}"
    user_key   = "${file(var.chef_user_pem)}"
    recreate_client = true
    fetch_chef_certificates = true
    environment = "_default"
    ssl_verify_mode = false
    version = "12"
  }
}
</code>```

error:

```<code>vra7_deployment.terraform-1: Still creating... (21m20s elapsed)
vra7_deployment.terraform-1 (chef): Connecting to remote host via WinRM...
vra7_deployment.terraform-1 (chef):   Host:
vra7_deployment.terraform-1 (chef):   Port: 5985
vra7_deployment.terraform-1 (chef):   User: engineering
vra7_deployment.terraform-1 (chef):   Password: true
vra7_deployment.terraform-1 (chef):   HTTPS: false
vra7_deployment.terraform-1 (chef):   Insecure: true
vra7_deployment.terraform-1 (chef):   NTLM: false
vra7_deployment.terraform-1 (chef):   CACert: false

* vra7_deployment.terraform-1: interrupted - last error: unknown error Post http://:5985/wsman: dial tcp :5985: connectex: No connection could be made because the target machine actively refused it.
</code>```

答:
I figured it out. The key was understanding that my instance of vRA is set up so that the VMs are called vSphere_Machine_1. It's right there in the UI, as Component Name.

There were definitely some mental leaps involved, and I'm sure I had to have seen all the other examples and made all the mistakes i did in order for my brain to put it all together at that moment. Whatever the mechanism, this code now WORKS:

```<code># in resource block
resource_configuration {
    vSphere_Machine_1.name = ""
  }

...

# in provisioner block
    connection {
      host = "${self.resource_configuration.vSphere_Machine_1.name}"
     ....
}
</code>```

Now, of course, on to the next brick wall... but I figured this out. And I intend to pay it forward to the community.

For others coming to this with the same question, you are looking for the Component Name in your vRa item's machine listing.

Body:
When creating a Windows machine in vRA, Terraform will move on to the Chef Provisioner block before it has acquired the IP/FQDN of the new machine to pass into the provisioner.

Terraform v0.11.14
+ provider.vra7 v0.2.0

I've tried everything I can get my hands on from the internet; loca-exec'ing knife bootstrap, using a depends_on attribute, setting a sleep timer, nothing seems to work.

resource "vra7_deployment" "terraform-1" {
  count             = "${var.server_count}"
  description       = "deployment via terraform"
  reasons           = "because it's awesome"
  catalog_item_name = "${var.vra_cat_item_name}"
  wait_timeout      = "1800"

  provisioner "chef" {
    # This is for chef_server to talk to the node
    connection {
      type = "winrm"
      user = "${var.KT_USER}"
      password = "${var.KT_PASS}"
      insecure = true
    }

    # This is for TF to talk to the chef_server
    server_url = "${var.chef_server_url}"
    node_name  = "terraform-chef-test"
    run_list   = [ ]
    user_name  = "${var.chef_user_name}"
    user_key   = "${file(var.chef_user_pem)}"
    recreate_client = true
    fetch_chef_certificates = true
    environment = "_default"
    ssl_verify_mode = false
    version = "12"
  }
}

error:

vra7_deployment.terraform-1: Still creating... (21m20s elapsed)
vra7_deployment.terraform-1 (chef): Connecting to remote host via WinRM...
vra7_deployment.terraform-1 (chef):   Host:
vra7_deployment.terraform-1 (chef):   Port: 5985
vra7_deployment.terraform-1 (chef):   User: engineering
vra7_deployment.terraform-1 (chef):   Password: true
vra7_deployment.terraform-1 (chef):   HTTPS: false
vra7_deployment.terraform-1 (chef):   Insecure: true
vra7_deployment.terraform-1 (chef):   NTLM: false
vra7_deployment.terraform-1 (chef):   CACert: false

* vra7_deployment.terraform-1: interrupted - last error: unknown error Post http://:5985/wsman: dial tcp :5985: connectex: No connection could be made because the target machine actively refused it.

Body:
I figured it out. The key was understanding that my instance of vRA is set up so that the VMs are called vSphere_Machine_1. It's right there in the UI, as Component Name.

There were definitely some mental leaps involved, and I'm sure I had to have seen all the other examples and made all the mistakes i did in order for my brain to put it all together at that moment. Whatever the mechanism, this code now WORKS:

# in resource block
resource_configuration {
    vSphere_Machine_1.name = ""
  }

...

# in provisioner block
    connection {
      host = "${self.resource_configuration.vSphere_Machine_1.name}"
     ....
}

Now, of course, on to the next brick wall... but I figured this out. And I intend to pay it forward to the community.

For others coming to this with the same question, you are looking for the Component Name in your vRa item's machine listing.