问:
Recycleview not populated with JSON and Retrofit?
I am making a simple app in which the user will able to search for books by its name, with google.com book api. For now, I wish to present a list of books with android in their name. I am doing it with Retrofit2 and RecycleView, but nothing is showing.
 MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
KnjigaAdapter knjigaAdapter;
List<KnjigaModel> listaKnjiga;
public static final String BASE_URL = "https://www.googleapis.com/books/";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    uzmiKomentare();
}

public void uzmiKomentare() {

    Gson gson = new GsonBuilder().serializeNulls().create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
   KnjigaApi knjigaApi = retrofit.create(KnjigaApi.class);
     final Call<KnjigaModel> pozivZaListuKnjiga = knjigaApi.getKnjige("android");

    pozivZaListuKnjiga.enqueue(new Callback<KnjigaModel>() {
        @Override
        public void onResponse(Call<KnjigaModel> call, Response<KnjigaModel> response) {
            if (!response.isSuccessful()) {
                return;
            }
       //generateRecycleView(WHAT TO PUT HERE!!!!);
        }

        @Override
        public void onFailure(Call<KnjigaModel> call, Throwable t) {
            Log.d("MainActivity:", t.getMessage());
        }
    });
}
private void generateRecycleView(List<KnjigaModel> knjige) {
    listaKnjiga = new ArrayList<>();
    recyclerView = findViewById(R.id.recycleview);
    knjigaAdapter = new KnjigaAdapter(this, knjige);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(knjigaAdapter);
    if (knjigaAdapter.getItemCount() == 0){
        Log.i("List is empty: ","YES");
    }
    else {
        Log.i("list is empty: ","No");
    }
}
</code>```

}

api inteface:

```<code>public interface KnjigaApi {
@GET("v1/volumes")
Call<KnjigaModel> getKnjige(@Query("q") String knjiga);
</code>```

}

model class:

```<code>public class KnjigaModel {
@SerializedName("title")
@Expose
private String imeKnjige;
@SerializedName("authors")
@Expose
private String imeAutora;
@SerializedName("thumbnail")
@Expose
private String slikaKnjige;

public KnjigaModel(String imeKnjige, String imeAutora,String slikaKnjige) {
    this.imeKnjige = imeKnjige;
    this.imeAutora = imeAutora;
    this.slikaKnjige = slikaKnjige;
}

public String getImeKnjige() {
    return imeKnjige;
}

public String getImeAutora() {
    return imeAutora;
}

public String getSlikaKnjige() {
    return slikaKnjige;
}
</code>```

}

and my adapter:

```<code>public class KnjigaAdapter extends RecyclerView.Adapter<KnjigaAdapter.KomentariViewHolder> {
private List<KnjigaModel> listaKnjiga;
private LayoutInflater inflater;
private Context context;

public KnjigaAdapter(Context context, List<KnjigaModel> listaKnjiga) {
    this.listaKnjiga = listaKnjiga;
    this.context = context;
}

@Override
public KomentariViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

     inflater = LayoutInflater.from(context);
    // Inflate the custom layout
    View postView = inflater.inflate(R.layout.single_item, parent, false);
    // Return a new holder instance
    return new KomentariViewHolder(postView);
}

@Override
public void onBindViewHolder(KomentariViewHolder holder, int position) {
    KnjigaModel knjige = listaKnjiga.get(position);
    holder.naslovKnjige.setText(knjige.getImeKnjige());
    holder.imeAutora.setText(knjige.getImeAutora());
    Glide.with(context)
            .load(knjige.getSlikaKnjige())
            .into(holder.slikaKnjige);
}

@Override
public int getItemCount() {
    return listaKnjiga.size();
}

public class KomentariViewHolder extends RecyclerView.ViewHolder {
    private TextView naslovKnjige;
    private TextView imeAutora;
    private ImageView slikaKnjige;

    public KomentariViewHolder(View itemView) {
        super(itemView);

        naslovKnjige = itemView.findViewById(R.id.ime_knjige);
        imeAutora = itemView.findViewById(R.id.autor_knjige);
        slikaKnjige = itemView.findViewById(R.id.sika_korica);
    }
}
</code>```

}

my JSON format:

```<code>https://www.googleapis.com/books/v1/volumes?q=android
</code>```

答:
First of all, I strongly recommend to use RxJava for asynchronous requests, though it's totally optional.

Your Problem:
Your "getKnjige" Method returns only ONE Model, though the endpoint is named volumes (plural), you need to wrap your KnjigaModel in a class like

data class KnjigaResponse(val items: List<KnjigaModel>)
(Kotlin for simplicity, you can also generate a Java class with a single member volumes member that holds a list of KnjigaModel)

In addition, your model is wrong. authors is not a string, but a List of Strings, and "thumbnail" is wrapped in an "imageLinks" Object, and title is wrapped in a volumeInfo Object.

Your retrofit interface then would look like this:

```<code>public interface KnjigaApi {
@GET("v1/volumes")
Call<KnjigaResponse> getKnjige(@Query("q") String knjiga);
</code>```

Request:

```<code>     final Call<KnjigaResponse> pozivZaListuKnjiga = knjigaApi.getKnjige("android");

    pozivZaListuKnjiga.enqueue(new Callback<KnjigaResponse>() {
        @Override
        public void onResponse(Call<KnjigaResponse> call, Response<KnjigaResponse> response) {
            if (!response.isSuccessful()) {
                return;
            }
         generateRecycleView(response.items);
        }

        @Override
        public void onFailure(Call<KnjigaResponse> call, Throwable t) {
            Log.d("MainActivity:", t.getMessage());
        }
    });
</code>```

Body:
I am making a simple app in which the user will able to search for books by its name, with google.com book api. For now, I wish to present a list of books with android in their name. I am doing it with Retrofit2 and RecycleView, but nothing is showing.
 MainActivity:

public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
KnjigaAdapter knjigaAdapter;
List<KnjigaModel> listaKnjiga;
public static final String BASE_URL = "https://www.googleapis.com/books/";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    uzmiKomentare();
}

public void uzmiKomentare() {

    Gson gson = new GsonBuilder().serializeNulls().create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
   KnjigaApi knjigaApi = retrofit.create(KnjigaApi.class);
     final Call<KnjigaModel> pozivZaListuKnjiga = knjigaApi.getKnjige("android");

    pozivZaListuKnjiga.enqueue(new Callback<KnjigaModel>() {
        @Override
        public void onResponse(Call<KnjigaModel> call, Response<KnjigaModel> response) {
            if (!response.isSuccessful()) {
                return;
            }
       //generateRecycleView(WHAT TO PUT HERE!!!!);
        }

        @Override
        public void onFailure(Call<KnjigaModel> call, Throwable t) {
            Log.d("MainActivity:", t.getMessage());
        }
    });
}
private void generateRecycleView(List<KnjigaModel> knjige) {
    listaKnjiga = new ArrayList<>();
    recyclerView = findViewById(R.id.recycleview);
    knjigaAdapter = new KnjigaAdapter(this, knjige);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setAdapter(knjigaAdapter);
    if (knjigaAdapter.getItemCount() == 0){
        Log.i("List is empty: ","YES");
    }
    else {
        Log.i("list is empty: ","No");
    }
}

}

api inteface:

public interface KnjigaApi {
@GET("v1/volumes")
Call<KnjigaModel> getKnjige(@Query("q") String knjiga);

}

model class:

public class KnjigaModel {
@SerializedName("title")
@Expose
private String imeKnjige;
@SerializedName("authors")
@Expose
private String imeAutora;
@SerializedName("thumbnail")
@Expose
private String slikaKnjige;

public KnjigaModel(String imeKnjige, String imeAutora,String slikaKnjige) {
    this.imeKnjige = imeKnjige;
    this.imeAutora = imeAutora;
    this.slikaKnjige = slikaKnjige;
}

public String getImeKnjige() {
    return imeKnjige;
}

public String getImeAutora() {
    return imeAutora;
}

public String getSlikaKnjige() {
    return slikaKnjige;
}

}

and my adapter:

public class KnjigaAdapter extends RecyclerView.Adapter<KnjigaAdapter.KomentariViewHolder> {
private List<KnjigaModel> listaKnjiga;
private LayoutInflater inflater;
private Context context;

public KnjigaAdapter(Context context, List<KnjigaModel> listaKnjiga) {
    this.listaKnjiga = listaKnjiga;
    this.context = context;
}

@Override
public KomentariViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

     inflater = LayoutInflater.from(context);
    // Inflate the custom layout
    View postView = inflater.inflate(R.layout.single_item, parent, false);
    // Return a new holder instance
    return new KomentariViewHolder(postView);
}

@Override
public void onBindViewHolder(KomentariViewHolder holder, int position) {
    KnjigaModel knjige = listaKnjiga.get(position);
    holder.naslovKnjige.setText(knjige.getImeKnjige());
    holder.imeAutora.setText(knjige.getImeAutora());
    Glide.with(context)
            .load(knjige.getSlikaKnjige())
            .into(holder.slikaKnjige);
}

@Override
public int getItemCount() {
    return listaKnjiga.size();
}

public class KomentariViewHolder extends RecyclerView.ViewHolder {
    private TextView naslovKnjige;
    private TextView imeAutora;
    private ImageView slikaKnjige;

    public KomentariViewHolder(View itemView) {
        super(itemView);

        naslovKnjige = itemView.findViewById(R.id.ime_knjige);
        imeAutora = itemView.findViewById(R.id.autor_knjige);
        slikaKnjige = itemView.findViewById(R.id.sika_korica);
    }
}

}

my JSON format:

https://www.googleapis.com/books/v1/volumes?q=android

Body:
First of all, I strongly recommend to use RxJava for asynchronous requests, though it's totally optional.

Your Problem:
Your "getKnjige" Method returns only ONE Model, though the endpoint is named volumes (plural), you need to wrap your KnjigaModel in a class like

data class KnjigaResponse(val items: List<KnjigaModel>)
(Kotlin for simplicity, you can also generate a Java class with a single member volumes member that holds a list of KnjigaModel)

In addition, your model is wrong. authors is not a string, but a List of Strings, and "thumbnail" is wrapped in an "imageLinks" Object, and title is wrapped in a volumeInfo Object.

Your retrofit interface then would look like this:

public interface KnjigaApi {
@GET("v1/volumes")
Call<KnjigaResponse> getKnjige(@Query("q") String knjiga);

Request:

     final Call<KnjigaResponse> pozivZaListuKnjiga = knjigaApi.getKnjige("android");

    pozivZaListuKnjiga.enqueue(new Callback<KnjigaResponse>() {
        @Override
        public void onResponse(Call<KnjigaResponse> call, Response<KnjigaResponse> response) {
            if (!response.isSuccessful()) {
                return;
            }
         generateRecycleView(response.items);
        }

        @Override
        public void onFailure(Call<KnjigaResponse> call, Throwable t) {
            Log.d("MainActivity:", t.getMessage());
        }
    });


来源: stackexchange

问:
Can I call commit from one of mutations in Vuex store
I have a vuex store, like following:

```<code>import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
  products: [],
  categories: []
}

// mutations
const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   commit('SET_CATEGORIES')
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(function(product) { return product.category})
 }

}

const actions = {
 FETCH_PRODUCTS: (state, filters) => {
   return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
 }
}

export default {
  state,
  mutations,
  actions
}
</code>```

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

答:
I prefer to call mutations.SET_CATEGORIES(state) instead of:
- calling 2 different commits from an artificial action
- or doing commit() inside a mutation as it makes unit testing more difficult.

```<code>const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   mutations.SET_CATEGORIES(state)
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(product => product.category)
 }
}
</code>```

My opinion is that you don't need to see SET_CATEGORIES in the VueToolbox. The time travel should work anyways. Please, correct me if I'm wrong.

ContentLicense: CC BY-SA 3.0

Body:
I have a vuex store, like following:

import spreeApi from '../../gateways/spree-api'
// initial state
const state = {
  products: [],
  categories: []
}

// mutations
const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   commit('SET_CATEGORIES')
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(function(product) { return product.category})
 }

}

const actions = {
 FETCH_PRODUCTS: (state, filters) => {
   return spreeApi.get('products').then(response => state.commit('SET_PRODUCTS', response))
 }
}

export default {
  state,
  mutations,
  actions
}

I want to call mutation: SET_CATEGORIES from mutation: SET_PRODUCTS, But this gives me error:

projectFilter.js:22 Uncaught (in promise) ReferenceError: commit is not defined(…)

What should be correct way to do this. I tried store.commit and this.commit, but these also gave similar errors.

Body:
I prefer to call mutations.SET_CATEGORIES(state) instead of:
- calling 2 different commits from an artificial action
- or doing commit() inside a mutation as it makes unit testing more difficult.

const mutations = {
 SET_PRODUCTS: (state, response) => {
   state.products = response.data.products
   mutations.SET_CATEGORIES(state)
 },
 SET_CATEGORIES: (state) => {
   state.categories = state.products.map(product => product.category)
 }
}

My opinion is that you don't need to see SET_CATEGORIES in the VueToolbox. The time travel should work anyways. Please, correct me if I'm wrong.

ContentLicense: CC BY-SA 4.0


问:
How to pass an element to another component (easiest way)?
I have a string in one of the components and I would like to send it to another component when the submit button is pushed. I found solutions (input, emit...) but none of them worked.

This is my component from where I'd like to pass the variable:

```<code>export class UsersComponent {
  public data: string;

  public exportDocument() { // This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     // I have no idea what to write here, to pass this variable
  }
}
</code>```

Other component:

```<code>export class CvPageComponent implements OnInit {
  public cvData; // This should be equal with the value of "data"
}
</code>```

答:
If they have parent child relationship then you can use @Input way parent to child Demo

ViewChild or Sharing Data via Output() and EventEmitter for child to parent

If they are not related components. You can use

Sharing Data with a Service as a way Demo

storage method as a way you can use sessionStorage or localStorage etc...

sending parameter within url as a way Demo

Body:
I have a string in one of the components and I would like to send it to another component when the submit button is pushed. I found solutions (input, emit...) but none of them worked.

This is my component from where I'd like to pass the variable:

export class UsersComponent {
  public data: string;

  public exportDocument() { // This function is called, when the submit button is pushed!
     this.data = doc.output("datauristring");
     // I have no idea what to write here, to pass this variable
  }
}

Other component:

export class CvPageComponent implements OnInit {
  public cvData; // This should be equal with the value of "data"
}


问:
getting undefined for a function used in another function
I'm getting the required result from console.log in getuser(), but I'm getting undefined when used it in another function

```<code>let getuser = (id) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      return "wrong user id";
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      return { name, _id };
    }
  });
};
</code>```

I'm getting undefined when i use getuser() in send()

```<code>exports.send = (req, res) => {
let {id}=req.body
let a=getuser(req.User._id)
let b=getuser(req.body.id)
console.log(a)
console.log(a)
let message = new messages({
                user1: a,
                user2: b,
              });
              message.save((err, saved) => {
                if (err) {
                  return res.json(err);
                } else {
                  return res.json(saved);
                }
              });
            }
</code>```

im getting undefined in

console.log(a)
console.log(a)

答:
You probably want to use a Promise for the getuser method:

```<code>let getuser = (id) => new Promise((resolve, reject) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      reject("wrong user id");
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      resolve({ name, _id });
    }
  });
});
</code>```

The operation looks asynchronous, so you need to wait for the result before continuing. This means that your getuser calls need to handle promise/async values:

```<code>let a = await getuser(req.User._id)
let b = await getuser(req.body.id)
</code>```

Of course, await must be used in a function marked with async. Read up on Promises and async/await if any of this is unclear - they're absolutely imperative for working with databases, APIs etc.. It may be possible to use it immediately by changing your exports line:

```<code>exports.send = async (req, res) => {
</code>```

But I don't know what environment this is for, so I can't say if that will work out of the box.

Please note that I haven't tested this at all, as it's a rather incomplete example to begin with. What I've suggested is merely theoretical.

Body:
I'm getting the required result from console.log in getuser(), but I'm getting undefined when used it in another function

let getuser = (id) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      return "wrong user id";
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      return { name, _id };
    }
  });
};

I'm getting undefined when i use getuser() in send()

exports.send = (req, res) => {
let {id}=req.body
let a=getuser(req.User._id)
let b=getuser(req.body.id)
console.log(a)
console.log(a)
let message = new messages({
                user1: a,
                user2: b,
              });
              message.save((err, saved) => {
                if (err) {
                  return res.json(err);
                } else {
                  return res.json(saved);
                }
              });
            }

im getting undefined in

console.log(a)
console.log(a)

Body:
You probably want to use a Promise for the getuser method:

let getuser = (id) => new Promise((resolve, reject) => {
  user.findById(id, (err, user) => {
    if (err || !user) {
      reject("wrong user id");
    } else {
      let { name, _id } = user;
      console.log(JSON.stringify({ name, _id }));
      resolve({ name, _id });
    }
  });
});

The operation looks asynchronous, so you need to wait for the result before continuing. This means that your getuser calls need to handle promise/async values:

let a = await getuser(req.User._id)
let b = await getuser(req.body.id)

Of course, await must be used in a function marked with async. Read up on Promises and async/await if any of this is unclear - they're absolutely imperative for working with databases, APIs etc.. It may be possible to use it immediately by changing your exports line:

exports.send = async (req, res) => {

But I don't know what environment this is for, so I can't say if that will work out of the box.

Please note that I haven't tested this at all, as it's a rather incomplete example to begin with. What I've suggested is merely theoretical.


问:
Android - barcode scanner - how to scan only in defined area
i've made an Android app with a barcode scenner following this tutorial: https://www.varvet.com/blog/android-qr-code-reader-made-easy/ (https://github.com/varvet/BarcodeReaderSample). It uses gms:play-services-vision and it works well and fast, but it uses a full screen camera to find a barcode/qr code and I would like to set some focus area to search only in some square in the midle of the screen(like the most of qr scanner apps has), so you would be able to select and focus on one barcode when there are more of them on small space.

Is there any way how to tell detector to search for barcode only in some area?

Thanks

答: Exactly as Michael said, each Barcode has method getBoundingBox() returns the barcode's axis-aligned Rect.


问:
Can I set up a 'before hook' on certain SSH hosts?
I have several hosts in my ~/.ssh/config file, some of which are on my work network. Before accessing those, I need to authenticate myself on that network by running kinit, but I often forget to do that.

Is there a command to run kinit in a 'before hook' on those SSH hosts?

答:
I'm not sure there's exactly such a thing as a 'before hook', but I can see two hacks that could achieve the a similar effect.

Bash Functions (in some init file like .bashrc, .profile, etc)

```<code>ssh ()
{
    echo "do this before ssh'ing"
    command ssh "$@"
}
</code>```

The other possibility that I can think on would be the ProxyCommand option. In your ~/.ssh/config:

```<code>Host *
  ProxyCommand sh -c 'kinit >&2 && nc %h %p'
</code>```

Couple of salient points:

If you're going to do this, I'd recommend replacing the raw kinit, with a script (ensure_kinit.sh perhaps) which checks if running kinit is necessary, and if so running it.

If you choose the second option, ensure that you redirect stdout to stderr; stdin and stdout should be kept for SSH Protocol network messages.

The latter method will work for other commands such as git, and scp, which use ssh to communicate, while the former will only work for ssh.

Body:
I'm not sure there's exactly such a thing as a 'before hook', but I can see two hacks that could achieve the a similar effect.

Bash Functions (in some init file like .bashrc, .profile, etc)

ssh ()
{
    echo "do this before ssh'ing"
    command ssh "$@"
}

The other possibility that I can think on would be the ProxyCommand option. In your ~/.ssh/config:

Host *
  ProxyCommand sh -c 'kinit >&2 && nc %h %p'

Couple of salient points:

If you're going to do this, I'd recommend replacing the raw kinit, with a script (ensure_kinit.sh perhaps) which checks if running kinit is necessary, and if so running it.

If you choose the second option, ensure that you redirect stdout to stderr; stdin and stdout should be kept for SSH Protocol network messages.

The latter method will work for other commands such as git, and scp, which use ssh to communicate, while the former will only work for ssh.


问:
How-to parse XML key:value pair
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

```<code>$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';
</code>```

I was hoping that the following would work, but it appears not.

```<code>$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999
</code>```

答:
```<code>```
<?php
$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

$test = new SimpleXMLElement($xml);
echo "Mask = ".$test->string[2];
?>
```
</code>```

Here is the working code.

Title: How-to parse XML key:value pair

Body:
I have a clients server returning the following (strange) XML response; how do I access each key:value pair?

$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

I was hoping that the following would work, but it appears not.

$test = new SimpleXMLElement($xml);
echo "Mask: " . $xml->response->mask; // Mask: 9999

Body:
<pre>
<?php
$xml = '<?xml version="1.0"?>
  <response>
    <string key="__status">success</string>
    <string key="id">1000</string>
    <string key="mask">9999</string>
</response>';

$test = new SimpleXMLElement($xml);
echo "Mask = ".$test->string[2];
?>
</pre>

Here is the working code.


问:
Remove object from an array?
remove an object from an array is not working properly ,but it add object perfectly

```<code>const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.indexOf(selected);
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
    setSelectedItems(data);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}
</code>```

render button function add or remove on click it

```<code><div className="file-list">
  <MappedElement
   data={[{ _id: 1 }, { _id: 2 }]}
   renderElement={(value, index, arr) => {
   let check=selectedItems.some((obj) => obj._id === value._id);
   console.log("check", check);
   return (
    <DocumentCard key={index} className={file-list-item ${check ?
       "active" : ""}}
    onClick={() => addItem(value, arr, index)} /> ); }} />
 </div>
</code>```

答:
Use</p>

```<code>const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.findIndex(value => value._id === selected._id)ж
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}
</code>```

Title: Remove object from an array?

Body:
remove an object from an array is not working properly ,but it add object perfectly

const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.indexOf(selected);
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
    setSelectedItems(data);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}

render button function add or remove on click it

  <MappedElement
   data={[{ _id: 1 }, { _id: 2 }]}
   renderElement={(value, index, arr) => {
   let check=selectedItems.some((obj) => obj._id === value._id);
   console.log("check", check);
   return (
    <DocumentCard key={index} className={file-list-item ${check ?
       "active" : ""}}
    onClick={() => addItem(value, arr, index)} /> ); }} />

Body:
Use

const addItem =(selected)=>{
let data = selectedItems ? [...selectedItems] : [];
if (data.length) {
  let index = data.findIndex(value => value._id === selected._id)ж
  console.log(index);
  if (index !== -1) {
    data.splice(index, 1);
  } else {
    data.push(selected);
  }
} else {
  data.push(selected);
}
console.log("selected", selectedItems);

setSelectedItems(data);
}


问:
How to count the strings in a vector?
I have a data set as I've shown below:

```<code>df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)
</code>```

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

```<code>desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)
</code>```

答:
Here's an approach with separate_rows from tidyr:

```<code>library(tidyr)
library(dplyr)
df_A %>%
  separate_rows(id, sep=", ") %>%
  group_by(id) %>%
  dplyr::summarize(counted_id = n())
## A tibble: 6 x 2
#  id    counted_id
#  <chr>      <int>
#1 1              1
#2 2              1
#3 3              3
#4 4              2
#5 5              1
#6 6              2
</code>```

Title: How to count the strings in a vector?

Body:
I have a data set as I've shown below:

df_A <- tribble(
      ~shop_name,      ~id,
        "A",         "1, 4, 3",
        "B",         "4, 6",
        "C",         "3, 5",
        "D",         "6, 2, 3",
)

Now, I want to group the data by each unique id which in the vector, and then count them accordingly. Do you think it is doable? How can I manipulate the data to get my desired data?

desired <- tribble(
  ~id,   ~counted_id,
  "1",      1,
  "2",      1,
  "3",      3,
  "4",      2,
  "5",      1,
  "6",      2,
)

Body:
Here's an approach with separate_rows from tidyr:

library(tidyr)
library(dplyr)
df_A %>%
  separate_rows(id, sep=", ") %>%
  group_by(id) %>%
  dplyr::summarize(counted_id = n())
## A tibble: 6 x 2
#  id    counted_id
#  <chr>      <int>
#1 1              1
#2 2              1
#3 3              3
#4 4              2
#5 5              1
#6 6              2


问:
Can't see result set in MySQLWorkbench, Mac OS Catalina
I can't see my result set after executing a query in MySQLWorkbench (8.0), I'm operating on Mac OS Catalina</p>

答:
I had the same issue, and it turns out the problem was that the font I had configured for the result set was no longer available after the OS update, and there seems to be no font fallback mechanism in MySQLWorkbench, so it failed to render anything.

The solution for me was to go to MySQLWorkbench > Preferences > Fonts and type in Helvetica 13 as the value of Resultset Grid.

You may also choose to also change the fonts for the other options like SQL Editor if you have trouble with the display of other sections of the app. And you are free to choose any other font family, as long as it’s actually installed on your machine.

If you put in an invalid value into any of those fields, you may need to restart the app to recover from the resulting display error. And note that changes to those font settings are only applied to new instances of the related UI widgets, so you have to request a new result set in order to see the changes.


问:
Using Java8 to find string values in one ArrayList present in another ArrayList using endsWith method
I have following code.

```<code>public class ComparingTwoLists {
    public static void main(String[] args) {
        List<String> small = Arrays.asList("AA", "BB");
        List<String> big = Arrays.asList("a.b.AA", "a.b.BB", "a.b.CC");
        List<String> list = new ArrayList<String>();

        Consumer<String> consumer = (String outer) -> {
            Stream<String> stream1 = small.stream();

            Consumer<String> innerConsumer = (String inner) -> {
                if (outer.endsWith(inner)) {
                    list.add(outer);
                }
            };

            stream1.forEach(innerConsumer);
        };

        Stream<String> stream2 = big.stream();
        stream2.forEach(consumer);

        System.out.println(list);
    }
}
</code>```

I am trying to find out if string values in small is present in string values of big at end of string, using method endWith() method.

Is this efficient way of doing it?

Another problem I am facing in this code is that when I am trying to debug this code, I am able to view/inspect the value of inner, but cannot view the value of outer. Is there a way to check the value of outer while debugging.

答:
You can do like this: </p>

```<code>big.stream()
    .filter(s -> small.stream().anyMatch(s::endsWith))
    .collect(Collectors.toList());
</code>```

Body:
I have following code.

public class ComparingTwoLists {
    public static void main(String[] args) {
        List<String> small = Arrays.asList("AA", "BB");
        List<String> big = Arrays.asList("a.b.AA", "a.b.BB", "a.b.CC");
        List<String> list = new ArrayList<String>();

        Consumer<String> consumer = (String outer) -> {
            Stream<String> stream1 = small.stream();

            Consumer<String> innerConsumer = (String inner) -> {
                if (outer.endsWith(inner)) {
                    list.add(outer);
                }
            };

            stream1.forEach(innerConsumer);
        };

        Stream<String> stream2 = big.stream();
        stream2.forEach(consumer);

        System.out.println(list);
    }
}

I am trying to find out if string values in small is present in string values of big at end of string, using method endWith() method.

Is this efficient way of doing it?

Another problem I am facing in this code is that when I am trying to debug this code, I am able to view/inspect the value of inner, but cannot view the value of outer. Is there a way to check the value of outer while debugging.

Body:
You can do like this:

big.stream()
    .filter(s -> small.stream().anyMatch(s::endsWith))
    .collect(Collectors.toList());


问:
Pandas Series Apply
I want to create a new pandas series from an existing one based on a condition. I want to take each value in the series and compare it to an array of five values and take the nearest of those five values as the value for the new column at that index.

This is what I have currently:

```<code>nom_loads = array([-1089.32556032,  -873.46034816,  -657.595136  ,  -441.72992384,
    -225.86471168])

final_data['FZnom'] = final_data.FZ.apply(lambda x: nom_loads[np.argmax(x - nom_loads)])
</code>```

But the column I get is simply 1089.3 i.e. nom_loads[0] in all the rows. In my understanding x in the lambda function should be each value of final_data.FZ row by row, but maybe that's incorrect on my part.

Ben

答:
I believe you want:

```<code>lambda x: nom_loads[np.abs(x - nom_loads).argmin()]
</code>```

inside apply because you are looking for nearest value, not farthest value. So argmax is not a correct choice.

You can use a broadcasting approach:

```<code>idx = np.abs(final_data.FZ.values[:,None] - nom_loads).argmin(-1)

final_data['FZnom'] = nom_loads[idx]
</code>```

Title: Pandas Series Apply

Body:
I want to create a new pandas series from an existing one based on a condition. I want to take each value in the series and compare it to an array of five values and take the nearest of those five values as the value for the new column at that index.

This is what I have currently:

nom_loads = array([-1089.32556032,  -873.46034816,  -657.595136  ,  -441.72992384,
    -225.86471168])

final_data['FZnom'] = final_data.FZ.apply(lambda x: nom_loads[np.argmax(x - nom_loads)])

But the column I get is simply 1089.3 i.e. nom_loads[0] in all the rows. In my understanding x in the lambda function should be each value of final_data.FZ row by row, but maybe that's incorrect on my part.

Ben

Body:
I believe you want:

lambda x: nom_loads[np.abs(x - nom_loads).argmin()]

inside apply because you are looking for nearest value, not farthest value. So argmax is not a correct choice.

You can use a broadcasting approach:

idx = np.abs(final_data.FZ.values[:,None] - nom_loads).argmin(-1)

final_data['FZnom'] = nom_loads[idx]


答:
Your problem is probably in indexOf method you're using.

You can not use this to find objects in your array.

There are several options you can use. You can use find or findIndex and pass a callback to find an object by the specified (preferably unique property of the object).

Example

```<code>let found = data.findIndex(item => item.id === selected.id);
</code>```

Title: Remove object from an array?

Body:
Your problem is probably in indexOf method you're using.

You can not use this to find objects in your array.

There are several options you can use. You can use find or findIndex and pass a callback to find an object by the specified (preferably unique property of the object).

Example

let found = data.findIndex(item => item.id === selected.id);


问:
How to extract CNN activations using keras?
I want to extract CNN activations from the first fully connected layer using keras. There's such a function in Caffe, but I cannot use that framework because I'm facing installation problems. I'm reading a research paper that uses those CNN activations but the author is using Caffe.

Is there a way to extract those CNN activations, so I can use them as items in transactions by using data mining association rules, apriori algorithm.

Of course first I have to extract the k largest magnitudes of CNN activations. So each image will be a transaction, and each activation will be an item.

I have the following code so far:

```<code>from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.layers import Dense, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
import matplotlib.pylab as plt

model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),
                 activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])
</code>```

答:
Mentioning the solution below using Tensorflow Keras.

In order to be able to access the Activations, first we should pass one or more images and then the Activations corresponds to those Images.

Code for passing an Input Image and it's preprocessing is shown below:

```<code>from tensorflow.keras.preprocessing import image

Test_Dir = '/Deep_Learning_With_Python_Book/Dogs_Vs_Cats_Small/test/cats'
Image_File = os.path.join(Test_Dir, 'cat.1545.jpg')

Image = image.load_img(Image_File, target_size = (150,150))

Image_Tensor = image.img_to_array(Image)

print(Image_Tensor.shape)

Image_Tensor = tf.expand_dims(Image_Tensor, axis = 0)

Image_Tensor = Image_Tensor/255.0
</code>```

Once the Model is defined, We can access Activations of a any Layer using the code shown below (with respect to Cat and Dog Dataset):

```<code># Extract the Model Outputs for all the Layers
Model_Outputs = [layer.output for layer in model.layers]
# Create a Model with Model Input as Input and the Model Outputs as Output
Activation_Model = Model(model.input, Model_Outputs)
Activations = Activation_Model.predict(Image_Tensor)
</code>```

Output of the First Fully Connected Layer (with respect to Cat and Dog Data) is:

```<code>print('Shape of Activation of First Fully Connected Layer is', Activations[-2].shape)
print('------------------------------------------------------------------------------------------')
print('Activation of First Fully Connected Layer is', Activations[-2])
</code>```

It's Output is shown below:

```<code>Shape of Activation of First Fully Connected Layer is (1, 512)
------------------------------------------------------------------------------------------
Activation of First Fully Connected Layer is [[0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.02759874 0.         0.         0.         0.
  0.         0.         0.00079661 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.04887392 0.         0.
  0.04422646 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.01124999
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.00286965 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.00027195 0.
  0.         0.02132209 0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.00511147 0.         0.         0.02347952 0.
  0.         0.         0.         0.         0.         0.
  0.02570331 0.         0.         0.         0.         0.03443285
  0.         0.         0.         0.         0.         0.
  0.         0.0068848  0.         0.         0.         0.
  0.         0.         0.         0.         0.00936454 0.
  0.00389365 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.00152553 0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.09215052 0.         0.         0.0284613  0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.00198757 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.02395868 0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.01150922 0.0119792
  0.         0.         0.         0.         0.         0.
  0.00775307 0.         0.         0.         0.         0.
  0.         0.         0.         0.01026413 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.01522083 0.         0.00377031 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.02235368 0.         0.         0.         0.
  0.         0.         0.         0.         0.00317057 0.
  0.         0.         0.         0.         0.         0.
  0.03029975 0.         0.         0.         0.         0.
  0.         0.         0.03843511 0.         0.         0.
  0.         0.         0.         0.         0.         0.02327696
  0.00557329 0.         0.02251234 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.01655817 0.         0.
  0.         0.         0.         0.         0.00221658 0.
  0.         0.         0.         0.02087847 0.         0.
  0.         0.         0.02594821 0.         0.         0.
  0.         0.         0.01515464 0.         0.         0.
  0.         0.         0.         0.         0.00019883 0.
  0.         0.         0.         0.         0.         0.00213376
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.00237587
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.02521542 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.00490679 0.         0.04504126 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.        ]]
</code>```

For more information, please refer the Section 5.4.1 Visualizing intermediate activations of the Book, Deep Learning Using Python by Francois Chollet, Father of Keras.

Hope this helps. Happy Learning!

Body:
I want to extract CNN activations from the first fully connected layer using keras. There's such a function in Caffe, but I cannot use that framework because I'm facing installation problems. I'm reading a research paper that uses those CNN activations but the author is using Caffe.

Is there a way to extract those CNN activations, so I can use them as items in transactions by using data mining association rules, apriori algorithm.

Of course first I have to extract the k largest magnitudes of CNN activations. So each image will be a transaction, and each activation will be an item.

I have the following code so far:

from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.layers import Dense, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.models import Sequential
import matplotlib.pylab as plt

model = Sequential()
model.add(Conv2D(32, kernel_size=(5, 5), strides=(1, 1),
                 activation='relu',
                 input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1000, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adam(),
              metrics=['accuracy'])

Body:
Mentioning the solution below using Tensorflow Keras.

In order to be able to access the Activations, first we should pass one or more images and then the Activations corresponds to those Images.

Code for passing an Input Image and it's preprocessing is shown below:

from tensorflow.keras.preprocessing import image

Test_Dir = '/Deep_Learning_With_Python_Book/Dogs_Vs_Cats_Small/test/cats'
Image_File = os.path.join(Test_Dir, 'cat.1545.jpg')

Image = image.load_img(Image_File, target_size = (150,150))

Image_Tensor = image.img_to_array(Image)

print(Image_Tensor.shape)

Image_Tensor = tf.expand_dims(Image_Tensor, axis = 0)

Image_Tensor = Image_Tensor/255.0

Once the Model is defined, We can access Activations of a any Layer using the code shown below (with respect to Cat and Dog Dataset):

# Extract the Model Outputs for all the Layers
Model_Outputs = [layer.output for layer in model.layers]
# Create a Model with Model Input as Input and the Model Outputs as Output
Activation_Model = Model(model.input, Model_Outputs)
Activations = Activation_Model.predict(Image_Tensor)

Output of the First Fully Connected Layer (with respect to Cat and Dog Data) is:

print('Shape of Activation of First Fully Connected Layer is', Activations[-2].shape)
print('------------------------------------------------------------------------------------------')
print('Activation of First Fully Connected Layer is', Activations[-2])

It's Output is shown below:

Shape of Activation of First Fully Connected Layer is (1, 512)
------------------------------------------------------------------------------------------
Activation of First Fully Connected Layer is [[0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.02759874 0.         0.         0.         0.
  0.         0.         0.00079661 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.04887392 0.         0.
  0.04422646 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.01124999
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.00286965 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.00027195 0.
  0.         0.02132209 0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.00511147 0.         0.         0.02347952 0.
  0.         0.         0.         0.         0.         0.
  0.02570331 0.         0.         0.         0.         0.03443285
  0.         0.         0.         0.         0.         0.
  0.         0.0068848  0.         0.         0.         0.
  0.         0.         0.         0.         0.00936454 0.
  0.00389365 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.00152553 0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.09215052 0.         0.         0.0284613  0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.00198757 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.02395868 0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.01150922 0.0119792
  0.         0.         0.         0.         0.         0.
  0.00775307 0.         0.         0.         0.         0.
  0.         0.         0.         0.01026413 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.01522083 0.         0.00377031 0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.02235368 0.         0.         0.         0.
  0.         0.         0.         0.         0.00317057 0.
  0.         0.         0.         0.         0.         0.
  0.03029975 0.         0.         0.         0.         0.
  0.         0.         0.03843511 0.         0.         0.
  0.         0.         0.         0.         0.         0.02327696
  0.00557329 0.         0.02251234 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.01655817 0.         0.
  0.         0.         0.         0.         0.00221658 0.
  0.         0.         0.         0.02087847 0.         0.
  0.         0.         0.02594821 0.         0.         0.
  0.         0.         0.01515464 0.         0.         0.
  0.         0.         0.         0.         0.00019883 0.
  0.         0.         0.         0.         0.         0.00213376
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.00237587
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.02521542 0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.00490679 0.         0.04504126 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.        ]]

For more information, please refer the Section 5.4.1 Visualizing intermediate activations of the Book, Deep Learning Using Python by Francois Chollet, Father of Keras.

Hope this helps. Happy Learning!


问:
How to convert array byte to string in java
Before that sorry for my bad english because it's not my first language.
Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2.  I've tried but always error, i hope someone can help me.

Here's my code:

```<code> package exception;

    public class TugasTiga {
        public static void main (String [] args) {
            byte[] b = new byte[5];
            System.out.println("Input bilangan bulat: ");
            try { System.in.read(b);
            } catch (java.io.IOException e);
            int N = Integer.valueOf(b).intValue();
            System.out.println("Hasil: " + (N+2));
        }
    }
</code>```

答:
Here's the solution:

```<code>byte[] bytes = new byte[5]; //create the list
String finalS = ""; //create the string
for(byte element : bytes) { //for all elements in the list
    finalS += Byte.toString(element); //add to the string "finalS" the byte converted to string
}
</code>```

EXAMPLE: if the 5 bytes are {1,2,3,4,5}, the string is "12345"

Body:
Before that sorry for my bad english because it's not my first language.
Excuse me, i'm trying to convert array byte to string in error handling try catch java. And if user input integers, the result will be +2.  I've tried but always error, i hope someone can help me.

Here's my code:

 package exception;

    public class TugasTiga {
        public static void main (String [] args) {
            byte[] b = new byte[5];
            System.out.println("Input bilangan bulat: ");
            try { System.in.read(b);
            } catch (java.io.IOException e);
            int N = Integer.valueOf(b).intValue();
            System.out.println("Hasil: " + (N+2));
        }
    }

Body:
Here's the solution:

byte[] bytes = new byte[5]; //create the list
String finalS = ""; //create the string
for(byte element : bytes) { //for all elements in the list
    finalS += Byte.toString(element); //add to the string "finalS" the byte converted to string
}

EXAMPLE: if the 5 bytes are {1,2,3,4,5}, the string is "12345"


问:
Log to rsyslog facility from a python script
I have this in my /etc/rsyslog.conf:

```<code>local0.*     /var/log/local.log
</code>```

And I have a simple python script which reads from standard input and is supposed to send to local0

```<code>#!/usr/bin/python3

import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message\n\n")
</code>```

But it does not work. rsyslog does not see the messages as comming to local0

Only when I change to *.* does rsyslog see it:

```<code>*.*     /var/log/local.log
</code>```

I assume I don't properly configure the facility in my python script.

How can I specify I want to log to local0 ?

答:
Rsyslog and local*:

Rsyslog have the facilities local0 to local7 that are "custom" unused facilities that syslog provides for the user. If a developer create an application and wants to make it log to syslog, or if you want to redirect the output of anything to syslog (for example, Apache logs), you can choose to send it to any of the local# facilities. Then, you can use /etc/syslog.conf (or /etc/rsyslog.conf) to save the logs being sent to that local# to a file, or to send it to a remote server (source).

Config:

Under /etc/rsyslog.conf

```<code>local0.*     /var/log/local.log
</code>```

This is correct and it assign the log file /var/log/local.log to apps that log to local0. As an other example kern.=warn -/var/log/kernel/warnings.log can be used to  log kernel warnings.

Python application/script:

```<code>#!/usr/bin/python3
import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message {line}\n\n")
</code>```

The initial code does work, and as pointed in the comments this can be used as an alternative and {line} variable have been added as suggested by @apoorva-kamath...

The important side here is on the communication between the Python script and Rsyslog.

Also as pointed on the command try is to reload rsyslog systemctl restart rsyslog; you can as well check the Rsyslog config with rsyslogd -N1 and check if rsyslog is working correctly with:

```<code>sudo cat /var/log/messages | grep rsyslog
</code>```

Depending on the Python script running context, communications to Rsyslog may fail, further details on your config are needed otherwise you can try (from the script's context):

```<code>logger -p local0.error "TroubleshootingTest"
</code>```

And finally check the data transmission with:

```<code>sudo netstat -taupn | grep syslog
</code>```

Documentations:

More details about Python syslog, troubleshooting Rsyslog and Rsyslog facility

Body:
I have this in my /etc/rsyslog.conf:

local0.*     /var/log/local.log

And I have a simple python script which reads from standard input and is supposed to send to local0

#!/usr/bin/python3

import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message\n\n")

But it does not work. rsyslog does not see the messages as comming to local0

Only when I change to *.* does rsyslog see it:

*.*     /var/log/local.log

I assume I don't properly configure the facility in my python script.

How can I specify I want to log to local0 ?

Body:
Rsyslog and local*:

Rsyslog have the facilities local0 to local7 that are "custom" unused facilities that syslog provides for the user. If a developer create an application and wants to make it log to syslog, or if you want to redirect the output of anything to syslog (for example, Apache logs), you can choose to send it to any of the local# facilities. Then, you can use /etc/syslog.conf (or /etc/rsyslog.conf) to save the logs being sent to that local# to a file, or to send it to a remote server (source).

Config:

Under /etc/rsyslog.conf

local0.*     /var/log/local.log

This is correct and it assign the log file /var/log/local.log to apps that log to local0. As an other example kern.=warn -/var/log/kernel/warnings.log can be used to  log kernel warnings.

Python application/script:

#!/usr/bin/python3
import sys, syslog

syslog.openlog(ident="MY_SCRIPT", facility=syslog.LOG_LOCAL0)

for line in sys.stdin:
    syslog.syslog(syslog.LOG_WARNING, f"Message {line}\n\n")

The initial code does work, and as pointed in the comments this can be used as an alternative and {line} variable have been added as suggested by @apoorva-kamath...

The important side here is on the communication between the Python script and Rsyslog.

Also as pointed on the command try is to reload rsyslog systemctl restart rsyslog; you can as well check the Rsyslog config with rsyslogd -N1 and check if rsyslog is working correctly with:

sudo cat /var/log/messages | grep rsyslog

Depending on the Python script running context, communications to Rsyslog may fail, further details on your config are needed otherwise you can try (from the script's context):

logger -p local0.error "TroubleshootingTest"

And finally check the data transmission with:

sudo netstat -taupn | grep syslog

Documentations:

More details about Python syslog, troubleshooting Rsyslog and Rsyslog facility


问:
How To Get Every Alternate Object In Array In JS
I wanted to know how can we get every alternate object in a array. For EG -

```<code>arr = ["foo","bar","foo1","bar1"]
</code>```

I Need The values -

```<code>fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]
</code>```

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance

答:
If I know what you mean... We can be reasoned with odd and even index.
In this way:</p>

```<code>let arr = ["foo","bar","foo1", "bar1"],
    fir_alt = [],
    sec_alt = [];

for (let i=0;i<arr.length;i++){
    if ((i+2)%2==0) {
        sec_alt.push(arr[i]);
    }
    else {
        fir_alt.push(arr[i]);
    }
}
</code>```

Body:
I wanted to know how can we get every alternate object in a array. For EG -

arr = ["foo","bar","foo1","bar1"]

I Need The values -

fir_alt = ["foo","foo1"]
sec_alt = ["bar","bar1"]

If This Helps This Is My Intention -

I am trying to link localstorage and firestore using the js-sdk.. Data is in array and have to take the array to store it back in localstorage.fir_alt would be the keys and sec_alt would be values. So I Can Make it Much More Multi-Device..

Thanks In Advance

Body:
If I know what you mean... We can be reasoned with odd and even index.
In this way:

let arr = ["foo","bar","foo1", "bar1"],
    fir_alt = [],
    sec_alt = [];

for (let i=0;i<arr.length;i++){
    if ((i+2)%2==0) {
        sec_alt.push(arr[i]);
    }
    else {
        fir_alt.push(arr[i]);
    }
}


问:
textbox textchanged event always firing
I have a form with a few text-boxes and a Grid-view. There is this one text-box called "Inward Number", whose text-changed event fires all the time. When i want to fire another control's event, it simply fires the text-changed event of the Inward Number text-box. This happens with all of the other controls. Can someone please help?

```<code>protected void txtInward_No_TextChanged(object sender, EventArgs e)
{
   a = 'A';
   NewRow();
}
</code>```

I have used the correct names, but still this error occurs.

```<code><asp:TextBox ID="txtInward_No" runat="server" Width="220px" CssClass="txtbox"
                    EnableViewState="False"
                    AutoPostBack="True" ontextchanged="txtInward_No_TextChanged">
</asp:TextBox>
</code>```

new row just makes a new row in my grid.

private void NewRow()
       {
        int rowIndex = 0;

```<code>        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtnew = new DataTable();
            dtnew = (DataTable)ViewState["CurrentTable"];
            DataRow drr = null;
            if (dtnew.Rows.Count > 0)
            {
                for (int i = 1; i <= dtnew.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
                    TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox4");
                    TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox5");

                    drr = dtnew.NewRow();
                    if (txtInward_No.Text =="1")
                    {
                        drr["InwardNumber"] = txtInward_No.Text + b.ToString();
                    }
                    else
                    {
                        drr["InwardNumber"] = txtInward_No.Text + a.ToString();
                    }
                    drr["Bags"] = box1.Text;
                    drr["GrossWt"] = box2.Text;
                    drr["TareWt"] = box3.Text;
                    drr["NetWt"] = box4.Text;
                    drr["DCBillWt"] = box5.Text;

                    rowIndex++;
                }
                dtnew.Rows.Add(drr);
                ViewState["CurrentTable"] = dtnew;
                GridView1.DataSource = dtnew;
                GridView1.DataBind();
            }
        }
        PrevData();
        b++;
        a++;
   }
</code>```

答:
I think what's probably happening is that ASP.NET relies on ViewState to decide whether the TextBox's value has changed. But you've disabled ViewState on this control. I'm not sure why it can't use ControlState instead, but you could try enabling ViewState for this TextBox and see if this has an effect.

The MSDN page on the OnTextChanged event mentions this.

Title: textbox textchanged event always firing

Body:
I have a form with a few text-boxes and a Grid-view. There is this one text-box called "Inward Number", whose text-changed event fires all the time. When i want to fire another control's event, it simply fires the text-changed event of the Inward Number text-box. This happens with all of the other controls. Can someone please help?

protected void txtInward_No_TextChanged(object sender, EventArgs e)
{
   a = 'A';
   NewRow();
}

I have used the correct names, but still this error occurs.

<asp:TextBox ID="txtInward_No" runat="server" Width="220px" CssClass="txtbox"
                    EnableViewState="False"
                    AutoPostBack="True" ontextchanged="txtInward_No_TextChanged">
</asp:TextBox>

new row just makes a new row in my grid.

private void NewRow()
       {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtnew = new DataTable();
            dtnew = (DataTable)ViewState["CurrentTable"];
            DataRow drr = null;
            if (dtnew.Rows.Count > 0)
            {
                for (int i = 1; i <= dtnew.Rows.Count; i++)
                {
                    TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox1");
                    TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox2");
                    TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
                    TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox4");
                    TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox5");

                    drr = dtnew.NewRow();
                    if (txtInward_No.Text =="1")
                    {
                        drr["InwardNumber"] = txtInward_No.Text + b.ToString();
                    }
                    else
                    {
                        drr["InwardNumber"] = txtInward_No.Text + a.ToString();
                    }
                    drr["Bags"] = box1.Text;
                    drr["GrossWt"] = box2.Text;
                    drr["TareWt"] = box3.Text;
                    drr["NetWt"] = box4.Text;
                    drr["DCBillWt"] = box5.Text;

                    rowIndex++;
                }
                dtnew.Rows.Add(drr);
                ViewState["CurrentTable"] = dtnew;
                GridView1.DataSource = dtnew;
                GridView1.DataBind();
            }
        }
        PrevData();
        b++;
        a++;
   }


问:
How to exclude one element from selecting entire body
my question is:

I have a context menu that should disappear whenever you click anywhere else but one row in that context menu.

id = "except" is a li element within my context menu(which is a ul element). I try to exclude that element from selection of the entire body but it does not work like that because except is burried deep in multiple other parent elements

body->.wrapper->.content-wrapper->.content->#contextMenu->#except

```<code>$("body").not("#except")
            .one("click",
                () => {
                        $("#contextMenu").hide();
                        $("body").detach("#contextMenu");
                });
</code>```

Is there a way to specify the path from body to #except element inside .not() function? I tried multiple things without success

I can make my way from body to contextMenu like this $("body>>>>"), but the problem is, my click function will only be called when I click somewhere inside contextMenu.

thank you!

EDIT: important info: These lines of code are inside a contextMenuHandler function so I think I need to disable #except somewhere before that click function and that's why I try .not() function

答:
You can do like this

```<code>$("body").one("click", (event) => {
    if (event.target.id !== 'except') {
        $("#contextMenu").hide();
        $("body").detach("#contextMenu");
    }
});
</code>```

$("body").not("#except") will select body tags those don't have except id. Which will not work in your case.

Update:

If I didn't misunderstood your problem then this will work for you

```<code>$("body").on("click.contextMenu", (event) => {
    if (event.target.id !== 'except') {
        $("#contextMenu").hide();
        $("body").detach("#contextMenu");
        $("body").off("click.contextMenu");
    }
});
</code>```

What I did is,
Instead of binding event by one binded it with on. Also specified a namespace.

The reason behind specifying namespace is we can then unbind this event using the namespace.

I have used contextMenu here, you can specify any name.

Body:
my question is:

I have a context menu that should disappear whenever you click anywhere else but one row in that context menu.

id = "except" is a li element within my context menu(which is a ul element). I try to exclude that element from selection of the entire body but it does not work like that because except is burried deep in multiple other parent elements

body->.wrapper->.content-wrapper->.content->#contextMenu->#except

$("body").not("#except")
            .one("click",
                () => {
                        $("#contextMenu").hide();
                        $("body").detach("#contextMenu");
                });

Is there a way to specify the path from body to #except element inside .not() function? I tried multiple things without success

I can make my way from body to contextMenu like this $("body>>>>"), but the problem is, my click function will only be called when I click somewhere inside contextMenu.

thank you!

EDIT: important info: These lines of code are inside a contextMenuHandler function so I think I need to disable #except somewhere before that click function and that's why I try .not() function

Body:
You can do like this

$("body").one("click", (event) => {
    if (event.target.id !== 'except') {
        $("#contextMenu").hide();
        $("body").detach("#contextMenu");
    }
});

$("body").not("#except") will select body tags those don't have except id. Which will not work in your case.

Update:

If I didn't misunderstood your problem then this will work for you

$("body").on("click.contextMenu", (event) => {
    if (event.target.id !== 'except') {
        $("#contextMenu").hide();
        $("body").detach("#contextMenu");
        $("body").off("click.contextMenu");
    }
});

What I did is,
Instead of binding event by one binded it with on. Also specified a namespace.

The reason behind specifying namespace is we can then unbind this event using the namespace.

I have used contextMenu here, you can specify any name.


问:
Android 10 Bluetooth LE Scan Issues
I am trying to get a simple Bluetooth LE Scanning app working under Android 10

The Scan starts but does not discover the devices.

There is a lot of traffic about correct permissions needed for Android 10 and I think I have them correct, Currently, I am requiring and asking the user for:

BLUETOOTH
BLUETOOTH_ADMIN
ACCESS_FINE_LOCATION
FOREGROUND_SERVICE
ACCESS_BACKGROUND_LOCATION

The app is simple, just a single form, a start scan button, a stop scan button and a textview to show the results.

Can someone point out what i have missed?

Many thanks

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

BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;

Button startScanningButton;
Button stopScanningButton;
TextView peripheralTextView;

private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private static final int PERMISSION_REQUEST_BACKGROUND_LOCATION = 2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);

    peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
    peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

    startScanningButton = (Button) findViewById(R.id.StartScanButton);
    startScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startScanning();
        }
    });

    stopScanningButton = (Button) findViewById(R.id.StopScanButton);
    stopScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopScanning();
        }
    });
    stopScanningButton.setVisibility(View.INVISIBLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                if (this.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("This app needs background location access");
                    builder.setMessage("Please grant location access so this app can detect beacons in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @TargetApi(23)
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                                    PERMISSION_REQUEST_BACKGROUND_LOCATION);
                        }

                    });
                    builder.show();
                }
                else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since background location access has not been granted, this app will not be able to discover beacons in the background.  Please go to Settings -> Applications -> Permissions and grant background location access to this app.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }

            }
        } else {
            if (!this.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                        PERMISSION_REQUEST_FINE_LOCATION);
            }
            else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons.  Please go to Settings -> Applications -> Permissions and grant location access to this app.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }

        }
    }

    final BluetoothManager btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);

    btAdapter = btManager.getAdapter();

    if (btAdapter == null || !btAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
    }

    btScanner = btAdapter.getBluetoothLeScanner();

}

// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + "\n");
    }
};

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_FINE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                System.out.println("fine location permission granted");
            } else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover devices when in the background.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }
            return;
        }
    }
}

public void startScanning() {
    peripheralTextView.setText("");
    peripheralTextView.append("Start Scanning");
    startScanningButton.setVisibility(View.INVISIBLE);
    stopScanningButton.setVisibility(View.VISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.startScan(leScanCallback);
        }
    });
}

public void stopScanning() {
    peripheralTextView.append("Stopped Scanning");
    startScanningButton.setVisibility(View.VISIBLE);
    stopScanningButton.setVisibility(View.INVISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.stopScan(leScanCallback);
        }
    });
}
</code>```

}

答: It seems Bluetooth scanning is disable. Please find below screenshot. Only location enable will not work along with location you need to enable Bluetooth scanning.

Title: Android 10 Bluetooth LE Scan Issues

Body:
I am trying to get a simple Bluetooth LE Scanning app working under Android 10

The Scan starts but does not discover the devices.

There is a lot of traffic about correct permissions needed for Android 10 and I think I have them correct, Currently, I am requiring and asking the user for:

BLUETOOTH
BLUETOOTH_ADMIN
ACCESS_FINE_LOCATION
FOREGROUND_SERVICE
ACCESS_BACKGROUND_LOCATION

The app is simple, just a single form, a start scan button, a stop scan button and a textview to show the results.

Can someone point out what i have missed?

Many thanks

public class MainActivity extends AppCompatActivity {

BluetoothAdapter btAdapter;
BluetoothLeScanner btScanner;

Button startScanningButton;
Button stopScanningButton;
TextView peripheralTextView;

private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSION_REQUEST_FINE_LOCATION = 1;
private static final int PERMISSION_REQUEST_BACKGROUND_LOCATION = 2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
    NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
    NavigationUI.setupWithNavController(navView, navController);

    peripheralTextView = (TextView) findViewById(R.id.PeripheralTextView);
    peripheralTextView.setMovementMethod(new ScrollingMovementMethod());

    startScanningButton = (Button) findViewById(R.id.StartScanButton);
    startScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startScanning();
        }
    });

    stopScanningButton = (Button) findViewById(R.id.StopScanButton);
    stopScanningButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            stopScanning();
        }
    });
    stopScanningButton.setVisibility(View.INVISIBLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            if (this.checkSelfPermission(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                if (this.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("This app needs background location access");
                    builder.setMessage("Please grant location access so this app can detect beacons in the background.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @TargetApi(23)
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                                    PERMISSION_REQUEST_BACKGROUND_LOCATION);
                        }

                    });
                    builder.show();
                }
                else {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Functionality limited");
                    builder.setMessage("Since background location access has not been granted, this app will not be able to discover beacons in the background.  Please go to Settings -> Applications -> Permissions and grant background location access to this app.");
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }

                    });
                    builder.show();
                }

            }
        } else {
            if (!this.shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_BACKGROUND_LOCATION},
                        PERMISSION_REQUEST_FINE_LOCATION);
            }
            else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons.  Please go to Settings -> Applications -> Permissions and grant location access to this app.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }

        }
    }

    final BluetoothManager btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);

    btAdapter = btManager.getAdapter();

    if (btAdapter == null || !btAdapter.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent,REQUEST_ENABLE_BT);
    }

    btScanner = btAdapter.getBluetoothLeScanner();

}

// Device scan callback.
private ScanCallback leScanCallback = new ScanCallback() {
    @Override
    public void onScanResult(int callbackType, ScanResult result) {
        peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() + "\n");
    }
};

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_FINE_LOCATION: {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                System.out.println("fine location permission granted");
            } else {
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Functionality limited");
                builder.setMessage("Since location access has not been granted, this app will not be able to discover devices when in the background.");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {

                    @Override
                    public void onDismiss(DialogInterface dialog) {
                    }

                });
                builder.show();
            }
            return;
        }
    }
}

public void startScanning() {
    peripheralTextView.setText("");
    peripheralTextView.append("Start Scanning");
    startScanningButton.setVisibility(View.INVISIBLE);
    stopScanningButton.setVisibility(View.VISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.startScan(leScanCallback);
        }
    });
}

public void stopScanning() {
    peripheralTextView.append("Stopped Scanning");
    startScanningButton.setVisibility(View.VISIBLE);
    stopScanningButton.setVisibility(View.INVISIBLE);
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            btScanner.stopScan(leScanCallback);
        }
    });
}

}


问:
about Java.sql.TimeStamp and angular
i am working on a website (angular 9, spring boot).

i need a user to be able to send me a Date AND Time of a certain event,
while on the java side i am working with java.sql.TimeStamp
and in angular i am using both NgbDatepicker (for date) and Time (for hours&minutes). what i want to do is to combine them to be the same as the java.sql.TimeStamp with the TimeZone.

is there any idea that should help me, or should i maybe send them as they are to the java and create a new TimeStamp each time before putting into the DB?

答:
I had the same promblem: My solution: I got a 'date' (as ISO 8601 string) from backend. In the frontend I created a second variable (a copy): One copy for date picker and one for time input. Before sending back to backend I joined these two values into one iso string.

```<code>const date = new Date(datevalue); // datevalue from datepicker
const hhmm = timevalue.split(':');
date.setHours(parseInt(hhmm[0], 10));
date.setMinutes(parseInt(hhmm[1], 10));
date.setSeconds(0);
date.setMilliseconds(0);
this.resultingDate = date;
</code>```

In my solution :

date: input matDatepicker

time: input type="time"

Title: about Java.sql.TimeStamp and angular

Body:
I had the same promblem: My solution: I got a 'date' (as ISO 8601 string) from backend. In the frontend I created a second variable (a copy): One copy for date picker and one for time input. Before sending back to backend I joined these two values into one iso string.

const date = new Date(datevalue); // datevalue from datepicker
const hhmm = timevalue.split(':');
date.setHours(parseInt(hhmm[0], 10));
date.setMinutes(parseInt(hhmm[1], 10));
date.setSeconds(0);
date.setMilliseconds(0);
this.resultingDate = date;

In my solution :

date: input matDatepicker

time: input type="time"


问:
Babel-Loader Syntax error on npm run build
I am not very strong with webpack and am trying to update webpack from V3 to V4 and have managed to update my webpack config to the point where its not throwing depreciation errors at me, but I am now stuck on a syntax error from babel-loader:

```<code>      Module build failed (from ./node_modules/babel-loader/lib/index.js):
      /path/react/node_modules/schema-utils/dist/util/hints.js:16
      const currentSchema = { ...schema
      SyntaxError: Unexpected token ...
</code>```

In my webpack config I have this:

```<code>         test: /\.(js|jsx)$/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  presets: [
                    '@babel/preset-env',
                    '@babel/preset-react',
                    {
                      plugins: [
                        '@babel/plugin-proposal-class-properties'
                      ]
                    }
                  ],
                  compact: true,
                  cacheDirectory: false, // @todo: legacy option: true
                },
              }
            ]
</code>```

and I am using the following versions:

```<code> "@babel/core": "^7.1.6",
 "@babel/plugin-proposal-class-properties": "^7.8.3",
 "@babel/preset-env": "^7.1.6",
 "@babel/preset-react": "^7.0.0",
 "babel-loader": "^8.0.4",
</code>```

I have tried multiple times with diffent versions of babel but always end up at this message. Can anyone see any obvious mistakes I am making?

答:
The SyntaxError: Unexpected token ... implies that your node isn't transpiling ES6. Have you upgraded node/npm to relatively new versions?

Also, if you're changing versions, I would suggest deleting your node_modules folder and package-lock.json file before running npm install again.

Body:
I am not very strong with webpack and am trying to update webpack from V3 to V4 and have managed to update my webpack config to the point where its not throwing depreciation errors at me, but I am now stuck on a syntax error from babel-loader:

      Module build failed (from ./node_modules/babel-loader/lib/index.js):
      /path/react/node_modules/schema-utils/dist/util/hints.js:16
      const currentSchema = { ...schema
      SyntaxError: Unexpected token ...

In my webpack config I have this:

         test: /\.(js|jsx)$/,
            use: [
              {
                loader: 'babel-loader',
                options: {
                  presets: [
                    '@babel/preset-env',
                    '@babel/preset-react',
                    {
                      plugins: [
                        '@babel/plugin-proposal-class-properties'
                      ]
                    }
                  ],
                  compact: true,
                  cacheDirectory: false, // @todo: legacy option: true
                },
              }
            ]

and I am using the following versions:

 "@babel/core": "^7.1.6",
 "@babel/plugin-proposal-class-properties": "^7.8.3",
 "@babel/preset-env": "^7.1.6",
 "@babel/preset-react": "^7.0.0",
 "babel-loader": "^8.0.4",

I have tried multiple times with diffent versions of babel but always end up at this message. Can anyone see any obvious mistakes I am making?


问:
NetSuite: Attach a SalesRep and a receivable account to a customer record
I am trying to update customers,
I am try to attach a salesrep and a receivablesAccount to the newly created customers.

When I use the following code, I encounter the following error:
ReferenceError: "RecordRef" is not defined.

```<code>/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/currentRecord'],
    function(currentRecord) {
  function beforeSubmit(context) {
    var curRecord = context.newRecord;
    curRecord.salesrep = new RecordRef(){
      InternalId: "-5"
    };
    curRecord.receivablesAccount = new RecordRef(){
      ??? how to retrieve the id ?
    };
    try {
      log.debug('record created successfully');
    } catch (e) {
      log.error(e.name);
    }
  }
        return {
            beforeLoad: beforeLoad,
            beforeSubmit: beforeSubmit,
            afterSubmit: afterSubmit
        };
    });
</code>```

答:
RecordRef() is something you would use if you were trying to connect to NetSuite via SOAP web services with C# or PHP.  With SuiteScript, you would use .setValue() to set these values.

```<code>/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define([],
  function () {
    function beforeSubmit(context) {
      var curRecord = context.newRecord;
      curRecord.setValue({ fieldId: 'salesrep', value: -5 });
      curRecord.setValue({ fieldId: 'receivablesaccount', value: 7 });
    }

    return {
      beforeSubmit: beforeSubmit,
    };
  }
);
</code>```

To find the internal ID for your chart of accounts, navigate to Home -> Set Preferences, check the Show Internal IDS box, and click Save.  Then navigate to Setup -> Accounting -> Chart of Accounts.  You should be able to find the internal ID for the receivables account that you wish to use.

Also, the N/currentRecord module can only be used in client scripts and modules and should not be used in user event scripts.

Body:
I am trying to update customers,
I am try to attach a salesrep and a receivablesAccount to the newly created customers.

When I use the following code, I encounter the following error:
ReferenceError: "RecordRef" is not defined.

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/currentRecord'],
    function(currentRecord) {
  function beforeSubmit(context) {
    var curRecord = context.newRecord;
    curRecord.salesrep = new RecordRef(){
      InternalId: "-5"
    };
    curRecord.receivablesAccount = new RecordRef(){
      ??? how to retrieve the id ?
    };
    try {
      log.debug('record created successfully');
    } catch (e) {
      log.error(e.name);
    }
  }
        return {
            beforeLoad: beforeLoad,
            beforeSubmit: beforeSubmit,
            afterSubmit: afterSubmit
        };
    });

Body:
RecordRef() is something you would use if you were trying to connect to NetSuite via SOAP web services with C# or PHP.  With SuiteScript, you would use .setValue() to set these values.

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define([],
  function () {
    function beforeSubmit(context) {
      var curRecord = context.newRecord;
      curRecord.setValue({ fieldId: 'salesrep', value: -5 });
      curRecord.setValue({ fieldId: 'receivablesaccount', value: 7 });
    }

    return {
      beforeSubmit: beforeSubmit,
    };
  }
);

To find the internal ID for your chart of accounts, navigate to Home -> Set Preferences, check the Show Internal IDS box, and click Save.  Then navigate to Setup -> Accounting -> Chart of Accounts.  You should be able to find the internal ID for the receivables account that you wish to use.

Also, the N/currentRecord module can only be used in client scripts and modules and should not be used in user event scripts.


问:
How can I use git from within Xcode?
How can I use git from within Xcode? I've found SVN easy to use from Xcode; can I use git as easily?</p>

答:
You CAN use git easily from Xcode. Easily, but not well.

One of the design decisions Apple made with Xcode was to present a unified interface to version management regardless of what version control system was on the back-end. So if you're using git, you only get the subset of git functionality that svn also supports. No index, no stash, not really even branching.

I've quit trying to use Xcode's onboard git "integration". It's broken by design.

Title: How can I use git from within Xcode?