Find a center of the sphere

Question: I need to find the center of a sphere of radius $5$ which is tangent to both the planes $x − 2y + 2z = 3$ and $3x + 4z = 8$.
I attempted the problem in the following way:
Let the point be $(x_0, y_0, z_0)$. Then the perpendicular distance from each plane to $(x_0, y_0, z_0)$ should be $5$.
So,
$5 = \frac{|x_0-2y_0+2z_0-3|}{\sqrt{1+4+4}}$,
$5 = \frac{|3x_0+4z_0-8|}{\sqrt{9+0+16}}$.
This leaves me with 2 equations and three variables. How can I proceed? Also, what to do with absolute values?
EDIT: I also noticed that the normal vector to the second plane has magnitude 5 (same as radius). Can that be helpful?
Comment: I'd recommend you not delete your own questions. This one is actually well-posed.
Answer: $$\pi_1:\mathbf r\cdot(1,-2,2)=3\\
\pi_2:\mathbf r\cdot(3,0,4)=8$$
Given two non-parallel planes, the centres of spheres of a fixed radius tangent to both planes must lie on a line parallel to the planes' line of intersection, and hence parallel to the cross product of the planes' normals. In this case:
$$(1,-2,2)×(3,0,4)=(-8,2,6)=2(-4,1,3)$$
Hence the locus of sphere centres lies on the line $\mathbf a+k(-4,1,3)$ where $k\in\Bbb R$ and $\mathbf a$ is a point to be determined.
To find an $\mathbf a=(x_0,y_0,z_0)$, arbitrarily set $z_0=0$ in the two distance equations you have derived so that they become
$$\frac{|x_0-2y_0-3|}{\sqrt{1+4+4}}=5,\frac{|3x_0-8|}{\sqrt{9+0+16}}=5$$
$$|x_0-2y_0-3|=15,|3x_0-8|=25$$
Depending on whether we substitute $|q|=n$ with $q=+n$ or $q=-n$, we get four different solutions for $\mathbf a$ and hence four distinct loci of sphere centres.

$x_0-2y_0-3=+15,3x_0-8=+25$: $\mathbf a=(11,-\frac72,0)$
$x_0-2y_0-3=+15,3x_0-8=-25$: $\mathbf a=(-\frac{17}3,-\frac{71}6,0)$
$x_0-2y_0-3=-15,3x_0-8=+25$: $\mathbf a=(11,\frac{23}2,0)$
$x_0-2y_0-3=-15,3x_0-8=-25$: $\mathbf a=(-\frac{17}3,\frac{19}6,0)$

Hence the locus of centres of spheres of radius 5 tangent to $\pi_1$ and $\pi_2$ is
$$\mathbf c=\mathbf a+k(-4,1,3)\\
k\in\Bbb R, \mathbf a\in\{(11,-\tfrac72,0),(-\tfrac{17}3,-\tfrac{71}6,0),(11,\tfrac{23}2,0),(-\tfrac{17}3,\tfrac{19}6,0)\}$$
Comment: Thank you. I really appreciate your help.
Answer: Is there only one sphere that is tangent to both planes, or are there more than one? Solving these equations will most probably give you one free variable, or in other words, the equation of a line. Then any point on this line will satisfy your desired property. See if this works. In terms of absolute values, remember $$\left| x \right| = \cases{x = x \space \space for \space x \geq 0, \\ x = -x \space for \space  x < 0}$$ Therefore, you can split the problem up into two different cases, and that will probably make it easier.
Comment: Your answer is not a concrete solution but contains some valid hints.  However in the case that the Question has presented a valid attempt to solve the problem, it probably is of greater value to future Readers to address any shortcomings of that attempt (resolve them), rather than to say mainly "See if this works".
Comment: I understand what the abs.value is. So, I will get then 4 different cases and eliminating variables will get 4 equations of lines. I cannot picture how many spheres are there that would be tangent. Is it infinitely many?

Find a center of the sphere


How to put lions into n cages

Question: In how many ways can you put lions into n cages so that in each cage there's no more than 1 lion and every two adjacent cages are not occupied (lions cant be located next to each other). We have an unlimited number of lions and there's at least one lion (so at least one cage is occupied).
Thanks in advance for any help!
Edit: I think I could find the generating function if I had the reccurent sequence
Comment: Cages are on a row? Or in a circle?
Comment: @peterwhy on a row
Answer: If you remove condition that at least one cage is occupied, this is the same as asking

How many $n$-lengthed strings of $A$'s and $B$'s are there, in which there are no conscutive $A's$?

Recursion. Let be $T(n)$ number of strings.
$T(1) = 2$, $T(2) = 3$ and
$$T(n) = T(n-1) + T(n-2)$$
for $n>2$. Try to prove upper relation. Hint: take a look at the last char of string.
Comment: @Max Keep $T(1)$ and $T(2)$ as in the answer, or else you might lose the cases where the first cage is empty.
Answer: Let $f(n)$ be the number of the ways you want.
Also, let $g(n)$ be the number of the ways with a lion in the $n$-th cage, and let $h(n)$ be the number of the ways without any lion in the $n$-th case.
So, we have
$$f(n)=g(n)+h(n).$$
Now you'll easily get
$$g(n+1)=h(n)$$
$$h(n+1)=g(n)+h(n).$$
Hence, you'll get
$$h(n+1)=h(n)+h(n-1).$$
This is a well-known sequence...
Answer: As this question is tagged generating-functions, here's a different approach (looks long but it gives the generating function directly), using the formalism from the wonderful book Analytic Combinatorics (available online!) by Flajolet and Sedgewick.
Let "L" denote a cage with a lion in it, and "E" denote an empty cage. Then, convince yourself that

any configuration of cages can be denoted by a sequence of 'E's and 'L's such that no two 'L's are consecutive, and that
this is the same as a sequence over the alphabet $\{\mathrm{E}, \mathrm{EL}\}$, except possibly with an $\mathrm{L}$ at the beginning.

For example, "EELEEELEEE" is one arrangement of $10$ cages, and it can be viewed as the sequence $(\mathrm{E}, \mathrm{EL}, \mathrm{E}, \mathrm{E}, \mathrm{EL}, \mathrm{E}, \mathrm{E}, \mathrm{E})$.
Let $\mathcal{C}$ denote the class of all cage configurations. Then, by the reasoning above, we have (where $\epsilon$ denotes the empty string)
$$\mathcal{C} = (\epsilon + \mathrm{L}) \operatorname{S\scriptsize EQ}(\{\mathrm{E}, \mathrm{EL}\})$$
which immediately translates (by the first theorem in the book) to the generating function
$$C(z) = (1 + z)\frac{1}{1-(z+z^2)}$$
which (note that $C(z) = 1 + 2z + 3z^2 + 5z^3 + 8z^4 + \dots$) is exactly what you would get from the recurrence relations.
Note that we didn't have to consider configurations of specifically $n$ cages explicitly and then sum over $n$ to get the generating function; we directly derived the generating function of the entire class of configurations.

[Notes: $\epsilon$ is of size $0$ and has generating function $z^0 = 1$, $\mathrm{L}$ is of size $1$ and has generating function $z^1 = z$, the set $\{\mathrm{E}, \mathrm{EL}\}$ has generating function $z^1 + z^2$, and a sequence over a class with generating function $B(z)$ has generating function $\dfrac{1}{1-B(z)}$.]

Oh also: I just noticed the "at least one lion" requirement. Well, in that case (dropping some braces in the notation for convenience):
$$\mathcal{C} = \left((\epsilon + \mathrm{L}) \operatorname{S\scriptsize EQ}(\mathrm{E}, \mathrm{EL})\right) \setminus \operatorname{S\scriptsize EQ}(\mathrm{E})$$
so
$$C(z) = (1 + z)\frac{1}{1-(z+z^2)} - \frac{1}{1-z}$$
Another way of deriving the same result is to say: we want a (possibly empty) sequence of 'E's, followed by an 'L' (the "at least one lion", namely the first), followed by a (possibly empty) sequence over $\{\mathrm{E}, \mathrm{EL}\}$. So
$$\mathcal{C} = \operatorname{S\scriptsize EQ}(\mathrm{E}) \, \mathrm{L} \, \operatorname{S\scriptsize EQ}(\mathrm{E}, \mathrm{EL})$$
which translates to
$$C(z) = \frac{1}{1-z} z \frac{1}{1-(z+z^2)}$$
which is the same.
Answer: If you write out the number of lions in each cage, the zeros and ones give you exactly the Zeckendorf representations of length at most $n$, so there are $F_{n+2}-1$ ways (minus one because you eliminated $0$). (With the usual Fibonacci numbers starting at $F_0=0$.)
See Zeckendorf on Wikipedia for details.

How to put lions into n cages


Putting Stickers on an acoustic guitar

Question: Does placing stickers on an acoustic guitar alter its sound quality?

I have my whole front covered with stickers.
Should I remove them?
Answer: Stickers will change the sound a little, making it less rich, duller. However, since they are already stuck, you may well create a bigger problem as you remove them. The adhesive may already have spoiled the finish in the guitar's body, so removing them will leave you with a tarnished (at least) front. If they've been there a while, the wood under them may end up darker than the rest of that face.You may pull some lacquer off as they are removed. Unless the first one comes off easily - try the smallest - I'd advocate leaving them. Warming them with a hair-drier is a (risky) possibility.
Comment: @Wheat - we don't know if the guitar in question is new or old. Caution was and still is encouraged.Not all sticky on stickers is googonable.
Comment: Unless it's an expensive guitar I really doubt you'd have a discernible different sound. Many acoustic guitars have a scratchplate which is essentially a large, _very_ thick sticker. And I doubt it's a very expensive guitar or you wouldn't have put stickers on it in the first place!
Comment: I disagree. Most acoustic guitars these days are finished with a very durable and thick polyurethane or polyethylene finish. In this case putting on and removing stickers does no harm to the finish. Try removing a small part of one sticker and see if you can detect any damage to the guitar's finish or any discoloration. If there is none, then it should be safe to remove the rest of the stickers if you want to. A commercial solvent that is designed to remove the adhesive on stickers, such as Goo-Gone, is useful for this purpose. http://googone.com
Comment: I took many stickers off one if my guitars last year. Some had been on for over six years... The surface was destroyed. Lacquer and varnish were eaten away badly.

Putting Stickers on an acoustic guitar


Undefined variable: row on CodeIgniter when trying to access single row

Question: I have a database of pets, and basically I want to view a pet's details by its ID. Here is what my Controller method is like:
public function details()
{
    $this->load->model('animalsmodel');
    $row = $this->animalsmodel->details($this->uri->segment(3));
    $this->load->view('shared/header');
    $this->load->view('animals/details', $row);
    $this->load->view('shared/footer');
}

And here is the AnimalsModel code for grabbing the relevant row:
function details($animalId) {
    $q = $this->db->query('SELECT Animals.Name, Animals.DateAdmitted, Animals.FoundDescription, Animals.Description, Animals.Neutered, Animals.DateNeutered, Types.Name AS Type, Healthchecks.CheckInfo FROM Animals LEFT JOIN Types ON Animals.TypeId = Types.TypeId LEFT JOIN Healthchecks ON Animals.HealthcheckId = Healthchecks.HealthcheckId WHERE Animals.AnimalId = ?', $animalId);
    if ($q->num_rows() > 0)
    {
        $row = $q->row();
        return $row;
    } else
    {
        echo "No Results Man!!";
    }
}

I have run that MySQL query manually in phpMyAdmin, and it works, it gets me the correct row.
EDIT: I have just gone ahead and did a var_dump() on the $row object, and I got the following:
object(stdClass)#17 (8) { ["Name"]=> string(6) "Quemby" ["DateAdmitted"]=> string(10) "2013-01-28" ["FoundDescription"]=> string(94) "The story of how I got to be here. Phasellus ornare. Fusce mollis. Duis sit amet diam eu dolor" ["Description"]=> string(65) "massa non ante bibendum ullamcorper. Duis cursus, diam at pretium" ["Neutered"]=> string(1) "0" ["DateNeutered"]=> string(10) "0000-00-00" ["Type"]=> string(3) "Dog" ["CheckInfo"]=> string(26) "a, facilisis non, bibendum" }

So it looks like I have my row! but why does CI keeps complaining about Undefined variable: row :(
Comment: please print $row and check is it correct or not?
Comment: First Print: $q->num_rows();
Check if  greater than 0?
Comment: @Praveen and Veekay: Q Updated.
Answer: please try this
public function details()
{
    $this->load->model('animalsmodel');
    $row = $this->animalsmodel->details($this->uri->segment(3));
    $data['row'] = $row;
    $this->load->view('shared/header');
    $this->load->view('animals/details', $data);
    $this->load->view('shared/footer');
}

Now try to access data in view.
Comment: It worked ! Thanks very much Praveen ^_^. Can you please explain why this worked and mine didn't? Is it a convention in CI that the thing being passed must always be called $data and be of type array?
Comment: Read this you will get idea. still you have doubt leave a message for me i will get back to you.
http://ellislab.com/codeigniter/user-guide/general/views.html
Answer: You can check your last query in CI by using

 <?php print_r($this->db->last_query()) ?>

then copy past it and try it in phpMyadmin or whatever you use.
and for better result/review/maintain your MODEL code should be look like this
  function details($animalId) {
$this->db->select('Animals.Name, Animals.DateAdmitted, Animals.FoundDescription,...');
$this->db->where('AnimalId', $animalId);
$this->db->join('Types'       , 'Types.TypeId               = Animals.TypeId'       , 'left');
$this->db->join('Healthchecks', 'Healthchecks.HealthcheckId = Animals.HealthcheckId', 'left');
$this->db->from('Animals');
$q = $this->db->get();

if ($q->num_rows() > 0)
{
    $row = $q->row();
    return $row;
} else
{
    echo "No Results Man!!";
}

}
and last thing is:
in CI it is better to use names like follow:
   mymodelname_model not myModelNameModel
in your case
   animals_model not animalsmodel
thats the way CI users do it :)
Enjoy your code


Can not parse xml data to listview on xamarin android

Question: In menu/ Genre.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <group android:checkableBehavior="single">
    <item
      android:id="@+id/nav_home"
      android:icon="@drawable/ic_home_black_48dp"
      android:title="Home" />
    <item
      android:id="@+id/nav_genre"
      android:icon="@drawable/ic_toc_black_48dp"
      android:title="Genres" />

    <item
      android:id="@+id/nav_download"
      android:icon="@drawable/ic_get_app_black_48dp"
      android:title="Download" />
  </group>
  <item android:title="Account">
   <menu>
  <group android:checkableBehavior="single">
   <item
     android:id="@+id/nav_about"
     android:icon="@drawable/ic_lock_open_black_48dp"
     android:title="About"/>
     <item
     android:id="@+id/nav_signout"
     android:icon="@drawable/ic_perm_identity_black_48dp"
     android:title="Sign out"/>
  </group>

   </menu>
  </item>

</menu>

In layout/GenreFragment.axml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lst_genre"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

In viewModel/ GenreFragmentVM:

public class GenerFragmentVM : Fragment
 {
  public override void OnCreate (Bundle savedInstanceState)
  {
   base.OnCreate (savedInstanceState);

   // Create your fragment here
  }
  ListView lst;
  public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
  {
   // Use this to return your custom view for this Fragment
   // return inflater.Inflate(Resource.Layout.YourFragment, container, false);

   base.OnCreateView (inflater, container, savedInstanceState);
   var view = inflater.Inflate (Resource.Layout.abc_list_menu_item_layout, container, false);
   lst = view.FindViewById<ListView> (Resource.Id.lst_genre);
   lst.SetAdapter(new ArrayAdapter<string> (this,Resource.Layout.abc_list_menu_item_layout,Resource.Menu.Genres));

   //Event click on listview
   lst.ItemClick+= delegate(object sender, AdapterView.ItemClickEventArgs e) {

   };
  }
 }

Error: (19,19): Error CS1502: The best overloaded method match for
  `Android.Widget.ArrayAdapter.ArrayAdapter(Android.Content.Context,
  int, int)' has some invalid arguments (CS1502) (SoundCloud)
(45,45): Error CS1503: Argument #1' cannot convert
  SoundCloud.GenerFragment' expression to type
  `Android.Content.Context' (CS1503) (SoundCloud)

In Mainactivity.cs
protected override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);

        // Set our view from the "main" layout resource
        //ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
        SetContentView (Resource.Layout.Main);

        var mToolbar= FindViewById<Toolbar> (Resource.Id.toolbar);
        //Toolbar will now take on default action bar chacracteritics
        SetActionBar(mToolbar);
        ActionBar.Title = "home";

        //Enable suppport action bar to display hamburger
        //ActionBar.SetHomeAsUpIndicator(Resource.Drawable.icon_hambuger);
        //ActionBar.SetDisplayHomeAsUpEnabled (true);

        //Set menu hambuger
        ActionBar.SetHomeAsUpIndicator (Resource.Drawable.ic_menu_white_24dp);

        ActionBar.SetDisplayHomeAsUpEnabled (true);

        drawerLayout = FindViewById<DrawerLayout> (Resource.Id.drawer_layout);
        navigationView = FindViewById<NavigationView> (Resource.Id.nav_view);

        //Event click on navigatonView
        //
        CreateFragments();
        LoadInditialFragment ();

        navigationView.NavigationItemSelected += NavigationView_NavigationItemSelected;

    }

    void NavigationView_NavigationItemSelected (object sender, NavigationView.NavigationItemSelectedEventArgs e)
    {
        e.MenuItem.SetChecked (true);
        if (e.MenuItem.ItemId != currentFragmentId) {
            SwitchFragment (e.MenuItem.ItemId);
        }
        drawerLayout.CloseDrawers ();
    }

    // Khoi tao gia tri cho fragment layout

    private void CreateFragments()
    {
        explorFragment= new ExploreFragment();
        genreFragment = new GenerFragment ();

    }
    //
    private void LoadInditialFragment ()
    {
        var transaction = FragmentManager.BeginTransaction ();
        transaction.Add (Resource.Id.fragmentContainer, explorFragment).Hide (explorFragment);
        transaction.Add (Resource.Id.fragmentContainer, genreFragment);
        transaction.Commit ();
    }

    private void SwitchFragment(int FragmentId)
    {
        var transaction = FragmentManager.BeginTransaction ();

        switch (currentFragmentId) {
        case Resource.Id.nav_home:
            transaction.Hide (explorFragment).Commit ();
            break;
        case Resource.Id.nav_genre:
            transaction.Hide (genreFragment).Commit ();
            break;
        }

        transaction = FragmentManager.BeginTransaction ();
        switch (FragmentId) {
        case Resource.Id.nav_home:
            transaction.Show (explorFragment);
            transaction.Commit ();
            break;

        case Resource.Id.nav_genre:
            transaction.Show (genreFragment);
            transaction.Commit ();
            break;
        }

        currentFragmentId = FragmentId;
    }

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:titleTextColor="@android:color/background_light" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <FrameLayout
                android:id="@+id/fragmentContainer"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </RelativeLayout>
    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/navmenu" />
</android.support.v4.widget.DrawerLayout>
Comment: Change the first argument in the `ArrayAdapter` constructor call to `this.Activity`.
Comment: Assuming the code you pasted is not complete, missing the `return` of the `View`.
Comment: I got that problem Object reference not set to an instance of an object
Comment: @J.Joe Sounds like you are trying to access a method of a class instance using a null reference(?) Can you provide more details (update your answer if needed) on which line, stack trace, etc, ...
Answer:
Passing the Activity of your Fragment as the first arg of the Widget's ArrayAdapter
Added a return of your new view;

Code:
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    base.OnCreateView (inflater, container, savedInstanceState);
    var view = inflater.Inflate (Resource.Layout.abc_list_menu_item_layout, container, false);
    lst = view.FindViewById<ListView> (Resource.Id.lst_genre);
    lst.SetAdapter(new ArrayAdapter<string> (this.Activity,Resource.Layout.abc_list_menu_item_layout,Resource.Menu.Genres));
    //Event click on listview
    lst.ItemClick+= delegate(object sender, AdapterView.ItemClickEventArgs e) {
    };
    return view;
}

Comment: I got that problem Object reference not set to an instance of an object
Comment: lst.SetAdapter(new ArrayAdapter (this.Activity,Resource.Layout.abc_list_menu_item_layout,Resource.Menu.Genres));
Comment: Are any of those objects' null? Just set a break point there and debug that line.
Comment: lst.SetAdapter(new ArrayAdapter (this.Activity,Resource.Layout.abc_list_menu_item_layout,Resource.Menu.Genres));  it get null
Comment: App be break there
Comment: Where are you going?
Comment: I see that you updated, code, I'll take a look at it
Comment: @J.Joe Have a look at my answer.
Answer: Reason for your first Build Error is as explained by SushiHangover, i.e You should be passing an instance of the parent Activity (activity which hosts this fragment) as the first parameter to ArrayAdapter Constructor.
Reason for your run-time (Object reference not set to an instance of an object) Exception is because "Activity" property is null. "Activity" property will have a value only when the Fragment attachment to parent Activity is complete. So essentially, you should not be accessing Activity property from OnCreateView Method. You can initialize your listview either in OnAttach or OnCreate callbacks. I am modifying your code accordingly.
`public class GenerFragmentVM : Fragment
{
    ListView lst;
    public override void OnCreate (Bundle savedInstanceState)
    {
        base.OnCreate (savedInstanceState);

         lst.SetAdapter(new ArrayAdapter<string> (this.Activity,Resource.Layout.abc_list_menu_item_layout,Resource.Menu.Genres));
    }

public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView (inflater, container, savedInstanceState);
var view = inflater.Inflate (Resource.Layout.abc_list_menu_item_layout, container, false);
lst = view.FindViewById<ListView> (Resource.Id.lst_genre);

//Event click on listview
lst.ItemClick+= delegate(object sender, AdapterView.ItemClickEventArgs e) {
};
return view;
}
}


JCache CacheStatisticis with Cache Size

Question: I have used JCache with EhCache as provider. Using the MBean I am able to get cache statistics but there is missing attributes like size of the cache. I see LiveCacheStatistics provide that but how to get instance of it from JCache
<code>List<Map<String,Object>> cacheStatasticsList = new ArrayList<>();

try {
    final MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();

    final Set<ObjectInstance> cacheBeans = beanServer.queryMBeans(ObjectName.getInstance("javax.cache:type=CacheStatistics,CacheManager=*,Cache=*"), null);

    for (ObjectInstance cacheBean : cacheBeans) {
        final CacheStatisticsMXBean cacheStatisticsMXBean =
                MBeanServerInvocationHandler.newProxyInstance(beanServer, cacheBean.getObjectName(), CacheStatisticsMXBean.class, false);

        Map<String,Object> cacheStatasticsMap = new HashMap<>();
        cacheStatasticsMap.put("Name",cacheBean.getObjectName().getKeyProperty("Cache"));
        cacheStatasticsMap.put("Gets",cacheStatisticsMXBean.getCacheGets());
        cacheStatasticsMap.put("Hits",cacheStatisticsMXBean.getCacheHits());
        cacheStatasticsMap.put("Misses",cacheStatisticsMXBean.getCacheMisses());
        cacheStatasticsMap.put("Removals",cacheStatisticsMXBean.getCacheRemovals());
        cacheStatasticsMap.put("Evictions", cacheStatisticsMXBean.getCacheEvictions());
        cacheStatasticsMap.put("AvgGetTime", cacheStatisticsMXBean.getAverageGetTime());
        cacheStatasticsMap.put("AvgPutTime", cacheStatisticsMXBean.getAveragePutTime());
        cacheStatasticsMap.put("AvgRemoveTime" , cacheStatisticsMXBean.getAverageRemoveTime());
        cacheStatasticsList.add(cacheStatasticsMap);
    }

} catch(Exception e){
    log.error("Error in getting cache statistics.");
    return cacheStatasticsList;
}
return cacheStatasticsList;
</code>
Answer: Unfortunately, the JSR107 standard does not define a size in the statistics object. See: CacheStatisticsMXBean
Some reasons that I recall from discussions with the expert group and spec leads and from my own experience as cache implementer:

For a distributed cache it is hard to determine the size. There might be a need to call the other nodes and the value might be somehow only an estimate
The JSR107 standard omitted to specify a size limit as well. This is because some implementations specify the the count of entries, some use bytes. So probably the "idea of size" was left out consequently in the statistics as well
If expiry is defined, the cache size can mean different things: the number of entries not expired yet, the number of entries occupying memory in the cache. The most logical measure would be the "entries not expired". But that would some cache implementations check for expired entries before the statistics can be returned

Although it is very painful, that the size is missing in the statistics, there are reasons not to include it. The metrics that are available now, are just a read out from counters. Depending on the implementation, to come up with the size, some heavier operations are needed.

JCache CacheStatisticis with Cache Size


If $K$ is compact, then $m_*(K) = m^*(K)$

Question: I was reading http://people.math.harvard.edu/~shlomo/212a/11.pdf
In page 25, it mentions that:

If $K$ is a comapct set, then $m_*(K) = m^*(K)$ since $K$ is a comapct set contained in itself.

I don't quite understand how the inner measure equal the outer measure here.
Answer: I misread the definition of inner measure.
The inner measure is given as:
$$m_\ast(A)=\sup\lbrace m^*(K): K\subseteq A \text{ is compact}\rbrace.$$
Hence, when $K$ compact, by definition
$$m_*(K) = m^*(K)$$


Remove escaping sequences automatically while redirecting

Question: Lots of shell tools such as grep and ls can print colorful texts in the terminal. And when the output is redirected to a regular file, the escaping sequences representing colors are removed and only pure texts are written to the file. How to achieve that?
Answer: Use:
if [ -t 1 ]

to test whether stdout is connected to a terminal. If it is, print the escape sequences, otherwise just print plain text.
Answer: Specifically, grep has a command-line switch to adjust this setting:
echo hello | grep ll                 # "ll" is printed in red
echo hello | grep --color=never ll   # "ll" is printed without special colouring

Most if not all tools that do this sort of thing will have a similar switch - ls does.  Check the manpages for other tools.
Another way to do this for tools that auto detect whether stdout is connected to the terminal or not is to trick them by piping output though cat:
echo hello | grep ll | cat           # "ll" is printed without special colouring

Answer: I had the same issue the other day and realized I had the following in my .bashrc
alias grep='grep --color=always'

I changed it to the following and had no further problems
alias grep='grep --color=auto'


overlap dropdown menu and slideshow

Question: I use Zeropoint theme and the drop-down menu in this theme.
When I hover the mouse over a menu, and the menu is expanded, my submenu is placed under the slideshow and is not show completely.
Do you have any suggestion on how to solve it?
Comment: The slideshow you're talking about, is it flash or javascript based? Do you have a url where we can see it ourselves?
Comment: http://devel.codeproject.ir/amad-bsco
Answer: I have this problem using things like Views Slideshow and NiceMenus.  You can perhaps fix it by changing the CSS of the menu to include the following: z-index: 99. If you post a link to the site I can give you a more detailed answer.
Comment: my slide show is Views Slideshow too.
http://devel.codeproject.ir/amad-bsco

overlap dropdown menu and slideshow


Prove the equation $\ln(x) = \frac1 {x-1}$ has exactly 2 real solutions.

Question:
Prove the equation $\ln(x) = \frac1 {x-1}$ has exactly 2 real solutions.

Hello all. I thought of defining the function $f(x)=x-e^{\frac 1 {x-1}}$ and showing it has only 2 single roots, though I am not sure on how to show it and I understand it is better to prove using Lagrange's theorem.
Would be happy to get some help on that question, thanks in advance :)
Answer: Consider the function $f$ defined on $(0,1)\cup(1,\infty)$ by $$f(x) = (x-1)\ln x\,.$$
We have
$\lim_{x\to 0^+} f(x) = +\infty$, $\lim_{x\to 1^-} f(x)=\lim_{x\to 1^+} f(x) = 0$, and $\lim_{x\to +\infty} f(x) =+\infty$. Further, $f$ is differentiable twice on its domain, with
$$
f''(x)  = \frac{x+1}{x^2} > 0
$$
and
$$
f'(x)  = 1+\ln x - \frac{1}{x}
$$
which has limit $0$ at $x=1$ (on both sides), $-\infty$ at $0^+$ and $+\infty$ at $\infty$.Combining the two (the limits of $f'$ and the fact that $f'$ is strictly increasing on $(0,1)$, and strictly increasing on $(1,\infty)$), $f' <0$ on $(0,1)$ and $f'>0$ on $(1,\infty)$, i.e. you have strict monotonicity of $f$ on both parts of its domain.
From this last thing, along with the limits of $f$, you get the result: $f$ takes the value $1$ exactly once on $(0,1)$, and exactly once on $(1,\infty)$.
Comment: Why would you leave $1$ out of the domain of $f$?
Comment: @orangeskid You don't need to, but the original problem leaves out $1$ (for obvious reasons: not defined), so it makes sense to not worry about $x=1$ in the analysis.
Answer: HINT
Consider and study the function $f(x)=(x-1)\log x-1$ using derivatives and IVT to prove that we have exactly 2 solutions for $f(x)=0$.
Comment: @ClementC. Yes of course, strictly monotonicity!
Comment: The IVT will give existence; the "exactly $2$" requires something else.
Answer: Consider $f(x)=ln(x)- \frac{1}{1-x}$ and then differentiate it once and look at how many times this function changes monotony
Answer: Start with this:  On $(1,\infty)$, $x\mapsto \ln(x)$ is strictly increasing and increases without bound.  On the same interval $x \mapsto 1/(x-1)$ decreases from $+\infty$ to $0$.  Now apply the intermediate value theorem to see you have at least one root on $(1,\infty)$.  The monotonicities can be used to see the root is unique.  Now deal similarly on $(0,1)$.
Answer: Without using a study function, you can look over $]0,1[$ and $]1,+\infty[$.
On both segments, $x\mapsto \frac{1}{x-1}$ and $x\mapsto \ln(x)$ are continuous respectively strictly decreasing and increasing : they can have on both segment at most one intersection point. Now looking on the values near the boundaries, and using a corollary of the Intermediate value theorem, you can conclude the existence of exactly one point of intersection on each segment, two in total.
Answer: $\ln x$ does not exist for $x \le 0$ and $\frac 1{x-1}$ does not exist for $x = 1$.
So if there are solution they will exist on the intervals $(0,1)$ and $(1, \infty)$.
On these intervals the function $f(x) = \ln x - \frac 1{x-1}$ is continuous.
$f'(x) = \frac 1x - (-1)\frac 1{(x-1)^2} = \frac 1x + \frac 1{(x-1)^2} > 0$ so $f'(x)$ is increasing on the intervals $(0,1)$ and $(1,0)$. So if $f(x)$ ever "crosses the $x$-axis".  It can only do so at most once in each interval.
Taking the limits of $f(x)$ as $x \to 0^+; x \to 1^-; x\to 1^+$ and $x\to \infty$ we will see that $f(x)$ will have negative and positive values on each of these intervals.  So by the intermediate value theorem there will be values in these intervals where $f(x) = 0$.
And as $f'(x) > 0$ there can only at most one on each interval, so there will be exactly one on each interval.
And, obviously, if $f(x) = 0$ then $\ln x = \frac 1{x-1}$.


Can an imperfect (or half) cadence feel completely stable/finished?

Question: A while ago I wrote a quartet (or attempted to) which contained an imperfect cadence in a minor key, specifically i - V. The V chord is simply a triad with no seventh. In the context that I wrote it, it does not feel unstable or create the feeling of needing to resolve to the tonic.  Though it naturally returns to the i chord afterward, it feels perfectly stable - in fact I use this cadence as the finishing cadence. Were I to describe the kind of 'aesthetic' qualities it has, I'd say "grand", "heroic" or "momentous" though I realise that this is subjective and dependent on context too.
Here's a screenshot of the cadence from my quartet. The key is A minor and the final chord of that phrase is E major. Although not in the screenshot, the following chord would be A minor.

Another example of this is in the piece of music Death of Walter from the video game Fable III.
YT link:

The cadence occurs at roughly 0:40 and again at 1:31. If this version hasn't been transposed then the key is B minor and chord V is F# major.
So my question I suppose is: is this simply considered an imperfect cadence or is it a different type of imperfect cadence? I've looked into it a little but could not find anything regarding one that doesn't feel a need to be resolved. Generally descriptions of imperfect cadences give that as their defining quality. Although I'm maybe making a big deal of this, this isn't to say it's an uncommon sound to hear in music - it sounds quite natural and intuitive. I suppose one thing I should note is that perhaps it's kind of subjective; compared to me you may find it to feel less stable than I've described. I've not looked into it so I don't know if what I'm describing could be replicated in a major key. I'm just making guesses but the raised seventh degree in a minor scale to create the major V chord may play a role.
Comment: This might be subjective or a matter of context. Pieces (especially songs) have been ended on half cadences or with unresolved harmonies. I expect if one listens to enough of such music one might hear stability in a harmony that would be considered unresolved in other contexts. Also harmony alone does not make the cadence. With a strong enough rhythmic resolution the music can feel stable even with a less stable harmony. I'll confess I'm not sure I can come up with and example right now but it should be possible.
Answer: I will look up a proper source for this (away from my counterpoint books at present!) but I seem to recall it was common to use endings that sound like this in 16th Century counterpoint.
Imagine you were writing in E Phrygian (all "white keys" with the final cadence on E).  One way of managing a cadence in this mode which lacks a perfect fifth in its dominant [V] was to cadence through iv to I.
So your work could be laid out like so...
[E phrygian] ..... counterpoint .... iv...I
It is easily mistaken for a half-cadence in A minor but actually was a legitimate ending to a piece in the Phrygian mode.
This is not your exact situation, as you stated you are deliberately writing in A minor, but there is at least some precedent for ending with this sonority.
Again, I will add a proper citation when I find it!
Comment: I'm wondering if the G# stymies this idea. E Phrygian doesn't (and didn't) have that, just the G natural. Not sure either if Tierce de Picardie had been 'invented' by then.
Comment: Thanks for your answer - very interesting. I had a thought that it may not actually be in A minor, but didn't give modes any thought. But as Tim had noted, there is a G sharp in the E chord - the major third of the chord. Unless it's a plagal cadence in E phrygian combined with a Tierce de Picardie (also suggested by Tim).
Comment: One possible citation (my translation): "The paragon of a 'phrygian' in the 16c was not the just discussed one, which has the tenorizans in the bottom voice. It does not allow an appropriate movement in the bass. As the phrygian mode forbids a falling fifth in the bass, it must fall a fourth, often following another auxiliary cadence." (T. Daniel: "Kontrapunkt." Dohr, 2002)
Answer: Somewhat in the ear of the beholder. It's going to be subjective, but there's no reason why finishing on a V in a minor key won't sound like an end cadence - to some - if not many. We're all used to the end harmony being a major one, heck, even pieces in minor keys quite often finish on a major (Tierce de Picardie).
I guess the 'purpose' of an imperfect cadence is to keep the listener hanging on, expecting there to be more to follow, but if it doesn't, well, at least things have finished on a satisfying V chord in the diatonic key! It's your piece, and you can do whatever you like. Haydn's Surprise symphony was unconventional, but it worked, and is renowned even today!
Comment: One thing I had mentioned was that the sound/feel that this cadence produces is not unconventional by any means. It's quite natural and intuitive to the ear. Also (provided it is actually in A minor not some other key or mode) then it can't be a Tierce de Picardie as it isn't finishing with a major I chord (A major).
Answer: It's still considered an imperfect (half) cadence. The greater or lesser sense of stability at the cadence point does not change the analysis or the name of the cadence. In the case of this piece, it's especially true, since the piece continues by immediately stating the chord of resolution.
A similar effect can sometimes be found between movements in Baroque music. For example, the Largo of Corelli's C Minor Concerto Grosso (Op. 6, No. 3) ends on an imperfect cadence. If one listens only to the bars immediately preceding the cadence, it's sounds perfectly stable, though in the larger context, it's clearly an imperfect cadence.
YouTube, timed to bars immediately before cadence
Same video, started a bit earlier
Comment: Thanks for the links. What I found interesting was that even with more context I still thought that it sounded quite stable - though I agree that it is definitely an imperfect cadence. Thanks for your answer!
Comment: Another piece that comes to mind is the ending of the Lacrimosa in Mozart's Requiem in D minor (https://www.youtube.com/watch?v=1u2fCJwW8Ys). I'm not 100% sure but I think it's an imperfect cadence and is in line with what you say about endings of movements in Baroque music (Mozart isn't baroque but you know).
Answer: This kind of cadence was called a "plagal" cadence (versus an "authentic" cadence) in old (19c and early 20c) harmony books and it was very common in the 16th century and still used in the 17th century. Beware however that the progression in modern harmony terms is not I-V, but IV-I. Modern harmony and counterpoint books put this cadences in the context of modes, and classify these cadences as standard endings in the mixolydian mode and the phrygian mode, often added as a "flosculus" ("litte flower") after a different cadence, eg. the chord progression F76 E AM E.
For famous examples, see, e.g., all endings in the Missa Papae Marcelli  (Palestrina), all endings in the Missa Quarti toni (Victoria), or (perhaps the best known example) Aus tiefer Noth (Le Maistre). And for a particular weird example of a phrygian (mode IV) piece ending on a E minor(!) *) chord, see Mille regretz (ascribed in some sources to Josquin). The most bombastic example, however, known to me is the ending of Virgo prudentissima (Isaak), where the notes C and G alternate many times on the text "ut sol" ("like the sun") as a solmization: The effect is overwhelming (which, admittedly, was the precise purpose of the piece).
Whether this is still applicable to a piece utilizing late romantic harmony is a different question, though. To my ears (more used to renaissacne counterpoint than to romantic music), it sounds pretty natural.
*) One might argue that the final third in the cantus could be altered by musica ficta to g#, but this is in contradiction to all extant lute intabulations of the piece, which undeniably end with a minor chord.


Number of solutions of the congruence, $x-y \equiv z \pmod{n}$, where $x,y$ in a set contain less than $n$ and relatively prime to $n$?

Question: I know number of solutions of the congruence,
$$x+y \equiv z \pmod{n},\tag{1}$$ $x,y\in U_{n}$,
is $$N(z)=n\prod_{p\mid n}\left(1-\frac{\varepsilon(p)}{p}\right),$$ where $\varepsilon(p)$ = $\left\{
\begin{array}{l l}
1 & \quad \text{if $p\mid z$}\\
2 & \quad \text{if $p\nmid z$}
\end{array} \right.$
$U_n$ denotes the set of numbers less than $n$ and relatively prime to $n$.
Let $p_{1},p_{2},\cdots ,p_{r}$ be the different prime divisors of $n$, $n=p_{1}^{\alpha_{1}},p_{2}^{\alpha_{2}},\cdots , p_{r}^{\alpha_{r}}$ and $m=p_{1},p_{2},\cdots ,p_{r}$.
If $x$ and $y$ satisfy $(1)$, then $y$ is uniquely determined modulo $n$ bu $x$. So we have find out the number of possible entries for $x$. We partition the interval of integers $[0, n-1]=\{0,1,2,\cdots ,n-1\}$ into the disjoint intervals $I_{k}=[(k-1)m,km-1]$, $k=1,2,3,\cdots , \frac{n}{m}$. By the Chinese Remainder Theorem every integer $x\in I_{k}$ is uniquely determined by its values $x_{i}$ modulo $p_{i},1\leq i\leq r$. i.e. by the congruence $x\equiv x_{i} \mod p_{i},0\leq x_{i}\leq p_{i}-1,1\leq i\leq r$.
$x$in both $I_{k}$ and $U_{n}$, so all $x_{i}$ must be nonzero. There remain $p_{i}-1$ possible choices for $x_{i}$. An additional values for $x_{i}$ has to be ruled out, if $z\equiv z'\mod p_{i},0<z'<p_{i}$. In this case $x_{i}=z'$ would have consequence $y\equiv 0\mod p_{i}$ implying $y\notin U_{n}$. So the number of possible choices for $x$ in both $I_{k}$ and $U_{n}$ to satisfy $(1)$ is $(p_{1}-\varepsilon(p_{1})\cdots (p_{r}-\varepsilon(p_{r})$.
I need to find number of solution of the congruence,
$x-y \equiv z \pmod{n}$, $x,y\in U_{n}$
Comment: MO copy: http://mathoverflow.net/questions/195354/number-of-solutions-of-the-congruence-x-y-equiv-z-pmodn-x-y-in-u-n
Comment: Did you mean to write $\prod_{p\mid n}$ instead of $\prod_{p\backslash n}$?
Comment: yes. $\prod_{p\mid n}$. Please give ans
Answer: $x\in U_{n} \Leftrightarrow n-x\in U_{n}$
So both $x+y\equiv z \pmod{n}, x,y\in U_{n}$ and $x-y\equiv z \pmod{n}, x, y \in U_{n}$, have same number of solutions.


Two dots on toilet paper roll problem

Question: I have an empty toilet paper roll.
-I grab a pencil and draw two dots on the outside of the roll in random places.
-I connect these dots with a straight line, along the shortest path.
-I grab some scissors, and cut the roll vertically (where the holes are on the top and bottom of the roll). The cut is perfectly straight, through a random point on the line.
The line is now severed and I am left with a rectangular piece of cardboard with two dots and now TWO lines instead of one. One line going from dot 1 to its closest edge, and the other going from dot 2 to its closest edge.
If I erase both lines completely, how can I get them back using math?
I know the distance from each dot to their respective edge, as well as the distance from each dot to the top and/or bottom of the now flat, rectangular toilet paper roll.
I need to figure out how to draw a line from each dot, to a point on their edge of the rectangle, so that if I roll it back up into a cylinder again, the line is straight like it was in the beginning.
The distance from the top or bottom of the roll to where each line meets their respective edge should be exactly the same, as these lines were once a single line.
Comment: Whatever you like -- enjoy, bur toilet paper is not my cup of tea.
Comment: From each point drop a perpendicular to the nearest edge. With the erased line, they form two similar triangles. From that, you can reconstruct the erased line.
Answer: You have erased the lie and your figure looks like

Make 2 additional copies of your figure

and connect the dots.

And delete the left and right copies.
Comment: This does not answer the question 'how can I get them back using math?'
Comment: @DanielMathias I disagree.  Applications of symmetry, translation, geometric construction etc. is very much "using math."
Comment: Your answer appears to bypass all of that using the copy/paste tools of image editing. I'll concede that translation is implied, and this is therefore valid.
Answer: Construction using parallel lines:
Comment: @Yimin Other reviewers disagree. Have a nice day.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/2020493)
Comment: @Yimin This most certainly does provide an answer. I believe the construction is quite clear, without need for detailed explanation. What about it do you not understand?
Comment: It is flagged since it is the same as the previous one, showing how to construct it might be better to put in a comment.
Answer:
As the figure shows, you have the two points $A(x_1, y_1)$ and $B(x_2, y2)$, and you know length $L$.
You only need to find $h$ (the distance along the vertical from the bottom).  The condition to be satisfied by the line is that the slope of the two segments is the same.
The first segments extends from $(0, h)$ to $(x_1, y_1)$, and the second segment from $(x_2, y_2)$ to $(L, h)$.  Therefore, we have
$ \dfrac{ y_1 - h }{x_1} = \dfrac{ h - y_2 }{L - x_2} $
Cross multiplying,
$ (L - x_2) (y_1 - h) = x_1 (h - y_2) $
Therefore,
$ h = \dfrac{ x_1 y_2 + (L - x_2) y_1 }{ x_1 + L - x_2 } $
Now you can draw the two line segments.

Two dots on toilet paper roll problem


Was the pitch A given that letter because the minor key was originally the "basic" mode?

Question: It's something that's puzzled me; The key that has no sharps and no flats, in essence the "basic" key, is C Major. Well, fine, but why C? Why not label that key and note A, if it's the foundation of the "basic" key of Western music? A second look, however, shows that A is indeed involved; the minor key with no sharps and flats is A minor.
That then leads to the question; does the pitch named A have that name because it is the start of the minor key, and because the minor key was more prevalent in plain chant as of the creation of written music notation? Or is there another reason?
Comment: possible duplicate of [Why is C the base note of standard notation and keys?](http://music.stackexchange.com/questions/893/why-is-c-the-base-note-of-standard-notation-and-keys)
Comment: Keith, can you comment on whether the quest Luke links addresses this?  I'm not totally sure.
Comment: It is close enough that if I were a mod I'd consider this a dupe. The accepted answer from that question is that the assigning of letters to notes and the development of key signatures were not contemporary developments, and actually, neither were the introduction of Ionian and Aeolian modes. Like most human systems that have been around a sufficiently long time, we simply built and adapted one system atop an older one.
Comment: The succinct answer is that C happened to be the starting note of the latin hymn "Ut queant laxis", which became the "natural" starting note of the hexachordal system used for Gregorian chant. As music theory evolved this remained a standard reference point.
Comment: In fact, A was never the starting point of any key in the hexachordal system until the heptachordal system evolved and all seven modes (including Ionian/major and Aeolian/minor) were introduced.
Comment: I think this is likely the case, but I can't cite a reference. I believe that around the time that music notation came into being that the interval of the major third was considered dissonant, as were major chords.
Comment: Yeah, cause everyone in the middle ages was depressed by default :D
Answer: The lowest note in the Greek scale was Proslambanomenos, an octave below the primary note, Mese.  The eight notes between Proslambanomenos and Mese (inclusive) in the Greek diatonic genus form the A aeolian minor scale.  This is probably why musicians chose to place A, the first letter, on both the lowest and most central note.
By the later Middle Ages, it became common to extend this scale downwards by one note to G, which was written with the Greek letter Gamma.  Since (after the 10th c.) the first note of a scale was called Ut (now Do everywhere except in French string tuning), this note was called Gamma-Ut.  Thus playing the whole scale from lowest to highest involves the whole "gamut" of music.
Comment: Wow, I had no idea that the [etymology of *gamut*](http://etymonline.com/index.php?term=gamut) had this origin!


is it always possible to transform any nth order ODE in a system of n first order ODEs?

Question: I mean, the addition of n-1 variables corresponding to the second, third ... n^th derivative of the original one seems quite straightforward and generic, and I don't see particular caveats... nevertheless most texts I found online say "for most nth order ODEs" or "generically", so I was wondering whether there was any need for a more rigorous proof for complete equivalence or if there are some special cases for which this equivalence does not fully hold.
Also, a counterexample would be particularly helpful.
I have an engineering background hence a practical approach to math and I am not used to "traps" or corner cases.
Thanks all! this is my first question over here so please be merciful
Answer: An $n$th order ODE is an equation of the form
$$
f(x,y,y', \ldots, y^{(n)}) = 0
$$
Now, the fact that the ODE is $n$th order means that $f$ must actually depend on $y^{(n)}$.
Now, suppose that $f$ is $C^1$. The fact that $f$ depends on $y^{(n)}$ means
$$
\frac{\partial f}{\partial y^{(n)}} \neq 0
$$
By the implicit function theorem, there exists a $C^1$ function $g$ such that
$$
f(x, y, y', \ldots , g(x, y, y', \ldots, y^{(n - 1)})) = 0
$$
Informally, this means $y^{(n)} = g(x, y, y', \ldots, y^{(n - 1)}$. Even more informally, we can say that $y^{(n)}$ depends only on $x, y, y', \ldots, y^{(n-1)}$.
Now, define $z_0 = y$, $z_{k} = y^{(k)}$ for $1 \leq k \leq n - 1$, and let $z_n = g(x,y, y' , \ldots, y^{(n - 1)})$.
Then we have the $n$ first order equations: $z_{k - 1}' = z_{k}$ for $1 \leq k \leq n - 1$ and $z_{n-1}' = g(x,z_0, z_1 , \ldots, z_{n - 1})$.
You can check that $f(x,y,y', \ldots, y^{(n)}) = 0$ if and only if the $n$ first order $z$ equations are satisfied.
To summarize, if the $z$ equations are satisfied, then we'll have $f(x, z_0, \ldots, z_n) = 0$ by construction. If the $y$ equation is satisfied, then we can apply the implicit function theorem to solve for $y_n$, define $z_k = y^{(k)}$, and form the $n$ first order equations relating the $z_k$.
Comment: To be more careful, we are only allowed to use the implicit function theorem if we know $f(\ldots) = 0$ is true for some point in $\mathbb{R}^{n + 1}$ and, at that point, the partial derivative of $f$ with respect to $y^{(n)}$ doesn't vanish.
Answer: It is as you say completely straightforward. The point is that it is equivalent to consider an $n$-th order ODE on say $\mathbb R$, or a first order ODE on $\mathbb R^n$.
But there are differences between a first order ODE on $\mathbb R$ and eg a first order ODE on $\mathbb R^3$. For instance, you cannot have periodic trajectories in dimension one, you need at least two dimensions. More complicated phenomena also only appear in dimension starting from 3.
Comment: thanks! I did not understand the point related to periodicity. can't we take the solutions of $\dot y = \sin t$ as example of periodic, yet single dimensional, orbits?
Comment: I mean autonomous ODEs. Non autonomous ODEs can also always be written as autonomous ODEs in more variable
Comment: thanks again. you mean by introducing a new variable $x_{N+1}$ and a new equation $\dot x_{N+1} = 1$ and replacing all occurrencies of $t$ with $x_{N+1}$? do you have any references that discuss the physical insights, if any, of this additional dimension? seems like we are modeling a changing velocity vector field as "slices" stack one onto the other and we are forcing the orbit to traverse these slices as time goes by...


How can I prove that I can assume $\sin{x}, \tan{x}$ to be x when $x \rightarrow 0$

Question: I know the proof of $\lim_{x\rightarrow 0}{\frac{\sin{x}}{x}}=1$ and $\lim_{x\rightarrow 0}{\frac{\tan{x}}{x}}=1$.
However, I do not think that this means that I can change every  $\sin{x}$ and $\tan{x}$ inside a limit to x and solve the problem, because the rule of limits can only be apllied if both limits exist, and it also does not mention anything about composite functions (for example $\sin{(\sin{(x)})}$)
Is it possible to prove that every $\sin(x)$ and $\tan(x)$ can be canged into x no matter its location if $x\rightarrow 0$ Without Taylor Expansion
Comment: Those limits in your question do not tell you that $\sin x$ etc can be replaced by $x$ but they rather tell you that $\lim_{x\to 0}\dfrac{\sin x} {x} $ can be replaced by $1$. You should understand that this is fundamentally different from assuming $\dfrac{\sin x} {x} =1$. Also the genesis of such ideas (that limit equations should imply or justify the replacement of $\sin x$ by $x$) is totally mysterious for me.
Answer: It can't be proven, because it's not true. For example:
$$\lim_{x \to 0} \frac{x-\sin(x)}{x^3}=\frac{1}{6}$$
While
$$\lim_{x \to 0} \frac{x-x}{x^3}=\lim_{x \to 0} \frac{0}{x^3}=0$$
Answer: See Taylor expansion of these functions : you can say that near $0$, they "look like" a polynomial and control the difference.
For example, $\sin x = x + x\cdot \varepsilon(x)$ where $\varepsilon$ is a continuous function of $x$ vanishing at $0$.
Comment: Actually we haven't learned taylor expansion yet, so I need an alternative solution. Edited question.
Comment: Did you learn about the equivalence $f$ is differentiable at $x$ and $f'(x) = a \iff \exists \varepsilon$ continuous and vanishing at $0$ and $a \in \mathbb{R}$ such that $f(x+h) =f(x) +  a(x+h) + x\varepsilon(h)$ ?


problemas com bindValue

Question:     $query = "INSERT INTO
                " . $this->table_name . "
            (data, sexo)
            VALUES
            (:data,:sexo)";

    $stmt->bindValue(':data', $_REQUEST['data']);
    $stmt->bindValue(':sexo', $_REQUEST['sexo']);

está dando um erro: Undefined index: sexo.
o campo sexo é um radio button e eu não selecionei ele antes de salvar no banco.
se eu selecionar o campo sexo, os dados são salvos normalmente no banco, por que?
queria salvar mesmo se o campo estiver selecionado ou não...
Comment: Bom, o erro é claro e você pareceu entender o motivo. Você está tentando pegar uma informação que não existe, por isso o undefined. Tente verificar se o campo existe com um `if(isset($REQUEST_['campo']))` antes de inserir, se não existir, vc toma uma decisão, como salvar o campo como null ou 0, dependendo de como está a coluna no banco. Leia mais sobre [isset()](http://php.net/manual/pt_BR/function.isset.php)
Answer: São salvos porque quando você seleciona o campo do tipo radio e envia o POST ao resgatar pela global $_REQUEST este index irá existir.
Quando você não seleciona ele não envia este index: O motivo do erro.
se você quer salvar mesmo sem selecionar coloque um valor como default para salvar no banco. Exemplo:
debug para ferificar os index recebidos pelo formulário
print_r($_REQUEST);
evitar erro de index inexistente
if (!isset($_REQUEST['sexo'])) {
   $sexo = 'seu valor';
}

problemas com bindValue


Pushing array into array then handling elements inside

Question: so I just came across this, but could anyone explain it to me, why is this phenomenon present here? I didn't find any help online...
1.So if I were to get the following two arrays:
let a = [];
let b = ['','',''];

2.and then push array b into array a three times:
a.push(b);
a.push(b);
a.push(b);

3.but then when I try to change the first element of the first array like so:
a[0][0] = 'foo';

4.then all the first element of ALL the arrays change, not just the first one, as console.log(a) outputs:
(3) [Array(3), Array(3), Array(3)]
0: Array(3)
  0: "foo"
  1: ""
  2: ""

1: Array(3)
  0: "foo"
  1: ""
  2: ""

2: Array(3)
  0: "foo"
  1: ""
  2: ""

I would like to ask, why does this happen and in what way could I change an element based on its index inside of array a
Comment: The indices in `a` are all holding a *reference* to `b` -- "they all get updated" is a bit misleading, you're updating one object and it appears in multiple places.
Answer: b is a pointer to a mutable array, changing the array it points to will cause the other places you point to it to update as well.
You would either push copies of b into the array or create a modified copy of b when trying to mutate the value it points to.
Answer: Because you're passing b which is just a reference to an object. To have the behavior you want, change your code to be like this:
a.push(b.map((x) => x))

For more see this page.
Answer: if you console.log(b), you'll see that as well.
Try doing b[1] = "test" then check the value of a and you'll see all the b's that were pushed into there have test in them too.
b is a reference so anytime you change the value of it, you are altering the places it is referenced to.


How to use THIS with OOP javascript?

Question: I am new to OOP in JavaScript, just trying to do some stuff the same way I would i PHP. In the example below I can't use the THIS keyword to generically call the method getMyWeekDay() of the class Screen, what I have to do in my prototype function is to call a specific instance of my "Screen" class (namely my instance called "screen") which kind of ruins the purpose a little bit...
I guess I just made a newbie mistake in my design?
//Our screen object
function Screen() {}

//update the clock element on the screen
Screen.prototype.updateClock = function(date) {
    //do some stuff
    $('#dateContainer').html(screen.getMyWeekDay(date)+' '+date);
    //Here I would prefer    $('#dateContainer').html(this.getMyWeekDay(date)+' '+date);
}

//return the day name in swedish
Screen.prototype.getMyWeekDay = function(d) {
    var d=new Date(d);
    var weekday=new Array(7);
    weekday[0]="Söndag";
    weekday[1]="Måndag";
    weekday[2]="Tisdag";
    weekday[3]="Onsdag";
    weekday[4]="Torsdag";
    weekday[5]="Fredag";
    weekday[6]="Lördag";
    var n = weekday[d.getDay()];
    return n;
}

screen = new Screen();

//use the new instance (screen) of class Screen

-- UPDATE --
I realize my problem might have been outside of the code I shared, using the solution suggested worked though.
Here is my entire code, I was just trying to spare you a bunch of what I considered unneccessary reading...
Screen.prototype.updateClock = function() {

    var jqxhr = $.get('{{ path('getClock') }}')
      .success(function(data) {
            time = data.substring(data.indexOf("|")+1, data.indexOf("|")+6);
            date = data.substring(0, data.indexOf("|"));

            $('#timeContainer').html(time);

            try{
                //see if template has its own function for date rendering...
                template_date_format(getMyWeekDay(date),date);
            }
            catch(e) {
                //standard fallback if not
                $('#dateContainer').html(this.getMyWeekDay(date)+' '+date);
            }
       })
      .error(function() {
            console.log('there was an error fetching clock data');
      });
            setTimeout(function() {
              updateClock();
            }, 15000);

}

Comment: Here is a good introduction from MDN for OOP in JS: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Comment: Ok.. there was an answer here a minute ago that totally works, but when I went to check it as the solution it had been deleted.. whoever you postee are, was there a problem with the code you posted?
Comment: There is no reason using `this.getMyWeekDay()` shouldn't work. Do you get any error?
Comment: dcodesmith are you the one posting that answer? Anyways, my own answer below builds on the "save a reference to the THIS" that someone here just taught me. Have a look below, you'll propably see why calling THIS where I did didn't work.
Comment: More on how to use constructor functions and what `this` exactly is here: http://stackoverflow.com/a/16063711/1641941
Answer: Screen.prototype.updateClock = function() {

var oopThis = this;

var jqxhr = $.get('{{ path('getClock') }}')
    .success(function(data) {

        // the log line below will return an object which contains the ajax calls options
        console.log(this);

        time = data.substring(data.indexOf("|")+1, data.indexOf("|")+6);
        date = data.substring(0, data.indexOf("|"));

        $('#timeContainer').html(time);

        try {
            //see if template has its own function for date rendering...
            template_date_format(getMyWeekDay(date),date);
        } catch(e) {
            //standard fallback if not
            $('#dateContainer').html(oopThis.getMyWeekDay(date)+' '+date);
        }
    })
    .error(function() {
        console.log('there was an error fetching clock data');
    });

    setTimeout(function() {
        oopThis.updateClock();
    }, 15000);
}

OK. Based on your code above this in the context of an ajax/get/post function refers to the ajax object which contains its options.
BTW, The common convention is to do var self = this;

How to use THIS with OOP javascript?


Qual o motivo de se usar "super()" antes de se criar as variáveis da classe filha?

Question: Encontrei esta questão que fala quase do mesmo assunto porém o foco dela é sobre acesso a métodos da classe pai. E minha dúvida é saber qual o motivo do uso de super() antes da declaração de variáveis na classe filha, como no exemplo abaixo:
class List{

 constructor(){
   this.data = [];
 }

 add(data){
  this.data.push(data);
 }
 showdata(){
   console.log(this.data);
 }
}

class TodoList extends List{

   constructor(){

      //qual a finalidade deste super para a criação de variáveis na classe filha ?
      super();
      this.owner = "John";
   }

  showmeowner(){

    console.log(this.owner);

  }

}

const MyList = new TodoList();

Se eu retiro o super() do construtor da classe TodoList o navegador me retorna o seguinte erro:
Uncaught TypeError: Cannot set property 'owner' of undefined
    at new TodoList (bundle.js:54)
    at bundle.js:68
Como a propriedade owner pode estar como undefinedse ela está no construtor da classe TodoList? Porque o super()é necessário nesta situação ?
Answer: Em resumo tecnicamente:

Quando uma função regular é executada com new, ela cria um objeto
vazio e o atribui a this.
Mas quando um construtor derivado (Herdado) é executado, ele não
    faz isso. Ele espera que o construtor pai faça esse trabalho.

Em outras palavras é uma especificação da linguagem.
Entre neste site: https://javascript.info/class-inheritance e procure por este título: 'Overriding constructor'. É mais detalhado e técnico. Se você quiser é um ótimo site para aprender javascript moderno.


C# write graph to coordinate-system

Question: There are millions of data in my SQL DB and every Row is a Item with a Starttime and a duration. Now I want to visualize this Data to know which Data overlap at a time.
My idea is to create a coordinate-system with x-axis show the time and y-axis count the Item. Every graph is a line parallel to the x-axis start at Starttime + duration. The next graph is y+1 and also Starttime + Duration. Then I can see which Items overlap at which time.
How can I program that with C# any suggestion to solve this problem?
Comment: Can you draw your idea for better understanding?
Answer: I think you should take a look in the various chart controls out there:

Microsoft
Dundas
Nevron
whatever you find on the net

All of these support some kind of bar chart which could visualize this kind of data. But be aware that displaying can take a lot of time if you try to put millions of data points at a chart at once.
If high performance and mass of data is your constraint you should maybe take a look at one of these:

Lightning Chart
Measurement Studio
Dynamic Data Display
whatever you find on the net
Comment: thx for your answer, is any Framework optimized for high performance?

C# write graph to coordinate-system


Comparar Hash de dois arquivos em Python

Question: Preciso comparar o hash dos arquivos a.txt e b.txt usando uma biblioteca nativa do python3.
Tentei fazer assim:
import hashlib

file_0 = 'a.txt'
file_1 = 'b.txt'

hash_0 = hashlib.new('ripemd160')
hash_0.update(file_0)
hash_1 = hashlib.new('ripemd160')
hash_1.update(file_1)

assert hash_0 != hash_1, f'O arquivo: {file_0} é diferente do arquivo: {file_1} '

Mas ocorreu o seguinte erro:
TypeError: Unicode-objects must be encoded before hashing

Obs: Antes de editar cometi o erro de por duas variáveis file_0. No projeto estava correto.
Comment: Você precisa comparar os conteúdos dos arquivos ou os nomes deles apenas? Da forma que está fazendo você comparará apenas os nomes. O método `update` aceita apenas *bytes-like* como parâmetro, então precisará codificar a sua *string* com o método `encode`.
Comment: Preciso comparar o conteúdo do arquivo. Vou continuar pesquisando e encontrar como comparo o conteúdo. Obrigado.
Answer: Primeiro - você está comparando os nomes dos arquivos - a chamada a update nas classes da Hashlib não abre arquivos sozinha - ela espera objetos do tipo "bytes" (e esse é o motivo da mensagem de erro, você esta passando texto) - mas mesmo que você ponha o prefixo b' nessas strings de nome, ou use .encode() nas mesmas, vai continuar fazendo o hash só do nome dos arquivos. (Outro erro: você usou duas vezes o mesmo nome de variável - se estivesse abrindo os arquivos, iria estar comparando o arquivo "b.txt" com ele mesmo)
Para ver o hash do conteúdo dos arquivos faça:
import hashlib

file_0 = 'a.txt'
file_1 = 'b.txt'

hash_0 = hashlib.new('ripemd160')
hash_0.update(open(file_0, 'rb').read())

hash_1 = hashlib.new('ripemd160')
hash_1.update(open(file_1, 'rb').read())

if hash_0.digest() != hash_1.digest():
    print(f'O arquivo: {file_0} é diferente do arquivo: {file_1} ')

(você também estava usando o assert de forma errada. Evite usar o  assert em código mesmo - e reserve esse comando para testes.
Apesar de parecer um encurtamento de um  if seguido de um  raise em alguns lugares, ele é um teste que é desabilitado dependendo dos parâmetros com que o runtime do Python é executado - então, tem muito desenvolvedor aí colocando assert em código de produção que mais dia menos dia pode se encrencar, com um teste que não é feito, por conta de uma configuração aparentemente inócua alterada em outro lugar)
Comment: Perdoe a ignorância, mas não seria melhor os arquivos serem abertos para leitura ao invés de escrita? Usando `rb` ao invés de `wb`?
Comment: Isso -deveria ter sido "rb" - está errado aí - vou alterar.
Answer: Para comparar usando hashlib pode ser feito assim:
import hashlib

def open_txt(file):
    with open(file) as f:
        return "".join(f.read())

file_1 = 'a.txt'
file_2 = 'b.txt'
text_1 = open_txt(file_1)
text_2 = open_txt(file_2)

def compare(text_1, text_2):
    hash_1 = hashlib.md5()
    hash_1.update(text_1.encode('utf-8'))
    hash_1 = hash_1.hexdigest()

    hash_2 = hashlib.md5()
    hash_2.update(text_2.encode('utf-8'))
    hash_2 = hash_2.hexdigest()

    assert hash_1 == hash_2, f'O arquivo: {file_1} é diferente do arquivo: {file_2} '

compare(text_1, text_2)

Porém acho mais prático e rápido usar filecmp que compara byte a byte.
import filecmp
filecmp.cmp('a.txt', 'b.txt')


How to get key from Hive box object and map it to specific field of the object?

Question: The box is auto-incrementing.
Let's say that I have an object like so:
@HiveType(...)
class Dummy {

  @HiveField(0)
  int id;

  @HiveField(1)
  String name;

}

I want Hive deserialization to map the Dummy object's key to id field.
Answer: If you inherit your class from HiveObject, then you can use built in property 'key'.
    @HiveType(...)
    class Dummy extends HiveObject{
      //id not needed anymore

      @HiveField(0)
      String name;

    }

    ...

    Box<Dummy> db = Hive.box<Dummy>('dummy');
    Dummy dummy = Dummy(name: "some text");
    db.add(dummy); //add assigns next integer as key

    //after storing object to a database, you can access its key using 'key' property
    int id = dummy.key;

    //another advantage of extending HiveObject, is that you can store or delete object from the database without accessing the box:
    dummy.name = "other text";
    dummy.save(); //put modified object into box
    dummy.delete(); //delete object from the database

Comment: The reply is much appreciated. I've switched to SQLite. I hope this helps someone else.
Answer: How about
db.put(dummy.id, dummy);


Taking the derivative of square root of y by squaring the equation instead of using implicit differentiation

Question: For an equation like:
$$
\sqrt{y}+\sqrt{x}=1
$$
Why can't I isolate the "square root of $y$" and then raise both sides of the equation by the power of $2$? That will get $y$ outside of the radical, but for some reason the result is not the same as with using implicit differentiation. Why is that?
Answer: With implicit differentiation we get
$$
\frac{y'}{2\sqrt{y}}+\frac{1}{2\sqrt{x}}=0
$$
so
$$
y'=-\frac{\sqrt{y}}{\sqrt{x}}=\frac{\sqrt{x}-1}{\sqrt{x}}=1-\frac{1}{\sqrt{x}}
$$
By doing $y=(1-\sqrt{x})^2=1-2\sqrt{x}+x$
we get
$$
y'=-\frac{1}{\sqrt{x}}+1
$$
as before.
Comment: Oh, so it's just a matter of algebra manipulation :|
Thank you!!


Capturar elemento de array javascript

Question: Olá, como posso capturar o nome maria do id 2?
listform: [
  {
    id: "1",
    nome: "juana"
  },
  {
    id: "2"
    nome: "maria"
  },
  {
    id: "3"
    nome: "carlos"
  }
]

Comment: Você quer fazer a busca pelo `id` ou pelo `nome`?
Comment: @Marconi quero recuperar só os segundos valores do meio que no caso é o id 2 e o nome maria
Comment: Não tenho certeza se entendi mas pode fazer um loop na lista e retornar o objeto (ou uma propriedade dele) cujo id/nome seja o desejado
Comment: Josimara, gostaria de saber se a minha resposta tem ajudado você
Answer: No seu código o array está sendo definido incorretamente, a atribuição é com = e estão faltando algumas vírgulas.
Caso você saiba a posição do objeto, poderá capturar facilmente com listform[1].nome, julgando que a posição começa no 0, maria está no objeto de posição 1, exemplo.

let listform = [
  {
    id: "1",
    nome: "juana"
  },
  {
    id: "2",
    nome: "maria"
  },
  {
    id: "3",
    nome: "carlos"
  }
];

console.log(listform[1].nome);

Caso queira pegar o nome maria baseado no seu id 2, basta usar a propriedade indexOf juntamente com um looping, exemplo...
map

let listform = [
  {
    id: "1",
    nome: "juana"
  },
  {
    id: "2",
    nome: "maria"
  },
  {
    id: "3",
    nome: "carlos"
  }
];

key = listform.map(function(e) { return e.id; }).indexOf('2');

if(key != -1)
    console.log(listform[key].nome)
else
    console.log('Não foi possível encontrar o id')

Caso você queira um suporte maior entre os browsers, basta adaptar o método para um looping mais simples.
Answer: Uma das formas mais diretas de obter o resultado que quer é utilizando find que lhe permite passar uma função com a busca que pretende fazer e devolve o primeiro elemento que seja válido para essa busca. No seu caso tem de efetuar a busca através do id:
let pessoa = listform.find(p => p.id === "2");

Veja a funcionar:

const listform = [
  {
    id: "1",
    nome: "juana"
  },
  {
    id: "2",
    nome: "maria"
  },
  {
    id: "3",
    nome: "carlos"
  }
];

let pessoa = listform.find(p => p.id === "2");
console.log(pessoa.nome);

É importante mencionar que neste momento o find não é suportado no antigo Internet Explorer no entanto a própria página da documentação tem o polyfill que pode utilizar se precisar desse suporte.
Answer: Olá, tudo bem?!
Quando falamos sobre Array, podemos tratar sobre arrays unidimensionais e multidimensionais...
Um array unidimensional é um array que contém "apenas um nível de índices", por exemplo:
//Criando um array unidimensional
var meu_array = new Array();
meu_array[0] = 'Hello World';
meu_array

Note que na imagem acima o 0 circulado é referente ao indice unidimencional (temos apenas um indice para cada "espaço" no array e mais nenhum ligado à ele.
Já um array multidimensional é um array que contém outros arrays dentro dele, por exemplo:
// Criando um array multidimensional
var meu_array = new Array();
meu_array[0] = new Array("id:1","nome:juana");
meu_array[1] = new Array("id:2","nome:maria");
meu_array[2] = new Array("id:3","nome:carlos");
meu_array

Note que na imagem acima, o índice 0 está apontando para mais (2) indices, ou seja, além
cada de "espaço" no índice primario do array, temos mais 2 "espaços" no índice secundário.
Lembrando que a contagem de índices para Arrays começam sempre do número 0 em ordem crescente.
O listform
do qual você está utilizando se enquadra no tipo de array multidimensional:
Então, capturar apenas no nome "maria" do índice 1, podemos utilizar o seguinte código:
 meu_array[1][1]

Espero ter ajudado!

Capturar elemento de array javascript


Background is changing in Mouse_Leave but not in Mouse_Enter

Question: I am just getting into WPF. I have two event handlers:
private void Mouse_Enter(object sender, MouseEventArgs e)
{
    ((Button)sender).Background = Brushes.Red;
}
private void Mouse_Leave(object sender, MouseEventArgs e)
{
    ((Button)sender).Background = Brushes.Black;
}

When the mouse enters the button's area, nothing happens. However, when leaving the button's area, the button does go black. I have put a breakpoint inside Mouse_Enter and it is definitely executing the method, just doesn't change the background color.
How to fix it? Thanks!
Comment: If it doesn't need to be in the c# code and can be in the XAML i suggest looking at [this answer](https://stackoverflow.com/questions/20073294/change-color-of-button-when-mouse-is-over)
Comment: Does your button change color to the default "button hover" color when your mouse enters?
Comment: @Fleury26 Yes, it does.
Comment: There is a lot more to re-styling a button than just overriding the background color. The default template can be found [here on msdn](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/button-styles-and-templates)
Answer: This is happening because there is a "built-in" trigger in the default button template that's causing the button to ignore your attempts to change it's background on a MouseEnter event, you will need to edit the template and disable the trigger first, follow these steps:
In the Visual Studio editor right click on your button and pick "Edit Template" then "Edit a Copy..." name your style whatever you want and look through the XAML for a trigger called "IsMouseOver" and delete the 2 lines below.
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsDefaulted" Value="true">
                            <Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                        </Trigger>
                        <Trigger Property="IsMouseOver" Value="true">
    --- Delete this line    <Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
    --- Delete this line    <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
                        </Trigger>
                        <Trigger Property="IsPressed" Value="true">

Comment: Thanks a lot, but I really want to do it using code-behind. Not for production purposes of course, but just for learning. Could you please explain how would I fix it without using XAML triggers? Thanks again!


Is World XI a full member of ICC

Question: Is World XI team a full member of ICC like Australia, South Africa? Is its match considered international or domestic? Would the wickets,catches,runs etc scored by a player in World XI team be included in its international career or not?
Answer: ICC members are made up of governing bodies, not teams. Therefore the World XI, which was a team directly organised by the ICC, is not an ICC member itself.
However, the matches were given ODI and Test status. They therefore do count towards official international records, and individual player statistics.

Is World XI a full member of ICC


why $ f(x,y) =-g(x,y)?$

Question: I have  some confusion in Apostol  calculas book Page no $: 369$
Books Pdf link : https://www.academia.edu/4744309/Apostol_-_
My confusion is  marked  in red circle ,given below

why $ f(x,y)  =-g(x,y)?$
why negative  sign come ?
Comment: The ellipsoid has two parts: one with $z>0$ and one with $z<0$.
Answer: Let $(x,y) \in S$. Let $E$ be the solid in question. Then:
$$(x,y,z) \in E \iff \frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2} \le 1 \iff z^2 \le g(x,y)^2 \iff |z| \le g(x,y) \iff -g(x,y) \le z \le g(x,y).$$

why $ f(x,y) =-g(x,y)?$


Field available only when a value from a Hierarchical Select is chosen

Question: I am using the Hierarchical Select module to allow users to first select a continent and then a country. I wish to enable a field only when a user selects North America (first selection) and USA (second selection).
I hope someone could explain how I achieve this.
Comment: Have a look at [#states](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#states). Quick tutorial: http://randyfay.com/states
Example: http://d7.drupalexamples.info/examples/form_example/states
Answer: I created a module that implemented the node_validate function and from the values selected determined if child taxonomies existed when the form was submitted. If they did then obviously the user had not made a selection from the second drop down list.
This is the code I wrote.
<code>function mp_admin_node_validate($node, $form, &$form_state) {
    if ($form["#form_id"]=="jobs_node_form") {
        $loc = taxonomy_get_children( $node->field_tax_regions[und][0][tid]);
        if ((count($loc)>0) && ($loc)) {
            form_set_error("field_tax_regions", t('Location region is required.'));
        }
    }
}
</code>


Como posso verificar se todas as textbox estão vazias?

Question: Código:
if (string.IsNullOrWhiteSpace(txtNumero.Text) && string.IsNullOrWhiteSpace(txtTitle.Text))
{
    MessageBox.Show("Preencha todas as informações");
}

Tentei fazer com && e não funciona, como posso fazer? Quero verificar duas ou mais textboxs
Comment: `&&` quer dizer que as duas tem que estar vazias, se uma só estiver, não entra no seu `if`, troque para `||`
Comment: Ah era coisa boba haha, obrigado.
Answer: Se deseja verificar todos os textBoxes a melhor forma e criar um método dinâmico(imagine uma tela de cadastro onde tiver uma grande quantidade de textBoxes)
private bool textBoxVazias()
{
   foreach (Control c in this.Controls)
      if (c is TextBox)
      {
         TextBox textBox = c as TextBox;
         if (string.IsNullOrWhiteSpace(textBox.Text))
            return true;
      }
    return false;
}

Apos criar o método, basta chama-lo e caso o retorno for positivo, algum textBox esta vazio.
if(textBoxVazias()) MessageBox.Show("Preencha todas as informações");

Caso ainda prefira especificar os campos, ou se eles forem poucos como em seu exemplo, basta utilizar || (ou) ao invés de && (e)
if (string.IsNullOrWhiteSpace(txtNumero.Text) || string.IsNullOrWhiteSpace(txtTitle.Text))
    MessageBox.Show("Preencha todas as informações");


What's the difference between landing pages and panel pages?

Question: I'm trying to create pages (like 'Questions', 'Tags'... on top of this website). I thought the best way to do this is to use the Panels module. The Panels module has two types of pages: landing pages and panel pages.
What's the difference between them and which one's the best to create static pages?
Answer: I do not see much difference between both, in fact landing page itself a panel page.The only difference I can say is there might be predefined pages like user profile, node template that we can override using panels and thus making them a panel page while landing page is pretty much same as a node with a url to navigate and contents with various ways might be static text, embedded blocks and much more.
Panels should be never be considered as a tool to build static pages as they are resource intensive,instead use nodes for that purpose.There are many reasons why node is preferred instead of panels like node being entity has attached attributes like author, created time, revisions, also there is long list of node api which allows you to hook into node edit/insert/view processes.
Answer: panel page mainly use for to create home page, there is a option to check(tick) the check box and option are also there to be.
but in
landing page is similar to panel page,but here is no option of setting the front page.


Advice needed on migrating shares from a 2003 DC to a new 2012: how can I avoid breaking my software install GPOs?

Question: I've finally virtualized our entire server infrastructure and I'm ready to start migrating to our bought Windows server 2019. Since our current setup is based on Windows Server 2003 we obviously have to do the migration step via an interim installation of say 2012 R2 (AFAIK 2016 would be ok too).
My problem is the following. Our 2003 DC hosts a number of file shares. Some of them are very easy to copy over to the 2019 installation and simply change my existing GPOs to refer to the 2019 server name, instead of the 2003.
My problem resides with certain software install GPOs, for which the relevant MSI install packages do not reside on the SYSVOL, but on a share accessible as \\srv2003\installers. Obviously this will end up as \\srv2019\installers\ but how does one go from one to another? If I "modify" our GPO installation tasks to refer to the new installation paths I'll produce an installation storm over all our clients...
Can you offer any advice on how I can accomplish this task? And possibly a better way to have our GPO msi's ready for installation (in SYSVOL perhaps instead of a different share)?
EDIT: Since my question was closed and to avoid cluttering the OP with the why it should be re-opened, do check my explanation as to why this should stay around.
Answer: Since this upgrade involves an interim installation of Windows Server 2012R2 I've thought of a possible path. The caveat is that there are no margins of error whatsoever, since the entire procedure should be performed in one step. Therefore, planning should be taken to, for example, accomodate the change to DFS-R. And this entire procedure should be performed during off-hours.
Assume the current AD servers are srv1 and srv2 (Windows Server 2003R2) and that the former provides a share with the purpose of GPO-based software installation.
First backup the shares somewhere. Then introduce two (and not one, since if things go sideways we're doomed) Windows 2012R2 servers into the domain. Avoid using Server 2016 for this step, I believe it has stopped supporting FRS.
Move roles and do whatever is needed to promote one of the two new servers, transfer roles etc and then demote srv1 and srv2. Remove both 2k3 servers from the domain. Raise functional level to 2008 R2 (for example), replace FRS with DFS. Finally make two new 2019 server installations, taking care to:

name the first with the name of the first old 2k3 server, that is srv1, and the second server as srv2
configure the ip addresses of these two new servers to correspond to the old ones (optional step, but I'd do it just in case)

Redo the migrate path, this time from the temp servers to the new srv1 and srv2 and finally demote/remove the interim servers. Re-create shares on srv1 and populate them.
Not a super clean solution, but it will allow me to keep my install GPOs without any name-changing/re-installations.
EDIT: I've just finished this procedure. It worked flawlessly, with new client systems downloading GPO install packages. Everyone's happy!
Answer: The first important thing to note: it is highly recommended to not use any server roles on domain controllers except for "DNS Server" and "Active Directory Domain Services".
If you were migrating from a 2003 File Server to a 2019 File Server, I would recommend using the storage migration wizard that is included with Windows Server 2019. It helps with migrating the shares and can also redirect users to the new server after the cutover from the original file server. In this case, I don't think that approach can be recommended (migrating from a domain controller).
My first inclination was to put both of these as comments instead of an answer, but at this time, it would really be the "right" solution to build a file server, copy the installation files to a new share on it (you can even use the same share name), and then edit the GPOs to replace the DC name with the new file server name in the UNC of the installer.
Comment: Since my domain is at a 2003 functional level, I can think of two: the ***minimum*** functional level for a Server 2019 is the server 2008 functional level which, alone, would prohibit joining a 2019 server to this domain. Hence one has to join a 2008/2012/2016 server and after moving roles and demoting the 2k3 servers he would raise the functional level and only afterwards he would introduce 2019 servers. The other reason is that 2019 uses DFS-R [link](https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/active-directory-functional-levels)
Comment: Unfortunately I lack the $$$ (EDIT: and time to tender a purchase procedure) to purchase another 2019 server (as it is I've got two, to replace the two 2k3 servers). I'll go to 2019 gradually, but using a 2012R2 trial as an intermediate step. My bottomline is that unfortunately I'll have to actually attach a file server role to one of my DCs. Now, I do not know if 2012R2 offers a similar share migration. Considering my constraints, would you believe that migrating from the 2k3 file server to a 2012 **file** server is viable and possibly recommended?
Comment: Furthermore, would your last sentence indicate that it would be feasible to somehow magically modify my install GPOs to point to the new UNC without causing a re-install/redeploy storm?
Comment: You could certainly use a 2012R2 trial as an intermediate step--but for that matter, you could also use a 2019 trial as an even better intermediate step! You'll get more file server features, better security, and potentially a better running server. Any reason to use 2012R2 in particular? (I can't think of one.)
Comment: Your second question is an insightful one, and something that you'd want to test and/or check documentation about. Worth testing with one (or a few) for sure.
Comment: Great points! It has been quite a while since I've had to consider 2003.
Answer: I agree with SturdyErde that you should avoid having file shares on your DC, but I migrated my company off SBS08 a couple of years ago, and do understand that sometimes it is what it is. A high level description of my suggested upgrade path is:

Add the 2012 R2 server to the domain as a domain controller
Mirror your shares
Decommission srv2003
Add your 2019 server to the domain
Create a DNS alias of srv2003 that points at srv2019
Promote 2019

There will be raising the functional domain level steps in there, but the main point is to make a DNS alias of srv2003 to point at the new shares as soon as you decommission the old server.
I also agree with SturdyErde that you should look at the storage migration wizard. I believe there's an option that renames the new server with the old server's name, but am a little nervous at the idea of doing that with a DC.
Good luck!
Answer: I don't know a clean solution to your current problem. But I can offer you a hint for the future:
Use a specific name for this purpose like install.your.domain and set a DNS record to srv2019 with this name. Next time you move your install share just change this DNS record.
For your current problem something like this might be considerable:

Make sure srv2003 is only used for this share anymore.
Mirror the share to srv2019
Change the DNS record for srv2003 to the IP of srv2019.
Decommission srv2003
Make new GPOs for fresh installed Clients and new software, use the specific name mentioned above here

As old clients get replaced or completely set up new, the usage of your old GPO reduces until it can be deleted at some point.
Comment: OP is likely to have unexpected future results if changing an old domain controller's A record to be a CNAME for a file server.
Comment: @carmik fyi; to make that work you need to play with the registry DisableStrictNameChecking for the LanmanService
Comment: First, a clarification: as I've noted in the OP I'll be using Server 2012R2 as an interim step, since a direct migration of my 2003-based AD to 2019 is not possible for a variety of reasons. I **believe** I have tried adding a CNAME pointing to the actual A address record of my current 2k3 server, but connection to the CNAME fails. I believe the SMB internals do not like connecting to a well known ip address with another name.
Comment: You would need to demote the FSMO roles from srv2003, take it out of the domain and then add the CNAME.
Comment: @yagmoth555 I didn't know about that. And a quick search brought up this [technet article](https://docs.microsoft.com/en-us/troubleshoot/windows-server/networking/dns-cname-alias-cannot-access-smb-file-server-share). Will test and report back.


A function $p \in C^2\big([0,R),\mathbb{R}\big)$ satisfies $p(x) ≥ \alpha$ and $(1 + \beta)[p'(x)]^2\leq p''(x)p(x).$

Question: The following is exercise IV.3.1. from Analysis I by Amann and Escher.

Suppose that $\alpha, \beta, R > 0$ and $p \in C^2\big([0,R),\mathbb{R}\big)$ satisfy $p(x) ≥ \alpha$ and $$(1 + \beta)[p'(x)]^2\leq p''(x)p(x),\quad x\geq0.$$ Show that $R < \infty$ and $p(x)\to\infty$ as $x\to R−$. (Hint: The function $p^{-\beta}$ is concave. Use a tangent line to $p^{-\beta}$ to provide a lower bound for $p$ (see Application 3.9(e)).

I think I found a counterexample. Let $\alpha:=\beta:=1$ and $p:[0,\infty)\to\mathbb{R}$ with $$p(x):=\frac{x+2}{x+1},\quad x\geq0.$$ Then $p'(x)=-1/(1+x)^2$, $p''(x)=2/(1+x)^3$, so $$(1 + \beta)[p'(x)]^2=\frac{2}{(1+x)^4}=\frac{2}{(1+x)^3}\frac{1}{1+x}\leq\frac{2}{(1+x)^3}\frac{2+x}{1+x}=p''(x)p(x)$$ for all $x\geq0$. Now $p(x)\geq1$, $R=\infty$ and $p(x)\to1$ as $x\to R-$.
Maybe I'm missing something. The question has been asked here but there are no answers yet.
Comment: the exercise seems wrong, some time ago I get a counterexample choosing $p(x)=be^{ax}$, see [here](https://math.stackexchange.com/questions/2091098/show-that-lim-x-to-r-px-infty-if-p-ge-alpha-and-1-betap2-le-p)
Answer: I wrote an email to the author of this series and the following is the screenshot of the email I received:

Since in email system, it can not show Latex, I will type it down for convenience:
$0\leq (1+\beta)p'(x)\leq p''(x)p(x)$ for $0\leq x\leq R$.
In addition, you have to add "unless p is constant" at the end of the assertion.
Now you should be able to do the exercise.
Although the question was proposed three years ago, I hope this would help you somehow.


Cant find any info on this method being removed in webform or how to fix

Question: I am writing a patch for a module that used an old beta or even alpha of webform for drupal 8.
There is a line WebformEntityReferenceItem::getEntityWebformFieldName($node); in the module that errors out saying getEntityWebformFieldName() does not exist and sure enough in Drupal\webform\Plugin\Field\FieldType\WebformEntityReferenceItem the method does not exist.
I checked an older release and the method was there at some point. I've been searching since yesterday but cannot find a workaround or even an answer as to why it was removed. Any ideas?
EDIT
So I managed to get it working, but this certainly seems like the incorrect way to do it.
$node->get('webform')->getValue()[0]['target_id'];
So it seems WebformEntityReferenceItem::getEntityWebformFieldName($node); just gets the webform on the webform node and then grabs its 'target_id' value.
$webform_field_name = WebformEntityReferenceItem::getEntityWebformFieldName($node);
$webform_id = $node->$webform_field_name->target_id;

What I posted in my edit, I do not believe is the correct solution, albeit it is now working. Any suggestions would be appreciated.
Comment: Run update.php, clear cache, should fix it
Comment: Sorry, I meant I am writing a patch to update the module. Not apply an update. I'll edit my post. @Clive
Comment: What is your final goal? Are you after the webform itself, or its submissions?  You might want to take a look at https://drupal.stackexchange.com/questions/244574/programmatically-get-webform-submissions-of-a-specific-nodes-webform
Comment: @Neograph734 I needed the webform id when using webform node. `WebformEntityReferenceItem::getEntityWebformFieldName();` doesn't appear to exist anymore as of webform 8-rc1. I want to know what to replace that with. I cannot find any mention of it being removed. The line in my edit seems to have fixed the module I am patching, but it seems hacky.
Answer: The WebformEntityReferenceItem::getEntityWebformFieldName() static method was not removed but it was refactored and moved to the 'webform.entity_reference_manager'service.
Here is an example of showing how to use the service.
/** @var \Drupal\webform\WebformEntityReferenceManagerInterface $entity_reference_manager */
$entity_reference_manager = \Drupal::service('webform.entity_reference_manager');
$field_name = $entity_reference_manager->getFieldName($node);
...

@see \Drupal\webform\WebformEntityReferenceManager
@see \Drupal\webform\WebformEntityReferenceManagerInterface
Comment: perfect, this is exactly what I was looking for. Thanks for all the work you've done for this module
Comment: I added a code example to my answer.
Comment: I am trying to get this working and I am doing: `WebformEntityReferenceManager::getFieldName($node);`, but getting an error saying `Error: Using $this when not in object context`where $node is of type `Drupal\node\Entity\Node` I must be calling this incorrectly but cant figure it out. If I call the method through the interface it says non static methods can be called statically. Any ideas?