Call an activity method from a fragment

Question: Trying to call a method in my activity from a fragment. I want the fragment to give the method data and to get the data when the method return. I want to achieve similar to call on a static method, but without the use of static because it create problems in the activity.
New to fragments so I need an easy and pedagogic explanation!
Thanks!
Comment: check this if helps https://stackoverflow.com/a/73796270/13560080
Answer: From fragment to activty:
((YourActivityClassName)getActivity()).yourPublicMethod();

From activity to fragment:
FragmentManager fm = getSupportFragmentManager();

//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();

If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");

Comment: To avoid the cast problem use:

Activity act = getActivity();
if (act instanceof YourActivityClassName)
    ((YourActivityClassName) act).yourPublicMethod();
                    }
Comment: It's bad design and unsafe to cast an Activity. A Fragment is not limited to a specific Activity.
Comment: BE careful cause unexpected things happen if cast doesn't work.. :S
Comment: @Kay Not  necessarily. Fragments can be used as "fragments" of any larger activities broken apart. To create responsive UIs for instance. I rarely use the same fragment and attach it to different activity hosts.
Comment: Fragments are meant to be reused and set in any Activity. What if I have 5 activities using same Fragment? Marco's answer is the correct one and a good practice for inter-fragment and Activity-Fragment communication.
Comment: @Richard In my use case it wasn't the same. I have made a library full of fragments and I would never know which developer will be attaching them to which activity and I do need the callbacks for effective navigation. I might have exaggerated in my comment saying the correct answer, but its a good practice.
Comment: Ideally you don't want to access activity methods via casting because it couples your fragment with your activity and makes it difficult to write unit tests for your fragment with the new Roboelectrics launchFragment() test APIs  (you;ll get ClassCastExceptions) https://developer.android.com/training/basics/fragments/testing
Comment: @Richard : How can we perform opposite action, like, if we have to perform a fragment's method inside the Activity?
Comment: Could you explain the cast ((YourActivityClassName)getActivity()) and/or direct my to some documentation how this is working under the hood in Java?
Comment: what is "your tag" means? and how to set tag?
Comment: @SantoshPandey "yourTag" is just a string to identify your fragment with. Think if it as a fragment id.
Comment: hey guys I was wondering which is faster accessing an activity like this ((MainActivity) getActivity()) or getting an instance of the activity like this         MainActivity mainActivity = (MainActivity) getActivity();
Comment: This is bad practice. Refer to Marco RS's answer for better architecture.
Answer: You should probably try to decouple the fragment from the activity in case you want to use it somewhere else. You can do this by creating a interface that your activity implements.
So you would define an interface like the following:
Suppose for example you wanted to give the activity a String and have it return a Integer:
public interface MyStringListener{
    public Integer computeSomething(String myString);
}

This can be defined in the fragment or a separate file.
Then you would have your activity implement the interface.
public class MyActivity extends FragmentActivity implements MyStringListener{

  @Override
  public Integer computeSomething(String myString){
   /** Do something with the string and return your Integer instead of 0 **/
   return 0;
  }

}

Then in your fragment you would have a MyStringListener variable and you would set the listener in fragment onAttach(Activity activity) method.
public class MyFragment {

        private MyStringListener listener;

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                listener = (MyStringListener) context;
            } catch (ClassCastException castException) {
                /** The activity does not implement the listener. */
            }
        }

    }

edit(17.12.2015):onAttach(Activity activity) is deprecated, use onAttach(Context context) instead, it works as intended
The first answer definitely works but it couples your current fragment with the host activity. Its good practice to keep the fragment decoupled from the host activity in case you want to use it in another acitivity.
Comment: For anyone else looking at this, while the accepted answer obviously does work, this is the better, and safer, approach from a design perspective.
Comment: this answer is so much better in terms of code design. also it wouldn't cause crashes if the activity is casted wrong
Comment: +1 but I wouldn't use a try-catch in the onAttach. Let it fail. If the listener is optional (that is, failing is not appropriate), add a set/addListener method to the fragment.
Comment: I think it'd also be important for `MyFragment` to override `onDetach` and set the listener to null in order to avoid memory leaks.
Comment: I'm new and this is tough for me. Can someone break down what's happening in the try{}? Appreciated :)
Comment: For the opposite side communication please see:http://developer.android.com/training/basics/fragments/communicating.html. Using the fragment's interface(which is also the safe way to do fragment->activity comm as explained above) you can call a method that's in your fragment from your activity as well if you want to take an action based on your fragment->activity comm.
Comment: Fragments are meant to be reused and set in any Activity. What if I have 5 activities using same Fragment? Marco's answer is the correct one and a good practice for inter-fragment and Activity-Fragment communication
Comment: On the MyFragment.OnAttach, you do a casting to the activity. For the case that mentioned by @Kay, let's say I have 5 activities using same fragment, I think, the casting code should be changed, right?
How should the code in the OnAttach looks like in order to support multiple activities? Should I use switch-case for each activity?
Comment: If your fragment needs other Activity methods, instead of the interface you can use an abstract class which extends Activity.
Comment: I point out that ***IN SOME CASES*** again this is only ***IN SOME CASES*** it's the perfect use case for a singleton. Have your manager singleton hold the current "where to go back to" interface instance (if any).  Much as you would do in a typical game in a game engine milieu.
Comment: Just a note: it will be safer to do the call to the Activity in fragment's `onActivityCreated`, or make sure it will be after that, to avoid the Activity not being initialized yet.
Comment: @ataulm I like your comment.  I have a similar use case.  Can you post an answer that includes your recommendation to add a set/addListener method to the fragment?
Comment: @NathanielHoyt I too struggled to understand this. From my current point of knowledge, you can *cast* an object that *implements* an interface into an *interface instance* and then call the interface methods that were implemented in the object. So basically, you then call the methods on the `listener` and this executes the methods defined in the Activity.
Answer: For Kotlin developers
(activity as YourActivityClassName).methodName()

For Java developers
((YourActivityClassName) getActivity()).methodName();

Comment: When I run it. I get null value of ActivityClass, I think this is not the proper way doing this in kotlin even no error. or maybe a bug?
Comment: it gives error in kotlin if we run this code.. is there another way ?
Comment: @JakeGarbo Its proper way otherwise 12 people have not voted for it. second thing some time **getActivity()** returns null check those question on SO.
Comment: there is an important thing here. You can just call parent activity in your fragments. if you try to call other activities (non-parent activities) methods in your fragment, you may get null reference error or can't cast error.
Answer: Update after I understand more how fragments work. Each fragment belongs to a parent activity. So just use:
getActivity().whatever

From within the fragment. It is a better answer because you avoid superflous casts. If you cannot avoid the casts with this solution use the one below.
============
what you have to do is to cast to the outer activity
((MainActivity) getActivity()).Method();

creating a new instance will be confusing the android frame and it will not be able to recognize it.
see also :
https://stackoverflow.com/a/12014834/1984636
https://stackoverflow.com/a/2042829/1984636
Answer: Although i completely like Marco's Answer i think it is  fair to point out that you can also use a publish/subscribe based framework to achieve the same result for example if you go with the event bus you can do the following
fragment  :
EventBus.getDefault().post(new DoSomeActionEvent());

Activity:
 @Subscribe
onSomeActionEventRecieved(DoSomeActionEvent doSomeActionEvent){
//Do something

}

Comment: Using the singleton pattern (relying on any dependency injection library) plus making that class extend `DefaultLifecycleObserver` and attaching it to the activity to subscribe/unsubscribe it `onResume()` or `onPause()` that "event bus" can be any class you want.
Answer: Here is how I did this:
first make interface
interface NavigationInterface {
    fun closeActivity()
}

next make sure activity implements interface and overrides interface method(s)
class NotesActivity : AppCompatActivity(), NavigationInterface {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notes)
        setSupportActionBar(findViewById(R.id.toolbar))
    }

    override fun closeActivity() {
        this.finish()
    }
}

then make sure to create interface listener in fragment
private lateinit var navigationInterface: NavigationInterface

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    //establish interface communication
    activity?.let {
        instantiateNavigationInterface(it)
    }
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_notes_info, container, false)
}

private fun instantiateNavigationInterface(context: FragmentActivity) {
    navigationInterface = context as NavigationInterface
}

then you can make calls like such:
view.findViewById<Button>(R.id.button_second).setOnClickListener {
    navigationInterface.closeActivity()
}

Comment: good man @Droid Chris
Answer: Best way to call the activity method from their respective fragment
(activity as YourActivity).activtiyMethod()

use this line from your activity. For example
Suppose You have Activity A and method add() and your fragment ABC and you want to call the method add from Fragment ABC,
(activity as A).add()

Answer: In kotlin you can call activity method from fragment like below:
var mainActivity: MainActivity = activity as MainActivity
        mainActivity.showToast() //Calling show toast method of activity

Answer: Thanks @BIJAY_JHA and @Manaus. I used the Kotlin version to call my signIn() method that lives in the Activity and that I'm calling from a Fragment. I'm using Navigation Architecture in Android so the Listener interface pattern isn't in the Fragment:
 (activity as MainActivity).signIn()

Answer: For accessing a function declared in your Activity via your fragment please use an interface, as shown in the answer by marco.
For accessing a function declared in your Fragment via your activity you can use this if you don't have a tag or an id
private void setupViewPager(ViewPager viewPager) {
    //fragmentOne,fragmentTwo and fragmentThree are all global variables
    fragmentOne= new FragmentOne();
    fragmentTwo= new FragmentTwo();
    fragmentThree = new FragmentThree();

    viewPagerAdapteradapter = new ViewPagerAdapter(getSupportFragmentManager());
    viewPagerAdapteradapter.addFragment(fragmentOne, "Frag1");
    viewPagerAdapteradapter.addFragment(fragmentTwo, "Frag2");
    viewPagerAdapteradapter.addFragment(fragmentThree, "Frag3");

    //viewPager has to be instantiated when you create the activity:
    //ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
    //setupViewPager(viewPager);
    //Where R.id.pager is the id of the viewPager defined in your activity's xml page.

    viewPager.setAdapter(viewPagerAdapteradapter);

    //frag1 and frag2 are also global variables
    frag1 = (FragmentOne)viewPagerAdapteradapter.mFragmentList.get(0);
    frag2 = (FragmentTwo)viewPagerAdapteradapter.mFragmentList.get(1);;

    //You can use the variable fragmentOne or frag1 to access functions declared in FragmentOne

}

This is the ViewpagerAdapterClass
    class ViewPagerAdapter extends FragmentPagerAdapter {
    public final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

This answer is for noobs like me. Have a good day.
Answer: This is From Fragment class...
((KidsStoryDashboard)getActivity()).values(title_txt,bannerImgUrl);

This Code From Activity Class...
 public void values(String title_txts, String bannerImgUrl) {
    if (!title_txts.isEmpty()) {

//Do something to set text
    }
    imageLoader.displayImage(bannerImgUrl, htab_header_image, doption);
}

Answer: ((your_activity) getActivity).method_name()

Where your_activity is the name of your activity and method_name() is the name of the method you want to call.
Answer: I have been looking for the best way to do that since not every method we want to call is located in Fragment with same Activity Parent.
In your Fragment
public void methodExemple(View view){

        // your code here

        Toast.makeText(view.getContext(), "Clicked clicked",Toast.LENGTH_LONG).show();
    }

In your Activity
new ExempleFragment().methodExemple(context);

Answer: I have tried with all the methods shown in this thread and none worked for me, try this one. It worked for me.
((MainActivity) getContext().getApplicationContext()).Method();

Answer: For Kotlin try it out
class DataForm : Fragment() {
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        Tasks(this).getData()
    }

    fun getResponse(response: String) {
        // code
    }
}

class Tasks(private val context: Any) {
    fun getData() {

        val getContext = (context as DataForm).activity
        val getFragment = (context as DataForm)

        val responseListener = Response.Listener<String> { response ->
            getFragment.getResponse(response)
        }

        val errorListener = Response.ErrorListener { error ->
            error.printStackTrace();
        }

        val stringRequest = StringRequest(Request.Method.GET, url, responseListener, errorListener)
        Volley.newRequestQueue(getContext).add(stringRequest)
    }
}

Comment: I like this since it removes a level of knowledge that the child has of the parent. Fragments should not directly call parent methods.
Answer: ((YourActivityName)getActivity()).functionName();
Example : ((SessionActivity)getActivity()).changeFragment();
Note : class name should be in public
Answer: From fragment to activity:
((YourActivityClassName)requireActivity()).yourPublicMethod();
Answer: I think it would be a better approach to pass the activity instance on fragment initialization. I passed the instance like below:
class FragmentSignUp : Fragment() {

    private lateinit var authActivity: AuthenticateActivity

    ...

    companion object {

        fun newInstance(a: AuthenticateActivity): FragmentSignUp {
            val fragment = FragmentSignUp()
            fragment.authActivity = a
            return fragment
        }
    }
}

Now you can initialize the fragment with the activity instance passed on and also can call any public method in your activity. Like below:
val fragmentManager = supportFragmentManager
val fragment = FragmentSignUp.newInstance(this)

fragmentManager.beginTransaction().replace(R.id.authenticate_fragment, fragment, FragmentSignUp::class.java.simpleName)
            .commit()

You can now access your activity public method in your fragment; like in my case:
authactivity.goToLogInFragment()

In Java your fragment class should be:
public class FragmentSignUp extends Fragment {

    private AuthenticateActivity authActivity;

    public static FragmentSignUp newInstance(AuthenticateActivity a) {
        FragmentSignUp fragment = new FragmentSignUp();
        fragment.authActivity = a;
        return fragment;
    }
}

Note: We can also inject the activity directly into the fragment constructor. But in most cases we should avoid that since it can cause some runtime issues.
Comment: Passing data like this is not safe; since Android may recreate the Fragment using no-args constructor. And in that case; the recreated fragment will not receive the data (in this case `authActivity`).

Call an activity method from a fragment


Confusion about interpreting log likelihood (and likelihood ratio test) output

Question: I am using the nlme package in R to use mixed effects models to analyze multilevel (i.e., students nested within classrooms) data.
I am confused about interpreting the log likelihood output from these functions, and while there are other questions that address why the log is taken of the likelihood statistic and why it is negative, it is not clear how these apply to interpreting these values.
In particular, a negative log likelihood is output. Since estimation methods maximize the log likelihood, I understand a larger value indicates better fit.
Does this interpretation apply to the (negative) log likelihood output, so that a larger (i.e., closer to 0) value indicates better fit, so that if I were comparing, for example, log likelihood values of -3146.9 and -2931.41 using the anova() function, and a likelihood ratio test indicated a test statistic associated with a p-value less than .05, then the model with the log likelihood of -2931.41 demonstrates better fit?
Comment: No. we minimise the negative log likelihood.
Answer: We take the log-likelihood because each case in the dataset gets a likelihood, and the log-likelihood is the product of these likelihoods. But each of these likelihoods is less than 1, and when you multiply lots of numbers less than 1 together you tend to get really, really small numbers.
Nothing wrong with those really small numbers - except that we hit precision limits on the computers that we use. Try exponentiating your log-likelihoods of -3000 and -2000. I suspect that your computer will say that they are both zero - so the likelihood of both models is zero - and they are indistinguishable.
So instead of trying to multiply lots of values togehter, it is easier to take their logs, and add them together. So we don't get a likelihood, we get a log-likelihood, and we don't hit precision limits.
Then @PlayStarCraftOkLetsGo's answer.
Answer: We try to minimise the negative log-likelihood function, which is equivalent to maximising the log-likelihood function. The model with the lower negative log-likelihood value would be a better fit.
Comment: I think it should be smaller, as in more negative, the better model.
Comment: Lower, rather than smaller.
Comment: By smaller, we mean smaller in absolute value, not smaller as in more negative, correct?


How do I navigate namespaces in MonoTouch / Xamarin for iOS?

Question: This is an example of something that I have experienced a couple of times when working with MonoTouch:
I find a code example on the internet giving an example on how to use the NSUrl class.  I try to add it to my code in Xamarin Studio.  It is simple, except I can't find which using statement to use.  I try to google, but no examples I find include the elusive using statement I am looking for.  I find the the official Mac Developer Library NSUrl description, but it does not tell me much (or perhaps it tells me too much).
In general, how do you go about finding which using statement to use in a case like this?  Is there a Xamarin documentation of this somewhere that I just can't find?  I'm not looking for the specific namespace from the example, but how to go about finding it myself.
Answer: If it's an iOS API, it will always be
MonoTouch.<iOS Framework Name>

So if you found NSUrl, you should also be able to see that it is part of Apple's "Foundation" framework.
MonoTouch.Foundation

Of course, I would just recommend just letting the IDE figure it out for you.

Right-click (on NSUrl) -> Resolve -> "using MonoTouch.Foundation"
Comment: Argh!  I can't understand how I missed right-click and Resolve!!  Thanks! :)
Comment: Hi, Erik!  I did not recognise that I had met you before.  Well, I have been working on my app.  A simple version of it is already out (just check my bio).  Thanks for your help again!


Manually calculate the variance-covariance matrix for a fitted GLS model -- i.e., vcov(glsModel)

Question: I've been working to better understand GLS by manually fitting the parameters in R. In the example below I fit the coefs of a GLS from the nlme package in R. However, I'm trying now to calculate the standard errors on those coefs. I don't understand how the variance-covariance matrix for a fitted GLS model is calculated (i.e., vcov(glsModel) in R).
library(nlme)
set.seed(3415)
n <- 25
x <- rnorm(n = n)
B0 <- 10
B1 <- 0.5
phi <- 0.8
epsilon <- arima.sim(model = list(c(1,0,0), ar = phi),n=n, sd=0.5)
y <- B0 + B1 * x + epsilon

# Fit a gls with ar1 errors fixed to phi so I can
# compare results easily...
gls1 <- gls(y~x,correlation = corAR1(value = phi,fixed=TRUE))
coef(gls1)

############################
# Fit the GLS model
############################
# 1. Create design matrix
X <- cbind(1, x)
# equivalent to model.matrix(gls1)
# 2. Get the variance-covariance matrix of errors
V <- toeplitz(phi^(1:n-1)) * 0.5^2
# 3. Fit GLS model using matrix algebra
Sigma <- solve(V)
XtX <- t(X) %*% Sigma %*% X
Xty <- t(X) %*% Sigma %*% y
betas <- solve(XtX) %*% Xty
betas # equivalent to coef(gls1)

############################
## Get std errors
############################

# 1. Get residuals
e <- as.matrix(y-betas[1] - betas[2]*x)
e # equivalent to resid(gls1)

# 2. calc variance-cov mat for the fitted model -- aka vcov(gls1)
vcov(gls1) #??

I've tried several approaches to getting vcov(gls1) manually but I'm flailing about. Can anybody shed some light?
Answer: In an attempt to match your variable names, suppose the (conditional) error covariance matrix $\Psi = \sigma^2 \Sigma^{-1} = \sigma^2V$ in your general linear regression model is know up to a positive constant $\sigma^2$. Then, the (conditional) covariance matrix of the generalized least squares estimator $\hat\beta_{\text{GLS}}$ is given by
$$
\mathop{\mathbb{V}}\left(\hat\beta_{\text{GLS}}\,|\,X\right) = \left(X^\top \Psi^{-1} X\right)^{-1} = \sigma^2\left(X^\top \Sigma X\right)^{-1}.
$$
To obtain an unbiased estimator of $\mathop{\mathbb{V}}\left(\hat\beta_{\text{GLS}}\,|\,X\right)$ we thus need an unbiased estimator of $\sigma^2$. One such estimator$-$the one that will answer your question$-$is given by
$$
\hat\sigma^2= \frac{1}{n-k} \left(y - X\hat\beta_{\text{GLS}}\right)^\top \Sigma\left(y - X\hat\beta_{\text{GLS}}\right),
$$
where $n$ is the number of entries of $y$ and $k$ the number of entries of $\hat\beta_{\text{GLS}}$.
In your example we have
$$
\Psi
= \sigma^2 \frac{1}{1-\phi^2}
\begin{pmatrix}
1 & \phi & \cdots & \phi^{n-1} \\
\phi & 1 & & \phi^{n-2} \\
\vdots & & \ddots & \vdots \\
\phi^{n-1} & \phi^{n-2} & \cdots & 1
\end{pmatrix}
= \sigma^2 V,
$$
where $\sigma^2 = 0.5^2$ is the variance of the innovations $u_t$ in your AR(1) error term process $\varepsilon_t = \phi\varepsilon_{t-1} + u_t$, $u_t \overset{\text{i.i.d}}{\sim} \mathcal N(0, \sigma^2)$ with AR coefficient $\phi = 0.8$.
In your code this would correspond to redefining
V <- toeplitz(phi^(1:n - 1)) / (1 - phi^2)

which doesn't change betas (the realized value of $\hat\beta_{\text{GLS}}$) since any scaling factor of $V$ cancels out in the corresponding calculation.
With the new V (and thus new Sigma) you can calculate the realization of $\hat \sigma^2$ via
sigma_sq_hat <- as.numeric(1/(n-2) * t(e) %*% Sigma %*% e)

and the realized value of $\mathop{\hat{\mathbb{V}}}\left(\hat\beta_{\text{GLS}}\,|\,X\right) = \hat \sigma^2 \left(X^\top \Sigma X\right)^{-1}$, i.e. vcov(gls1), via
sigma_sq_hat * solve(XtX)

Note that, again due to cancellation, this term would be the same if calculated with your original definition of V; but sigma_sq_hat would then be scaled by a factor of $100/9$.
Comment: @user111024 I'm glad I could help.
Comment: This is incredibly helpful. Thanks for such a detailed reply. Much clearer now.


Non-zero vector equation that requires you to find a scalar

Question: I have stumbled across an exercise that goes like this:

Let vector a be a non-zero vector. Find the value of scalar $k$, given the equation: $(k+1)(k-2)a+ka=2a$

How is it done?
Answer: All the terms are some scalar multiple of $a$, so it is possible to divide $a$ out (since it is non-zero):
$$(k+1)(k-2)+k=2$$
Now you have just a simple quadratic equation to solve.
Comment: So simple, yet so helpful... thank you very much
Answer: Let $V$ be a vector space over a field $F$.
 Then, for any $\alpha \in F$ and for any $v \in V$, the following holds:
$\alpha v = \mathbf{0}$ if and only if either $\alpha = 0$ or $v = \mathbf{0}$.
Proof:

If $\alpha = 0$ or $v = \mathbf{0}$, then we have $\alpha v = \mathbf{0}$, by the axioms of a vector space. So let's conversely assume that $\alpha v = \mathbf{0}$. If $\alpha = 0$, then we are done. So let's assume that $\alpha \neq 0$. Then there exists an element $\alpha^{-1} \in F$ such that $$ \alpha \alpha^{-1} = 1 =  \alpha^{-1} \alpha. $$
  Now as we have assumed that  $\alpha v = \mathbf{0}$, so we also have
  $$\mathbf{0} = \alpha^{-1} \mathbf{0} =  \alpha^{-1} ( \alpha v) = \left( \alpha^{-1} \alpha \right) v = 1v = v. $$
  That is, $v = \mathbf{0}$.

Using the above we can also conclude that, for any  $\lambda, \mu \in F$ and for any non-zero $v \in V$, the following holds: $\lambda v = \mu v$ if and only if $\lambda = \mu$.
Proof:

We see that $\lambda v = \mu v$ if and only if $\lambda v - \mu v = \mathbf{0}$, which is the same as $(\lambda - \mu) v = \mathbf{0}$, and the last equation holds if and only if $\lambda - \mu = 0$ (because $v$ is non-zero), and this holds if and only if $\lambda = \mu$.

In what has gone so far, I've assumed that you are familiar with the definiion of a field and that of a vector space over a field.
Hope this helps.


Show a popup after saving a new node

Question: How do I create a popup which can use the node variables after saving a new node?
For example, I want to show a popup with the social media share button. Should I use node_save()?
Answer: When a node is saved, the user is normally redirected to the page showing the node, which is not a form. In that case, hook_form_alter() doesn't help. I said the user is normally redirected to the page showing the node, as that is what Drupal does, but there could be a module that redirects the user to a different page, such as the one showing the node edit form to add a new node.
To show the popup when the node is viewed, you can use hook_node_view(), which can be used to add HTML tags to the node view page.
The example shown in the documentations shows how to add markup to the node view page.
function mymodule_node_view($node, $view_mode, $langcode) {
  $additional_markup = 'Markup to add to the page';

  $node->content['my_additional_markup'] = array(
    '#markup' => $additional_markup,
    '#weight' => 10,
  );
}

As for showing the popup right after the node has been saved, you could implement hook_form_alter() to add a form submission handler to the "Save" button; that submission handler would add a session variable that is the checked from your implementation of hook_node_view(). Its code should then be similar to the following one.
function mymodule_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && mymodule_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';

    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}

The values in $_SESSION are the ones set by the form submission handler. mymodule_check_timestamp() should return TRUE when $_SESSION['timestamp'] doesn't contain a value too past in time; this would help in the case there is a module that redirect the user to a different page, and then the user visit the node page to review the node s/he saved. For example, it could return TRUE when $_SESSION['timestamp'] is a timestamp 5 seconds earlier. It is up to you to decide how much delay should be acceptable between when the node is saved, and when the node is viewed from the same user who edited it.
You can change the weight used in hook_node_view(); that changes where in the node view page your markup is added.
Comment: can I use drupal_add_js?
Comment: Hi kiamlaluno, function bartik_node_view($node, $view_mode, $langcode) {
  if (isset($_SESSION['nid']) && isset($_SESSION['timestamp']) && $_SESSION['nid'] == $node->nid && bartik_check_timestamp($_SESSION['timestamp'])) {
    $additional_markup = 'Markup to add to the page';
    $node->content['my_additional_markup'] = array(
      '#markup' => $additional_markup,
      '#weight' => 10,
    );
  }
}
this does not work for me
Comment: What I write in my answer is just part of the code you need. You still need to write code for `mymodule_check_timestamp()`,  and add a form submission handler to the node edit form to set those variables in the session.
Answer: drupal_add_js inside a hook_form_alter, like so:
function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
  if ([your logic to pick out the node form])
    {
      drupal_add_js([your javascript]);
    }
}

Or you could probably do it with Rules calling some custom code.
Comment: Hi Beth, I've used hook_form_alter, how do I get the node variables?
Comment: First I'd look in $form to see if what you want is in there. If not, `if (arg(0) == 'node') {
  $nid = arg(1);
}` should give you the current node NID and then you can node_load() or whatever you like. (Credits to [this question](http://drupal.stackexchange.com/questions/6638/get-a-node-id-from-the-url))
Comment: ok, now what's you suggestion for the popup? how can build it?
Comment: [w3schools](http://www.w3schools.com/js/js_popup.asp) has basic JavaScript popup info. You can do something as simple as that or as complicated as [this](http://yensdesign.com/2008/09/how-to-create-a-stunning-and-smooth-popup-using-jquery/).
Comment: Now the problem is not how to create a popup, I can use a dialog or lighbox or whatever, the problem is that the js works with the html and as long as i cannot print html through node_form_alter I cannot call anything... unless i do a drupal_set_message(contents) ... it could be a solution... Any other suggestion?
Comment: drupal_add_js() adds the javascript into the page. [There's documentation on this page](http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_js/7). drupal_set_message() would strip tags out, I believe, so don't use that.
Comment: function bartik_form_node_form_alter(&$form,&$form_state,$form_id)
{
     if($form['#node']->type=="test")
     {
         $form['actions']['submit']['#submit'][] = 'my_callback_function';
     }
}

function my_callback_function() {
 if (arg(0) == 'node') {
   $node_id = arg(1);
   drupal_set_message($node_id);
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');

 }
}

Drupal add js does not work... drupal set message does.

Show a popup after saving a new node


Given a triangle with two known vertices and the angle, get the coordinates of the last vertex

Question: I have tried attaching an image of the triangle I am working with but since I am a new user this site will not let me post images (kind of defeats the purpose, but anyways).
I have the following triangle:
Point A = (x:40, y:100)
Point B = (x:50, y:50)
Point C = ??
d = 20 degrees (which is the angle between vectors BA and CA.
I am tring to find out the coordinates of Point C.  I have tried using the law of cosines and scoured the net looking for a close example that I can learn from and figure out why I can't get the correct formula for this.
Can any one please lend a hand in figuring out this formula.
Thank you!
Comment: Post a link to the image (upload it to [imgur](http://imgur.com/) if necessary), and someone will edit it into your question.
Comment: An informal sketch should convince you that there are many $C$ that work.  Did the problem say *anything* else about $C$?  Typical in this sort of game, for example, would be to say that $C$ is on the $x$-axis.
Answer: Just to repeat what everyone has told you: what you have stated in the question is not enough information about C. Here's a picture:
Comment: There's also another half-line on which C can lie, on the other side of AB.
Comment: @Ilmari: Yes, I thought adding both may lead to more confusion, so I arbitrarily picked one. :-)
Answer: I don't think you have enough information to find a unique solution, or even to narrow the solution down to a finite number of possibilities.  A triangle in the plane has six degrees of freedom, i.e. you need six real numbers to uniquely specify the locations of its vertices.  You only have five known parameters.
Answer: From  the information you've given point C can be any point along the vector AC such that the Y coordinate is less than the Y coordinate of A. This gives an infinite number of solutions.
Answer: Those numbers are unpleasant and irrational, so I'm going to do a simpler example. The idea is that we know one side length and one angle of a triangle. But we can quickly construct two such triangles - for example, if AB = 5, angle ABC is 30 degrees, and angle BCA is a right angle, then we quickly get that AC is $5/2$ and BC is $\frac{5}{2} \sqrt 3$.
On the other hand, if AB = 5, ABC is 30 degrees, and angle BAC is right, then we get that AC is $\dfrac{5}{\sqrt 3}$ and BC is $\dfrac{10}{\sqrt 3}$.
So two different triangles, but each with one side and one angle the same. So it's not unique.


Fair division of bills

Question: Suppose at a restaurant my friend ordered \$30 worth of pizza, and I ordered \$20. The restaurant is having a promotion so that we could get the second order at half price (the second order can't be more expensive than the first one), so we should pay \$30+\$20/2=\$40. How much should we pay?
I've heard of the Talmud division, but here we're claiming debts rather than incomes, so I'm not sure that the concept applies. Besides if we do the Talmud division then the person who placed the first order always have to pay the full price, which doesn't seem fair. Is there any equilibrium state here?
Thanks!
Answer: There are some hidden assumptions in the question, namely whether or not the orders were made expecting to get a discount from the  promotion.
In the simple case where both orders were made ignorant of the promotion (and the waitstaff just tells you that there will be a discount), then your friend is willing to pay \$30 and you are willing to pay \$20.  If you were each eating separately, that is what you would pay.  The restaurant is giving you a \$10 bonus, which neither of you would get if you were dining alone.  Hence it seems fair to split the bonus equally.
However, things get more complicated if one or both of you were already expecting to get some part of the discount.  For example, suppose you would have ordered nothing at all without the promotion, but are willing to pay a maximum of \$10 for pizza (which you believe to be overpriced).  Then, in your mind, there is no bonus.
Sadly, once the orders have been placed it is too late to sort these issues out; the best time to decide on the discount is before the order has been placed.  There are various methods involving bidding that would resolve the matter as well, provided you and your friend are willing to swap dinners for the right price.

Fair division of bills


How do I save data with chrome extensions?

Question: Say I wanted to make a chrome extension with a text input. Right now, every time I re-open the the extension, the text input clears (does not save what I had last time), but what if I wanted the value in the text input to remain every time I re-opened the extension?
Answer: Try using chrome.storage.
When the user inputs a value, you save it with:
await chrome.storage.local.set({ key: value})

You can then retrieve it in background.js every time the user opens the browser again.
See the docs here: https://developer.chrome.com/extensions/storage


how to show plane text with break lines and space in bootstrap modal

Question: i read text file and show it on modal
but the modal remove all spaces and new line
even i can see my text file in correct format in Inspect window
How i can show text in correct format ?
Comment: Please read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask)
Comment: @MDAshik the image show anything that you want . really you dont understand my question ????
Answer: Though your question is not clearly understandable, i have done something looking at your image . I hope this could help you in something you are trying to achieve.
Try coding in the following way,

TCP 0.0.0.0.80   0.0.0.0

TCP 0.0.0.0.81   0.0.0.0

TCP 0.0.0.0.82   0.0.0.0

TCP 0.0.0.0.83   0.0.0.0

TCP 0.0.0.0.84   0.0.0.0

TCP 0.0.0.0.85   0.0.0.0

TCP 0.0.0.0.86   0.0.0.0

the styling goes like this;

I hope this helps you.
Comment: I read a text file and show in modal view , all text file are not in same format ...
Comment: Is there any link to your demo that i can view about what actually you are trying to achieve. Still your question lacks clear visualization to  answer us.
Answer: Put the text you want to not wrap inside

 tags, like this:

TCP 0.0.0.0.80   0.0.0.0
TCP 0.0.0.0.81   0.0.0.0
TCP 0.0.0.0.82   0.0.0.0
TCP 0.0.0.0.83   0.0.0.0
TCP 0.0.0.0.84   0.0.0.0
TCP 0.0.0.0.85   0.0.0.0
TCP 0.0.0.0.86   0.0.0.0


MQTT - how to check port and IP is running in mqtt

Question: I am trying to check the given IP and port running or not, if not then I have to return exception to client.
Here is my code,
MqttMessage message2 = new MqttMessage();
MQTT mqtt_connect = new MQTT();
mqtt_connect.setHost(Host_Address, Integer.parseInt(port));
String topic = "/call/MQTT_Config";
mqtt_connect.setClientId("MQTT_Config");
mqtt_connect.setWillRetain(false);
mqtt_connect.isWillRetain();
mqtt_connect.setWillTopic(topic);
BlockingConnection m_publisher = mqtt_connect.blockingConnection();
m_publisher.connect();
if(connection establish){
    // here how to check the condition
    do publish  here
}
else{
    return "connection failure";
}

Someone tell me the validation in my code.
Answer: Wrap up your code in try/catch as follow
try{
    MqttMessage message2 = new MqttMessage();
    MQTT mqtt_connect = new MQTT();
    mqtt_connect.setHost(Host_Address, Integer.parseInt(port));
    String topic = "/call/MQTT_Config";
    mqtt_connect.setClientId("MQTT_Config");
    mqtt_connect.setWillRetain(false);
    mqtt_connect.isWillRetain();
    mqtt_connect.setWillTopic(topic);
    BlockingConnection m_publisher = mqtt_connect.blockingConnection();
    m_publisher.connect();

}
catch(Exception e){
    add message for connection not established
}


Labelling particles in a ParticleSystem/PointCloud in THREE.js

Question: Updated:
I have one million 2D circles spanning the X,Y axes with their Z value as 0 (like a scatter plot). I'm using THREE.PointCloud and WebGL shader programs in hope of it improving performance (seems to work). They are made using a 256x256px PNG image of a ball (even though the points never reach 256x256px when scaling?). I'm also using raycasting to hover over and click on the circles (which are of varying colours and sizes).
I'm trying to add text labels for the points, which scale and are anchored to the circles when the user zooms and pans the scene.
I've tried creating a 2D THREE.TextGeometry object for each point and adding them into a Object3D and adding it to the scene. The performance is expectedly poor, but everything else is great.
I'm currently in the process of creating a 2D canvas texture for each point's label, adding the textures to an object and then adding that to the scene (seems fast, but font-size, pixelation and coordinates are giving me a headache).
I'd like to think there's some sort of 2D plane that I can add lots of text labels to, which don't pixelate when zooming on the Z axis. THREE.PlaneGeometry sounds good, but I got an error when trying to add an object to it.
Another option would be to only show labels for the points that are visible. I understand that a PointCloud is considered a single object and so FrustrumCulling doesn't apply to individual points. So I'd have to implement my own culling detection. If I did this though, I could go down the route of using HTML elements for the labels, or even the TextGeometry approach.
Old question:
Has anyone had any success labelling points/particles in THREE.js?
Ideally a non-pixelated text label, able to scale and rotate with the pointcloud.
Regarding pixelation, I'm thinking of using TextGeometry() to make a 2D text label. And then adding the labels to an object and then to the scene using the same coordinates as the points.
But then in the case of 1 million points, would adding a separate object of 1 million text labels be too much?
Comment: Your question is a bit poor for SO, as "Yes I have." would be a technically correct answer. Geometry = bye bye performance (and they won't easily face the camera). CSS sprites might be a possible solution for you, though they would overlay the scene rather than be integrated with them. I'm using Sprites, but one million of them ... ain't going to happen (won't fit on screen, and you'd be out of texture memory pretty darn quick). Please be much more specific in your question.
Comment: Sorry, I'll update my question.
Answer: After some research it seems as though signed distance field fonts render text crisply without pixelation and can be achieved through the use of WebGL shaders - so offloading the workload to the GPU which should be great for labelling a million particles.
Comment: can you share your experience, how you achieve it? Iam facing the same problem. [link](http://stackoverflow.com/questions/27376252/100000-city-names-using-single-three-pointcloud)
Comment: I am also interested in knowing how you solved this.


REST Post creating entities with relations

Question: I am having trouble creating comments on nodes ( articles etc. ) with the Rest module.
I have enabled the endpoint in rest.settings.yml :
resources:
  'entity:node':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth
  'entity:comment':
    GET:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - cookie
    POST:
      supported_formats:
        - hal_json
        - json
      supported_auth:
        - basic_auth

I have followed the information here rest tutorial - headless drupal 8 and on drupal.org
I used this tutorial as a base to build my request, noting that there have been changes since the article was posted.
I am using basic_auth, setting the CSRF token as per issue and I have set permissions for the test user to edit, delete and create articles, basic pages and comments.
I am using application/json+hal because of the outstanding issue
with application/json
What is happening is the server is reponding :
403 Forbidden :
{"error":"Access denied on creating field entity_id"}
The request is failing where checking access on read only fields, which return AccessResult::forbidden();
Clearly I am missing something from my request ? I thought that the hal _links reference points to the entity_id ?
My request so far :
{
   "_links":{
      "type":{
         "href":"http://d8.dev/rest/type/comment/comment"
      },
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "href":"http://d8.dev/node/1?_format=hal_json"
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "href":"http://d8.dev/user/1?_format=hal_json",
            "lang":"en"
         }
      ]
   },
   "_embedded":{
      "http://d8.dev/rest/relation/comment/comment/entity_id":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/node/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/node/article"
               }
            },
            "uuid":[
               {
                  "value":"c4b5b929-3ccb-4cfd-8200-0ec8f9170926"
               }
            ]
         }
      ],
      "http://d8.dev/rest/relation/comment/comment/uid":[
         {
            "_links":{
               "self":{
                  "href":"http://d8.dev/user/1?_format=hal_json"
               },
               "type":{
                  "href":"http://d8.dev/rest/type/user/user"
               }
            },
            "uuid":[
               {
                  "value":"76555fc7-c4c4-4e1f-a053-83ab818bba4f"
               }
            ],
            "lang":"en"
         }
      ]
   },
   "comment_type":[
      {
         "target_id":"comment"
      }
   ],
   "comment_body":[
      {
         "value":"Hello world this is a comment",
         "format":"basic_html"
      }
   ],
   "subject":[
      {
         "value":"A comment test"
      }
   ],
   "name":[
      {
         "value":"admin"
      }
   ],
   "thread":[
      {
         "value":"01/"
      }
   ],
   "entity_type":[
      {
         "value":"node"
      }
   ],
  "field_name": [
    {
      "value": "comment"
    }
  ]
}

Answer: Okay so this issue is actually a bug. For me the issue was fixed by applying the latest patch for now, likely the patches will need work and tests.
There were issues with my request and I have changed them above to reflect how an actual comment request should look like ( at the time I am writing this ).


JavaScript, Eval, and New -- poor man's factory

Question: Rare cases aside, eval() is considered bad practice in JavaScript.
I've just come across a fragment of code that takes a string and constructs an object by that type name.  Error checking, business logic, and context for doing so removed, here's what it looks like:
function factory(klass) {
  eval("var obj = new " + klass + "()"); // Is there a better way?
  return obj;
}

Is there a better (safer, cleaner, and/or faster) way to accomplish the class creation without using eval?
I'm looking for a generic way to create a class by its name.
e.g., Imagine, for instance, another part of the code dynamically loads JavaScript files, generates code, or allows user extensions, but then some other part of the code needs to make that class without the factory having prior knowledge of its existence.
Comment: Error checking, et. al., was removed for the sake of making a terse example on StackOverflow -- fret not.
Comment: Without getting into too much of the why behind it, klass is a string.  The ponderance was to find a way to do the logical equivalent, using the same input, without using eval() to pull off the stunt.
Answer: You can register classes with your factory object and than create them by string name:
var allClasses = [];
allClasses["MyClass"] = function(){return new MyClass();}
allClasses["MyStruct"] = function() {return {F1:"", F2:42};}

function factory(klass)
{
    if (!allClasses[klass]) throw "Bad name!";
    return allClasses[klass]();
}

Comment: I'd really like to give split credit on this.  David Titarenco indicated in his comments that it is not possible to do what I was trying to do without eval.  Alexei Levenkov managed to give the next closest thing, taking a string as I needed, returning classes from a factory object.  So I'm accepting this as the best way presented so far to get around not using eval().  Thanks to all of you.
Answer: Here's a situation where error-checking IS important and you should not have removed it. Say we go with @Gabi's "hard factory" solution:
function hardfactory(klass) {
  var obj = new klass();
  return obj;
}

try {
var x = hardfactory(asdf); // this will break unless
                           // we wrap every single hardfactory() call in a try-catch
} catch (err) {
    console.log(err);
} // who wants to do this every time we invoke hardfactory? not I

Now lets look at your original "soft factory" solution:
function softfactory(klass) {
  try {
      eval("var obj = new " + klass + "()");
  } catch (err) {
      console.log(err);
  }
  return obj;
}

var y = softfactory("asdf"); // this will not break
                             // since we do the try catch inside the softfactory()

The eval() call is well-warranted in this case. It's important to understand that every language construct (yes, even eval()) is useful and part of the language for a reason. The fact that some people overuse it or use it in the wrong circumstances doesn't mean it's not a very powerful tool in the right ones.
Comment: Also, you should make it clear that `eval` requires you to be careful with the input: if `klass` was something like `function(){}; /* your evil code */ (function(){})`, you're in for some trouble
Comment: So, error-checking aside, which I agree with but is not part of question pertaining to eval, is this answer confirming that this is one of the few acceptable cases for using eval, and that this is the proper way to achieve this functionality?
Comment: If you're asking if there's a way to pass a string to a function and get the object representation of the string then no, there's no way of doing that without eval.
Answer: You don't need eval. You can simply pass the object instead of its name, and use var obj = new klass(). Voilà
function factory(klass) {
  var obj = new klass();
  return obj;
}

function C() {...}
C.prototype = {...}

factory(C);

Comment: It seems to me they *want* to pass a variable's name, a string. That's what the question is about.
Comment: @katspaugh The question says clearly "Is there a better (safer, cleaner, and/or faster) way to __accomplish the class creation without using eval?__". Reading comprehension
Comment: Yet there is a way to accomplish class creation provided a name and a namespace, the bracket notation. And it's a bit closer to the original function, don't you think?
Comment: @katspaugh no, I don't think that. The OP doesn't state anywhere a _namespace_. The class definition may be very well in any outer scope level, so bracket notation fails. Also, if you think you have a better solution, post an answer; the OP may appreciate it.
Comment: More info: the string is coming from an external source, no object instance exists at the time the factory is called.


OledDbDataAdapter "Syntax error in FROM clause" exception

Question: I'm using OleDB to import data into grid from text file with extension ".K$$".
Here's some example code:
FileInfo file = new FileInfo(filename);
string connectionString = "";
OleDbDataAdapter adapter;
OleDbConnection con;

connectionString = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=" + file.DirectoryName + ";Extended Properties=\"Text;Format=TabDelimited;\"";

con = new OleDbConnection(connectionString);
con.Open();
adapter = new OleDbDataAdapter(String.Format("SELECT * FROM {0} ", file.Name), con);

adapter.Fill(MyDataTable);

when executing the Fill method it throws the exception. What's wrong with the FROM clause? Thanks

EDIT:
Ok, after some tests I found out that the problem is with the "$" symbols. Maybe it's some reserved symbol ?
Also, if I rename the extension to ".txt" the file got loaded into the grid but it only have 1 column , which means it can't see that there're tabs in the rows.
Another issue is that when I change the file extension to something different than ".txt" (for ex. ".tx") the Fill method throws exception "Cannot update. Database or object is read-only".
Comment: What is the exception? You should use a Try and Catch statement withthis also.
Comment: what is the value of `file.Name`?
Comment: The syntax all looks fine, it has to be with the connection string
Comment: @codingbiz the name of the file (not the full path name) plus the extension.
Comment: Does the path have spaces in it? Neither the directory nor the filename is escaped/quoted.
Comment: @DanielRenshaw the filename is  6328523.K$$
Comment: Print out the value of `String.Format("SELECT * FROM {0} ", file.Name)`. What about the special symbols???
Comment: @codingbiz the ouput is "SELECT * FROM 6328523.K$$"
Comment: I'm not familiar with this but I suspect `6328523.K$$`. Try select another file name that doesn't have all this funny symbols e.g. SomeData.TXT
Comment: can you please add the connection string in full.. so i can see teh exact string its building please
Answer: OK, I just tried creating an example.K$$, and then tried to connect to it using the same provider as stated through Server Explorer in Visual Studio 2010. Its an Unrecognised format.
I don't think this will ever work.
You may need to look at connecting via a different provider or method.
I think You should look at this link :-
EDIT :
http://www.codeproject.com/Articles/6737/Fill-a-DataSet-from-delimited-text-files
It will allow you to read your txt file into a datable correctly.
Comment: No worries, I have to be honest, Your trying to read a txt file like a structured Database. I use OLE Data Adapters alot, with MS Access Databases. I'll do some researchand see if theres a solution for you.
Comment: Thanks for finding it. I don't have problem with .csv and excel files with the OleDB but I guess I'll have to make my own parser for the other text files.
Answer: Try checking the path of the filename if its correct
Answer: Check that neither the directory, nor the filename, contain spaces. If they do, you'll need to escape/quote them.
You'll also need to quote the filename if it contains an extension since the . is not a valid character in the FROM clause. Try FROM [{0}] (though this may not be the correct quoting character for the OleDbDataAdapter).
Comment: None of them is containing spaces.
Comment: @DimitarTsonev you'll still need to quote the filename because of the extension character. See my updated answer.


$|G| = pqr$ with $p$, $q$ and $r$ distinct primes. Show G is not simple.

Question: $|G| = pqr$ with $p$, $q$ and $r$ distinct primes. Show G is not simple. I know this might have been asked and answered before. I just wanted someone to tell me if my argument is OK:
Let $|G| = pqr$, and assume $p < q < r$. We have at least one Sylow-$q$ subgroup (call it $Q$) and at least another Sylow-$r$ subgroup (call it $R$). Consider the subgroup $K = $ $<Q, R>$. Now $K$ is not the whole group because there is no element of order $p$ in there. Further, $|K|$ must equal $qr$ because nothing smaller is possible by Lagrange's theorem.
Therefore [G : K] = p, which is the smallest prime dividing G. Hence by a standard theorem (for instance, see corollary 4.5, p. 44, Isaacs' Algebra), K must be normal. Hence $G$ is not simple.
Thanks!
WH
Comment: Why, or in fact: how would you prove $\;K\;$ contains no element of order $\;p\;$ ??
Comment: My original reasoning was that $K$ is subgroup generated by $Q$ and $R$, which are Sylow-p subgroups of distinct primes $q$ and $r$. If an element of order $p$ distinct from $q$ and $r$ was present in $K$, $p$ would have to divide the order of $K$, which could not include a prime factor, $p$, because of the way it was constructed: $K = $.
Comment: That's wrong, @Wulfang. For example, $\;S_5=\langle (12)\,,\,(12345)\rangle\;$ , so according to your argument $\;S_5\;$ cannot have elements of order $\;3\;$...yet it does.
Comment: If $|G| = pqr$, then is not $G \approx Z_p \times Z_q \times Z_r$? How could $$ generate the whole group?
Comment: Well, I just gave you an example of a group of order $\;5!=2^3\cdot 3\cdot 5\;$ generated by a cyclic group of order two and one of order five. What else do you want?! And no: if $\;|G|=pqr\;$ then it is not *necessarily* true that $\;G\cong C_p\times C_q\times C_r\;$ , as this would imply yhe group is abelian (even cyclic, if the three primes are distinct) ...
Answer: There is nothing stopping $K$ from being equal to $G$ - ie. $K$ might have elements of order $p$. However, I cannot think of a counterexample of the top of my head. Here is an alternate solution though.
You can do this by counting elements of orders $p, q$ and $r$ : Let $n_s$ denote the number of $s$-Sylow subgroups, for $s\in \{p,q,r\}$. Since any two distinct $s-$Sylow subgroups intersect trivially (why?), it follows that

The number of elements in $G$ of order $s$ is $n_s(s-1)$

Now assume $n_s \neq 1$ for all $s\in \{p,q,r\}$. Then

$n_r \equiv 1\pmod{r}, n_r\mid pq \Rightarrow n_r = pq$
$n_q \equiv 1\pmod{q}, n_q \mid pr \Rightarrow n_q \in\{ r,pr\} \Rightarrow n_q \geq r$
$n_p \equiv 1\pmod{q}, n_p\mid qr \Rightarrow n_p \geq q$

Hence,
$$
|G| \geq n_r(r-1) + n_q(q-1) + n_p(p-1) + 1
$$
$$
\Rightarrow pqr \geq pq(r-1) + r(q-1) + q(p-1) + 1
$$
Solving this gives you a contradiction, and so $G$ cannot be simple (in fact, one of these Sylow subgroups must be normal)
Comment: Many thanks for suggesting an alternate solution. However, since Q and R are Sylow p-subgroups of distinct primes q and r. How could a subgroup  thus formed have an element of order p (distinct from q and r) inside ? I just want to see if I could still salvage my argument. Thank you again.
Comment: @Wulfgang : In general, what you say is not true (for instance, $A_5$ is generated by 3-cycles), but in this case it is (because the r-Sylow subgroup turns out to be normal. However, proving that is much harder.
Comment: OK, but what about the distinct Sylow-p subgroup in G (call that P). Now P cannot be contained in K = . So, K cannot be the whole group. So, should not [G : K] still be p?
Comment: Well, if you can prove that $P$ cannot be contained in $K$, you are good to go. But what I mean to say is that you cannot just say that is true because of an order argument - it is more subtle than that.
Comment: Thank you again, and for the warning. As a beginning graduate student, I am beginning to see that most "obvious" things (esp. in Algebra) are wrong when details are sought.
Answer: Can you use Feit-Thompson? An odd order simple group must have prime order. So, in this case, the smallest prime must be 2. But if a group has order equal to twice an odd number, it must have a normal subgroup of index two.
Comment: The asker shows a rather elementary approach to try to answer his own question. It seems obvious that (s)he's attending an introductory course in group theory. To use the F-T theorem is like trying to use a bazooka to get rid of a pesky mosquito.
Comment: Thanks to everyone for helping me. Yes, I am pretty sure I could not quote the F-T theorem in a homework problem without proving it first!
Comment: I am indepentantly studying algebra from Dummit and Foote. They present the F-T theorem quite early. They imply that the result is so simple and useful, but the proof so difficult, that it would be a shame to limit its use to the very limited audiences who could reproduce it. 255 pages of hard math! How many people could actually reproduce this?
Comment: My understanding is that the F-T theorem (although quoted by Dummit and Foote) is actually a very deep result--and that the 255 pages are well justified. Thompson won the Fields Medal for this effort. It is simple to state, and the meaning can be understood by anyone with undergrad algebra. That is why Dummit and Foote quote the result.


What is the time limit of an inings?

Question: What is maximum time limit of an innings in t20 and one day format? If time is wasted by batting team or by any natural way like time waste in large number of  unexpected extra boundaries (huge sixes) will bowling side captain still be fined?
Answer: The time limit for a limited-overs innings will be specified in the regulations covering that competition.
The T20i regulations are here, and they state that each session should be 1 hour 25 minutes in duration, with a minimum over-rate of 14.11 per hour.
The ODI regulations are here, and they state that each session should be 3 hours 30 minutes in duration, with a minimum over-rate of 14.28 per hour.
Umpires are permitted to extend the allowed time to cover things like delays due to injury, lost balls etc.

What is the time limit of an inings?


Partial fractions integration - Constant denominator value

Question: How do I chose which factor goes under what constant?
I understand that $x^{2}+x = Ax+B$ or $Bx+C$ etc (That is not my question/concern)
My question is:
When I factor a quadratic, say for example:
$$\frac{x-1}{x^{2}+3x+2}$$
The denominator would factor out to $(x+2)(x+1)$
How do I know if A goes over $(x+2)$ or $(x+1)?$
Setting these up wrong seem to mess up my answer completely when I check on symbolab and emathhelp
Answer: Given
$$\frac{x-1}{x^2+3x+2}=\frac{x-1}{(x+2)(x+1)}$$
it doesn't matter if you set
$$\frac{x-1}{x^2+3x+2}=\frac{A}{x+2} + \frac{B}{x+1}\tag{1}$$
or
$$\frac{x-1}{x^2+3x+2}=\frac{B}{x+2} + \frac{A}{x+1}\tag{2}$$
when you do partial fraction decomposition. In both cases, the constant for $A$ equals the constant for $B$ in the other case. Therefore, you will arrive at the same solution.
Both $A$ and $B$ refer to arbitrary constants. The important part is that you choose two different constants and then solve by the partial fractions decomposition.


Kubernetes Blocked Mixed Active Content

Question: Issue:
When working with K8's [Kubernetes] on development, I'm running into the issue where my Ingress/Nginx seems keep my client side (React) from pulling data from my API (Flask/Python).
Details:
The connection between the client and API is facilitated using an Environment Variable that we'll call API_URL for the sake of this post.  API_URL is used so that the Client knows which API routes to GET and POST.
On Minikube with K8's in dev, the Minikube IP that is provided forces https from what I understand (or maybe it's ingress/nginx?).  The API_URL environment variable value is value: api-cluster-ip-service.  However, when I hit the dev site it's showing that this value gets assigned to http://localhost (not-https)
This causes: Blocked loading mixed active content "http://localhost/server/stuff".  As a result, I can't pull anything from my API.
Question:
Is there a recommended approach for this? Perhaps a way to turn https off on dev (I don't even know if that's possible)?  Or maybe I need a certificate for localhost? I'm fairly new to Kubernetes so any help is much appreciated!
Ingress-server.yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
    - http:
        paths:
          - path: /
            backend:
              serviceName: client-cluster-ip-service
              servicePort: 3000
          - path: /api/
            backend:
              serviceName: server-cluster-ip-service
              servicePort: 5000

Ingress Namespace output
kubectl get ing --all-namespaces
default     ingress-service   *       10.0.2.15   80      4d21h

Comment: @dizzy, have you tried specifying the `host` in your .yaml? Also you can disable the redirect adding annotation `nginx.ingress.kubernetes.io/ssl-redirect: "false"`
Comment: @dizzy kubectl get ing --all-namespaces
Comment: Can you share your ingress yaml?
Comment: @Crou Yup!  added in an edit
Comment: @dizzy how did you deploy your ingress controller?
Comment: @c4f4t0r
`Minikube > kubectl apply` is how I deployed the ingress server file to the cluster.
`minikube addons enable ingress` is how I turned it on.  No other configuration.  This is strictly for a dev environment. Let me know if that answers your question!
Comment: @c4f4t0r added in an edit above.  Let me know if that's enough info!
Comment: I actually haven't tried modifying the host in the .yaml file. I'll give that a shot.  Thanks for the tip on disabling SSL.  Will try that as well and report back if that's the answer to this mess!
Comment: It's unclear to me what you're trying to do. What does this "mixed active content" error mean? Are you using websockets or something?
Comment: @AhmetB-Google I honestly think it's a consequence of another database related error and I'm just seeing something else pop up in the console.  I'm seeing less of the error now that I've resolved that.  Will come back and update this issue if it corrects itself or persists after I make a couple more changes.
Answer: I found the cause of my problem...and the error message was fairly misleading.  On a local environment, my Client side talks to my API via http://localhost/api/.  However, I realized that because I was on Minikube, it's no longer on localhost (because Minikube has it's own IP). Once I changed my API_URL to http:// it began working immediately.
The only challenge here is that minikube, when stopped, changes the IP on each refresh, meaning I need to grab the IP and update the API_URL each time.  However, that's a separate question/answer.
Summary:
Changed my API_URL from http://localhost to the Minikube IP.  Began working immediately.

Kubernetes Blocked Mixed Active Content


Reliable or Repairable Ampeg amps

Question: I've had an Ampeg SVT-7Pro for a few years and one of the ICE2A165 chips overheated. Apparently this is a common problem with earlier models of the amp. I took the amp to my repair man and he mentioned that the chip replacement itself is very challenging/expensive, but replacing the board may be an option. I found a replacement board with an upgraded chip ("revision H" of the amp) for a few hundred bucks which should be pretty easy to self install.
However, my tech mentioned that many of today's Class D amps are notoriously fragile and once broken, they are often more expensive to repair than to replace. He said that if the amp is light, small, and powerful, it usually falls into this category.
I love the SVT sound and controls, so I'm wondering if I'm better off getting one of the big heavy SVT-3 or 4 Pros. They only have a two year warranty when I look at most online stores, but would they be easier/cheaper to repair in the event of a fault? I want an amp that lasts a long time.
UPDATE 1:
Here are pictures of the chip explosion. It took other parts with it. I'm curious what those other are and how easy it would be to replace them all (I'm sure they're cheap.) I can solder, I just don't have all the fancy diagnostic tools. Spending $20 and some spare time seems worthwhile, so I don't have to buy a new amp .

UPDATE 2:
I found the three parts online that were destroyed:

The ICE2A265 (upgrade from the ICE2A165)
One US1M diode to go in space D9
One 1-ohm/1-watt resistor for space R46

I'm going to try soldering these in using the schematic and see what happens.
Comment: @Taschi there shouldn't really be any need for sockets – Ampeg's fault is using an IC that's not up to the task! And, come on, replacing a THT IC isn't _that_ difficult. An SMD one – yeah, though even that is doable.
Comment: Swapping the IC, even with a regular iron & vac-pump is not the tough part. The tough part is figuring out what else it took down with it - & that might not only be the bits that look charred, it might be anything one or two steps away down the PCB track, &/or the track itself. Get a pro to do it. I had my favourite Dynacord go down last year & it cascade-failed half the components.
Comment: Yeah, looking at the photos, I take back everything I said yesterday. It's not like a socket would really help here.
Comment: I took a glance at some photos of the SVT-7 Pro's board and it seems that the amp chip is soldered to the board, rather than socketed. This is most likely the main issue with repairing them, as THT-soldered ICs are notoriously hard to remove without damaging other components on the PCB. The SVT-4 Pro apparently shares this issue, again judging by photos on the interwebs. (Side note: being too cheap to use IC sockets in a $700 piece of gear is a very bad engineering decision.)
Comment: @Taschi don't use a heat gun. Unsolder the legs individually with a desoldering pump, then simply pull the IC out with small pliers (it'll still require some force because of flux residues, but shouldn't be so much that you risk damaging the board).
Comment: Does the replacement board use IC sockets? Because if so, replacing a burnt-out IC is literally a matter of screwing the amp open, ripping the old IC out, sticking a new one in, and screwing it together again.
Comment: TBH, without a heat gun i find even removing a component with two or three pins fairly tough, and the heat gun could easily damage other semiconductors. But I'm not really experienced in that area so I'll take your word for it. I stand by my opinion that not using sockets is a bad choice, even if you also *should* use ICs that do not burn out under standard load. That's just a stupid way to create unnecessary garbage.
Comment: This discussion is getting out of hand, i think, but at least with my pesky desoldering pump, getting the solder out of PCB holes is *incredibly* hard. I've had cases where i spilled solder into an empty hole, and used a hand drill to get it open again. Admittedly, my tools might just be bad.
Answer: The U2 ICE2A165 chip should be replaced by an ICE2A265 (just as cheap). It's a standard 8-pin IC; if I was working on that board, I'd pull the broken chip, insert an 8-pin IC socket and then use the upgraded chip (it has better thermal properties).  Talk to another repair man - this doesn't seem like a challenging or expensive fix.
Comment: @taschi Soldering  a socket in place has most of the hassles of soldering an IC, except that you're not worrying about local heat build up. I agree with replacing all the visibly damaged components.
Comment: @PeteCon, yeah, that too. My point was, there is no downside to putting in a socket.
Comment: Thanks! When the chip exploded, it took other parts with it. I'm adding images to the OP. Also, how much trouble is it to insert the socket? I've soldered guitars before, maybe I could probably do this myself.
Comment: Inserting the socket is exactly as much trouble as inserting a new IC: you put it into the holes and then you solder the pins. So, trivially easy. But TBH i think you should AT THE VERY LEAST replace the charred resistors and caps, check that the PCB paths are still conductive, and check all other components within the fat white line. (I assume U8 and the DIP next to it are optocouplers and provide galvanic separation so the stuff outside the fat white line might be less likely to have taken damage?)
Comment: Soldering PCBs is different from soldering wires / leads together "in the air", so maybe get yourself some prototype PCBs and try a handful of joints on there.

Reliable or Repairable Ampeg amps


Searching for a connected neighborhood of fixed radius for every point of a submanifold

Question: Let $\Gamma=\gamma(\partial D)\subset \mathbb R^3$ be an image of $C^1$-curve, where $D$ is an open ball in $\mathbb R^2$.
My question is whether it is possible to find a fixed $\epsilon >0$ such that for every point $p \in \Gamma$ the neighborhood $$B_\epsilon(p) \cap \Gamma$$ is connected in space $\Gamma$. $B_\epsilon(p)$ denotes open ball of radius $\epsilon$ in $\mathbb R^3$.
I thought since $\Gamma$ can be considered as $C^1$-manifold of $\mathbb R^3$ some neighborhood of every point $p$ can be approximated (i.e. diffeomorphic) to tangent line. Now repeat procedure for every point, take smallest and we get desired $\epsilon$.
But how to assure no pathologies like $\sin(1/x)$ can occure? In this case I would get $\epsilon = 0$.
Edit: As @MoisheCohen  pointed out we have to assume that

$\Gamma$ is a compact 1 dimensional $C^1$-submanifold of $\mathbb R^3$ i.e. exists $\gamma: S^1 \to \mathbb R^3 $ regular smooth injective map such that $\gamma(S^1)=\Gamma$.
Comment: Your question is poorly phrased and it is unlikely you will get a reasonable answer. If all you assume is that your set is the image of $S^1$ under a $C^1$-map then what you are trying to prove is false. You need to assume that you have a compact $C^1$-smooth submanifold, e.g. the image of $S^1$ under a regular $C^1$-smooth injective map. Regularity means that the derivative is nowhere zero.
Comment: @MoisheCohen thank you for pointing out, I edited my post. Do you mind explaining what the difference is between $C^1$-smooth and $C^1$-submanifold? Also why do we require regularity property, isn't local homeorphism sufficient? Thank you!
Answer: You should first prove that for any point $p \in \Gamma$ there exists an $\bar{\epsilon} = \bar{\epsilon}(p) > 0$ (which depends on $p$) such that $B_{\epsilon}(p) \cap \Gamma$ is connected for every $0 < \epsilon \le \bar{\epsilon}$.
Now observe that $\{B_{\epsilon}(p) \cap \Gamma  \colon  0 < \epsilon < \bar{\epsilon}(p)\}$ is an open cover of $\Gamma$. Then the conclusion follows from the compactness of $\Gamma$.
Comment: What happens if you try to take $\min\{\bar\epsilon(p_i): 1\le i\le n\}$?
Comment: Thank you! Although I might need your help to finish the proof. As you mentioned $\Gamma = \cup _ {p \in \Gamma} \{B_{\epsilon}(p) \cap \Gamma  \colon  0 < \epsilon < \bar{\epsilon}(p)\}$. From compactness we get finitely many points $p_1,...,p_n \in \Gamma$ corresponding to your cover. Let $q \in \Gamma$ arbitrary, then $q$ is in $B_\epsilon(p_i) \cap \Gamma$ for some $\epsilon: 0<\epsilon<\bar \epsilon(p_i)$. Which fixed $\epsilon$ that is indepent on $q$ should I take? Sorry for being that ignorant.
Comment: @TedShifrin sure, let's take $\epsilon_m$ as you noted. Then in order to $B_{\epsilon_m}(q)\cap \Gamma$ to be connected it, we can show, $\epsilon_m \leq \bar \epsilon(q)$. Which is not quite clear to me... Please give me a hint, I feel embarassed. Also, Ted, have to say, your notes on differential geometry are awesome, helped me a lot. Thank you!
Answer: Assume that $B(x, \epsilon)\bigcap \Gamma$ is not
connected for $x\in \Gamma$.
Hence there is at least four points in $\partial B(x,\epsilon
)\bigcap \Gamma $, i.e. $x_i$ where $x_1,\ x_2$ are connected in the
ball and so are $x_3,\ x_4$.
Here there is $x_{12}$ in the arc between $x_1$ and $x_2$ whose
tangent line $T_{12}$ is close to a line containing segment
$[x_1x_2]$.
Consider a sequence of points $a_n\in \Gamma$ converging to $a$ s.t.
$B(a_n,1/n)\bigcap \Gamma$ is not connected.
Here $T_{12}(a_n),\ T_{34}(a_n)$ have different limits so that it is
not $C^1$.
If they have same limits and $x_2,\ x_3$ are connected, then there
is a point $x_{23}$ whose tangent line $T_{23}(a_n)$ is close to a
line containing $[x_2x_3]$. Hence $T_{12}(a_n),\ T_{23}(a_n)$ have
different limits.
Comment: OP is asking for a compact subset (continuous, in fact, $C^1$, image of the circle).
Comment: Thank you for your comment. I modified my answer.


How do I track Universal Analytics events through Google Tag Manager?

Question: With the old version of Analytics I was tracking events programmatically, like this:
_gaq.push(['_trackEvent', 'my-category', 'my-action', 'my-label'])

With new Universal Analytics, the tracking is done using:
ga('send', 'event', 'my-category', 'my-action', 'my-label');

Both of these create new events in Google Analytics panel, grouped by category and action.
How can I do it with Google Tag Manager? I have added Universal Analytics as a tag in the GTM panel. Now I need to add a piece of code to trigger the events, something like this?
dataLayer.push({'event': ???, 'category':xx, 'action';:xx, 'label':xx});

I do not want to add anything in the GTM admin panel. I would just like to add a piece of code on my website to track the events programmatically and the events to show up in the Google Analytics panel.
Answer: You have to add something in the admin panel, else this will not work.
"Event" in the dataLayer means something different than event tracking in GA - Google choose to confuse the heck out of everybody by using the same name for pretty much unrelated concepts (that those share the name with javascript events does not make things any easier).
"Event" in GTM/in the dataLayer is a reserved variable name that is often (but not always) automatically populated by GTM itself. An event is what triggers a tag to fire. This might be a pageview, a click or a custom event in the dataLayer. So a dataLayer event might be used to trigger an Google Analytics event, but it does send not any data by itself (as GTM and GA are completely independent from each other).
So you need to create a separate GA tag in your GTM interface and change the interaction type from "pageview" to "event". The fields of the tag template will change to reflect this setting, i.e. you will get fields for category etc.
You would then create three macros of the "dataLayer" type and set the "Data Layer Variable Name" to category, action and label respectively to pick up the values that you have set up in your dataLayer. Then enter the macros in the respective fields in the GA event trackins tag.
Finally you need a (GTM) event to create a rule to fire the tag. On Pageview/DOM Ready/Page loaded the event is automatically populated (gtm.js, gtm.dom or gtm.load), for clicks and submits there are autoevent handlers [1] (with their events gtm.click, gtm.linkClick, gtm.formSubmit) or you can use a custom event, i.e. set the "event" variable in the dataLayer to a custom value, let's say "ga_event".
Then you can create a new rule where event eq ga_event and use it to fire the new Analytics event tracking tag. Create version, publish, and there you are.
But you can not send any tracking calls from the dataLayer directly, that would defeat the purpose of the tag manager.
[1] So far you needed to set up autoevent handlers as separate tags. The new GTM interface will take care of this automatically.
Comment: so as you described, this events will be shown in the GTM admin panel, not in the analytic admin panel right ?
Comment: seems pretty complicated just for "event tracking". I guess I will just stick with universal analytic code (ga send) snippet and not use GTM for now. Thanks for the clarification.
Comment: There is no compelling reason to use GTM if you want it just for Analytics tracking - it's useful only if you have a variety of tags that change on a regular basis.


How to access the JNDI namespace defined in the Websphere 7.0 from outside of the container?

Question: I am tring to lookup the resource defined on the Websphere aplication server 7.0 from the out side of the Container with using the iiop protocol as below:
Java code for (RMI client)Test.jar:
public static void main(String[] args){
Hashtable<Object, Object> properties = new Hashtable<Object, Object>();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
        "com.ibm.websphere.naming.WsnInitialContextFactory");
           properties.put(Context.PROVIDER_URL, "iiop://localhost:2809");
InitialContext intCt;
try {
       InitialContext initCtx = new InitialContext(properties);
       Object obj = intCt.lookup(JNDI_NAME);
     }catch (NamingException namingE) {
            System.out.println("Naming Exception occurred :");
            namingE.printStackTrace();
        }
}

Cmmand file to call the Test.jar:

set appClassPath=C:\WebSphere\AppServer7.0\deploytool\itp\plugins\com.ibm.websphere.v7_7.0.1.v20090422_1423\wasJars\naming.jar;C:\WebSphere\AppServer7.0\deploytool\itp\plugins\com.ibm.websphere.v7_7.0.1.v20090422_1423\wasJars\namingclient.jar;C:\WebSphere\AppServer7.0\properties;C:\Batch\CommandFiles\JobServer\Test.jar

C:\WebSphere\AppServer7.0\java\jre\bin\java -jar -cp "%appClassPath%" C:\Batch\CommandFiles\JobServer\Test.jar %Parameters%

NOTE : Please not that I am runnig the client on my local machin and bootstrap host is : localhost and the port is 2809.
At the time of running the Test.jar code form the command file I am getting the following error:

javax.naming.NoInitialContextException: Failed to create InitialContext using factory specified in hashtable {java.naming.provider.url=iiop://localhost:2809, java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory} [Root exception is java.lang.NullPointerException]
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:243)
    at javax.naming.InitialContext.initializeDefaultInitCtx(InitialContext.java:327)
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:357)
    at javax.naming.InitialContext.internalInit(InitialContext.java:295)
    at javax.naming.InitialContext.(InitialContext.java:212)
    at com.uuic.ets.rmi.server.client.Client.main(Client.java:130)
Caused by: java.lang.NullPointerException
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:235)
    ... 5 more

I have no idea that why this code is not able to instantiat the InitialContext(Hashmap env). This same code is running in Websphere application server version 5.1 but having problem in Websphere application server version 7.0.
Answer: Using JARs from WAS_HOME/deploytool for the classpath is not supported.  Try using the documented EJB thinclient with WAS_HOME/runtimes/com.ibm.ws.ejb.thinclient_7.0.0.jar.
Comment: Where can I find IIOP port and hostname? somewhere on WAS8 Admin console?
Comment: @GovindaSakhare Presumably, yes, but I have not used WAS in several years.  If you can't find it, I recommend starting a new question rather than commenting on a 7-year-old answer.


How to stress test web server?

Question: Is there a tool (preferably a web service) that can stress test our site? We're having problems with our site going down once we have about 100 concurrent users. Forums seem to suggest I need to tweak my httpd.conf. I plan to try to tweak httpd.conf, but need to know if the tweaks actually did anything. So stress testing it after each configuration change might be my plan of attack. Suggestions?
Answer: If you're using Apache you can use a utility called ab (Apache Bench).
From the fine manual:

SUMMARY
ab is a tool for benchmarking your Apache Hypertext Transfer Protocol (HTTP) server. It is designed to give you an impression of how your current Apache installation performs. This especially shows you how many requests per second your Apache installation is capable of serving.

It's that last bit that you'll be interested in.
Comment: Example usage: ab -n 100 -c 20 http://...
Comment: these days wrk is more popular... :)
Answer: You could also try JMeter

Apache JMeter may be used to test performance both on static and
  dynamic resources (files, Servlets, Perl scripts, Java Objects, Data
  Bases and Queries, FTP Servers and more). It can be used to simulate a
  heavy load on a server, network or object to test its strength or to
  analyze overall performance under different load types. You can use it
  to make a graphical analysis of performance or to test your
  server/script/object behavior under heavy concurrent load.
Answer: You can try siege, very simple and powerfull tool. By the way check limit of clients in apache.conf, look for "MaxClients" parameter.
Comment: For openSUSE, it is available via the [Benchmark](http://download.opensuse.org/repositories/benchmark/openSUSE_12.3/) community repository
Answer: There are a few nice sites out there for testing, if you are looking for a web service for load testing. To name a few...
http://www.gomez.com/  (Paid service)
http://loadimpact.com/ (free up to 50 virtual users)
https://browsermob.com/website-load-testing ( free basic account)
Answer: You can use the curl library for stress testing.
Comment: How would you do that ?
Comment: Using CURL you can programmatically create heavy load and induce Race conditions as well. There might be other tools as well, if you are totally new to CURL, you might as well learn a newer framework. Go through this link as a starting point http://brainflush.wordpress.com/2008/03/18/using-curl-for-testing-web-applications/
Comment: I can understand the DOWN Vote but there are things you can ONLY do with CURL which other UI testing frameworks dont provide.
Comment: I'll give you a +1 to counter the slight unfair -1. Yes, you can write your own testing library with libcurl, but it's probably quite a effort given the readily available tools which do the job already.
Comment: An example of how to do it would would help.
Comment: This link shows some examples of curl -s with parameters http://servermonitoringhq.com/blog/how_to_quickly_stress_test_a_web_server

How to stress test web server?


É possível atribuir ObjectId() para subcollections no MongoDB?

Question: Imaginem a seguinte collection:
{
    _id:ObjectId("123456..."),
    user:"João",
    artigos:[
        {
            id: new ObjectId(),
            titulo:"Lorem ispsum.",
            texto:"Lorem ipsum dolor sit amet..."
        }
    ]
}

Resumindo: Um usuário pode ter n artigos, que por sua vez precisam de alguma forma de identificação para serem achados em uma consulta.
Só que aparentemente o MongoDB não aceita ObjectId() em subcollections, eu tentei gerar desta forma e ele dispara um erro informando que não foi possível fazer o parse do arquivo JSON. Então minha pergunta é:
É possível adicionar ObjectId() em subcollections? Se não, como eu conseguiria atribuir ids para meus itens dentro desta subcollection?
Comment: Estamos falando de subdocumentos, certo?
Comment: @CiganoMorrisonMendez isto.
Answer: É possível adicionar ObjectId() em subcollections (ou melhor dizendo, subdocuments)?
Sim, mas isso não é muito recomendado, porque considerando que a decisão de arquitetura de dados foi de colocar o dado como um subdocumento, supõe-se que a única chave importante é a do documento pai.
Claro que há exceções. Se por exemplo estamos falando de uma pessoa que tenha n endereços, e só queremos atualizar um deles, e isto é uma operação recorrente. Aí faz sentido ter.
Estou supondo para o exemplo que a declaração do Schema é mais ou menos assim:
Pessoa: {
    enderecos: [
        { _id: ObjectId(), nome: '' },
        ...
    ]
}

Fiz um teste com o seu exemplo e funcionou da seguinte forma:
db.pessoas.insert({
    "_id": ObjectId(),
    "user": "João",
    "artigos": [
        {
            "_id": ObjectId(),
            "titulo": "Lorem ispsum.",
            "texto": "Lorem ipsum dolor sit amet..."
        }
    ]
})

Comment: Mas ai que tá, eu faço isso, mas quando tento adicionar ao banco ele acusa erro, dizendo que esperava uma `string` ou `data`.
Comment: Acho que isso aqui tá errado: `id: new ObjectId()`. Não seria `_id: ObjectId()`?
Comment: Já tentei sem o `new` e também acusa erro. No caso eu já possuo um `ObjectId()` fora desse subdocument (como aparece lá no JSON da minha pergunta), será que é permitido apenas um por document e por isso dispara erro?
Comment: Acho que não. Pode ser apenas um problema sintático. Vou fazer um teste aqui.
Comment: @Kazzkiq Editei minha resposta e coloquei seu teste. Aqui funcionou perfeitamente na shell pura do MongoDB.
Answer: Essa é uma questão de design de documentos. A grosso modo, há duas rotas a se seguir:

incluir o subdocumento (artigo) dentro do documento-raiz (usuario)
linkar/referenciar o documento secundário (artigo) no primário (usuario)

Como você parece precisar de um identificador para cada artigo, eu sugeriria primeiro tentar encontrar um identificador natural, tipo um número único de arquivamento já existente. Se isso não for possível, você pode gerar qualquer identificador único na hora de salvar o artigo pela primeira vez, tipo um UUID/GUID ou alguma string derivada do título e possivelmente data de publicação (ex: id_artigo: "2014_08_03_lorem_imsum").
Se você preferir um número sequencial para esses artigos, uma forma simples de se conseguir isso é criando uma collection auxiliar sequencias que você pode usar para gerar esses números. Eu uso bastante essa técnica com findAndModify():
var contador = db.sequencias.findAndModify({
    query: {'_id': 'artigos'},
    fields: {'_id': 0, 'seq': 1},
    update: {'$inc': {'seq': 1}},
    new: true,
    upsert: true
});
var novo_num = contador.seq;

A alternativa 1 se aplica bem quando os artigos têm apenas um autor/usuário, pois você não duplicará nada:
{
    _id: ObjectId("123456..."),
    user: "João",
    artigos:[
        {
            id_artigo: "2014_08_03_lorem_impsum",
            data: new Date(2014, 07, 03),
            titulo: "Lorem ispsum.",
            texto: "Lorem ipsum dolor sit amet..."
        },
        {
            id_artigo: "2013_12_01_so_um_teste",
            data: new Date(2013, 11, 01),
            titulo: "Só um Teste",
            texto: "Meu primeiro artigo..."
        }

    ]
}

Já a alternativa 2 pode ser usada quando existe a possibilidade de um mesmo artigo ser relacionado a mais de um autor/usuário, evitando muita duplicação de dados:
Artigos:
    {
        _id: "2014_08_03_lorem_impsum",
        data: new Date(2014, 07, 03),
        titulo: "Lorem ispsum.",
        texto: "Lorem ipsum dolor sit amet..."
    }

    {
        _id: "2013_12_01_so_um_teste",
        data: new Date(2013, 11, 01),
        titulo: "Só um Teste",
        texto: "Meu primeiro artigo..."
    }

Usuários:
{
    _id: ObjectId("123456..."),
    user: "João",
    artigos: ["2013_12_01_so_um_teste", "2014_08_03_lorem_impsum"]
}

{
    _id: ObjectId("987654..."),
    user: "Armando",
    artigos: ["2014_08_03_lorem_impsum"]
}


jQuery: how to combine two events: $(document).ready + $("#superid a").hover?

Question: My problem is simple. I can't figure out how to combine two events, that perform the same function.
<code>$(document).ready(function()
{
//do something
});
</code>
+
<code>$("#superid a").hover(function()
{
//do something the same
});
</code>
How to combine it?
Answer: If I well understood
<code>$(document).ready(function() {

   var yourfunction = function() {
      // do something
   }

   $("#superid a").hover(function() {
      yourfunction();
   });

   yourfunction();
});
</code>
Comment: @barlasapaydin then how would you execute a function both at domready and at hover event? I think your downvote is wrong...
Comment: your hover function is inside document ready so you dont need to call that function again, useless.
Comment: @barlasapaydin It is correct this way. (Though you don't need the function in domready)
Comment: @barlasapaydin - you are wrong, and this is the right way to do it. Correctly encapsulates the `yourfunction` method inside the document ready, calls it, and wires up the `hover` correctly.
Comment: Please, who downvoted could explain how can I improve my answer?
Answer: Create a new function and pass it as a callback to both events.
<code>function myAction() { ... }
$(document).ready( myAction );
$( ... ).hover( myAction );
</code>
Comment: The problem with this is that the `hover` event is usually wired up *inside* the `document.ready`!
Comment: You don't always have to, the dom can be ready depending on where you include the script. If its absolutely necessary to wait, @F. Calderan's answer is the way to do it.


After installing any OS (bios is set to UEFI), the boot order constantly changes (windows and linux installs). How can I disable this "feature"

Question: Have numerous different servers (primarily Dell) that we are installing through pxeboot. After the OS is installed the first time, the UEFI boot sequence is automatically changed to allow the OS to load as the first boot option.
This works fine for regular people that want to build a single host one time, but in lab environments where things are continually rebuilt, this causes a large sore. Is there anyway to disable the OS install from changing boot order in UEFI after an install.
This article talks more regarding it
https://arstechnica.com/civis/viewtopic.php?f=21&t=1474353 and it is discussed that it is potetnially the uefi specification but no affirmative answer on this.
Is there a way to not allow the UEFI Boot Sequence to be modified after installing an OS?
Answer: The option to modify efi boot order is in the uefi specification. You could indeed create a firmware that ignores this part, or has an option to reset it. (Reach out to the manufacturer, Dell for this)
As a work around you could reset this from the OS at least in linux you can use efimgr to change the order.
Another option to consider could be that many machines have the option for different boot order depending on network start or not. That is normal startup uses the normal efi order, however if the machine is "started over the network" with WOL then the "network boot order" is used instead. - This could then be used to instead of restart of the machine, shut it down and then start it remotely.
Comment: efimgr was the solution for me
Answer: Made a script which will check if PXE is first boot option and set it in case it isn't:
<code>#!/bin/bash

# Get the current boot order
boot_order="$(efibootmgr -v | grep BootOrder | cut -d' ' -f2-)"

# Get first boot option hex number
first_boot_nr_hex="$(echo "${boot_order}" | cut -c1-4)"

# Get first boot option
first_boot_option="$(efibootmgr -v | grep "Boot${first_boot_nr_hex}")"

# Check if the first boot option is PXE boot
if echo "$first_boot_option" | grep -q "PXE"; then
    echo "PXE boot is already the first option in the boot order"
else
    # Get the list of boot options, excluding PXE boot
    boot_options="$(efibootmgr -v | grep -E "^Boot[0-9]{4}" | grep -v "PXE" | cut -c5-8 | tr '\n' ',' | sed 's/.$//')"

    # Get PXE boot option
    pxe_boot="$(efibootmgr -v | grep -E "^Boot[0-9]{4}" | grep "PXE" | cut -c5-8)"

    # Set the boot order to PXE boot followed by the other options
    new_boot_order="$(echo "$pxe_boot"),$(echo "$boot_options")"
    efibootmgr -o "$new_boot_order"

    echo "PXE boot is now the first option in the boot order"
fi
</code>


Segmentation fault, although the code is never executed?

Question: I have just started learning C and was looking into simple implementations of linked lists. When I tried printing my list I realized something peculiar. I would get segmentation errors at a part of the code even if that code was never executed. How can this be?
To my knowledge the while loop is never executed as the next pointer does not point at anything. I was thinking that maybe when evaluating the while loop it may cause it to point at something that causes the segmentation error, but strangely if you remove the line root = root->next it executes fine (without any errors). Even then it never enters the while loop. So how can a line of code (root = root->next cause an error if the code is never executed? The code compiles just fine. Have I made a simple mistake somewhere?
I know this is not nearly a proper implementation for a linked list, it was made for learning purposes.
#include <stdio.h>
#include <stdlib.h>

struct linkedlist   {
    int value;
    struct linkedlist * next;
};

typedef struct linkedlist item;

int main(int argc, char **argv) {
    item * root;
    item * current;

    root = malloc(sizeof(item));
    root->value = 500;

    int i;
    for(i = 0; i <= 20; i++)    {
        current->next = malloc(sizeof(item));
        current = current->next;
        current->value = i;
    }

    while(root->next != 0)  {
        //This is never executed
        printf("[%d]\n", root->value);
        //the line below does cause the segmentation error
        //but how can this affect anything at all if this is never executed?
        root = root->next;
    }
    return 0;
}

Answer: The first line with current->next is dereferencing an uninitialized pointer. You probably forgot to initialize current to root before the loop. Derefencing an uninitialized pointer is undefined behavior (UB) which means anything can happen. In practice, the uninitialized variables will have values corresponding to whatever contents was stored at their memory location. So an uninitialized pointer will be be set to some semi-random address and will either point to some also semi-random contents in memory (possibly other program variables) or be invalid.
There is another uninitialized pointer being dereferenced in the condition for the while loop testing root->next. Generally, you should make sure that the next field of each of your list item (including root) is set to 0, else you won't be able to detect the end of the linked list (uninitialized pointer again, so UB again and in practice the value is likely to be different from 0).
A proposal to correct this kind of problem in your code:
#include <stdio.h>
#include <stdlib.h>

struct linkedlist   {
    int value;
    struct linkedlist * next;
};

typedef struct linkedlist item;

int main(int argc, char **argv) {
    item * root;
    item * current;

    root = malloc(sizeof(item));
    root->value = 500;
    root->next = 0;

    current = root;

    int i;
    for(i = 0; i <= 20; i++)    {
        current->next = malloc(sizeof(item));
        current = current->next;
        current->value = i;
        current->next = 0;
    }

    while(root->next != 0)  {
        printf("[%d]\n", root->value);
        root = root->next;
    }
    return 0;
}

Comment: root->next is also never initialized prior to the while loop.
Comment: @dani-h dereferencing an uninitialized pointer is undefined behaviour, so you should not make any conclusion based on whether your problem crashes or not.
Comment: But if I uncomment the line root=root->next; and enter a prinf statement in the end it executes without crashing.
Comment: @OldProgrammer Can I check that in the while loop somehow? while(root->next != NULL) ?
Comment: @plabatut Can you make that a little more clear please?
Comment: Undefined behaviour means everything can happen, including it will crash or look work right.