NullPointerException getSupportFragmentManager() with Facebook onSessionStateChange

Question: I am using the Facebook SDK to do a FB login. Sometimes I receive a random NullPointerException when returning from the Facebook login.
The NPE is on my line:
FragmentManager fm = getActivity().getSupportFragmentManager();

My FB login is in a single Fragment. When the user logs into FB and is successful, it changes the Fragment to another. Why am I getting this NPE?
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        Log.i("Facebook", "Logged In");
        mPrefs.setFbLoggedIn(true);

        Request.newMeRequest(session, new Request.GraphUserCallback() {
            @Override
            public void onCompleted(GraphUser user, Response response) {
                if (response.getError() == null) {
                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    FragmentTransaction ft = fm.beginTransaction();
                    ft.setCustomAnimations(R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left,
                            R.anim.slide_in_right_to_left, R.anim.slide_out_right_to_left);
                    ft.remove(fm.findFragmentById(R.id.container));
                    ft.add(R.id.container, LoadingFragment.newInstance(), "loadingFragment");
                    ft.commit();

                    String fbId = "";
                    try { fbId = user.getId(); }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    String fullName = "";
                    try { fullName = user.getName(); }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    String email = "";
                    try { email = user.getProperty("email").toString(); }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    String gender = "";
                    try { gender = user.getProperty("gender").toString(); }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    String pictureUrl = "";
                    try { pictureUrl = "http://graph.facebook.com/" + user.getId() + "/picture?type=large"; }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    String birthdate = "";
                    try {
                        if (user.getBirthday() != null && !user.getBirthday().isEmpty()) {
                            try {
                                DateTime dateTime = DateTime.parse(user.getBirthday(), DateTimeFormat.forPattern("MM/dd/yyyy"));
                                DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")
                                        .withZone(DateTimeZone.getDefault());
                                birthdate = formatter.print(dateTime);
                            }
                            catch (IllegalArgumentException e) { e.printStackTrace(); }
                        }
                    }
                    catch (NullPointerException e) { e.printStackTrace(); }

                    User u = new User(fbId, email, fullName, gender, birthdate, pictureUrl);
                    FacebookMethods.writeFbInfo(getActivity(), u);

                    ((MainActivity)getActivity()).connectToServer();
                }
                else {
                    Toast.makeText(getActivity(), response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }).executeAsync();
    }
    else if (state.isClosed()) {
        Log.i("Facebook", "Logged Out");
        mPrefs.setFbLoggedIn(false);
    }
}

Stacktrace (not full, but the important lines)
java.lang.NullPointerException
   at com.walintukai.lfdate.LoginFragment$2.onCompleted(LoginFragment.java:278)
   at com.facebook.Request$1.onCompleted(Request.java:303)
   at com.facebook.Request$4.run(Request.java:1726)
   at android.os.Handler.handleCallback(Handler.java:733)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:136)
   at android.app.ActivityThread.main(ActivityThread.java:5050)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
   at dalvik.system.NativeStart.main(NativeStart.java)

Comment: Simply return from your method if getActivity() returns null
Comment: If it's on this line, it means `getActivity()` is null. It will happend if your `onCompleted` method gets called after your Activity being stopped/finished. Paste your full StackTrace
Comment: @SimonMarquis I don't have the full stacktrace, but here are the first set of lines. Is this enough?
Comment: definitively, your Activity is stopped. It will happend every time you press the back button too early. Your activity is stopped, onCompleted is called, getActivity() is null -> NullPointerException
Comment: @SimonMarquis Explained very well! Thank you. So, to reiterate, the user is logging in with FB, and then when returning to my app, they pressed the back button too early before `onCompleted` was called? What would be the best way to put in an error check for this?
Comment: @SimonMarquis Makes perfect sense! Thanks for the help! Please make an answer so I can accept it!
Answer: The getActivity() here can return null if the Activity was stopped (back button, home, recent, ...).
To avoid error simply stop the method early:
   Request.newMeRequest(session, new Request.GraphUserCallback() {
        @Override
        public void onCompleted(GraphUser user, Response response) {
            if (getActivity() == null) {
                // The activity was stopped
                return;
            }
            // else we can continue
            // ...
        }
    });


Tcl [list a b c] vs {a b c} is there a difference and in what context?

Question: I'm playing around with Tcl and have found several scenarios where [list a b c] is interchangeable with {a b c}.  What is the preferred method, and where does [list a b c] fail to match the behavior of {a b c}?
Answer: % set lista [list a b c]
a b c
% set listb {a b c}
a b c
% set b {1 2 3}
1 2 3
% set lista [list a $b c]
a {1 2 3} c
% set listb {a $b c}
a $b c

When you are building a list using literals, the two forms are equivalent.  When you are using variables, the [list ...] form will expand the variable before placing it in the string and the {...} form will not.
Essentially, {...} treats whatever is inside of it as a single, continuous string;  the special character $ is never interpreted.  The [list ...] statement takes its arguments and concatenates them together, separated by spaces.  Therefore, if the items you are working with are string literals and do not contain anything that needs to be interpreted, then the two forms are the same.
Comment: maybe worth comparing to 'set list c "a $b c"' as well
Answer: For literals, they're identical in all functional respects (other than that the straight literal form is slightly faster, of course). For non-literals, they're obviously doing different things (as bta says).
However, there's more to it than that. Let's dive deeper!
There are cases where you do not want to use the {…} or the "…" forms, and that's exactly when working with certain non-literals. In particular, if you are using tcom or Tcl/Java (i.e., Jacl or TclBlend) then you will be working with objects that do not obey Tcl's semantics properly. In particular, you'll have "fragile" objects attached to some of the values; if the Tcl_Obj containing the reference to the value has its type changed ("shimmered" in Tcl parlance) then the reference to the underlying COM or Java object will be irretrievably dropped and the garbage collector will delete the object before you're finished with it. Using the [list …] form to build lists (and list operations like lindex to retrieve) will ensure that these fragile internal representations are maintained correctly until you no longer need them.
For normal Tcl values, including those produced by most extension packages, you don't need to worry about this other than to note that using the non-lossy operations is also faster. If you want your code to be quick (who doesn't?) then [list] is your friend even when it is not necessary (which it often is).
The other case you want to pay attention to is when producing callbacks.
Often you want to do callbacks where some values are known at the point when the callback is created, and not otherwise stored in some variable that exists when the callback is executed. (I do this a lot with after, fileevent and trace, but there are lots of places where this is done.) Callback scripts that are created with list (or some other list-producing command) are faster than all the other alternatives because the Tcl script evaluation engine can prove that they have no substitutions and go directly to feeding the list elements into the command dispatcher. This is quite an advantage when you're just passing values to a procedure, which is considered good practice for callbacks.
Comment: There's also JTcl, which is a successor to Jacl. Not worth editing the post to add it in though.


Can a linear regression be significant if the data is not linear?

Question: I performed a linear regression which came out with a significant result however when I checked the scatter-plot for linearity I was not confident that the data was linear.
Are there any other ways to test for linearity without inspecting the scatterplot?
Could the linear regression be significant if it wasn't linear?
[Edited to include scatterplots]
Comment: See https://stats.stackexchange.com/search?q=anscombe+quartet for a classical set of simple examples.  At https://stats.stackexchange.com/a/152034/919 I posted an algorithm capable of constructing examples to suit almost any circumstance you can think of.
Comment: There can be multiple interpretations of the questions and multiple answers (but basically the answer is yes in all cases, and as your outcome proofs it is certainly possible in your case). Can you show the scatterplot? Then others can understand what you mean by data not being linear and in what sense the significant result turned out to be present anyway.
Comment: Of course *ignoring* nolineararity, even when the general trend is linear can lead to compromised inference in application. For example, if the true relationship is that $Y$ drops sharply, then flattens out across $X$, the *linear* interpretation of the is that $Y$ drops by some average amount over *all* values of $X$, whereas the true relationship is that $Y$ drops much more sharply over a much narrower range of $X$, and over the remaining range of $X$ is more or less unaffected. The linear interpretation would be bad for clinical treatment effects, or for policy expenditure effects.
Comment: Also: *linear regression* isn't significant or not, but rather tests of, for example, $H_{0}:\beta_{0} = c$, $H_{0}:\beta_{x} = c$, $H_{0}:F = c$, $H_{0}:R^{2} = c$ may be significant or not, with some degree of independence.
Comment: Thanks for the responses and apologies for the slow response - I've been away from technology! I've edited the post to include scattergraphs for those regressions that were significant.  Any advice on how to proceed would be greatly appreciated.
Comment: @IntoTheBlue How do you wish to proceed? Your data can be modeled by a linear relationship (it looks a bit like a triangular shape, for higher $y$ you got lower variance and mean for $y$). How is this a problem for you? What is the point?
Answer: Monotonic nonlinear relationships will almost always show up significant when modeling as linear models. If the relationship is nonlinear and not monotonic then it depends on the sample.
Examples of monotonic relationships is logarithm $y=\ln x$ and odd powers such as $y=x^3$. Example of non monotonic relationships are even powers $y=x^2$ and trigonomtric functions such as $y=\sin x$.
For instance, if your sample is for $x\in[-1,1]$, then $y=\sin x$ modeled as $y\sim x$ will likely be significant, see the plot:

However, if your sample is in $x\in[0,\pi]$, then linear modeling will not work at all:
Comment: @whuber, edited my answer, but one must agree that  $\ln x$ is dull and tedious compared to buoyant and joyful $\sin x$
Comment: +1.  But please note that the correct term is "monotonic."  "Monotonous" means dull and tedious through repetition.
Comment: +1 I'd also suggest defining what monotonic means.
Comment: Thankyou, I've updated the post to include scatterplots.  Any advice on how to proceed would be greatly appreciated.
Comment: I don't know if there's a test for linearity per se. You could add nonlinear regression terms and test their significance, e.g. $(x-\bar x)^2$.
Answer: Yes, Aksakal is right and a linear regression can be significant if the true relationship is non-linear. A linear regression finds a line of best fit through your data and simply tests, whether the slope is significantly different from 0.
Before trying to find a statistical test for non-linearity, I would suggest  reflecting on what you want to model first. Are you expecting a linear (non-linear) relationship between your two variables? What exactly are you trying to uncover? If it makes sense to assume that there is a non-linear relationship as for example between car speed and braking distance, then you can add squared terms (or other transformations) of your independent variable.
Also, a visual inspection of your data (scatterplot) is a very powerful method and an essential first step in your analysis.
Comment: @Alexis You'r right.  But adding a quadratic term is still a commonly-seen recommendation in some texts as a quick-and-dirty way to check for nonlinearity (understanding nobody is suggesting it is the only or even the first way to model nonlinearities), so I'm not quite as concerned about that passage.
Comment: Almost got my up-vote until "then you can add squared terms (or other transformations) of your independent variable". A quadratic relationship is just as arbitrary as a linear relationship. I think non-parametric regressions which make much more generalized assumptions about the functional form relation $Y$ to $X$ (followed by linear and/or nonlinear regression as appropriate if parametric estimates are needed), or algorithmic curve-fitting (e.g., fractional polynomials), possibly even shifting to maximal information coefficient approaches for generalized beyond even functional relationships.
Comment: Also: Welcome to CV, Pawel!
Comment: +1 @whuber Sadly, I've encountered many researchers, students and faculty practicing adding a quadratic term as the first check beyond eyeballing a scatter plot as "how to test for nonlinearity", with a negative result being interpreted as "linear is sufficient". (Quadratic terms can indeed be useful, and I have used them in my own research. :) I guess my perspective on "quick and dirty" is that the stuff that gets taught as easy, becomes *de rigour* for the overwhelming majority of researchers... I think nonparametric regressions are about as "easy" as linear and a better tool for exploring.
Comment: @Alexis Thank you. I think you have misunderstood me. I wasn't recommending to add squared terms to test for non-linearity but there definitely can be made cases for squared terms (or other transformations. economic data are often log-transformed). I think there needs to be a distinction between exploratory and explanatory analysis. If there are substantiated grounds to assume a squared relationship then this needs to be tested. What you are proposing is a more exploratory approach.
Comment: It really depends on the aims of the analysis, the research design and the data.
Comment: Thankyou for the reply.  I've updated the post to include the scatterplots for significant regressions and would be greatful for any advice on how to proceed.
Answer: I agree with everything Aksakal says.  But as to the first question I think the answer is correlation.  Correlation measures the extent to which there is a linear relationship between the data sets x and y.
Comment: By "first question", do you mean, "Are there any other ways to test for linearity without inspecting the scatterplot?"? If so, how would correlation be an answer & "everything Aksakal says" be correct at the same time? Eg, $y=\ln x$ is not linear, but will yield a significant correlation, as Aksakal correctly notes. Thus, correlation couldn't be an answer. Can you clarify what you are saying here?
Comment: The OP "performed a linear regression which came out with a significant result", but the scatterplot implied the relationship was not linear. A correlation would likely also have been significant, in fact, if the regression had only 1 X-variable, the p-values from the regression & the correlation would be identical. But if the relationship wasn't linear despite the significant regression, it would still not be linear despite the significant correlation. Thus, a significant correlation is not evidence that the relationship is linear.
Comment: Moreover, you won't get $r=1$ unless the relationship is deterministic. Thus, you can very well have linear relationships w/o finding $r=1$. That is, checking if the value of $r$ is $1$ isn't a good way to determine this either.
Comment: This may sound overly subtle or even nitpicking, but (a) I agree that correlation is a way to measure linearity of a bivariate relationship--that's a mathematical theorem, after all--but (b)  as a general proposition, I doubt that it could be construed as any more than an extremely crude way to assess *nonlinearity.*  Evidence of nonlinearity can be striking in a dataset with high absolute sample correlation and be completely absent in a dataset with small absolute correlation.  (cc @gung)
Comment: @gung Yes I do. What statement of his do you consider incorrect ?  Allow me to suggest that I understand what the words linear and non-linear mean and that, as in Aksakal's answer, it is really easy to find examples of variables with an exact and non-linear relationship. Nonetheless, correlation is a measure of the linear relationship and a correlation of +/-1 means that the relationship is indeed linear. Any correlation less than that means that the relationship is (not exactly) linear but it may be close enough.


Searching by sku number but some products and new product are not showing using search api drupal 7

Question: Some products are showing by sku number but some products are not showing.please someone help me to solve this problem.
Comment: Welcome to Drupal Answers! You need to provide more details in your questions, or it is rather hard to answer them.
Answer: This is probably due to indexing by the search module. You need to run cron in order to build the search index.


A question to Flash experts from a beginner: the flash object within a web page

Question: Here's my explanation of the question:
From JavaScript, you need to get a reference to the Flash Player object. There are two basic Flash Player versions that run in the browser: ActiveX and the plug-in version. The ActiveX version runs natively in Internet Explorer, while the plug-in version is used by the rest of the browsers.
The ActiveX player is controlled by the object tag in an HTML page, and you can retrieve a JavaScript reference using window. objectId where objectId is the value of the id attribute of the object tag. For example, if the object tag's id attribute is example, then the reference to the ActiveX player would be window.example.
The plug-in player is controlled by the embed tag in an HTML page, and you can retrieve a JavaScript reference by using window.document. embedName, where embedName is the value of the name attribute of the embed tag. For example, if the embed tag's name attribute is example, then the reference to the plug-in player would be window.document.example.
And here's the question itself:
Why does the Flash Player Object exist as a window property when embeded via the object tag, while, when embeded via the embed tag, it exists in the window.document property? And what is the most modern way of getting the Flash Player Object from within a web page?
Answer: The answer is embedded in the question itself. IE uses object tags and hence SWF is a window object when embedded with object tags. Rest of the world uses embed tags and hence SWF is a property of the window.document for them.
Comment: Excuse me, but it doesn't simply work in my IE 6 when I try to get the object like so: var o = window.flashId; But when I get the object like so: var o = window[flashId]; or like so: var o = document[flashId]; - it works in my IE 6. So, how on earth do people get the object??? How to do it right?
Answer: Today I got a funny things. I use the common way to embed a flash in my blog.
<object id="flashObject" width="290" height="100" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000">
    <param name="movie" value="javascriptcallflash.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="always" />
    <embed name="flashObject" width="100%" height="100%" wmode="transparent" allowScriptAccess="always" width="290" height="100" type="application/x-shockwave-flash" src="javascriptcallflash.swf"/>
</object>

And I also use the common way to get the flash reference:

The problem is that after I publish the post. It doesn't work. So I have try to replace window[movieName] to window.document[movieName]. Then it works. It's very weird.
What's the different between window[movieName], document[movieName], and window.document[movieName]?
Answer: swfobject.js still does this most reliably. So much so that it's been adopted by Adobe as the default embedding script.


Reverting a custom view

Question: I am working on an app that utilizes a custom view,MainView.java which extends View, by setting the view from the MainActivity on an onClick using:
        public void onClick(View view) {
           if(view.getId() == R.id.button){
               MainView = new MainView(this);
               setContentView(MainView);
               MainView.setBackgroundColor(Color.BLACK);
           }
        }

The MainView runs the game and if the player "loses" I want the screen to return to showing the initial activity_main.xml, or any other suitable View. I detect the loss in MainView's update() method.
    private void update() {
    if(lives == 0){
        reset();
    }
    if(score >= lvlScore){
        levelUp();
    }
    for(Projectile proj: balls) {//set positions good balls
        proj.setPosition();
    }
    for(Projectile proj: badBalls){//set positions bad balls
        proj.setPosition();
    }

What I have been unable to even figure out what to do is retrieve information from MainView in my Activity, like the score, and how to revert my custom view back to the initial XML based on something that happens in MainView.
Answer: Just give your MainView a reference to your activity.
in main view...
public void setParentActivity(final Activity activity){
  this.mActivity = activity;
}

altered on click
    public void onClick(View view) {
       if(view.getId() == R.id.button){
           MainView = new MainView(this);
           setContentView(MainView);
           MainView.setBackgroundColor(Color.BLACK);
           MainView.setParentActivity(this);
       }
    }

Comment: That adds tight coupling between a View and the hosting Activity.
Comment: Yeah an interface like you suggested is better for sure. A little more advanced than I thought Worley was looking for since he couldn't figure it out on his own...
Answer: Use an interface to communicate back to the Activity, just as you would for a click listener. For example, in your MainView class:
// Keep a reference to a listener that should be notified of events
private GameEventListener mListener;

// An interface defining events that a listener will receive
public interface GameEventListener {
    void onWin();
    void onLoss();
}

public void setGameEventListener(GameEventListener listener) {
    mListener = listener;
}

private void notifyGameWon() {
    if (mListener != null) {
        mListener.onWin();
    }
}

private void notifyGameLost() {
    if (mListener != null) {
        mListener.onLoss();
    }
}

Then, in your Activity:
// Have your Activity implement the GameEventListener interface
public class MyActivity extends Activity implements GameEventListener {
    public void onClick(View view) {
        if (R.id.button = view.getId()) {
            MainView mainView = new MainView(this);
            mainView.setBackgroundColor(Color.BLACK);

            // Since your Activity implements this interface, you can just
            // set `this` as the listener. Whenever your MainView class
            // calls one of the notify() methods, the implementations below
            // will be triggered.
            mainView.setGameListener(this);
            setContentView(mainView);
        }
    }

    @Override public void onWin() {
        // Reset your view here
    }

    @Override public void onLoss() {
        // Reset your view here
    }
}

Reverting a custom view


Thread com loading em python

Question: Estou tentando executar duas threads onde uma é uma animação de loading, e a outra um print, porém ao terminar de executar a thread work que é o print, o loading continua rodando, gostaria que ele finalizasse assim que o print fosse realizado
import itertools
import threading
import time
import sys

done = False

#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rloading ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

def work():
    print('\nexecutado, finalizando o loading')
    #long process here
    done = True

load = threading.Thread(target=animate)
load.start()
worker = threading.Thread(target=work)
worker.start()

Answer: Sua lógica está certa, na maneira de tentar finalizar uma Thread utilizando outra, mas existe um erro substancial no código, quando você indica dentro da função work que o done = True ele será True apenas dentro da função, quando fui rodar seu código, ao debugar utilizando prints básicos percebe-se que ao entrar na função work ela(a variável), fica verdadeira, mas ao sair retorna pra Falsa. Então o que deve ser feito é, fazer a função work() retornar o valor de done = True, e fora da função consumir esse valor.
import itertools
import threading
import time
import sys

done = False

#here is the animation
def animate():
    for c in itertools.cycle(['|', '/', '-', '\\']):
        if done:
            break
        sys.stdout.write('\rloading ' + c)
        sys.stdout.flush()
        time.sleep(0.1)
    sys.stdout.write('\rDone!     ')

def work():
    print('\nexecutado, finalizando o loading')
    #long process here

    done = True

    return done # Aqui você retorna o valor

load = threading.Thread(target=animate)
load.start()
worker = threading.Thread(target=work)

done = work()  #Aqui você recebe o valor True

worker.start()

Não trabalhei nada no código, só duas linhas, então só com essa adequação ele não terá a saída que desejas, mas pelo menos funcionou quanto a finalizar uma thread com outra thread.
Comment: Beleza mano! Quando coisas assim acontecem, ou você vai conferindo o funcionamento usando debugger da sua IDE, ou vai testando o funcionamento do código linha por linha, inicialmente printando todos os estados duvidosos.
Comment: Muito obrigado irmão, não estava enxergando o erro! :)
Comment: valeu pela dica!!

Thread com loading em python


Need to access dynamic controls ids inside the update panels

Question: I am populating dynamic controls inside the update panel. The steps are
Step 1: Dynamic controls are populated inside dynamic table like this which is inside panel
<asp:Panel ID="pnlShowDDF" runat="server" Visible="False" ViewStateMode="Enabled">
</asp:Panel>

Step 2:
         protected void loadTable()
            {
                HtmlTable tblDDF = new HtmlTable();
                var objDDF = new ddf();

            var dsDdfDetail = "DataSet Loaded"
            if (dsDdfDetail.Tables[0].Rows.Count > 0)
            {
                int RowsCount = dsDdfDetail.Tables[0].Rows.Count;
                for (int i = 0; i < RowsCount; i++)
                {
                    HtmlTableRow tblNewRow = new HtmlTableRow();
                    HtmlTableCell tblDdfCell = new HtmlTableCell();
                    tblDdfCell1.Controls.Add(addCheckbox(dsDdfDetail.Tables[0].Rows[i][0].ToString()));
    //The addCheckbox function returns the checkbox with its text

        tblNewRow.Controls.Add(tblDdfCell);
                    tblDDF.Controls.Add(tblNewRow);
                }
            HtmlTableRow htFooterRow = new HtmlTableRow();
            HtmlTableCell htFooterCell = new HtmlTableCell();

            htFooterCell.Controls.Add(DelButton());
//DelButton() is written in below
                htFooterCell.Attributes.Add("class", "pnlFooterRow");
                htFooterCell.ColSpan = 2;
                htFooterRow.Cells.Add(htFooterCell);
                tblDDF.Controls.Add(htFooterRow);
                }
            pnlShowDDF.Controls.Add(tblDDF);
            pnlShowDDF.Visible = true;
        }
protected Button DelButton()
    {
        var btnDelete = new Button();
        btnDelete.ID = "btnDelete";
        btnDelete.Text = "De-Allocate";
        btnDelete.Click += new EventHandler(btnDelete_Click);
        btnDelete.Attributes.Add("class", "button");
        btnDelete.ViewStateMode = ViewStateMode.Enabled;
        return btnDelete;
    }

Step 3 Need to access dynamic checkbox id from the btnDelete
void btnDelete_Click(object sender, EventArgs e)
    {
        //Need to access the checkbox id's here
        foreach(Control chk in pnlShowDDF.Controls)
        {
            if(chk is CheckBox)
            {
               CheckBox chkbx= chk as CheckBox;
                if(chkbx.Checked)
                {
                   //Here i need to access the id's which i can't right now
                }
            }
        }
    }

Step 4: i have recalled the loadTable function on OnInit but no gains
protected override void OnInit(EventArgs e)
    {
       base.OnInit(e);
        loadTable();
    }

What should be done so that i can access the checkbox id's ??
Comment: Have you tried with `FindControl`...?
Comment: Does the controls exist at this stage of the page? I will give it a try let see.
Answer: Whenever you add dynamic controls, you have to add them in Page_Init event and assign them proper IDs, so that when a postback occurs, those dynamic added controls are created again along with their values and will be accessible in other events, in your case btnDelete_Click.
So what you are missing is assigning IDs to the table cells and rows, I hope you are assigning ID to the checkboxes.
========================= EDIT ============================
Here is the code that is working with me, btnDelete_Click has good enough changes in it. I am getting the checkboxes that I added in and if I check any of them, i get the value as true.
protected void loadTable()
    {
        HtmlTable tblDDF = new HtmlTable();
        //var objDDF = new ddf();

        //DataSet dsDdfDetail = new DataSet();
        //if (dsDdfDetail.Tables[0].Rows.Count > 0)
        //{
            //int RowsCount = dsDdfDetail.Tables[0].Rows.Count;
            for (int i = 0; i < 5; i++)
            {
                HtmlTableRow tblNewRow = new HtmlTableRow();
                HtmlTableCell tblDdfCell = new HtmlTableCell();
                tblDdfCell.Controls.Add(addCheckbox(i.ToString()));
                //The addCheckbox function returns the checkbox with its text

                tblNewRow.Controls.Add(tblDdfCell);
                tblDDF.Controls.Add(tblNewRow);
            }
            HtmlTableRow htFooterRow = new HtmlTableRow();
            HtmlTableCell htFooterCell = new HtmlTableCell();

            htFooterCell.Controls.Add(DelButton());
            //DelButton() is written in below
            htFooterCell.Attributes.Add("class", "pnlFooterRow");
            htFooterCell.ColSpan = 2;
            htFooterRow.Cells.Add(htFooterCell);
            tblDDF.Controls.Add(htFooterRow);
        //}
        pnlShowDDF.Controls.Add(tblDDF);
        pnlShowDDF.Visible = true;
    }
protected Button DelButton()
    {
        var btnDelete = new Button();
        btnDelete.ID = "btnDelete";
        btnDelete.Text = "De-Allocate";
        btnDelete.Click += new EventHandler(btnDelete_Click);
        btnDelete.Attributes.Add("class", "button");
        //btnDelete.ViewStateMode = ViewStateMode.Enabled;
        return btnDelete;
    }
protected CheckBox addCheckbox(string id)
    {
        CheckBox chk = new CheckBox();
        chk.ID = id;
        return chk;
    }
void btnDelete_Click(object sender, EventArgs e)
    {
        //Need to access the checkbox id's here
        foreach (Control chk in pnlShowDDF.Controls)
        {
            if (chk is HtmlTable)
            {
                HtmlTable tbl = (HtmlTable)chk;

                foreach (HtmlTableRow row in tbl.Rows)
                {
                    foreach (HtmlTableCell cell in row.Cells)
                    {
                        foreach (Control chk1 in cell.Controls)
                        {
                            if (chk1 is CheckBox)
                            {
                                CheckBox chkbx = chk1 as CheckBox;
                                if (chkbx.Checked)
                                {
                                    //Here i need to access the id's which i can't right now
                                }
                            }
                        }
                    }
                }
            }
        }
    }

Comment: Yes the addcheckbox(id) function not mention in above code is doing exactly that. I am assigning it. But still no gains
Comment: In btnDelete_Click can you verify that there are rows available in the table, tblDDF?
Comment: The debugger cannot reach the btnDelete_Click. Since this button is also dynamically created. Panel losses all controls on the click event.
Comment: This is strange, if you are assigning ID to btnDelete, than it must be rendered.
Comment: This is why i am stuck and have put the code on here, if something is missing
Comment: In loadTable() method, you have HtmlTableCell tblDdfCell = new HtmlTableCell();             tblDdfCell1.Controls.Add(addCheckbox(dsDdfDetail.Tables[0].Rows[i][0].ToString()));      tblDdfCell1, is it typing mistake? as you have declared tblDdfCell and later using tblDdfCell1
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/16538/discussion-between-shah-and-imran-balouch)


Nginx Redirect all location block to https except 1

Question: I have a nginx config where everything is forced to https. I wanted to add a location block which is served over http. I get a "Too many redirects" with my current config.
Here's the config
# HTTP
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name example.com;

    # redirect non-SSL to SSL
    location / {
        return 301      https://$server_name$request_uri;
    }
    location /blog {
        rewrite ^/blog/(.*)$ /$1 break;

        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_pass http://remote-ip;

        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

#HTTPS server
server{
     listen 443 ssl spdy;
     server_name example.com;

     ssl_certificate /path/to/pem/file/fullchain.pem;
     ssl_certificate_key /path/to/private/key/privkey.pem;

     # performance enhancement for SSL
    ssl_stapling on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 5m;

    # safety enhancement to SSL: make sure we actually use a safe cipher
    ssl_prefer_server_ciphers on;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK';

    # config to enable HSTS(HTTP Strict Transport Security) https://developer.mozilla.org/en-US/docs/Security/HTTP_Strict_Transport_Security
    # to avoid ssl stripping https://en.wikipedia.org/wiki/SSL_stripping#SSL_stripping
    add_header Strict-Transport-Security "max-age=31536000;";

    # If your application is not compatible with IE <= 10, this will redirect visitors to a page advising a browser update
    # This works because IE 11 does not present itself as MSIE anymore
    if ($http_user_agent ~ "MSIE" ) {
        return 303 https://browser-update.org/update.html;
    }

    location /blog {
        return 301 http://$host$request_uri;
    }
    # pass all requests to Meteor
    location /{
        # meteor application config
    }
}

As you can see in the config, all request to block /blog are reverse proxied to another server. I do not want to enforce https here.
As mentioned before, if I go to example.com/blog, I get a "Too many redirects". Other location block is working as expected.
Answer: You cannot do this because you're enabling HSTS and thus telling the browser to only browse your domain via HTTPS. If you need to do this remove this line and clear your browser cache:
add_header Strict-Transport-Security "max-age=31536000;";


What Effect Could Splits or Cracks in a Cricket Bat Have?

Question: I am wondering how much of a different small splits/cracks in the toe of a cricket bat makes I shall add a few photos of the cracks.
The splits aren't very large, and I was wondering if they need to be repaired (I know nothing about bat repairing), or whether they won't really have that much effect? Also, of course, is there a realistic chance of the cracks' getting significantly larger and causing damage?
Comment: I'm asking someone to give up some time in order to help me, so I'll be polite and say "thank you". Also, I'm rather OCD about grammar (:P), and titles should have each word capitalised, except for articles (eg, a), some prepositions (eg with, to), etc.
Comment: Hi Smiley Sam! The use of Hi, Thanks etc is [not encouraged](http://meta.stackexchange.com/q/2950/187824). Also, capitalizing title [are discouraged](http://meta.stackexchange.com/a/98069/187824). That's why I updated your question.
Comment: Actually, if your questions is good (as it is and +1 for it) people who want to answer will answer anyway even when your question doesn't have such politeness. :)
Comment: Fair enough - as in your links, different people prefer different ways of doing it. :)
Answer: Judging by the way the crack is moving up the back of the bat it needs some form of repair or strengthening before it breaks.  Depending on where your based I'd try and find a local bat maker or contact the shop you bought it from to get Kookaburra to look at it.  I've generally found the bigger brands won't deal with you direct, you have to go via the shop.
Judging by the face you've already had this taped at the toe, it's probably worth reapplying some tape if you need to use this while you arrange a repair.
Answer: Yes the bat is damaged, but not irrepairable, if  you have such an issue, a good fix is to sand the bottom, and put a Kevlar toe guard (or get this put on). It will simultaneously hold the toe of the bat together and stop any further moisture getting in.


Use of determinants for vectors - what is the intuition behind it?

Question: I am currently taking a Calculus 3 class. We just began using determinants in the study of vectors. I have some questions as to the apparent 'arbitrariness' of how we use determinants in the study of vectors. How does the determinant of three vectors give the volume of the parallelepiped they form? Similarly, how does the determinant of two vectors yield their cross product?
The professor said that that is the way they have been defined. But such a definition did not seem self-explanatory, and I figured there must have been a deeper reason, perhaps owing to some physical intuition. Also, if determinants had been defined in such a precise manner so that our answer would match what we get using other methods (such as |A||B|sinθ), then how is that definition valid for other more abstract uses of determinants?
I have not yet taken Linear Algebra, so perhaps the reason will become clear to me once I do, but I thought I should know before I proceeded. Thanks.
Answer: Cross products are extremely unintuitive because they have simply been defined to work for our purposes, as your professor said. We basically made up $i$, $j$, and $k$. Then we said
$$i\times j=k,\: j\times i=-k$$
$$j\times k=i,\: k\times j=-i$$
$$k\times i=j,\: i\times k=-j$$
as well as $i\times i=j\times j=k\times k=0$. So we get the orthogonality relations we are so familiar with for cross products. Then, for $a=a_1i+a_2j+a_3k$ and $b=b_1i+b_2j+b_3k$, we get
$$a\times b=a_1i\times(b_1i+b_2j+b_3k)+a_2j\times(b_1i+b_2j+b_3k)+a_3k\times(b_1i+b_2j+b_3k)$$
$$=a_1b_1(i\times i)+a_1b_2(i\times j)+a_1b_3(i\times k)+a_2b_1(j\times i)+a_2b_2(j\times j)+a_2b_3(j\times k)+a_3b_1(k\times i)+a_3b_2(k\times j)+a_3b_3(k\times k)$$
$$=a_1b_2k-a_1b_3j-a_2b_1k+a_2b_3i+a_3b_1j-a_3b_2i$$
$$=(a_2b_3-a_3b_2)i-(a_1b_3-a_3b_1)j+(a_1b_2-a_2b_1)k$$
$$=\det\pmatrix{i&j&k\\a_1&a_2&a_3\\b_1&b_2&b_3}$$
Perhaps the determinant was purposely defined with this in mind, I honestly don't know enough about that or which came first.
Comment: Thanks, that does make sense. Makes me even more curious though -- what came first, the determinant or the cross product? :D
Comment: Isn't the cross product for vectors a, b defined as |a||b|sin, in the  direction othogonal to both a and b - then the relationships between i,j,k follow from this definition - that's inutitive. (orthogonal, I know is ambiguous, we can take it to be the right-hand or left-hand direction).
Comment: No, it is defined the way I have shown, and $|a\times b|=|a||b|\sin\theta$ is derived from that.
Comment: @Ferreroire I should add, although it isn't exactly designed to be intuitive, you can still reason out a little bit of intuition. For example, notice how the $z$ component is completely dependent on the $x$ and $y$ components of the other two vectors. There is reason for that geometrically. Also, I'm looking for a source on which came first and how they were derived, I'll post if I find anything :-)
Comment: Not when I went to school.  If you define it terms of i,j,k  it it restricted to cartesian systems, its quite valid in polar too.
Comment: Determinants came first, in the study of simulatenous equations, long before the notion of vectors came along and long before the vector product was invented.
Answer: My answer will be http://mathinsight.org/relationship_determinants_area_volume
To put short, determinants relates to the volume because determinants IS a combination of cross product and dot product (by definition of cross product), and the two product have a geometric meaning to volume and area. However, I will also provide a non-essential, but helpful, supplement below to make it even (hopefully) more intuitive.
The more detailed and picture rich explanation can be found in the link above. However, I have to make a supplement definition of cross product here, as most people only get an unintuitive and shitty definition that only works for $\mathbb R^3$.
Let $u_1,...,u_{n-1} \in \mathbb R^n$, we define
$$\times(u_1,...,u_{n-1}) := w$$
 to be the unique vector $w$ such that
$$\det[u_1 | u_2 | ... | u_{n-1} | x] = w \cdot x$$
for all $x \in \mathbb R^n$. Specifically, for $n= 3$, the handy dandy formula to calculate the cross product, is not just a formula, it is THE definition. I will give a motivation below.
For simplicity, let $n= 3$, as it is exactly the same for higher dimensions, you just need to write more. Cross product aims at creating a vector that is perpendicular to two give vectors $u_1, u_2$. Assuming you understand the canonical inner product aka dot product $u \cdot v$, we want to find a vector $w$ where
$$w \cdot u_1=0 = w\cdot u_2.$$
In fact any $x = a_1 u_1+a_2 u_2$ should have $w \cdot x = 0$. We now have a function
$$f(x) = w \cdot x$$
The next little bit requires a bit of linear algebra. We already know a function $g(x)$ such that $g(x) = 0 \iff x = a_1 u_1+a_2 u_2$, and that function is the determinant function
$$g(x) = \det M(x)$$
where $M(x) = [u_1 | u_2 | x]$. That is the $3 \times 3$ matrix where the first column is $u_1$, second is $u_2$, and the third is our input vector $x$. Or with $u_k = (u_{k1}, u_{k2}, u_{k3})$ and $x = (x_1,x_2,x_3)$:
$$M(x) = \begin{bmatrix} u_{11} & u_{21} & x_1\\u_{12} & u_{22} & x_2\\u_{13} & u_{23} & x_3\\ \end{bmatrix}$$
So we have
$$f(x) =w \cdot x = 0 \iff g(x) = \det \begin{bmatrix} u_{11} & u_{21} & x_1\\u_{12} & u_{22} & x_2\\u_{13} & u_{23} & x_3\\ \end{bmatrix} = 0$$
So why don't we just let $f(x) = g(x)$, that is take the vector $w$ where $w \cdot x = \det M(x)$ at all values rather than at the roots only. That's how we will define cross product.
It turns out this definition leads to many properties we love about cross product, and it extends to all dimensions, providing a tool to make perpendicular vectors.
Continue in $n= 3$. Again, $\det M(x) = (u_1 \times u_2) \cdot x$ for all $x \in \mathbb R^3$. It turns out the volume of the parallelopiped spanned by $a,b,c \in \mathbb R^3$, up to a sign, is
$$(a\times b) \cdot c$$
which is $\det[a|b|c]$, where $[a|b|c]$ is the $3 \times 3$ matrix with $a,b,c$ as columns, by definition. $(a \times b)$ contributes the bottom area, and $c$ contributes to the height. Explained in the link above.
You might have rows in your definition, but that's ok, as $\det M = \det M^T$. That is if you switch the rows with the columns, the determinant doesn't change.
P.S. Determinants is defined as the unique map that reverses signs when you switch two rows/columns, is multilinear, and preserves common factors in each row/column. The property I described about determinant being 0 is one possible motivation of why we defined cross product that way.


if $\lim\limits_{x\to \infty}x^p\mathbb{P}\{|\xi|>x\}=0$for $p>0$ then $\mathbb{E}|\xi|^r<\infty$ for all $r < p $.

Question: Question
Show that if $\lim\limits_{x\to \infty}x^p\mathbb{P}\{|\xi|>x\}=0$for $p>0$ then $\mathbb{E}|\xi|^r<\infty$ for all $r < p $. Give an example showing that for $r=p$ it is possible that $\mathbb{E}|\xi|^p = \infty$
Know
$\lim\limits_{x\to \infty}x^p\mathbb{P}\{|\xi|>x\}=0 \Rightarrow \lim\limits_{x\to \infty}x^r\mathbb{P}\{|\xi|>x\}=0$ for $r < p$
$\mathbb{E}|\xi|^r<\infty \Rightarrow \lim\limits_{x\to \infty}x^r\mathbb{P}\{|\xi|>x\}=0$
Any hints on how to prove the exercise will be helpful.
Answer: The property follows from the fact that for a non negative random variable $Y$,
$$
EY^r = \int_0^\infty  ry^{r-1}P(Y>y)\,dy.
$$
so in particular
$$
E|\xi|^r = \int_0^\infty  ry^{r-1}P(|\xi|>y)\,dy.
$$
The condition $\lim\limits_{y\to \infty}y^pP\{|\xi|>y\}=0$ implies that
$y^{r-1}P(|\xi|>y) =O(y^{r-p-1})$ from which the result follows.
Answer: I find an example:
$P(X>x)={\frac{1}{x\ln x}}{\mathrm{~for~}}x\geq C{\mathrm{~so~}}F_{X}(x)=1-{\frac{1}{x\ln x}}{\mathrm{~and~}}f_{X}(x)={\frac{1}{x^{2}\ln x}}+{\frac{1}{x^{2}(\ln x)^{2}}}.$
$$
 \begin{aligned}
  \text{Then}\quad xP(X>x)& =\frac{1}{\ln x}=o(1).\text{But}  \\
  &E|X|=\int_{x\geq C}\left(\frac{1}{x\ln x}+\frac{1}{x(\ln x)^2}\right)dx\geq(\ln\ln x)|^\infty_{x=C}=\infty.
 \end{aligned}
 $$


Components that inject `FirebaseApp` result in `No provider for FirebaseApp` message when running tests

Question: When running ng test for my Angular app I get this error message for components that have FirebaseApp from angularfire2 injected into the constructor.

I know for a regular service I would add that services to the providers array for that component spec file or if it was the http service I could add the HttpClientModule to the imports for that spec file but what do I do for Firebase?
Have tried doing this with no luck:
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        AngularFireModule.initializeApp(environment.firebase)
      ],
      declarations: [
        BlogPostComponent,
        HeaderComponent,
        FooterComponent
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(BlogPostComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;
    de = fixture.debugElement;

    fixture.detectChanges();
  }));

Answer: you need to put the FirebaseApp into the providers barrel in your spec
  declarations: [
    ...
  ],
  providers: [FirebaseApp]

and if you need to stub out the values for that app you can do it like this
  declarations: [
    ...
  ],
  providers: [{ provide: FirebaseApp, useValue: someStubHere }]


Help me to parse this kind of json for android

Question: I have this type of json from api:
[
    {
        "id": "12",
        "name": "elo2",
        "status": "ok",
        "vulumes": [
            {
                "id": 17592,
                "name": "vol1",
                "status": "ok"
            }
        ]
    },
    {
        "id": "13",
        "name": "elo",
        "status": "ok",
        "vulumes": [
            {
                "id": "17596",
                "name": "vol2",
                "status": "ok"
            }
        ]
    }
]

ID 12 and 13 its shelf, volumes is a part of shelf with id 17592 and 17596
I cannot to parse it with json, i trying to use gson or json, but i can't understand how to get sime block, for e.g. block with id 12 for parse info about shelf and existing volumes at this shelf.
Can you help me? In other apis i can see named objects vith k/v, but there is nothing.
Answer: With Gson, here's one simple approach you could take.  This demonstrates a Java data structure that matches the JSON example, along with how to deserialize and serialize it using Gson.
public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Type thingsType = new TypeToken<List<Thing>>() {}.getType();
    List<Thing> things = gson.fromJson(new FileReader("input.json"), thingsType);
    System.out.println(gson.toJson(things));
  }
}

class Thing
{
  String id;
  String name;
  String status;
  List<Vulume> vulumes;
}

class Vulume
{
  String id;
  String name;
  String status;
}

Since the attributes of the two object types are almost identical, then maybe the intention was that there be only one object type, with a reference to a collection of objects of the same type.  Here's what that would look like.
public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Type thingsType = new TypeToken<List<Vulume>>() {}.getType();
    List<Vulume> things = gson.fromJson(new FileReader("input.json"), thingsType);
    System.out.println(gson.toJson(things));
  }
}

class Vulume
{
  String id;
  String name;
  String status;
  List<Vulume> vulumes;
}

Comment: Thank you for your reply! An example of the above helped me, I'm right understand that i can get exact key: value from my class in json?


How do I get the height of a tabcontainer using jQuery or javascript?

Question: I have a tabcontainer within an accordion.
If the tab I am on is shorter than the tab I switch to, I have to scroll to see the content on the new tab.
I want to be able to "catch" the height of the tabcontainer when I switch to it and resize the div that contains it.
I thought:
 function clientActiveTabChanged(sender, args) {

         alert(sender.height());
        };

would show me the height, but it doesn't work.
TabContainer is:
 <ajaxToolkit:TabContainer ID="projTabContainer" OnClientActiveTabChanged="clientActiveTabChanged"  runat="server" CssClass="ajax__tab_red-theme">

Answer: The sender passed to the clientActiveTabChanged is not a jQuery object, it is a DOMElement. Try the following:
function clientActiveTabChanged(sender, args) {
  var height = $(sender).height();
  console.log('height is: ' + height);
};

Answer: i think that this will help you : here
$(myJquerySelector).attr('id');

You have just to change the "id" to "height"
EDIT : You can get the target of the event using : event_target
And to pick the id :
 $('TabContainer').change(function(event) {
  var tabContainerID = $(event.target).attr('id');
  alert(tabContainerID);
});

And now you have the id when you click on the tab.
With this id you can find the height easily.
I hope that this will help you.
Comment: Trouble is, I don't know the ID of the element, as the tabcontainer is nested in a repeater. is there a way I can use "sender" to identify the element?
Answer: You can auto re-size the tab container- (Reference: Auto Resize TabContainer)
function clientActiveTabChanged() {
    //get the tabContainer for later reference
    var tc = document.getElementById("<%=tabContainer.ClientId%>");

    //get the index of the tab you just clicked.
    var tabIndex =
         parseInt($find("<%=tabContainer.ClientId%>").get_activeTabIndex(), 10);

    //set the tabcontainer height to the tab panel height.
    tc.childNodes[1].style.height =
         tc.childNodes[1].childNodes[tabIndex].clientHeight;
};

Make the changes in above function as required.


how to show all of user's properties in django

Question: this is my code :
def callback(req):
 token = req.session.get('token', None)
 if not token:
  return render_to_response('callback.html', {
   'token': True
  })
 token = oauth.OAuthToken.from_string(token)
 if token.key != req.GET.get('oauth_token', 'no-token'):
  return render_to_response('callback.html', {
   'mismatch': True
  })
 token = get_authorized_token(token)

 # Actually login
 obj = is_authorized(token)
 if obj is None:
  return render_to_response('callback.html', {
   'username': True
  })
 try: user = User.objects.get(username=obj['screen_name'])
 except: user = User(username=obj['screen_name'])

 user.oauth_token = token.key
 user.oauth_token_secret = token.secret
 user.save()
 req.session['user_id'] = user.id
 del req.session['token']

 s = ''.join('%s: %s
' % (a, getattr(user, a)) for a in dir(user))
 return HttpResponse(s)

and i want use
s = ''.join('%s: %s
' % (a, getattr(user, a)) for a in dir(user))
return HttpResponse(s)

to show the user's properties  ,
but i get a error :
AttributeError at /twitter/login/callback/

Manager isn't accessible via User instances

so what can i do ,
thanks
Answer: You should troubleshoot by using a for loop and finding out where the problem is!
I looped through the User object, and found it doesn't like getattr(user, '_base_manager') or getattr(user, 'objects')
Do you just want the fields, or really all of the python code associated with the user object?
If you just want the fields defined in models.py:
for field in user._Meta.fields:
    print '%s: %s' % (field.name, field.value_to_string(user))

if you want all the magic that dir does
Just do a normal for loop. List comprehensions are not going to catch exceptions any easier.
for attr in dir(user):
    try:
        print '%s: %s' % (attr, getattr(user, attr))
    except Exception, e:
        print '%s: %s' % (attr, e)

If you love your list comprehensions that much
def no_exception_getattr(user, attr):
    try:
        return getattr(user, attr)
    except Exception, e:
        return e

''.join(['%s: %s' % (x, no_exception_getattr(user, x)) for x in dir(user)])

Answer: A cleaner way would be to add an introspective method to your model.
see Django templates: loop through and print all available properties of an object?
and also Iterate over model instance field names and values in template


web2py/pretty ImportError: No module named proj.modules.pretty

Question: I'm trying to import the "pretty" date module http://pypi.python.org/pypi/py-pretty in my web2py application. I unzipped, extracted init.py and renamed it to pretty.py and placed in:proj/modules. I am trying to import it using: local_import ('pretty', reload=True)
But, I get this error: ImportError: No module named proj.modules.pretty
How can I fix this?
Answer: local_import has been deprecated. You should now be able to do:
import pretty

Also, note that web2py includes its own pretty date functionality: http://web2py.com/books/default/chapter/29/14#Pretty-dates
Comment: Now I get this: ImportError: No module named pretty. Thanks for the link, that should solve my immediate need for pretty dates, but I do plan on using modules, so it will be nice to figure this out.
Comment: That probably indicates an error in the pretty.py module itself. Perhaps it is trying to import a dependency that you don't have. Are you able to import it (as is, from its current location) from a standalone Python program? If not, the problem is with the module.
Comment: I created a new file called 'common.py' in the modules directory. All it contains is:

 def add(a, b):
 return a+b

. I use import common in default.py, but I get the same error for common.
Comment: Ok, I figured out the problem - my application directory name was in all uppercase. Everything worked except for the import statement. Once I made it all lower-case, it started working.


How to replace numbers with more user-friendly text in a NumericUpDown?

Question: I want the funcionality of a NumericUpdown (cycle through the 12 possible values) but want to display month names rather than 1..12.
Possible?
Answer: Try using the DomainUpDown control, which is sort of the same thing as NumericUpDown, but for text.
Comment: And DomainUpDown has a "Wrap" property, whereas NumericUpdown does not - so even for numeric stuff it's better!


A question about a detail of proof

Question: proposition:
x∈The Jacobson radical <=> 1-xy is a unit in commutative ring A for all y∈A
I have proved (=>)
I don't figure out a detail of the  proof of (<=).
Here is the proof on book:
suppose x∉m for some maximal ideal m.
then m and x generate the unit ideal (1). (*Why?*It's the only thing I confused about in this proof)
.......
Here is what I thought:
(m) is still (m)
(x)=Ax=mx+(A-m)x=m+(A-m)x
so I only need to prove that (A-m)x=A-m
Then I stuck at here .
Comment: Isn't it just that since $ m $ is maximal, the *only* ideal containing $ m\cup\{x\} $ is the unit ideal?
Answer: By definition $\mathfrak{m} \subset A$ is maximal if and only if for all other ideals $I$ for which $ \mathfrak{m} \subseteq I \subseteq A$ holds, either $I = \mathfrak{m}$ or $I = A$.
The ideal $(\mathfrak{m}, x)$, generated by $\mathfrak{m}$ and $x$ indeed sits in between $\mathfrak{m}$ and $A$ as above, i.e.
$$
\mathfrak{m} \subseteq (\mathfrak{m}, x) \subseteq A.
$$
However, it cannot be equal to $\mathfrak{m}$, as $x \not \in \mathfrak{m}$. Therefore $(\mathfrak{m},x) = A$.

A question about a detail of proof


fetching a webpage using java socket class

Question: Good evening to all of you

I want to fetch a webpage using the socket class in java and i have done this as
import java.net.*;
import java.io.*;

class htmlPageFetch{
        public static void main(String[] args){
                try{
                        Socket s = new Socket("127.0.0.1", 80);
                        DataInputStream dIn = new DataInputStream(s.getInputStream());
                        DataOutputStream dOut = new DataOutputStream(s.getOutputStream());
                        dOut.write("GET /index.php HTTP/1.0\n\n".getBytes());
                        boolean more_data = true;
                        String str;
                        while(more_data){
                                str = dIn.readLine();
if(str==null)
more_data = false;
                                System.out.println(str);
                        }
                }catch(IOException e){

                }
        }
}

But it is just giving the null's.
Output
 HTTP/1.1 302 Found
Date: Wed, 01 Dec 2010 13:49:02 GMT
Server: Apache/2.2.11 (Unix) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8k PHP/5.2.9 mod_apreq2-20051231/2.6.0 mod_perl/2.0.4 Perl/v5.10.0
X-Powered-By: PHP/5.2.9
Location: http://localhost/xampp/
Content-Length: 0
Content-Type: text/html

null

Answer: I'm not sure if this is causing your problem, but HTTP expects carriage return and line feed for a newline:
dOut.write("GET /index.php HTTP/1.0\r\n\r\n".getBytes());

Also, it wouldn't hurt to flush and close your DataOutputStream:
dOut.flush();
dOut.close();

If you plan on doing anything more with this code than just connecting to simple test cases, I'd recommending using HttpURLConnection for this instead of implenting HTTP in a socket yourself. Otherwise, the result will contain more than just the web page. It will also contain the HTTP response including status codes and headers. Your code would need to parse that.
Update:
Looking at the response you added, that 302 response along with the Location: header indicate that the page you are looking for moved to http://localhost/xampp/ (see HTTP 302) and there is no longer any content at the original URL. This is something that is can be set to be handled automatically by HttpURLConnection or another library like Apache HttpClient. You will need to parse the status code, parse the headers, open a new socket to the response Location and get the page. Depending upon the exact requirements of your assignment, you will probably want to familiarize yourself with the HTTP 1.0 Specification, and the HTTP 1.1 Specification as well.
Comment: Ya laz that's true but i want to do this using socket as it is my assignment to parse the output received
Comment: I understand. Then you will need to properly interpret the HTTP status codes and response headers that the URL can return.
Comment: thanks that worked for me as changing the url to "xampp/index.php"
Answer: I think the code is working, except maybe that you don't see the output because it's swamped by all the nulls you print. You should stop the while after the first null.
 More generally, DataInputStream and DataOutputStream are not the right classes for this job. Try this code.
public static void main(String[] args) throws IOException {
    Socket s = new Socket("127.0.0.1", 80);
    BufferedReader dIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
    PrintStream dOut = new PrintStream(s.getOutputStream());
    dOut.println("GET /index.php HTTP/1.0");
    dOut.println();
    String str = null;
    do {
        str = dIn.readLine();
        System.out.println(str);
    } while (str != null);
}

Comment: Hey Flavio ya that is working but i m unable to see the whole page content. only "header" is shown to me and then "null" I have added the output to the question. please check this
Answer: Why are you using socket directly to perform HTTP connection? This is fine exercise but it requires deep knowledge of internals of HTTP protocol. Why not just to use classes URL, and URLConnection?
BufferedReader dIn = new BufferedReader(new URL("http://127.0.0.1:80").openConnection().getInputStream());
do {
        str = dIn.readLine();
        System.out.println(str);
    } while (str != null);
}

Comment: Hey that is fine but i want to do this using sockets as it is my assignment


Change Webform URL

Question: I had successfully submitted a webform. When I click on edit, it will go to this URL "node/254/submission/929/edit". Can I change to "form_a/user_name/edit"?
Answer: No. Using hook_menu_alter() to change the node/%webform_menu/submission/%webform_menu_submission/edit route would break the local task display as it would no longer be a subpath of the node/%webform_menu/submission/%webform_menu_submission route.
Aside from that, even if you created your own custom route that evoked the same webform callbacks, you'd have to deal with the issue that a webform/username alias combo wouldn't be enough information to map to a unique submission (webforms can have duplicate titles, users can submit multiple submissions).

Change Webform URL


Como fazer uma Janela ficar sempre acima das outras no PYQT5?

Question: Estou criando uma pequena aplicação e preciso que a janela principal fique sempre acima das demais, qual atributo usar no pyqt 5 ?
Desde de já agradeço
Answer: Não existe garantia que vá ficar no topo sempre, ainda mais se outros programas usarem do mesmo recurso, eu vou ter que ser um pouco mais sincero a respeito disso, programas no topo sempre me aborreceram, eu sou o usuário, eu sei o que eu quero no topo e o que eu não quero, claro que se for uma opção dentro do programa escolhida pelo usuário seria aceitável usar isso, mas se for forçadamente e não uma opção do usuário eu me recusaria a usar o tal programa.
Voltando a parte técnica, basicamente a flag para deixar no topo é Qt.WindowStaysOnTopHint
<objeto>.setWindowFlags(<objeto>.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)

Troque <objeto> pelo contexto (widget ou QMainWindow) que vai aplicar, lembrando que um mesmo programa pode ter várias janelas, um exemplo básico:
from PyQt5 import Qt, QtCore, QtWidgets
import sys

app = QtWidgets.QApplication(sys.argv)

w = QtWidgets.QWidget()
w.setWindowFlags(w.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
w.resize(800, 600)
w.show()
sys.exit(app.exec_())

Note que usei .windowFlags() para obter as flags padrões, para então com o | "combinar" com QtCore.Qt.WindowStaysOnTopHint.
Quase tudo do Qt em C++ em aplicável de forma semelhante no PyQt5 e como alternativa ao PyQt também existe o pyside, que é bastante semelhante, então consultar a documentação oficial da Qt pode lhe ajudar:

https://doc.qt.io/qt-5/classes.html


OLS and Probit possible on large sample enough?

Question: I think I understood that normality of residuals may not be a problem if the sample is large enough (cf, here).
My question is: Would my sample be large enough to be analysed using a probit and an OLS?
To describe my situation: I am working on a big dataset of some experimental answers. The answers are clearly distributed non normally (bimodal distribution with a majority of 0% and 100%). I want to analyse the dataset using the idea of extensive margin and intensive margin. I have thus two variables: one dichotomous (100% vs not 100%) and one continuous (how much between 0 to 99%). My initial thought would be to use a probit to analyse the first variable (164,000 observations) and an OLS for the second (83,000 observations if I exclude participants declaring 100%).
If there is a need for further information, do not hesitate to ask. Thank you in advance.
Best,
Antoine
Answer: Stata has a wonderful two-part model command, where the first stage is a logit or probit (extensive margin) and the intensive margin can be any GLM. You could even have different covariates for the two parts. The best intro to this type of model is the Deb, Norton, and Manning book. In your case, you could specify a GLM with a binomial distribution and a logit link function, which is the "fractional logit" of Papke and Wooldridge.  The dependent variable for FL is assumed to a proportion in the (0,1) interval.
The syntax would be something:
<code>tpm proportion_var x_var, firstpart(logit) secondpart(glm, family(binomial) link(logit))
</code>
The references:
Papke, L.E. and J.W. Wooldridge (1996) "Econometric Methods for Fractional Response Variables With an Application to 401 (K) Plan Participation Rates," Journal of Applied Econometrics. Vol 11, No. 6, pp. 619-632.
Deb, P, E.C. Norton, and W.G. Manning. 2017. Health Econometrics Using Stata. Stata Press.
Comment: Thanks for the proposition Dimitriy. However, I do not understand what is wrong with my first message. Why your model would perform better than a simple OLS/probit?
Comment: It would work better because your data does not satisfy the distributional assumptions of OLS. You have a bounded outcome on the intensive margin, which OLS would struggle with. You can use a probit instead of the logit if you like with tpm.
Comment: tpm would also allow you to combine both stages and joint calculate marginal effects.
Comment: Thank you very much for all your help. Indeed it sounds very interesting. One last question: why do you specify the family distribution as binomial and the link function as logit for the glm?
Comment: That comes about because the intensive part is a fraction, so you need a fractional logit to handle that.


Running a VNC client without X

Question: Think about a classroom equiped with a linux-KVM server and some tiny PCs (Raspbery Pis, Odroid, and such).
I would like to control a desktop VM on the linux-KVM server from a tiny client with screen, mouse and keyboard.
But I want to do it without installing X on the clients, to keep them as light as possible. Some applications can output full hd video, use mouse, keyboard and network, all without X. Xbmc or RetroArch can. So why not a VNC client ?
Is it only possible ? Does any software allows that ?
Answer: Use VNC Viewers Compiled for Other Graphics Libraries
You need a VNC viewer that uses an alternative graphics library rather than functioning as an X11 client. I'm not aware of any actively-maintained versions that do this, but historically you could use:

DirectVNC, which uses the Linux framebuffer via DirectFB. This port is available in Debian Sid, so it's probably your best bet.
svncviewer, which relies on svgalib. This port has been out of circulation for a while, and was dropped from Debian a long time ago.

There may be other, more programmatic options as well such as go-vnc or Net::VNC. In general, though, VNC is a graphics-oriented protocol that requires a suitable graphics driver to be usable as a point-and-click client.

Running a VNC client without X


Does there exist an uncountably infinite language?

Question: If an alphabet $= \{a, b\}$
I believe an example of a finite language over that alphabet with positive cardinality would be the set equal to $(a+b)^4$
An example of a countably infinite language over the alphabet would be ${a}^*$
But do uncountably infinite languages even exist? Each item (string) of the language is finite, so I believe you could make a one-to-one relationship with the set of integers.
Comment: Of course, there is also a difference between the language and the underlying alphabet. The alphabet $\{0,1\}$ is finite; the language $\{0,1\}^\omega$ of infinite sequences from that alphabet is an uncountably infinite language.
Comment: @Carl: Can you maybe give this a better set of tags? I feel like the proper tags would provide a lot more context.
Comment: *(modified from a comment in Asaf Karagila's recently deleted answer)* Regarding uncountably infinite languages, see my answer to [How to write an individual real number?](https://matheducators.stackexchange.com/questions/13216/how-to-write-an-individual-real-number/13218#13218) in the Mathematics Educators Stack Exchange.
Comment: @Dave: I believe that the question is not about *that* kind of languages, which is why I deleted my answer.
Comment: @Asaf Karagila: I understand, but I think few people outside of logician types are even aware of the existence of such things, and thus our contributions (in my opinion) may be of use for future visitors to this question. I only know about this (in a layman's sense) because Dickmann's 1975 book **Large Infinitary Languages** was on the library shelves when I went away to college (in 1977), and I was fascinated by the fact that people actually could study something like this (although I've seen so much since then that it's no longer THAT fascination to me).
Answer: In elementary computability theory, we usually work with languages that are subsets of $\mathbb{N}$, or which are in bijection with subsets of $\mathbb{N}$, such as languages consisting of finite words over a finite alphabet.
In more advanced levels of computability theory we also look at more general collections, such as collections whose elements are infinite sequences from a finite or countable alphabet.  Like countable languages, we can use Turing machines to define what it means for one of these uncountable "languages" to be decidable, semidecidable, etc.  The more general analogy is via the arithmetical hierarchy.    This allows us to make similar definitions for subsets of $\mathbb{N}$, subsets of $\mathbb{2}^\mathbb{N}$, and subsets of $\mathbb{N}^\mathbb{N}$.
However, it may may not be very common to call these uncountable collections "languages". For example, we are often interested in a "language" consisting of all infinite paths through some computable subtree of the complete binary tree. Rather than calling these "languages", we typically call them "$\Pi^0_1$ classes".


How do I find out which module loads which javascript file?

Question: I have been experiencing script related problems and would like to go through all the script files by disabling/enabling, to find out which is causing the problem.
So I'd like to be able to find out which module loads which javascript file. Then I can go by enabling disabling the modules.
How can I do that?
Comment: @turzifer Am I missing something? Can't you search the Drupal codebase for the filenames you find in the source to see which modules are adding them? Drupal doesn't keep track of which module/theme adds a JS file to the page so other than hacking `drupal_add_js()` with a debug backtrace I don't see how else you'd do it
Comment: If you look at the source of the page you can see the path for each script. This will identify where the script is.
Comment: @AlexGill  You should write that up as an answer.
Comment: I think in firebug and web developer toolbar of firefox also you will find the name and location of javascript which is causing the error.
Comment: Yes, I can find out where all the files are located but that does not help me. I need to find out which module is calling them and this information is not available in the source code -nor in the developer tools, as it is done on the server side.
Answer: "If you look at the source of the page you can see the path for each script. This will identify where the script is."
Example
Typically the script located at...
sites/all/modules/contrib/panels/js/panels.js

...would more often than not only be used by the module of the same name
sites/all/modules/contrib/panels/panels.module

...or possible an include file
sites/all/modules/contrib/panels/includes/SOME_FILE.inc

Obviously bare in mind that Drupal uses the jQuery library so references to errors might fallback to these files just because its been implemented wrong by the developer in the module. Its more than likely never going to be something wrong with the libraries.
/misc/jquery.js
/misc/jquery.once.js

Comment: Note that you have to turn off JS aggregation to see things this way.
Answer: You can get the list of all JS file called for a page to built by a function drupal_get_js(). Though I have never used this or checked but this is what documentation says..
Comment: I would love to find out the reason for negative vote here...
Comment: Because it doesn't *actually* answer the question. OP wants to know which module loads which JavaScript, and you are proposing a solution that just lists all currently loaded JavaScript.
Comment: I don't find any problem with the answer here. If I am facing any problem due to any JS file at any page, I can see what are the JS have been called during loading of the page by help of this function...
I can find the location of all one by one & do what ever I want..
This is the best way to follow from my point of view with comparison to going to each module & finding JS files over there...
Comment: And if you please read the question - He said, he is facing some problem, which usually happens while visiting any page...& want to know the location of the JS files...which my given function can do..

But still you have got reputation & power to down vote...so be it...

Thanks


Degeneracy paradox

Question: Say I have a highly biased coin that lands heads with $p_h=0.01$ and tails with $p_t=0.99$, and I flip it $98$ times.
The probability of zero heads is ${p_t}^{98} \approx 0.373$.
The probability of one head is $98 \times {p_t}^{97} \times p_h \approx 0.370$ as any of the 98 coin flips could have given H.
The probability decreases for larger numbers of heads.
The expected number of heads is $\Sigma xp_{xH} = 0.98$ where $p_{xh}$ is the probability of getting $x$ heads (this is also of course $p_h \times 98$).
But the expected number of heads appears to be different to the most likely number of heads.  How do we account for this?
Is the answer that if I had to bet on how many heads would come up in a single 98-flip experiment, I should place my bet on zero, but if I had to bet on the long run average of many 98-flip experiments I should bet on 0.98?
Comment: In the last sentence, shouldn't it be 0.01 instead of 0.98? Or more precisely, 0.01 times the number of flips?
Answer: You would normally bet on the mode of the outcome distribution, not on the expected value. The mode corresponding to 98 flips is 0, so you would bet on 0.
The mode corresponding to a very large number $N$ of flips will be approximately $N \cdot 0.01$ (rounding will play a very small role for very large $N$), so you would bet on that.
Edit: as pointed out by @CagdasOzgenc, what to bet on depends on the loss function. Expected value works for quadratic loss, while mode works for the principle "if you do not guess right, it does not matter how close your guess was".
Comment: Where to bet depends on your payoff/loss function. If it is MSE then you bet on expected value.
Comment: @ssdecontrol Understanding one of "$\hat y$" and "$y$" to be the bet and the other to be the outcome, and once you adjust that to account for the cost to play and the fact the payoff is not $1$, you would be in agreement with what I wrote :-).  Richard, thank you very much for the clarifying edits (+1).
Comment: Offhand I can't think of any loss function that would imply the mode is an optimum bet, unless the mode coincidentally equals some other value. What specific loss function leads you to this conclusion?
Comment: True, I did not think about different loss functions. My solution works for a game where you pay to play (so the cost is fixed) and can win only if you guess the number right -- like in roulette (when you bet on a number or a color) and the like.
Comment: @whuber, Think of a dice with "1", "2", "3", "4", "5", "5" on its walls (note the "5" instead of "6" in the end!). You pay USD 1 to play. You get USD 3 if you guess the number right; you get nothing if you guess wrong. Naturally, you would always bet on "5", which is the mode of one roll. How should I call the loss function in this example? It should fit my answer.
Comment: The loss function is the difference between the return on the bet and the cost to play.  But your example helps me re-interpret your first line: by "distribution" you seem to refer to the distribution of the *outcome* (rather than of the loss itself). I was confused because--since the expectation often will not be a whole number--it's difficult to imagine how anyone could possibly "bet on" an expected value!
Comment: @whuber, thank you for clarification, I edited my answer. Does it make sense now, or is it still confusing (and perhaps incorrect)?
Comment: @whuber the loss function here would be proportional to $\mathbb{I}\left(\hat y = y \right) = \cases{\begin{align}1, &\quad \hat y = y \\ 0, &\quad \hat y \neq y\end{align}}$

Degeneracy paradox


Windows PC Cannot access shared folder

Question: I need help figuring out why a PC (Windows 10) cannot access any shared folders. This happens to all users logged on to the domain joined PC. The error is "the operation being requested was not performed because the user has not been authenticated"
Thank you
Answer: Two months ago this article helps me when I was in the same spot https://support.microsoft.com/en-us/help/941050/error-message-on-a-windows-vista-based-computer-when-you-try-to-access-a-network-drive-that-is-mapped-to-a-web-share-the-operation-being-requested-was-not-performed-because-the-user-has-not-been-authenticated. Hope this will helps, good luck.
Comment: Referring to the link above, you can also add DWORD key with value "0" (instead of Multi-String Value) to authenticate all servers.

Windows PC Cannot access shared folder


I have warning message with PHP session login when I upload code to the server

Question: I have the login code as below:
<?php
session_start();
if (isset($_GET['action']) && $_GET['action']=='logout' ){
    session_destroy();
    header('location:index.php');
    exit();
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/login_style.css" />
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>

<title>Login</title>

   <form action="index.php" method="post" id="myform" name="log">

        Identifiant:	<input type="text" name="text_username" class="validate[required]" style="border:1px solid #c9bbbb; height:20px; width:180px;"/>

Mot de passe:
    <input type="password" name="text_password"  class="validate[required] TextInput" style=" margin-top:20px;border:1px solid #c9bbbb; height:20px; width:180px;"/>

        <input type="submit" name="tbn_submit" class="btnValider" value="Valider" style=""/>    <input type="reset" class="btnValider" value="Annuler" />

            Nouvel utilisateur?

        </form>
            <?php
             include('include/encriptUrl.php');
             include ('include/connectdb.php');
                if(isset($_POST['tbn_submit'])){
                      $username = $_POST['text_username'];
                      $password = $_POST['text_password'];
                      $query = "SELECT * FROM tblusers WHERE `user_username`='".$username."' AND user_password='".$password."'";
                      $res = mysql_query($query) or die (mysql_error());
                      if($res){
                            if(mysql_num_rows($res)){
                                $user = mysql_fetch_assoc($res);
                                $_SESSION['username'] = $user['user_username'];
                                $_SESSION['password'] = $user['user_username'];
                                    if($user['user_possition'] == "Admin"){
                                        echo '';
                                    }
                                    else if($user['user_possition'] == "User"){
                                        echo '';
                                    }
                                    else if($user['user_possition'] == "R1"){
                                        echo '';
                                    }
                                    else if($user['user_possition'] == "R2"){
                                        echo '';
                                    }
                             }
                             else {
                        echo '';
                        }
                     }
        }
    ?>

Problem:
  I use session to take session of user when login according to my code above it works well in local,but when I upload it to the server I got the warning message Warning: session_start() [function.session-start]: open(c:/wamp/tmp/sess_2m7odit3i1mprbmk1qg5b3j701, O_RDWR) failed: No such file or directory (2) in /homepages/0/d315362104/htdocs/demo/segpp/index.php on line 2 ,Warning: Unknown: open(c:/wamp/tmp/sess_2m7odit3i1mprbmk1qg5b3j701, O_RDWR) failed: No such file or directory (2) in Unknown on line 0 and Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (c:/wamp/tmp) in Unknown on line 0. I do not know how to fix this.
Anyone help me please,Thanks.
Comment: Probably your `ini` file has tampered
Comment: Why are you using an XHTML transitional doctype, what are you transitioning from? Better switch to an HTML 5 doctype.
Answer: Create the directory c:/wamp/tmp/ and make sure it's writeable by the user running the server...
Answer: Thanks so much for your answers, now I solved it as below code:
session_save_path('/tmp');
session_start();

So I just add session_save_path('/tmp');.Than it works well.


using global variables to encode and decode morse using a list of morsecode

Question: Basically I have to make a morse code encoder and decoder using two functions. My professor's template (and of course I have added code to the first function and main function) includes a global variable and I have no idea how to use it. Also I am getting an error for the current code because the letter is somehow an integer not a string letter. Can someone just explain how I could use the global variable in this program, because I am not worried about the errors right now?
MORSE_CODES=[' .- ',' -... ',' -.-. ',' -.. ',' . ',' ..-. ',' --. ',' .... ',' .. ',
' .--- ',' -.- ',' .-.. ',' -- ',' -. ',' --- ',' .--. ',' --.- ',' .-. ',
' ... ',' - ',' ..- ',' ...- ',' .-- ',' -..- ',' -.-- ',' --.. ']

ASCII_A=65 #global var

def encode_Morse(my_msg):
  my_msg_Morse=(my_msg.upper())
  my_msg_Morse=my_msg_Morse.replace(" ","   ")

  for letter in range(0, len(my_msg_Morse)):

    if ord(letter)>=65 and ord(letter)<=90:
      my_msg_Morse=my_msg_Morse.replace(letter, MORSE_CODES[letter])
    else:
      my_msg_Morse=my_msg_Morse.replace(letter,'*')
    my_msg_Morse=my_msg_Morse+" "+letter
  return my_msg_Morse

**#def decode_Morse(my_msg):
my_msg_Morse=my_msg.split("    ")
  string=""
  for word in my_msg_Morse:**

def main():
  my_msg=input("Enter your message: ")
  my_msg=my_msg.upper()
  print("Your message in plain text: ", my_msg)

  my_msg_Morse=encode_Morse(my_msg)
  print("Your message in Morse Code: ", my_msg_Morse)

Comment: Why are you using range? To iterate over all the characters in a string you should do `for letter in my_msg_Morse:`. There are other errors in your code such as `MORSE_CODES[letter])`. `MORSE_CODES` is a list and should be indexed by an integer, not a string.
Answer: Issues

for letter in range(0, len(my_msg_Morse)): does not loop over letters in message
my_msg_Morse=my_msg_Morse.replace(letter, MORSE_CODES[letter]) causes replacement of Morse code letters in messages with spaces (i.e. multiple word messages)
Regarding globals -- just use them if you only need to use their values (which you are here)

Code
MORSE_CODES=[' .- ',' -... ',' -.-. ',' -.. ',' . ',' ..-. ',' --. ',' .... ',' .. ',
' .--- ',' -.- ',' .-.. ',' -- ',' -. ',' --- ',' .--. ',' --.- ',' .-. ',
' ... ',' - ',' ..- ',' ...- ',' .-- ',' -..- ',' -.-- ',' --.. ']

ASCII_A=65 #global var

def encode_Morse(my_msg):
  result = ''
  for letter in my_msg_Morse:
    if 65 <= ord(letter) <= 90:
      if not result:
          result = MORSE_CODES[ord(letter)-ASCII_A]          # first Morse character
      else:
          result += ' ' + MORSE_CODES[ord(letter)-ASCII_A] # space between Morse character
    else:
      result += '*'

  return result

def decode_Morse(my_msg):
    for i, code in enumerate(MORSE_CODES):
        my_msg = my_msg.replace(code, chr(i+65))

    return my_msg.replace('*', ' ')

def decode_Morse_using_counter(my_msg):
    ' Version using counter rather than enumerate to track index '
    i = 0
    for code in MORSE_CODES:
        my_msg = my_msg.replace(code, chr(i+65))
        i += 1

    return my_msg.replace('*', ' ')

def main():
  my_msg = input("Enter your message: ")
  my_msg = my_msg.upper().replace(' ', '   ')  # upper case with 3 letters between words
  print("Your message in plain text: ", my_msg)
  encode_msg = encode_Morse(my_msg)
  print("Your message in Morse Code: ", encode_msg)
  print("Decoded Morse Code: ", decode_Morse(encode_msg))

main()

Example Run
Enter your message: This is a simple message
Your message in plain text:  THIS   IS   A   SIMPLE   MESSAGE
Your message in Morse Code:   -  ....  ..  ... *** ..  ... *** .- *** ...  ..  --  .--.  .-..  . *** --  .  ...  ...  .-  --.  .
Decoded Morse Code:  THIS   IS   A   SIMPLE   MESSAGE

Function Rewrite
Using list comprehension and Walrus operator, the encode_Morse function can be reduced to:
def encode_Morse(my_msg):
  my_msg_Morse = my_msg.upper()
  return ''.join(MORSE_CODES[p-ASCII_A] if 65 <=(p:=ord(letter))<= 90 else '*' for letter in my_msg_Morse)

Comment: thank you, am I going on the right track for the decode_morse function?
Comment: @qwvst--did this help with the encode function?
Comment: @qwvst--not sure what function you are referring in the question: "so i do not need the global function in the decode function".  The decode_Morse is the decode function.  It makes use of the dictionary I created REVERSE_CODE which consists of the morse code letters.  Do you see how the decode_Morse works?
Comment: ok i just saw where you defined the REVERSE FUNCTION. The code seems kind of complicated as I am a beginner and I have not learning about dictionaries yet. I tried to understand but i dont get it, thank you for your help
Comment: @qwvst--the dictionary is used to associate each Morse code sequence to a letter.  To decode we start from the first letter.  We take successive dashes & dots until the sequence maps to a letter (A-Z).  Then we start the process over again.
Comment: Initialize text_string to empty string
Stopping Condition: All codes in MORSE_CODES have been decoded in string Loop Body: Consider each code in MORSE_CODES
Replace code in text_string with the appropriate letter for code
Replace three spaces in text_string with single space to separate words Output text_string     >>>This is the design which I came up with, if you can help me make the code simpler]
Comment: @qwvst--updated the decoder based upon your suggestion.  Does this make sense?
Comment: I just looked up what enumerate does, its basically a counter. So can you do a manual counter instead ?
Comment: @qwvst--yes you can easily use a counter.  Do you need help with that or does it seem straightforward?  But, you should become familiar with `enumerate` since it is the Pythonic approach for looping through a list with an index for each element.  `enumerate is so popular that anyone reviewing your code would question why you're not using it if you tried to use a counter.
Comment: Yes, please I not exactly sure where to place the code. Also, what two things are you looping through? Is it each character and each word in the string?
Comment: @qwvst--added a version that uses counter rather than enumerate i.e. decode_Morse_using_counter.  A reminder is this answer was useful  don't forget to [accept nswer](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)
Comment: One last thing, for formating I need to have three spaces between each word and one space between morse characters, and * if its not in dictionary. Do I need an elif statement that converts the one space into three spaces for the spaces between the words
Comment: @qwvst--modified encode_Morse and main functions.  Does the latest output correspond to what you want?
Comment: I got it, i really appreciate your help and quick response on this! thank and I have accepted the answer:)


Matrix representation with non-standard bases.

Question: In chaprer 2.2 of Fiedberg's Linear Algebra is wroten about matrix representation. But all examples are only with standard ordered bases. I made a task to understand it. Please, could you show me matrix representation on this task or your own example?

Let $$ T\begin{pmatrix}x\\y\end{pmatrix}=\begin{pmatrix}x+y\\x-y\end{pmatrix}$$ is transformation from vector space V with a basis $$ v=   \{ \begin{pmatrix}1\\2\end{pmatrix}, \begin{pmatrix}3\\4\end{pmatrix}\} $$ to vector space W with a basis $$ w=   \{ \begin{pmatrix}1\\4\end{pmatrix}, \begin{pmatrix}2\\3\end{pmatrix}\} $$.
How to find the matrix representation $$ [T]_v^w $$?
Answer: Problem: Let
$$ T\begin{pmatrix}x\\y\end{pmatrix}=\begin{pmatrix}x+y\\x-y\end{pmatrix}$$
is transformation from vector space V with a basis
$$ v=   \{ \begin{pmatrix}1\\2\end{pmatrix}, \begin{pmatrix}3\\4\end{pmatrix}\} $$ to vector space W with a basis
$$ w=   \{ \begin{pmatrix}1\\4\end{pmatrix}, \begin{pmatrix}2\\3\end{pmatrix}\} $$. Find $[T]_v^w$ for $T: \mathbb{R}^2 \rightarrow \mathbb{R}^2$ as given.
Solution: there is a simple way to calculate for given examples. Basically, for each domain basis element (in $v$) we need to express it as a linear combination of the basis of the codomain ($w$). Let's begin:
$$ T(v_1)=T(1,2) = (1+2,1-2) = (3,-1) = A_{11}w_1+A_{21}w_2 \qquad \star$$
where $w_1 = (1,4)$ and $w_2 = (2,3)$. Likewise,
$$ T(v_2)=T(3,4) = (3+4,3-4) = (7,-1) = A_{12}w_1+A_{22}w_2 \qquad \star^2$$
So we must solve $\star$ and $\star^2$ for $A_{ij}$. That is,
$$ (3,-1)=A_{11}(1,4)+A_{21}(2,3) \ \ \& \ \ (7,-1)=A_{21}(1,4)+A_{22}(2,3)$$
These can be solved in many ways, for example:
$$ \left[ \begin{array}{c} 3 \\ -1 \end{array}\right]  = \left[ \begin{array}{cc} 1 & 2 \\ 4 & 3 \end{array}\right]\left[ \begin{array}{c} A_{11} \\ A_{21} \end{array}\right] \ \ \& \ \
\left[ \begin{array}{c} 7 \\ -1 \end{array}\right]  = \left[ \begin{array}{cc} 1 & 2 \\ 4 & 3 \end{array}\right]\left[ \begin{array}{c} A_{21} \\ A_{22} \end{array}\right]$$
reduce to a single matrix equation
$$ \left[ \begin{array}{cc} 3 & 7 \\ -1 & -1 \end{array}\right]  = \left[ \begin{array}{cc} 1 & 2 \\ 4 & 3 \end{array}\right]\left[ \begin{array}{cc} A_{11} & A_{12} \\ A_{21} & A_{22} \end{array}\right]$$
which I solve by multiplication by inverse
$$ \left[ \begin{array}{cc} A_{11} & A_{12} \\ A_{21} & A_{22} \end{array}\right] =
\frac{1}{-5}\left[ \begin{array}{cc} 3 & -2 \\ -4 & 1 \end{array}\right]\left[ \begin{array}{cc} 3 & 7 \\ -1 & -1 \end{array}\right]  = \frac{1}{-5}\left[ \begin{array}{cc} 11 & 23 \\ -13 & -29 \end{array}\right] = [T]_v^w.$$
Let $\Phi_v: \mathbb{R}^2 \rightarrow \mathbb{R}^2$ be the coordinate map defined by linearly extending $\Phi_v(v_i)=e_i$ and likewise $\Phi_w (w_i)=e_i$ for the standard basis $e_1=(1,0)$ and $e_2 = (0,1)$. Then I also denote $\Phi_v(x) = [x]_v$ and $\Phi_w(x) = [x]_w$; the coordinate charts with respect to bases $v$ and $w$ respective. Given all this notation the meaning of $[T]_v^w$ is simply that it is the matrix which acts as $T$ when we swap vectors in the domain and codomain for their corresponding coordinate vectors. That is:
$$ [T]_v^w[x]_v = [T(x)]_w $$
To actually calculate the coordinate charts (and hence the matrix of $T$) it generally requires we solve some systems of equations because it it not immediately obvious how to express $T(x)$ in the $w$-basis. I have examples and more discussion in a notation pretty close to the one I use here at:my linear algebra lectures on You Tube.
Comment: @facelesswanderer now that I fixed it, sadly my (wrong) integer answer has become cluttered with fractions. It's funny when the wrong answer is nicer.
Comment: Thank you so much for the detailed and distinct answer!
Comment: I've read your message again. Thank you so much for detailed answer, it really helped me. But Ifound a mistake in sentence $$ \left[ \begin{array}{c} 3 \\ -1 \end{array}\right]  = \left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array}\right]\left[ \begin{array}{c} A_{11} \\ A_{21} \end{array}\right] \ \ \& \ \
\left[ \begin{array}{c} 7 \\ -1 \end{array}\right]  = \left[ \begin{array}{cc} 1 & 2 \\ 3 & 4 \end{array}\right]\left[ \begin{array}{c} A_{21} \\ A_{22} \end{array}\right] $$ It's true for basis $$ w=   \{ \begin{pmatrix}1\\3\end{pmatrix}, \begin{pmatrix}2\\4\end{pmatrix}\} $$
Comment: But in the task $$ w=   \{ \begin{pmatrix}1\\4\end{pmatrix}, \begin{pmatrix}2\\3\end{pmatrix}\} $$ It's not problem for me, I've all understood. I wrote it for other people to not muddle up.
Comment: @facelesswanderer you're right. I should fix this for future readers. Thanks. I'll edit it now.
Answer: I suggest you to procede in the following way: let $V$ your vector space, and $\mathcal{B}$, $\mathcal{D}$ two different basis. You can calculate first the matrix $A$ associate to $T$ respect the canonical base $\mathcal{E}$. Then you can easily compute the matrix $M$ associate to the change of coordinates from $\mathcal{B}$ to $\mathcal{E}$ and finally the matrix $N$ associate to change of coordinates from $\mathcal{E}$ to $\mathcal{D}$.
Then the matrix associate to $T$ respect $\mathcal{B}$ and $\mathcal{D}$ is the matrix obtain by the following product:
$$[T]_{\mathcal{B}}^{\mathcal{D}}=MAN.$$
PS: I'm sorry, I change your notation.


What is the probability of two donuts picked are of the same type?

Question: A box contains two chocolate donuts, three cake donuts, and four sprinkle donuts. If two donuts are drawn from the box at random without replacement, what is the probability that the two donuts are of the same type?
Comment: What have you tried ? What is the Pr of drawing 2 chocolate donuts *without replacement* ? Can you not continue ?
Answer: $Pr(\text{ 2 donuts of the same type }) = Pr(\text{ 2 chocolate donuts})+Pr(\text{ 2 cake donuts })+ Pr(\text{ 2 sprinkle donuts})=\dfrac{2}{9}\cdot \dfrac{1}{8}+\dfrac{3}{9}\cdot \dfrac{2}{8}+\dfrac{4}{9}\cdot \dfrac{3}{8}= \dfrac{20}{72}=\dfrac{5}{18}$
Answer: Hint:
It often helps when beginning to learn probability like this to draw yourself a Tree Diagram.
Answer: P(Ch) = $\frac2 9$ , P(Ca) = $\frac3 9$ , P(Sp)= $\frac4 9$
Ch, Ca and Sp, are used for Chocolate, Cake and sprinkle donuts.
Now, for X type of donut, where one donut has already been picked are, the changed Probability be P(X').
So, P(Ch') = $\frac1 8$, P(Ca') = $\frac2 8$, P(Sp') = $\frac3 8$.
$P(XX') = P(Ch) P(Ch') + P(Ca) P(Ca') + P(Sp) P(Sp')$
$= \frac29 * \frac18 + \frac39 * \frac28 + \frac49 * \frac38$
$= \frac5{18}$
Answer: You can draw $2$ donuts out of the total $2+3+4=9$ donuts in $9\choose 2$$=9\times4  =36$ ways.
Now consider the specific criteria, that the two drawn donuts will be of same type.
So, these can be Chocolate donuts or cake donuts or sprinkle donuts.
Now, $2$ Chocolate donuts can be drawn from $2$ in $2\choose 2$$ =1$ ways, similarly, $2$ cake donuts can be drawn in $3\choose 2$$=3$ ways and $2$ sprinkle donuts can be drawn in $4\choose 2$$=6$ ways.
So the probability is $\frac {1+3+6}{9\choose 2}$$=\frac{10}{36}=\frac5{18}$