Exception when Intent Data to another Activity android.content.Context.getPackageName()

Question: Hello guys  iam trying to get Data to putExtra  => Intent from an Adapter to another Activity but every time i try to get data from the Adapter to the Activity  it Gives me this Exception that

java.lang.String android.content.Context.getPackageName()'

so i tried to Enter the Context class i found it too many Errors  cant fix that till now
what makes me really Believe that the problem with the Context is that when i Tried to use TinyDB
it need to define the Object  inside the Adapter

tinyDB = new TinyDB(mContext);

the program Crashed and Gives Me this Exception
    W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
W/System.err:     at android.content.ComponentName.<init>(ComponentName.java:128)
                  at android.content.Intent.<init>(Intent.java:4910)
                  at com.team.plustegara.Views.Models.Adapters.EventsAdapter$1.onClick(EventsAdapter.java:83)
                  at android.view.View.performClick(View.java:5647)
                  at android.view.View$PerformClick.run(View.java:22465)
                  at android.os.Handler.handleCallback(Handler.java:754)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
W/System.err:     at android.os.Looper.loop(Looper.java:163)
                  at android.app.ActivityThread.main(ActivityThread.java:6238)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

i tried to Fix that but still cant handle the Context problem

Here is my Adapter

public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsHolder> {

public EventsAdapter(List<EventsModel> list, Context mContext) {
    this.list = list;
    this.mContext = mContext;
}

private List<EventsModel> list;
private Context mContext;

FirebaseAuth mAuth;
DatabaseReference dbRef;

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

}

@Override
public void onBindViewHolder(@NonNull final EventsHolder holder, int position) {

    final EventsModel listy = list.get(position);

    holder.eventTitle.setText(listy.getTitle());
    holder.eventDate.setText(listy.getEventDate());
    holder.eventCosts.setText("Event Costs " + listy.getCosts());

    Picasso.get()
            .load(listy.getEventImage())
            .fit()
            .centerCrop()
            .placeholder(R.drawable.gradients_card)
            .into(holder.eventImage);

    holder.cardViewEvents.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {

                Intent intent = new Intent(mContext, ShowActivityEvents.class);

                intent.putExtra("EventImage", listy.getEventImage());
                intent.putExtra("EventTitle", listy.getTitle());
                intent.putExtra("EventDate", listy.getEventDate());
                intent.putExtra("EventCosts", listy.getCosts());
                intent.putExtra("EventDescription", listy.getDescription());
                intent.putExtra("eventID", listy.getPostID());
                   mContext.startActivity(intent);

                dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
                mAuth = FirebaseAuth.getInstance();

                String userName = mAuth.getCurrentUser().getDisplayName();

                String postID = listy.getPostID();
                dbRef.child("Events").child(postID).child("Views").push().setValue(userName);

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

        }
    });

    String postID = listy.getPostID();
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("PlusTeam");
    databaseReference.child("Events").child(postID).child("Views").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            long ViewsCount = dataSnapshot.getChildrenCount();
            holder.txtViews.setText(String.valueOf(ViewsCount));
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toasty.error(mContext, databaseError.getMessage(), Toast.LENGTH_LONG).show();
        }
    });

}

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

public class EventsHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.EventImageCard)
    ImageView eventImage;
    @BindView(R.id.txtEventTitle)
    TextView eventTitle;
    @BindView(R.id.txtEventDate)
    TextView eventDate;
    @BindView(R.id.txtEventCosts)
    TextView eventCosts;
    @BindView(R.id.cardView_EventsCard)
    CardView cardViewEvents;
    @BindView(R.id.txtEventsViews) TextView txtViews;

    public EventsHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);

       }
    }

}

here is my Activity which receive the Extras from the Adapter

public class ShowActivityEvents extends AppCompatActivity {

DatabaseReference dbRef;
FirebaseAuth mAuth;

@Override
protected void onStart() {
    super.onStart();

    checkIfUserAlreadyAccepttheEvent();

}

private void checkIfUserAlreadyAccepttheEvent() {

    final String postID = getIntent().getExtras().getString("eventID");
    final String UserID = mAuth.getCurrentUser().getUid();

    dbRef.child(postID).child("PeopleComing")
            .addListenerForSingleValueEvent(new ValueEventListener() {
                public static final String TAG = "ShowEvents";

                @SuppressLint("SetTextI18n")
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    Log.e(TAG, "onChildAdded: " + dataSnapshot);

                    String peopleCount = String.valueOf(dataSnapshot.getChildrenCount());
                    txtPeopleComing.setText( peopleCount + " People Comming");

                    if (dataSnapshot.child(UserID).exists()) {

                        btnIamIn.setEnabled(false);

                    } else {
                        btnIamIn.setEnabled(true);
                    }
                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toasty.error(ShowActivityEvents.this, "Error code : " + 1, Toast.LENGTH_LONG).show();

                }
            });
}

@BindView(R.id.btnIamIn)
Button btnIamIn;
@BindView(R.id.txtPeopleComingCount)
TextView txtPeopleComing;

@BindView(R.id.imgEventPost)
ImageView imgEvent;
@BindView(R.id.txtEventTitle) TextView txtEventTitle;
@BindView(R.id.txtEventDescription) TextView txtEventDescription;
@BindView(R.id.txtEventCost) TextView txtEventCost;
@BindView(R.id.txtEventDate) TextView txtEventDate;
Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_events2);

    ButterKnife.bind(this);

    dbRef = FirebaseDatabase.getInstance().getReference("PlusTeam");
    mAuth = FirebaseAuth.getInstance();

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

}

private void loadDataFromAdapter() {

    String Image = getIntent().getExtras().getString("EventImage");
    String Title = getIntent().getExtras().getString("EventTitle");
    String Date = getIntent().getExtras().getString("EventDate");
    String Costs = getIntent().getExtras().getString("EventCosts");
    String Description = getIntent().getExtras().getString("EventDescription");

    GlideApp.with(this)
            .load(Image)
            .fitCenter()
            .into(imgEvent);

    txtEventTitle.setText(Title);
    txtEventDescription.setText(Description);
    txtEventDate.setText(Date);
    txtEventCost.setText(Costs);

}

@OnClick(R.id.btnIamIn) public void addPersonToEvent(){

    String UserName = mAuth.getCurrentUser().getDisplayName();
    String userID = mAuth.getCurrentUser().getUid();

    String postID = getIntent().getExtras().getString("eventID");
    dbRef.child(postID)
            .child("PeopleComing").setValue(UserName);
    btnIamIn.setEnabled(false);

  }

}

Finally just wanted to say i searched for this kind of Problem in Google and inside questions in Stack but didn't worked
so any Suggestions
Comment: You have problems with context. How do you pass it to Adapter
Answer: You should pass your context in adapter like in the example below
Activity
adapter = new EventsAdapter(myList,MainActivity.this);

Fragment
adapter = new EventsAdapter(myList,getActivity());

Or another way
@Override
public void onClick(View v) {
    v.getContext().startActivity(v.getContext(), ShowActivityEvents.class);
}

Comment: can you please tell me how to handle that out side the OnClick(View v)
like in side adapter
Comment: Like you did in your code, but when you create adapter you should pass your context like in first or second example. It depends what do u have activity or fragment
Comment: the case is pass context to tinyDB = new TinyDB(context);   the problem is here  , you've fixed the OnClick method  but  out side didn't work
Comment: Just create another question, because you need to show up how you are passing context, code with TinyDb and the error
Comment: thanks dude i fixed it ,  just needed to add   in  onCreateViewHolder method

contex = parent.getContext();


Splitting ImageFolder into train and validation datasets

Question: I have loaded my dataset as follows :
full_dataset = ImageFolder(root = os.path.join(root, 'train'), transform=train_transforms)

Now to split my dataset into training and validation sets, I used the following code :
train_size = int(0.8 * len(full_dataset))
validation_size = len(full_dataset) - train_size
train_dataset, validation_dataset = random_split(full_dataset, [train_size, validation_size])

Both train_dataset and validation_dataset are of type : torch.utils.data.dataset.Subset. Is there any way to convert these datasets into torchvision.datasets.folder.ImageFolder.
I need to do this as I am not able to iterate through datasets of type torch.utils.data.dataset.Subset
Comment: what do you mean by "unable to iterate ... `Subset`"? `ImageFolder` and `Subset` should be derived from the same super class and have very similar interface.
Answer: You should be able to iterate through a Subset just fine, since it has the __getitem__ method implemented as you can see from the source code :
class Subset(Dataset):
    r"""
    Subset of a dataset at specified indices.

    Arguments:
        dataset (Dataset): The whole Dataset
        indices (sequence): Indices in the whole set selected for subset
    """
    def __init__(self, dataset, indices):
        self.dataset = dataset
        self.indices = indices

    def __getitem__(self, idx):
        return self.dataset[self.indices[idx]]

    def __len__(self):
        return len(self.indices)

So the following should work:
for image, label in train_dataset:
    print(image, label)

Or you can create a Dataloader from a Subset:
train_dataloader = DataLoader(train_dataset, batch_size, shuffle)

for images, labels in train_dataloader:
    print(images, labels)

Same for validation_dataset.
Comment: Sorry for the late reply. I was able to create a DataLoader from the Subset.


How to go about planning a modular eCommerce web application?

Question: I have been tasked with doing some planning and research for a home grown in house application.  Our primary development language is ColdFusion and Flex3, so I wanted to attack this problem with a modular solution, using an MVC framework.
I must mention that I am not a huge ColdFusion developer, but will be one of the architects behind this app (yikes!). I have a few years experience developing ecommerce applications in .NET / PHP / ASP, but never on this type of scale.
The overall goal is to build a module based applciation that we can roll out and 'add' modules for functionality, so as not to lock ourselves in a certain direction.
The system requires two key things:

Functionality must be a 'drop and go' type, so that if the eCommerce application requires functionality like paypal processing, we drop in the paypal module, and bam it is an option at checkout, etc;
Ability to handle multiple brands (we have a few markets we serve, and each market has its own brand).

Ok enough background...
My key concerns are, how should I start? I am looking at using a ColdFusion MVC framework, any suggestions at which? I've looked at the following(for Coldfusion):

Model-Glue
Cairngorm
Pivot-MVC
Fusebox

Am I on the right track? I hope using an MVC will help reach the goal of a drop in and go modular functionality with reduced time spent coding repetitive things. I don't know enough about these MVC frameworks tho.
Would appreciate any helpful suggestions so I can formulate a precise plan of attack.
EDIT:
Having reviewed ColdBox, what would be a comparison to use it over another MVC? I've read that it does not support the 'drop and go' type of functionality.
Any other opinions on an MVC framework for CF?
Answer: I selected the ColdBox Framework for ColdFusion for its rich feature set, ability to be a controller for my Ajax/Flash/Web Service development, active community and frequent releases. Most importantly, I selected ColdBox for the amazing amount of documentation--allowing me faster answers while affording me even more time to write code rather than documenting how the application works.
I encourage a framework--any framework. It will foster faster development, help guide best practices and enable the application to have a long life--past you and other developers.
So, YES! You are on the right track.
Links of Interest

Sample Applications
Down and Dity ColdBox PDF
Documentation
ColdBox API Reference
Paid Training and Certification
Who Uses ColdBox

Respectfully,
Aaron Greenlee
Comment: i'm a long time model-gluer, but would probably choose coldbox for a new app
Comment: Is functionality like the 'drop and use' method I described something that you have seen used before? OR should this angle be re-throught?  What I DON'T want to do is tailor the eCommerce app per biz unit, but for all as a whole, and provide specific needs via plug-in modules.
Comment: Just curious why would you choose coldbox over any other? Can you list a few points? In some research most CF MVC's seem to share same features, but coldbox just has more complete documentation it seems..? Or am I off...
Comment: Yes, I can add some points.

I first selected ColdBox for deeper exploration when I recognized it had an impressive amount of documentation. I invested in production applications on ColdBox after recognizing the value of the toolkit (check out the interceptors, plugins and cache). ColdBox was (and may still be) the only framework with a debugger.

ColdBox is more than MVC and code organization or a front controller. Its a framework and toolkit suite.
Answer: If it were me, i'd plan the users viewpoint of the application, how many steps there were, how many different pages, what is the function, design purposes of each page.
Then plan out each page's logic, what it needs to do etc..step by step no code, just lots of comments.
Then maybe do a wireframe html/css pages with no coldfusion to show you step by step how the ecommerce application would act like..
Then start making page by page, and do lots of testing....the clearer your plans are for any plans, the less chance of feature creep.
Answer: Well, I hope I'm understanding you correctly here.  All of the options you listed are great frameworks.  However, when you set one up, at most, you're going to get a 'Hello World' sort of site out of it, and from there, you're probably on your own.  MVC frameworks are designed to sort of split apart different part of programming (the logic, the appearance, the overall data model, etc.) to allow for easy reuse, but not at a level of 'Oh, add PayPal, Authorize.Net and PayflowPro to the last step of my cart' sort of application.
It sounds like you're looking for a CF-based eCommerce application like Cartweaver, and then to acquire or buy Cartweaver plugins to extend it (to offer different types of shipping, payment processing, etc., etc.).


Find the transfer function and state space of the system

Question: Two separate experiments are performed for t ≥ 0 on the single-input single-output (SISO) linear system $\dot{x} = Ax + Bu, y = Cx + Du$, $x(0) = \begin{bmatrix}1\\2\\-1\end{bmatrix}$ (the initial condition is the same in each experiment)
In the first experiment, $u(t) = e^{-t}$ and the resulting output is y(t) = $e^{-3t} + e^{-2t}$
In the second, $u(t) = e^{-3t}$ and the resulting output is $y(t) = 3e^{-3t} − e^{-2t}$
(a) Can you determine the transfer function $C(sI−A)^{-1}$B+D from this information? If it is possible, do so. If not, find two linear systems consistent with all the data given which have different transfer functions.
(b) Can you determine A, B, C, or D?
i tried taking the laplace transform of each inputs and outputs :
$Y_1(s) = \frac{1}{s+3} + \frac{1}{s+2} , U_1(s) = \frac{1}{s+1}$
$Y_2(s) = \frac{3}{s+3} - \frac{1}{s+2} , U_2(s) = \frac{1}{s+3}$
from what i've known output is summation of the initial condition term and input term, so if the initial condition is non-zero.Is the transfer function of the system still $ \frac{Y(s)}{U{s}}$
Comment: This is obviously an exercise, so you will have to show your attempts first. Also, it is better to write down the full question here (and not use a picture) in case the link dies.
Comment: No, when the initial conditions are nonzero, then you have that $Y(s)=C(sI-A)^{-1}x_0+H(s)U(s)$ where $H(s)=C(sI-A)^{-1}B+D$. What you can do now, is expressing $Y_1(s)$ and $Y_2(s)$ and a build a system of linear equations in the "unknowns" $H(s)$ and $C(sI-A)^{-1}x_0$. Then, solve that and see what you get.
Comment: i'm really sorry, this is my first time posting. I already edited the post.
Comment: No problem. This is much better now.
Comment: I tried thinking about it but don't really get how i can form the state space from Y(s) and does x(t) = [y1 dy1/dt y2]?
Comment: Answer first the first question. You'll see later for the state space form expression.
Comment: I've got $\begin{bmatrix}Y1(s)\\Y2(s)\\\end{bmatrix} =\begin{bmatrix}\frac{-H(s)}{s+1}+\frac{1}{s+2}+\frac{1}{s+3}\\\frac{-1}{s+2}+\frac{3-H(s)}{s+3}\\\end{bmatrix} + \begin{bmatrix}H(s)&0\\0&H(s)\\\end{bmatrix}U(s)$ and then i set the inital condition term of two equations equal to each other to find H(s). Am i doing this correctly?
Comment: No, you need to write a system of two linear equations with the two unknowns $H(s)$ and $C(sI-A)^{-1}x_0$. If $X(s)=[H(s)\ C(sI-A)^{-1}x_0]^T$, then you will have $Y(s)=M(s)Xs)$ for some $M(s)$ that you will need to find and invert, if possible, to find the solution(s).
Answer: I will post a beginning of a solution to help OP, and I will complete it bit by bit.
So, we can write the following system of equations
$$
\begin{bmatrix}
Y_1(s)\\
Y_2(s)
\end{bmatrix}=\begin{bmatrix}
U_1(s) & 1\\
U_2(s) & 1
\end{bmatrix}\begin{bmatrix}
H(s)\\
G(s)
\end{bmatrix}
$$
where $H(s)=C(sI-A)^{-1}B+D$ and $G(s)=C(sI-A)^{-1}x_0$. So, we get that
$$
\begin{bmatrix}
H(s)\\
G(s)
\end{bmatrix}=\begin{bmatrix}
U_1(s) & 1\\
U_2(s) & 1
\end{bmatrix}^{-1}\begin{bmatrix}
Y_1(s)\\
Y_2(s)
\end{bmatrix}=\dfrac{1}{U_1(s)-U_2(s)}\begin{bmatrix}
1 & -1\\
-U_2(s) & U_1(s)
\end{bmatrix}\begin{bmatrix}
Y_1(s)\\
Y_2(s)
\end{bmatrix}.
$$
Then, the idea would be to see whether the transfer function is realizable, which means that $H(s)$ is rational and proper (i.e. the degree of the numerator is at most that of the denominator).

Edit. Construction of a possible realization for the $H(s)$ of order 3.
So, after some tedious algebra we get (as @nap also correctly obtained)
$$H(s)=\dfrac{s+1}{s+2}=1-\dfrac{1}{s+2}$$
and
$$G(s)=\dfrac{1}{s+3}.$$
Since, there is constant term in $H(s)$, we can put this in the direct feedthrough $D=1$, and then we get that $C(sI-A)^{-1}B=-1/(s+2)$.
The dimension of the system is 3 (from the initial condition), so the model will not be minimal and a mode will be uncontrollable and/or observable.
One way to build the system is to fix an eigenvalue of $A$ to be $-3$ and to build $A$ such that $x_0$ is an eigenvector. Similarly, we can set an eigenvalue to be -2 and to set $B$ to be an eigenvector (i.e. this eigenvalues is chosen this way because we need to have $s+2$ at the denominator in one way or another). So, we pick for instance,
$$B=\begin{bmatrix}1\\0\\0\end{bmatrix},$$
and note that this choice is completely arbitrary. We just need to make sure that $B$ is linearly independent of $x_0$. And we can just a last eigenvalue at random, say -1, and pick the eigenvector to be $(0,1,0)$ which is linearly independent of the others.
We can now build the matrix of eigenvectors
$$V=\begin{bmatrix}1 & 1 & 0\\0 & 2 & 1\\0 & -1 & 0\end{bmatrix}$$
which is associated with the diagonal matrix
$$D=\begin{bmatrix}-2 & 0 & 0\\0 & -3 & 0\\0 & 0 & -1\end{bmatrix}$$ which is the diagonal form of $A$ in the basis $V$. We can now find $A$ using the expression $A=VDV^{-1}$ and we get
$$A=\begin{bmatrix}
-2 & 0 & 1\\
0 & -1 & 4\\
0& 0 & -3\end{bmatrix}$$
Now, we need to select $C$. To do so, we evaluate the following expressions
$$(sI-A)^{-1}x_0=\dfrac{1}{s+3}x_0$$
as expected and
$$(sI-A)^{-1}B=\dfrac{1}{s+2}B$$.
So, if we pick $C=\begin{bmatrix}-1 & 1 & 0\end{bmatrix}$, we get that
$$C(sI-A)^{-1}B+D=1-\dfrac{1}{s+2}$$
and
$$C(sI-A)^{-1}x_0=\dfrac{1}{s+3}$$
as desired.

Update. What if the order of the system is 2. In this case, $H(s)$ and $G(s)$ remain the same but one can define now
$$D=\begin{bmatrix}-2 & 0\\0 & -3\end{bmatrix}$$
and
$$V=\begin{bmatrix}b & x_0\end{bmatrix}$$
where $b$ must be such that $V$ is invertible; i.e. $b$ and $x_0$ are linearly independent. Then, the rest follows from the same lines as in the previous case.
Comment: Your expressions are correct. Now, the issue is how to interpret the second question. If the question is about the unique characterization of the matrices, then no, because the system is of order 3 (dimension of the initial condition) whereas the transfer function is of order 1, which means that some modes are uncontrollable, unobservable or both. If the goal is to find one possible solution for the matrices, then yes, you can, and there are infinitely many.
Comment: I have updated my answer with a possible way to find one possible realization as it is a bit complicated.
Comment: If the system is of order 2, $H(s)$ and $G(s)$ will remain exactly the same. The other matrices will have to be redesigned. I will update the answer.
Comment: Thanks, now i get $H(s) = \frac{s+1}{s+2}$ , $G(s) = \frac{1}{s+3}$.
I try to solve $H(s)=C(sI−A)^{−1}B + D$ and $G(s) = C(sI - A)^{-1}x_{0}$, but it doesn't seem to be possible to solve it directly to get A, B, C, D. Is there any other way?
Comment: I'm curious that if H(s) is of order 2, can we use the same method?, like suppose H(s) = $1 -\frac{1}{(s+2)(s+1)}$, i will get $ \frac{-1}{(s+2)(s+3)} = C(\frac{1}{s+2})B$  which is  $ \frac{-1}{s+3} = CB$. Is there something wrong?
Comment: sorry, i mean if i have a system that the transfer function is of 2nd order and $(sI-A)^{-1}B = \frac{1}{s+b}B$ where B is eigenvector and b is eigenvalue of A, if the transfer function is $\frac{1}{(s+a)(s+b)}$ and assume D is zero, i will get $\frac{1}{s+a} = CB$ but shouldn't CB be a constant?
Comment: No, if $H(s)$ is of order two and of the form you provide, then $B$ should be a vector in both the eigenspace of $-1$ and $-b$. You will need to do all the calculations from the beginning and not just try to fiddle around.
Comment: Thank you so much, i really appreciate you efforts.


How to find the torque and mass of an object hanging from a bended bar?

Question: The problem is as follows:
The figure from below shows a homogeneous bar with the shape of an $L$ which mass is $6\,kg$ and its length is $30\,cm$. Find the mass of the block which is hanging from a wire and pulley tied to the end of the bar such that it is in equilibrium in the position shown. You may use the gravity $g=10\,\frac{m}{s^2}$.

The alternatives given are as follows:
$\begin{array}{ll}
1.&4\,kg\\
2.&10\,kg\\
3.&15\,kg\\
4.&20\,kg\\
5.&24\,kg\\
\end{array}$
I'm not sure how to make the right interpretation of the torque in this problem. How should I make the vector decomposition?.
The figure from below shows how I attempted to use those vectors.

However I don't know where should I put the center of mass in this weird object. Is it in the middle?. Is it at $15\,cm$ going from the wall where the joint is put?.
From the drawing I could spot that the torque for the system would be as follows:
I'm assuming that the force on $x-axis$ will not generate torque.
$-60(15)+10m(\sin 37^{\circ})(20)=0$
$120m=900$
$m=7.5\,kg$
Although I arrived to an answer it does not check with any of the alternatives. Can someone help me to find where exactly did I made the mistake?. Can someone help me with a solution using trigonometry approach and vector decomposition?. I would like that an answer could include a method also to calculate or find the center of mass in such a figure. Will this be relevant for the solution of this problem?.
Answer: Every 2D system in equilibrium must satisfy three conditions: $\sum F_x = 0$, $\quad$ $\sum F_y=0$, $\quad$ $\sum M =0$ $\quad$ where $M$ is "momentum" product of force by distance, the torque. We use distances to the suport in the joinment to the wall.
I suppose your system is full-rigid, no deformations. Otherwise another considerations must be taken into account.
The bar can be considered as a unique element, with its center of mass located at $x= \frac {massHor·distHor+massVer·distVer}{massHor+massVer}$. But it's easier if we split the bar into two pieces: horizontal and vertical.
The mass of each "subbar" is proportional to its length, namely $4kg$ and $2kg$.
The actions of the bars over the joinment at wall are:
$\qquad$ $F_{xh} = 0$ $\qquad$ $F_{yh} = -4g$ $\qquad$ $M_{h}=F_{yh}·20/2 = -40g$
$\qquad$ $F_{xv} = 0$ $\qquad$ $F_{yv} = -2g$ $\qquad$ $M_{v}=F_{yv}·20 = -40g$
The action of the wire can be decomposed into X,Y directions:
 $\qquad$ $F_{xT} = mg·cos(37º)$ $\qquad$ $F_{yT} = mg·sin(37º)$
Using these forces to calculate the momentum:
 $\qquad$ $M_T= -F_{xT}·10 + F_{yT}·20 = -10mg·cos(37º)+20mg·sin(37º)= 10mg(-cos(37º)+2sin(37º))$ $\qquad$ Pay attention to the sign, positive as counter clockwise rotation.
The final action is that of the joinment to the wall. Intutively we can see that it has a X-component, balancing the system, otherwise the system would translate. So we have
$reaction_x = -F_{xh}-F_{xv}-F_{xT}= -mg·cos(37º)$
For the required equilibrium, because the joinment allows rotations (no momentum in reaction), to avoid them we use $\sum M =0$
$M_h + M_v + M_T = -40g - 40g + 10mg(-cos(37º)+2sin(37º)) = 0$
$m= \frac{80/10}{-cos(37º)+2sin(37º)} = 19.75 kg$
The last calculus is the Y-reaction in the support, using $\sum F_y=0$:
$reaction_y= -F_{yh}-F_{yv}-F_{yT}= 4g+2g-mg·sin(37º) = -5.89g = -58.9N$
This reaction points down (negative). This means that the mass in the hoist is used strictely to avoid the rotation of the bar, a the price of pulling up the support.
Answer: One approach: Split the bent bar into two pieces. Let one piece be the horisontal part together with a massless version of the vertical part, and let the other piece be a massless version of the horisontal part together with the original vertical part.
Each of the two pieces needs some green mass to stay in equilibrium at the position shown in the drawing. Add these two masses to find which mass the pieces need to stay in equilibrium when they are together.
Another approach: The center of mass of the entire bent bar is the (weighted) average of the means of the two pieces mentioned above. Then you can use that to calculate the torque caused by gravity from that center of mass.
Look at the drawing below:

If the horizontal part has mass $m_h$ and the vertical part has mass $m_v$, then the coordinates of the center of mass of the whole bent pipe is given by
$$
\frac{m_h(a, b) + m_v(c, d)}{m_v + m_h}
$$
Comment: I've updated my question because the lengths of the arms were not established correctly. Now it is correct. However I don't understand clearly from your words exactly how to find the center of mass of the object (which is exactly what I was aiming to in my attempt). If you could add some drawing that would help me a lot to visualize what you are trying to say. Can you do that please?.
Comment: @ChrisSteinbeckBell I've added a short description of how exactly to find the center of mass, with an incredibly detailed and skillful drawing to assist in visualisation.
Answer: Hint:
The rod is equilibrated wrt the gravity force when

Now add an additional horizontal $x$ force, plus a vertical force $x/2$ to equilibrate the additional momentum

in such a way as to get the resultant in A with the given angle .
Comment: Sorry I've updated the problem. There was an error in the assigned sizes for the arms of the L shaped object. I'm looking at your solution but I'm still stuck at how did you obtained the masses for each segment of the bar?.I don't understand the statement of adding a horizontal $x$ force and a vertical $\frac{x}{2}$ force and equilibrate the additional momentum. Can you explain this part please?.
Answer: We have
$$
2m\left(10, 0 \right)+m\left(20, 5 \right)= 3m\left(x_g,y_g \right)
$$
now calling
$$
\cases{
G =(x_g, y_g)\\
O = (0,0)\\
P = (20,10)\\
W = (0,-3mg)\\
F = f_0(\cos\phi,\sin\phi)
}
$$
we have the main equilibrium equation
$$
(G-O)\times W + (P-O)\times F = 0
$$
that can be solved for $f_0$
Answer: To determine the mass m.  First of all you take moments about the hinge that is after you determine the cg of the l shaped beam.
Lets find the cg of the beam so we split the beam up into two parts the length of the horizontal section is 20m and the length of the vertical section is 10m.
So to determine the cg of the L shaped beam
Taking moments about the hinge we get
20 × 10 + 10 × 20 = (20 + 10)x
=200 + 200 = 30x
=400.           = 30x
x.                  = 400/30
x.                  = 13.33m from the hinge
Therefore the cg of the beam is 13.33m from the hinge
Now to determine the mass for m we resolve the two components for mass m we get for F horizontal mg cos and Fvertical mg sin
Taking moments about the hinge we get
60 × 13.33 + mg cos 37 = mg sin 37 × 20
799.8 + mg × 0.799 × 10 = mg × 0.602 × 20
799.8 + 7.99 × mg                  = mg × 12.04
799.8.                                       = mg  × 12.04 - 7.99 × mg
799.8                                        = 4.05 × mg
mg                                            799.8/ 4.05
mg.                                           197.5.N. 19.75 kg
Now to determine the reaction on the hinge
Taking moments about the end of the beam at B we get
60(20-13.33) +Rv × 20  = 197.5 × 10 cos 37
60 × 6.67. + Rv × 20  =  19.75  × 10 × 0.799
400.2.+ Rv × 20  = 197.5. × 7.99
400.2 +  Rv × 20. = 1578
Rv × 20.          =  1578 - 400.2
Rv.                   =  1177.8/20
Rv.                    = 58.89N
Using pythagoras to determine the resultant reaction in the hinge
Horizontal reaction Rh. = - 157.8N
Therefore  R = (Rh^2 + Rv^2)^1/2
<code>               Rr =  (157.8^2 + 58.89^2)^1/2

               Rr = 168.4 N
</code>


Update a Single TableView Cell Label

Question: I am trying to create a cell with a 'count' variable which is a label that shows how many items are in a folder. I am doing this with a fetch request in the cellForRowAt func that counts the items in the request. The problem I am facing is that this isn't getting called every-time a new item is added resulting in the wrong count. Reloading the tableView every time in viewWillAppear fixes the problem but won't work in my use case as I am dealing with a lot of data. How could I fix this?
class FolderTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "folderCell", for: indexPath) as! FolderTableViewCell

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Note")
        request.predicate = NSPredicate(format: "userDeleted = false")
        let count = try! context.count(for: request)

        let folders = folderNames(name: "TEST", icon: "TestImage", count: count)
        cell.updateFolders(with: folders)
        return cell
    }

}

class FolderTableViewCell: UITableViewCell {

    func updateFolders(with folders: folderNames) {
        folderCellLabel.text = folders.name
        folderCellImage.image =  UIImage(named: "TestImage")

        if folders.count != 0 {
            folderCellCount.text = "\(folders.count)"
        }
    }

}

Answer: tableView.reloadRows(at: [selectedIndex], with: .automatic)

selectedIndex is the index you want to reload.
refer to this: Is it possible to refresh a single UITableViewCell in a UITableView?
Thanks
Comment: Is this the best way to go about doing this? The only problem with this method is that the deselection on unwind from another VC doesn't occur...

Update a Single TableView Cell Label


How to make comments in HAML

Question: I've found some answers to generate commented HTML code with HAML :
/
  This is actually an HTML comment and not an HAML comment

But it's not what I want.
Indeed, I'm searching for a way to make a line comment in HAML like // in JavaScript or # in Ruby without delete the line and have to re-add it later.
So is there a way to do that in HAML, and how to do this if it's possible ?
Answer: As nobody answered me (I'm very sad !), I didn't stop to search a method to make a comment in HAML file for Ruby, and I found something interesting :
Just declare a line as Ruby code (with -) and add your comment in Ruby !
Example:
%p= "Paragraph"
- # This is a comment in an HAML file and won't be interpreted, yay !

Comment: https://haml.info/docs/yardoc/file.REFERENCE.html#haml-comments-- (as another way to do it).

How to make comments in HAML


How to check entity is already created?

Question: I have the code that create entity named "Victory" in entity type, my problem is how to prevent user creates the entity with the same name again.
<code>function commerce_services_store_create($data, $flatten_fields) {
  $storeName = $data['store_name'];
  $status = 1;

  $entityType = "fruit_store";       //entity type name Fruit Store
  $entity = entity_create($entityType, array('type' => "store")); //bundle store
  $entityWrapper= entity_metadata_wrapper($entityType,$entity);  // create entity named "Victory"
  $entityWrapper->title->set($storeName);
  $entityWrapper->save();

  $store_id = $entityWrapper->id-> value();
  if($store_id != null){
    $reply= (array('status' => $status,'result' =>"Your store name ". $storeName. " Store id is ". $store_id));
  }else{
    $status = 0;
    $result = "Can't create store.";
    $reply = $reply= array('status' => $status,'result' => $result);
  }

  return $reply;

}
</code>
Answer: Just like validating the user email in any system you check if its already exists or not, in your case we need to check that we have no entity with the same attribute value exists:
<code>$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'Fruit_Store')
  ->entityCondition('bundle', 'store')
  // this is a condition for the entity field values
  ->fieldCondition('field_title', 'value', 'spotlight', '=');

$result = $query->execute();

if (!empty($result['Fruit_Store'])) {
  // entity already exsits.
}
else{
  // add new entity
}
</code>
you can find more information about EntityFieldQuery in this page:
https://www.drupal.org/node/1343708
Answer: You can validate the entity type with following:
entity_get_property_info($entity_type = NULL)
Reference:
http://www.drupalcontrib.org/api/drupal/contributions%21entity%21includes%21entity.property.inc/function/entity_get_property_info/7
Updated: Check the below example code for the existing entity
<code>  try {
    // account for user entity exists error
    if (!($args['type'] == 'user' && $account = user_load_by_name($values['name']))) {
      $data = entity_property_values_create_entity($args['type'], $values);
    } else {
            $data = entity_metadata_wrapper('user', $account);
    }
    return array('entity_created' => $data);
    }
catch (EntityMetadataWrapperException $e) {
    throw new RulesEvaluationException('Unable to create entity @type": ' . $e->getMessage(), array('@type' => $args['type']), $element);
}
</code>
Comment: If I am not wrong, that is for entity type, I mean entity, in my question entity_type is Fruit_Store, bundle is store, entity is Victory. I wouldn't let the user create Victory entity again, not entity_type. I just want to validate entity that is already created. Thanks
Comment: @SAWAUNG: check updated answer

How to check entity is already created?


Don't understand this guitar tablature notation

Question:
How do I play the slide at the 1st string? Usually in slides, one slides from one fret to another, but I'm not quite sure as to the meaning of the notation given in the picture. How do I play it? Should I play the open 1st string only then slide to the 8th fret?
Help?!!
Comment: If not stated from where to slide from, I use my own descression from where to slide from, related to the song you are playing. I tend to slide from as far down as possible from a note that fits into key of the song, or from a note that sounds good. No use sliding from the lowest note on the neck (ie 0) if it does not fit into the progression or key or just plainly sounding bad
Answer: Slide from any fret lower than 8. It depends on the speed of the piece, and as xero says, what's played directly previous. Just get to target note in time, but unless there's 'proper' music written, it's hard to say exactly when that time is! One or two fret slide is o.k.
As an aside - the x on the tab indicates a harmonic - see my re-edit to your other question. What sort of harmonic, though, seems to be a secret only the writer knows! I suspect it could even be a tapped harmonic, where the string is tapped sharply on the node.
Comment: Isn't an X on on a tab a (dead note)[https://www.youtube.com/watch?v=vfbQ9HdDg9Q]? Where you  stop the string from vibrating in no particular place?
Comment: @xerotolerant - generally speaking true. However, looking at Code's other question, it occurred to me that perhaps these were used differently. Taking that as read, the tab/stave in that question tally.
Answer: Well you probably can't reasonably slide up 8 frets. Just slide from the fret below. Also I  can't  see what is  in the bar before. If it is a 7 then you have your answer. Also you can listen to a recording to know for sure.
I would  slide from the fret below.
Answer: Basically this means you can slide up from any fret up to the eighth. It's not strictly important where it starts from, as long as it ends on the correct fret, so that it stays in tune with the song.
You can be very expressive when you come across a note like this, as it's entirely up to you to determine the pitch of the slide, and the speed of the slide (so long as you stay in tempo).


How to pass a table name as variable to a stored procedure

Question: I have inherited a bunch of stored procedures basically as a shell and inside the quotes is this huge dynamic SQL with lots of conditions, calculations and case statements, however the table name in the FROM clause within this dynamic SQL changes every quarter.
Now before I get flamed, I like to simply say that I inherited them, how it was designed was before me. So each quarter when a call is made out to these stored procedures, it comes with the actual table name passed as a parameter and then the dynamic SQL concatenates the table name.
The problem with this approach is that, with each run over time, the prior designers simply tacked on more criteria as conditions and calculations. But the dynamic SQL string has a length limit to it. Further it becomes quite difficult to maintain and debug.
CREATE PROCEDURE .....
    @dynSQL1 = 'SELECT......
            FROM' + strTblName + '
            WHERE.....
            GROUP BY....'
     ...
     EXEC @dynSQL1
 GO

However, I like to ask you all, is there a way to turn this stored procedure with this huge dynamic SQL string into a plain vanilla stored procedure based on a parameterized table name?
My main goal is two fold, one, get away from the long string as dynamic SQL and two, easier maintenance and debugging. I would like to think in the more current version of SQL Server from SQL Server 2016/2017 and on, this issue is addressed.
Your thoughts and suggestions is greatly appreciated.
~G
Comment: You cannot parametrise an object, it has to be a literal. This means you have to use dynamic SQL and **safely** inject the value (the above does not). Then you need to use `sys.sp_executesql` to execute and pass the parameters for any other variables to it. Have a look at [Dos and Don'ts of Dynamic SQL](https://www.sqlservercentral.com/articles/dos-and-donts-of-dynamic-sql) where I cover a lot of considerations you need to take.
Comment: @Tomasito  Table and index partitioning is available in every edition of SQL Server 2016 SP1 and later, including Azure SQL Database.
Comment: Perhaps you could use a synonym for the table and simply change the synonym every quarter? But it sounds like there is far more complicated logic for generating the correct query than simply swapping table names - so maybe your efforts are better spent elsewhere.
Comment: On 64-bit servers, the size of the dynamic SQL string is limited to 2 GB, the maximum size of nvarchar(max), so I wouldn't about that.
Comment: It's not any different on 32bit instances, @Piotr, it's still 2GB, or 1Billion~ characters.
Comment: Guys, I just did a little more research and I came across this:

https://codingsight.com/passing-data-table-as-parameter-to-stored-procedures/

curious to know if that would work, it seem it would...Your thoughts?  It's just so wonky that with one missing quote, things just blows in dynamic sql.
Comment: @Larnu, you said it man, "...a pain to debug if written poorly..."  It's like following behind a herd and you don't know what you will step on next.
Comment: *"t's just so wonky that with one missing quote, things just blows in dynamic sql."* That isn't just the case with dynamic SQL. `SELECT CONCAT('a, MT.MyColumn) FROM MyTable MT;` will fail too.
Comment: Which is why it's so important you write Dynamic SQL well as well. Formatting is just as important in a dynamic statement as it is in a non-dynamic one. I go on (in that article) to say *"One common reason I hear for why people don't use dynamic SQL is because it's difficult to troubleshoot. I personally find this a little untrue. Poorly written and/or formatted dynamic SQL is difficult to troubleshoot, but then the same is true for poorly written SQL in general."*.
Comment: Switching table name looks like some kind of https://www.brentozar.com/sql/table-partitioning-resources. Keep in mind it's enterprise feature. You could consider poor's man partitioning (search that fraze), whitch maybe someone was trying before you.
Answer:
So each quarter when a call is made out to these stored procedures, it comes with the actual table name passed as a parameter and then the dynamic SQL concatenates the table name.

You could change the procedure to codegen other stored procedures instead of running dynamic SQL.  EG:
CREATE PROCEDURE admin.RegenerateProcedures @tableName
as
begin

    declare @ddl nvarchar(max) = '
create or alter procedure dbo.SomeProc
as
begin
           SELECT......
            FROM dbo.' + quotename(@tableName) +  '
            WHERE.....
            GROUP BY....
end
'
     EXEC ( @ddl )
. . .
end
 GO

Comment: `EXEC (@DDL)` isn't a great idea. It promotes not parametrising the dynamic statement.
Comment: SQL Server doesn't support parameters in DDL.
Comment: That isn't what I said... I said that use of `EXEC(@SQL)` or(`EXEC(@DDL)`, `EXEC(@SomeVariableCotntainingSQL)`) promotes not parametrising the dynamic statement. Use `sys.sp_executesql`.


Page Navigation issue after executing a jQuery

Question: Using JSinjector, i included a jQuery and made use of a function. I wrote a query inorder to display the external link within a certain div section (within our site). My code goes here
<code> (function ($) {
       Drupal.behaviors.YOURTHEMENAME = {
              attach: function(context, settings) {
              $('.div-classname a').click(function(){
              var url = $(this).attr('href');
              var height = $('#div-id-name').height();
              var width = $('#div-id-name').width();
              $('#div-id-name').replaceWith( "'<object data="+url+" width="+width+" height="+height+"/>'" );
               return false;
             });
           }
         };
         })(jQuery);
</code>
In concise, the above query does the functionality - " whatever the hyperlinks within the div class (div-classname) when clicked the corresponding website opens within the div with id (as div-id-name). Previously, div-id-name region has a content but when the hyperlink is clicked, jquery executes now the content (within the div-id-name) is replaced with the corresponding site.
Everything goes well the query works..
But my problem here is after the content is replaced with the corresponding link, now when i press the back button - rather than loading the previous page or the website's home page it redirects to the browser's home page (i.e., either google.com or whatever).
What might be the problem? Is there any thing link configuration issues? or do I need to include any code (query)..
I m using Drupal 7
Answer: Disable the click function for the more links div.
<code>$('.div-classname a').on('click',function(){.....});

$('.more-link a').off('click');
</code>
This is the perfect solution.


Inverse covariance matrix, off-diagonal entries

Question: Let $\Sigma$ be a covariance matrix. According to the material in this link,

If the elements of $\Sigma$ are all positive, most of the off-diagonal elements in $\Sigma^{-1}$ will be negative.

This is actually written about the correlation matrix, but the principle should be the same.
What does "most" here mean? Is there a common condition that would make all the off-diagonal elements negative?
Comment: If $\Sigma$ were a 2x2 matrix, in which the off-diagonal element was positive, [all] the off-diagonal element of the inverse would be negative.
Comment: **The link is incorrect.** For instance, the $n\times n$ [Cartan matrix](https://en.wikipedia.org/wiki/Cartan_matrix) $A_{n-1}$ is the inverse of a symmetric positive-definite (spd) matrix with all positive entries. Because the eigenvalues are continuous functions of the entries, a sufficiently small perturbation of $A_{n-1}$ created by changing all its zeros to a positive number $\epsilon$ yields a matrix with only $2n-2$ negative entries, $n^2-3n+2\gg 2n-2$ positive off-diagonal entries, and it will be the inverse of an spd matrix with all positive entries.
Comment: @gung This is true but the $2x2$ case doesn't generalize well to larger dimension. I am more interested in $3x3$ and larger
Comment: What you ask for seems to be a necessary condition for the creation of a [Stieltjes matrix](https://en.wikipedia.org/wiki/Stieltjes_matrix). I do not know a "common condition" of the top of my head but check the following point made [here](https://en.wikipedia.org/wiki/Partial_correlation#Using_matrix_inversion) about partial correlations and how they link to the elements of the precision matrix $\Sigma^{-1}$; it will be easier to convince yourself about what takes place if you assign a meaningful interpretation to the elements of the precision matrix $\Sigma^{-1}$.
Answer: The underlying intuition is quite general: because multiplying a matrix by its inverse has to produce a matrix with a lot of zeros, if the original matrix contains only positive values then obviously the inverse has to contain some negative values in order to produce those zeros.  But the intuition goes wrong in making the leap from "some" to "most."  The problem is that only one negative coefficient is needed in each row to make this happen.
As a counterexample, consider the family of $n\times n$ matrices $X_{n,\epsilon} = A_{n-1} + \epsilon 1_{n}^\prime 1_{n}$ for $\epsilon \gt 0$ and positive integers $n$ where
$$A_{n-1} = \pmatrix{
 2 & -1 & 0  & 0  & 0 & 0 & 0 & \cdots & 0 \\
-1 & 2  & -1 & 0  & 0  & 0 & 0 & \cdots & 0 \\
 0 & -1 & 2  & -1 & 0  & 0 & 0 & \cdots & 0 \\
&&&&\ddots&&&&\\
0 & \cdots & 0 & 0 & 0 &  -1 & 2 & -1 & 0 \\
0 & \cdots & 0 & 0 & 0 & 0 & -1 & 2 & -1 \\
0 & \cdots & 0 & 0 & 0 & 0 &  0 & -1 & 2}
$$
and
$$1_{n} = (1,1,\ldots, 1)$$
has $n$ coefficients.  Notice that when $0\lt\epsilon\lt 1,$ $X_{n,\epsilon}$ has only $2(n-1)$ negative coefficients (namely, $-1+\epsilon$) and the remaining $n^2 - 2n + 2 = (n-1)^2 + 1$ of them (namely, $2+\epsilon$ and $\epsilon$) are strictly positive.
I chose these matrices $A_{n-1}$ because (1) they are (obviously) symmetric; (2) they are positive-definite (this is not so obvious, but it's an easy consequence of the theory of Lie Algebras in which they naturally arise); and (3) they have simple inverses with positive coefficients,
$$A_{n-1}^{-1} = \left(b_{ij}\right);\quad b_{ij} = \frac{\min(n+1-i,n+1-j)\min(i,j)}{n+1}.$$
For instance,
$$A_{3-1}^{-1} = \frac{1}{4}\pmatrix{3&2&1 \\ 2 & 4&2\\1&2&3}.$$
This is easy to prove simply by multiplying the two pairs of matrices and computing that the result is the $n\times n$ identity matrix.
The Sherman-Morrison formula asserts
$$X_{n,\epsilon}^{-1} = A_{n-1}^{-1} - \color{gray}{\frac{\epsilon}{1 + \epsilon\, 1_{n} A_{n-1}^{-1} 1_{n}} \left(A_{n-1}^{-1} 1_{n}^\prime 1_{n} A_{n-1}^{-1}\right)} = A_{n-1}^{-1} + \color{gray}{O(\epsilon)}.\tag{*}$$
Because the smallest entry in $A_{n-1}^{-1}$ is $1/(n+1),$ we can easily find  $0\lt \epsilon \lt 1$ that are also small enough to make all the entries in the subtracted (gray) part of $(*)$ less than $1/(n+1),$ which leaves all the entries of $X_{n}^{-1}$ positive.  (For instance, $0 \lt \epsilon\lt 1/(2n^3)$ will serve.)
Obviously $X_{n,\epsilon}^{-1}$ is symmetric.  For sufficiently small positive $\epsilon$ its eigenvalues must be close to those of $A_{n-1}^{-1},$ all of which are positive (because $A_{n-1}$ itself is positive definite), which makes all such $X_{n,\epsilon}^{-1}$ legitimate covariance matrices.
We may conclude

For all $n\ge 1$ and (for each $n$) sufficiently small $\epsilon\gt 0,$ the matrix $X_{n,\epsilon}^{-1}$ is a covariance matrix with strictly positive entries and its inverse $X_{n,\epsilon}$ has $(n-1)^2 + 1$ strictly positive entries, too.

Thus, as $n$ grows large, the proportion of its positive entries becomes arbitrarily close to $1,$ because
$$\frac{(n-1)^2 + 1}{n^2} \gt \left(1-\frac{1}{n}\right)^2 \to 1.$$


What does asymptotic efficiency mean?

Question: I read some comparison articles, and always find "asymptotic efficiency," "asymptotically less efficient," and "asymptotically normal."
I am really confused about the meaning of these words. What is the difference between "asymptotically efficient" and "asymptotic normal distribution?"  I searched many website but still can not get the idea in an easy way, say with an example. Also, when I can say that the estimator is "asymptotically efficient?"
Answer: Asymptotic efficiency is both simpler and more complicated than finite sample efficiency. The simplest statement of it is probably the Convolution Theorem, which says that (under some assumptions, which we'll get back to) any estimator $\hat\theta_n$ of a parameter $\theta$ based on a sample of size $n$ can be written as $$\sqrt{n}(\hat\theta_n-\theta)\stackrel{p}{\to}Z+\Delta$$
where $Z\sim N(0,I^{-1})$ has variance equal to the inverse Fisher information per observation and $\Delta$ is pure noise independent of $Z$.  The distribution $Z$ is the best possible limiting distribution of an estimator. If $\Delta$ is zero, so that $\sqrt{n}\hat\theta_n-\theta)\stackrel{p}{\to}Z$, we say $\hat\theta_n$ is asymptotically efficient.
The variance bound is the same as the Cramer-Rao one, so if $\hat\theta_n$ is unbiased and efficient in the finite-sample sense for every $n$ it will be asymptotically efficient. Asymptotic efficiency is a much broader concept, though: it allows for estimators to be biased as long as the limiting asymptotic distribution is unbiased.  For example, maximum likelihood estimators are asymptotically efficient under fairly weak assumptions, but they are only finite-sample efficient for a few specially nice models.
There are some tricky issues with asymptotic efficiency. It's possible for an estimator to beat the Convolution Theorem at a single point or even on a dense set of measure zero. That's why the Convolution Theorem needs assumptions: it's true for regular estimators (which don't have special weird points) and it's true almost everywhere in $\theta$ for arbitrary estimators, and there's a stronger result called the Local Asymptotic Minimax theorem that really nails down all the loopholes. Aad van der Vaart's Asymptotic Statistics has nice coverage of these details.
Answer: It has something to do with Cramer - Rao inequality. For most familiar distributions you know, the variance of any unbiased estimator (which coincides with mean-squared error) is at least as high as the inverse of the Fisher information, a fixed, deterministic quantity but unknown as it is a function of unknown parameters. It is the lower bound for variance of an unbiased estimator for specific parameter(s).
An estimator is efficient implies that it achieves such efficiency by providing an unbiased estimator with lowest possible variance. It also implies that it is the best unbiased estimator.
So what is "asymptotic behavior" of an estimator? It is just how "properties" of the statistics change as the sample size approaches infinity. For example, consider the biased sample variance $S^2$ as an estimator of a continuous distribution. The bias is $\frac{\sigma^2}{n}$. As $n$ approaches infinity, the bias approaches 0. It is an asymptotic behavior of this estimator.
Similarly, an estimator may not be the best unbiased one at a fixed sample size n, but as n approaches infinity, the variance of that estimator approaches the Cramer - Rao lower bound. That is what we call it an "asymptotically efficient" estimator.
Comment: It is something else @Alice. We call it consistency. Efficiency means you do something as efficient as possible given what you have. So an unbiased estimator is efficient if and only if its variance is equal to "inverse of Fisher information at size n", the lowest theoretical variance of an unbiased estimator given that sample size. "Assymtotically efficient" means as n approaches infinity, the unbiased estimator will become an efficient one if it is not efficient when n is fixed to a particular positive integer ; or it will remain to be an efficient one if it is already efficient at any n.
Comment: Thanks a lot for helping me. So, can I said that "Asymptotic efficiency" is that the estimator still provides efficient result as the sample size goes to infinity. By efficiency  I mena small difference between the estimated value and the ture value.
Comment: Amazing clarification. Thank you so much.

What does asymptotic efficiency mean?


Cajon Sound Help

Question: I play a cajon in a band with a few guys.  Some gigs are in a pub and some are outdoors and it can be difficult to be heard.  Any suggestions on what type of sound equipment to buy so that it could be easily heard?  An amp or a PA?
Comment: They have these nifty little tape-on mics that can be awesome. Even just a regular mic on a stand pointed at the hole will do the trick. That's what my other low-cost gigs have done. I suggest: basic amp, basic mic, keep it simple. But I don't really know that much about sound equipment.
Comment: Depending on the music and your taste it might be completely wrong, but if you're using the cajon as a drumset substitute rather than as a desired instrument in and of itself, maybe consider a cocktail drumkit? You'll save yourself the hassle of sound equipment and gain a lot of expressive potential. Obviously, this isn't applicable to music that specifically asks for a cajon.
Answer: Last time I saw a cajon live the player brought his own Shure Beta 91A.. It's a flat box-shaped kick mic that fits perfectly inside a cajon, it sounded great but it's not the cheapest option. It probably helped that he stressed to the soundie that he wanted the bass frequencies exaggerated.
I have a cajon at home and when I record it I use my beta 56a right in the sound hole and get pretty good results. Definitely look at mics designed for kicks or toms.
Answer: I play cajon in an acoustic band. In order to make it sound like a drum kit, I incorporate a a Meinl Luis Conte shaker strapped to my ankle (as my hi-hat), as well as 2 thin 12" crash cymbals, a mounted tambourine and a mounted vibra-slap.  I use an Audix ADX60 barrier mic inside the cajon, sitting on a foam cushion, that also helps eliminate unwanted ring, and 2 Sennheiser 835 mics aimed at the shaker and what's on the cymbal stand. I have my own rig I use for the cajon,   I have an Alto ZMX122FX mixer, which I run through an Alto TS315S sub woofer and a TS110 powered 2 way speaker.  In most of the places we play, my stage rig fills the room. I also run a line out of my percussion mixer into the main PA, depending on the size of the venue. For those not wanting to lug around a small PA for just the cajon, instead of a bass or keyboard amp, I would recommend a 2 way powered PA speaker with a small mixer. The Audix ADX60 is an awesome mic for the cajon. It pics up all the highs and lows, but it needs to be run through a mixer with phantom power, or it won't work.
Comment: But drums are acoustic anyway! And lugging that lot round isn't much different from a drum kit - often, we play with just kick, snare, hi-hat and a couple of cymbals - not miced, Don't really see an advantage.
Comment: This does not really answer the question. If you have a different question, you can ask it by clicking [Ask Question](https://music.stackexchange.com/questions/ask). To get notified when this question gets new answers, you can [follow this question](https://meta.stackexchange.com/q/345661). Once you have enough [reputation](https://music.stackexchange.com/help/whats-reputation), you can also [add a bounty](https://music.stackexchange.com/help/privileges/set-bounties) to draw more attention to this question. - [From Review](/review/late-answers/75910)
Answer: I've always used a Sure Sm57 with the tip of the mic just inside the sound hole.
It doesn't cause feedback and picks up the nuances pretty well. I also play with brushes on some songs and it picks that up too.
The mic is then put straight through the PA and sounds great.
I'm thinking of trying a Bass amp to have more control over my sound levels as often I can't hear myself well if it's a loud gig and the pa speakers are forward.
Answer: Piezo clip on pickup maybe. I've heard they can be used on almost any instrument and they are really cheap.
Answer: A very practical way to mic a cajón is with a boundary microphone. You don't need any mic stand, gooseneck support etc., just put the mic in the box and you're set!
For amplification, a PA is definitely the best thing; certainly if it's also used for other instruments or vocals. If there's no PA, the next best option I'd consider would be to use a bass amp. Acoustic bass amps often have some kind of extra input, and even in a normal electric-bass amps it is possible to achieve this with a small mixing console (best used in the effects loop).
Only if there is no bass amp would I consider it worthwhile to use a dedicated amp for the cajón alone. Make sure it is a universal-purpose / acoustic-guitar amp, electric guitar amps are very badly suited for percussion. AER, Schertler and Fishman are three brands you should check out. Alternatively, a single general-purpose fullrange PA box will also do the trick, though you'll probably need an extra mic preamp (or small mixing console) then.
Answer: I have used a regular SM58 connected to the mic input on a Roland AC60. AC30 should work fine too.
Answer: When I have to, I usually mic it with a kick mic near the hole and an sm57 on the front, to have a mic for the very low sounds and another for the rest. I really think this combination can't fail.
Hope this helps!

Cajon Sound Help


"User removed" reputation change

Question: I saw in my reputation report a line saying -8 points and the comment is "User was removed" without any link. What does that mean?

I assume that some user was deleted. But in this case shouldn't the value be -5 or -10 or -15 or something like that?
Answer: Good point. I would never notice this fact.
My option the user could down-vote some of your answers which will decrease you score and then when the user was removed increased it again.

"User removed" reputation change


Forecasting average values with varying number of observations

Question: Every day $t$ we observe several (independent) realizations of a variable $X_t$. This variable is the sum of a time dependent mean value and white noise:
$$X_t=\mu_t+\epsilon_t$$
You can assume $\epsilon_t$ has a fixed variance over time, is Gaussian and independent of everything. The underlying time series $\mu_t$ could be forecasted with usual time-series methods.
But $\mu_t$ is not directly observable. Instead we observe:

$a_t$ the average observed value for $X_t$ over day $t$
$n_t$ the number of observations for this day

The number $n_t$ can vary very much. The goal is not to forecast it but to take it into account to forecast $\mu_t$. Typically, when $n_t$ is small, we observe a noisy average. When $n_t$ is big, $a_t$ is very close to $\mu_t$ (the standard deviation of $a_t-\mu_t$ is $\frac{\sigma}{\sqrt n_t}$)
Do you know/think of a way to take $n_t$ into account when using forecasting methods? (Possibly very simple ones: assuming $\mu_t$ is just a random walk)
Comment: Kalman filters might fit what you want, since they are intended to track a hidden variable with noisy measures. Your measures just get more noisy when sample size is small, but Kalman filters take that in account. Furthermore, since you know Et, you know how noisy is your measure, and that should ease your task.
Comment: Many thanks. It was what I was looking for. I posted my answer after understand all this.
Answer: The idea is to use the Kalman filter. An easy to read (but quite complete) introduction is available here: How a Kalman filter works, in pictures. It is essentially Gaussian Bayesian inference.
Assume $\mu_t$ is just a random walk with Gaussian step of known variance $1$. I explain how to implement the Kalman filter in this simple case.
At each time $t$ the filter saves its knowledge about $\mu_t$ as a Gaussian distribution for  $\mu_t$ with mean $m$ and variance $s^2$. When you move forward into the future, you loose information because $\mu_t$ varies randomly with variance $1$. The filter is updated as such:
$$m\leftarrow m
\\
s^2\leftarrow s^2+1\\$$
When you observe $x$ a realization of $X_t$, the filter does a Bayesian inference resulting in:
$$m\leftarrow \frac{\frac{1}{\sigma^2}x+\frac{1}{s^2}m}{\frac{1}{\sigma^2}+\frac{1}{s^2}}
\\
s^2\leftarrow \frac{1}{\frac{1}{\sigma^2}+\frac{1}{s^2}}\\$$
You can manage $n$ observations as a single update replacing $x$ by the average value $a_t$ and $\sigma^2$ by $\sigma^2/n_t$.
In other words, when you move forward into the future, the uncertainty $s^2$ increases. After each observation the uncertainty $s^2$ decreases and the forecast $m$ is updated with weights depending on the present uncertainty and the number of observations.
Red: observations. Blue: $m$ after observations
Answer: Interesting question ! If you model the average as a function of N and find that the variance of the conditional average is related to N then this might suggest a Box-Cox value of 0 . Why don't you post data for 100 consecutive days and I will try to investigate your assertion.


Do finitely generated nilpotent groups contain torsion free subgroups of finite index?

Question: I have a question about the proof of proposition 6.9 of the paper "Rational Subgroups of Biautomatic Groups" by Gersten and Short (available here). The proposition states that a finitely presented nilpotent subgroup $H$ of a biautomatic group contains an abelian subgroups of finite index.
In the second line of the proof the authors claim that they can pass to a torsion free subgroup of $H$ of finite index and then proceed to prove the result for finitely generated, torsion free nilpotent subgroups. They do not justify why they can always find such a finite index subgroup.
I know that in finitely generated nilpotent groups the torsion subgroup $T$ is always finite and that $H/T$ is torsion free but this is not what the authors are claiming.
So my question is: if $H$ is a finitely generated nilpotent group, does there exist a subgroup $H'$ such that $H'$ is torsion free and $[H:H']<\infty$?
Comment: I have seen  Proposition 2 in page 2 of D. Segal, Polycyclic groups, CUP, Cambridge, 1983 as a reference for this result (but haven't checked it). It also follows from the fact that $T$ is finite and f.g. nilpotent groups are residually finite.
Comment: @DerekHolt thank you. I will follow up on the reference.
Answer: This is an immediate corollary of Theorem 2.1 in
G.Baumslag, "Lectures on nilpotent groups," Regional Conference Series in Mathematics, No. 2 American Mathematical Society, Providence, R.I. 1971.
Theorem (K.A.Hirsch, 1938). Every finitely generated nilpotent group embeds as a finite index subgroup in $A\times B$ where $A$ is a finite group and $B$ is a torsion-free group.
(The result you are after also follows from Corollary 1.21 in Baumslag's book: Residual finiteness of polycyclic groups, which Baumslag also attributes to Hirsch.)


How to detect sound frequency / pitch on an iPhone?

Question: I'm trying to find a way to detect sound frequency being recorded by iPhone's Microphone. I'd like to detect whether the sound frequency is going up or down.
Answer: you can try to use SCListener. It's a small open-source class and very easy to use
EDIT:
The formatter does not like the _ in the name.  Here is the link. http://github.com/stephencelis/sc_listener
Comment: Seems SC_Listener is deprecated, for iOS 3.0+, you can try to use this tutorial, which works pretty well: http://mobileorchard.com/tutorial-detecting-when-a-user-blows-into-the-mic/
Answer: To detect frequency you should check out the fast Fourier transform (FFT) algorithm.
Answer: Note that the SC_listener does not work on iPhones running iOS 3.0 or above, check in AVAudioRecorder and FFT. It somehow works in the simulator though....
Answer: For simple pitch detection, I think the FFT is good enough. Try look into Aurio Touch 2 and vDSP reference in accelerate framework.
Answer: I wrote some code with explanation for tracking pitch in C. It uses the FFT, which is not the optimal method, but you can see if this is good enough for your application. Ideally, you'd replace the FFT with something hardware accelerated.
http://blog.bjornroche.com/2012/07/frequency-detection-using-fft-aka-pitch.html
https://github.com/bejayoharen/guitartuner
Answer: Beethoven looks like a good option: https://github.com/vadymmarkov/Beethoven


Why should I prefer the standard deviation over other measures of variance?

Question: The most common kind of deviation is the standard deviation.
$$ \text{Sd}(x) = \sqrt{\text{Mean}((x - \text{Mean}(x))^2)}$$
The standard deviation is very similar to the mean absolute deviance or
$$ \text{MAD}(x) = \text{Mean}(|x - \text{Mean}(x)|)$$
but is often simpler to calculate or obeys nice algebraic properties.
But there are a lot of other measures of variance. For example, there is the most common absolute deviance from the mean value:
$ \text{Mode}(|x - \text{Mean}(x)|)$.
It is not clear to me why I should prefer the standard deviation over other kinds of measures of dispersion. I suppose the simplest answer is that this measure of dispersion is the most highly studied and well known and using other methods of dispersion will confuse people you try to communicate with.
I guess I would have to use these kind of alternative measures for pathological distributions like the Cauchy distribution though.
Comment: One reason variance is popular (and hence standard deviation) is that the variance of a sum of random variables has a very simple form (doubly so if they're independent). None of the main competitors does.
Comment: I'd agree that the questions were not phrased identically, eg the other question talked about squaring vs square rooting, but the actual answers received there were far more general than the title suggests.
Comment: This question is being asked in different forms over and over, that's my point. It's impossible to compare variance to every measure of dispersion.
Comment: Try to look for related threads. I think this question has been answered earlier, just cannot find the duplicate right now.
Comment: @Aksakal This is not a duplicate. This is not about squaring or square rooting but about the mean versus the mode and similar.
Comment: You're comparing the SD to the MAD. That is the question of whether to square or not.
Comment: @gung I'm comparing mean versus mode and similar and not square versus absolute value.
Comment: @StevenStewart-Gallus your question is poorly formulated if your last comment is true. It's not clear that you're comparing mean vs mode from the question. That's why it should be either closed or edited. The question in its current from is all about dispersion, not "central tendency"
Answer: You may come up with infinite number of dispersion measures. It's a lost cause to compare the variance to each and everyone of them.
There are two features of variance that are attractive to me. First, it's a smooth function. For instance, the mean absolute deviation is not.
Second, it's one of the central moments:
$$\mu_k=\sum_ip_i(x_i-\mu_1)^k$$
Here $\mu_2$ is a variance.
Being a moment is important, for it defines the distribution when combined with all other moments. Other measures of dispersion are stand-alone metrics.
Comment: Well you could take the moment around the mean but couldn't you just as easily take the moment around the median? The nth moment is $\int^{\infty}_{-\infty} (x-c)^n f(x) \, \mathrm{d} x$ but c does not need to be the mean at all.
Comment: @StevenStewart-Gallus, that wouldn't be a central moment. In fact non-central moment is defined as $\gamma_k=\sum_ip_ix_i^k$. So, the mean is not important here. The important part is squaring.
Comment: I don't follow. Why should I care for the central moment and not some other moment?
Comment: @StevenStewart-Gallus, a full set of moments defines the distribution, central or non-central. The central second moment has a nice interpretation as a dispersion measure. All I'm saying is that this measure of dispersion is not a stand alone, it's like a piece which completes the puzzle, unlike other measures of dispersion
Comment: but you just said that other moments work too? The moment around the median seems to have just as nice an interpretation.
Comment: @StevenStewart-Gallus, why are you stuck on the median? OP's question is about dispersion. Yes, you can build a set of moments around the median, then the dispersion would be around the median. The nice thing about the central moments is that the mean is itself a moment. So, when you talk about the mean and variance, you're talking about two moments, which are part of a full set of moment that define the distribution. If you don't see the elegance in this setup, then I guess you could prefer other measures like MAD to dispersion.
Answer: I'm surprised no one has mentioned the really essential property that Variance is additive for independent random variables:
$$\mbox{Var}(a_1X_1+\cdots+a_nX_n)=\sum_{i=1}^na_i^2\mbox{Var}(X_i),$$
and the equally nice linearity properties that covariance shares. This becomes completely intractable without the square inside the expectation in the definition of variance.
As well for Central limit theorem it is variance, and not L1 that gives rise to the CLT. Specifically L1 gives rise to the strong law of large numbers, but not the fluctuations therein.
Answer: In some sense, a related and deeper question is why do people tend to use the $L_2$ norm instead of the $L_1$ norm or indeed other norms? In the two-dimensional Euclidean vector space, why do people tend to use $\sqrt{x^2+y^2}$ (i.e. $L_2$ norm) as a measure of distance instead of $|x| + |y|$ (i.e. $L_1$ norm)?
How the $L_2$ and $L_1$ norm are related to standard deviation and mean absolute deviation respectively:
Let $x$ be a mean zero random variable and $P$ be a probability measure.
The standard deviation is simply the $L_2$ norm:
$$ \left( \int |x|^2 \;dP \right) ^\frac{1}{2} $$
And the mean absolute deviation is simply the $L_1$ norm.
$$ \left( \int |x| \; dP \right)^ \ $$
Comment: $L_1$ is not rotation invariant, while $L_2$ is.
Comment: This is not what I'm asking about. I'm asking about the mean versus the mode and similar and not square versus absolute value.


Problema ao tentar fazer uma subtração constante no Android Studio

Question: Estava querendo criar joguinho muito simples em que consiste em apertar em um botão, após isso o programa daria dois números aleatórios e a vida de cada personagem cairia conforme esse número, porém sempre que aperto o botão novamente a vida reseta e fica nesse loop infinito.
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void batalha(View view){
        //Criando variaveis e colocando valor nelas
        //Vinculação dos objetos
        TextView paladino = findViewById(R.id.txthppaladino);
        TextView quimera = findViewById(R.id.txthpquimera);
        int hppaladino, hpquimera;
        hppaladino = 200;
        hpquimera = 200;
        int danopaladino = new Random().nextInt(50);
        int danoquimera = new Random().nextInt(50);
        hppaladino = hppaladino - danoquimera;
        hpquimera = hpquimera - danopaladino;
        //Criando um AlertDialog
        AlertDialog.Builder dano = new AlertDialog.Builder(MainActivity.this);
        //Alterar titulo
        dano.setTitle("Dano");
        //Alterar mensagem
        dano.setMessage("Dano do Paladinho foi " +danopaladino+" e o Dano da Quimera foi " +danoquimera);
        //Alterar mensagem da caixa
        dano.setNeutralButton("Fechar", null);
        //Mostrando o Alert Dialog
        dano.show();
        paladino.setText("HP Paladino = " +hppaladino);
        quimera.setText("HP Quimera = " +hpquimera);
        if (hppaladino <=0 && hpquimera >=0){
            AlertDialog.Builder vitoria1 = new AlertDialog.Builder(MainActivity.this);
            //Alterar titulo
            dano.setTitle("Parabéns");
            //Alterar mensagem
            dano.setMessage("Vitória da Quimera =D");
            //Alterar mensagem da caixa
            dano.setNeutralButton("Fechar", null);
            //Mostrando o Alert Dialog
            dano.show();
        }
        if (hppaladino >= 0 && hpquimera <=0){
            AlertDialog.Builder vitoria1 = new AlertDialog.Builder(MainActivity.this);
            //Alterar titulo
            dano.setTitle("Parabéns");
            //Alterar mensagem
            dano.setMessage("Vitória do Paladino =D");
            //Alterar mensagem da caixa
            dano.setNeutralButton("Fechar", null);
            //Mostrando o Alert Dialog
            dano.show();
        }
        if (hppaladino <= 0 && hpquimera <= 0){
            AlertDialog.Builder vitoria1 = new AlertDialog.Builder(MainActivity.this);
            //Alterar titulo
            dano.setTitle("Triste");
            //Alterar mensagem
            dano.setMessage("Ocorreu um empate ;-;");
            //Alterar mensagem da caixa
            dano.setNeutralButton("Fechar", null);
            //Mostrando o Alert Dialog
            dano.show();
        }

    }

Answer: Você não precisa inicializa os TextViews sempre na ação do botão, tanto eles como hppaladino e hpquimera dentro do onCreate. Do jeito que você está fazendo sempre que clica no botão os valores hppaladino e hpquimera sempre são 200.
Então ficaria algo assim:
public class MainActivity extends AppCompatActivity {
    //Declara as suas variáveis principais
    private TextView paladino, quimera;
    private int hppaladino, hpquimera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Inicializando variáveis
        paladino = findViewById(R.id.txthppaladino);
        quimera = findViewById(R.id.txthpquimera);
        hppaladino = 200;
        hpquimera = 200;
    }

    public void batalha(View view) {
        int danopaladino = new Random().nextInt(50);
        // restante do seu código igual...
    }
}


Understanding the proof a metrizable connected space has uncountable elements if $|X|\geqslant 2$

Question:
Exercise: Using the fact $d$ is a metric hence continuous. Prove that if a metrizable space $(X,\tau)$ is connected and $X$ has at least 2 points, then $X$ has uncountable number of points.

I found the following answer on Mathstackexchange by Mariano Suárez-Álvarez

Let your points be $a$ and $b$.
Let $\lambda\in(0,1)$ Suppose there is no point $x$ in your space such that $d(a,x)=\lambda d(a,b)$. Then the sets $\{z:d(a,z)<\lambda d(a,b)\}$ and $\{z:d(a,z)>\lambda d(a,b)\}$ are two non-empty open sets which partition the space.
Since we are assuming connectedness, this is impossible.
Therefore, the image of the function $d(a,\mathord\cdot):X\to\mathbb R$ contains the interval $(0,d(a,b))$, and this can only happen if $X$ is uncountable.

Questions:
1) Why does the author uses $\lambda$? If instead the author used $d(a,b)$ and all other points were diferent from $b$ the distance would still be different, allowing the disjoint partition of the space.
2)
I know the metric is continuous function into $\mathbb{R}$. How does the author deduces that the image contains $(0,d(a,b))$? How does that relate to the previous argument of the partition?
Thanks in advance!
Comment: I don't understand your questions.  The writer's $\lambda$ argument appears to make sense, no?  It's possible, of course, that you have an alternate argument, though I don't understand what you wrote.  That wouldn't invalidate the given argument though.  And I can't follow question $2$ at all.
Comment: The argument appears to be entirely straight forward.  If $0<r<d(a,b)$ then let $\lambda = \frac r{d(a,b)}$.  We note that $0<\lambda <1$ so we can apply the writer's argument to deduce the existence of $x$ such that $d(a,x)=\lambda \times d(a,b)=r$.
Comment: @lulu Thanks for reading! On point 1) I am writing about how would the proof work if $\lambda$ was absent. On point 2) there was a flaw I forgot to write the interval. I do not understand how the author deduces the image of $d(a,.):X\to\mathbb{R}$ contains the open interval (0,d(a,b)) on the real line. Hope I was a  clearer.
Comment: Hint: the first paragraph proves that for any $\rho \in (0, d(a, b))$, there is a point $x$ such that $d(a, x) = \rho$ (by taking $\lambda = \rho/d(a, b)$).
Comment: The author takes $r\in(0,d(a,b))$ and shows that there exists $x$ such that $d(a,x)=r$.
Comment: @lulu Why not an official answer?
Comment: What do you mean in question 1? What would the partition you re describing be?
Comment: The point of the lambda argument is precisely to show that every point in the interval $[0,d(a,b)]$ is in the image of $d$.
Comment: @RobArthan I understood your hint. But I cannot see why that would imply that I would have uncountable points in $X$ since it starts with a finite number of points. How would the increase in points impede the contradiction of $(X,\tau)$ being connected?
Comment: @lulu I know that insofar but I do not understand the mechanism. Could you explain it?
Comment: Any set which surjects onto an uncountable set must itself be uncountable.
Comment: @lulu       I know that as well. The problem is that I am not understanding how the author is proving that.
Comment: @metamorphy How does the author proves there is an $x$ such that $d(a,x)=r$?
Answer: If it helps, the idea of the argument is two parts.
1) If $f: X \to Y$ is a continuous map and $X$ is connected, then so is $f(X)$. It suffices to assume $f$ is surjective (otherwise, replace $Y$ with $f(X)$ with the subspace topology).
If $f$ is surjective, then given any pair of open sets $U_1, U_2 \subset Y$ with $U_1 \cap U_2 = \varnothing$ and $U_1 \cup U_2 = Y$, we may take the inverse image to obtain $f^{-1}(U_1)$ and $f^{-1}(U_2)$. These are nonempty if and only of the corresponding $U_i$ is nonempty; furthermore their intersection is trivial and union is all of $X$ (this does not use surjectivity). Therefore, if $U_1 \cup U_2 = Y$ is a disconnection of $Y$ (that is, neither $U_i$ is the empty set), then the same is true of $f^{-1}(U_1) \cup f^{-1}(U_2) = X$, and so if $Y$ is disconnected so is $X$, as desired.
2) If $I$ is a connected subset of the real line, if $a, b \in I$, then $[a, b] \subset I$. For if not, choose $x \in (a,b)$ not in $I$, and write $I = \left((-\infty, x) \cap I\right) \cup \left(x, \infty) \cap I\right)$ to obtain a disconnection of $I$.
Now consider the conditions map $X \to [0,\infty)$ given by $x \mapsto d(a,x)$. This has image containing both $d(a,a) = 0$ and $d(a,b) \neq 0$. So therefore the image must contain all of $[0, d(a,b)]$ and hence must be uncountable; so the domain is as well.
Mariano rolled these two points into one proof: he took the open sets $U_1$ and $U_2$ in the first step to be $(0, x)$ and $(x, d(a,b))$ if $x$ is not in the image.
Comment: I find it hard to fit your explanation to the quoted proof, which contains no instance of the assertion that the continuous image of a connected set is connected (your part (1)).
Comment: @RobArthan not explicitly, but the entire point of the proof is to show that a continuous map $f: X \to \Bbb R$ from connected $X$ which contains $a$ and $b$ indeed contains $[a, b]$. To do that you are implicitly showing that $f(X)$ is path-connected (hence connected). Of course, Mariano's proof does both in one step. This is what my last line was supposed to indicate.
Comment: I don't agree. See my answer: my proof (1) is the real essence of Mariano's proof and does not involve what you claim is the "entire point of the proof". Personally, I prefer my proof (2), which is the same as the proof you give, but I can see why the OP might be confused given a (correct, but over-complicated) mixture of the two proofs.
Comment: @RobArthan I disagree that there is any difference in the idea in the two proofs, and we will have to leave it at that.
Answer: I think your confusion arises because the proof you quote only uses continuity of the metric in a rather artificial way. Here are two proofs, the first doesn't really use the continuity and the second does. In both proofs, we assume $X$ is connected and metrizable and has at least two points, say $a \neq b$.

Let $\lambda \in (0, 1)$. I claim that $d(a, z) = \lambda d(a, b)$ for some $z = z(\lambda)\in X$, for, if not, the sets $\{z:d(a,z)<\lambda d(a,b)\}$ and $\{z:d(a,z)>\lambda d(a,b)\}$ are non-empty, open, disjoint and partition $X$, leading to a contradiction because $X$ is connected. Since there are uncountably many $\lambda \in (0, 1)$, and $d(a, b) \neq 0$ there must be uncountable many $z(\lambda) \in X$. (This is the proof you quote adapted to remove the artificial appeal to continuity of the metric.).
Consider the function $f : X \to \Bbb{R}$ defined by $f(x) = d(a, x)$. $f$ is continuous and hence the image $I = f[X]$ is a connected subspace of $\Bbb{R}$, because $X$ is connected and the continuous image of a connected set is connected. A non-empty connected subset of $\Bbb{R}$ is either a single point or an interval. As $f(a) = d(a, a) = 0$ and $f(b) = d(a, b) \neq 0$, $I$ is an interval and so contains uncountably many points. Thus the uncountable set $I$ is an image of $X$ and hence $X$ must be uncountable.
Comment: I've just written a comment on your answer disagreeing with the comment that you were writing at the same time $\ddot{\smile}$. That those two inverse images are open follows from first principles from the definition of open sets wrt a metric. I am very happy to agree to differ: the important thing is that the OP understands what's going on. Cheers!
Comment: I think that (2) is essentially just (1), because you need to prove that connected sets are intervals. The proof in (1) includes the fact that any interval which contains two points contains the entire interval. This is the proof I would use to check the stated property. Also, (1) absolutely needs continuity of the metric, otherwise there is no reason to believe that the inverse image of these open sets are open.
Comment: Ok, sure, I grant my second point :) But I think that we are just playing word games, since the definition of open set encodes continuity of the metric. And of course I agree this sort of disagreement is just for fun.
Comment: I am not sure it is entirely about word games. The statement that the metric is continuous presupposes an understanding of the product topology, whereas the problem and the proof here don't require that.
Comment: I really only meant the function $x \mapsto d(a, x)$, which is all either of us use. anyway, I'll let you spend your time on something more productive!


Passing object of derived class to base class

Question: Hi I have a derived class and I want to pass the pointer of the derived class object to the base class.
I am getting segmentation fault while running the code.
#include <iostream>
using namespace std;

class A {
    public:
    virtual void x() = 0;
    A* a;
};

class B: public A {
public:

  B(A* x) {
    a = x;
  }

 void x () {}

};

class C: public B {
    public:
    C() : B(new C) { }
};

int main() {
    C c;
    return 0;
}

Can someone help me suggest a way to achieve this or help me in fixing the code.
Comment: pretty sure you have infinite recursion, creating a `C` requires making a `new C` which requires making a `new C` ... you get the point
Comment: `C() : B(new C)` ? You do understand that `new C` creates new `C` object, that then calls `C` constructor, that then creates `new C`, that then calls `C` constructor, that then ..
Comment: I want to call base class constructor and base the object pointer of derived class
Comment: May I ask what your final application is?
Comment: why do you think you need it?
Comment: Unrelated but always put a virtual destructor in your base class
Answer: I believe you want to pass a pointer to current object. This is what this is for.
C() : B(this) { }

Comment: I am a bit new to C++. Don't I need to allocate space to  the class pointer ?
Comment: @user2033594 No you don't. `this` just points to the object `C` that you've created. But I don't see the benefit of storing it in the base class, as you simply can use `this` in the base class.


Record audio from two microphone and video from one webcam and mux using FFMPEG

Question: Iam trying to mux audio from two different microphones and video from webcam using ffmpeg in linux.
I used the following code
<code>    ffmpeg -f video4linux2 -s 320x240 -i /dev/video0 -f alsa -ac 1 -i hw:1,0 -acodec libmp3lame -ab 96k camera.mp4    </code>
it works for muxing audio from one microphone and video from one webcam
I went through forums and googled for an hour without any positive result.

So, the question is i need to mux two audio from microphones and one video from webcam and produce a video output with two audio tracks.
Thanks
Comment: Add the 2nd input and `-map u`
Comment: Thanks for the reply. Can you give me the complete syntax or any other source as reference.
Comment: Do you know the url for the 2nd mic input?
Comment: @Mulvya the url of second microphone is hw:2,0.
Comment: @shellter thanks for letting me know, i will take necessary steps to move it.
Answer: Use
<code>ffmpeg -f video4linux2 -s 320x240 -i /dev/video0 -f alsa -ac 1 -i hw:1,0 -f alsa -ac 1 -i hw:2,0 -map 0 -map 1 -map 2 -acodec libmp3lame -ab 96k camera.mp4
</code>
Comment: Where is the parameters for the two cameras? I got lost.
Comment: Sorry. *Microhones


Overfitting GBM by simultaneously adding trees and lowering learning rate?

Question: I understand that you can overfit a Gradient Boosting Machine (GBM) by using too many trees (unlike random forest), and also that you can overfit a GBM by using too high of a learning rate. My question is, if I simultaneously lower the learning rate and increase the number of trees in an inversely proportionate manner, could I expect to change the amount of overfitting in a predictable way? More precisely, could I expect this to decrease the extent of overfitting?
Comment: A more straightforward and direct way to control overfitting is to adjust *minimal score improvement* in early stopping (eg `min_delta` in [LightGBM sklearn API](https://lightgbm.readthedocs.io/en/stable/pythonapi/lightgbm.early_stopping.html#lightgbm.early_stopping)). Learning-rate/number-of-trees scheme seems more complicated because the exact proportion is unclear until you run enough experiments, and it would certainly depend on the other hyperparams like tree depth.
Answer: Just to note, a very large learning rate can result in underfitting too.
Returning to your main question: "yes". Lowering the learning rate while increasing the number of trees will likely result in decreasing the extent of overfitting, but that is not a given and it will be likely a dataset dependant phenomenon. In general, the decreased learning rate can potentially reduce overfitting, while the increased number of trees can compensate for the more conservative updates, by capturing more complex patterns (i.e. we explore our function space taking more, but smaller, steps). To be clear, though: The best approach depends on our specific dataset, using some a GBM implementation with in-build cross-validation for early stopping (e.g. LightGBM) is probably our best bet to get the balance between the two hyperparameters.


Do we need a liberalism tag

Question: I just saw we have a liberalism tag.
https://economics.stackexchange.com/questions/tagged/liberalism
Do we really need this? It does not seem to be on-topic for the site.
If we agree that we don't need it, can someone with mod priviliges delete it?
Answer: We should remove the tag, it is about politics, not economics.
Comment: We don't have a lot of questions with the tag and it though it could be useful descriptively, it might encourage a lot of questions out of the scope of the site. I have no problem getting rid of it.
Comment: @KitsuneCavalry I have just realized that [one of the tagged questions](https://economics.stackexchange.com/questions/12344/sens-liberal-paradox) is from you. Always the troublemaker :) I'll wait a few more days before accepting the most upvoted answer.
Comment: It was from my more frivolous years I suppose xd if you don't like it fight me! But yeah in theory it can be a good tag but in practice it hasnt really gotten much use. We'll see what some of the others say.
Comment: And also "liberal" in politics means something different in the UK than in the US: see [here](https://www.reddit.com/r/explainlikeimfive/comments/32qbkt/eli5_the_difference_between_american_liberal_and/).
Answer: We should remove the tag because
1) The word "liberal", "liberalism" may indeed be used in economic contexts, but alone and on its own, it is mostly perceived as describing something in politics rather than in economics.
2) Even if one argues that the users here will "read" the tag in an economic context, the problem then is to clearly define "liberalism" from an economic point of view. (is it, say, "laissez passer laissez faire"? If yes the latter is our own tag. Is it something else?)
3) Even if we want the tag as a political tag because "economics in real life is intertwined with politics", as a political label also liberalism is too liberal a label, it definitely defies a world-wide definition (as most political labels do).
Answer: We should keep the tag, it is sometimes necessary to intertwine political and economic philosophies.
Comment: I upvoted to keep it, not because I'm a fan of liberalism, but because I agree that it sometimes impossible to separate economics from politics. Especially when it comes to policy recommendations or political economy the two often go together, no matter how positivist  & neutral we try to be.
Answer: This is actually a relevant tag for economics. Irrespective of the way the tag has been applied to any question, the fact remains that liberalism is an economic context. That fact that it is used usually in a political context (perhaps social liberalism(??) at least in USA as far as I know) that inverts its true (original) meaning in economics, does not mean that liberalism gets removed from the domain of economics.
Perhaps, it would be correct, if questions where liberalism is used as a tag to refer to/imply the (current) political use of the term are edited so that the tag is not used incorrectly (in the economic sense).

Do we need a liberalism tag


Create two-way connection between pages in Selenium Java

Question: I wonder if there is possibility to create two-way connection between pages. I want to write tests which references to method in both a specific pages and the common class at any time.
Sample diagram:
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: You can Inherit the common page Class in Internal employee class, External employee class such that you can Access methods of common class aka (base Class) in children classes


How to normalise outputs of neural networks with different distribution?

Question: I have a NN model that predicts 8 different variables. I use a multi-task learning approach, where I compute the loss between predictions and targets for each of the 8 variables, and then I add all the 8 losses together. The sum of the losses is then minimised using gradient descent.
The output variables all have different physical units and ranges. Therefore, I want to normalise the data first before computing the loss. But the problem is, some of the variables are highly skewed, while some are normally (or close to it) distributed.
I need to make sure that all outputs are normalised so that they have values between specific range (e.g. 0 and 1). Because, the original output values for some variables are between 0 and 1, and for some it can be as high as 2000, and for some it can be 50-100.
My question is, should I use the same normalisation algorithm or can I use different normalisation algorithms for different outputs? Which algorithms are recommended for extremely left skewed data?
Comment: If the only reason for normalization is to create a comparable scale (unit interval) then the skew of the distribution is unimportant.
Answer: Note that you are solving a multi-objective optimization problem. If you scalarize your 8 losses to obtain one scalar, then you are selecting one specific pareto optimum from the set of Pareto optimal points. https://en.m.wikipedia.org/wiki/Multi-objective_optimization
Wikipedia has an example showing that scalarization may not be able to recover all possible Pareto optimal points of the Pareto front if it is non-convex.
This paper suggests some weights which can be chosen for constructing the final objective function = fitness function https://www.tandfonline.com/doi/full/10.1080/23311916.2018.1502242
This paper suggests some other scalarization https://www.sciencedirect.com/science/article/abs/pii/S0020025518307370 which they claim is better when you have more than 3 single objectives.
My take is that there are a lot possible scalarization functions (where normalization may or may not be the first step). In my mind, finding a suitable scalarization comes down do defining the trade-off you are willing to accept. Maybe you can search for more information with the ideas provided here or make your trade-offs more explicit (the needed normalizations will follow from there).
Now a bit more hands-on ideas:
For your multi-task learning approach with losses having different physical units and ranges, it's common to use separate normalization schemes for each losses. You can tailor the normalization to the characteristics of each loss value. For highly skewed values, you might consider using techniques like log transformation or robust scaling to address the skewness and outliers effectively. For normally distributed loss values, standard normalization methods like Min-Max scaling or z-score normalization should work well. Adjust the normalization strategy based on the characteristics of each loss variable to ensure appropriate scaling for all losses.