Why does my simulation not produce the expected confience interval?

Question: I'm doing a simulation. I first simulate a mean vector and a semi - positive definite covariance matrix.
I then go through and generate 5000 samples of 10 length. I then construct the 95% Confidence interval for each sample. Finally, I see how many samples overlap the true means (which I know). However it's all of them. Shouldn't there be a few that fall out of the range?
The code is attached.
<code>library(MASS)
library(clusterGeneration)

#set.seed(314159) # For ease of replication

######################
#Generate mean vector and sigma information
######################
trueMu<- runif(n = 2, min = 0, max = 2)
matrixData <- genPositiveDefMat(dim = 2, covMethod = "eigen", lambdaLow = 8)
trueSigma <- matrixData$Sigma
trueMu
trueSigma

######################
#Generate random data 5000 times @ sizes of 10,20, 150
######################
TenSampleList <- lapply(1:5000,function(x){
  mvrnorm(n = 10, mu = trueMu, Sigma = trueSigma)
})

######################
#Function to calculate confidence interval
######################
calcConfInterval <- function(currentData, corrected= FALSE){
  #browser()
  meanCol1 <- mean(currentData[,1])
  meanCol2 <- mean(currentData[,2])

  sdCol1  <- sqrt(var(currentData[,1]))
  sdCol2  <- sqrt(var(currentData[,2]))

  lengthObs <- nrow(currentData)
  confidenceLevel = 1 - .05/(2 * ifelse(corrected ==TRUE, 2 ,1))

  col1Conf <- c(meanCol1 - qt(confidenceLevel, lengthObs - 1)*sdCol1,meanCol1 + qt(confidenceLevel, lengthObs - 1)*sdCol1)
  col2Conf <- c(meanCol2 - qt(confidenceLevel, lengthObs - 1)*sdCol2,meanCol2 + qt(confidenceLevel, lengthObs - 1)*sdCol2)

  return(list(col1Conf = col1Conf, col2Conf = col2Conf))
}

######################
#Get ConfidenceIntervals for each sampel set
######################

TenSampleConfIntUncorrected <- lapply(TenSampleList, calcConfInterval, corrected = FALSE)

checkIfInside <- function(data, trueMu1, trueMu2){
  #browser()
  result1 <- if(trueMu1 >= data$col1Conf[1] && trueMu1 <= data$col1Conf[2]){1}else{0}
  result2 <- if(trueMu2 >= data$col2Conf[1] && trueMu2 <= data$col2Conf[2]){1}else{0}
  return(result1 * result2)
}

TenSampleUncorrectedInsideProportion <- sum(unlist(lapply(TenSampleConfIntUncorrected, checkIfInside, trueMu1 = trueMu[1], trueMu2 = trueMu[2])))

TenSampleUncorrectedInsideProportion
</code>
Comment: The standard error on the mean is the one for the population **divided by** $\sqrt{n}$. Moreover you take 0.95 confidence on each dimension so you have a 0 9025 CI ( if I understand your code well)
Comment: Ack! Such a simple thing. Thanks for the reminder. And yes, I realize that it's 0.9025 CI for both together. That's why I have the ifelse in the "confidenceLevel" line. To show that after I do bonferroni's correction it's more on target to 0.95
Comment: Fine :-) so if you use the $\sqrt{n}$ then you should have some non-covering intervals?
Comment: Yep, I do. Using the sqrt(n) it's about 90.something % and after I use the correction it's about 95%-- exactly as I expected. The mistake to forget sqrt(n) was silly. Thank you for pointing it out. Much appreciated. If you put it as an answer I'll mark it correct and give you credit.
Comment: Your title gives misleading impression of the question. Maybe you could change it to: "Why my simulation does not result in correct coverage for confidence interval?" or something similar.
Comment: @Tim Why people keep on using this ungrammatical form for Stack Exchange question titles? *Why does my simulation not result in correct coverage for confidence interval?*
Comment: @nekomatic I guess that many SE users, like myself, are not native English speakers. Feel free to correct the grammar by suggesting edits using the `[edit]` button if you find it appropriate.
Answer: As indicated in my comment, the standard error on the mean should be the one of the random variable divided by $\sqrt{n}$.


Divisor of degree 2 on a smooth plane curve

Question: Let $X$ be a smooth plane curve of genus $3$ (assume a smooth plane quartic) and $D$ a divisor of degree $2$ on this curve.
Assume that $\mathcal{l}(D)>0$. It means that there exists a rational function $f$ such that $div(f)+D\geqslant 0$, hence $D$ is linearly equivalent to $P+Q$ (since it is of degree $2$). Why it implies that $\mathcal{l}(D)=1$?
Another question: assume that $D$ is an odd theta characteristic (it means $2D\simeq K_X$ where $K_X$ is a canonical divisor). From the previous question it would follow that $D$ is of equivalent to $P+Q$. Why then the line passing through $P$ and $Q$ is bitangent to $X$?
Answer: a) As you notice, you have  $l(D)\geq 1$ .
On the other hand, if you had $l(D)\geq 2$, the curve $X$ would have a $g^1_2$, and thus be hyperelliptic.
But this is impossible because hyperelliptic curves (of genus $\geq 2$) cannot be embedded into the projective plane. Hence $l(D)=1$
b) The adjunction formula $$K_X=(K_{\mathbb P^2}\otimes_{\mathcal O _{\mathbb P^2}} \mathcal O_{\mathbb P^2}(X))\mid X=(\mathcal O _{\mathbb P^2}(-3)\otimes_{\mathcal O _{\mathbb P^2}} \mathcal O_{\mathbb P^2}(4))\mid X=\mathcal O _X(1)$$
shows that the canonical divisor $K_X$ consists of intersections of lines in $\mathbb P^2$ with $X$.
So in the case $2P+2Q \simeq2D\simeq  K_X$, the divisor $2P+2Q$ is the intersection divisor of some line $L\subset \mathbb P^2$ with $X$.
This implies that the line through $P$ and $Q$ is tangent to $X$ at $P$ and $Q$, as required.


Access to view into Fragment

Question: I'm trying to start an animation when the fragment is showed on screen(I'm working with a ViewPager).
This a part of my code
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

        private Map<Integer, String> mFragmentTags;
        private FragmentManager mFragmentManager;

        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
            mFragmentManager = fm;
            mFragmentTags = new HashMap<Integer, String>();
        }

        public ScreenSlidePageFragment getFragment(int position) {
            String tag = mFragmentTags.get(position);
            if (tag == null)
                return null;
            return (ScreenSlidePageFragment) mFragmentManager.findFragmentByTag(tag);
        }

        @Override
        public Fragment getItem(int position) {
            return ScreenSlidePageFragment.create(position);
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Object obj = super.instantiateItem(container, position);
            if (obj instanceof Fragment) {
                // record the fragment tag here.
                Fragment f = (Fragment) obj;
                String tag = f.getTag();
                mFragmentTags.put(position, tag);
                System.out.println("holi");
            }
            return obj;
        }

    }

    public class ScreenSlideActivity extends FragmentActivity {
    (...)
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_screen_slide);

            // Instantiate a ViewPager and a PagerAdapter.
            mPager = (ViewPager) findViewById(R.id.pager);
            mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());

    (...)

    SimpleOnPageChangeListener mPageChangelistener = new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    // When changing pages, reset the action bar actions since they are dependent
                    // on which page is currently active. An alternative approach is to have each
                    // fragment expose actions itself (rather than the activity exposing actions),
                    // but for simplicity, the activity provides the actions in this sample.
                    ScreenSlidePageFragment currentFgm = mPagerAdapter.getFragment(position);
                    Animation animacion = AnimationUtils.loadAnimation(ScreenSlideActivity.this, R.anim.glasses);
                    currentFgm.getView().findViewById(R.id.image).startAnimation(animacion);
                    invalidateOptionsMenu();
                }
(...)

The problem is when onPageSelected is called returns a NullPointer Exception in
currentFgm.getView().findViewById(R.id.image).startAnimation(animacion);

How could I start the animation when the fragment is showed on screen?
Answer: If you are trying to add animation to the ViewPager then you can implement the ViewPager.PageTransformer interface and supply it to the view pager to display a different animation than the default screen slide animation.
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
...
mPager.setPageTransformer(true, new CustomTransformer());

You will find here two examples of PagerTransformers.
Comment: Sorry, I haven't explained well. When the fragment is showed(after page transition) a animation in a image should start.

Access to view into Fragment


How to change text size of dialog preference message?

Question: I have a class that extends EditTextPreference and I use it in my own layout, such as:
    <com.app.MyEditTextPreference
        android:key="@string/key"
        android:title="@string/title"
        android:summary="@string/summary"
        android:dialogTitle="@string/title"
        android:dialogMessage="@string/message"
        android:layout="@layout/preference_edittext"/>

My app theme inherits from Theme.AppCompat.Light.DarkActionBar and I have changed the values of the text sizes:

However, when the preference dialog is displayed, the size of the message is different than the one I have defined in my style.
So how do I set the text size of the dialog message correctly?
EDIT
I copied the dialog layout from the sdk:

<LinearLayout
    android:id="@+android:id/edittext_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:orientation="vertical">

    <TextView
        android:id="@android:id/message"
        android:layout_marginBottom="48dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingStart="4dp"
        android:paddingEnd="4dp"
        android:textColor="?android:attr/textColorSecondary"
        style="@style/TextAppearance.Small" />

</LinearLayout>

However, I get a build error Resource is not public on the line android:id="@+android:id/edittext_container".
And if I change it to "@*android:id/edittext_container", the edit text is not visible anymore.
Is there a simpler way to just change the textsize of the message?
Answer: First create new xml file name cus.xml in layout folder.
it need for set the view for dialog at runtime .
<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Name :"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="18dp" />

<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:textSize="18dp" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:textSize="18dp" />

As you need dialog:
here's dialog code:
Dialog d=new Dialog(getActivity());
                d.setTitle("Image Title");
                d.setContentView(R.layout.cus);
                d.show();

Answer: I finally managed to change the message text size by:
a) Changing the id of the LinearLayout to: @+id/edittext_container, and
b) Adding the following code in my class extending EditTextPreference:
@Override
protected void onAddEditTextToDialogView(View dialogView, EditText editText) {
    ViewGroup container = (ViewGroup) dialogView
            .findViewById(R.id.edittext_container);

    if (container != null) {
        container.addView(editText, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
    }
}

This works fine and is clearly a valid answer, however a simpler solution would be to just change the message text size through themeing.


How to start TinyMCE with contenteditable:false

Question: I'm struggling with building a TinyMCE textarea input field which should be toggled from enabled/disabled depending on the state of other input fields.
So far I've got the following working to toggle it:
var mceInstance = tinymce.get(TargetElementId);
mceInstance.getBody().setAttribute('contenteditable',false);

By toggling the 'contenteditable' parameter like this I can easily make the textarea disabled or not, so far so good.
The last problem I have to tackle, is that the textarea should be disabled upon initial loading, and it seems the 'contenteditable' parameter can't be passed as an tinyMCE.init() parameter...
There is a 'readonly' paremeter which can be passed with tinyMCE.init(), but that one can't be toggled at a later time...
Any ideas on how to accomplish this?
Answer: Solved it!
I found that by passing init_instance_callback with the TinyMCE init code, I could run the same code as used in my 'toggle' function.
So you can pass this in the TinyMCE init part if you want this:
init_instance_callback : function(editor)
{
    if(document.getElementById(editor.id).hasAttribute('disabled'))
    {
        editor.getBody().setAttribute('contenteditable',false);
        editor.getBody().style.backgroundColor = "grey";
    }
}

The above code will look at the specified instance, if the originating HTML element (textarea in my case) has the 'disabled' attribute, it will set the 'contenteditable' parameters to false.
I hope this is useful to someone else, I know I was happy when I cracked it :-)
Comment: Even old - still saved my day. Great that you've posted a solution :-)


React-router-dom TypeError: n is not a function on route, reloading page works

Question: When I click a  any route, the page doesn't render and throws an error - TypeError: n is not a function located in the react-dom.production.min.js file. I am using React-Router V6.
App.js
function App() {
return (
    <BrowserRouter>

            <Navbar />

                <Routes>
                    <Route exact path="/" element={<UploadOrdersPageHome />} />
                    <Route exact path="/admin-users" element={<AdminPageUsersTab />} />
                    <Route exact path="/admin-clients" element={<AdminPageClientsTab />} />
                    <Route exact path="/create-client" element={<CreateClientPage />} />
                    <Route exact path="/edit-client/:rowkey" element={<EditClientPage />} />
                </Routes>

    </BrowserRouter>
);

navbar.js
const Navbar = () => {
return (

                <Link to="/">

                </Link>

                <Link to="/">Upload Orders</Link>

                <Link to="/admin-clients">Admin</Link>

                    username

                <button className="btn btn-lg btn-outline-primary">
                    Log Out
                </button>

);

Errors
Href="/" works fine for links to pages, but the router doesn't. I would like to use this to later pass props to Components when routing.
Comment: Add code in the questions, not the images.
Comment: Try updating `dom` and `router` to the latest version.
Comment: package.json
    "react-dom": "^18.2.0",
    "react-router": "^6.8.2",
    "react-router-dom": "^6.8.2",
Answer: Solved
I was using the UseEffect hook as an async without declaring a function and then calling it.
Original:
    useEffect(async () => {
    const response = await fetch(`http://localhost:3000/orders`);
    const data = await response.json();
    const sortedData = data.sort((a, b) => (a.properties.createdOn < b.properties.createdOn ? 1 : -1));
    setFiles(sortedData);
}, []);

Updated:
    useEffect(() => {
    const loadOrders = async () => {
        const response = await fetch(`http://localhost:3000/orders`);
        const data = await response.json();
        const sortedData = data.sort((a, b) => (a.properties.createdOn < b.properties.createdOn ? 1 : -1));
        setFiles(sortedData);
    };
    loadOrders();
}, []);

The pages now render correctly and all pages can be routed to
Comment: My man, I had the same exact problem, thank you. Much love. This was driving me nuts.


Consulta ao MySQL com PDO não retorna dados

Question: Tenho o seguinte problema. Desenvolvi um class PHP para um site que estou criando e em uma dessa funções estou tendo problema com o PDO. Ao dar o comando SELECT utilizo a função rowCount() para verificar se obteve resultados e o resultado obviamente é 0 rows. Eu já testei a QUERY e os includes e está funcionando normalmente.
Código da função:
public function search($s) {
    $db = $this->db;
    $find = $db->prepare("SELECT `id`, `type`, `title`,`coverofpost`, `date` FROM `posts` WHERE title LIKE '% :tl %' OR tags LIKE '% :tags %' OR post LIKE '% :post %'");
    $find->bindValue(":tl", $s, PDO::PARAM_STR);
    $find->bindValue(":tags", $s, PDO::PARAM_STR);
    $find->bindValue(":post", $s, PDO::PARAM_STR);
    $find->execute();
    if ($find->rowCount() > 0) {
        $this->mountArray();
        while ($data = $find->fetch(PDO::FETCH_ASSOC)) {
            array_push($this->id, $data['id']);
            array_push($this->type, $data['type']);
            array_push($this->title, $data['title']);
            array_push($this->cover, $data['coverofpost']);
            array_push($this->time, $data['date']);
        }
        $this->makeUrls();
        $this->makeArray();
        $this->postArray['status'] = true;
    } else {
        $this->postArray['status'] = false;
    }
    return $this->postArray;
}

O retorno é sempre postArray['status'] //false
Comment: Remova as aspas simples da consulta e passe os `%` no `bindValue()`
Answer: A consulta não deve retornar resultados mesmo devido à aquelas aspas simples e aos coringas (%). Ou seja as aspas simples vão anular seu placeholder, ao invés de procurar %termo digitado% vai procurar %:tl%.
Para resolver remova as aspas simples e passe os conringas em bindValue()
Mude sua consulta para:
SELECT `id`, `type`, `title`,`coverofpost`, `date`
FROM `posts` WHERE title LIKE :tl OR tags LIKE :tags OR post LIKE :post

E os binds para:
$find->bindValue(":tl", '%'. $s .'%',  PDO::PARAM_STR);
$find->bindValue(":tags", '%'. $s .'%', PDO::PARAM_STR);
$find->bindValue(":post", '%'. $s .'%', PDO::PARAM_STR);

Em todos os LIKEs tem espaços (LIKE '% :tl %'), se foram intencionais adicione eles no bind.
$find->bindValue(":tl", '% '. $s .' %',  PDO::PARAM_STR);
espaço extra--------------^        ^--------------espaço extra

Comment: Resolveu. Muito obrigado!


Generate Email HTML using Razor in an ASP.NET MVC Project

Question: I have an ASP.NET MVC project that uses Razor for rendering HTML using the built-in engine.
I would like to create Email Templates using the same process.  Usually, these templates are created as part of a Action Context (for instance, when a user has completed a purchase, a notification would be sent).  However, there are some instances where there is no context available.  For instance, sending a log when the application is restarting.
This is what I have come up with so far:
public static string RenderRazor(ViewTemplateType TemplateType, string ViewName, PageController Controller = null, object Model = null)
{
    try
    {
        ControllerContext Context;

        if (Controller != null)
        {
            Context = Controller.ControllerContext;
        }
        else
        {
            if (HttpContext.Current == null)
            {
                throw new InvalidOperationException("Cannot render a razor template if the current context is null (See DEV-1669).");
            }
            var RouteData = new RouteData();
            RouteData.Values.Add("controller", "Pseudo");
            Controller = new PseudoController(Model);
            Context = new ControllerContext(new HttpContextWrapper(HttpContext.Current), RouteData, Controller);
            // If this isn't set, an error occurs when calling FindView/FindViewPartial.
            Controller.ControllerContext = Context;
        }

        // I'm not really sure what the point of this is...
        // Further, it was actually causing an exception to occur since the Controller may not actually be populated?
        // Without this, the Notification Debug wasn't working - so apparently it is required in some circumstances for notifications.
        if (Controller != null && Controller.ViewData != null && Model != null) { Controller.ViewData.Model = Model; }

        var ViewResult = ViewName.StartsWith("_")
            ? ViewEngines.Engines.FindPartialView(Context, string.Format("~/Views/Template/{0}/{1}.cshtml", TemplateType, ViewName))
            : ViewEngines.Engines.FindView(Context, string.Format("~/Views/Template/{0}/{1}.cshtml", TemplateType, ViewName), string.Format("~/Views/Template/{0}/_Shared/{1}.cshtml", TemplateType, "_Layout"));

        if (ViewResult.View == null)
        {
            StringBuilder LocationBuilder = new StringBuilder();
            string[] SearchedLocations = ViewResult.SearchedLocations.ToArray();
            for (int i = 0; i < SearchedLocations.Length; i++)
            {
                LocationBuilder.Append(string.Format("({0}) {1} ", i, SearchedLocations[i]));
            }

            throw new InvalidOperationException(string.Format("Could not find the {0} Template named {1} using the {2} Master. Locations Searched: {3}", TemplateType, ViewName, "_Layout", LocationBuilder));//
        }
        using (var Writer = new StringWriter())
        {
            //ViewResult.View.Render(new ViewContext(
            //  Context,
            //  ViewResult.View,
            //  (Controller != null) ? Controller.ViewData : (Model != null) ? new ViewDataDictionary(Model) : new ViewDataDictionary(),
            //  (Controller != null) ? Controller.TempData : new TempDataDictionary(), Writer), Writer);

            ViewResult.View.Render(new ViewContext(
                Context,
                ViewResult.View,
                Controller.ViewData,
                Controller.TempData, Writer), Writer);

            ViewResult.ViewEngine.ReleaseView(Context, ViewResult.View);

            // This must remove Tabs (\t) Returns (\r) and Newlines (\n)
            // Always making the quotes single makes sense for statically generated stuff - the only time when it wouldn't make sense is for more complex stuff or if it includes JS which i don't think
            // a statically generated one should ever?

            string result = Regex.Replace(Writer.GetStringBuilder().ToString().Replace("\"", "\'"), "(\\t|\\r|\\n)", string.Empty);

            // Currently, this process does not work well when initiated outside of a request (e.g. in the startup method or purely within a
            // hangfire task). This serves as a warning if it ever is (since it will return an empty string).

            if (result.Blank()) { throw new InvalidOperationException("There was an error rendering the " + ViewName + " template. This can happen if the template was initialized outside of the context of an actual request."); }
            else
            {
                return result;
            }
        }
    }
    catch (Exception ex)
    {
        // This could indicate an error in the underlying template
        // If there is an error on any of the underlying templates in a given class,
        // this can be called.
        Logging.Error(ex);
        return string.Empty;
    }
}

This works pretty well except for when I am trying to generate a template when I don't have a reference to a Controller.
I have also started looking into applying the third-party RazorEngine (https://antaris.github.io/RazorEngine) - but is this overkill?  Is it even feasible to implement this in a project that also utilizes the built-in razor engine?
Answer: I've used ActionMailer in the past. It's no longer maintained but there's a fork https://github.com/crossvertise/ActionMailerNext.
You set up a controller to bind the templates but can call it like another service class.
public class EmailController : MailerBase, IEmailService
{
    public EmailResult PasswordRecovery(PasswordRecoveryModel model)
    {
        To.Add(model.Email);
        From = "email@example.com";
        Subject = "Password Recovery";
        return Email("PasswordRecovery", model);
    }
}

I set it up with my own interface so I can inject it wherever
public interface IEmailService
{
    EmailResult PasswordRecovery(PasswordRecoveryModel model);
}

public class Foo
{
    private readonly IEmailService emailService;

    public Foo(IEmailService emailService)
    {
        this.emailService = emailService;
    }

    public void DoSomething()
    {
        this.emailService.PasswordRecovery(new PasswordRecoveryModel { ... });
    }
}

The templates look just like regular views
PasswordRecovery.html.cshtml
@using ActionMailer.Net.Mvc
@model PasswordRecoveryModel

@Model.UserName

 ...

I haven't tried the fork so I can only assume it's similar in usage.


Divergence/Convergence $\int_{5}^{\infty}e^{-\ln^{6}x}$

Question: $$\int_{5}^{\infty}e^{-\ln^{6}x}$$
I have first tried to simplify the integrand
$$e^{-\ln^{6}x}=\frac{1}{e^{\ln^{6}x}}=\frac{1}{e^{\ln x\cdot \ln^5x}}=\frac{1}{x^{\ln^5x}}$$
how should I continue? I am think about the limit test with some $\frac{1}{x^{\alpha}}$
Comment: Can't you compare it to $\frac{1}{x^2}$ since $ln^5x>2$ for $x\ge 5$?
Comment: it is true that $-ln^{6}x\neq -ln(x)^6\neq-6lnx$?
Comment: Yes, order matters. $-ln^6x=-(ln\ x)^6\neq -ln(x^6)$
Answer: Since $\ln x$ is continuous on the domain considered it suffices to look at the integral from $e^2$ to $\infty$. But for $x\geq e^2$ we have $\ln x \geq 2$ so writing $(\ln x)^6 = (\ln x)^5 \ln x \geq 32 \ln x$:
$$ \int_{e^2}^{\infty} e^{-(\ln x)^6} \; dx \leq \int_{e^2}^\infty e^{-32 \ln x} dx = \int_{e^2}^\infty \frac{1}{x^{32}} dx<+\infty$$
Comment: He used that $\ln x \ge 2$ in the range he is interested in.  That is why he raised the lower limit to $e^2$.  The area between $5$ and $e^2$ is some finite number which doesn't matter for whether the integral converges or diverges.  All that matters for that is what happens "near infinity".
Comment: Can you please elaborate more about the steps?
Answer: I suggest another path. By the change of variable, $u=\ln x$, $dx=e^udu$, one gets
$$
\int_{5}^{\infty}e^{-ln^{6}x}dx=\int_{\ln 5}^{\infty}e^{\large u-u^6}du
$$ then one may use that, as $u \to \infty$,
$$
u^2e^{\large u-u^6} \to 0
$$ to obtain, for some $u_0>\ln 5$,
$$
0<e^{\large u-u^6}<\frac1{u^2}, \quad u>u_0,
$$ yielding the convergence of the given integral.
Comment: Thanks, I did not understand in the second equation where $u^2$ came from and the last equation I did not understand at all, why $e^{u-u^6}<\frac{1}{u^2}$?
Answer: If you wish to continue from where you left off, I can suggest the following: $$x\geq5\implies \ln x\geq\ln5\implies \ln^5x\geq\ln^5(5)>10$$
$$\frac{1}{x^{\ln^5(x)}}<\frac{1}{x^{10}}$$
$$\int_5^\infty \frac{1}{x^{\ln^5(x)}}dx< \int_5^\infty \frac{1}{x^{10}}dx=\left[\frac{x^{-9}}{-9}\right]_5^\infty=\frac1{17578125}$$
So the integral does converge...
Answer: Once we write the equivalent integral
$$ I=\int_{\log 5}^{+\infty}\exp\left(u-u^6\right)\,du $$
from $\log 5>1$ we have that for every $u\geq \log 5$ the inequality $1-\frac{1}{u^5}\geq \frac{9}{10} $ holds, hence
$$ I \leq \int_{\log 5}^{+\infty}\exp\left(-\frac{9}{10}u^6\right)\,du\leq \int_{\log 5}^{+\infty}\frac{du}{1+\frac{9}{10}u^6}, $$
for instance.


Como alterar chart.js exibir c,

Question: Estou aprendendo trabalhar chartsjs trago data, com valor  janeiro com 10 clientes,  a escala fica 0.5, 1.0,1.5,2.0  eu gostaria de deichar com 1,2,3,4,... nao existe meio cliente
/*********************************** GRÁFICO DE LINHAS DIARIO ***********************************/
function os_dia() {
var periodoDia = $('#os_select').val();
$.ajax({
    type: 'POST',
    dataType: 'json',
    data: {
        periodoDia: periodoDia
    },
    url: BASE_URL + 'home/lista_homeDia',
    success: function(resposta) {
        console.log(resposta);
        data = {
            labels: Object.keys(resposta),
            datasets: [{
                label: 'OS por Dia',
                data: ret(resposta),
                borderWidth: 2,
                borderColor: '#80B6ED',
                backgroundColor: '#80B6ED',
                fill: false
            }]
        };
        options = {
            labels: {
                fontStyle: 'bold'
            }
        };
        Chart.defaults.global.responsive = true;
        var contexto = document.getElementById("graficoOsDia").getContext("2d");
        grafico = new Chart(contexto, {
            type: 'line',
            data: data,
            options: options
        });
    }
});
        }
     function ret(param) {
          var valores = [];
      $.each(param, function(key, val) {
    valores.push(val);
     });
     return valores;
      }

                os_dia();

             $("#os_select").change(function() {
           os_dia();
            });

Comment: Poderia fornecer o seu código html?
Answer: Você pode adicionar um para a escala tanto do eixo X como do eixo Y
scales: {
    yAxes: [{
        ticks: {
            max: 5,
            min: 0,
            stepSize: 1
        }
    }]
}

Na opção max você escolhe o valor máximo da escala, na min o valor minimo, na stepSize é de quanto em quanto sua escala vai aumentar, no seu caso: 1.
EDIT: Você não precisa passar o valor min e max se não quiser, fica apenas como informação.
Você encontra mais informações aqui http://www.chartjs.org/docs/latest/axes/cartesian/linear.html#step-size
Espero ter ajudado!

Como alterar chart.js exibir c,


Is the slope of $\vert x\vert$ not $0$ at $x=0$?

Question: The absolute function
$$f(x)=\begin{cases}
x, &\text{if $x\ge0$}\\
-x, &\text{if $x<0$}
\end{cases}$$
has the derivative
$$f'(x)=\begin{cases}
1, &\text{if $x\ge0$}\\
-1, &\text{if $x<0$}
\end{cases}$$
So the slope of the graph at $x=0$ is
$$f'(0)=1$$
The graph of $f(x)$ and it's slope (calculated by $f'(x)$) at $x=0$ are shown below.

However I was wondering that the slope of $\vert x\vert$ at $x=0$ should be $0$, based on the fact that the tangent should be the $x$-axis as shown below.
My question is: Shouldn't the value of the slope of $\vert x\vert$ at $x=0$ be $0$ based on graphical methods. I say this because slope is rather a graphical concept while differential is the calculus concept. If the slope is $0$, what method should be used to derive this result?
Comment: Think about it: why "should" the slope be horizontal in your opinion? Symmetry is no reason. Also note that there is no reason that the equal sign is in the upper case rather than the lower. Both will define the same function $|x|$.
Comment: "The graph of $f(x)$ and its slope are shown below." You graphed the slope incorrectly, and I think that's causing some confusion.  Also, the tangent line you have drawn at the origin is only one of many tangent lines at the origin, which explains visually why the slope at the origin is undefined.
Comment: I am curious about your intuition regarding what the tangent line "should" be.  What would you suggest for the tangent line at $0$ to the graph of$$f(x)=\begin{cases}
2x, &\text{if $x\ge0$}\\
-\frac{1}{3}x, &\text{if $x<0$}
\end{cases}$$
Answer: First, in $x = 0$, we have:
$$\lim_{x\to0-}\frac{|x|-0}{x-0} = \lim_{x\to0-}\frac{-x}{x} = -1$$
On the other hand,
$$\lim_{x\to0+}\frac{|x|-0}{x-0} = \lim_{x\to0+}\frac{x}{x} = 1$$
Because both limits are not the same, it follows that the function defined by
$f(x) = |x|$ is not differentiable at $x = 0$ (this is the calculus approach to see that the slope is not defined)
If you know the geometrical meaning of the derivative, you should be able to see why the slope of the tangent line in a point at the graph and the derivative are the same thing. Intuitively, you can think about this in the following way:
Remember, $$f'(a) = \lim_{x\to a}\frac{f(x) - f(x)}{x-a}$$
so you can think about the quotient $\frac{f(x) - f(x)}{x-a}$ where $x$ is a number really close to $a$. You will notice, when you make a drawing, that this is more or less the slope of the tangent line.
Now, to answer your question, it should be clear that the slope is not defined at $x = 0$. How would you draw a unique tangent line? As mentioned in the comments, symmetry is no reason. If you consider $y = 0$ to be the tangent line, then other lines such as $y = x$ and $y = -x$ are also tangent lines.


Is arg(f(z)) continuous when f is analytic?

Question: My question is same with the title.
When f(z) is analytic(or just continuous), arg(f) is differentiable(or just continuous)?
If not, what restrictions are needed for arg(f) to be continuous?
Thanks!
Comment: It doesn't really make sense to ask whether arg(f) is continuous, since arg(f) is not even uniquely defined.
Comment: If $U$ is a simply connected domain and $f$ is analytic on $U$ and has no zero then there is an analytic function $g$ such that $f(z) = e^{g(z)}$. Proof : $g'(z )= f'(z)/f(z)$ is analytic thus so is $g(z) = \log f(a)+ \int_a^z g'(s)ds$
Comment: f'/f is analytic on simply connected domain U. Thus f'/f has an antiderivative g. So g' = f'/f. And I don't get it how I can get the last equation and how the conclusion follows from it.
Comment: If I get the conclusion, just put g(x+iy)=u(x,y)+iv(x,y)? Then arg(f(z)) = v(x,y) and v is continuous?
Comment: If we restrict the arg function to have values between α and α+2π, does it make sense?
Comment: On a simply connected domain that does not contain zero, arg(z) can have (α,α+2π) as a codomain.
Answer: $\operatorname{Arg}(z)$, if defined in any sensible way on all of $\Bbb C$, isn't continuous, no matter how you slice it.
If $f(z)$ is continuous and never zero, $\operatorname{Arg}(f(z))$ can be continuous. There are two ways to make this work:

If there is some continuous, non-self-intersecting curve from the origin to $\infty$ that $f(z)$ never hits, you can use that as the branch cut for $\operatorname{Arg}$, and everything works nicely.
Accept the multivalued nature of $\operatorname{Arg}$, and let $\operatorname{Arg}(f(z))$ be multivalued as well. Then it's not strictly speaking a function, but locally it behaves like a function.

In either case, it is continuous. An $\varepsilon$-ball around $\operatorname{Arg}(f(z))$ corresponds to a sector around $f(z)$ in $\Bbb C$. And assuming $f$ is continuous and $f(z)\neq0$, you can always find a $\delta$-ball around $z$ which, when mapped with $f$, lands inside this sector.
Comment: If you take $f(z) = z$ on the punctured complex plane, your two sentences seem to contradict each other.
Comment: This answer is incorrect as on domains that are not simply connected it may not be possible to define the argument continuously even if the function is non zero ($z$ on the punctured unit disc). On a simply connected domain the argument of an analytic function that is never zero can be defined uniquely if one fixes the value at a point and then it is harmonic hence infinitely differentiable and more - the standard choice is to fix it as zero at a fixed real value of the function; the proof is noting that it is the imaginary part of the analytic function $\log f$
Comment: Oh! How can I show that its argument is continuous when it is never zero?
Comment: @anadad Standard $\epsilon$-$\delta$ ought to do the trick. Alternately, $\operatorname{Arg}(z)$ is continuous anywhere else, and composition is continuous.
Comment: Should I think it geometrically? I drew a δ-ball around a non-zero point and try to find the relation between δ and the maximum argument between a point in the ball and the non-zero point. But I don't have an idea yet.
Comment: @Conrad I am aware. I have updated my answer (even before you posted your comment). I believe that edit addressed most of your concerns.
Comment: It is actually not that hard to show that you can define $\log f$ as a continuos function for any continuos function that is never zero on a simply connected domain and then the argument is just the imaginary part of that and is continuos
Comment: Thank you! I understand it now :)


Quick and easy way to remove outliers

Question: I have a set of data of locations and associated rent prices. Now there seem to be several outliers which I would like to get rid of so that a plot of my original data gains more meaning. In the "world" of statistics, would it be acceptable if I did this by eliminating any prices that who deviate from the mean by more than twice the standard deviation?
The aim of what I'm working on is to test out several machine learning techniques. I don't have to be extremely accurate but I wouldn't like to do something that is totally unacceptable.
Comment: Please investigate some of the previous threads on the topic of removing outliers: you can find them by linking through the [tag:outlier] tag.
Comment: Outliers with respect to which model? "*...would it be acceptable if...*" -- acceptable to whom? What properties do you require?
Comment: you are dealing with a regression task. The hypothesis of your model pertain to the residuals (not to the $y$'s themselves). You should be wary of observations whose associated residuals are too far from the fit. The only reliable way to reveal such observations is in terms of their distances to a robust fit of your data. See [this](http://stats.stackexchange.com/questions/15426/whether-to-delete-cases-that-are-flagged-as-outliers-by-statistical-software-whe/50780#50780) answer for more info
Answer: Surely, if your machine learning techniques are to be realistic, then they should include outliers!  The only thing to add is that your training dataset should be of a reasonable size, such that your "sample" for each location is probably at least 100.  In my view the only outliers to exclude are those arising from data errors.

Quick and easy way to remove outliers


Sequência de Fibonacci

Question: Preciso fazer um exercício sobre a sequência de Fibonacci:

Cada novo termos na sequência de Fibonacci é gerada a partir da soma
  dos 2 termos anteriores. Se começarmos com 1 e 2, os primeiros dez
  números serão: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Considerando os
  termos da sequência de Fibonacci com valores menores que cem mil,
  encontre a soma de todos os números pares. Resposta: 60696

e estou quase chegando lá, vejam o código:
public static void main(String[] args) {
        int termo1 = 1;
        int termo2 = 2;
        int termos[] = new int[10];
        int soma = 0;
        termos[0] = 1;
        termos[1] = 2;

        for (int i = 2; i < termos.length; i++) {
            termos[i] =  termos[i - 1] + termos[i - 2];
        }

        for (int termo : termos ) {
            if (termo % 2 == 0) {
                soma += (long) termo;
            }
        }

        System.out.println(soma);

    }

Estou usando arrays, e estou conseguindo fazer com os 10 primeiros termos da sequência, o problema é que quando troco o tamanho do array para 100000, a soma dos termos dá errado, e número negativo, como se a variável soma não suporta-se.
Comment: Tenta fazer "`int soma = 0;`" ser "`long soma = 0;`"
Comment: Eu fiz, deu -289570595282
Comment: Eu troquei os int pra long e deu "7203226363417812526" ao fazer a matriz assim "`long termos[] = new long[100000];`"; deveria ter dado "60696"?
Comment: Sim, se você analisar o algorítimo, estou fazendo a soma de todos os termos pares, então só precisaria mudar o tipo das variáveis pra dar 60696
Answer: O algoritmo não faz o que está no enunciado. Ele não pede para criar array. Ok, é uma forma, mas confusa e não otimizada. Ele manda parar quando a soma chegar em 100000, isso nunca é verificado. Ele não fala quantas interações precisam se feitas.
class Main {
    public static void main(String[] args) {
        int termo1 = 1;
        int termo2 = 2;
        int soma = 0;
        while (termo2 < 100000) {
            int novoTermo = termo1 + termo2;
            if (novoTermo % 2 == 0) soma += novoTermo;
            termo1 = termo2;
            termo2 = novoTermo;
        }
        System.out.println(soma);
    }
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: `class HelloWorld`...
Comment: C# já é uma desgraça pq exige classe até em coisa simples, Java é pior por exigir o mesmo nome do arquivo, aí dá muito trabalho trocar nesses IDE online.

Sequência de Fibonacci


Plotting on maps in android

Question: I am making an application where I get an message with latitude and longitude, I search that and then plot it on google maps.
How to accomplish the plotting ??
Comment: You may want to edit your question and put relevant code you have already.
Comment: In the question you mention you want to know how to perform plotting on the map, yet on my answer you mention you want to know how to parse a lat/lng from a String. Please re-phrase your question, and add what you already tried to do.
Answer: If by "plotting on the map" you mean adding a marker (icon) to a map at a given Latitude / Longitude, you can use the following code to put a Marker on Sydney on the map :
<code>private GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.addMarker(new MarkerOptions()
        .position(new LatLng(-33.88,151.21))
        .title("Hello world"));
</code>
The LatLng object accepts 2 doubles representing a latitude and a longitude in degrees.
The Google Maps Android API v2 is pretty well-documented. There's also a guide on Markers in Google Maps Android API v2
Comment: this above code is hardcoded and only those locations will be shown with the balloon. but i need to plot external lat long which i get through message
Comment: please explain a bit better what you want to achieve. What is your input and output ?
Comment: The google map application receives a text message. The message contains set of string and latitude and longitude of a place. What i want my application to do is it searches the lat and long values using a search java code and immediate after that i want those to be plotted on a google map saying balloon-A/or marker(wt ever)..then sequence of such message arrives from different location and they should be similarly plotted on  map.
Comment: What do you mean by "searches the lat and long values using a search java code". The code in answer shows you how to plot a marker with an InfoWindow for a given lat/lng. (replace 0,0 with whatever you get in your text message). Do you need help receiving the text message, parsing the text message, do you want to lookup an address/place for the given lat/lng ?
Comment: I receive text message. but how to fit the lat long values in the code above. i might need help in parsing once the lat long values from the message is searched.
Comment: Don't know what else to say... if you have a reference to your latitude / longitude as a string, convert them to doubles and store them in a LatLng as illustrated in the code.
Comment: @ ddewaele - any suitable search code to search the lat and long values. the string format might be like this "# Lat= 3456.677675544 Long= 344.098765657"

Plotting on maps in android


webkitSpeechRecognition automatically stops

Question: I am using webkitSpeechRecognition. But when recognition is initiated, it stops after 1-2 mins of inactivity. I am trying to firing it back after it is ended. When I execute start_transcript(language), it keeps producing a thousand of console.log("voice recognition terminated"); and it does not recongnize anymore.
var final_transcript = '';
var recognizing = false;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
  upgrade();
} else {
  var recognition = new webkitSpeechRecognition();
  recognition.continuous = true;
  recognition.interimResults = true;
  recognition.onstart = function() {
    recognizing = true;
  };

  recognition.onend = function() {
    console.log("voice recognition terminated");
    recognition.start();
  };

function start_transcript(language) {
  if (recognizing) {
    recognition.stop();
    return;
  }
  final_transcript = '';
  var rec_lang = 'fr-FR';
    recognition.lang = rec_lang;
  recognition.start();
}

Any help and advice will be very appreciated.
Thanks
Answer: Just some tiny missings here and there. Updated your code with filling those missing gaps,Try this in your console. Also don't forget to call start_transcript.

var final_transcript = '';
var recognizing = false;
var start_timestamp;
if (!('webkitSpeechRecognition' in window)) {
  upgrade();
} else {
  var recognition = new webkitSpeechRecognition();
  recognition.continuous = true;
  recognition.interimResults = true;
  recognition.onstart = function() {
    recognizing = true;
  };

  // need to have result as well
  recognition.onresult = function(e) {
    console.log(e.results);

    // Extracting the words from the result and printing in the console
    var transcript = [...e.results]
      .map(result => result[0])
      .map(result => result.transcript)
      .join('');
    console.log(transcript);
  };

  recognition.onend = function() {
    console.log("voice recognition terminated");
    recognition.start();
  };
} // I guess you forgot closing the else block as well

function start_transcript() {
  if (recognizing) {
    recognition.stop();
    return;
  }
  final_transcript = '';
  var rec_lang = 'fr-FR';
  recognition.lang = rec_lang;
  recognition.start();
}

PS: Also I had made a similar kind of project by referring Wesbos's javascript30, and mixed it with webpack. If you want to refer it then please visit  https://github.com/Mondal10/personal-voice-assistant
Comment: Hi, thanks for the help. I tried your code, but it spines my app in countless "voice recognition terminated" console logs.


MySQL: Select row by id, CHANGE id, and insert it into another table

Question: I have two tables, A and B.
I'd like to select a row from B based on it's Primary Key, alter the primary key to a different value, and then insert this row into A.
Something like this:
INSERT INTO A SELECT id, title, date FROM B WHERE B.id="4" UPDATE B SET id="5";

Is there a solution for this?
Comment: Original poster here: Just a note, A and B have identical columns.
Comment: where do you want this changed id, in original row (table B) or in newly inserted (table A) ?
Comment: What's wrong with what you have?  You want to do it in a single query?
Comment: It should have the new value inserted into A.
Comment: are you just incrementing id by 1 or is there some other formula whats the data type
Comment: The increment by one is just an example. I'll actually be drastically changing the values. The data type is int.
Answer: INSERT INTO A(id, title, date)
SELECT 5 AS id, title, date FROM B WHERE B.id="4";
#      ^--- here is the trick

Answer: Maybe something like
insert into a (select id as "new_id", title, date from b where b.id="4")

Comment: Thanks for the response, would select id as "new_id" let me change the id value to whatever is in the quotes?


Nonlinear First-Order ODE: $\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{1}{x\cos(y)+y\sin(2y)}$

Question: Having some fun with this:
$$
\frac{\mathrm{d}y}{\mathrm{d}x} = \frac{1}{x\cos(y)+y\sin(2y)}
$$
I have tried various substitutions and factorizations, and an obvious trig identity. It looks like a numerical problem to me. I would appreciate any hints/ideas to find a function $f(x,y)=C$ with this property.
Comment: I think you are right - numerical methods is the way to go on this one.
Answer: I think this is as close as you can get: If you view $x$ as a function of $y$, your differential equation will be
$$
x'-x\cos y=y\sin2y,
$$
which you might be able to solve using integrating factor. You will end up with something like
$$
xe^{-\sin y}=\int y e^{-\sin y}\sin(2y)\,dy.
$$
It seems difficult to find a closed expression for that integral, though.


css - div overflowing outside of fieldset parent

Question: jsFiddle: https://jsfiddle.net/0q3ega2n/
I'm currently at a bit of a loss.  I have a fieldset that has a select box in its legend and is meant to dynamically update the content within my fieldset, which works fine.  For layout purposes, the fieldsets are fixed at a height of 200px.
Where I'm running into issues is adding scrollbars to the fieldsets in the event the content overflows.  I can't use an overflow: auto on the fieldset itself, because that causes the legend tag to scroll as well.  Some other answers suggested using a content wrapper div to add the scrollbars, which I've done.
However I'm still not quite where I want.  I need to specify a height attribute for the wrapper div in order for the overflow to occur.  Setting it to 100% results in text still overflowing outside the box (albeit not as much as it does with no overflow set).  Setting it to 92% is pretty much exactly what I want but 92% was chosen arbitrarily and as a result doesn't feel right (plus I'm slightly concerned about cross-browser compatibility)
CSS:
* {
  font: 12pt Verdana;
}

fieldset.metrics {
  height: 200px;
}

div.metrics-wrapper {
  width: 100%;
  height: 92%;
  overflow: auto;
}

HTML:
<fieldset class='metrics'>
  <legend>
    Fieldset Title, with a
    <select>
      <option selected='selected'>select box</option>
    </select>
  </legend>

      Content goes here

</fieldset>

Comment: You're misusing the `legend`. It' supposed to be a **caption**. - Not another element - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/legend
Comment: While I appreciate the comment, this doesn't pertain to the issue.  Were I to use it as a caption (i.e. text only), the text in the legend tag will still scroll with the content actually contained within the fieldset, which is the issue I'm trying to prevent.
Answer: The metrics-wrapper is still overflowing metrics
adding overflow: hidden fixes it
fieldset.metrics {
  height: 200px;
  overflow: hidden;
}

Comment: Great.  This gets me ~95% of the way there, thank you!  The last thing I want to do is add a 5px padding between the border of the fieldset and the bottom of the div, which is proving troublesome because of `metrics-wrapper` overflowing.  I've tried `padding-bottom` on the fieldset and also `margin-bottom` on the div, but no dice.


node information and messages

Question: I created a user login page, and used the login destination module to redirect my user to a new "front page" I created using views.
On this "front page" I call all the nodes created by the logged in user, so a user can see newly created nodes.
My question is, how do I call a message or view which tells my user when a node has been deleted or edited?  This "front page" acts as a 'notification wall', which the user can see everything that is added or edited.  It will become more complex later where admins will be able to edit user nodes.  So I need to let the user know when he/admin has edited or deleted a node.
Answer: You can used Rules, and/or Views Rules.
Here is the rule that you need to created:

Event: When a node from a content have been delete or updated.
Condition: based on role.
Action: message display if a node from an specific content type have been remove or updated
Comment: It sounds like if an Admin or he edits a node he wants that information to show, regardless of if the edit occurred while he was asleep, or logged out, your solution only deals with immediate status notifications. For long term recording of such events look at https://www.drupal.org/project/message
Comment: Thanks, this works. But I can only display the message as a status, warning or error. That appears only once.  I want the message to display on the 'front page' and stay there. Similarly to when a new node is created, and shown on the front page of your site.
Comment: Thanks @tenken. I will try your solution. Will let you know.
Answer: For long term logging of activities on a website to show on a wall look at Message module. It helps to support the idea of an Activity Stream on a site.

The Message module is the core of the message stack. It enables
  logging and displaying system events in a number of different use
  cases. Events that are recorded over time are sometimes call activity
  streams. Exportable messages subtypes can be created for different use
  cases with custom fields and display (view) modes.
Comment: Perfect! exactly what I needed.

node information and messages


azure chatbot not working. after publishing from visual studio(2017)

Question: i done the following steps:

created  web app bot (bot framework sdk v4) and perform 'test web chat'. which is successful and the bot responded.
note: Microsoft app id and password are created.
Downloaded the code.
updated bot file(.bot) with luis and qna configuration manually
<code>#{
"appId": "XXXXXXX",
"authoringKey": "xxxxxxxxxx",
"version": "0.1",
"region": "xxxxx",
"type": "luis",
"name": "BasicBotLuisApplication",
"id": "6"
#}

#{
"appId": "XXXXXXX",
"authoringKey": "xxxxxxxxxx",
"version": "0.1",
"region": "xxxxx",
"type": "qna",
"name": "myqna"
#}
</code>
and put 'Padlock' with empty value
Also updated the code (Startup.cs,BotServices.cs) and build app locally.
For testing locally,used bot framework emulator and which was successful.
Then 'Publish' the application with visual studio.
Try to connect with 'Test webchat'. The operation failed and received error code(401 and 403).

what shall do? any solutions?
Comment: Do you have other pages in your bot that work? For example, do you have the default.htm page that comes by default underneath wwwroot folder? (Browse to https://.azurewebsites.net/ to test). Does *browsing* to the endpoint (https://.azurewebsites.net/api/messages) give you the typical HTTP 405, or does it also give a 401/403?
Answer: 401 is unauthorized so did you make sure your file containing your authorization key got published?
If the file is not part of your solution/project it will not get deployed. Make sure that file is available post deployment on your app service (I presume?), you can use Kudu by going to [AppServiceName].scm.azurewebsites.net
Use the Debug Console to verify the file.
Answer: You need to look at your authentication. Usually, there should be some sort of session ID token that your browser session caches after authentication. From what you told us, there doesn't seem to be an authentication step.


Convert current time from Unix timestamp to date format (d/m/y)

Question: In my custom module (.module) file, I am using:
$current_time = \Drupal::time()->getCurrentTime();
date_default_timezone_set('GMT');

to get the current date... However, the date value is returned in int A Unix timestamp like: 1556582116
I have tried so far something like:
$current_time = \Drupal::time()->getCurrentTime();
$timenow = $current_time->format('Y-m-d H:i:s');

or
$current_time = \Drupal::time()->getCurrentTime('d');

to get only the day value... but with no success
How can I return the date value in the format of: D/M/Y like: 30/04/2019 or 30/Apr/19
Answer: You can format the current date using the below solutions.
Drupal 8:
//format date in 30/04/2019
$current_time = \Drupal::time()->getCurrentTime('d');
$date_today = format_date($current_time, 'custom', 'd/m/Y');

//format date in 30/Apr/2019
$current_timestamp = \Drupal::time()->getCurrentTime();
$todays_date = format_date($current_timestamp, 'custom', 'd/M/Y');

Drupal 9:
//format date in 30/04/2019
$current_time = \Drupal::time()->getCurrentTime('d');
$date_today = \Drupal::service('date.formatter')->format($current_time, 'custom', 'd/m/Y');

//format date in 30/Apr/2019
$current_timestamp = \Drupal::time()->getCurrentTime();
$todays_date = \Drupal::service('date.formatter')->format($current_timestamp, 'custom', 'd/M/Y');

Answer: You can do that with simple PHP function. Is there any specific reason you want a drupal function ? If not then you can use PHP's date() function.
$current_time = \Drupal::time()->getCurrentTime();

//To return 30/04/2019
$date_output = date('d/m/Y', $current_time);

//To return 30/Apr/19
$date_output = date('d/M/y', $current_time);

Comment: You should use Drupal date services so the set application timezone is accounted for.


How do we interpret the results of regression for log transformed data containing negative values, $\log(Y-\min(Y)+1)$?

Question: I have a question regarding interpretation of regression results based on data where I have some negative values. Since the residuals were positively skewed I needed to log-transform my data, and because of negative values my log transformation looked like $\ln(Y-\min(Y)+1)$. Normally, if we have $\ln$ in both sides of the equation, then our $b$ coefficient means a percentage change of DV for 1 % change of IV. But I have big doubts whether the same is valid for such log-transformed data, where I added a constant to my DV in order to make the minimum value equal to 1. I can't also find any literature on this topic. Does anyone know for sure what would be the correct interpretation in such a situation?
Answer: I would try either a glm approach with a log link function or something like a cube root transformation (any any other root whose power is the reciprocal of an odd positive integer and that accomplishes your goal). Some guidance on the latter here, along with some more exotic transformations. The glm approach would allow you to get the marginal effects in terms of elasticities. The root transform will give the marginal effects with a bit of calculus and algebra, but they really won't be elasticities.
Comment: does glm approach work for data with negative values? actually, I'm not familiar with this model. But I think there are a lot of subtypes of glm approach, right?
Comment: GLM will work with negative values. I would try it with the log link function and maybe normal errors to start.
Comment: @DimitriyV.Masterov , would the results of a `glm` approach with a log link function be interpreted the same way one would interpret a simple `lm( log(y) ~ log(x))` ?


Centralizar texto verticalmente

Question: Eu estou tentando fazer uma DIV pra uma assinatura com uma foto (24x24) ao lado.
Eu quero centralizar este texto verticalmente, de acordo com o tamanho da foto. Eu tentei usar vertical-align: middle, mas não me pareceu surtir efeito.

body {
  padding: 50px;
  font: 14px Verdana, Helvetica, Arial, sans-serif;
  background: #444;
  color: #FFF;
}

.assinatura {
  vertical-align: middle;
  line-height: 24px;
}

        Este texto eu quero no centro

Comment: É, eu cheguei a ver esta resposta, mas não tinha me ligado que o alinhamento estava na tag errada.
Answer: Basta colocar vertical-align: middle; na tag img, então os textos inline que estão junto a imagem irão acompanhar a sua "base", com isto também é possível ajustar a base abaixo dos textos ou acima, semelhante a esta Alinhar ícone com texto verticalmente
Um exemplo:

body {
  padding: 50px;
  font: 14px Verdana, Helvetica, Arial, sans-serif;
  background: #444;
  color: #FFF;
}

footer > div > img {
   vertical-align: middle;
   }

        Este texto eu quero no centro

Answer: Não sei se eu entendi bem, mas só faltou você adicionar a classe assinatura na imagem.

body {
  padding: 50px;
  font: 14px Verdana, Helvetica, Arial, sans-serif;
  background: #444;
  color: #FFF;
}

.assinatura {
  vertical-align: middle;
  line-height: 24px;
}

    Este texto eu quero no centro

Centralizar texto verticalmente


"Simple" proof that an n x n matrix is similar to its transpose

Question: At the risk of getting voted down for duplicating A matrix is similar to its transpose or Proving an $n\times n$ matrix is similar to its transpose, or such, I didn't feel comfortable "answering" their questions with my own question as I believe that's a faux pas worse than duplication, perhaps?
Anyway, the first question on our department's algebra qualifying exam in January 2015 was this, vis:

Prove or give a counterexample: every $n \times n$ complex matrix $A$ is similar to its transpose, $A^t$.

My question is this: what is wrong with my "simple" proof (below)? I'm skeptical of its viability because of the much more sophisticated solutions which accompany this question elsewhere on this forum. In particular, they all appear to appeal to Jordan Normal Form, which I didn't know about at the time I "solved" this. TIA for comments.
Claim: $A \sim A^t$.
Proof: By induction on $n$.
For the base case, $A = (z)$, a single complex number; $A^t = A = (z)$; hence the claim is true
if we take $P$ to be the $1 \times 1$ identity matrix, $(1)$.
The base case is established, therefore
assume, for $k < n$ we have that all $k \times k$ complex matrices are similar to their transpose,
and consider $k = n$. We can break up $A_{n \times n}$  into $m$ blocks of size $i_m \times i_m$
where $i_m < n$. Let $B_i$ denote the $i$-th block of $A$. We have that
$A = (B_i)_{1 \leq i \leq m}$.
By the induction hypothesis, each block is similar to its transpose. Hence, there are $P_i$
for $1 \leq i \leq m$ such that $B_i^t = P_i^{-1} B_i P_i$ for $1 \leq i \leq m$.
It should be clear that $A^t = (B_i^t)$. In other words, we can transpose $A$ block-wise and obtain
the same result. [Should I be proving this? I'd use another induction, I guess, on $m$, with fixed $n$.]
Consider the matrix $\mathcal{P} = (P_i)_{1 \leq i \leq m}$. We have that:
\begin{align*}
\mathcal{P}^{-1} A \mathcal{P} &= ( P_i^{-1} B_i P_i) \\
&= ( B_i^t ) \text{ by induction } \\
&= A^t.
\end{align*}
Comment: You can't transpose block wise. Imagine you have 4 blocks, then all the blocks get transposed, but the 1, 2 and 2, 1 block switch places. Try your inductive step on a $2\times 2$ matrix to see the difficulty in defining $P$.
Comment: "We can break up $A_{n \times n}$  into $m$ blocks of size $i_m \times i_m$
where $i_m < n$." This is not specific, and as you think about what precisely this would mean, I think you'll find that it's actually not true.
Answer: Perhaps you can apply your method to $A = \pmatrix{1 & 1 \\ 0 & 1}$. Since in this case $m$ is necessarily $1$, each $1 \times 1$ matrix is similar to its transpose, with each similarity matrix being $\pmatrix{1}$.
How do you propose to construct a $2 \times 2$ similarity matrix for $A$ from these? More generally, for any $n \times n$ matrix, we can break it into $1 \times 1$ blocks and use the same argument. So you should be able to show how to find the similarity matrix $P$, for any matrix, from a large collection of $1 \times 1$ identity matrices.
I think you see by now what's missing from your proof: when you find the smaller matrices, you also have to show how to assemble them into a larger one...and as the $m = 1$ example shows, that's not going to work out.
Comment: Please pardon my ignorance but you say "with each similarity matrix being (1)". Why is the 1,2 similarity matrix not (0)?
Comment: The (1, 2) similarity matrix **could** be zero, because $(0)^t (0) (0) = (0)$, but it could also be $(1)$, because $(1)^t (0) (1) = (0)$ as well. I chose to make all my similarity matrices be the same because it was easier to write (and to show that the general solution could not be derived from the block-solutions).
Comment: Thank you. I don't take the question to mean that I have to exhibit an actual similarity matrix $P$. I just have to show one exists, right? I think the key to whether this works is in how the blocks are developed, as Greg Martin indicates above. For example, there may be a notion of "maximal" blocks, in which case the  2 x 2 case may be one block. Or two columns. Or two rows. Etc. I feel like there is a way to make this work, or, at least, that I have to play with it more to convince myself it doesn't.
Comment: You last claim is that some matrix $P$ which is (somehow) assembled from the $P_i$s will suffice to transpose $A$. In my example case, the only $2\times2$ matrix you can build is $P = \pmatrix{1 & 1 \\ 1 & 1}$, which does not in fact transpose my matrix $A$. So at least the last paragraph of your answer is wrong. It's true that you only need to show the existence of a matrix $P$ rather than exhibiting it...but I'll be honest: I don't think you're going to be able to show the existence, either (and not because of *you*: I *suspect* that in general no such $P$ exists).
Comment: And now I see, looking at the linked questions, that such a matrix *does* exist. Live and learn!


AttributeError: 'super' object has no attribute 'feature2'. What's the reason for this error?

Question: class a:
    def __init__(self):
        super().__init__()
        print("in a init")

    def feature1(self):
        print("feature 1 is working")
    def feature2(self):
        print("feature 2 is working")

    def sink(self):
        super().feature2()

class b(a):
        def __init__(self):
            super().__init__()
            print("in b init ")

        def feature3(self):
            print("feature 3 is working")

        def feature4(self):
            print("feature 4 is working")

A=a()
A.sink()

I tried defining the sink function within class a
Comment: It's _not_ defined in any of a's parents, it's defined in an itself.
Answer: When you use super(), python starts looking for members from above the current class. Since there is no feature2 above a, python reports the error.
You could have just used self:
    def sink(self):
        self.feature2()

Answer: The error is because the super() function in the sink() method of class a is trying to access the feature2() method from the superclass of a, but no such method exists in the superclass.
The superclass of a is object, which is the default superclass for all classes in Python. The object class not have feature2() method, so when you call super().feature2(), it give an AttributeError.
To fix this, change super().feature2() to self.feature2()
class a:
    ...

    def sink(self):
        self.feature2()
    ...

AttributeError: 'super' object has no attribute 'feature2'. What’s the reason for this error?


Link Aggregation & Windows Servers

Question: So... We have a few servers that we would like load balanced link aggregation between multiple network interfaces. In the past we have used broadcom basp teaming using LACP.
Today we encountered THIS problem. An 'A' record for one of our DCs disappeared and would not recreate. It co-incided with configuring a different DC with a LACP nic team.
We have broken the team now and things seem normal again, but wtf is happening here? Is LACP a bad idea for windows servers 'full stop'? Is it just DCs?
Edit: It looks like 2012 implements LACP, I should make it clear that I am using 2008 r2.
Comment: Is that DC a DNS server?
Comment: It shouldn't break the A record.  I wonder if it's related to which mac address gets used and silly arp cache issue on the DC.
Comment: @ShaneMadden: The DC that LACP was configured on was not a dns server. The host for the A record that was lost is a DC with dns.
Comment: @Matt: An interesting thought but in an LACP group isn't a single MAC used?
Comment: @Ablue A DC that runs DNS has a bit of a novel method of putting its `A` records in DNS - the DNS server process adds an `A` record directly for each listening interface configured for the DNS service.  Would any changes you were making at the time have affected the DNS service on that system?
Comment: @ShaneMadden: There were no changes on any server running dns, but the zone affected was an AD integrated zone. Could this be a factor?
Comment: @Ablue That shouldn't affect anything.. is scavenging set up for the zone on any of the DNS servers?
Comment: @Ablue does multiple `A` records with the same FQDN/label as the one that disappeared exist in the zone?
Comment: @ShaneMadden: No these records have no scavenging set.
Comment: @MathiasR.Jessen: No
Comment: @Ablue Did the record actually get deleted, from all DNS servers that have the zone?  Or did it just not resolve from some places?  I'm having a hard time imagining how it might have gotten deleted.
Comment: @ShaneMadden: Yes, it was not present in the snap-in and nslookup said it didnt exist either. I couldn't believe such a problem could exist. I was very surprised.
Comment: @Ablue Interesting.  Do you by any chance have the `Active Directory Changes` audit subcategory set to log successful changes on your DCs?  I'm curious what happened to that entry's object.
Comment: @ShaneMadden: I don't. I am hesitant to try recreating the problem to gather information.
Comment: @Ablue Heh, fair enough.
Comment: @ShaneMadden:Can I ask you what your experience with link aggr in windows server has been? Do you use it? Do you do something different? Do you have any suggestions for safely load balancing network links in windows?
Comment: @Ablue My experience with it is pretty limited, but, not good.  The vendor-provided aggregation setups and their wacky virtual interfaces have caused me nothing but problems.  I haven't actually messed with the implementation in 2012, either, but I'd avoid aggregation until after upgrading to 2012.
Comment: @ShaneMadden: I really hoping that wasn't my only option.
Comment: @Ablue Well, what's the need for LACP?  Is it for redundancy or added bandwidth?  If it's redundancy, then I'd say get application redundancy in place in other ways - AD domains are very good about dealing with a domain controller being down.
Comment: @ShaneMadden I am not really concerned about DCs having LACP. It was other 2008 r2 servers; like a file server, or a CAS etc. This fault has made me question my assumptions around lacp and windows. In those situations I would really like additional bandwidth, but full lbfo would be ideal.
Comment: @ShaneMadden The inbuilt windows 'network bridge' creates a virtual interface that uses spanning tree to run a active/standby HA for network interfaces.
Comment: Eek, I wouldn't trust a bridge to speak spanning tree properly to the switches and not create a loop.  The approach that I've always taken would be to either cluster or DFS the file server, and stick multiple CAS servers behind reverse proxies or load balancers that do health checks.  Because NIC redundancy has been unsupported by MS for so long, I don't think it's very common to use LACP on physical Windows servers pre-2012.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11722/discussion-between-ablue-and-shane-madden)
Answer: Teaming with Broadcom or Intel is very widely used and in my experience has caused no problems.  I am not saying that a particular driver could not be buggy but it seems that jumping to conclusion that LACP is flaky in general is a bit of a red herring.  I would suspect a misconfiguration in the process of setting it up is far more likely.
Comment: Same here, I've been using Broadcom and Intel teaming for many years on physical domain controllers (2003 R2 and 2008 R2) without problems.
Comment: So as far as you are concerned the causes for the described issue are limited to a bad driver or mis-configuration?
Comment: Seen this one? Might be to do with service start order http://serverfault.com/questions/120052/windows-2003-domain-controller-very-upset-about-nic-teaming?rq=1
Answer: Looks like it is probably not a good idea to use third party link aggregation software on windows server.
Possible solutions include:

Upgrade to 2012
P2V servers
Cluster instead
Commit seppuku

Link Aggregation & Windows Servers


Responsive Margins with React

Question: I am currently experiencing a structural problem with React and styled-components where I cannot find a seemingly nice solution for every case.
Here's the (quite simple) problem:
<Margin top="10%" left="5%">
    <Card>Some text</Card>
</Margin>

The Margin component extracts the margin settings from the Card component so that the Card component can be reused in other scenarios. The Margin component itself can be reused aswell.
If one wanted to make this responsive though, it would only be possible via different props like topPhone, topTablet and so on, which I find very unintuitive and hard to maintain if the responsive boundaries ever change.
So what one could do is duplicate all the content into different other components and display only the one that currently fits (e.g. react-responsive's MediaQuery component).
But in that case, the page would have a lot of overhead for different device sizes.
What would be the best way to approach this?
Answer: Here's an outline of the implementation I use (slimmed down), it may fit your case. It involves a little set up but helps keep responsive boundaries maintainable (which I believe is the main concern).
1) Setup an object with your desired responsive boundaries:
const screenSize = {
  sm: 576,
  md: 768,
  lg: 992,
};

2) Create a Theme to help pass those boundaries through your application via styled-components. Here I set them up with the breakpoints (media-queries) in mind, using something like Bootstrap as a guideline (These should be extended to include smMin, mdMin etc):
const theme = () => {
  return {
    xsMax: screenSize.sm - 1 + 'px',
    smMax: screenSize.md - 1 + 'px',
    mdMax: screenSize.lg - 1 + 'px',
  };
};

3) Wrap your application with your Theme as mention here.
render() {
  return (
    <ThemeProvider theme={theme}>
      <MyApplication />
    </ThemeProvider>
  )
}

4) Using styled-components' tips-and-tricks as an example. Create an exportable media helper to make use of those Theme breakpoints (I'll only illustrate 2 breakpoints, but you should expand this to include xsDown, smDown, lgUp, mdOnly etc etc)
export const media = {
  smDown: (...args) => css`
    @media (max-width: ${({ theme }) => theme.smMax}) {
      ${css(...args)};
    }
  `,
  mdDown: (...args) => css`
    @media (max-width: ${({ theme }) => theme.mdMax}) {
      ${css(...args)};
    }
  `,
};

5) import media and use it like a normal old media-query wrapping your responsive styling:
const MyComponent = styled('section')`
  /* Everything to be pink on screens with widths < 768px */
  ${media.smDown`
    * {
      background: papayawhip;
    }
  `};
`;

const MyOtherComponent = styled('li')`
  /* Everything to be purple on screens with widths < 992px */
  ${media.mdDown`
    * {
      background: purple;
    }
  `};
`;

You can import media and reused it in Margin or any other component in your application. Responsive boundaries are maintained in one place.
Comment: This is a nice solution for media queries, but does not answer my question. I need to change margins which the component should not know about. The margin component itself should be reusable. Therefore, this approach is not what I was looking for. Sorry
Answer: Have you checked out react-socks yet? It helps building responsive React components.
<Breakpoint topPhone only>

I will render only in topPhone

</Breakpoint>

<Breakpoint topTablet only>

I will render only in topTablet

</Breakpoint>

Disclaimer: I am the author of this library.
Comment: As I've described, approaches like this result in overhead for different device sizes if you compare the React output. I'm looking for a no-overhead solution.

Responsive Margins with React


Machine Learning with Aggregated Frequency Data as Training

Question: I am trying to build a Deep Learning model in which I have the following structure

user
feature
binary_label

1
100
0

2
200
1

3
140
0

...
...
...

6000000
188
1

But the problem is that when I try to use all data I am running out of memory.
Since some users have the same features and labels I rewrote my SQL to
select
  count(user) users,
  feature,
  binary_label
from
  table
group by 2,3

which returns

users
feature
binary_label

1132
100
0

2
200
1

3435
140
0

...
...
...

3251
188
1

Since my users are aggregated I cannot parse that as an input as my prediction users would always be one (prediction per user). I think I'd lose value if I only use the feature since I believe the number of users falling in a particular segment adds weight to the prediction model. What would be the best approach to be able to use this column in python?
The current model that only uses the feature is
X_train, X_test, y_train, y_test = train_test_split(
    df.feature.values,
    df.binary_label.values,
    test_size=.2,
    shuffle=True)

model = Sequential()

model.add(Dense(4, input_shape=(1,), activation='tanh'))
model.add(Dense(1, activation='sigmoid'))

model.compile(optimizer='sgd', loss='binary_crossentropy')

model.fit(X_train, y_train, epochs=100)

model.evaluate(X_test, y_test)

Which when evaluated returns .7
Answer: The loss function binary_crossentropy is equivalent to the negative log-likelihood of a Bernoulli model that estimates a success probability $p$. In this case, you're using a neural network $f$ to estimate $p$ as a function of the feature $x$, so we have $f(x_i)=p_i$. It's perfectly appropriate to use binary_crossentropy in the first case, where each observation is a single trial of the binary outcome $y\in \{0,1\}$.
And you are correct, that we should be able to compress the data in some manner. This answer shows how to do so by exploiting the connection between the Bernoulli distribution and the binomial distribution.
We can compress that data by grouping the like observations together, which we can do by adjusting your SQL query.
select
  feature,
  count(*) as n,
  sum(binary_label) as k
from
  table_name
group by feature

This tells us how many trials $n$ were undertaken, and how many of those trials $k$ were a success at each value of feature. When you repeat a Bernoulli trial for a fixed number of times $n$ and the trials have fixed probability of success $p$ and the trials are independent, the distribution of successes $k$ is a binomial random variable.
A binomial random variable has cross entropy (negative log-likelihood) given by
$$\begin{align}
L &= \prod_{i=1}^N \binom{n_i}{k_i} p_i^{k_i}  (1-p_i)^{n_i-k_i} \\
-\log L &= -\sum_{i=1}^N \left[ \log\binom{n_i}{k_i} + k_i \log p_i + (n_i-k_i)\log(1-p_i) \right] \\
&= -k_i \log p_i - (n_i - k_i)\log(1-p_i) +C
\end{align}$$
where $i$ indexes the rows in your SQL output.
This function should be immediately recognizable as the Bernoulli cross-entropy function, except we've weighted it by the number of successes $k$ and failures $n-k$. (We can drop the binomial coefficient from the expression because it is not a function of $p$, so it does not change the location of any optima.) We can use this loss function in place of binary_crossentropy.
Here's what this looks like in psuedocode.
f = SomeNeuralNetwork()
train_data = SqlQuery("select feature, count(*) as n, sum(binary_label) as k from table name group by feature;")
for x, n, k in train_data:
    p = f(x)
    loss = - k * log(p) - (n - k) * log(1 - p)
    backprop_update(loss)

I don't think Keras has a native implementation of this loss function, so if you use Keras, you'll have to do that yourself (I explain this in a comment). Pytorch does have an implementation, but you'll need to do a little algebra to use it, as Jonny Lomond explains in a comment:

[T]his loss function is equivalent to passing $k_i/n_i$ as the target and passing $n_i$ as the sample weight with [BCELoss].

In a comment, OP says

I'm gonna be honest with you I got lost with this response. I guess I am still a beginner. I've used your suggestion though to get sum(binary_label) and created a calculated label using sum(binary_label) / count(*). I've then fitted a poly to get the 'predicted' probability for a feature so any >=50% = 1 and any <50% = 0. Would using a deep learning model, in this case, be more suitable?

This relabeling scheme is a very bad idea! This has no relation to the original model that you want to fit, and will badly bias your model.
Comment: (+1) Want to point out that, I think, this loss function is equivalent to passing $k_i/n_i$ as the target and passing $n_i$ as the sample weight with `binary_crossentropy`, so there's no need to implement a new loss function.

The resulting model will still be different than one trained on the full data because of differences unrelated to the loss function, for example the batches created with the uncompressed data will be different than those created with compressed data.
Comment: @JonnyLomond I understand what you mean, but my reading of the Keras documentation does not appear to support this usage. https://keras.io/api/losses/probabilistic_losses/#binary_crossentropy-function "`y_true` (true label): This is either 0 or 1" -- so we can't use the fractional representation you suggest and also there's no "weight" argument for in this documentation page. On the other hand, there are `pytorch` functions that work the way you outline: https://pytorch.org/docs/stable/generated/torch.nn.BCELoss.html
Comment: I'm gonna be honest with you I got lost with this response. I guess I am still a beginner. I've used your suggestion though to get sum(binary_label) and created a calculated label using sum(binary_label) / count(*). I've then fitted a poly to get the 'predicted' probability for a feature so any >=50% = 1 and any <50% = 0. Would using a deep learning model, in this case, be more suitable?
Comment: Relabeling your data in this way is a terrible idea, and fitting a deep neural network to it won't fix the problems that the relabeling creates. I've added some psuedocode to show you how this loss function actually works. The intuition should be obvious though: write down the binary cross entropy loss for 3 samples with the same value of feature (1 in one class, 2 in the other class) and then add them together. The result will look exactly like my loss expression.


ios7.1 beta - which version do i need?

Question: I'm trying to access the beta version of 7.1 but there are 2 version for the 3rd Gen iPad with 3G.  One is for AT&T, the other is for Verizon... but my iPad is UK version and as far as I know is neither of these.
Anyone know which I should download?
I did find this out months ago but it took for ever and I have lost my notes (and memory apparently).
Thanks
Rob
Answer:
First: Wifi only
Second: Cellular with SIM card slot
Third: Cellular without SIM card slot
But this question is really an off topic and could be easily done our good old friend, Google.
Comment: this allows to clearly see the version
Comment: Thanks!  I had no idea that was the difference.  I guess it must be the way I google, but results I kept getting were basically rehashes of the Apple instructions.  I must have spoken to about 20 different people at Apple last time (passed back and forth from Developer support to Product support) and they couldn't tell me this. Huh. Why they have to have a completely different model number for my iPad is a mystery.
Answer: According to this page there is no European version available for 3rd Generation iPad. The only ones available are iPad with retina display (3rd Generation) model A1430 which is for I believe a United States and Canada model number and iPad with Retina display (3rd Generation) Model A1403 which is United States model as well. If your model number matches A1430 or A1403 (Which I don't it will) you can try one of them or you could risk using the Wifi only version (Which doesn't seem to be in that list which models it will work on) but here is the download dmg (This may expire)
Comment: That was the problem I had last time.  There model number shows as MD370B/A.  I'll follow the advice above as I definitely have a SIM card.
Comment: @Bertie My recommendation would be unless your model number is included it isn't worth the risk. Someone at my company made this mistake last time for an iPhone 5 and they bricked it and we had to return it and get a new one, all because they didn't want to ask for advice of me - it was quite annoying. But it is your decision no one else's. They do model numbers for a reason and it can void your warranty if you stick the wrong one on.
Comment: Hahaha, I just noticed there is a second model number on the case which says A1430.  So partially my bad for assuming that the model number (in Settings->General->About) was, actually, the model number. But c'mon Apple wtf do I need 2 model numbers for?  Anyway A1430 it is...
Comment: @Bertie Normally the model number can be found on the back of the device. Glad you found it though.

ios7.1 beta - which version do i need?


Let $f(x)=x^2-kx$ and $g(x)=x^3-kx$, such that for a rational number $\alpha$, $f(\alpha)$ and $g(\alpha)$ both are rational numbers. Find k

Question: Let $f(x)=x^2-kx$ and $g(x)=x^3-kx$, $k\in\mathbb{R^+}$ be two real valued functions such that for a rational number $\alpha$, $f(\alpha)$ and $g(\alpha)$ both are rational numbers.
Find the range of values that $k$ can take.
My Attempt
If $k=1$ then given condition is trivially true. But can there be other values.
If $m$ and $n$ be rational numbers such that $\alpha^2-k\alpha=m$ and $\alpha^3-k\alpha=n$.
This would imply that $k$ is rational since $\alpha,m$ and $n$ are all rational
Also by eliminating $k$, we have $\alpha^2(\alpha-1)=n-m$.
But after this I reach some kind of dead end.
Comment: For any $\alpha \in \mathbb Q$ we have that $f(\alpha), g(\alpha) \in \mathbb Q$? Or are there some other restraints on $\alpha$ as well?
Comment: None given. But one thing comes to mind is tha $k^2+4m$ must be a perfect square.
Answer: The statement is a bit unclear. I think that you are saying that for a fixed rational $\alpha$, we have $f(\alpha)$ and $g(\alpha)$ are both rational. Then what possible values of $k$ are there (depending possibly on $\alpha$)?
That is, we know only that
\begin{align}
  \alpha^2 - k \alpha &= a \in \mathbb{Q} \\
  \alpha^3 - k \alpha &= b \in \mathbb{Q}.
\end{align}
If $\alpha = 0$, then $k$ can be anything and this is uninteresting. Suppose now that $\alpha \neq 0$. Then we can divide by $\alpha$ and find
\begin{align}
  \alpha - k &= a' \in \mathbb{Q} \\
  \alpha^2 - k &= b' \in \mathbb{Q}.
\end{align}
The first equation tells us that $k = \alpha - a' \in \mathbb{Q}$, and thus $k$ must be rational. Clearly any rational $k$ suffices.
We gain no new information from $g$, and we conclude that $k$ can be any rational when $\alpha \neq 0$, and otherwise $k$ has no restrictions.


Show that ${{n}\choose{k}} = {{n}\choose{n-k}}$ without using ${{n}\choose{k}} = \frac{n!}{k!(n-k)!}$

Question: Suppose $n,k \in \mathbb{Z} $ and $0 \leq k \leq n$. Show that ${{n}\choose{k}} = {{n}\choose{n-k}}$ without using ${{n}\choose{k}} = \frac{n!}{k!(n-k)!}$
It's easy to prove by using that definition, but I'm supposed to use the following fact:
"If $n$ and $k$ are integers, then ${{n}\choose{k}}$ denotes the number of subsets that can be made by choosing $k$ elements from a set with $n$ elements."
So if $S$ is a set and $|S| = n$, then ${{n}\choose{k}} = |\{X: X \in \wp(S)$ and $|X| = k \}|$ and  ${{n}\choose{n-k}} = |\{X: X \in \wp(S)$ and $|X| = n - k \}|$
From there, I'm stuck. Any hints?
Thank you.
Comment: Hint: If $|X|=k$, what is $|S-X|$?
Comment: *Choosing $k$ objects among $n$ objects is the same thing as* not choosing *(better: choosing not to take) $n-k$ objects among $n$ objects*.
Answer: Use the following bijection $$\varphi:\{X\ :\ X\in\wp(S), \vert{X}\vert=k \}\longrightarrow\{Y\ :\ Y\in\wp(S), \vert{Y}\vert=n-k\}$$ such that $X\longmapsto X^{c}$ where $X^{c}$ is the complement of $X$ w.r.t $\wp(S)$. This map is bijective because it is it's own inverse (is an involution on $\wp(S)$).
Answer: The answer just given got my vote but other people may prefer a more wordy version.
$n\choose k$ counts in how many ways you can pick $k$ elements from a bag of $n$ different elements.
$n\choose n-k$ counts in how many ways you can pick $n-k$ elements from the same bag.
Now imagine when you pick the $n-k$ elements, you leave remaining $k$ elements to your friend.
So $n \choose n-k$ also counts in how many ways your friend can receive $k$ elements from that bag, but there are $n\choose k$ such ways.
Answer: I am not sure if this is helpful and I think you are already well aware of this but just in case :
nCk denotes how many combinations are there to choose k items from a set of n items, but choosing k items is the also same as choosing and discarding (n-k) items, thus proven verbally.


Implicit form of an ellipse - Geometrical interpretation

Question: The general equation of an ellipse is:
$$\frac{x^2}{a^2} +\frac{y^2}{b^2}=1,$$
where $0<b \leq a$. It turns out that:
$$\begin{cases} x = a \cos(\alpha) \\y = b \sin(\alpha)\end{cases}, $$
where $\alpha \in [0, 2\pi]$.
Similarly, it turns out that:
$$\begin{cases} x = r(\theta) \cos(\theta) \\y = r(\theta) \sin(\theta)\end{cases}, $$
where $\theta \in [0, 2\pi]$ and
$$r(\theta) = \frac{ab}{\sqrt{(b \cos(\theta))^2+ (a\sin(\theta))^2} } . $$
The two formulations are so similar, but at the same time, they are different.
What is the geometrical difference of the angles $\alpha$ and $\theta$?
Comment: @user376343 It is not necessarily a circle, unless $a=b$ ($r(\theta)$ is a non-constant function in general)
Comment: See https://en.wikipedia.org/wiki/Ellipse#Polar_form_relative_to_center for $\theta$ and the diagram to the right of https://en.wikipedia.org/wiki/Ellipse#General_ellipse for $\alpha$.
Comment: Right @GReyes    thank you for pointing out my mistake.
Answer: The difference is as follows: $\theta$ is the polar angle of a generic point on the ellipse, and $r(\theta)$ the corresponding value of $r$ (which clearly changes with $\theta$ unless the ellipse is a circle). On the other hand, $\alpha$ has the following meaning: draw a vertical line through a point on the ellipse and consider the intersection of that line with the circle of radius $a$ concentric with the ellipse (this circle is tangent to the ellipse at $(a,0)$ and $(-a,0)$). Then, $\alpha$ is the polar angle of that point of intersection. The ellipse is just a shrunk version of the circle of radius $a$ with scaling factor $b/a$. If you start with the circle $x=a\cos\alpha$ $y=a\sin\alpha$ and you multiply $y$ by the scaling factor you get the equation of the ellipse, but of course $\alpha$ keeps its original meaning, the one I explained above. Hope this helps.


MSTest Deployment without DeploymentItemAttribute

Question: Is there any way to deploy an item without using this attribute? I'm starting to get a stack of attributes over my test base and it's becoming hard to maintain. Most of my items are DLLs that need to be put into a folder below the deployment directory.
Answer: You can define them in the local test run configuration.
Test => Edit Test run configurations => choose one.
Go to the deployment section, add you deployment items.
The problem here is that you need to maintain the test run configurations, which is sometimes not better then maintaining the attributes. Even more, the tests are not self contained anymore, they depend on this configuration. And - the deployment items are deployed even if you only run a single test which wouldn't need it. But sometimes its easier here.
IMHO, MSTest is quite half-baked. Deployment items are a nightmare.
Comment: I'll see if using the TestRunConfig makes this less painful. Thanks for the suggestion. Yeah and these cookies are not done at all..
Comment: I ended up referencing the assemblies I needed so they would be copied to the test output directory. From there I could copy then to where I needed them.


Explain how ubuntu 9.04 apache2 processes are managed to me

Question: Ok every so often my website which runs on a ubuntu 9.04 vps seems to fall over as apache does not seem to respond.
a simple apache restart solves the issue but obviously it's not a good scenario having to manually restart the server every time this happens.
the site is a wordpress site with minimal traffic (max. 200 visitors a day)
i've also got php running as an apache mod with APC caching setup.
i removed some processes which were running on the server like clamav which has reduced memory usage somewhat (server has half a gig of RAM).
users report seeing "out of memory" errors just before apache becomes responsive.
running a top command on the server now shows approx 50% memory usage.
the apache error logs not showing anything interesting either.
but running a top command shows me there are 4 unique instances of apache2 running - each consuming about 15% of memory. The cpu is at 0%
Can anyone explain why there are 4 individual apache processes running and how to manage these correctly?
Thanks all.
Ed
Answer:
but running a top command shows me
  there are 4 unique instances of
  apache2 running - each consuming about
  15% of memory. The cpu is at 0%

What you are probably seeing is Apache with its child processes ready to serve requests. You most likely don't have to manage those (other than make sure you don't have too high MaxClients defined, so a sudden traffic spike won't eat up all the available RAM and other resources).
Instead you need to find out what is taking up so much memory - Apache itself is definitely not the most light-weight web server out there, but it's not THAT heavy. Most likely something causes the PHP take up lots of memory; perhaps you have very high memory limits defined for APC?
Also, with that kind of low traffic, are you sure you really need APC? For me it seems the RAM is the weakest link in your server, so it would make sense to strip out every RAM consuming extension there is now installed.
Here's my suggestion for you:
1) Benchmark your site with APC enabled, use for example siege - it's available in Ubuntu repositories, so apt-get install siege should install it. Let it run for a while, see the results and also see if siege shoots down your Apache.
2) Disable APC, repeat the test. If the results are similar or better to previous one and/or Apache survives this test without running out of memory, leave your server without APC for now.
If you want to try completely different route, lighttpd with fcgi is a more lightweight and also more controllable combination. In that case lighttpd only server the http-requests and PHP parsing is done on fcgi backend. You can define how many fcgi backend processes there are waiting, so even a sudden spike in traffic does not eat up much more RAM, in the worst case it makes the site slower or causes some "500 Server too busy" errors, but you don't need to restart anything.
Comment: thanks Janne for the really detailed reply. I'm going to do as you've suggested and run some benchmarks with and without APC and see what happens.


Ucontext gets blocked signal after swapcontext

Question: I am blocking a SIGINT in ucontext A, for example, say I hit ^C (SIGINT) while it is running, nothing happens as expected.
In context B, there is a SIGINT handler.
When I swapcontext(A, B) then ucontext B immediately executes the signal handler. Even though context A is the one that received and blocked this signal.
Is there a way to ensure process B does not enter the signal handler right away?
Comment: Blocking a signal is not the same as discarding it.
Comment: See: https://stackoverflow.com/questions/63866300/does-a-blocked-signal-also-a-pending-signal
Answer: While I did not figure this out, using a critical flag, instead of blocking the signal was what I used.
Comment: please add some example in your answer.


Something overriding PHP.ini setting, not htaccess. Need suggestion

Question: I'm struggling to find where a specific PHP.ini setting is being overridden in my AWS Linux 2 instance with PHP 7.3.11 and httpd 2.4.  I am trying to set
mysqli.allow_local_infile = On
I have set it correctly in the PHP.ini file as you can see here (and restarted httpd)
Here's my PHP.ini file
I then used grep to check the setting from the command line:
Shows the allow_local_infile setting is On
But when I go to phpinfo.php that I have set up on my httpd webserver it shows allow_local_infile = Off:
phpinfo.php shows allow_local_infile = Off
Any suggestions where something else could be set that would override?  It's not in an htaccess file because I don't have it enabled at the moment.  Plus I don't believe allow_local_infile the value can be overridden at the htaccess level.
Thanks in advance for your help!
Comment: Can you check in your phpinfo.php that the path to php.ini is correct ?
Comment: Thanks Swisstone.  Good question.  I have checked several times and it is correct.
Answer: Ok, that answer to the question is that I needed to restart the AWS EC2 instance.  Simply restarting httpd didn't do it.  Apparently the value was cached somewhere and the restart was needed to fix it.
When all else fails, restart the AWS instance, not just service.
Comment: Were you using fpm or fcgi? Restarting httpd wouldn't pick up the changes if so.


Automatically add a new node to a drop-down menu

Question: When a user creates a node of a certain type, I want that node to be added to a drop-down menu at the top of the screen: i.e., so that when the user mouseovers the parent item in that menu, a list of all the nodes of that type is displayed. What's the best way to achieve this?
Answer: I achieved this effect by using https://drupal.org/project/nice_menus, and building a view that contains all of the nodes I want displayed in the drop-down. Then https://drupal.org/project/menu_views can display that view as menu items within the menu that Nice Menus has built.