问:
Getting an error 'redirect' on views.py of django project
All the registration form is running fine.The problem is on the redirect of function addUser.I am getting the error on redirect.I am trying to save the data in the admin panel but i am stuck on this.

```<code> from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import RegistrationForm
from .models import RegistrationData
#from django.contrib.auth.form import UserCreationForm

# Create your views here.
def index(request):
return render(request, "Yatri/home.html")

def SignUp(request):
 context= {"form":RegistrationForm}
 return render(request,"Yatri/register.html",context)

def addUser(request):
  form=RegistrationForm(request.POST)
  if form.is_valid():
        register=RegistrationData(username=form.cleaned_data['username'],
                                  password=form.cleaned_data['password'],
                                  email=form.cleaned_data['email'],
                                  phone=form.cleaned_data['phone'],

        register.save()

  return redirect('index')
</code>```

I expect the username,password,email and phone to be saved in database but i get the error the site cant be reached.

Urls.py

```<code>from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('Signup/',views.SignUp,name='Signup'),
path('addUser/',views.addUser,name='addUser'),
]
</code>```

答:
missed parentheses in addUser view:</p>

```<code>def addUser(request):
  form=RegistrationForm(request.POST)
  if form.is_valid():
        register=RegistrationData(username=form.cleaned_data['username'],
                                  password=form.cleaned_data['password'],
                                  email=form.cleaned_data['email'],
                                  phone=form.cleaned_data['phone'],)

        register.save()

  return redirect('index')
</code>```

Body:
All the registration form is running fine.The problem is on the redirect of function addUser.I am getting the error on redirect.I am trying to save the data in the admin panel but i am stuck on this.

 from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import RegistrationForm
from .models import RegistrationData
#from django.contrib.auth.form import UserCreationForm

# Create your views here.
def index(request):
return render(request, "Yatri/home.html")

def SignUp(request):
 context= {"form":RegistrationForm}
 return render(request,"Yatri/register.html",context)

def addUser(request):
  form=RegistrationForm(request.POST)
  if form.is_valid():
        register=RegistrationData(username=form.cleaned_data['username'],
                                  password=form.cleaned_data['password'],
                                  email=form.cleaned_data['email'],
                                  phone=form.cleaned_data['phone'],

        register.save()

  return redirect('index')

I expect the username,password,email and phone to be saved in database but i get the error the site cant be reached.

Urls.py

from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
path('', views.index, name='index'),
path('Signup/',views.SignUp,name='Signup'),
path('addUser/',views.addUser,name='addUser'),
]

Body:
missed parentheses in addUser view:

def addUser(request):
  form=RegistrationForm(request.POST)
  if form.is_valid():
        register=RegistrationData(username=form.cleaned_data['username'],
                                  password=form.cleaned_data['password'],
                                  email=form.cleaned_data['email'],
                                  phone=form.cleaned_data['phone'],)

        register.save()

  return redirect('index')


来源: stackexchange

问:
How can I make my bot make embeds from collected messages
I want to make my bot to collect messages and then put them in to a embed

I already tried collectmessages and awaitmessages but it's not working.

```<code>const colectoraddbuilding = await new  Discord.MessageCollector(msgobject.channel, msg => msg.author ==  msgobject.author ,{time: 10000});

building1 = ${colectoraddbuilding.collected};
</code>```

there are not errors but when i try to send the embed where the building 1 var is is then its not adding the new text to the building 1 var

答:
If you have the messages and that part is working, then I think the problem is here:

building1 = ${colectoraddbuilding.collected};
```

<p>Two things, first, you should use <code>const</code> in you declaration of building1 to prevent unwanted globals, and two, <code>building1</code> is not a string, so that could be a big problem.</p>

<p>Final:</p>

<pre class="lang-js prettyprint-override"><code>const building1 = `${colectoraddbuilding.collected}`;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to make my bot to collect messages and then put them in to a embed

I already tried collectmessages and awaitmessages but it's not working.

const colectoraddbuilding = await new  Discord.MessageCollector(msgobject.channel, msg => msg.author ==  msgobject.author ,{time: 10000});

building1 = ${colectoraddbuilding.collected};

there are not errors but when i try to send the embed where the building 1 var is is then its not adding the new text to the building 1 var

Body:
If you have the messages and that part is working, then I think the problem is here:

building1 = ${colectoraddbuilding.collected};

Two things, first, you should use const in you declaration of building1 to prevent unwanted globals, and two, building1 is not a string, so that could be a big problem.

Final:

const building1 = `${colectoraddbuilding.collected}`;


问:
Android implement search with view model and live data
I'm working on a project in android for a udacity course I'm currently trying to implement a search function while adhering to android architecture components and using firestore and room I'm fairly new to all these concepts so please point out anything that seems wrong.

So I made a database repository to keep my firestore and room databases in sync and to deliver the data. I'm then using viewmodel and the observer pattern (I think) so my observer gets the data and looks for changes gives it to my adapter (refreshMyList(List)) which populates a recyclerview like this :

```<code> contactViewModel = ViewModelProviders.of(this).get(ContactsViewModel.class);
 contactViewModel.getAllContacts().observe(this, new
 Observer<List<DatabaseContacts>>() {
        @Override
        public void onChanged(@Nullable List<DatabaseContacts>
        databaseContacts) {
            ArrayList<DatabaseContacts> tempList = new ArrayList<>();
            tempList.addAll(databaseContacts);
            contactsAdapter.refreshMyList(tempList);
            if (tempList.size() < 1) {
                results.setVisibility(View.VISIBLE);
            } else {
                results.setVisibility(View.GONE);
            }
        }
    });
</code>```

I now want to perform a search of the data, I have my room queries all set up fine and I have methods in my data repository to get contacts based on a search string but I cant seem to refresh my list I've read that there are ways to do it like Transformations.switchMap ? but i cant seem to wrap my head around how it works can anyone help me

Currently I'm trying to return a List of results from an async task, it used to return live data but I changed it as getValue() was always null, not sure if that's correct, heres the async :

```<code>private static class searchContactByName extends AsyncTask<String, Void,
ArrayList<DatabaseContacts>> {

    private LiveDatabaseContactsDao mDao;

    searchContactByName(LiveDatabaseContactsDao dao){
        this.mDao = dao;
    }

    @Override
    protected ArrayList<DatabaseContacts> doInBackground(String... params) {
        ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
        mDao.findByName("%" + params[0] + "%");
        return contactsArrayList;
    }
}
</code>```

I call this from my contacts repository in its own sort of wrapper :

```<code>public List<DatabaseContacts> getContactByName(String name) throws
ExecutionException, InterruptedException {
    //return databaseContactsDao.findByName(name);
    return new searchContactByName(databaseContactsDao).execute(name).get();
}
</code>```

and this is called from my view model like this :

```<code>public List<DatabaseContacts> getContactByName(String name) throws
ExecutionException, InterruptedException {
    return  contactRepository.getContactByName(name);
}
</code>```

I'm then calling this from my fragment :

```<code>private void searchDatabase(String searchString) throws ExecutionException,
InterruptedException {
    List<DatabaseContacts> searchedContacts =
    contactViewModel.getContactByName("%" + searchString + "%");
    ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
    if (searchedContacts !=  null){
        contactsArrayList.addAll(searchedContacts);
        contactsAdapter.refreshMyList(contactsArrayList);
    }
}
</code>```

and this is called from an on search query text changed method in my onCreateOptionsMenu :

```<code>        @Override
        public boolean onQueryTextChange(String newText) {
            try {
                searchDatabase(newText);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }
</code>```

but it just does nothing my original recyclerview contents never change any ideas?

答:
I faced the same issue and I managed to fix it using

switchMap

and

MutableLiveData

We just need to use MutableLiveData to set the current value of editText, and when the user search we call setValue(editText.getText())

```<code> public class FavoriteViewModel extends ViewModel {
            public LiveData<PagedList<TeamObject>> teamAllList;
        public MutableLiveData<String> filterTextAll = new MutableLiveData<>();

        public void initAllTeams(TeamDao teamDao) {
            this.teamDao = teamDao;
            PagedList.Config config = (new PagedList.Config.Builder())
                    .setPageSize(10)
                    .build();

            teamAllList = Transformations.switchMap(filterTextAll, input -> {
                if (input == null || input.equals("") || input.equals("%%")) {
//check if the current value is empty load all data else search
                    return new LivePagedListBuilder<>(
                            teamDao.loadAllTeam(), config)
                            .build();
                } else {
                    System.out.println("CURRENTINPUT: " + input);
                    return new LivePagedListBuilder<>(
                            teamDao.loadAllTeamByName(input), config)
                            .build();
                }

            });

            }

    }
</code>```

in Activity of fragment

```<code>viewModel = ViewModelProviders.of(activity).get(FavoriteViewModel.class);
                        viewModel.initAllTeams(AppDatabase.getInstance(activity).teamDao());
                        FavoritePageListAdapter adapter = new FavoritePageListAdapter(activity);
                        viewModel.teamAllList.observe(
                                activity, pagedList -> {
                                    try {
                                        Log.e("Paging ", "PageAll" + pagedList.size());

                                        try {
                                            //to prevent animation recyclerview when change the list
                                            recycleFavourite.setItemAnimator(null);
                                            ((SimpleItemAnimator) Objects.requireNonNull(recycleFavourite.getItemAnimator())).setSupportsChangeAnimations(false);

                                        } catch (Exception e) {
                                        }

                                        adapter.submitList(pagedList);

                                    } catch (Exception e) {
                                    }
                                });
                        recycleFavourite.setAdapter(adapter);

//first time set an empty value to get all data
                        viewModel.filterTextAll.setValue("");

                edtSearchFavourite.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    @Override
                    public void afterTextChanged(Editable editable) {
                      //just set the current value to search.
                        viewModel.filterTextAll.setValue("%" + editable.toString() + "%");

                    }
                });
</code>```

Room Dao

```<code>@Dao
public interface TeamDao {

        @Query("SELECT * FROM teams order by orders")
        DataSource.Factory<Integer, TeamObject> loadAllTeam();

        @Query("SELECT * FROM teams where team_name LIKE  :name or LOWER(team_name_en) like LOWER(:name) order by orders")
        DataSource.Factory<Integer, TeamObject> loadAllTeamByName(String name);

    }
</code>```

PageListAdapter

```<code>public class FavoritePageListAdapter extends PagedListAdapter<TeamObject, FavoritePageListAdapter.OrderHolder> {
    private static DiffUtil.ItemCallback<TeamObject> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<TeamObject>() {
                // TeamObject details may have changed if reloaded from the database,
                // but ID is fixed.
                @Override
                public boolean areItemsTheSame(TeamObject oldTeamObject, TeamObject newTeamObject) {
                    System.out.println("GGGGGGGGGGGOTHERE1: " + (oldTeamObject.getTeam_id() == newTeamObject.getTeam_id()));
                    return oldTeamObject.getTeam_id() == newTeamObject.getTeam_id();
                }

                @Override
                public boolean areContentsTheSame(TeamObject oldTeamObject,
                                                  @NonNull TeamObject newTeamObject) {
                    System.out.println("GGGGGGGGGGGOTHERE2: " + (oldTeamObject.equals(newTeamObject)));
                    return oldTeamObject.equals(newTeamObject);
                }
            };

    private Activity activity;

    public FavoritePageListAdapter() {
        super(DIFF_CALLBACK);
    }

    public FavoritePageListAdapter(Activity ac) {
        super(DIFF_CALLBACK);
        this.activity = ac;

    }

    @NonNull
    @Override
    public OrderHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_favourite, parent, false);
        return new FavoritePageListAdapter.OrderHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull OrderHolder holder,
                                 int position) {
        System.out.println("GGGGGGGGGGGOTHERE!!!");

        if (position <= -1) {
            return;
        }
        TeamObject teamObject = getItem(position);

        try {
                holder.txvTeamRowFavourite.setText(teamObject.getTeam_name());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public class OrderHolder extends RecyclerView.ViewHolder {

        private TextView txvTeamRowFavourite;

        OrderHolder(View itemView) {
            super(itemView);
            txvTeamRowFavourite = itemView.findViewById(R.id.txv_team_row_favourite);
        }

    }
}
</code>```

Body:
I'm working on a project in android for a udacity course I'm currently trying to implement a search function while adhering to android architecture components and using firestore and room I'm fairly new to all these concepts so please point out anything that seems wrong.

So I made a database repository to keep my firestore and room databases in sync and to deliver the data. I'm then using viewmodel and the observer pattern (I think) so my observer gets the data and looks for changes gives it to my adapter (refreshMyList(List)) which populates a recyclerview like this :

 contactViewModel = ViewModelProviders.of(this).get(ContactsViewModel.class);
 contactViewModel.getAllContacts().observe(this, new
 Observer<List<DatabaseContacts>>() {
        @Override
        public void onChanged(@Nullable List<DatabaseContacts>
        databaseContacts) {
            ArrayList<DatabaseContacts> tempList = new ArrayList<>();
            tempList.addAll(databaseContacts);
            contactsAdapter.refreshMyList(tempList);
            if (tempList.size() < 1) {
                results.setVisibility(View.VISIBLE);
            } else {
                results.setVisibility(View.GONE);
            }
        }
    });

I now want to perform a search of the data, I have my room queries all set up fine and I have methods in my data repository to get contacts based on a search string but I cant seem to refresh my list I've read that there are ways to do it like Transformations.switchMap ? but i cant seem to wrap my head around how it works can anyone help me

Currently I'm trying to return a List of results from an async task, it used to return live data but I changed it as getValue() was always null, not sure if that's correct, heres the async :

private static class searchContactByName extends AsyncTask<String, Void,
ArrayList<DatabaseContacts>> {

    private LiveDatabaseContactsDao mDao;

    searchContactByName(LiveDatabaseContactsDao dao){
        this.mDao = dao;
    }

    @Override
    protected ArrayList<DatabaseContacts> doInBackground(String... params) {
        ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
        mDao.findByName("%" + params[0] + "%");
        return contactsArrayList;
    }
}

I call this from my contacts repository in its own sort of wrapper :

public List<DatabaseContacts> getContactByName(String name) throws
ExecutionException, InterruptedException {
    //return databaseContactsDao.findByName(name);
    return new searchContactByName(databaseContactsDao).execute(name).get();
}

and this is called from my view model like this :

public List<DatabaseContacts> getContactByName(String name) throws
ExecutionException, InterruptedException {
    return  contactRepository.getContactByName(name);
}

I'm then calling this from my fragment :

private void searchDatabase(String searchString) throws ExecutionException,
InterruptedException {
    List<DatabaseContacts> searchedContacts =
    contactViewModel.getContactByName("%" + searchString + "%");
    ArrayList<DatabaseContacts> contactsArrayList = new ArrayList<>();
    if (searchedContacts !=  null){
        contactsArrayList.addAll(searchedContacts);
        contactsAdapter.refreshMyList(contactsArrayList);
    }
}

and this is called from an on search query text changed method in my onCreateOptionsMenu :

        @Override
        public boolean onQueryTextChange(String newText) {
            try {
                searchDatabase(newText);
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        }

but it just does nothing my original recyclerview contents never change any ideas?

Body:
I faced the same issue and I managed to fix it using

switchMap

and

MutableLiveData

We just need to use MutableLiveData to set the current value of editText, and when the user search we call setValue(editText.getText())

 public class FavoriteViewModel extends ViewModel {
            public LiveData<PagedList<TeamObject>> teamAllList;
        public MutableLiveData<String> filterTextAll = new MutableLiveData<>();

        public void initAllTeams(TeamDao teamDao) {
            this.teamDao = teamDao;
            PagedList.Config config = (new PagedList.Config.Builder())
                    .setPageSize(10)
                    .build();

            teamAllList = Transformations.switchMap(filterTextAll, input -> {
                if (input == null || input.equals("") || input.equals("%%")) {
//check if the current value is empty load all data else search
                    return new LivePagedListBuilder<>(
                            teamDao.loadAllTeam(), config)
                            .build();
                } else {
                    System.out.println("CURRENTINPUT: " + input);
                    return new LivePagedListBuilder<>(
                            teamDao.loadAllTeamByName(input), config)
                            .build();
                }

            });

            }

    }

in Activity of fragment

viewModel = ViewModelProviders.of(activity).get(FavoriteViewModel.class);
                        viewModel.initAllTeams(AppDatabase.getInstance(activity).teamDao());
                        FavoritePageListAdapter adapter = new FavoritePageListAdapter(activity);
                        viewModel.teamAllList.observe(
                                activity, pagedList -> {
                                    try {
                                        Log.e("Paging ", "PageAll" + pagedList.size());

                                        try {
                                            //to prevent animation recyclerview when change the list
                                            recycleFavourite.setItemAnimator(null);
                                            ((SimpleItemAnimator) Objects.requireNonNull(recycleFavourite.getItemAnimator())).setSupportsChangeAnimations(false);

                                        } catch (Exception e) {
                                        }

                                        adapter.submitList(pagedList);

                                    } catch (Exception e) {
                                    }
                                });
                        recycleFavourite.setAdapter(adapter);

//first time set an empty value to get all data
                        viewModel.filterTextAll.setValue("");

                edtSearchFavourite.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    }

                    @Override
                    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                    @Override
                    public void afterTextChanged(Editable editable) {
                      //just set the current value to search.
                        viewModel.filterTextAll.setValue("%" + editable.toString() + "%");

                    }
                });

Room Dao

@Dao
public interface TeamDao {

        @Query("SELECT * FROM teams order by orders")
        DataSource.Factory<Integer, TeamObject> loadAllTeam();

        @Query("SELECT * FROM teams where team_name LIKE  :name or LOWER(team_name_en) like LOWER(:name) order by orders")
        DataSource.Factory<Integer, TeamObject> loadAllTeamByName(String name);

    }

PageListAdapter

public class FavoritePageListAdapter extends PagedListAdapter<TeamObject, FavoritePageListAdapter.OrderHolder> {
    private static DiffUtil.ItemCallback<TeamObject> DIFF_CALLBACK =
            new DiffUtil.ItemCallback<TeamObject>() {
                // TeamObject details may have changed if reloaded from the database,
                // but ID is fixed.
                @Override
                public boolean areItemsTheSame(TeamObject oldTeamObject, TeamObject newTeamObject) {
                    System.out.println("GGGGGGGGGGGOTHERE1: " + (oldTeamObject.getTeam_id() == newTeamObject.getTeam_id()));
                    return oldTeamObject.getTeam_id() == newTeamObject.getTeam_id();
                }

                @Override
                public boolean areContentsTheSame(TeamObject oldTeamObject,
                                                  @NonNull TeamObject newTeamObject) {
                    System.out.println("GGGGGGGGGGGOTHERE2: " + (oldTeamObject.equals(newTeamObject)));
                    return oldTeamObject.equals(newTeamObject);
                }
            };

    private Activity activity;

    public FavoritePageListAdapter() {
        super(DIFF_CALLBACK);
    }

    public FavoritePageListAdapter(Activity ac) {
        super(DIFF_CALLBACK);
        this.activity = ac;

    }

    @NonNull
    @Override
    public OrderHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_favourite, parent, false);
        return new FavoritePageListAdapter.OrderHolder(view);

    }

    @Override
    public void onBindViewHolder(@NonNull OrderHolder holder,
                                 int position) {
        System.out.println("GGGGGGGGGGGOTHERE!!!");

        if (position <= -1) {
            return;
        }
        TeamObject teamObject = getItem(position);

        try {
                holder.txvTeamRowFavourite.setText(teamObject.getTeam_name());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public class OrderHolder extends RecyclerView.ViewHolder {

        private TextView txvTeamRowFavourite;

        OrderHolder(View itemView) {
            super(itemView);
            txvTeamRowFavourite = itemView.findViewById(R.id.txv_team_row_favourite);
        }

    }
}


问:
Delete push notifications from the Notification Center/Panel when the app is closed
I am looking for a way to delete some of the notifications from the notification panel when the app is closed. When the app is running in the background or foreground this is quite possible on both Android and iOS.

I have gone through docs and multiple articles to see if this is possible, and I found in android I can do this using a background service. But for iOS I think I'm confused.

Not sure didReceiveRemoteNotification:fetchCompletionHandler can do it when the app is swiped off by the user.

答:
In ios add the code in appdelegate class

func applicationWillTerminate(_ application: UIApplication) {

```<code>    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests()
    center.removeAllDeliveredNotifications()
}
</code>```

Body:
In ios add the code in appdelegate class

func applicationWillTerminate(_ application: UIApplication) {

    let center = UNUserNotificationCenter.current()
    center.removeAllPendingNotificationRequests()
    center.removeAllDeliveredNotifications()
}


问:
What are the benefits of Java's types erasure?
I read a tweet today that said:

It's funny when Java users complain about type erasure, which is the only thing Java got right, while ignoring all the things it got wrong.

Thus my question is:

Are there benefits from Java's type erasure? What are the technical or programming style benefits it (possibly) offers other than the JVM implementations preference for backwards compatibility and runtime performance?

答:
Most answers are more concerned about programming philosophy than the actual technical details.

And although this question is more than 5 years old, the question still lingers: Why is type erasure desireable from a technical point of view? In the end, the answer is rather simple (on a higher level): https://en.wikipedia.org/wiki/Type_erasure

C++ templates don't exist at runtime. The compiler emits a fully optimized version for each invocation, meaning the execution doesn't depend on type information.
But how does a JIT deal with different versions of the same function? Wouldn't it be better to just have one function? Wouldn't want the JIT to have to optimize all the different versions of it. Well, but then what about type safety? Guess that has to go out of the window.

But wait a second: How does .NET do it? Reflection! This way they only have to optimize one function and also get runtime type information. And that is why .NET generics used to be slower (though they have gotten much better). I am not arguing that that isn't convenient! But it is expensive and shouldn't be used when it isn't absolutely necessary (it isn't considered expensive in dynamically typed languages because the compiler / interpreter relies on reflection anyway).

This way generic programming with type erasure is close to zero overhead (some runtime checks / casts are still required): https://docs.oracle.com/javase/tutorial/java/generics/erasure.html


问:
Drupal Views Arguments
I know how to successfully use arguments in drupal's views module, but when it "filters" based on those arguments it uses "=" in the where clause of the SQL statement. However, I would like to use "like" instead of "=" in the where clause of the SQL statement so I can pass in, say the title of a node, as an argument and then show all nodes that CONTAIN the title passed in. I am not interested in grabbing only the nodes where the title is exactly the same as the title passed in. Does anyone know how I can do this? Is this possible?</p>

答: You could export the view, which outputs the views-generated query as code, then modify the query to suit your needs, and load it programatically (http://www.chilipepperdesign.com/2010/01/15/how-to-programmatically-create-views-in-drupal-6)

ContentLicense: CC BY-SA 2.5

Title: Drupal Views Arguments

ContentLicense: CC BY-SA 3.0


问:
Calculate mean of specific rows Julia dataframe
I am new to Julia and I have a relatively simple question (I think) about calculating means in Julia dataframes.

Imagine I have the following dataframe:

```<code>df = DataFrame(A=1:12, B=13:24)
</code>```

Where my goal is to calculate the mean values in both column A and B for every 4 rows.

So in column A that includes 3 means for the values [1,2,3,4], [5,6,7,8],[9,10,11,12]. And for column B includes 3 means for the values [13,14,15,16],[17,18,19,20],[21,22,23,24].

I tried splitting the dataframe into 3 dataframes manually, but I have a large dataset so iterating over rows will be much more efficient.

Hopefully someone can help me out (I am using Julia version 1.0.3).

答:
See the documentation here: https://dataframes.juliadata.org/stable/man/split_apply_combine/
So you could do</p>
```<code>df.group = repeat(1:3, inner = 4)
aggregate(df, :group, mean)
</code>```

Body:
I am new to Julia and I have a relatively simple question (I think) about calculating means in Julia dataframes.

Imagine I have the following dataframe:

df = DataFrame(A=1:12, B=13:24)

Where my goal is to calculate the mean values in both column A and B for every 4 rows.

So in column A that includes 3 means for the values [1,2,3,4], [5,6,7,8],[9,10,11,12]. And for column B includes 3 means for the values [13,14,15,16],[17,18,19,20],[21,22,23,24].

I tried splitting the dataframe into 3 dataframes manually, but I have a large dataset so iterating over rows will be much more efficient.

Hopefully someone can help me out (I am using Julia version 1.0.3).

Body:
See the documentation here: https://dataframes.juliadata.org/stable/man/split_apply_combine/
So you could do

df.group = repeat(1:3, inner = 4)
aggregate(df, :group, mean)


问:
How do i output contents of a map using operator <<
I'm trying to output the contents of my map but i'm not sure on how to go about it. i've got the following declarations for a map and a iterator set as private in my header file

```<code>typedef map<long, string> Student;
Student newstudent;
typedef Student::const_iterator studentItr;
studentItr itr;
</code>```

and i have the following declaration in my .cpp

```<code>map<long, string> classname::GetMap()
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
{
    cout << itr->first << " => " <<itr->second << '\n';
}

    return newstudent;
}
</code>```

and this is how i'm trying to pass this into my overloaded operator << function

```<code>ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.GetMap() << '\n';

    return os;
}
</code>```

Usually this would work for any other function but since its a map i get the following error:

no match for 'operator<<' (operand types are 'std::basic_ostream< char >' and 'std::map < long int, std::__cxx11::basic_string< char > > ')|

Could anybody point me in the right direction of what i'm doing wrong

EDIT: Thanks for posting your suggestions i appreciate the help, but i think something isnt right either with my complier or with how i've stated something.

Everytime i try using Student as a type it wont register as a type and i get an error about it.

E.g if i declare this statement

```<code>ostream & operator <<( ostream & os, const Student & R)
</code>```

OR

```<code>Student & classname::GetMap()
</code>```

i get the error:

'Student' does not name a type

This error ultimately is leading to nothing within my statements making any sense and i'm not sure how to fix that

答:
Initially you are trying to insert an std::map directly into the operator<<(). This will not work because std::map has no idea how to convert to a std::ostream object and std::ostream's operator<<() doesn't know how to accept a map.

You can always write an overload of operator<<() for your map type, however if a type inside of your map is a non trivial type such as a class or struct with multiple fields then that class would have to have its own associated operator<<() as well. So it's just easier to write them for the types themselves and just iterate over the map or collection.

So now that the class has a working relation with operator<<() you can iterate over any kind of container either it be a vector, an array, a list or queue etc. The operator<<() doesn't care about what kind of container, it only cares about the object that is in the container.

Do not try to get into the habit of declaring an operator<<() or operator>>() as a member of a class, try to get into the habit of writing the operators as just that a standalone operator function that works on your type!

Here is a complete demonstration:

If your compiler supports using in place of typedefs; You can try this program and check its expected output. There shouldn't be any errors, but there might be a typo that I've overlooked when I was fixing the formatting. If you find one let me know and I'll update it accordingly.

main.cpp

```<code>#include "Students.h"

int main() {
    using namespace "your namespace here";

    Student JacobKnight("Jacob Knight", 233);
    Student SaraAndrews("Sara Andrews", 245);
    Student AllenReed("Allen Reed", 259);

    Students students;
    addStudent(JacobKnight, students);
    addStudent(SarahAndrews, students);
    addStudent(AllenReed, students);

    using It = std::map<long, Student>::const_iterator;
    for (It it = students.cbegin(); it != students.cend(); ++it) {
        std::cout << "Map ID: " << std::setfill('0') << std::setw(8)
        << it->first << "\nStudent: " << it->second;
    }

    return EXIT_SUCCESS;
}
</code>```

Students.h

```<code>#pragma once   // if your compiler doesn't like this then use header guards!

#include <iomanip>
#include <iostream>
#include <map>
#include <string>

namespace "your namespace here" {

    struct Student {
        long id_;
        std::string name_;

        Student() = default;
        Student(const std::string name, long id) : name_{name}, id_{id} {}
    };

    using Students = std::map<long, Student>;

    void addStudent(const Student& student, Students& students) {
        students.insert( std::make_pair( student.id_, student ) );
    }

    std::ostream& operator<<(std::ostream& os, const Student& student) {
        return os << std::setfill('0') << std::setw(8) << student.id_
                  << " " << student.name_ << "\n\n";
    }

} // your namespace
</code>```

Output

```<code>Map  ID: 00000233
Student: 00000233 Jacob Knight

Map  ID: 00000245
Student: 00000245 Sarah Andrews

Map  ID: 00000259
Student: 00000259 Allen Reed
</code>```

Here I like to think of a single student as a single object and that it contains the details of that object, a numerical id, and a character array or string name. So I put these in a struct as public members. You can always change this to a class, make them private with accessory functions to encapsulate the data, but for quick demonstration, I made a simple structure or class here nothing too complex.

Next I used the using directive to define a typename of a type. Now I can later on easily use this to declare my objects. I used this to simplify the usage of std::map<T1,T2>. I also use the using directive again in main to define my iterator typename as It. Then I use that to declare my iterator for my map.

I wrote a simple function that will populate a map of students. To me this is more intuitive and expressive because a map contains multiple objects and in this case students, hence being plural where the structure itself of a single entity is just a student! This makes the code expressive and readable and helps to imply your intent.

Then I simply wrote an overloaded operator<<() that takes in a Student by const ref. It then formats the output to either my liking or the required layout. Then it returns it back to the stream operator for insertion into the stream output to the standard out either it being the console or to a file.

I hope this answer(s) your question(s) and that it will give you some guidance along the way...

EDIT

In main.cpp I changed the map's iterators from begin() and end() in the for loop to cbegin() and cend(). This shouldn't make a big difference but since my map's iterator was declared as a const_iterator. I prefer staying consistent with the type of iterators that I'm traversing over.

Body:
I'm trying to output the contents of my map but i'm not sure on how to go about it. i've got the following declarations for a map and a iterator set as private in my header file

typedef map<long, string> Student;
Student newstudent;
typedef Student::const_iterator studentItr;
studentItr itr;

and i have the following declaration in my .cpp

map<long, string> classname::GetMap()
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
{
    cout << itr->first << " => " <<itr->second << '\n';
}

    return newstudent;
}

and this is how i'm trying to pass this into my overloaded operator << function

ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.GetMap() << '\n';

    return os;
}

Usually this would work for any other function but since its a map i get the following error:

no match for 'operator<<' (operand types are 'std::basic_ostream< char >' and 'std::map < long int, std::__cxx11::basic_string< char > > ')|

Could anybody point me in the right direction of what i'm doing wrong

EDIT: Thanks for posting your suggestions i appreciate the help, but i think something isnt right either with my complier or with how i've stated something.

Everytime i try using Student as a type it wont register as a type and i get an error about it.

E.g if i declare this statement

ostream & operator <<( ostream & os, const Student & R)

OR

Student & classname::GetMap()

i get the error:

'Student' does not name a type

This error ultimately is leading to nothing within my statements making any sense and i'm not sure how to fix that

Body:
Initially you are trying to insert an std::map directly into the operator<<(). This will not work because std::map has no idea how to convert to a std::ostream object and std::ostream's operator<<() doesn't know how to accept a map.

You can always write an overload of operator<<() for your map type, however if a type inside of your map is a non trivial type such as a class or struct with multiple fields then that class would have to have its own associated operator<<() as well. So it's just easier to write them for the types themselves and just iterate over the map or collection.

So now that the class has a working relation with operator<<() you can iterate over any kind of container either it be a vector, an array, a list or queue etc. The operator<<() doesn't care about what kind of container, it only cares about the object that is in the container.

Do not try to get into the habit of declaring an operator<<() or operator>>() as a member of a class, try to get into the habit of writing the operators as just that a standalone operator function that works on your type!

Here is a complete demonstration:

If your compiler supports using in place of typedefs; You can try this program and check its expected output. There shouldn't be any errors, but there might be a typo that I've overlooked when I was fixing the formatting. If you find one let me know and I'll update it accordingly.

main.cpp

#include "Students.h"

int main() {
    using namespace "your namespace here";

    Student JacobKnight("Jacob Knight", 233);
    Student SaraAndrews("Sara Andrews", 245);
    Student AllenReed("Allen Reed", 259);

    Students students;
    addStudent(JacobKnight, students);
    addStudent(SarahAndrews, students);
    addStudent(AllenReed, students);

    using It = std::map<long, Student>::const_iterator;
    for (It it = students.cbegin(); it != students.cend(); ++it) {
        std::cout << "Map ID: " << std::setfill('0') << std::setw(8)
        << it->first << "\nStudent: " << it->second;
    }

    return EXIT_SUCCESS;
}

Students.h

#pragma once   // if your compiler doesn't like this then use header guards!

#include <iomanip>
#include <iostream>
#include <map>
#include <string>

namespace "your namespace here" {

    struct Student {
        long id_;
        std::string name_;

        Student() = default;
        Student(const std::string name, long id) : name_{name}, id_{id} {}
    };

    using Students = std::map<long, Student>;

    void addStudent(const Student& student, Students& students) {
        students.insert( std::make_pair( student.id_, student ) );
    }

    std::ostream& operator<<(std::ostream& os, const Student& student) {
        return os << std::setfill('0') << std::setw(8) << student.id_
                  << " " << student.name_ << "\n\n";
    }

} // your namespace

Output

Map  ID: 00000233
Student: 00000233 Jacob Knight

Map  ID: 00000245
Student: 00000245 Sarah Andrews

Map  ID: 00000259
Student: 00000259 Allen Reed

Here I like to think of a single student as a single object and that it contains the details of that object, a numerical id, and a character array or string name. So I put these in a struct as public members. You can always change this to a class, make them private with accessory functions to encapsulate the data, but for quick demonstration, I made a simple structure or class here nothing too complex.

Next I used the using directive to define a typename of a type. Now I can later on easily use this to declare my objects. I used this to simplify the usage of std::map<T1,T2>. I also use the using directive again in main to define my iterator typename as It. Then I use that to declare my iterator for my map.

I wrote a simple function that will populate a map of students. To me this is more intuitive and expressive because a map contains multiple objects and in this case students, hence being plural where the structure itself of a single entity is just a student! This makes the code expressive and readable and helps to imply your intent.

Then I simply wrote an overloaded operator<<() that takes in a Student by const ref. It then formats the output to either my liking or the required layout. Then it returns it back to the stream operator for insertion into the stream output to the standard out either it being the console or to a file.

I hope this answer(s) your question(s) and that it will give you some guidance along the way...

EDIT

In main.cpp I changed the map's iterators from begin() and end() in the for loop to cbegin() and cend(). This shouldn't make a big difference but since my map's iterator was declared as a const_iterator. I prefer staying consistent with the type of iterators that I'm traversing over.


问:
How to find if we have two or more equal minimum values in specific columns
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

```<code>head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")
</code>```

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

```<code>head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")
</code>```

Thank you in advance.

答:
Does this help you?:

```<code>mydata$flag=apply(mydata,1,function(x){  # iterate through rows
    x=na.omit(x);        # omit NAs in a row (optional)
    tab=table(x[x<200]); # count numbers of all row values below 200
    if(any(tab>1)){      # check if any values are not unique
          return(TRUE)
          }else{
          return(FALSE)
         }})
</code>```

You can choose to include or omit NA values or not.

Body:
I have this problem I was hoping someone could help.

I have a very large data frame (close to 20000000 observations)in R with about 43 columns, in four of those columns I need to find whether there is more than one equal minimum value below 200, then if we have rows where more than one column has the same value that meets this criteria I need to flag that row to TRUE (in a a new flag column). Please note that those columns include NA values, and NAs should not be used (when NA is present in the columns being compared, returns NA)

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row

for simplicity let's say that this is how my data data look like

head(mydata)
t1  a1  a2  a3  a4
34  NA  NA  NA  NA
26  10  15  250 150
34  20  20  100 30
35  5   5   10  5
25  45  100 3   45
31 400 310 500 310
")

the goal is to look up the values in each row for columns a1 to a4 and find whether the minimum value that does not exceed 200, occurs in more than one column per row, if it does return true if not, false

the expected result will look like this

head(mydata)
t1  a1  a2  a3  a4  flag
34  NA  NA  NA  NA  NA
26  10  15  250 150 FALSE
34  20  20  100 30  TRUE
35  5   5   10  5   TRUE
25  45  100 3   45  FALSE
31 400 310 500 310  FALSE
")

Thank you in advance.

Body:
Does this help you?:

mydata$flag=apply(mydata,1,function(x){  # iterate through rows
    x=na.omit(x);        # omit NAs in a row (optional)
    tab=table(x[x<200]); # count numbers of all row values below 200
    if(any(tab>1)){      # check if any values are not unique
          return(TRUE)
          }else{
          return(FALSE)
         }})

You can choose to include or omit NA values or not.


问:
How can I find the current function's closure when debugging JavaScript in vscode
I am debugging a React JS application through VSCode and Chrome. At a breakpoint a variable I am interested in is visible in the Closure section of the variables list. At other levels of the stack trace the variable is not available. The function is defined at the top level of its JS file, and I can't see where the closure is defined, and in particular where the variable is first assigned. Called from elsewhere the closure scoped variable is different and I can't see why.

Is there any way in VS Code Debugging or Chrome Dev Tools to see where the closure scope was defined?

As a simple example, if debugging the JS code below and hitting a breakpoint at a=1 is there any way to identify the closureScope variable in which a is defined? In the real example the function and closure scoped variables are not obviously contained in any other functions or blocks, but my understanding of modern JS and closures is limited and I may be missing something obvious.

```<code>function main() {
  let closureScope = (
    function() {
    var a = 0;
    return {
      inside1: function() {
        a = 1;
      },
      inside2: function() {
        a = 2;
      }
    };
  })();

  closureScope.inside1();
  closureScope.inside2();
}

main();
</code>```

答:
You can simply use debugger in vscode or chrome

Add a breakpoint in code, you can click on the red dot in the left side of your file to add a break point

Or use debugger; where you want breakpoint

On the left hand side expand the variable list and than closureScope to see your value in that particular scope

Body:
I am debugging a React JS application through VSCode and Chrome. At a breakpoint a variable I am interested in is visible in the Closure section of the variables list. At other levels of the stack trace the variable is not available. The function is defined at the top level of its JS file, and I can't see where the closure is defined, and in particular where the variable is first assigned. Called from elsewhere the closure scoped variable is different and I can't see why.

Is there any way in VS Code Debugging or Chrome Dev Tools to see where the closure scope was defined?

As a simple example, if debugging the JS code below and hitting a breakpoint at a=1 is there any way to identify the closureScope variable in which a is defined? In the real example the function and closure scoped variables are not obviously contained in any other functions or blocks, but my understanding of modern JS and closures is limited and I may be missing something obvious.

function main() {
  let closureScope = (
    function() {
    var a = 0;
    return {
      inside1: function() {
        a = 1;
      },
      inside2: function() {
        a = 2;
      }
    };
  })();

  closureScope.inside1();
  closureScope.inside2();
}

main();


问:
how to be sure in Linq to SQL that record has been added successfully or not?
I am just learning Linq to SQL and don't know much. Kindly guide and help me.

I am adding a new record by using a SubmitChanges();  How I can be confirmed that record has been added? For example, in using stored procedures we use to send a flag back to application but how is it done in LINQ to SQL? Please guide me.

答:
Allow your code to flow out of your method. Only when an exception is throw has your statement not completed.

If you wanted a 'flag', you could return a bool.

```<code>public bool AddCustomer()
{
  try{
     ....
     db.SubmitChanges();
     return true;
  }
  catch(Exception e)
  {
    ...
    return false;
  }
}
</code>```

Body:
Allow your code to flow out of your method. Only when an exception is throw has your statement not completed.

If you wanted a 'flag', you could return a bool.

public bool AddCustomer()
{
  try{
     ....
     db.SubmitChanges();
     return true;
  }
  catch(Exception e)
  {
    ...
    return false;
  }
}


问:
Share encrypted AMIs across accounts to launch instances to be used with ASG
Following on from the recent announcement from AWS about sharing encrypted AMIs

Been testing this today, shared the encrypted AMI and KMS key.
It worked when I launched a single instance from the console using the shared encrypted AMI.

Although trying to use the same shared encrypted AMI in an ASG produced the following error message, has anyone else seen this?

```<code>Launching a new EC2 instance: i-0a306b1c0c65fb197. Status Reason: Instance became unhealthy while waiting for instance to be in InService state. Termination Reason: Client.InternalError: Client error on launch
</code>```

答:
The ASG service linked role needs access to the CMK as detail in case 2, solution 2 of the following forum thread.
https://forums.aws.amazon.com/thread.jspa?threadID=277523</p>

Body:
Following on from the recent announcement from AWS about sharing encrypted AMIs

Been testing this today, shared the encrypted AMI and KMS key.
It worked when I launched a single instance from the console using the shared encrypted AMI.

Although trying to use the same shared encrypted AMI in an ASG produced the following error message, has anyone else seen this?

Launching a new EC2 instance: i-0a306b1c0c65fb197. Status Reason: Instance became unhealthy while waiting for instance to be in InService state. Termination Reason: Client.InternalError: Client error on launch


问:
Math.Random always setting random number to 0
Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters

```<code>package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;

public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner

public static void main(String args[]) //start of main
{

System.out.println("Welcome to the guessing game, the computer will
generate a random number that you have to guess, good luck!"); //opening
message explaining how to play

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();

generate_random_number(secret_number); //calls he function
generate_random_number to say the random number has been generated

for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20

System.out.println("Please make your guess"); //asks user to enter make
their guess
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess

if(entered_numbers.contains(user_guess)) //checks if entered number =
number stored in array
{
System.out.println("You have already entered this number"); //displays
error message if user enters same number again
continue;
}

else
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number)
{
System.out.println("Your guess is too high");
}

System.out.println (20 - number_of_guesses + " Guesses remaining");
//Tells the user how many guesses they have remaining

} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function
generate_random_number function passing secret_number as a parameter
{
secret_number = (int)(Math.random()*100) + 1; //generates random number
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the
user know that the random number has been generated
} //end of function generate_random_number
</code>```

} //end of public class

答:
You should change your methods return type to int.
Change your method like this:

```<code>static int generate_random_number(int secret_number)
</code>```

And in the main function set your secret_number to the value that method returns

```<code>secret_number = generate_random_number(secret_number);
</code>```

You should also add return value for your method so it should be like this:

```<code>static int generate_random_number(int secret_number){
    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");
    return secret_number;
}
</code>```

Body:
Creating a program where a random number is generated using math.random which i have put into a function and called this function in the program to make things tidier but the random number that gets outputted is always what the integer secret_number is set to, and i am not sure how to fix this to create a random number. I would like to keep the math.random in the function and use parameters

package guessinggame3;
import java.util.Scanner; //imports scanner to read from keyboard
import java.util.ArrayList;

public class GuessingGame3 { //start of public class

static Scanner kboard = new Scanner(System.in); //calls scanner

public static void main(String args[]) //start of main
{

System.out.println("Welcome to the guessing game, the computer will
generate a random number that you have to guess, good luck!"); //opening
message explaining how to play

int secret_number = 0;
int number_of_guesses = 0;
int user_guess ;
ArrayList<Integer> entered_numbers = new ArrayList<Integer>();

generate_random_number(secret_number); //calls he function
generate_random_number to say the random number has been generated

for(int i=0; i<20;i++) { // start of for loop sets user attempts to 20

System.out.println("Please make your guess"); //asks user to enter make
their guess
user_guess = kboard.nextInt();
number_of_guesses++; // adds on to the counter after each user guess

if(entered_numbers.contains(user_guess)) //checks if entered number =
number stored in array
{
System.out.println("You have already entered this number"); //displays
error message if user enters same number again
continue;
}

else
{
entered_numbers.add(user_guess);
if (user_guess == secret_number)
System.out.println("Your guess is corret you win!");
}

if (user_guess < secret_number)
{
System.out.println("Guess is too low");
}

if (user_guess > secret_number)
{
System.out.println("Your guess is too high");
}

System.out.println (20 - number_of_guesses + " Guesses remaining");
//Tells the user how many guesses they have remaining

} //end of for loop

} //end of main

static void generate_random_number(int secret_number)  //start of function
generate_random_number function passing secret_number as a parameter
{
secret_number = (int)(Math.random()*100) + 1; //generates random number
between 0 and 100
System.out.println("The computer has generated it's number"); //lets the
user know that the random number has been generated
} //end of function generate_random_number

} //end of public class

Body:
You should change your methods return type to int.
Change your method like this:

static int generate_random_number(int secret_number)

And in the main function set your secret_number to the value that method returns

secret_number = generate_random_number(secret_number);

You should also add return value for your method so it should be like this:

static int generate_random_number(int secret_number){
    secret_number = (int)(Math.random()*100) + 1;
    System.out.println("The computer has generated it's number");
    return secret_number;
}


问:
About @waves/waves-transactions library
I was testing https://www.npmjs.com/package/@waves/waves-transactions and npm installed and create a simple transaction to sign and tried to display the Tx object in console however this error is displayed.

```<code>node tx.js
module.js:529
throw err;
^

Error: Cannot find module '@waves/waves-transactions'
at Function.Module._resolveFilename (module.js:527:15)
at Function.Module._load (module.js:476:23)
at Module.require (module.js:568:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/SatoruBito 1/waves-transactions/tx.js:1:84)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
</code>```

Code is below in tx.js

```<code>const { transfer } = require('@waves/waves-transactions');
const nodeUrl = 'https://nodes.wavesplatform.com';

const seed = "a valid seed phrase";

const signedTranserTx = transfer({
amount: 0.01,
recipient: 'a valid Waves mainet address',
timestamp:Date.now()
}, seed)

console.log(signedTranserTx);
</code>```

wanted to sign Tx and show the Tx object with signature

答: The problem is within you node environment, since you have import error. Make sure you have package installed and require it from within the project

Title: About @waves/waves-transactions library

Body:
I was testing https://www.npmjs.com/package/@waves/waves-transactions and npm installed and create a simple transaction to sign and tried to display the Tx object in console however this error is displayed.

node tx.js
module.js:529
throw err;
^

Error: Cannot find module '@waves/waves-transactions'
at Function.Module._resolveFilename (module.js:527:15)
at Function.Module._load (module.js:476:23)
at Module.require (module.js:568:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/Users/SatoruBito 1/waves-transactions/tx.js:1:84)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)

Code is below in tx.js

const { transfer } = require('@waves/waves-transactions');
const nodeUrl = 'https://nodes.wavesplatform.com';

const seed = "a valid seed phrase";

const signedTranserTx = transfer({
amount: 0.01,
recipient: 'a valid Waves mainet address',
timestamp:Date.now()
}, seed)

console.log(signedTranserTx);

wanted to sign Tx and show the Tx object with signature


问:
How to efficiently sync data between multiple clients with MySQL?
I am setting up an arduino based network that has multiple controllers (phones, web page, PC app) to configure a relay system (base). This network uses MySQL database to store and sync configuration between clients and the base. All clients and the base can manipulate configuration and clients should see real-time configuration of the base. It means if a client changes the configuration, all other clients and the base should see this change. How can I sync data in this network and avoid conflicts? Is there any efficient algorithms?

I used database server's timestamp to track changes. Whenever db changes, it saves timestamp. All clients get this timestamp and compare it to last fetched one. But the problem is when 2 or more clients access this database simultaneously, conflict occurs and I loose configuration changes of all clients except one.
Using timestamp doesn't seem to be a good idea. If the base goes offline, we can't save the changes made on the base during offline time. Because as soon as it gets back online, it fetches configuration from database.
Sorry for my poor English.

答:
The database should be the synchronization point: before making an update the clients should lock the data in a transaction, make their changes and then commit them.

One of the way to lock the data is to add for update to your select statements. There's more information in the MySQL documentation


问:
Is it safe to send a password unencrypted via an AJAX POST to a Flask Backend, should I encrypt it on the client side?
I have a form that I'm sending via AJAX to my Flask backend so I can skip the reload page, I've never really thought about it but is it wise to encrypt the password on the client side and decrypt it on the back end? What is the normal process for this? I'll be turning my Flask App into a desktop application using PyFlaDesk so it wont be hosted securely but on a users local machine, therefore it's only ever going to send the credentials to 'localhost:5000', do I even need to worry?</p>

```<code>   let credentials = {
        'client_id': $('#clientid').val(),
        'client_secret': $('#clientsecret').val(),
        'username': $('#username').val(),
        'password': $('#password').val(),
    }

    $.ajax({
        url: '/authorise',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({credentials}),
        dataType: "json",
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
        });
</code>```

答: No need to worry. Even if you send credentials over the net, making sure you use HTTPS is plenty sufficient.</p>

Body:
I have a form that I'm sending via AJAX to my Flask backend so I can skip the reload page, I've never really thought about it but is it wise to encrypt the password on the client side and decrypt it on the back end? What is the normal process for this? I'll be turning my Flask App into a desktop application using PyFlaDesk so it wont be hosted securely but on a users local machine, therefore it's only ever going to send the credentials to 'localhost:5000', do I even need to worry?

   let credentials = {
        'client_id': $('#clientid').val(),
        'client_secret': $('#clientsecret').val(),
        'username': $('#username').val(),
        'password': $('#password').val(),
    }

    $.ajax({
        url: '/authorise',
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({credentials}),
        dataType: "json",
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
        });


问:
filter mongodb object result by ObjectId with Underscore
I have a problem combining  UnderscoreJS and MongooseJS in NodeJS. I have a result of mongoose and I want filter a array

```<code>var __ = require("underscore"),
    platformInfo = __.findWhere(user.platforms, {"pId": platformId});
</code>```

But pId inside user.platforms is a ObjectId and can't find.
But if i make a each and compare like this all its OK:

```<code>__.each(user.platforms, function(platform){

                if(platform.pId.toString() == platformId){

                }

});
</code>```

How i can find in findWhere method (one line, and cool) the same result? Thanks

答:
You can use .toString after id of mongo response obbject
For ex

_.findWhere(allMappingData, {_categoryId: catObj._id.toString() ,_contentId: content.contentId.toString()}));

Body:
I have a problem combining  UnderscoreJS and MongooseJS in NodeJS. I have a result of mongoose and I want filter a array

var __ = require("underscore"),
    platformInfo = __.findWhere(user.platforms, {"pId": platformId});

But pId inside user.platforms is a ObjectId and can't find.
But if i make a each and compare like this all its OK:

__.each(user.platforms, function(platform){

                if(platform.pId.toString() == platformId){

                }

});

How i can find in findWhere method (one line, and cool) the same result? Thanks


问:
Avoid UI locking/freezing when assigning datasource?
I'm using MVP pattern, so I have a View that has almost no logic in it and a Presenter that knows how to react to the user's interactions with the view.
Everytime I need to get data from a service or such my code does so asynchronously, the problem I'm having is that lets say I get 10,000 items that need to be databound to a Grid, when I assign those (marshalling them through the UI thread) my UI locks for short periods of time (because of the Grid control/CurrencyManager locking the thread I think)

Does anybody know possible ways to avoid this?

I've tried assigning the data in incremental chunks with a timer, but still ends making the UI freeze randomly

Cheers

答:
You need to download the data from the server in chunks on a background thread then append them to a client side collection object.  If that collection object implements INotifyCollectionChanged then the grid should update automatically.  You can get this with ObservableCollection, or with Bindable Linq which may be a better choice.

The problem you will run into is that you have a grid re-drawing 10,000 items over and over again.  This is generally not that good of a solution but it can work if you get a grid with UI Virtualization.  For example I use the Telerik GridView control and I have had good results with around 5000 records.

Having tried to answer your question directly, let me give you some advice that may lead you in a better direction.  Direct query of 10,000 items over the network isn't going to be blazing fast no matter how cool your grid control is.  You may want to consider using a service bus to communicate async to the server and store a copy of the data in a local database.  I am working on a project that will use Rhino Service Bus to make a smart client that can work even if the network connection goes down for a short time.  The service bus approach to smart client development should make your UI locking pains go away and make your app more stable and resilient to network traffic.


问:
How can I get numeric value of Sunday to 1
I am trying to get numeric value of Sunday as 1

```<code>$day_of_week = date('N', strtotime('Sunday'));
</code>```

returns 7.

Can I get 1 instead of 7?

答:
```<code>$day_of_week = date('w', strtotime('Sunday'));
echo $day_of_week + 1;
</code>```

You can use this method because there are only two way for get week days one is 'N' which you are using which returns 1-7 But monday is first day

Second is 'w' is returns 0-6 And Sunday is first day so you just need addition for number 1

Body:
I am trying to get numeric value of Sunday as 1

$day_of_week = date('N', strtotime('Sunday'));

returns 7.

Can I get 1 instead of 7?

Body:
$day_of_week = date('w', strtotime('Sunday'));
echo $day_of_week + 1;

You can use this method because there are only two way for get week days one is 'N' which you are using which returns 1-7 But monday is first day

Second is 'w' is returns 0-6 And Sunday is first day so you just need addition for number 1


问:
Doctrine2 - add or update without Id
I need to check my database for two fields and if they exist to update them and if not to create new.

I want to do that without using an id as post parameter. I was trying to search with $firstFiled parameter.

It throws an error

"Call to a member function setFirstName() on null"

and there are no changes in a database.

My code:

```<code>public function import($firstName, $lastName)
{
    if($firstName instanceof MyEntity) {

        $new = $this->getMyEntityRepository()->findOneBy([
            'firstName' => $firstName,
            'lastName' => $lastName,
        ]);

    } else {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    $new->setFirstName($firstName);
    $new->setLastName($lastName);
    $this->em->flush();

}
</code>```

答:
That code does not make a lot of sense to me; not the condition nor the nested MyEntity objects.

What you probably want, is to look for and fetch an object or instantiate a new one if none is found. That is assuming that the first- and last names are not actually instances of that same class.

Edit: Note that you need the actual first- and lastnames in order to find the entity in the repository.

So something like:

```<code>public function import($firstName, $lastName, $newFirstName, $newLastName)
{
    # Get entity from the repository using the current values
    $new = $this->getMyEntityRepository()->findOneBy([
        'firstName' => $firstName,
        'lastName' => $lastName,
    ]);

    # If no entity is found, create a new one
    if(!$new instanceof MyEntity) {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    # Update the existing or new entity with the new values
    $new->setFirstName($newFirstName);
    $new->setLastName($newLastName);
    $this->em->flush();

}
</code>```

By the way, renaming your class and variables to the things they actually represent, would make it easier to spot logical errors like that.

Title: Doctrine2 - add or update without Id

Body:
I need to check my database for two fields and if they exist to update them and if not to create new.

I want to do that without using an id as post parameter. I was trying to search with $firstFiled parameter.

It throws an error

"Call to a member function setFirstName() on null"

and there are no changes in a database.

My code:

public function import($firstName, $lastName)
{
    if($firstName instanceof MyEntity) {

        $new = $this->getMyEntityRepository()->findOneBy([
            'firstName' => $firstName,
            'lastName' => $lastName,
        ]);

    } else {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    $new->setFirstName($firstName);
    $new->setLastName($lastName);
    $this->em->flush();

}

Body:
That code does not make a lot of sense to me; not the condition nor the nested MyEntity objects.

What you probably want, is to look for and fetch an object or instantiate a new one if none is found. That is assuming that the first- and last names are not actually instances of that same class.

Edit: Note that you need the actual first- and lastnames in order to find the entity in the repository.

So something like:

public function import($firstName, $lastName, $newFirstName, $newLastName)
{
    # Get entity from the repository using the current values
    $new = $this->getMyEntityRepository()->findOneBy([
        'firstName' => $firstName,
        'lastName' => $lastName,
    ]);

    # If no entity is found, create a new one
    if(!$new instanceof MyEntity) {
        $new = new MyEntity();
        $this->em->persist($new);
    }

    # Update the existing or new entity with the new values
    $new->setFirstName($newFirstName);
    $new->setLastName($newLastName);
    $this->em->flush();

}

By the way, renaming your class and variables to the things they actually represent, would make it easier to spot logical errors like that.


问:
mPDF creates blank page after TOC when using different orientation
I'm trying to create a PDF file via mPDF where the sheets have the following orientation:

```<code>___________
| Page 1   |
|          |
| Portrait |
|          |
___________
___________
| Page 2   |
|  TOC     |
| Portrait |
|          |
___________
__________________
| Page 3          |
| Landscape       |
|                 |
__________________
___________
| Page 4   |
|          |
| Portrait |
|          |
___________
</code>```

However, changing the orientation of page 3 makes mPDF create a blank page between page 2 (TOC) and page 3.

The PDF is created in HTML and then processed to mPDF. The code is as follows:

HTML:

```<code><html>
<head>
    <style>
        @page page-landscape { size: landscape; }
        @page page-portrait { size: portrait; }

        div.landscape {
            page: page-landscape;
        }
        div.portrait {
            page: page-portrait;
        }

    </style>
</head>
<body>
    <div>
        <div>First page - displayed Portrait. The second page should be the TOC (portrait) and the 3rd should be on landscape</div>
    </div>

    <tocpagebreak />

    <div class="landscape">
       <bookmark content="TOC entry" level="0"/>
        <tocentry content="TOC entry" level="0"/>
        <p>TOC entry - Shouldn\'t have a empty page before</p>
    </div>

    <div class="portrait">
        another page
    </div>
</body>
</html>
</code>```

PHP

```<code>$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output();
</code>```

I've tried a number of things to make this work, without success. I'll list some of them:

Using toc-selector="page-portrait" on the <tocpagebreak> tag

Using toc-orientation="P" on the <tocpagebreak> tag

Adding a <pagebreak orientation="L" /> after the <tocpagebreak>

Using class="landscape" in the div after the TOC, using the @page selector, as shown in this example

Setting the variable autoPageBreak to false on mPDF's constructor

Wrapping the pages in div and messing around with the position of <pagebreak>

I was using mPDF v6.0 and now I'm updating to mPDF v8.0.1. This issue occurs on all versions (6, 7 and 8). While on version 6 I used a hack by adding $mpdf->DeletePages(2); after $mpdf->WriteHTML($html); but this has two major problems:

This method is undocumented and seems buggy

With this, the page number doesn't match the correct pages, so I can't add page number on the footer

Is there any way to accomplish this without a blank page? Or a viable workaround?

答:
I am using the code in the question and updated it to generate pdf without empty page after TOC in pdf.

It is given here that TOCpagebreak will always start at an odd page number. Also, there is an issue with mpdf where it adds a blank page after TOC page.

I have divided the html code in two parts and deleted the blank page after TOC to get the final pdf.

The code in php is:

```<code>
require_once __dir__.'/vendor/autoload.php';

$html = '<html>
<head>
    <style>
        @page page-landscape { size: landscape; }
        @page page-portrait { size: portrait; page-break-inside:avoid; }

        div.landscape {
            page: page-landscape;
        }
        div.portrait {
            page: page-portrait;
        }

    </style>
</head>
<body>
    <div>
        <div>First page - displayed Portrait. The second page should be the TOC (portrait) and the 3rd should be on landscape</div>
    </div>

<tocpagebreak />';

$mpdf = new \Mpdf\Mpdf();

$mpdf->WriteHTML($html);
$page = $mpdf->page;

$html2= '<div class="portrait" style="page-break:avoid !important;">
       <bookmark content="TOC entry" level="0"/>
        <tocentry content="TOC entry" level="0"/>
        <p>TOC entry - Shouldn\'t have a empty page before</p>
    </div>

    <div class="landscape">
        another page
    </div>
</body>
</html>';

$mpdf->WriteHTML($html2);
$mpdf->DeletePages($page);
$mpdf->Output();
</code>```

Body:
I'm trying to create a PDF file via mPDF where the sheets have the following orientation:

___________
| Page 1   |
|          |
| Portrait |
|          |
___________
___________
| Page 2   |
|  TOC     |
| Portrait |
|          |
___________
__________________
| Page 3          |
| Landscape       |
|                 |
__________________
___________
| Page 4   |
|          |
| Portrait |
|          |
___________

However, changing the orientation of page 3 makes mPDF create a blank page between page 2 (TOC) and page 3.

The PDF is created in HTML and then processed to mPDF. The code is as follows:

HTML:

First page - displayed Portrait. The second page should be the TOC (portrait) and the 3rd should be on landscape

    <tocpagebreak />

       <bookmark content="TOC entry" level="0"/>
        <tocentry content="TOC entry" level="0"/>

TOC entry - Shouldn\'t have a empty page before

        another page

PHP

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML($html);
$mpdf->Output();

I've tried a number of things to make this work, without success. I'll list some of them:

Using toc-selector="page-portrait" on the <tocpagebreak> tag

Using toc-orientation="P" on the <tocpagebreak> tag

Adding a <pagebreak orientation="L" /> after the <tocpagebreak>

Using class="landscape" in the div after the TOC, using the @page selector, as shown in this example

Setting the variable autoPageBreak to false on mPDF's constructor

Wrapping the pages in div and messing around with the position of <pagebreak>

I was using mPDF v6.0 and now I'm updating to mPDF v8.0.1. This issue occurs on all versions (6, 7 and 8). While on version 6 I used a hack by adding $mpdf->DeletePages(2); after $mpdf->WriteHTML($html); but this has two major problems:

This method is undocumented and seems buggy

With this, the page number doesn't match the correct pages, so I can't add page number on the footer

Is there any way to accomplish this without a blank page? Or a viable workaround?

Body:
I am using the code in the question and updated it to generate pdf without empty page after TOC in pdf.

It is given here that TOCpagebreak will always start at an odd page number. Also, there is an issue with mpdf where it adds a blank page after TOC page.

I have divided the html code in two parts and deleted the blank page after TOC to get the final pdf.

The code in php is:

require_once __dir__.'/vendor/autoload.php';

$html = '<html>
<head>
    <style>
        @page page-landscape { size: landscape; }
        @page page-portrait { size: portrait; page-break-inside:avoid; }

        div.landscape {
            page: page-landscape;
        }
        div.portrait {
            page: page-portrait;
        }

    </style>
</head>
<body>
    <div>
        <div>First page - displayed Portrait. The second page should be the TOC (portrait) and the 3rd should be on landscape</div>
    </div>

<tocpagebreak />';

$mpdf = new \Mpdf\Mpdf();

$mpdf->WriteHTML($html);
$page = $mpdf->page;

$html2= '<div class="portrait" style="page-break:avoid !important;">
       <bookmark content="TOC entry" level="0"/>
        <tocentry content="TOC entry" level="0"/>
        <p>TOC entry - Shouldn\'t have a empty page before</p>
    </div>

    <div class="landscape">
        another page
    </div>
</body>
</html>';

$mpdf->WriteHTML($html2);
$mpdf->DeletePages($page);
$mpdf->Output();


问:
SQL Server Subquery returned more than 1 value.This is not permitted
I have this query

```<code>SELECT
   concat(section.SectionType,Item.Size,'-',Grade.Grade)as 'item'
  ,sum([RemainingQuantity]) as 'Quantity'
  ,[Length]
  ,[Width]
  ,loc.Location
 ,(Select sum(ODRM.[QuantityBooking]-ODRM.ChangeLocationQty)
    FROM [dbo].[OrderDetailsRawMaterial] ODRM
    inner join RawMaterial rawmat on rawmat.id=[FK_RawMaterial]
    Where  ODRM.[QuantityBooking] >ODRM.ChangeLocationQty
    Group By rawmat.FK_Item
    )as'QuantityBooking'
FROM [dbo].[RawMaterial]
inner join item on Item.id=FK_Item
inner join SectionType section on section.id=Item.FK_SectionType
inner join Grade on Grade.id=Item.FK_Grade
inner join Location loc on loc.id=FK_Location
Where show=1 and ShowQuality=1 and [RemainingQuantity]>0
Group By
 concat(section.SectionType,Item.Size,'-',Grade.Grade)
 , [Length]
  ,[Width]
  ,loc.Location
Order By concat(section.SectionType,Item.Size,'-',Grade.Grade)
</code>```

but when i run the query i get this error

Msg 512, Level 16, State 1, Line 4
  Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Why do I get this error and how can I fix it. Thanks in advance.

答:
group by naturally produces more than one rows whereas subquery in select statement needs only one.

You need to change group by in the way that outer query will be related with inner query.

the trick is to add awmat.FK_Item = item.Id

Change the inner query like below

```<code>select sum(ODRM.[QuantityBooking]-ODRM.ChangeLocationQty)
FROM [dbo].[OrderDetailsRawMaterial] ODRM
inner join RawMaterial rawmat on rawmat.id=[FK_RawMaterial]
Where  ODRM.[QuantityBooking] >ODRM.ChangeLocationQty
  and awmat.FK_Item = item.Id
</code>```

Body:
I have this query

SELECT
   concat(section.SectionType,Item.Size,'-',Grade.Grade)as 'item'
  ,sum([RemainingQuantity]) as 'Quantity'
  ,[Length]
  ,[Width]
  ,loc.Location
 ,(Select sum(ODRM.[QuantityBooking]-ODRM.ChangeLocationQty)
    FROM [dbo].[OrderDetailsRawMaterial] ODRM
    inner join RawMaterial rawmat on rawmat.id=[FK_RawMaterial]
    Where  ODRM.[QuantityBooking] >ODRM.ChangeLocationQty
    Group By rawmat.FK_Item
    )as'QuantityBooking'
FROM [dbo].[RawMaterial]
inner join item on Item.id=FK_Item
inner join SectionType section on section.id=Item.FK_SectionType
inner join Grade on Grade.id=Item.FK_Grade
inner join Location loc on loc.id=FK_Location
Where show=1 and ShowQuality=1 and [RemainingQuantity]>0
Group By
 concat(section.SectionType,Item.Size,'-',Grade.Grade)
 , [Length]
  ,[Width]
  ,loc.Location
Order By concat(section.SectionType,Item.Size,'-',Grade.Grade)

but when i run the query i get this error

Msg 512, Level 16, State 1, Line 4
  Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Why do I get this error and how can I fix it. Thanks in advance.

Body:
group by naturally produces more than one rows whereas subquery in select statement needs only one.

You need to change group by in the way that outer query will be related with inner query.

the trick is to add awmat.FK_Item = item.Id

Change the inner query like below

select sum(ODRM.[QuantityBooking]-ODRM.ChangeLocationQty)
FROM [dbo].[OrderDetailsRawMaterial] ODRM
inner join RawMaterial rawmat on rawmat.id=[FK_RawMaterial]
Where  ODRM.[QuantityBooking] >ODRM.ChangeLocationQty
  and awmat.FK_Item = item.Id


问:
Eloquent query with two models
I need your help, please!
I have two models customer and membership. Customer hasMany Memberships.
I need to extract all customers with a membership active. I did this but it extracts only memberships, without customers data. How can I change it to solve the problem?

```<code>Membership::has("customer")
    ->forCompany($companyId)
    ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
    ->where(function ($query) {
        $query
            ->where('end_date', '>=', Carbon::now()->toDateString())
            ->orWhereNull('end_date');
    })
</code>```

答:
You want to pull customer and check for it's active membership. Rather your query calls membership first. You query should be:

```<code>Customer::whereHas('memberships', function ($query) use ($companyId){
    $query
        ->forCompany($companyId)
        ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
        ->where(function ($sub_query) {
            $sub_query
                ->where('end_date', '>=', Carbon::now()->toDateString())
                ->orWhereNull('end_date');
        });
    })
    ->with(['memberships'])
    ->get();
</code>```

In above code, 'memberships' is the relationship definition in customer model. Similar as below:

```<code>public function memberships() {
   return $this->hasMany('App\Membership');
}
</code>```

Title: Eloquent query with two models

Body:
I need your help, please!
I have two models customer and membership. Customer hasMany Memberships.
I need to extract all customers with a membership active. I did this but it extracts only memberships, without customers data. How can I change it to solve the problem?

Membership::has("customer")
    ->forCompany($companyId)
    ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
    ->where(function ($query) {
        $query
            ->where('end_date', '>=', Carbon::now()->toDateString())
            ->orWhereNull('end_date');
    })

Body:
You want to pull customer and check for it's active membership. Rather your query calls membership first. You query should be:

Customer::whereHas('memberships', function ($query) use ($companyId){
    $query
        ->forCompany($companyId)
        ->whereIn('state', ['ATTIVA', 'IN ATTESA DI ESITO', 'DA INVIARE'])
        ->where(function ($sub_query) {
            $sub_query
                ->where('end_date', '>=', Carbon::now()->toDateString())
                ->orWhereNull('end_date');
        });
    })
    ->with(['memberships'])
    ->get();

In above code, 'memberships' is the relationship definition in customer model. Similar as below:

public function memberships() {
   return $this->hasMany('App\Membership');
}