ASP.NET Core MVC - Passing Model Data Back to Controller from View

Question: Should be a relatively simple question but currently I'm not able to pass model values updated in the view back to the controller.
As you can see below we have a very simple dropdown list in the view. The 'tenant' string in the Model should be getting set with whichever value is selected in the dropdown list.
However, when clicking on the submit button the 'tenant' string returns null in the controller...
What am I missing?
Thanks!
Model:
public class TenantModel
    {
        public List<string> tenantList { get; set; }

        public string tenant { get; set; }
    }

View:
@model TenantModel

@{
    ViewData["Title"] = "Manage";
}

Manage Databases

@Html.DropDownListFor(m => m.tenant, new SelectList(Model.tenantList), "Select Tenant", new { @class = "dropdown", @style = "width: 220px" })

<button type="submit" onclick="firstname.lastname@example.com("DropDbs", "Environments", Model)'" class="btn btn-danger">Destroy</button>

Controller
    public class EnvironmentsController : Controller
    {

        public IActionResult Manage()
        {
            var tenantModel = new TenantModel();

            tenantModel.tenantList = Utils.TenantList();

            return View(tenantModel);
        }

        public IActionResult DropDbs(TenantModel tenantModel)
        {

            return RedirectToAction("Manage");
        }
    }

Comment: where is your form tag or Html.BeginForm?
Answer:
I want to have multiple buttons on the form each targeting a different action inside my controller.

In Asp.net core MVC, you can use tag helper asp- to implement it.
<form method="post">
    @Html.DropDownListFor(m => m.tenant, new SelectList(Model.tenantList), "Select Tenant", new { @class = "dropdown", @style = "width: 220px" })

    <button type="submit" asp-action="Action1" asp-controller="Controller" class="btn btn-danger">Operate1</button>
    <button type="submit" asp-action="Action2" asp-controller="Controller" class="btn btn-danger">Operate2</button>
    <button type="submit" asp-action="Action3" asp-controller="Controller" class="btn btn-danger">Operate3</button>

</form>

Comment: Thanks, I did try this but wasn't able to get it to work initially, I think I was missing the form tags around the buttons, adding these in seems to have done the trick.
Answer: You're all doing wrong. You're redirecting to action and passing a Model but problem is that not going to fill by your dropdown that why it's null.
You need to wrap your dropdown in form tag and post form to the action.
Comment: Thanks - if I wrap it in @using (Html.BeginForm("DropDbs", "Environments", FormMethod.Post) it does work and passes the 'tenant' string through BUT I can only target a single action this way, I want to have multiple buttons on the form each targeting a different action inside my controller.
Comment: Use hidden field as tag to identify operation and change field on button click and then submit Form.


Is this true (Trigonometry) and if so, can it be proved by induction?

Question: I'm considering functions of the form $\cos{(n\theta)}+\sin{(n\theta)}$ and have noticed that when $n=4k+1$ for positive integers $k$ the expression seems to be divisible by $\cos{\theta}+\sin{\theta}$ (also works in the trivial case when $k=0$) and when $n=4k-1$ the expression is divisible by $\cos{\theta}-\sin{\theta}$
I've tested this idea for a few integers $k$ and it seems to work, so I'm wondering if it can be proven. Induction seems like the logical choice but exactly how to proceed is, for now, beyond my grasp.
Does anyone have any ideas?
(or a counter-example?)
Comment: Does "divisible" here mean the quotient is an integer?
Comment: @fleablood For what it's worth, depending on the browser magnification, your first posted comment is hard to read.  MathSE comments do not always format *run-on* math expressions well.  True that avoiding such run-ons does makes it difficult for you to express the math ideas.
Comment: If you want to try induction you can try expanding $\cos([4(k+1)+1]\theta) = \cos((4k+1)\theta + 4\theta) = \cos((4k+1) \theta)\cos(4\theta) -\sin((4k+1) \theta)\sin (4\theta)$ and $\sin([4(k+1)+1]\theta)=\sin((4k+1)\theta + 4\theta) = \sin((4k+1)\theta\cos(4\theta) + \cos((4k+1)\theta)\sin (4\theta)$. Does that work?
Comment: Actually,   If you state you proposition as $\cos((4k\pm 1)\theta) + \sin((4k\pm 1)\theta)$ is divisible by $\cos \theta \pm \sin \theta$ then doing induction by expanding $\cos([4(k\pm 1)\theta + 2\theta)$ will do it in my comment above.
Comment: @peterwhy - I mean that $\cos{\theta}+\sin{\theta}$ is a factor. I'm not sure "integer" has a proper meaning in this instance.
Comment: @fleablood - that is basically what I started doing. It certainly worked for SPECIFIC values of $k$, but I'm not yet seeing how it works for ALL.
Answer: Let $\varepsilon=\pm1$. First note that $\cos t+\varepsilon\sin t=\sqrt2\cos(t-\varepsilon\pi/4)$, so that your question amounts to

Prove that $\cos(\theta-\varepsilon\pi/4)$ divides $\cos((4k+1)\theta-\varepsilon\pi/4)$.

Moreover, letting $x:=\theta-\varepsilon\pi/4$, we have $\cos((4k+1)x)=\cos((4k+1)\theta-\varepsilon k\pi-\varepsilon\pi/4)=(-1)^k\cos((4k+1)\theta-\varepsilon\pi/4)$, so the task simplifies to:

Prove that $\cos x$ divides $\cos((4k+1)x)$.

Actually, we even have
$$\forall n\text{ odd},\quad\cos x\mid\cos(nx)=T_n(\cos x)\quad\text{in}\quad\Bbb Z[\cos x]$$
since the $n$th Chebyshev polynomial $T_n(X)\in\Bbb Z[X]$ has the parity of $n$ (there are many ways to prove it, including induction).
Edit: alternatively,

either notice directly (using De Moivre's formula and the binomial theorem) that
$$\begin{align}\cos((2m+1)x)&=\operatorname{Re}\left((\cos x+i\sin x)^{2m+1}\right)\\&=\sum_{j=0}^m\binom{2m+1}{2j}(-1)^j\sin^{2j}x\cos^{2m+1-2j}x\\
&=\cos x\sum_{j=0}^m\binom{2m+1}{2j}(\cos^2x-1)^j\cos^{2m+1-2j}x
\end{align}$$
or use induction:
$$\cos((2m+1)x)=2\cos x\cos(2mx)-\cos((2m-1)x).$$
Comment: Ah... thanks @Anne... that $\cos{((2m+1)x)$ expansion is a stroke of genius! Brilliant.
Comment: Thanks - a good answer, but a bit more complicated than what I was hoping for. I have a very limited understanding of Chebyshev polynomials (I do not doubt their usefulness, it is just a more difficult idea than I think/hope the problem requires).   I was hoping/thinking that a more fundamental induction proof was possible, along the lines suggested by @fleablood.


Most braces in one season in Premier League

Question: What is the record of most braces in the Premier League season and who holds it?
Braces - two (or more) goals in a match (if I'm correct)
Comment: Welcome to Sports Stack Exchange. A brace is typically defined as two, with a hat trick being three (and beyond this somewhat depending on the sport and the country). Can you clarify that you are looking for player with most matches scoring more than one (two or more), or just exactly two goals?
Comment: @Nij - two or more
Answer: This is what I've managed to find:
42-match season:
Alan Shearer (93/94) - 10 times 2 or more goals
38-match season:
Kevin Phillips (99/00), Thierry Henry (05/06), Cristiano Ronaldo (07/08), Luis Suarez (13/14) - 9 times 2 or more goals


Is it possible to play Jordan by Buckethead without kill switch?

Question: I don't want to destroy my Les Paul by drilling any holes into it. I've seen someone create a kill switch that you can take off anytime but I don't know how to use a soldering iron. I also do not want to use the toggle since I've heard it destroys the wires that connects it to the neck and bridge.
Comment: More likely to wear out the switch itself than destroy the wires.
Comment: As I mention in the other comment, I doubt you'll destroy anything by using the pickup selector as a kill switch. If you somehow did wear out the switch, they are easy to replace.
Comment: Is your question about playing Jordan without using a kill switch at all, or implementing an equivalent without modifying your guitar?
Comment: Little bit of both
Comment: So learn to solder.  It's not hard.  At some point you'll want that skill, along with wire strippers, voltmeters, etc. if you continue using electronics (a category that electric guitars, pedals, amps belong to)
Comment: You definitely need to learn to solder on. (-;
Comment: Another way to do this without modifying the guitar is to make cable splice adapter: you can wire up two 1/4 jacks with a "normally closed" momentary switch (use a length of wire fro the switch connection and use double-sided tape etc to attach the switch to a convenient location; attach the adapter to the guitar using a short patch cable, connecting the other end to the normal cable.
Answer: If your guitar has two pickups and a volume knob for each of them you can put the one pickup on 10 and the other one on 0 and use your pickup selector switch as a kill switch.
That is in fact how Tom Morello used a kill switch for many years before he got his custom made guitars.
EDIT:
Just note that if you do this and you use your pickup selector switch as a kill switch you are probably going to wear that pickup switch out many times.
You mention wanting to use a Les Paul but make sure it is not a guitar that should be kept mint. That pickup selector switch probably never built for the vigorous switching that a kill switch has to endure.
So just make sure you do this on a guitar that can have switches replaced.
Comment: I wouldn't cry at all about replacing a pickup selector on any Les Paul. It's literally the easiest wiring job I can think of for any electric guitar. You don't even have to take off the strings. At the same time, if you look at the design and construction of the Les Paul pickup selector, it is a fairly simple and reliable design that would be very hard to break. And you better believe I have a strong sentimental attachment to my first real guitar, the aforementioned Studio that I've had for over 20 years!
Comment: I have a 1995 Les Paul Studio and I have used the pickup selector as a kill switch to do Rage songs many times over the 21 years I've had that guitar and I've never had to replace the pickup selector. I **did** have to replace the little plastic knob on the end but I think that was due to impact. Either way, it was like $3 and 30 seconds work
Comment: It is OK to replace things on a Studio but can you think how long you would cry if you had to do that on a custom. My point is just if you have a sentimental attachment to your guitar than maybe do this with another one.
Comment: Ah, now that I think about it, the output jack on a Strat-style guitar would be slightly easier than a Les Paul style pickup selector. It's only a few screws to undo and no string removal either way, but the Strat output jack is only two wires and the pickup selector is three. So, *second* easiest wiring job I can think of for any electric guitar.
Answer: I would suggest building a switch box for the floor. A light-action microswitch built into a metal box, similar to a standard effects pedal. This could even be used while picking.
The only limitation I can see is it can only be used as quickly as you can tap your foot...
Comment: I used to have a tremolo box which would do this: turn the signal off and on repeatedly.
Answer: This question reminds me of a project called the Scrub Board by Jeremy Bell.
http://jeremyseanbell.com/scrubboard/rocker.html
I'm not sure what state it's in, but half of the project was a home-made "rocker" to cut audio signals in and out. Made from a couple of coins and a rocking piece of foil. There are videos of him using it with his guitar (as well as looping and delay effects).
If you could get a kit, or construct one of your own, that would create the effect you want.
(Again, I'm not sure if this is something you could easily do at the moment.)
Answer: Get a D'addario circuit breaker cable it has a built-in kill switch you could if you wanted have the button side plugged into your effects & use it without your feet or your hand or you can get a mute pedal or something like that


How to "dereference a type" in C++03?

Question: How do I get the "dereferenced type" of another type in C++03?  Note that it can be other dereferenceable type like std::vector<int>::iterator.
e.g. if I have
template<typename T>
struct MyPointer
{
    T p;
    ??? operator *() { return *p; }
};

How can I figure out what to replace the ??? with?
(No Boost! I want to know how to figure it out myself.)
Comment: @Tux-D Mehrdad is saying that he doesn't want to restrict the templatized type to pointers only, since non-pointer types may overload `operator*` as well.
Comment: Why not make the T the type that is being pointed at. That why you will know both the pointer type `T* p` and the type to return `T operator*()`
Comment: @Tux-D: Because you can't assume `p` is a pointer.
Comment: I must be missing something. I am saying you can explicitly make it a pointer by making T the type that is pointed at. Thus you define p as 'T* p'.
Comment: For anyone looking for the C++11 version of the question: http://stackoverflow.com/questions/14471224/c11-how-to-get-the-type-a-pointer-or-iterator-points-to
Answer: template<typename>
struct dereference;

template<typename T>
struct dereference<T*>
{
    typedef typename T type;
};

template<typename T>
struct MyPointer
{
    T p;
    typename dereference<T>::type operator *() { return *p; }
};

Comment: @Paul: Mehrdad asked how do dereference a type, I provided an answer.
Comment: This looks best. However, what about types that overload `operator*`?
Comment: @Mehrdad: Sure I can, the compiler will complain if you supply a non-pointer type.
Comment: @Mehrdad: Do you want your program to work with non-pointer types that have an overloaded `operator*`, or do you want it to fail for those types?
Comment: Is there not a standard naming convention that recommends a type have the typedef(s) value_type/pointer_type/reference_type if it overloads operators like *? If you make that assumption then you can a default version of deference. It if they don't follow that convention you still get a compiler error (best of both worlds). Anyway +1,
Comment: Why complicate things with yet another template?
Comment: FredOverflow: I was referring to what @UncleBens mentioned -- you can't be sure that `p` is a pointer. It might have just overloaded `operator*`.
Comment: That works in the simplest case, but needs handling for e.g. `int* const` or `int* volatile`. Also, what UncleBens said.
Comment: @Mehrdad if it has overloaded `operator*`, then it's a class and you can require it to have a proper typedef or require it to specialize `dereference`
Answer: In the general case, you can't. For raw pointers, you can partially specialize as shown in other answers- custom smart pointers may have a common typedef for the result type. However, you cannot write a single function that will cope with any pointer in C++03.
Comment: @DeadMG:  can't the return type simply be `typename std::iterator_traits::value_type`?  Anything passed to a `MyPointer` class should probably also overload `iterator_traits`.
Comment: Seems like the correct answer, as much as I wasn't hoping for it to be. :) Thanks!
Answer: You can have a simple construct which recursively removes all the pointers from a given type as below:
template<typename T>
struct ActualType { typedef T type; };
template<typename T>
struct ActualType<T*> { typedef typename ActualType<T>::type type; };

Below is the inline wrapper function to recursively find out the actual value from a given pointer or non-pointer types;
template<typename T>
typename ActualType<T>::type ActualValue (const T &obj) { return obj; }
template<typename T>
typename ActualType<T>::type ActualValue (T *p) { return ActualValue(*p); }

And just use it as:
template<typename T>
struct MyPointer
{
  T p;
  typename ActualType<T>::type operator *() { return ActualValue(p); }
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^                       ^^^^^^^^^^^^^^
};

In this example, it removes all the pointers from a given type, but as per the need you can configure the ActualType<> and ActualValue<>. There won't be any compiler error even if you declare MyPointer<> with a non-pointer type.
Here is a working demo for a single pointer and no pointer types.
Comment: But that has the problem described in the comments to Paul Manta's old answer. It doesn't work for types that are not pointer types. `operator*` can be overloaded for a non-pointer type.
Comment: @jogojapan, it will work. See the edited answer with [demo](http://ideone.com/AoVsLX).
Comment: That seems to be a special case, where `MyPointer` has its `operator*` defined such it returns an object of type `ActualType::type`. But how do you get this to work if you have an arbitrary class, with an  `operator*` that returns an arbitrary data type?
Comment: @jogojapan, then it will be a compiler error and I don't think OP has any intention to return any arbitrary type. One has to use `ActualType<>` and `ActualValue<>` in combination to get the real object type and value.
Answer: You can do it like this, and it is ensured that the template will only compile when you pass pointers to it:
template<typename T>
struct MyPointer<T*>
{
    T* p;
    T operator*() { return *p; }
}

Comment: I mean you cannot assume that `p` is a pointer **in my example**. It may simply be that `p` has `operator*` overloaded instead.
Comment: @Mehrad Yes you can. In fact you are sure of it. Look at the second line of the code, and see the specialization of the template.

How to "dereference a type" in C++03?


What are the differences between different marching music traditions?

Question: I've often heard of people talking about "prussian marches" or "british marches" in the context of a style of march. It seems that they could tell just by hearing a march as to what tradition it's from and what's the appropriate style of marching would be. Are there noticeable and identifiable distinctions between the marches of various nations and if yes, how can one tell?
Comment: Have you seen that the Wikipedia entry on March (music) has a section about [National Styles](https://en.wikipedia.org/wiki/March_%28music%29) in march music? This looks like a good start.
Comment: I didn't know about this link and I'm surprised how my comparision of the styles is confirmed by this comments. And yes, I forgot to mention the great countermelodies in the English marches and the genius Bass Solos!
Answer: This answer will be quite opinion based. But I am pretty sure that the prussian marches are influenced by the instrument setting:
They use rather trumpets,  woodwind instruments,french horns, baritones and the result is a thinner sound, paired with simpler harmonies remaining in the main chords tonic, dominant, subdominant, with fanfares (trumpets), trillers (clarinets, flutes) and horn fifths.
Thats my impression and memories that I have from the few prussian marches we used to play in military service,
while in the british marches using cornets, tenor horns, euphoniums, rarely woodwind instrument the sound is rounder, softer, less military like, based on more interesting harmonies, in a less military way and sound.
Marches are not my favorite music, but there are a dozen  Salvation Army marches of Eric Ball, Ray Steadman-Allen, Erik Leidzen, Dean Goffin, Eric Silfverberg, Donald Osgood, Leslie Condon, Wilfred Heaton etc. for which I would lay my hand in the fire that they are fantastic music, smart, intelligent, tuneful, while the German or also traditional Swiss marches (influenced by the prussian) are really simple, sorry, not to say primitive.
I forgot to mention the great countermelodies in the English marches and the genius Bass Solos!
As an example of a very special festival march I allow myself to post one of my favorites:

(please don't watch the conductor! I never dance
 around like him!)
Comment: Extra credit for anyone who can find a march with an odd-count meter (3/4, 5/4,...)
Comment: @CarlWitthoft - Does Schumann's "Marche des Davidsbündler contre les Philistins" at the end of his *Carnaval* count?
Comment: (If you want I can post you a  list of some really good british marches.)
Comment: yes, that would be great! If you know anything about austrian marches, can you also compare those to the prussian ones?
Comment: No, I never played some of them.
Comment: @SalmonKiller: I will post you a list of really good marches if you send me your e-mail on facebook.
Comment: Then there's the "County Band March"  :-) .


Running .bat file before .exe automatically in Advanced Installer

Question: I'm new to Advanced Installer. After Installing the file setup, I need to run a ".bat" file before running my ".exe" file every time. I found to add it, setting it's attributes as (Hidden, Vital and System), but I need to run it every time before lunching the application.
Please help me, Thanks
Answer: If you're launching the application as a Finish Action from the Dialogs page, here are the steps:

go to Custom Actions page and add a Launch File custom action without sequence to launch the BAT file
enable the custom action's "When the system is being modified (deferred)" and "Run under the System account with full privileges (no impersonation)" options
go to Dialogs page, select the ExitDialog from First Time Install in the Install Sequence
select the Finish button then go to its Published Events tab and enable "Show all events" option
add an "Execute custom action" event passing in the "Launch file" created above as an argument
set the event's condition to the checkbox's name so the BAT doesn't execute unless the user selects the checkbox to launch your application
make sure the event is the first one in the Published Events list so it gets executed before the event that launches your application

There are a couple of articles to help you with other details:
How to launch a CMD or BAT file?
How to launch a file after an installation?
The main thing you need to consider is to run the event that executes the BAT custom action before the event that launches your application.
Also, I'm not sure you can do this from a Professional project type. You may need Enterprise or Architect.


How to use addOverrideApn() method in Android API level 28?

Question: I'm trying to create a mobile application to manage APN(Access Point Name). In first I need to add an APN into the mobile application. I followed this documentation.
https://developer.android.com/reference/android/telephony/data/ApnSetting.Builder
I did as follows.
package com.example.myapplication;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.telephony.data.ApnSetting;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity {
    private static String TAG = "MainActivity";

    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create an MMS proxy address with a hostname. A network might not be
        // available, so supply a dummy (0.0.0.0) IPv4 address to avoid DNS lookup.
        String host = "mms.example.com";
        byte[] ipAddress = new byte[4];
        InetAddress mmsProxy;
        try {
            mmsProxy = InetAddress.getByAddress(host, ipAddress);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return;
        }
        ApnSetting apn=null;
        try{
           apn = new ApnSetting.Builder()
                .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT | ApnSetting.TYPE_MMS)
                .setApnName("apn.example.com")
                .setEntryName("Example Carrier APN")
                .setMmsc(Uri.parse("http://mms.example.com:8002"))
                .setMmsProxyAddress(mmsProxy)
                .setMmsProxyPort(8799)
                .build();
        }catch (NoClassDefFoundError error){
            error.printStackTrace();
        }
        ComponentName componentName = new ComponentName(this, MainActivity.class);
        DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getApplicationContext().getSystemService(Context.DEVICE_POLICY_SERVICE);
        devicePolicyManager.addOverrideApn(componentName,apn);
    }
}

But it gets the following error.
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 24556
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.SecurityException: No active admin ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3160)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3303)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1991)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7258)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Caused by: java.lang.SecurityException: No active admin ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}
    at android.os.Parcel.createException(Parcel.java:1966)
    at android.os.Parcel.readException(Parcel.java:1934)
    at android.os.Parcel.readException(Parcel.java:1884)
    at android.app.admin.IDevicePolicyManager$Stub$Proxy.addOverrideApn(IDevicePolicyManager.java:11791)
    at android.app.admin.DevicePolicyManager.addOverrideApn(DevicePolicyManager.java:10785)
    at com.example.myapplication.MainActivity.onCreate(MainActivity.java:54)
    at android.app.Activity.performCreate(Activity.java:7353)
    at android.app.Activity.performCreate(Activity.java:7344)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1275)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3140)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3303)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1991)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7258)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Caused by: android.os.RemoteException: Remote stack trace:
    at com.android.server.devicepolicy.DevicePolicyManagerService.getActiveAdminWithPolicyForUidLocked(DevicePolicyManagerService.java:3080)
    at com.android.server.devicepolicy.DevicePolicyManagerService.getActiveAdminForCallerLocked(DevicePolicyManagerService.java:3017)
    at com.android.server.devicepolicy.DevicePolicyManagerService.addOverrideApn(DevicePolicyManagerService.java:14120)
    at android.app.admin.IDevicePolicyManager$Stub.onTransact(IDevicePolicyManager.java:4339)
    at android.os.Binder.execTransact(Binder.java:739)
    Process 24556 terminated.

The error occurring in the following line.
devicePolicyManager.addOverrideApn(componentName,apn);

As per my knowledge, I need to use addOverrideApn() method to create this mobile application. So What should I do for that?
Answer: Your app needs to be Device Owner to use addOverrideApn(). Device Owner was first introduced in Lollipop to replace Device Admin and is intended to be used for Mobile Device Management (MDM) applications. You can activate it using adb for development / personal use but otherwise it must be activated during the setup wizard to prevent malicious admin apps from being installed via the Play store.


What's the difference between using-style and typedef-style?

Question: using IntegerType1 = int;
typedef int IntegerType2;

int main()
{
    IntegerType1 n1 = 1; // OK
    IntegerType2 n2 = 2; // OK
}

My questions are:

What's the difference between using-style and typedef-style?
As we already have typedef-style, what's the motivation to make using-style become a C++ standard?
Comment: There's multiple questions on this already.
Answer: The "using-style" was introduced to allow templated typedefs:
template< typename T >
using int_map = std::map< int, T >;

You can not do this with typedef. I found it strange myself that it was decided to use using and not typedef as the keyword for this, but I guess the committee must have found some problem with extending the typedef syntax.
Comment: With `using` the name of the newly defined type is always on the left side of expression. With `typedef` the name can be in the middle of expression. So `using` improves readability, IMHO.
Comment: @VasilyBiryukov True and I personally like the new `using`-syntax much better than the old `typedef`-syntax. It also has other benefits when you need to apply alignment with [`alignas`](http://stackoverflow.com/a/15912208/2073257).
Answer: I find that readability is greatly improved even for non-templates:
typedef void (*FunctionPtr)();  // right-to-left, identifier in the middle of the definition
using FunctionPtr = void (*)(); // left-to-right, same as variables

It's probably minor, but in template-metaprogramming this syntactic advantage makes a program easier to read, and makes template metafunctions easier to refactor towards constexpr functions. Essentially replace
using T = type_expression;
constexpr auto v = value_expression;

Furthermore (appeal to authority), it's also in the draft Effective C++11/14 guidelines.


Is it good practice to override simple db_query or EntityFieldQuery with a View

Question: I am using several autocomplete fields in a form. To retrieve the data, I have used db_query for very simple queries, EntityFieldQuery for more complex, until I found one that is somehow convoluted, so I used a View and views_get_view_result to retrieve the list of suggested terms. Is it a good practice or am I consuming too many resources instead of digging a little more in my code?
Answer: There is no simple answer possible to this question because it very much depends on circumstances. The customary response to such fears is to invoke the spectre of Premature Optimization and to advise you not to worry until you know you have a performance issue.
However, from an educational perspective it's probably worth at least looking at the query Views is executing and considering whether it is efficient: is it scanning every row of a large table because of the lack of an index, for example.
On the Views settings page there's an option to display the SQL for a query. You can copy and paste it into a tool such as PhpMyAdmin (removing the curly brackets peculiar to Drupal SQL queries) then put "EXPLAIN" in front of it to see what's happening under the hood.
But in general I would not bother to rewrite a query like this until there's a proven need to do so.
Comment: This whole answer should be in bold, flashing, red text with a "DO NOT PROCEED UNTIL YOU'VE READ AND UNDERSTOOD THIS" label at the top :)
Comment: I don't understand the reply. I am using SQL output and I have put it in my code - I can modify it to make it perform faster (if I know that all nodes are published, don't  even need to left join the node table). However, my question is if I could take confidence on the Views output. As I see it, if I hard code the db_query I am at risk of upgrades of the database layout affecting my query. If I use EntityFieldQuery I am more secure, but it is complicated. If I directly throw the output of the View, I have no worry anymore, not about obsolescence or my bad coding using EntityFieldQuery.
Comment: Your question asked about "consuming too many resources", so that's what I tried to address: how to know whether the SQL generated by a view is efficient or not. As I say, generally it's not something to worry about: go ahead and use the view until in realistic testing you find there's a performance issue.
Comment: Well, I am using the SQL query because I found problems to pass parameters to the view. So sad, so real. I hope that the SQL keeps working after upgrading modules and core.


Primefaces taking random form ID

Question: What is the way to refresh page in primefaces?
I have tried

Add Legend

View Legend

The third one would generate error in page with datatable. The error I get:
Cannot find component with expression "pnlform" referenced from "j_idt22:legendviewdatatable:0:editLink". I would like to refresh the form when I hit edit and open editpanel. And I would like to refresh only datatable when I hit delete.
The full html:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <title>Legend</title>
    </h:head>
    <h:body>
        <ui:composition template="/generalTemplate.xhtml">
            <ui:define name="title">Legend </ui:define>
            <ui:define name="content" >
                <f:view>
                    <h:form id="legendform" prependId="false" >

                            <f:facet name="header">

Add Legend

View Legend

                            </f:facet>

                                <h:panelGrid columns="2"  >
                                    <h:outputLabel value="Legend Name" for="legendname" />
                                    <h:inputText id="legendname" value="#{legendcontroller.legendType.legendname}" title="Legendname" required="true" requiredMessage="The Legendname field is required."/>
                                    <h:outputLabel value="Legend Description" for="legendDesc" />
                                    <h:inputText id="legendDesc" value="#{legendcontroller.legendType.legendDesc}" title="LegendDesc" />
                                    <h:outputLabel value="Legend For" for="legendfor" />
                                    <h:inputText id="legendfor" value="#{legendcontroller.legendType.legendfor}" title="Legendfor" required="true" requiredMessage="The Legendfor field is required."/>
                                </h:panelGrid>

                                        <f:facet name="header">
                                            <h:outputText value="Legend SN"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.legendSn}"/>

                                        <f:facet name="header">
                                            <h:outputText value="LegendDesc"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.legendDesc}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Lower Range"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.lowerrange}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Upper Range"/>
                                        </f:facet>
                                        <h:inputText value="#{legend.upperrange}"/>

                                        <f:facet name="header">
                                            <h:outputText value="Color"/>
                                        </f:facet>

                                        <f:facet name="header">
                                            <h:outputText value="ADD/Delete"/>
                                        </f:facet>

                                        <h:outputText value=" / "/>

                                    <f:facet name="footer">

                                    </f:facet>

                                    <f:facet name="header">
                                        <h:outputText value="Legendname"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendname}"/>

                                    <f:facet name="header">
                                        <h:outputText value="LegendDesc"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendDesc}"/>

                                    <f:facet name="header">
                                        <h:outputText value="Legendfor"/>
                                    </f:facet>
                                    <h:outputText value="#{legendtype.legendfor}"/>

                                    <f:facet name="header">
                                        <h:outputText value="Edit/Delete"/>
                                    </f:facet>

                                    <h:outputText value=" / "/>

                    </h:form>
                </f:view>
            </ui:define>
        </ui:composition >
    </h:body>

Finally I found that primefaces is not taking the id gave but is using random id:
<form id="j_idt12" name="j_idt12" method="post" action="/Configuration/LegendManager/LegendType.xhtml" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt12" value="j_idt12">

<button id="j_idt12:j_idt15" name="j_idt12:j_idt15" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" title="Welcome" type="submit" role="button" aria-disabled="false">Home</button><button id="j_idt12:j_idt16" name="j_idt12:j_idt16" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" title="Configuration" type="submit" role="button" aria-disabled="false">Configuration</button>

<button id="j_idt12:j_idt18_button" name="j_idt12:j_idt18_button" type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-icon-left" role="button" aria-disabled="false">sugandha</button>

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="2044288989474132123:952602282947229034" autocomplete="off">
</form>

Answer: Since you used prependId="false", you should use update="pnlform" only, or remove prependId="false" so you will be able to keep update="yourformname:yourid" or update=":yourid".
More info :

h:form
Comment: I am getting error : Cannot find component with expression "pnlform" referenced from "j_idt22:legendviewdatatable:0:editLink".
Comment: Did you replaced `` by `` ?
Comment: yes. That's why the error is saying pnlform. I am confused why is this not working?
Comment: I found that it is using random form id. Edited.
Comment: @Kitex pretty strange, are other forms in your project doing the same?
Comment: Thanks. But I found that there is already a form in template which is causing this problem. I am really thank ful for your help.
Comment: Yes nested forms can cause strange problems!
Answer: change your code as follow: <h:form id="legendform" prependId="true" > or without prependId attribute then reference to nested component inside this form with update=":legendform:pnlform" attribute from every where else.
in your case if you want to set prependId=false and then reference from nested components inside <datatable> in same form you should update withupdate=":pnlform".
this is because <datatable> has own NamingContainer

Primefaces taking random form ID


Unknown column in 'field list' while executing seeder command

Question: I have created migration file and its seeder file for the table. Now when I try to execute the seeder command it is throwing error of "Unknown column in 'field list'"
I have recreated these many times, I don't know why I am getting this! May be some minor mistake I have made.
Here is my migration file:
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('subscriptions', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      subscriptionPlanType: {
        type: Sequelize.STRING
      },
      name: {
        type: Sequelize.STRING
      },
      memberCount: {
        type: Sequelize.INTEGER
      },
      amount: {
        type: Sequelize.FLOAT
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('subscriptions');
  }
};

and here is the seeder file:
"use strict";

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    /**
     * Add seed commands here.
     *
     * Example:
     * await queryInterface.bulkInsert('People', [{
     *   name: 'John Doe',
     *   isBetaMember: false
     * }], {});
     */
    return queryInterface.bulkInsert("Users", [
      {
        subscriptionPlanType: "Monthly",
        name: "Tset1",
        memberCount: 15,
        amount: 65.99,
        createdAt: "Oct 17 2022 22:34:39",
        updatedAt: "Oct 17 2022 22:34:39",
      },
      {
        subscriptionPlanType: "Yearly",
        name: "Test2",
        memberCount: 25,
        amount: 105.99,
        createdAt: "Oct 17 2022 22:34:39",
        updatedAt: "Oct 17 2022 22:34:39",
      },
    ]);
  },

  async down(queryInterface, Sequelize) {
    /**
     * Add commands to revert seed here.
     *
     * Example:
     * await queryInterface.bulkDelete('People', null, {});
     */
  },
};

And I am getting the error while executing this command: npx sequelize-cli db:seed:all

Unknown column 'subscriptionPlanType' in 'field list'

How can I get rid of this error?
Answer: You made a mistake either in the migration or in the seeder. The table names are not the same. In the migrations, the table name is subscriptions and in the seeder it is Users
Comment: Yes, this was the problem. Thank you @Joe.
Comment: Top. Don't forget to mark the forum as solved for others. Good luck Jayna ;)


What are examples of non-Classical cadences?

Question: Perfect/imperfect authentic cadences, half cadences, deceptive cadences, and plagal cadences have been around since at least Mozart.  What are some either specific cadences or approaches to cadences that started with...

Wagner and the late Romantics
Bartok and the folk music enthusiasts
Debussy and the Impressionists

I do know that they're much more likely to use chromaticism in general than Classical composers, but I'm looking particularly for interesting non-Classical ways they handled ends of phrases when they wanted to convey at least some degree of closure.
Comment: One plagal cadence variation is known as ii-I.
Answer: It turns out that David James Heetderks's 300-page thesis "Transformed Triadic Networks: Hearing Harmonic Closure in Prokofiev, Copland, and Poulenc" has a lot to say on the subject.  He speaks in terms of operations on the standard V-I, tritone-collapsing-inward progression, including reversing privileged root motion (ascending as opposed to descending fifth), changing the privileged root motion entirely (establishing that the major third is the interval of root motion in cadences), and adding essential dissonances.
Comment: By "ascending as opposed to descending fifth" does he mean "ascending fifth as opposed to descending fifth" (thus plagal rather than perfect cadence) or "ascending fourth as opposed to descending fifth" (thus a different chord layout)?


Difference between skbuff frags and frag_list

Question: The sk_buff has two places where it can store the next fragmentation data:
skb_shinfo(head)->frag_list
skb_shinfo(head)->frags[]

What are the differences between these two ways to handle fragmentation?
Comment: *skb* = [socket buffer](http://vger.kernel.org/~davem/skb.html)
Answer: Both are used for different cases.
frags[]
When your device supports scatter-gather I/O, and you want it to do the combining of data, etc., you can populate the frags[] structure starting with the second fragment till the nth fragment. The first fragment is always specified by the data and tail pointers. The rest of the fragments are filled in the frags[] structure. If you don't use scatter gather, this variable is empty.
frag_list
This is the list of IP fragments. This will be filled during ip_push_pending_frames.
Say your sk_buffs are in this arrangement,
sk_buff0->next = sk_buff1
sk_buff1->next = sk_buff2
...
sk_buffn-1->next = sk_buffn

After ip_push_pending_frames is called
sk_buff0->frag_list = sk_buff1
sk_buff1->next = sk_buff2
...
sk_buffn-1->next = sk_buffn

Simply put

frags[] are for scatter-gather I/O buffers
frag_list is for IP fragments
Comment: Thank a lot @bjxt! your explanation is very clear. Now I know how different they are
Answer: skb_shinfo(head)->frags[]
If the NIC supports SG I/O, __ip_append_data will copy user space data to skb_shinfo(head)->frags. The NIC driver (e.g., ixgbe_add_rx_frag) can also use these frags[] to carry the received network traffic; please note that every content in frags[] is a part of a complete packet. A complete packet consists of all frags[] + (skb->data ~ skb->tail).
skb_shinfo(head)->frag_list
This member is not used by IP fragmentation directly.
In __ip_make_skb(), the frag_list is used to collect all skbs from sk->sk_write_queue; some NIC drivers also use this frag_list for carrying a packet to the upper network stack. Every content/skb in frag_list is also not a complete packet; tcp_v4_send_ack -> ip_send_unicast_reply -> ip_push_pending_frames -> ip_finish_skb -> __ip_make_skb;


Heapsort recursivo em C

Question: Eu tenho um heapsort, e gostaria de implementar ele recursivo. O que eu preciso mudar no meu algoritmo?
void criarHeap(int v[], int inicio, int final){
    int aux = v[inicio];//v[pai]//inicio=pai
    int filho = (inicio * 2)+1;//i=filho
while(filho<=final){
    if(filho<final && (filho+1)<final){
        if(v[filho]<v[filho+1]){//pai tem 2 filhos ? se sim, qual o maior
            filho++;
        }
    }
    if(aux<v[filho]){//troca o filho com o pai se o filho for maior
        v[inicio]=v[filho];
        inicio=filho;
        filho=(2*inicio)+1;
    }
    else{
        filho=final+1;
    }
}
    v[inicio] = aux;//pai troca com filho mais profundo mais a direita
}

void heapSort(int v[], int tam){
    int i;
    int aux;
    for(i=(tam-1)/2;i>=0;i--){// cria heap
        criarHeap(v,i,tam-1);
    }
    for(i=tam-1;i>=1;i--){//pega o maior elemento e coloca na posicao o array
        aux = v[0];
        v[0]=v[i];
        v[i]=aux;
        criarHeap(v,0,i-1);//cria o heap sem o maior elemento anterior
    }
}

Answer: Primeiro, criei um teste para o seu algoritmo:
int main(void) {
    int teste[] = {8, 4, 2, 9, 5, 0, 10, 7, 1, 3, 6};
    heapSort(teste, 11);
    for (int i = 0; i <= 10; i++) {
        printf("%i ", teste[i]);
    }
    return 0;
}

A saída foi a esperada: 0 1 2 3 4 5 6 7 8 9 10. Veja aqui funcionando no ideone.
Então, agora podemos mexer no seu código. O primeiro passo é transformar o while da função criarHeap em uma recursão.
Vemos que esse while altera a variável filho que será utilizada após o término desse laço. Assim, a função recursiva que irá substituir esse while poderá retornar o valor dessa variável. As variáveis que são utilizadas nesse while e que são recebidas externamente são v, inicio, aux, filho e final, logo essas tornam-se os parâmetros para a função recursiva.
O código fica assim:
int criarHeapRecursao(int v[], int inicio, int aux, int filho, int final) {
    if (filho > final) return inicio;

    // Pai tem 2 filhos? Se sim, qual é o maior?
    if (filho < final && filho + 1 < final && v[filho] < v[filho + 1]) {
        filho++;
    }

    // Troca o filho com o pai se o filho for maior.
    if (aux < v[filho]) {
        v[inicio] = v[filho];
        inicio = filho;
        filho = 2 * inicio + 1;
    } else {
        filho = final + 1;
    }
    return criarHeapRecursao(v, inicio, aux, filho, final);
}

void criarHeap(int v[], int inicio, int final) {
    int aux = v[inicio];
    int filho = inicio * 2 + 1;
    inicio = criarHeapRecursao(v, inicio, aux, filho, final);
    v[inicio] = aux; // Pai troca com filho mais profundo mais a direita.
}

Observe que a recursão está no final da função criarHeapRecursao e aquilo que era a condição de parada do while tornou-se um if no início da função.
Feito isso, agora temos a função heapSort que tem dois laços. Cada laço vai virar uma função recursiva a parte. A condição de parada é colocada como um if no início da função e o contador torna-se um dos parâmetros de cada uma dessas funções recursivas. As demais variáveis utilizadas nos laços (v e tam) também tornam-se parâmetros. A chamada recursiva é colocada ao final de cada fução. O resultado é isso:
void heapSort1(int v[], int i, int tam) {
    if (i < 0) return;
    criarHeap(v, i, tam - 1);
    heapSort1(v, i - 1, tam);
}

void heapSort2(int v[], int i, int tam) {
    if (i <= 0) return;
    int aux = v[0];
    v[0] = v[i];
    v[i] = aux;
    criarHeap(v, 0, i - 1); // Cria o heap sem o maior elemento anterior.
    heapSort2(v, i - 1, tam);
}

void heapSort(int v[], int tam) {
    heapSort1(v, (tam - 1) / 2, tam);
    heapSort2(v, tam - 1, tam);
}

Desta forma, os laços da função heapSort foram convertidos nas funções recursivas heapSort1 e heapSort2.
A variável aux tinha um escopo onde era utilizada apenas dentro do segundo laço, mas o seu valor não era utilizado entre uma iteração e outra, não fazia sentido antes da primeira iteração e nem era usada após a última iteração. Por esse motivo, ela tornou-se uma variável local de heapSort2.
A saída permanece a esperada, 0 1 2 3 4 5 6 7 8 9 10. Veja aqui funcionando no ideone.

Heapsort recursivo em C


Tratar lista de CNPJ's com expressão regular

Question: OTenho uma lista de CNPJ's, gostaria de pegar essa lista e acrescentar aspas simples e separar cada um deles com vírgula, fazendo isso com expressão regular.
Ex.:
Minha lista:

32132132132 32132132132 321321321323 32132132132132

Como desejo que fique:

'32132132132','32132132132','321321321323','32132132132132'
Comment: Faltou a linguagem, os Regexs (Expressões Regulares) funcionam de maneira diferente dependendo da Linguagem
Comment: Possível duplicata de [Expressão regular para validar um campo que aceita CPF ou CNPJ](https://pt.stackoverflow.com/questions/11045/express%c3%a3o-regular-para-validar-um-campo-que-aceita-cpf-ou-cnpj)
Comment: Eu faria algo do tipo: [demo](https://regex101.com/r/8UXZhq/1), que funcionaria em alguns dos editores de texto mais simples... A sua pergunta seria mais para substituir numa lista que possui o espaço como separador, para vírgula como separador e colocar apóstrofe delimitando cada elemento. E não tratar CNPJ...
Answer: Sinceramente não vejo motivo para utilizar Expressões Regulares em algo simples.
Em PHP utilize explode e join
$str = '32132132132 32132132132 321321321323 32132132132132';
$exp = explode(' ', $str);
echo "'" . join("';'", $exp) . "'";

Veja funcionando em repl.it

Em Python utilize split e join
str = '32132132132 32132132132 321321321323 32132132132132';
exp = str.split();
print("'" + "';'".join(exp) + "'")

Veja funcionando em repl.it

Em Java utilize split e join
String link = "32132132132 32132132132 321321321323 32132132132132";
String[] partes = link.split(" ");
System.out.println("'" + String.join("';'", partes) + "'");

Veja funcionando em repl.it

Em JavaScript utilize split e join

let str = '32132132132 32132132132 321321321323 32132132132132';
let res = "'" + str.split(' ').join("';'") + "'";
console.log(res)


How to use drush with proxy

Question: I am using Acquia Dev Desktop 2 for my Drupal 8 project, I tried to download module with Drush. But I can only access the internet via a proxy. How can I configure drush to use the correct http proxy settings for downloading?
Answer: Drush by default is using wget to download project (if available), otherwise curl. This can be change by --package-handler. You can check which package handler is in place by running your command with debug parameter (-d).
So you configure proxy the same way as you would configure this for wget or curl.
For wget, you can configure these lines in ~/.wgetrc:
use_proxy = on
https_proxy = http://proxy-host:8080
http_proxy = http://proxy-host:8080

Note: Please check /usr/local/etc/wgetrc for some examples.
For curl this line should in your ~/.curlrc:
proxy=http://username:password@proxy-host:port

For both I think you can try to export http_proxy/https_proxy as a system variable.
Comment: For the record : drush 8 provide the " --update-backend" option that could be set to drush (default) which used wget to fetch update (hence use kenorb answer) or drupal which use the core update module (you have to enable it and set the $settings['http_client_config']['proxy']* options in settings.php.
Comment: Please where would I find these setting (Wget and Curl)
Comment: @GoodTaofiq You've to create a new files in your HOME user directory. Check `/usr/local/etc/wgetrc` for example, read `man wget` or Google for some sample files.
Comment: Unfortunately this doesn't answer the question of how to get drush to work on Acquia Dev Desktop under Windows, cf [my question here](http://drupal.stackexchange.com/questions/207549/how-to-configure-drush-with-acquia-devdesktop-on-windows-to-access-through-proxy?rq=1)

How to use drush with proxy


Confidence interval for RMSE

Question: I want to estimate 95% C.I. for RMSE(Root mean square error).
However, i have a difficulty in estimating C.I. due to RMSE equation
(there is a root in RMSE equation)
Answer: You can use the same approach that is common to get confidence intervals for standard deviation: we get confidence intervals for variance and then just take the square root of the extremes of the interval.
Here you can compute a CI for mean square error and take the square root of the values you get. Since square root is a monotonic growing function, probabilities inside and outside of the interval remain the same.

Confidence interval for RMSE


If there is a bijection between $A$ and $\operatorname{Fin}(A)$, is there a bijection between $A$ and $A\times A$?

Question: If there is a bijection between $A$ and $\operatorname{Fin}(A)$ then there is a bijection between $A\times A$ and $A$?
Comment: What are your thoughts on the question?  What have you tried so far?
Comment: i prove there is injective between N to Fin(N) and there also injective between Fin(N) to N and by Schroder- Bernstein theorem there is a bijection between N and Fin(N), but the second one i cannot do anything so i said i might be wrong or there is any way in 1 that can help me with 2
Comment: (1) Have been asked ***many*** times before. And it seems that you got it under wraps. So you might as well remove it from the question. I've answered (2), but you should perhaps elaborate on your question, what you know and don't know. And while you're at it, perhaps a better title is in order.
Comment: thanks Asaf, you help me to find the right answer.
Answer: The answer for (2) is indeed positive.
Recall that we can encode an ordered pair $(a,b)$ as the set $\{\{a\},\{a,b\}\}$. Therefore $A\times A$ is a subset of $\operatorname{Fin}(\operatorname{Fin}(A))$.
If $A$ and $\operatorname{Fin}(A)$ have the same cardinality, show that we actually get that $A$ and $\operatorname{Fin}(\operatorname{Fin}(A))$ also have a bijection between them, and conclude from the Cantor-Bernstein theorem the wanted result.
(Note that assuming the axiom of choice this is easier, since for a finite set, $A$, $\mathcal P(A)=\operatorname{Fin}(A)$ and therefore there is no bijection between them, and for every infinite set, $A\times A$ and $A$ have a bijection between them. But the crux of the question, I suppose, is without the axiom of choice.)


Can a different service solve my elastic search use cases for cheaper?

Question: I use elastic search to:

Search for items by name
Search for items that are hats
Search for items that aren't hats
Combos of the above

My data looks like this:
<code>{
        "id": string,
        "name": string,
        "owner_user_id": number,
        "moderation_status": string,
        "component_keys": ["Hat", "Clothing", "Render"] # There are hundreds of unique values here
}
</code>
My cluster has 104 shards and only uses 93 MB of memory.
I'm a hobby developer, and Elastic is my highest operating expense right now.
Comment: U can run a single node Elasticsearch cluster with just 1 GB of heap size as well, you need to provide more information on you Elasticsearch cluster and why you are using 104 shards ?
Answer: Elasticsearch cost depends on the multiple factors, like memory, disk, instance type and number of nodes in the cluster. And Elasticsearch cluster can have minimum 1 to no upper limit specified by Elasticsearch.
In your case I can see you have very less memory footprint so you can simply create a single node Elasticsearch cluster(if you are not using it for production use-case), and just assign the heap memory to 1 GB, this should solve your cost issue.
Apart from that curious to know why you have 104 shards, better to delete the unused shard to claim even more memory.
Hope this helps.
Comment: I'm not sure how to delete shards, as its controlled my Elastic Search. "Solving" the cost issue puts it at 100 dollars a month. Hard to stomach when my dynamo db usages for more data costs <20 bucks a month.
Comment: @OliverBarnum 100 $ per month is huge, what about the other details, like number of nodes in Elasticsearch cluster and instance type as mentioned you can simply run in to t4g.small instance which would cost less than 10$ per month according to EC2 calculator https://calculator.aws/#/createCalculator/EC2
Comment: Im running this off of elastic searches website cloud.elastic.co, not hosting it myself. Would you suggest that for tiny amounts of data?
Comment: @OliverBarnum why not when you are paying too much for such a small usage and its not that overhead to manage a small cluster
Comment: @OliverBarnum its been really long, please accept my answer if it helped you :)


Relationships across multiple Realms?

Question: Realm:
We have the following scenario: There are several stores with employees and customers, several employees that could work at more than one store, and several customers that may shop at several stores. This could be represented with these classes
class Store {
    dynamic var id = ""
    dynamic var address = ""
    let workers = List<Employee>()
    let customers = List<Customer>()
}

class Customer {
    dynamic var id = ""
    dynamic var name = ""
    let stores = LinkingObjects(fromType: Store.self, property: "customers")
    // ... many more fields about this customer
}

class Employee {
    var id
    var name
    let work = LinkingObjects(fromType: Store.self, property: "workers")
}

The catch here is that we must protect customer information, so none of the customer info can be present in a shared realm and needs to be secure. Neither the store nor Employee data is a security matter. Our current approach is to give each customer their own realm, however, the major drawbacks to this is that requires massive duplication since each customer realm must copy the data of the store. The other drawback is that we would be copying customer data into a shared realm which is a security risk. What would be the best way to architect this scenario that allows for relationships across different Realms?
Answer: Realm doesn't currently support "direct" object links across Realms analogous to object properties within the same Realm.
Instead, what I suggest you do is to give your objects primary keys (you can probably just declare your existing id fields as such, or create a new internalId field if your existing id field can't be used for this purpose).
Primary keys are mandatory, must be unique, and can't be changed after they are set, which makes them great for uniquely identifying objects. Our documentation discusses them in greater detail.
Then, instead of directly storing customer info/a customer object in a shared Realm, you can just store the primary keys for the relevant customers, for example in a list. (Right now you'll have to make a wrapper CustomerKey object for example to store the customer's primary key, but we plan to support collections directly containing strings or other primitive types very soon.)
You can enhance this further by adding helper methods on your objects that can be passed in a customer Realm and return the user object (or whatever object's primary key is being stored), looking it up in the Realm automatically. You can use Realm's object(ofType:forPrimaryKey) method to look up an object based on its primary key.
The main limitation is that you won't get the automatic updating of links you would get with object, list, and LinkingObjects properties. You'll have to manually perform the bookkeeping yourself.
If you have ideas for functionality you want to see in Realm that would go beyond what I've posted here, feel free to share your thoughts at our GitHub issue tracker. We welcome feature requests.
Comment: Great response. However, if we logged in as a customer and wanted to see a list of customers for a store I go to, that may require opening 100 different realms then making a query for the corresponding user object and I feel like that'd be incredibly inefficient (unless you know that to be otherwise?). Additionally, would this even be possible on mobile as it does not have the Realm.Sync.adminUser method like what's possible in the realm-js lib?

Relationships across multiple Realms?


como alterar o formato da data para d/m/a no php wamp serve

Question: criei um sistema de cadastro e consultas de dados para o cartório em que trabalho, porém, as datas estão sendo exibidas no formato a/m/d e quero alterar para o formato nacional, mas não sei como fazer. alguém pode me ajudar?
Comment: Mostre o código onde tenta exibir as datas. Provavelmente é só uma questão de formatar corretamente logo antes de exibir.
Answer: Com PHP:
$sua_data_atual='2018-05-19';
echo date('d/m/Y' strtotime($sua_data_atual));

Retona 19/05/2018.

Referência da função date()
Referência da função strtotime()


URL validation in java

Question: Hey I'm trying a url validation based upon What is the best regular expression to check if a string is a valid URL? in java but for some reason it's not working. Suggestions?
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class urlValidate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        test_url("http://brb/", false);
            test_url("https://localserver/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", false);
    test_url("https://www.google.com/", true);
    test_url("https://www.google.co.uk/projects/my%20folder/test.php", false);
    test_url("https://myserver.localdomain/", true);
    test_url("https://192.168.1.120/projects/index.php/", false);
    test_url("https://192.168.1.1/", true);
    test_url("https://projectpier-server.localdomain/projects/public/assets/javascript/widgets/UserBoxMenu/widget.css", false);
    test_url("https://22.214.171.124/project-pier?c=test&a=b", false);
    test_url("https://localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", false);
    test_url("https://user:password@localhost/a/b/c/test.php?c=controller&arg1=20&arg2=20", false);
    test_url("myserver",false);
    test_url("https://tomcat:8080/",true);
    test_url("https://facebook.com",false);
}

public static void test_url(String url, boolean expected) {
    boolean valid = isURLValid(url, true);
    String out = "URL Valid?: " + (valid ? "yes" : "no") + " for URL: "
            + url + ". Expected: " + (expected ? "yes" : "no") + ". ";
    if (valid == expected) {
        out += "PASS\n";
    } else {
        out += "FAIL\n";
    }
    System.out.println(out);
}

public static boolean isURLValid(String url, boolean forcehttps) {
    String regex = "";
    if (forcehttps) {
        regex = "/^(https):\\/\\/";
    } else {
        regex = "/^(https?):\\/\\/";
    }
    regex += "((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*"
            + "[a-z][a-z0-9-]*[a-z0-9]"
            + "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}"
            + "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])"
            + ")(:\\d+)?)"
            + "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?(\\/)"
            + "$/i";

    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(url); // get a matcher object
    return m.matches();
}

}

Comment: @SotiriosDelimanolis -Actually, it doesn't. It only cares if a protocol exists.
Comment: Personally, I wouldn't do complex URL validation for the same reason I wouldn't do complex email address validation. Take a look at http://davidcel.is/blog/2012/09/06/stop-validating-email-addresses-with-regex/.
Comment: @BrianRoach Good stuff, thanks.
Answer: The regex is initially wrapped in slashes (to serve as delimiters, which are required for PCRE in PHP).  Java does not use these.
if (forcehttps) {
    regex = "^(https):\\/\\";
} else {
    regex = "^(https?):\\/\\";
}

The /i at the end is also undesirable.  Instead, write
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE)

Answer: You can use the Apache commons-validator api. There is a class named UrlValidator, or something like that.
Take a look at this: http://commons.apache.org/validator/
I dont't understand a lot of regex, so I can't help you much in this subject.
Good Luck.
Comment: While that does accomplish the task at hand, unless you need something else from apache commons that's a pretty large dependency to attach to your project just to validate an URL.
Answer: Although it is not a problem to write regex to URL validation why not just to use java.io.URL class? Just create instance of URL like following: new URL(spec) and it will throw MalformedURLExcption if syntax is wrong.
Comment: according to the javadoc it will only throw that if the protocol is missing or the `spec` is `null`

URL validation in java


Integral of a Gaussian process

Question: Let $(\Omega,\Sigma,P)$ be a probability space and $X: [0,\infty) \times \Omega \to \mathbb{R}$ be a Gaussian process (i.e. all finite linear combinations $\sum_i a_i X_{t_i}$ are Gaussian random variables). If the
process is continuous, it seems to be clear that the process $Y_t (\omega) = \int_0^t X_s(\omega) ds$ is a Gaussian process.
Is it true that $Y_t$ is a Gaussian process even if $X$ is only assumed to be measurable? I am working through the derivation of Kalman Filter in the text by Bernt Oksendal Eq 6.2.10 (fifth edition) and this seems to be a way to show that $M_t$ (in the book) is a Gaussian process.
Comment: Yes, the measurability in the sense of $([0,\infty)\times \Omega, \mathcal{B}([0,\infty))\otimes \mathcal F) \to (\mathbb{R},\mathcal{B}(\mathbb{R}))$ is enough.
Comment: @zhoraster Why do you think so? For example, if $Z \sim N(0,1)$, then $X_t := \frac{1}{t} Z$, $t>0$, $X_0 := 0$, is Gaussian, but the integral $\int_0^t X_s \, ds$ is not well-defined. As far as I can see, we need some additional assumption on the integrability, e.g. $\sup_{t \leq T} \mathbb{E}(|X_t|)<\infty$ for $T>0$.
Comment: @saz, I assume that everything is well-defined. Of course, to this end we need some integrability.
Comment: @zhoraster I see.
Comment: @saz Could you name a source to prove the sufficiency of $sup_{t\leq T}\mathbb{E}(|X_t|)<\infty$ ?
Answer: Question 1: Is $Y_t(\omega)$ well-defined?
Answer: No, in general, $Y_t(\omega)$ is not well-defined; we need some additional assumption on the integrability of $X$ to ensure that $$\int_0^t |X_s(\omega)| \, ds <\infty$$ for $t>0$. This is e.g. satisfied if $X$ has continuous sample paths or $\sup_{t \leq T} \mathbb{E}(|X_t|)<\infty$ for any $T>0$. (To see that it $Y_t$ is in general not well-defined, just consider $X_t := t^{-1} Z$, $t>0$, for $Z \sim N(0,1)$; then $X$ is Gaussian, but the integral $\int_0^t X_t \, ds$ does not exist.)
Question 2: Is $\omega \mapsto Y_t(\omega)$ a random variable for fixed $t \geq 0$?
Answer: If the process $X: (0,\infty) \times \Omega \to \mathbb{R}$ is jointly measurable, then $Y_t$ is a random variable for each $t \geq 0$. Otherwise, measurability of $Y_t$ might fail.
Question 3: Is $(Y_t)_{t \geq 0}$ Gaussian?
Answer: If $t \mapsto X_t(\omega)$ is Riemann integrable, this follows by approximation the integral by Riemann sums; see e.g. this question. (Note that a bounded function $f:[0,T] \to \mathbb{R}$ is Riemann integrable if, and only if, the points in $[0,T]$ where $f$ is discontinuous is a Lebesgue null set.)
Edit: Okay, so somewhat more detailed: For any (Riemann) integrable function $f:[0,t] \to \mathbb{R}$ it is known that the (Riemann) integral
$$\int_0^t f(s) \, ds$$
can be approximated by Riemann sums
$$\sum_{j=0}^{n-1} f(s_j) (t_{j+1}-t_j)$$
where $0=t_0 < \ldots <t_n = t$ is a partition of the interval $[0,t]$ and $s_j \in [t_j,t_{j+1}]$. In particular, if we choose $s_j = t_j := t \frac{j}{n}$, we find
$$\int_0^t f(s) \, ds = \lim_{n \to \infty} \frac{t}{n} \sum_{j=0}^{n-1} f \left( t \frac{j}{n} \right).$$
Applying this in order (stochastic) setting, we get
$$\int_0^t X_s \, ds = \lim_{n \to \infty} \frac{t}{n} \sum_{j=0}^{n-1} X_{t j/n};$$
and $\frac{t}{n} \sum_{j=0}^{n-1} X_{t j/n}$ is Gaussian because $X$ is Gaussian.
Comment: @jpv Yes, but the continuity is not used to prove that it is Gaussian. The point is simply that the Riemann sums are Gaussian (since they are finite linear combinations) and so is their limit.
Comment: @jpv No, the sums convergence whenever the integrand is integrable; this follows directly from the definition of the Riemann integral (or Lebesgue integral, if you prefer it; it doesn't matter).
Comment: @jpv Just write down how the Lebesgue integral of a step function of the form $$f(s) = 1_{[a,b]}(s),$$ or more generally, $$ f(s) = \sum_{j=1}^n c_j 1_{[a_j,b_j]}(s)$$ looks like - then you will see that this gives Riemann sums. So, by approximating the integrand by step functions, we get Riemann sums. Moreover, note that the Riemann integral and the Lebesgue integral coincide in this particular case. (Finaly, mind that $\int_0^t f(s) \, ds$ is even differentiable (in $t$), if $f$ is continuous, but we do no not need this property here).
Comment: @jpv See my edited answer. (And please note that the integral $\int_0^t f(s) \, ds$ exists if and only if $\int_0^t |f(s)| \, ds < \infty$.)
Comment: @jpv Ah, sorry, I did a stupid mistake there. You are right, we have to *assume* that $t \mapsto X_t(\omega)$ is Riemann integrable; otherwise we are lost (at least using the argumentation I sketched above).
Comment: @DanielCamarenaPerez Right, there were some $t$'s missing; thank you.
Comment: saz: Your answer to the linked question uses continuity of Brownian paths to prove this. I am not sure if I am missing something.
Comment: saz: When the process is not continuous, the Riemann sums might not converge to the integral. Isn't that so?
Comment: saz: I am assuming that $Y_t(\omega) = \int_0^t X_s(\omega) ds$ exists for all $\omega,t$ in the Lebesgue sense. I think that the Lebesgue integral cannot be approximated by Riemann sums. The way to approximate the Lebesgue integral is by using $Y_t^+,Y_t^-$ and using the fact that these non-negative random variables can be approximated by step functions. However, I cannot see how this entire process of approximation will preserve Gaussianity.
Comment: I still have some troubles with the proof. For simplicity assume $f \geq 0$, then the simple functions which approximate $f$ are $f_n (t):= \sum_{k=0}^{n2^n-1}(k/2^n)\chi_{[k/2^n \leq f(t) <(k+1)/2^n)}$. Then, $\int_0^T f_n(s)ds = \sum_{k=0}^{n2^n-1}(k/2^n)\lambda[k/2^n \leq f <(k+1)/2^n)$ and it is not directly related to the Riemann sums.
Comment: Thanks. I completely understand the part where the sums are Gaussian and hence their a.s. limit is Gaussian. I am unable to get my head around this: "If $f : [0,T] \to \mathbb{R}$ is Lebesgue measurable and $\int_0^T|f(s)|ds < \infty$, then $f$ is Reimann integrable and both the integrals coincide". If this is false, then we atleast need to show that the Lebesgue integral can be approximated by Riemann sums. Lebesgue integral is defined using partitioning the range of the function so I am unable to see a direct connection. It may be that I am missing some very important knowledge.
Comment: I will go with this extra assumption for now. Thanks for your effort and time.
Comment: I assume the correct integral is $\int_0^t f(s) \, ds = \lim_{n \to \infty} \frac{t}{n} \sum_{j=0}^{n-1} f \left( t \frac{j}{n} \right)$.

Integral of a Gaussian process


Aumentar/Diminuir progresso do SeekBar com ação de um Button?

Question: Alguém pode ajudar: Como aumentar e diminuir o progresso do seekBarHomem através da ação do  Button?

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

    tv_QtdHomem = (TextView) findViewById(R.id.tv_QtdHomem);

    bt_MenosHomem = (Button) findViewById(R.id.bt_MenosHomem);
    bt_MaisHomem = (Button) findViewById(R.id.bt_MaisHomem);

    seekBarHomem = (SeekBar) findViewById(R.id.seekBarHomem);

    seekBarHomem.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public  void onProgressChanged(SeekBar seekBar, int i, boolean b) {

                 tv_QtdHomem.setText(""+i);

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    bt_MaisHomem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

   bt_MenosHomem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
}

}
Comment: Quais os métodos de `SeekBar`? Pode ser a documentação da classe. Deve ter algum método como `seekBar.setProgress(int)`
Answer: Basta utilizar os métodos setProgress e getProgress do SeekBar:
bt_MaisHomem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        seekBarHomem.setProgress(seekBarHomem.getProgress() + 1)
    }
});


Uso do while dentro do if

Question: Tenho que ler infinitas médias de alunos e se elas forem maiores ou iguais a 7  o aluno está aprovado , caso não , ele esta reprovado , e caso eu digite -1 o programa para e emite uma mensagem de finalização.
Estou tentando dificuldade em fazer esse programa e também queria adicionar algo que diga quando o usuário digite algo que não esteja entre 0 e 10 (que são as possíveis notas do alunos) , só que não estou conseguindo.
    printf("Digite a media final do aluno");
    scanf("%d",&media);

    if(media>=0 && media<=10)

    while(media!=-1)
    {
    if(media>=7)
    printf(" APROVADO! \n");
    printf("Media do proximo aluno: \n");
    scanf("%d",&media);
    else {
    printf(" REPROVADO! \n");
    printf("Media do proximo aluno: \n");
    scanf("%d",&media);}

    }
    printf("Fim do programa! \n"); // quando eu digito -1

    else
    printf("Voce digitou numero invalido ");

    system("PAUSE");
    return 0;

Comment: esta faltando um %d no primeiro scanf esta apenas o d
Comment: ah sim , nem percebi mas acho que não era só esse erro rsrs
Comment: De fato tinham mais algumas coisinhas, mas foi o que enxerguei logo de cara haha
Answer: Imagino que seja isto que quer:
#include <stdio.h>

int main(void) {
    int media = 0;
    while (media != -1)  {
        printf("Digite a media do final aluno: \n");
        scanf("%d", &media);
        if (media < -1 || media > 10) {
            printf("Voce digitou numero invalido ");
            continue;
        }
        printf(media >= 7 ? "APROVADO!\n" : "REPROVADO!\n");
    }
    printf("Fim do programa! \n"); // quando eu digito -1
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Olha como ficou mais simples. Um dos motivos de ter dificuldade é porque ainda não se acostumou a caprichar na escrita. Quando você tenta fazer tudo no lugar certo, dar os espaços que precisa, não dar onde não precisa, colocar as chaves corretas, tudo direitinho fica até mais fácil visualizar. Eu nem tentei achar o erro de tão confuso que estava.
O código tinhas repetições e partes desnecessárias. A lógica é simples:

Entra no laço em um condição que você sabe ser verdadeira
Pede a nota
Verifica se ela está fora dos parâmetros estabelecidos, se está fora dá uma mensagem de erro e manda reexecutar o laço sem fazer o resto com o comando continue
Se manter o fluxo manda imprimir aprovado ou reprovado de acordo com a nota
Volta ao laço
Sai do laço quando digitar -1
Comment: @FábioMorais só não abuse, tem hora pra usar
Comment: Agora entendi , eu cresci  muito o programa. Obrigado!
Comment: Só outra duvida , estaria ''errado'' essa forma aqui ? :
Comment: https://imgur.com/a/6uxEaRW (melhor para ver)
Comment: Errado não é, mas tem código duplicado e é diferente do que você postou originalmente. Eu fiz baseado no que você postou.
Comment: @Maniero Usar o `? :` realmente deixa o codigo muito bonito, tenho de começar a usar!
Comment: @Maniero Vou lendo um pouco sobre isso, porque é instinto meu usar logo `if` `else`, obrigado
Answer: Primeiro, para que leia infinitas notas, você tem que ler o valor de média dentro do while.
Segundo, teste o valor se for maior que 10 e dê uma mensagem.
Aproveite e pense como validar menores que zero mas não -1 :)
media = 0;
while(media!=-1)
{
    printf("Digite a media final do aluno");
    scanf("d",&media);

    // testar a media
    if (media > 10)
    {
       printf("digite uma média entre 0 e 10");
       continue;  // volta para o começo
    }
    ... restante do código ...

}

Comment: Não deveria de testar a hipótese de ser menor que 0 tambem? Neste caso menor que -1
Comment: sim, por isso deixei na resposta *"Aproveite e pense como validar menores que zero mas não -1"*, se resolver tudo não tem graça ;)
Comment: Ah ok, estava a ler os codigos apenas
Answer: Para esse algoritmo ter laços infinitos até que que uma condição não seja atendida (Ex: while(media != -1)) você precisar introduzir uma estrutura de repetição.
Veja:
#include <stdio.h>
#include <stdlib.h>

int main(void){

float media = 0;

while(media != -1)){

    system("cls");
    printf("Digite a media do aluno:");
    scanf("%f",&media);

    if(media < -1 || media > 10){
        printf("Valor invalido!\n");
        system("PAUSE");
    }
    else if(media >= 7 && media <= 10){
        printf("Aluno aprovado!\n");
        system("PAUSE");
    }
    else if(media >= 0 && media < 7){
        printf("Aluno reprovado!\n");
        system("PAUSE");
    }

 }

 return 0;
}

Existem outras formas de parar um laço de repetição, como exemplo a função feof(), no seu caso não seria necessário, mas não deixa de ser uma boa opção em situações onde não é possivel ou recomendado usar valores inteiros para sair de um laço.

Uso do while dentro do if


Why is a projection matrix symmetric?

Question: I am looking for an intuitive reason for a projection matrix of an orthogonal projection to be symmetric. The algebraic proof is straightforward yet somewhat unsatisfactory.
Take for example another property: $P=P^2$. It's clear that applying the projection one more time shouldn't change anything and hence the equality.
So what's the reason behind $P^T=P$?
Comment: In general, a projection matrix has $P^2=P$. However, only orthogonal projection matrices are symmetric.
Answer: In general, if $P = P^2$, then $P$ is the projection onto $\operatorname{im}(P)$ along $\operatorname{ker}(P)$, so that $$\mathbb{R}^n = \operatorname{im}(P) \oplus \operatorname{ker}(P),$$ but $\operatorname{im}(P)$ and $\operatorname{ker}(P)$ need not be orthogonal subspaces. Given that $P = P^2$, you can check that $\operatorname{im}(P) \perp \operatorname{ker}(P)$ if and only if $P = P^T$, justifying the terminology "orthogonal projection."
Answer: There are some nice and succinct answers already. If you'd like even more intuition with as little math and higher level linear algebra concepts as possible, consider two arbitrary vectors $v$ and $w$.
Simplest Answer
Take the dot product of one vector with the projection of the other vector.
$$
(P v) \cdot w
$$
$$
v \cdot (P w)
$$
In both dot products above, one of the terms ($P v$ or $P w$) lies entirely in the subspace you project onto. Therefore, both dot products ignore every vector component that is not in this subspace - they consider only components in the subspace. This means both dot products are equal to each other, and are in fact equal to:
$$
(P v) \cdot (P w)
$$
Since $(P v) \cdot w = v \cdot (P w)$, it doesn't matter whether we apply the projection matrix to the first or second argument of the dot product operation. Some simple identities then imply $P = P^T$, so $P$ is symmetric (See step 2 below if you aren't familiar with this property).
Less intuitive Answer
If the above explanation isn't intuitive, we can use a little more math.
Step 1.
First, prove that the two dot products above are equal.
Decompose $v$ and $w$:
$$
v = v_p + v_n
$$
$$
w = w_p + w_n
$$
In this notation the $p$ subscript indicates the component of the vector in the subspace of $P$, and the $n$ subscript indicates the component of the vector outside (normal to) the subspace of $P$.
The projection of a vector lies in a subspace. The dot product of anything in this subspace with anything orthogonal to this subspace is zero. We use this fact on the dot product of one vector with the projection of the other vector:
$$
(P v) \cdot w \hspace{1cm}  v \cdot (P w)
$$
$$
v_p \cdot w \hspace{1cm}  v \cdot w_p
$$
$$
v_p \cdot (w_p + w_n) \hspace{1cm}  (v_p + v_n) \cdot w_p
$$
$$
v_p \cdot w_p + v_p \cdot w_n \hspace{1cm}  v_p \cdot w_p + v_n \cdot w_p
$$
$$
v_p \cdot w_p  \hspace{1cm}  v_p  \cdot  w_p
$$
Therefore
$$
(Pv) \cdot w = v \cdot (Pw)
$$
Step 2.
Next, we can show that a consequence of this equality is that the projection matrix P must be symmetric. Here we begin by expressing the dot product in terms of transposes and matrix multiplication (using the identity $x \cdot y = x^T y$ ):
$$
(P v) \cdot w = v \cdot  (P w)
$$
$$
(P v)^T w = v^T (P w)
$$
$$
v^T P^T w = v^T P w
$$
Since v and w can be any vectors,  the above equality implies:
$$
P^T = P
$$
Comment: Great answer. This also provides a intuition for a way to see adjoint in terms of projections instead of arbitrary linear operations
Answer: You can also directly verify this by definition of self-adjointness:
Let $U$ be a subspace of $V$, let $P$ be the orthogonal projection that projects onto $U$; let $x, y \in V$, and we can decompose them as $x=u_x+v_x, y=u_y+v_y$, with $u_x, u_y \in U, v_x, v_y \in U^\perp$, so $\langle u_x, v_y \rangle = \langle v_x, u_y \rangle = 0 $. By definition of $P$, $P x = u_x, P y = u_y$.
Then
$$ \langle Px, y \rangle  = \langle u_x,u_y+v_y \rangle =  \langle u_x,u_y
 \rangle = \langle u_x + v_x, u_y \rangle = \langle x, Py \rangle $$
it follows $P$ is self-adjoint and its matrix is Hermitian (i.e. symmetric when $V$ is real).
UPDATE: I just read your question again; here's a more intuitive explanation.
Remember:

$\forall A \in \mathbb{R}^{n\times n} $, $\operatorname{null}(A)$ and $\operatorname{row}(A)$ are always orthogonal complements of each other in $\mathbb{R}^n$
when $A$ describes a projection, $A^2=A$, $\mathbb{R}^n = \operatorname{null}(A)  \oplus \operatorname{col}(A)$

Now when $A$ describes an orthogonal projection, we also have $\operatorname{null}(A) \perp \operatorname{col}(A)$, so $\operatorname{null}(A)$ and $\operatorname{col}(A)$ are orthogonal complements of each other in $\mathbb{R}^n$; this happens iff $A$ is symmetric, so that $\operatorname{row}(A) = \operatorname{col}(A)$.
Answer: In the simple case where $P$ is projection onto a line with unit vector $\vec{e}$, you can look at it like this: if $\theta$ is the angle between $x$ and $\vec{e}$, and $\varphi$ is the angle between $y$ and $\vec e$, we have:
$$\langle Px,y \rangle = \langle \|x\| \cos{\theta \vec{e}},y \rangle = \|x\|\cos{\theta}\langle \vec{e},y \rangle = \|x\|\cos{\theta}\|y\|\cos{\varphi} \\
\langle x, Py \rangle = \langle x,\|y\|\cos{\varphi}\vec{e}\rangle = \|y\| \cos {\varphi} \langle x,\vec{e} \rangle = \|y\|\cos{\varphi}\|x\| \cos{\theta}.$$
(Recall that $P$ is symmetric iff $\langle Px, y \rangle = \langle x, Py \rangle$ for all $x,y \in V$.)
Another reason: Given a projection (orthogonal or not), we can describe it as the projection onto $A$ along $B$ (or $\rho_{A,B}$), where $A$ and $B$ are complementary subspaces. That is, if $V = A \oplus B$, take a basis for the vector space passing through the subspaces $A$ and $B$. Then the action of $P = \rho_{A,B}$ is to set the $B$-coordinates equal to zero, and leave the $A$ coordinates untouched. Every projection is of this form, and knowing $A$ and $B$ completely characterizes the projection.  A projection is orthogonal iff $B = A^\perp$.
It is an exercise in the algebra of inner products to show that if $P = \rho_{A,B}$, then $P^T = \rho_{B^{\perp}, A^{\perp}}$ (no matter if $P$ is orthogonal or not). So if $P$ is an orthogonal projection and $A = B^{\perp}$, we can see that $\rho_{B^{\perp}, A^{\perp}} = \rho_{A,B}$, and $P$ is symmetric.

Why is a projection matrix symmetric?


Compare very large numbers stored in string

Question: What is the best way to compare two very large numbers contained in string literals?
For example I want to compare the followings:
"90000000000000000000000000000000000000000000000000000000000000000000000000001"
"100000000000000000000000000000000000000000000000000000000000000000000000000009"
or
"0000000000111111111111111111111111111111111111111111111111111111111111111111"
"0000001111111111111111111111111111111111111111111111111111111111111111111111"
In both cases obviously the second one is greater, but how could I find it out efficiently without iterating on elements?
Comment: BigDecimal or BigInteger.
Answer: I would personally take the simplest approach: use BigInteger to parse both values, and compare those results. That wouldn't be terribly efficient, but it would be very simple - and then you could benchmark to see whether it's fast enough.
Otherwise, you could find the effective length by ignoring leading zeroes - and if one number is longer than the other, then that's all you need to know. Or write a method to get the "effective" digit of a string which may be shorter, returning 0 if necessary, and then compare from the longer string's length downwards until one string gives a bigger value. Something like:
// Return the digit as a char to avoid bothering to convert digits to their
// numeric values.
private char GetEffectiveDigit(string text, int digitNumber)
{
    int index = text.Length - digitNumber;
    return index < 0 ? '0' : text[index];
}

private int CompareNumbers(string x, string y)
{
    for (int i = int.Max(x.Length, y.Length); i >= 0; i--)
    {
        char xc = GetEffectiveDigit(x, i);
        char yc = GetEffectiveDigit(y, i);
        int comparison = xc.CompareTo(yc);
        if (comparison != 0)
        {
            return comparison;
        }
    }
    return 0;
}

Note that this doesn't check that it's a valid number at all, and it definitely doesn't attempt to handle negative numbers.
Comment: If he's already using strings, wouldn't a simple "the string which is shorter is the smaller number" approach work?
Comment: @Shark: Nope. Which number is bigger, "2" or "000001"?
Comment: Agreed, trailing zeros need to be truncated first, my mistake for presuming 'normal number behaviour' and skipping that part :)
Comment: +1 for this answer. I think it's a good idea to avoid all those bug-prone string manipulations, and rely on the parse methods of the `BigInteger` method. Much more understandable/readable, and probably, as you said, efficient enough.
Comment: @ken2k: I felt duty-bound to provide some efficient code too, mind you :)
Answer: If by comparison you mean boolean check, this will work:
public class Program
{
    static void Main(string[] args)
    {
        string a = "0000000090000000000000000000000000000000000000000000000000000000000000000000000000001";

        string b = "000100000000000000000000000000000000000000000000000000000000000000000000000000009";

        Console.WriteLine(FirstIsBigger(a, b));

        Console.ReadLine();
    }

    static bool FirstIsBigger(string first, string second)
    {
        first = first.TrimStart('0');
        second = second.TrimStart('0');
        if (first.Length > second.Length)
        {
            return true;
        }
        else if (second.Length == first.Length)
        {
            for (int i = 0; i < first.Length; i++)
            {
                double x = char.GetNumericValue(first[i]);
                double y = char.GetNumericValue(second[i]);
                if (x > y) return true;
                else if (x == y) continue;
                else return false;
            }
        }

        return false;
    }
}

Answer: Here is another solution:
    public static int CompareNumbers(string x, string y)
    {
        if (x.Length > y.Length) y = y.PadLeft(x.Length, '0');
        else if (y.Length > x.Length) x = x.PadLeft(y.Length, '0');

        for (int i = 0; i < x.Length; i++)
        {
            if (x[i] < y[i]) return -1;
            if (x[i] > y[i]) return 1;
        }
        return 0;
    }


Can I backup VMware Workstation settings (e.g. favorites, etc.) so that I can import them into another VMware Workstation install?

Question: I have VMware Workstation installed on Server 2008. I am backing up Virtual Machines so that I can restore them later. Is there any way to backup VMware Workstation's settings as well so that I don't have to manually open VMs and add them to favorites or change settings for things like adapters?
Answer: It seems like most, if not all, settings for Workstation are stored in the registry if on Windows. Here is a communities articles containing a script and some information to dump the settings into registry files: http://communities.vmware.com/message/157381
Note: The vmxnet registry keys appear to be unique per install. You'd probably need some more fancy scripting to loop through keys to find the proper vmxnet entries and dump them to be truly portable.


Interpretation of stopping time sigma algebra (as explained in Durret)

Question: I'm reading Rick Durret's "Probability Theory and examples". The book is available online here [ https://services.math.duke.edu/~rtd/PTE/PTE4_1.pdf ]. Please refer to the definition cum interpretation of the sigma algebra associated with a stopping time which appears in the book  following Example 4.1.4 on page 156.
I understand the mathematical definition of $F_N$, but I wish to know the interpretation of this. I don't quite understand Durret's explanation.
Thanks!
Answer: This is definitely a tricky thing to wrap one's mind around. In what follows, $n$ is supposed to be an integer, and $\tau$ an arbitrary stopping time.
How I think of it is as follows: for each $n$, we have a sigma algebra $F_n$. Thus we have a "decomposition" of the sigma algebra $F$, with each element of the decomposition being its own sigma algebra $F_n$.
Our goal is the following: to form a new decomposition which is "compatible" with the stopping time $\tau$, and use this decomposition to define a sigma algebra compatible with $\tau$.
Note  that the notion of being compatible with $\tau$ will depend on the time, hence why we split up the filtrations by each $n$ and consider how to make each $F_n$ individually compatible with $\{ \tau =n\}$.
Thus, for each $n$, in order to form this new compatible decomposition, we form a new sigma algebra collection of sets $\tilde{F}_n = " \{\tau =n  \}\cap F_n"$. By this I mean $\tilde{F}_n = \{ A \cap \{ \tau = n \} |\ A \in F_n   \}$.
Why would we do this? Because we only want to consider events for which $\tau$ is measurable, otherwise our sigma algebra would not be compatible with $\tau$. Thus we only consider events for which $\tau$ is measurable and which are contained in the information provided by the original decomposition. The logical "and" here means that we have to take set intersection, hence why intersection is used to form a decomposition compatible with $\tau$.
As one final step, we also have to create the "sigma algebra at infinity" $\tilde{F}_{\infty}$ formed by the limit of the filtration $F$ as well as the event $\{  \tau = \infty\}$. (EDIT 1.5 years later: I think this means $$\tilde{F}_{\infty} := "\{\tau = \infty\} \cap \bigcup\limits_{n \ge 1} F_n " := \left\{ A \cap \{\tau = \infty\} \left| A \in \bigcup\limits_{n \ge 1} F_n \right. \right\} $$
Then $F_{\tau}$ is the smallest sigma algebra formed by combining all of the collections of sets $\tilde{F}_n$ ($\forall n$) and $\tilde{F}_{\infty}$. We take the smallest sigma algebra containing all of the compatible sigma algebras collections of sets because we don't want any redundant information.
In other words, $F_{\tau}$ is formed by the "projections" or "traces" of each event $\{\tau=n\}$ onto each sigma algebra $F_n$ via intersection.
Comment: How is $\overline{\mathcal{F}_n}$ a $\sigma$-algebra?  For instance, it contains $\{\tau=n\}$ but not its complement?
Comment: @user3281410 The more I read this answer, the less sure I am that it agrees with what Durrett writes on p. 156. I wish I remembered my thought process when I wrote this 1.5 years ago, but I honestly don't. For now I will hold off on editing it more because it probably doesn't make sense for me to edit it if I don't understand it completely. All I remember is that I had stayed up all night working with someone on a homework assignment involving the stopping time $\sigma$-algebra several months before writing this answer, and the answer is similar to the resulting interpretation we came up with.
Comment: @user3281410 I think you're right -- for example, even if it did contain $\{ \tau = n\}$ and its complement, there's no reason why it would contain $\Omega$, since $\{ \tau = n \} \cap \Omega = \{ \tau = n \}$ which would be a strict subset in any interesting case. Also Durrett only says "collection of sets", and there is probably a good reason for that. I am editing the post to fix the mistake, please let me know if any mistakes still remain.