How do I make a search insensitive in VB.NET?

Question: This is my first post, please let me know how to improve.
My question is kind of in 2 parts. First, I'm making a search function that takes text in a text box, references it in a database and adds the result to a data grid view. It works, but it is case sensitive, and long winded. I've managed to get around the sensitivity issue, but not without adding a ton of lines. Also, my method is producing multiple of the same result in the data grid view.
My questions are: is there an easier way to code this search, and how can I make it insensitive?
 dgvFileInfo.Rows.Clear()

    If searchBox.Text = "" Then

    ElseIf srchCrit = "ProjectNumber" Then
        Dim srchDesc As String = ""
        Dim rtrnDesc As String = ""
        Dim j As Integer = 0

        For Each row As DataRow In TblFiles.Rows
            rtrnDesc = row.Item(srchCrit).ToString
            srchDesc = searchBox.Text
            If rtrnDesc.Contains(srchDesc) Then
                dgvFileInfo.Rows.Add()
                dgvFileInfo.Item(0, j).Value = row.Item("ProjectNumber").ToString
                dgvFileInfo.Item(1, j).Value = row.Item("ProjectName").ToString
                dgvFileInfo.Item(2, j).Value = row.Item("Client").ToString
                dgvFileInfo.Item(3, j).Value = row.Item("City").ToString & ", " & row.Item("State").ToString
                j += 1
            End If
        Next
    Else
        Dim srchDesc As String = ""
        Dim rtrnDesc As String = ""
        Dim j As Integer = 0

        Dim letter As Char = searchBox.Text.Substring(0, 1)
        Dim line As String = searchBox.Text.Substring(1, searchBox.Text.Length - 1)

        For Each row As DataRow In TblFiles.Rows '***Here's my sensitivity issue**
            rtrnDesc = row.Item(srchCrit).ToString
            srchDesc = UCase(letter) & line
            If rtrnDesc.Contains(srchDesc) Then
                dgvFileInfo.Rows.Add()
                dgvFileInfo.Item(0, j).Value = row.Item("ProjectNumber").ToString
                dgvFileInfo.Item(1, j).Value = row.Item("ProjectName").ToString
                dgvFileInfo.Item(2, j).Value = row.Item("Client").ToString
                dgvFileInfo.Item(3, j).Value = row.Item("City").ToString & ", " & row.Item("State").ToString
                j += 1
            End If

            srchDesc = LCase(letter) & line
            If rtrnDesc.Contains(srchDesc) Then
                dgvFileInfo.Rows.Add()
                dgvFileInfo.Item(0, j).Value = row.Item("ProjectNumber").ToString
                dgvFileInfo.Item(1, j).Value = row.Item("ProjectName").ToString
                dgvFileInfo.Item(2, j).Value = row.Item("Client").ToString
                dgvFileInfo.Item(3, j).Value = row.Item("City").ToString & ", " & row.Item("State").ToString
                j += 1
            End If

            srchDesc = LCase(letter) & LCase(line)
            If rtrnDesc.Contains(srchDesc) Then
                dgvFileInfo.Rows.Add()
                dgvFileInfo.Item(0, j).Value = row.Item("ProjectNumber").ToString
                dgvFileInfo.Item(1, j).Value = row.Item("ProjectName").ToString
                dgvFileInfo.Item(2, j).Value = row.Item("Client").ToString
                dgvFileInfo.Item(3, j).Value = row.Item("City").ToString & ", " & row.Item("State").ToString
                j += 1
            End If

            srchDesc = UCase(letter) & UCase(line)
            If rtrnDesc.Contains(srchDesc) Then
                dgvFileInfo.Rows.Add()
                dgvFileInfo.Item(0, j).Value = row.Item("ProjectNumber").ToString
                dgvFileInfo.Item(1, j).Value = row.Item("ProjectName").ToString
                dgvFileInfo.Item(2, j).Value = row.Item("Client").ToString
                dgvFileInfo.Item(3, j).Value = row.Item("City").ToString & ", " & row.Item("State").ToString
                j += 1
            End If

        Next

    End If

Comment: One way to improve - don't post so much irrelevant code. Another is to always include the [tag:vb.net] tag when posting a VB.NET question. That way, the VB.NET experts will see your question.
Answer: 1) You are doing comparisons on the application side, meaning it is happening in the VB code.  To do a case insensitive search, you can either do a .ToUpper() or .ToLower() and compare that way.  Or, you can use String.Compare.
' using ToUpper (ToLower would be the same)
Dim isFound as Boolean = ("My string".ToUpper() = row("myField").ToString().ToUpper())

' using String.Compare
Dim isFound as Boolean = (String.Compare("My String", row("myField"), True) = 0)

2) The easiest way to do this would be to do the searching in the database.  If you can do that and your database is case insensitive (SQL Server instances default to case insensitive), you can now use LINQ and/or an ORM like NHibernate to build and execute sql in the database.  That is going to be a long series of questions that have been answered numerous times here on SO and around the web.
Comment: Thanks! I'll give those suggestions a try.
Answer: I found a nice method for searching with case insensitivity via some other posts.
If myString.IndexOf(myVar, 0, StringComparison.CurrentCultureIgnoreCase) > -1 Then
       'your code here
End If

This has been working very well for me, I hope you find it useful.


Laravel - make directory not working when is called by a seeder

Question: I'm trying to create icons for sites created in the past using laravel intervention, and this line is to make directories to save the icons for each site using this seeder
I'm trying to run a seeder, in the seeder I call a function from my controller, but when the function tries to make a directory it's stopping works.
this is a part of my seeder
<code>$route = $this->templateController->resizeImage($logo, $placeName, $domain);
</code>
and when I do a debug with xdebug, this line of code call to the function correctly.
my controller:
<code>public function resizeImage($logo, $placeName, $domain)
    {
        $img = \Image::make($logo)->resize(32, 32, function ($constraint) {
            $constraint->aspectRatio();
            $constraint->upsize();
        });

        $route = 'img' . DIRECTORY_SEPARATOR . $domain . DIRECTORY_SEPARATOR . 'favicon.png';
        if (File::exists($route)) {
            $img->save(public_path($route));
        } else {
            $newRoute = File::makeDirectory('img' . DIRECTORY_SEPARATOR . $domain);
            $img->save(public_path($route));
        }
        return $route;
    }
</code>
All works correctly, but when I debugging this line
<code>$newRoute = File::makeDirectory('img' . DIRECTORY_SEPARATOR . $domain);
</code>
I get this error in the artisan console

mkdir(): No such file or directory
at
D:\Programas\laragon\www\google-places-ranking\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:581
577▕         if ($force) {
578▕             return @mkdir($path, $mode, $recursive);
579▕         }
580▕   ➜ 581▕         return mkdir($path, $mode, $recursive);
582▕     }
583▕
584▕     /**
585▕      * Move a directory.
1
D:\Programas\laragon\www\google-places-ranking\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:581
mkdir("img\testing")
2
D:\Programas\laragon\www\google-places-ranking\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:261
Illuminate\Filesystem\Filesystem::makeDirectory("img\testing")

Note: This function works correctly when I use this controller with a form
Comment: Why is there a `makefile` tag in this question?
Answer: I solved replacing the line
<code>$newRoute = File::makeDirectory('img' . DIRECTORY_SEPARATOR . $domain);
</code>
to this
<code>$newRoute = File::makeDirectory(public_path(). DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . $domain,0777,true);
</code>


passing array as key pair in json format to function pgsql

Question: I have created a function that accepts a json. Here is the query
CREATE OR REPLACE FUNCTION public.data_get(
    data json)
    RETURNS SETOF json
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
DECLARE
        declare _text text;

    BEGIN
    -- get fields data from json - https://www.postgresql.org/docs/9.3/functions-json.html
    _text = data::json#>>'{text}';

and this is how i call this function
select * from data_get ('{"text":"my"}'::json) as info;

and this works fine
now i want to pass the array element so i added the variables like this
DECLARE
        declare
           _text text;
           _ids bigint[];

and accessed from json like this
_ids = data::json#>>'{ids}';

but when i call this function
select * from data_get ('{"text":"","ids":[1]}'::json) as info;

it shows
ERROR:  malformed array literal: "[1]"
DETAIL:  Missing "=" after array dimensions.
CONTEXT:  PL/pgSQL function posts_get(json) line 18 at assignment
SQL state: 22P02

how can i call this function?
Answer: Postgres doesn't do implicit conversion from json array to postgres array.
You need to use own function:
CREATE OR REPLACE FUNCTION public.json_to_int_array(json)
 RETURNS integer[]
 LANGUAGE sql
AS $function$
SELECT array_agg(v::int) FROM json_array_elements_text($1) g(v)
$function$

postgres=# SELECT public.json_to_int_array(('{"text":"","ids":[1, 2, 3]}'::json)->'ids');
┌───────────────────┐
│ json_to_int_array │
╞═══════════════════╡
│ {1,2,3}           │
└───────────────────┘
(1 row)


PostgreSQL: apply return of query to a function

Question: I have a recursive method defined below:
with recursive temp(id, s, r, e) as (
    select *
    from rel
    where rel_to_id = <parameter from sql query>

    union all

    select *
    from temp P
    inner join relationship C on P.r = C.s
)

and I need to call this on each row returned from an SQL query with a column value defined in the recursive query (marked as )
I dont really want to call X queries through python which slows things down, there must be a way to do it in sql. I tried to write a function in plpgsql but I am having trouble defining the return type setof TABLE and taking the union of it each time.
Comment: There is no return type "setof TABLE". It's either `TABLE` or `SETOF`. See [here](http://www.postgresql.org/docs/current/static/sql-createfunction.html)
Answer: I'm not sure I fully understand the problem, is your issue to call your recursive function on more than 1 initial value, as per the values returned by your ?
In that case, could you just create your initial table at once with all required values, and then recurse through it? Something like this:
with recursive temp(id, s, r, e) as (
    select *
    from rel r
    join <sql query> q on r.rel_to_id = q.id

    union all

    select *
    from temp P
    inner join relationship C on P.r = C.s
)

Comment: Doesn't necessarily need to be a JOIN though. Could be a simple `where rel_to_id IN (select some_id from some_value)` as well
Answer: IMHO calling the recursive query multiple times, once per parameter value is the worst you can do. Instead you should combine the recursive query with the one that supplies the parameter values and iterate over their "product". Often it is convenient to temporarily pack the recursive query into a view and join that with the other leg of the query. The optimiser will take care.
CREATE VIEW temp_view AS (
    with recursive temp(id, s, r, e) as (
    SELECT *
    from rel
    WHERE {recursive_condition}
    -- Omit the restriction
    -- AND rel_to_id = <parameter from sql query>
    union /* all? */
    select *
    from temp P
    inner join relationship C on P.r = C.s
    WHERE {recursion_stopper}
    ) SELECT * FROM temp_view
);

-- Now join the recursive part
-- with the one that supplies the restrictions
SELECT ...
FROM temp_view tv
    , other_table ot
WHERE tv.parameter = ot.parameter
AND ... -- more stuff
;

Comment: thanks for your answer, I tried this but the result of this query is wrong, the output contains duplicated columns ==> temp_view has columns a,b,c and the other_table has the same but the output is this:a,b,c,a,b,c


Is it possible for a Bayes estimator to be independent of the sample?

Question: I am trying to derive the Bayes estimator. Without getting into the nuts and bolts of the question, basically I have an indicator loss function of the form
$$L(\delta , \theta) = \mathbb{1}\{A\}$$
For an event $A$. I found that $EL(\delta,\theta |X)$ is minimized for almost all $X$ when $\delta$ is a function solely of the hyperparameters of $\theta$'s prior distribution. A theorem in my textbook then implies that such a $\delta$ is the bayes estimator of $\theta$.
On the one hand this seems ridiculous, but then again I figure such a result might be correct since we have a somewhat strange loss function.
I can go into the details of the problem if needed.

To clarify. We have the posterior distribution $\theta | X$ as being a truncated $N(\mu, \sigma^2)$ distribution truncated below at $\max_i X_i$. I want to derive the Bayes estimator under the loss function
$$L_\epsilon (\theta, \delta) = 1 - 1 \{ \delta - \epsilon \leq \theta \leq \delta + \epsilon \}$$
To find the $\delta$ that minimizes this, clearly it is equivalent to find the $\delta$ that maximizes
$$E 1 \{ \delta - \epsilon \leq \theta \leq \delta + \epsilon \}$$
There is also a theorem in my textbook that says it is enough to show that $\delta$ minimizes $E[L(\theta, \delta)|X]$ for almost all $X$ for it to be a Bayes estimator. So to find the Bayes estimator I tried to find the $\delta$ that maximizes
$$E [1 \{ \delta - \epsilon \leq \theta \leq \delta + \epsilon \}|X] = P(\delta - \epsilon \leq \theta \leq \delta + \epsilon | X)$$
Since we know the posterior distribution of $\theta$ is truncated normal we can work with this probability. From here I used the CDF of the truncated normal distribution $F$ given on the Wikipedia page to find the $\delta$ that minimizes
$$F(\delta + \epsilon) - F(\delta - \epsilon)$$
and using $$\frac{d\Phi (f(\delta))}{d\delta} = f'(\delta) \phi(f(\delta))$$ I found was that this is maximized when
$$\delta = \mu$$
which does not depend on $X$ at all. So I'm pretty sure I'm making a stupid mistake, or have misunderstood how to find Bayes estimators.
Comment: This question is not precise enough, how is $A$ connected with $\delta$ and $\theta$?
Answer: If one considers the loss function
$$L(\delta , \theta) = \mathbb{1}_{|\theta-\delta|>\epsilon}$$ the Bayes estimator $\delta^*(\cdot)$ is obtained as solving$$\arg\min_\delta\mathbb{E}[L(\delta , \theta) | x]$$for every $x$. Now
\begin{align*}
\mathbb{E}[L(\delta , \theta) | x] &= \int L(\delta , \theta)\pi(\theta | x)\,\text{d}x\\
&= \int \mathbb{1}_{|\theta-\delta|>\epsilon}\,\text{d}x\\
&= \mathbb{P}(|\theta-\delta|>\epsilon)\\
&= 1-\pi([\delta-\epsilon,\delta+\epsilon] | x)
\end{align*}
One thus wants to maximise the coverage of $[\delta-\epsilon,\delta+\epsilon]$ under the posterior distribution. This amounts to finding the location $\delta$ of the center of an interval of length $2\epsilon$ with the largest coverage. A graphic illustration is to imagine a stick of length $2\epsilon$ that is moved up under the graph of $\pi(\cdot|x)$ until it cannot move higher. It obviously depends on $\pi(\cdot)$ and on $f(x|\theta)$.
Note that differentiating $\pi([\delta-\epsilon,\delta+\epsilon] | x)$ in $\delta$ leads to$$\pi(\delta-\epsilon)=\pi(\delta+\epsilon)$$meaning that the resulting interval is an HPD region if the posterior is unimodal and monotone on each side of the posterior mode (MAP). It is only when the posterior is symmetric that $\delta^*$ is the MAP. Note also that when the posterior support is truncated, as in the truncated Normal example, the solution is an HPD but does not necessarily satisfy the equation$$\pi(\delta-\epsilon)=\pi(\delta+\epsilon)$$. For instance, if the posterior is the Normal distribution $\text{N}(\mu,\sigma^2)$ truncated below $\max x_i>\mu$, $\delta^*$ will be equal to $\max x_i+\epsilon$.
Comment: Thanks Xi'an, it is good to know the formal reasoning. I will have a think about how to deal with the truncation in order to maximize the coverage. I think my mistake before is assuming that $\mu$ is in the support of the posterior? when there's no guarantee that is the case.
Comment: After working through it I found the solution is a lot closer to what I was expecting. Thanks again


VMWare to Physical Machine - Windows 7

Question: Is it possibly (for example) to build a Virtual Machine, with windows 7, and then port this to a physical machine..?
For example, build up a configuration of a machine in virtual machine, then deploy this to a physical machine, so that it basically installs all the software on to the target machine, without running it as a VM?
Answer: yes. Build your VM, capture it with a disk imaging solution (WinPE/WIM for instance) and deploy your image to a physical computer. Or you can (I believe) use VMWare Converter to do V2P conversions.
Bear in mind though, that you might run into driver difficulties, but the risks here are way lower than they were on previous OSes.
Give it a go!
Answer: You can but it can be a bit of a headache, HERE is how VMWare recommend you do it.
Answer: I don't know if being able to do a virtual-to-physical installation with only freely available tools was a requirement or not, but you could do something like this using Acronis TrueImage with Universal Restore.
TrueImage allows one to make an image of the system drive and install it to multiple machines (and supports changing of SIDs, etc).
Universal Restore (which is an extension to TrueImage) allows one to install an image to a machine with different hardware (and specify drivers requried for the different hardware).
Unfortunately, both of these are paid software and not freely available ones.

VMWare to Physical Machine - Windows 7


How to add fields to menu items

Question: I need to build a main menu that is a subset of the regular menu. The design team thinks it would be better for user to have only the most important links in the main menu and not have everything. Some links are top level menu and some are sub menus. For this I was hoping to be able to add a field to the menu link item form as a drop down. When creating a link the user could use this dropdown to "promoteToMainMenuAsBigLink" or "promoteToMainMenuAsSmallLink" or leave none to not show the item on the main menu.
I'm looking for a similar solution as this Drupal 7 solution but for Drupal 8.
I was hoping to be able to add a column in the table menu_link_content_data beside 'expanded'. I was hoping not to have to record this information in an other table like shown in the d7 solution.
I was able to add a field to the link form in a custom module I build, just for test purpose I only added a text field to start with:
custom_menu.module:
function custom_menu_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if($form_id == 'menu_link_content_menu_link_content_form') {
    $form['promoteToMainMenu'] = array(
      '#type' => 'textfield',
      '#title' => t('Promote to main menu'),
      '#description' => t('Promote link menu to main menu.'),
      '#default_value' => '',
      '#weight' => -9
    );
  }
}

The field is indeed shown in the link form but it is never recorded.
Can someone help me with this?
Comment: As unlikely as it sounds, custom menu link items are content entities ( https://api.drupal.org/api/drupal/core!modules!menu_link_content!src!Entity!MenuLinkContent.php/class/MenuLinkContent/8.2.x ). That means you need to use a hook to add the field (maybe https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_base_field_info_alter/8.2.x ) and then run an update function to update the schema.
Answer: Check the Menu Item Extras module.
Comment: This is definitely the way to go, as of v2.0 of this module turns menu links into fully fieldable entites. Better solution than Colossal menu because it enhances the core menu system instead of replacing it.
Comment: +1 great for including today's date in the menu bar, for example
Comment: There is the article about all features https://lembergsolutions.com/blog/get-fieldable-drupal-menu-menu-item-extras-overview
Comment: I don't think this is a good solution. You can only add additional fields to a menu, but you can't use existing fields that belong to the menu item entity?
Answer: You can use hook_entity_base_field_info to add an additional field to the menu_link_content entity with the following code:
/**
 * Implements hook_entity_base_field_info().
 */
function MYMODULE_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  $fields = [];

  if ($entity_type->id() == 'menu_link_content') {
    $fields['FIELD_NAME'] = \Drupal\Core\Field\BaseFieldDefinition::create('FIELD_TYPE')
      ->setLabel(t('FIELD_LABEL'))
      ->setDescription(t('FIELD_DESCRIPTION '))
      ->setDisplayOptions('form', ['type' => 'FIELD_TYPE', 'weight' => 0]);
  }

  return $fields;
}

See https://www.drupal.org/docs/8/api/entity-api/defining-and-using-content-entity-field-definitions for more details on BaseFieldDefinition.
After which, you'll need hook_form_menu_link_content_menu_link_content_form_alter() to add a field to the form.
Comment: You do not have to add fields via form alter. You can simply use the `BaseFieldDefinition->setDisplayOptions()` method: `...->setDisplayOptions('form', [ ... ])`.
Comment: I've solved this problem.
/update.php is not working so column is never crated.
I've used drush to update db: drush updatedb --entity-updates
Comment: How I can create image field? I cannot find example with this field type and I need it. I can see image upload field when using this but when I try to save menu item I get:
Drupal\Core\Entity\EntityStorageException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'field_menu_image__target_id'

Also when I refresh page for add menu item form I see in logs:
 Notice: Undefined index: field_menu_image__height
 Notice: Undefined index: field_menu_image__width
and so on... Any example for image field type? Thanks
Comment: What do you put in hook_form_menu_link_content_menu_link_content_form_alter() to add the field?
Comment: i used this  but filed comes  on menus  but not store values i am using boolean filed  can anyone help me
Answer: Unfortunately there is indeed no fields UI for menu links by default in Drupal 8 as @MatthieuScarset said. But menu_link_content is a content entity in Drupal 8, so it is possible to add fields to it.
Option #1 Of course you can do it programmatically as @Decipher suggested.
Option #2 But there is another workaround to enable fields UI for menu links temporary:

Open Drupal\menu_link_content\Entity\MenuLinkContent
Add field_ui_base_route = "entity.menu.add_link_form" to the
annotation
Rebuild cache
Visit /admin/structure/menu/manage/main/add/fields
Manage all your fields, displays
Export your site configuration (drush cex -y).
Remove field_ui_base_route = "entity.menu.add_link_form" from the
annotation at Drupal\menu_link_content\Entity\MenuLinkContent
Rebuild cache.
Comment: I tried this approach. At first it looks good, but when I tried to create new field I get error: There was a problem creating field Menu image: Attempt to create a field 'field_menu_image' without a bundle.
I'm trying to achieve this programmatically now, but it would be better if this could work also.
Answer: You could use Colossal Menu to add the field instead of the core Menu module.
Answer: "Menu item extras" is one way to achieve this, as @Mykhailo Gurei suggested.
But in my case I had to add extra fields and to use Mega menu module. I was using "We mega menu" and with it "Menu item extras" is not working. Simply menu is not shown on front-end (some templates override issue).
So other option that works with "We mega menu" is "Menu item content fields":
https://www.drupal.org/project/menu_item_fields
Has the same functionality and doesn't have conflict with We mega menu module.
Answer: A newer solution could be menu item content fields
According to the project description its features are:

Add fields to menu items and sort their display.
Show fielded menu items with a block chosing the view mode.
Configure additional options on the formatter like the rel and target attributes.
Add more attributes with the Link attributes module.
Optionally have a field on the menu link entity that overrides the display mode.

Is up to the site builder to create it.
This field needs to store the string value of the display mode, for example: 'mega'.
Answer: Unfortunately, Drupal 8 core developers have not made Menu links fieldable.
So it is not possible to add fields to menu links for now.
The site builder "work around" is to create a custom vocabulary which can have custom fields.
Comment: Wrong. MenuLinkContent is a fieldable content entity.
Comment: Menu Item Extras do that https://www.drupal.org/project/menu_item_extras
Comment: How would you do to add new fields to MenuLinkContent?
Comment: see the answers above. They both explain how to add new fields to MenuLinkContent.
Comment: So to be clear @milkovsky

True. MenuLinkContent is NOT a fieldable content entity.
Comment: Ok, but MenuLinkContent is still NOT a fieldable content entity.

How to add fields to menu items


Find general solution of Differential equation if you know three solutions.

Question: I have three solutions for a non homogeneous, linear, 2nd order D.E
$$y_1(x)=3x−2x^2$$
$$y_2(x)=−2x^2+5xe^x$$
$$y_3(x)=2x−2x^2+3xe^x$$
I want to find the general solution.
I know that the general solution is a combination of the three but with some coefficients,   $c_1y_1+c_2y_2+c_3y_3$ such that $c_1+c_2+c_3=1$.
How do i find the $c_1$, $c_2$, and $c_3$ coefficients, in order to calculate the general solution?
Comment: The differential equation is not known.
Comment: Isn't this convex combination the general solution? Specific values of these coefficients come into play if you're solving an initial-value or boundary-value problem.
Comment: You said it yourself that the general solution is just some convex combination $c_1y_1+c_2y_2+c_3y_3$ of the coefficients.

So now you just compute that convex combination and it equals $$(3c_1+2c_3)x+(5c_2+3c_3)xe^x -2x^2.$$

Now by renaming $a=3c_1+2c_3$ and $b=5c_2+3c_3$, you see that the general solution is $ax+bxe^x-2x^2$.
Comment: @ shalop I am sorry, my mind was stuck. I finally understand. Thank you!
Comment: I can't see the differential equation.  Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference)
Comment: @Shalop Thank you so much! But how is the convex combination computed? I did not understand that part.
Comment: @user1584421 There is nothing to compute. That is literally the answer, as amd and I have said.
Comment: @shalop and how it is what it is?
Answer: You are looking for an ODE on the form :
$$y''+f(x)y'+g(x)y+h(x)=0$$
The first known solution is $\quad y_1=3x-2x^2\quad,\quad y'_1=3-4x \quad,\quad y''=-4. \quad$ Putting them into the above ODE leads to a first equation :
$$-4+(3-4x)f+(3x-2x^2)g+h=0 \tag 1$$
On the same manner we put the two other known solutions into the PDE.
$$(-4+10e^x+5xe^x)+(-4x+5e^x+5xe^x)f+(-2x^2+5xe^x)g+h=0 \tag 2$$
$$(-4+6e^x+3xe^x)+(2-4x+3e^x+3xe^x)f+(2x-2x^2+3xe^x)g+h=0\tag 3$$
The system of three equations $(1)$ , $(2)$ , $(3)$ can be solved for the unknowns $f,g,h$.
$$\begin{bmatrix}
f &\\
g \\
h
\end{bmatrix} =
\begin{bmatrix}
(3-4x) & (3x-2x^2) & 1 &\\
(-4x+5e^x+5xe^x) & (-2x^2+5xe^x) & 1\\
(2-4x+3e^x+3xe^x) & (2x-2x^2+3xe^x) & 1
\end{bmatrix}^{-1}
\begin{bmatrix}
4 \\
4-10e^x-5xe^x \\
4-6e^x-3xe^x
\end{bmatrix} $$
The result is :
$$\begin{bmatrix}
f &\\
g \\
h
\end{bmatrix} =
\begin{bmatrix}
-\frac{x+2}{x}\\
\frac{x+2}{x^2}\\
-2x
\end{bmatrix}$$
The ODE is :
$$ \boxed{y''-\frac{x+2}{x}y'+\frac{x+2}{x^2}y=2x}$$
Comment: Thanks a ton for taking the time to write this, it was super useful. But what is asked is not to find the ODE, but the general solution of the ODE. I gave an upvote to this answer.
Comment: the general solution of the ODE is : $$y=c_1x+c_2xe^x-2x^2$$ If this was only what you wanted, no need for the above troublesome calculus. The form of the general solution can be more easily guessed and then proved by inspection of the three solutions and linear combination of them. See the pertinent comment from Shalop.
Comment: Thank you very much!


two wifi networks for redundancy

Question: I have two wifi networks in the office, one hooked up to a cable which is unmetered and one to a cellular net which is metered. The idea is to provide a redundant network connections should one go down.
I can hook up both networks to the relevant servers (obviously there are modems that bridge onto the wifi networks). But what I want to do is prioritize so that all traffic goes through the cabled network and the cellular network is only used if the cable network is down. The goal is to have the cellular bridged network as a back up. The idea is that all the computers that actually need this level of redundancy have a couple of USB->WiFi devices plugged in.
All devices are Windows 10 systems.
This seems to be something that a lot of people would want to do but short of some ridiculously expensive equipment from CISCO I'm not sure how it can be done. It is surely possible simply in the network stack software, but I cannot find how to configure it.
Anybody got any suggestions?
Comment: Instead of two wifi networks, consider a router that connects to both your cable and cellular network.  The router can choose the cable path, or the cellular if cable is unavailable.    With two wifi networks, every computer has to test the connections on its own.  And the cable may be down, but the wifi will still be up.
Comment: @RonTrunk is right - this is a task for a router with two network connections. There are plenty of options that are not 'ridiculously expensive' in a work environment.
Answer: Go shopping for a multi homed "dual WAN" router, and a cellular modem. Include products targeted at small business and branch office. There are many more vendors than one. Prices are usually competitive.
A central point to mange the path is easier. Traffic must already go through this router. A desktop operating system doesn't have obvious tools to deal with down paths one hop away; the wifi may still be working but without Internet and WAN. Extra USB wifi NICs are not necessary if physical multi pathing to the desktops can be removed.
Comment: So yes, I understand from this and the other comments that you can do it like that, but I already have the hardware to bridge from my cable modem to the wifi net, and from the cellular network to another wifi net. I can switch between the wifi networks pefectly adequately by manually selecting them. But it seems obvious that this can be easily done automatically in software with no need for extra hardware. Am I hearing from you all that although it could be done Microsoft just never put it in the network stack?
Comment: I mean I could do some horrible hack like turning off the cell network connection, and constantly pinging the cable network to see if it is alive. If it is down I could run a powershell script to turn on the cell network, then doing a ping to turn it off when the cable network comes back. But that is a quite horrible hack for something that it seems to be should be pretty straightforward in the network configuration. Am I missing something?
Comment: @FraserOrr yes, you are missing believing the answer that is correct.
Comment: I am not saying it cannot be done in the client OS. Rather, the cost of a small multihomed router is not that much compared to the uptime it gives you, plus the time you will spend on this.

two wifi networks for redundancy


Unknown protocol when trying to connect to remote host with stunnel

Question: I'm trying to set up a stunnel for WebDav on Windows. I want to connect 80 port on my local interface to 443 on another machine in my network. I can ping the machine remote machine. However when I use the tunnel, I'm getting this error all the time
<code>SSL state (accept): before/accept initialization
SSL_accept: 140760FC: error:140760FC:SSL routines:SSL23_GET_CLIENT_HELLO:unknown protocol
</code>
There is nothing in the logs on the other machine and here's my stunnel connection config
<code>[https]
accept  = 127.0.0.2:80
connect = 10.0.0.60:443
verify = 0
</code>
I've set it up to accept all certificates so this shouldn't be a problem with a self-signed certificate remote host uses.
Does anyone knows what might be the problem that this connection cannot be eastablished?
Comment: Are you using stunnel, which is a piece of software, or are you trying to create a secure tunnel? Your question appears to have the terms confused.
Comment: I'm using stunnel the app. http://www.stunnel.org/
Answer: I've found the solution for this problem. I've been using SSL in server mode when I actually needed client mode.
Comment: Care to share the solution with us? Would be most appreciated thanks.
Answer: I guess you are accessing your local host with http, but looks like your remote host is already https. stunnel is meant for reverse cases, when local services do not support SSL.
Why can't you just go directly with https/webdav on the remote machine and bypass stunnel completely?
Comment: I'm doing a proof of concept. This SLL tunnel is a part of a larger app and I'm going to implement it on my own because I need several modifications. I just want to test how stable this kind of solution is.


Pseudo-field for custom entity without hook

Question: I developed custom entities in the code, using entity references :
A <- R -> C. Entity "R" contains references to "A" and "B".
I'd like to add a pseudo-field in entity "A", configurable in view display, that could render referencing entities (mean "R" entities referencing "A" with a given field "F").
Since I made my own classes for the entities, I'd really like to continue that way and prevent using hooks. I know I could achieve this with views, but it seems more logical, reusable, and quicker, to put it in entity code.

Is there a way to add the display field to my entity without using hook_entity_extra_field_info() ? For example could I create my own FieldEntityManager ?
Is EntityViewBuilder the right place to render the field with my own data ?
In a more generic way, would it be possible to develop a custom field type "referencing_entities" that I could reuse in every referenced entities I have ?
Would it be only a field formatter since I don't need to store anything ? Is it possible to access to the entity from the field to query referencing entities ?
Comment: Add a computed field. Theres a core issue just rtbc that makes this easier and discusses some catches, I suggest looking at that.
Comment: I am looking for the same requirement i.e. having pseudo field with formatter drupal 8. Did you find your answer to this query?
Answer: As time goes by there's Extra Field now.

Provides a plugin type for extra fields in entity view.
This module allows developers to add custom fields by simply providing
  a plugin. Site builders can use these fields in entity view modes as
  normally. Extra fields do not store data and do not have a field
  widget. Extra fields typically combine existing entity data and format
  it for display.


Como fazer requisições via c#? WebRequest vs HttpClient

Question: Tenho um projeto em .Net Framework 4.6.1, e em minhas pesquisas concluí que posso usar a classe WebRequest para fazer requisições a outros servições web via backend.

Eu gostaria de poder realizar requisições utilizando qualquer verbo HTTP.
Também poder fazer uso do protocolo SSL/TLS quando necessário.

A classe WebRequest é a única disponível para esse fim?
Além dos requisitos acima, considerando performance e segurança, essa é a forma mais indicada para estabelecer conexões através da plataforma .net?

Edição:
Considere os seguintes trechos de código:
Caso 1:
public class MyServiceController : ApiController
{
    public void Post()
    {
        // ...
        using (var httpClient = new HttpClient())
        {
            var result = httpClient.GetAsync("https://pt.stackoverflow.com");
        }
        // ...
    }
}

Caso 2:
public class MyServiceController : ApiController
{
    public void Post()
    {
        // ...

        var request = WebRequest.Create("https://pt.stackoverflow.com");
        request.Method = "GET";
        // ...

        using (var response = request.GetResponse())
        {
            // ...
        }
    }
}

1. Se ambos podem me auxiliar a fazer uma requisição em C#, qual seria a
diferença entre eles? Quais os cenários mais indicados?
2. Ambos possuem suporte para qualquer verbo HTTP?
3. Ambos possuem suporte para o uso do protocolo SSL/TLS?
4. Qual é mais performático?
5. Algum deles está obsoleto e pode me oferecer riscos de segurança na requisição?
Comment: Dê uma olhadinha na classe `HttpClient` e veja se te atende
Comment: @KevinKouketsu muito obrigado pelo comentário. Se puder postar uma resposta com um breve comparativo entre WebRequest e HttpClient acredito que já possa aceitá-la.
Answer: O HttpClient é a classe mais atual para ser utilizada (a partir do 4.5), inclusive no ASP.NET Core (Qual eu uso) é possível aplicar comportamentos de resiliência em micro-serviços usando o Polly

Essa classe permite o uso de chamadas para vários servidores e hosts na mesma instancia e a quantidade que quiser.
Você pode derivá-la para sua próprias classes especializadas.
Foi escrita usando o TAP (Task-based Asynchronous Pattern) podendo lidar com solicitações assíncronas, uso do Await, gerenciar solicitações pendentes etc...
Abstraiu muito coisa, sendo muito mais fácil a implementação e com menos linhas de código.
Suporta ssl

O macoratti fez uma comparação que você pode encontrar clicando aqui
Espero ter ajudado!


Digital piano/keyboard under $1000 tuned to 432 hz with weighted keys?

Question: I am relatively new to piano and looking to invest in a digital piano or keyboard with weighted keys that I can tune to 432 hz.
One more thing I have noticed that I sing better in lower octaves. So is there a piano with 88 keys that'd replace the higher most octave with one lower?
Comment: Just because you *sing* better lower has little bearing on a piano being capable of playimg lower notes! The two phenomena are not connected at all. Changing key is way more useful. And tuning to A=432Hz is pretty well inconsequential as far as your singing is concerned. There are other questions you need to ask that may shed light on what I am saying.
Comment: @guidot - most digital pianos have a convenient transpose button!
Comment: Also, my 2 cents about it: 432Hz is nonsense in music history, it's a lysergic trip mixed with esoteric marketing. Play in 415~418Hz, much more satisfying, as our baroque colleagues really did in the past.
Comment: If your voice reaches down to the lowest octave on a standard piano, you're one heckuva contra-bass
Comment: @ScottWallace - thanks - it was the principle that I was trying to make, but thanks anyway!
Comment: @RodrigoB.Furman - yes, 432 is a trip.  You're probably aware that 432 is the frequency of the Universe (because it's a pretty number, 2x2x2x2x3x3x3).  And that 440 is a brainwashing frequency introduced by the Rockefellers, or maybe the Nazis.  Lol.  Or not.
Comment: @CarlWitthoft - the deepest bass voice I've ever heard, who really had a strong centered note at the pitch, sang an A below cello C.  That's still an octave above the lowest note of a standard concert grand piano.  So yeah.
Comment: tbh, if you can sing off either end of a piano, let alone both, there's little we can do to help. For everyone else, there's ***transposition*** ;)
Comment: @ScottWallace you know this story is fairytale for adulteens, don't ya? There's not something as "frequency of Universe".
Comment: @RodrigoB.Furman - surely that's the same as playing a piece written in, say, F, and playing it in (I guess) Eb?
Comment: The transposition proposed by Tim might not be overly helpful for a piano player unable to do it mentally, since then a modified score is required.
Comment: @Tim - 415 Hz is pretty exactly a half step below A=440, so F sounds in E.
Comment: @RodrigoB.Furman - yes, I'm well aware of the silliness of 432.  If anyone wants a really good resource on this bizarre conspiracy theory, which at least doesn't involve killing people, check out miltonline's in-depth study: http://www.miltonline.com/2014/01/07/hertz-so-good/
Answer: Any decent digital piano these days can be tuned any way you want, shift octaves, split the keyboard in two or more sections, etc.
What instead changes quite a bit from one model to the next is the quality of the weighed keys system, and secondarily, the quality of the internal sound samples.
Therefore, if it were for me, I would want to personally try the touch of as many different models as possible, and that would be my main criterion of choice. Everything else, i.e. everything digital rather than mechanical, these days can be easily customized in any way you want.
Comment: To cover some of the comments under the question, mentioning of *transpose* functionality might be a welcome addition.
Answer: No need to spend as much as $1000!
If you have a Mac, I would recommend investing in a decent MIDI keyboard (prioritizing touch and feel), an audio interface, and software that allows you to use many different piano and keyboard samples.

For the keyboard, I would visit a music store in person and try them out until you find one whose touch you like. At the $400 price point, you'll be able to find one with built-in speakers as well, so you can practice without plugging into the computer, too. If that doesn't matter to you, there are plenty of options in the $200 range.
For the audio interface, I'd recommend the Focusrite Scarlett Solo, which runs about $120. You can also use this to record guitar, bass, or vocals if you want that.
For software, the app GarageBand has plenty of samples built in, so you try using that first and see if it doesn't satisfy you. If you want more sounds, Mainstage is basically just the Logic sample library without the production capabilities, and it costs $30. The full Logic program runs $200, and I think it's overkill for your purposes.

Total cost: about $400-600, and you have a rig that you can upgrade piece by piece as your interests evolve.


Ordenar lista em ordem alfabética com JavaScript

Question: Eu tenho um HTML simples onde preciso de uma lista de nomes que eu consiga adicionar, remover e de dois botões que ordene por ordem crescente e decrescente.
Eu consegui fazer somente o adicionar e o remover da lista.

var convidados = new Array();

function InsereConvidado() {
  var conv = document.getElementById("convidado");
  if (conv.value !== '') {
    convidados.push(conv.value);
    conv.value = '';
    AtualizaLista();
  }
}

function AtualizaLista() {
  if (convidados.length > 0) {
    document.getElementById("presentes").innerHTML = "";
    convidados = convidados.sort();
    for (i = 0; i < convidados.length; i++) {
      document.getElementById("presentes").innerHTML += '
' + convidados[i] + ' [x]
';
    }
  } else {
    document.getElementById("presentes").innerHTML = "Nenhum convidado na lista.";
  }
}

function RemoverConvidado(el) {
  var nome = el.parentNode.firstChild.innerHTML;
  for (i = 0; i < convidados.length; i++) {
    if (convidados[i] === nome) {
      convidados.splice(i, 1);
      AtualizaLista();
    }
  }
}

Lista de Presentes

Nenhum convidado na lista.

Inserir Convidado

<input type="text" placeholder="Nome do Convidado" id="convidado" />
<button type="button" onClick="InsereConvidado();">Inserir</button>

Alguém pode me ajudar a adicionar dois botões nesta lista? Um que ordene por ordem crescente os nomes e outro que ordene por ordem decrescente.
Comment: Se o código for simples, é preferível que coloque ele dentro da pergunta.
Comment: Um você quer A-Z e ou Z-A é isso?
Comment: eu prefiro deixar ele aonde está pois ficar mais facil de ser executado, e tbm eu não sei como criar aquela parte de executar o codigo dentro do post desculpa ;\
Comment: isso, são dois botoes uma de A-Z e outra de Z-A
Comment: @Tibialize respondi, ve se funciona qualquer coisa me avisa e se possível marque como correta :).
Answer: Consegui fazer de forma simples:

var convidados = new Array();

function OrdenarInvertido() {
var conv = document.getElementById("convidado");

                conv.value = '';
    convidados = convidados.sort();
    convidados = convidados.reverse();
        document.getElementById("presentes").innerHTML = "";

            for (var i = 0; i < convidados.length; i++) {
              document.getElementById("presentes").innerHTML += '
' + convidados[i] + ' [x]
';
    }

    }
    function Ordenar() {
    var conv = document.getElementById("convidado");

                conv.value = '';
    convidados = convidados.sort();
        document.getElementById("presentes").innerHTML = "";

            for (var i = 0; i < convidados.length; i++) {
              document.getElementById("presentes").innerHTML += '
' + convidados[i] + ' [x]
';
    }

    }

        function InsereConvidado() {
            var conv = document.getElementById("convidado");
            if (conv.value !== '') {
                convidados.push(conv.value);
                conv.value = '';
                AtualizaLista();
            }
        }

        function AtualizaLista() {
            if (convidados.length > 0) {
                document.getElementById("presentes").innerHTML = "";
                convidados = convidados.sort();
                for (i = 0; i < convidados.length; i++) {
                    document.getElementById("presentes").innerHTML += '
' + convidados[i] + ' [x]
';
                }
            } else {
                document.getElementById("presentes").innerHTML = "Nenhum convidado na lista.";
            }
        }

        function RemoverConvidado(el) {
            var nome = el.parentNode.firstChild.innerHTML;
            for (i = 0; i < convidados.length; i++) {
                if(convidados[i] === nome) {
                        convidados.splice(i, 1);
                    AtualizaLista();
                    }
            }
        }
<title>Exercício</title>

Lista de Presentes

Nenhum convidado na lista.

Inserir Convidado

    <input type="text" placeholder="Nome do Convidado" id="convidado" />
    <button type="button" onClick="InsereConvidado();">Inserir</button>
  <button type="button" onClick="Ordenar();">Ordenar</button>
  <button type="button" onClick="OrdenarInvertido();">Ordenar Invertido</button>
Comment: Isso mesmo que eu queria @Breno, muito obrigado pela sua ajuda
Answer: A sua função atualizar já ordena por ordem crescente. Para fazer por ordem decrescente, é só criar uma cópia da sua função atualizar e colocar convidados = convidados.reverse() após convidados = convidados.sort();. Depois é só atribuir os cliques dos botões a essas funções.
Comment: como que eu faço isso?
Comment: pode me dar um exemplo
Comment: https://jsfiddle.net/9afggkr7/

Utilizei o seu mesmo método de Atualizar, alterando-o para receber um parâmetro que indica se a ordenação deve ocorrer em ordem crescente ou decrescente.


Formula to search data in 1 column and from data in 2nd column and display data of 2nd column

Question: I have two columns. Each cell in column A contains a full sentences and each cell in column B contains a word or phrase. I would like to check if the contents of any cell in column B appears in each cell in column A and get the word or phrase of the cell/cells of Column B that appear in Column A.
Column A      Column B     Search Result
Twenty One    Twenty       Twenty, One
Five Boxes    Ten
Ten Words     Thirty       Ten
Twenty Pens   One          Twenty

Answer: You can use a matrix (array) formula to achieve this. Please enter the following formula into cell C2 (assuming your table starts at A1):
=LEFT(CONCAT(IF(ISNUMBER(SEARCH($B$2:$B$5;A2))=TRUE;$B$2:$B$5&", ";""));MAX(LEN(CONCAT(IF(ISNUMBER(SEARCH($B$2:$B$5;A2))=TRUE;$B$2:$B$5&", ";"")))-2;0))

Please make sure you press Ctrl+Shift+Enter after pasting the formula into the cell! This combination says to the Excel that you are using a matrix formula. If you press Enter only the formula will not work properly. Then you can copy the formula into cells below in a standard way. If you want to input more data you need to expand range $B$2:$B$5.
You can check my example sheet here. You can also read more about matrix formulas in Microsoft documentation.
Edit #1
There is a different list separator in the US locale. If you use US locale please try this formula:
=LEFT(CONCAT(IF(ISNUMBER(SEARCH($B$2:$B$5,A2))=TRUE,$B$2:$B$5&", ","")),MAX(LEN(CONCAT(IF(ISNUMBER(SEARCH($B$2:$B$5,A2))=TRUE,$B$2:$B$5&", ","")))-2,0))

Please keep in mind to use Ctrl+Shift+Enter after entering the formula.
Comment: It did not work. Highlights the $B$5 part in the code.
Comment: Sorry but I don't understand the problem. Did you try to download my example sheet? You can see a working example in it.
Comment: Maybe you have a comma as a parameter separator in your Office. Please try to replace `;` by `,` in your Excel file.
Comment: Did this fix help?


How is cdf input converted from negative to positive?

Question: Suppose X has normal $(μ,σ^{2})$ distribution, and $P(X \leq 0)=1/3, P(X \leq 1)=2/3$
What are the values of μ and σ?
$\frac{1}{3}=P(X \leq 0)=P(\frac{X-μ}{σ} \leq \frac{0-μ}{σ})=φ(\frac{-μ}{σ})$
$φ(\frac{-μ}{σ})=\frac{1}{3} → φ(\frac{μ}{σ})=\frac{2}{3} → \frac{μ}{σ}=φ^{-1}(\frac{2}{3})=0.43$
I don't understand how this $φ(\frac{-μ}{σ})=\frac{1}{3} → φ(\frac{μ}{σ})=\frac{2}{3}$ happened.
Comment: Ok, I added the full question. I think I understand where I went wrong with my original post. I forgot to add that $P(X \leq 1)=2/3$. But I still don't understand how it is so.
Comment: Are you talking about a specific distribution?
Comment: Specific to the given example. I think I'll get how it's done generally if I understand this example. If I don't, I'll ask more questions.
Comment: What you have written is not true in general but it could be true for a particular distribution. Also $\mu$ should be negative since CDF is non-decreasing so $\mu/\sigma=0.43$ is simply not true if $\sigma$ is the standard deviation.
Comment: Ok, I added some more details. Can you check if it makes sense now?
Comment: In the first line you say $\psi(-\mu/\sigma)=1/3$, in the next you say $\psi(-\mu/\sigma)=1/2$?
Comment: Sorry, there were some massive typos in my first post. They're fixed now. It's $1/3$ to $2/3$ And first and second line match now.
Comment: You can't infer $\Phi(\mu/\sigma)=2/3$ from the given information. It is not true in general.
Comment: But that's what the textbook solution says... If I try $Φ(1.22) - Φ(0.14) = 0.3333 = 1/3$, then it's $μ/σ = 1.08$, which is not the given solution $0.43$.
Comment: You will have to provide more details about the distribution.
Comment: It all gets sorted now!
Answer: You will have to make use of a special property of the CDF of standard normal distributions, namely $\Phi(x)+\Phi(-x)=1\forall x\in\Bbb R$. It is easy to see why this is true:$$\begin{align*}\Phi(x)+\Phi(-x)&=\int_{-\infty}^x f(x)dx+\int_{-\infty}^{-x}f(x)dx\\&=-\int_{-\infty}^x f(-(-x))d(-x)+\int_{-\infty}^{-x}f(x)dx\\&=-\int_\infty^{-x} f(-y)dy+\int_{-\infty}^{-x}f(x)dx\end{align*}$$ where $y=-x$ and $f(x)$ is the PDF of standard normal distribution. $f(x)$ is even so $f(-y)=f(y)$, giving$$\int^\infty_{-x} f(y)dy+\int_{-\infty}^{-x}f(x)dx=1$$You can extend this concept to general normal distributions:$$F(\mu-x)+F(\mu+x)=1$$
Comment: Here's what I'm confused about. So for $P(X \leq 1)=2/3$, it says $φ([1-μ]/σ)=2/3$. How can both $φ(μ/σ)$ and $φ([1-μ]/σ)$ equal $2/3$?
Comment: Because $\mu/\sigma=(1-\mu)/\sigma$ ($\Phi$ is bijective).
Comment: Oh... Thank you so much! The professor skipped the CDF part and want us to learn Normal Distribution without going through it, so I was so confused. Now I get it.
Comment: Glad to be of help.
Comment: Hey, just a last bit. Can you give me a link where it shows the bijection of Φ, so that this solution works? I'm trying to look it up so I can find something solid to write down in my notes, but I'm having a hard time.
Comment: @JacobToho Can you prove that $\Phi$ is strictly increasing? The derivative of $\Phi$ is the PDF of $Z$ and the PDF is positive. Strictly increasing means that $\Phi$ is injective, which means it is bijective over its range $(0,1)$ (although we only need injectivity here)


Exam FM problem using force of interest. Calculate $P-Q$

Question:
The foce of interest at time $t$ is given by $\delta_t=.01t$. $P$ is the present value of a 12 yr annuity due of $100$ payable annually.  $Q$ is the present value of a 12 yr annuity immediate of $100$ payable annually.  Calculate $P-Q$.

The solution to this problem states that we do not need to calculate $P$ or $Q$ and I honestly do not see that at all.
All I know is $e^{\int_0^t{\delta_s}ds}$ is the effective accumulation. Can I get some help?
Answer: The difference between an annuity-due and annuity-immediate is that the former pays at the beginning of the year and the latter pays at the end.  So the difference in the two cash flows is simply the difference in present values of the first payment of the annuity-due and the last payment of the annuity-immediate.  This is exactly analogous to a telescoping sum:  all the intermediate cash flows cancel out exactly.  More concretely, consider the following table of payments:  $$\begin{array}{c|c|c|c|c|c} t & 0 & 1 & 2 & \ldots & 11 & 12 \\ \hline P & p_0 & p_1 & p_2 & \ldots & p_{11} & \\ Q & & q_1 & q_2 & \ldots & q_{11} & q_{12} \end{array}$$ but note that because the force of interest is the same and the level payments are also the same ($100$ for each annuity), it is clear that no matter what the actual values of $p_i$ and $q_j$ are, that $p_i = q_i$ for each $i = 1, 2, \ldots, 11$.  So $P - Q = p_0 - q_{12}$.
So, the only real computation you need to do is calculate the present value of the final payment at $t = 12$.  This is given by the present value discount factor $$ \exp \left( - \int_{s=0}^{12} \delta(s) \, ds \right) = e^{-18/25} \approx 0.486752,$$ hence $$P - Q = 100(1 - e^{-18/25}) \approx 100(1 - 0.486752) = 51.3248.$$
Comment: The table made it very clear to understand.  Thank you very much.


Can I combine several ordinal questions to create an index and/or composite measure?

Question: I am using a survey that contains several questions about various dimensions of performance for policy research institutes. Here, performance in the policy arena is unpacked into things like:

quality of research,
overall ability to engage with policy stakeholders,
quality of recommendations, overall support to, and influence on, policymakers,
etc.

Each question has a typical 5-level ranking (i.e., ordinal response from "strongly disagree" to "strongly agree", or "very bad" to "very good").
I am thinking of pursing either of two options:

Creating a sort of composite measure, where all dimensions of performance are aggregated together so as to have one composite variable of "performance". I could then use this composite variable as the dependent variable (perceptions of performance).
Combining 20 of these questions to create a performance index. For each dimension, responses range between 1 and 5. So total scores on the index would thus range from a minimum of 20 up to a maximum total of 100 points. This index could also be used as a dependent variable. Or perhaps only for descriptive statistics.

Does this make sense? Any advice and reference would be greatly appreciated.
Comment: Welcome to the site, @Philippe. I don't understand the difference between your conception of "composite measure" & "index". To me they both seem like putting individual question responses into one new variable. Can you clarify that?
Comment: You can't sum ordinal items; if you sum them it means they are scale and not ordinal for you.
Comment: @ttnphns This is done all the time is areas like psychological research (but much more widely than that); that's after all exactly what a [Likert scale](https://en.wikipedia.org/wiki/Likert_scale) is - a sum of items from ordinal items to produce a composite scale. It makes an implicit assumption (that the category intervals are equispaced), but in practice it's done when there's no particular reason to think it's the case. If there are many related items it seems to work quite well.
Comment: You may wish to search on this site for "survey validity". There are about 60 articles here.  If you add the questions together, the issue is whether you have something meaningful at the end. In many fields assumptions are violated due to the robustness of the analysis to such violations.  The issue of meaningfulness will have to rest with you, but you can check for the internal consistency of the items you sum by running one of many estimates (Cronbach's alpha is one example). You could also determine if your construct is unidimensional.
Comment: @Glen_b. `It makes an implicit assumption ... when there's no particular reason to think it's the case` The assumption of (equi)intervality is usually made _without_ grounds, indeed, and it's normal. But that simply means you don't take items as ordinal, when you do it. Likert (summative) construct is the constellation of interval-scaled items.
Comment: Thanks for your useful comments. @gung I think I was seeing composite measure as still being an ordinal variable (5-point ranking) and therefore amenable to logistic regression, and index as scale (20 to 100) to be tested with OLS. But in effect this is putting individual question responses into one new variable.
Comment: @ttnphns Would you say that the idea of combining question responses into a new variable to be abandoned?
Comment: @Glen_b Thanks. Would you then use OLS on the composite scale?

Any key, understandable, literature on creating an index/composite measure?
Comment: @Phillipe I'm not the right person to point you toward literature on this; I'm more of an interested bystander on the whole area relating to Likert-scales and similar instruments. I try to understand (not least because as a statistician with a little experience and ongoing contact with academia I am often asked questions by people in the areas that tend to use such instruments), but I really don't know much relevant literature. I hope to learn something (we may have already exhausted my knowledge of any relevance to your question).
Comment: Can you still create a composite variable if a "don't know" response option is included?
Answer: Yes, both your points make perfect sense, and are indeed a standard practice - at least in an area called psychometry.
But I cannot agree with the title question: it is not always valid to ordinal variables. In general case one cannot add nor subtract values measured on ordinal scale and hope, that the result would be independent from arbitrariness that come in the notion of ordinal variable.
Ordinal variable is a special case of interval variable; one in which we cannot say how far away from each other are adjacent levels of the variable. For instance, the education (which in many contexts is a valid ordinal variable) can be measured in 3 levels:

Primary education
Secondary education
Higher education

These 3 levels are usually mapped internally into numeric values "1", "2" and "3" - but this mapping is completely arbitrary. One can equally well map these levels as "1", "10", "100", or "8", "12", "17" (the last example would be a rough estimate of years of education) or employ the procedure from the Witkowski's paper. All statistical procedures that are designed for ordinal variables are invariant with respect to any injective function applied to the values associated to the levels. Imagine now, that we asked the subject to state the education level of mother and father. And now we want to build a parents' education index - by simply averaging parents' education level.
Now the outcome will become highly dependent on the mapping done between education levels and numbers, that represent them internally. For the most typical case ("1", "2" and "3") the process of averaging yields the same level "2" if one parent has Primary education and the other has Higher education, and if both parents have Secondary education. This feature might be correct, or might not, depending on how well the assigned numerical values represent the actual value each education has in our view.
The typical 5-level ranking you mentioned (a.k.a. Likert scale) was specially crafted in such a way, that the semantical distance between consecutive levels is kept roughly constant. Because of this property, such variables can be classified as interval, hence we can proceed with addition (or arithmetic mean, or any other mathematical manipulations).
Answer: I assume here that your study's requirement is something along the lines of:
Given the ordinal responses to n questions for each candidate (a policy research institute in your case), rank/sort order the candidates by functionally combining the n-dimensional response tuple's elements into a score/metric.
Then perhaps you can look into the work of Wittkowski et al. (2004) and the references therein, on combining multiple ordinal variables for scoring.
Reference:

Wittkowski et al. (2004) Combining several ordinal measures in clinical studies. Statistics in medicine, 23, 1579-1592.


add associative array into another

Question: i want to add one associative array into another but when i use array_push it overrides the value of previous one
<?php
$tem = ["blue","ss"];
$len = count($tem);
print_r($len);
for($i=0;$i<$len;$i++){
    $data = [
        'code' => $tem[$i],
        'discount_type' => 'percent',
    ];
    $a=array();
    $result[$i] =array_push($a,$data);
    print_r($a);
}
?>

and the output is
2Array ( [0] => Array ( [code] => blue [discount_type] => percent ) )
 Array ( [0] => Array ( [code] => ss [discount_type] => percent ) )

Answer: The one problem is that you reset the $a array inside the loop, so it will only ever contain the last item.  Also, you don't assign the return from array_push() as it updates the array itself (but you never use $result[$i] anyway)...
So your code would end up something like..
$tem = ["blue","ss"];
$len = count($tem);
print_r($len);
$a=array();
for($i=0;$i<$len;$i++){
    $data = [
            'code' => $tem[$i],
            'discount_type' => 'percent',
    ];
    array_push($a,$data);
}
print_r($a);

You can also shorten the code using a foreach loop and creating the array as you add it to the result...
$tem = ["blue","ss"];
$a=array();
foreach ( $tem as $t )  {
    $a[] = [
        'code' =>  $t,
        'discount_type' => 'percent',
    ];
}
print_r($a);

Comment: Is there any progress with this?

add associative array into another


How to interpret R Pearson's correlation test?

Question: I am trying to learn a bit of R and statistics so as "toy project" I have started from the famous Iris dataset (150 rows, 3 classes). I have applied to two features the "correlation test" in this way:
cor.test(iris$Sepal.Length, iris$Petal.Length)
#
#   Pearson's product-moment correlation
#
# data:  iris$Sepal.Length and iris$Petal.Length
# t = 21.646, df = 148, p-value < 2.2e-16
# alternative hypothesis: true correlation is not equal to 0
# 95 percent confidence interval:
#  0.8270368 0.9055083
# sample estimates:
#       cor
# 0.8717542

which uses by default the Pearson's correlation.
Based on 2 hypothesis how do I interpret the confidence interval? I tried to use a t-table but I am still not sure if the value "0.8717542" is a good value or not based on the df.
I am using the t-table here (pdf).
I cannot see the DF = 148 but from 100 to 1000 looks there is not too much shift. So is it correct if I affirm that the interval of confidence is between 60% and 70% and based on that, there is an acceptable positive correlation between the two features?
Answer: The correlation between Sepal.Length and Petal.Length is $r_{SP} = 0.872$.  However, that is a point estimate.  It is perhaps more likely than any other point value, but that doesn't mean it's actually the true value of the correlation in the population.  Thus, R has also provided a 95% confidence interval around that estimate, $(0.827 \le r_{SP} \le 0.906)$.  This is interpreted as any other frequentist confidence interval would be interpreted.  Namely, if you were to repeat the data gathering process and analysis identically, over and over, ad infinitum, 95% of the intervals formed the way that one was would be expected to cover the true value of the correlation.  With respect to this sample, you can think of it as a measure of the precision of the estimate, in the sense that if your null hypothesis had been any value (not just $0$) that lay outside that interval, your test would still have been significant.
I think part of your confusion pertains to the question of how to test if an $r$-score is significantly different from $0$.  One way to do so is to use a $t$-test.  (That's what R is doing.)  In that context, you don't assess the fitted $r$ value, you convert that $r$-score into a test statistic that is distributed as $t$.  The equation is:
$$
t = r\sqrt{\frac{n-2}{1-r^2}}
$$
Although you are correlating two variables, this isn't a 2-group $t$-test.  It is a one-sample $t$-test.  At any rate, R has done that for you.  The value of your test statistic is $t = 21.646$.  To see how extreme that value is, you can compare it to a central $t$ distribution with $148$ degrees of freedom.  When you do so, you will see that the $p$-value is $p < 2.2\times 10^{-16}$.
Comment: thank you for your very interesting and detailed answer. How do I interpret the value "p" at this point? Any related link or reading to suggest about all of this?
Comment: @Randomize, the p-value is the probability of getting a result as extreme or more extreme than yours, if the null hypothesis is true. See: [What is the meaning of p values and t values in statistical tests?](http://stats.stackexchange.com/q/31/7290) In your case, the probability that $r\ge |0.872|$ or $t\ge|21.6|$.
Answer: I guess I don't really follow the question, but the "0.8717542" is the Pearson correlation estimate (link). 0.8 is usually considered a very strong correlation as 1 is a perfect correlation.
Comment: That is only the correlation, you still need to run a test to check the significance levels and probability. You can get more details here: http://www.sthda.com/english/wiki/correlation-test-between-two-variables-in-r


Prove that if $n$ is composite, then $(n-1)! \equiv 0 \pmod n$

Question: This theorem is the converse of Wilson's theorem:

If $n$ is composite and $n>4$, then $(n-1)! \equiv 0 \pmod n$

The question holds up for all the composites I have tried but I'm struggling to form a proof for all composites greater than $4$.
Comment: http://math.stackexchange.com/questions/164852/if-n-is-composite-then-n-divides-n-1
Comment: http://math.stackexchange.com/q/691618/462
Comment: I meant to include n>4 sorry
Comment: I don't think the vote to close makes any sense.
Answer: If $n$ is composite, then there are $1<a<b<n$ with $ab=n$, unless $n=p^2$ is the square of a prime. In the first case, $a$ and $b$ appear in the product $(n-1)!$ thus $n|(n-1)!$. In the second case, your hypothesis $n>4$ implies $p\geq 3$ and thus $1<p<2p<n-1$ so that $2n=p\times 2p$ divides $(n-1)!$.
Answer: Suppose first that there exist integers $a$ and $b$, such that $1\lt a\lt b\le n-1$ and $ab=n$. Then since $b\le n-1$, it follows that $ab$ divides $(n-1)!$. For each of $a$ and $b$ appears among the numbers from $1$ to $n-1$.
But $n$ can be composite without meeting the above condition: It could be that the only proper factorizations of $n$ have the shape $n=a^2$. (This only happens if $a$ is prime.)  In that case, if $a\ne 2$, then $a$ and $2a$ are both $\le n-1$. So $2a^2$ divides $(n-1)!$, and therefore $a^2$ divides $(n-1)!$.
Answer: Notice first that
Suppose $p$ is prime and $p\mid n$. Since $n$ is composite, we have $p<n$, so $p\le n-1$.
The multiplicity of the prime factor $p$ in the the factorization of $n$ is the largest integer $k$ such that $p^k\mid n$. Thus $p,p^2,p^3,\ldots,p^{k-1}$ divide $n$ and are all less than $n$.  We have
$$
(n-1)! = (n-1)(n-2)(n-3) \cdots 3\cdot2\cdot1.
$$
The numbers $p$ and $p^{k-1}$ are both in this string of numbers from $1$ to $n-1$, so the product is divisible by $p\cdot p^{k-1} = p^k$. And $p^k$ itself is in that string of numbers unless $p^k=n$. Either way, $p^k\mid n.$
This is true of all prime numbers that divide $n$, and thus it is true of the product of those powers of primes, and the product is $n$.  So $n$ is a divisor of $(n-1)!.$
Revised postscript: As Bill Dubuque points out in comments $4$ is not a divisor of $(4-1)! = 6$. The problem is this: although $p=2$ and $p^{k-1}=2^{2-1} =2 $ are both in this string of numbers, in this case $p$ and $p^{k-1}$ are both the same number, namely $p$. This happens whenever $p$ and $p^{k-1}$ are both the same number, i.e. when $p^{k-1} = p^1$ so that $k=1.$ So we can't conclude that $p\times p^{k-1}$ divides $(n-1)!$ by that same method in that case.
However, the result can be proved by another method when $k=1$ and $p>2$: Observe that $p$ and $2p$ are both divisors of $(n-1)!$, so $p^k=p^2\mid (n-1)!.$ That doesn't work when $p=2$ because in that case $2p$ is $n$ itself rather than some number less than $n$.
Comment: @MichaelHardy I think you should give more details in your answer. Even I cannot infer *precisely* which proof you have in mind. One could give the same answer for *any* divisibility problem, so it does not say much about this particular problem.
Comment: @MichaelHardy yes, and in hindsight you can see that such a case-based proof is in fact simpler *without* using primes, i.e. if $\, n = ab\,$ then wlog either $ a < b$ and both occur as factors, or $\,a = b\,$ and then $\,a,2a\,$ occur as factors. I didn't think you intended that proof because primes are not needed. Hence my prior comment about not being able to guess what you had in mind. One should not have to guess. Proofs should be clear enough to avoid having to guess.
Comment: I have been trying to use this approach, but have been unable to produce a proof. Could you please elaborate?
Comment: ok, Suppose $n=60$.  Then $n = 2 \times 2\times3\times5$. The primes that divide $60$ are $2$, $3$, and $5$.  So you have $$ 59! = 1\times 2\times 3\times 4 \times 5\times \cdots\times59.$$The prime numbers that divide $60$, namely $2$, $3$, and $5$ are all in this factorization of $59!$ because, since $60$ is not prime, all of them are less than or equal to $59$. And the one that appears more than once, namely $2$, appears more than once is the factorization of $59!$. So $2\times2\times3\times5$ is present in the factorization of $59!$, so $60$ divides $59!.\qquad$
Comment: @ShreyAryan : I've rearranged the answer somewhat. $\qquad$
Comment: @MichaelHardy : Thank you! The edited answer is much more understandable.
Comment: @Shrey The proof is incorrect. You might find it instructive to try to locate the error.
Comment: It seems fine to me. Could you give a hint.
Comment: I mean $p$ is an arbitrary prime divisor of $n$.
Comment: @Shrey Hint: the hypothesis $n>4$ is necessary since $\,4\nmid 3!.\,$ But the proof never uses this hypothesis. So it cannot be correct. When you track down the error you will find that the proof fails for infinitely many integers. But it is not too difficult to remedy.
Comment: @BillDubuque : I've added a postscript that boldly says: "there's no problem with this argument when $n>4$." You seem to say that's wrong. So maybe we're not done here yet. $\qquad$
Comment: Generally, it fails for $n = p^2$, Michael. For $n = p^2$ with $p > 2$, use $p$ and $2p$.
Comment: @MichaelHardy That's the error I hinted at. But as I mentioned, it occurs not only for $4$ but for infinitely many integers, viz. $\, n = p^2.\ $ Update: Daniel has pointed that out too, along with the obvious fix for this case (his comment hd not yet appeared here when I first posted this comment).
Comment: @BillDubuque : ok, I think I've got everything fixed now.
Comment: In any case, kudos to you for describing the debugging process in the answer since it will serve as a very instructive example to students. I thought that might happen in the comments after my hint, but certainly it gets better exposure in the answer.
Answer: If $n=pq$, try to prove that $pq$ divides $(n-1)!$


Eclipse CDT convert a "normal folder" to a "source folder" or vice versa

Question: Because of me not being used to Eclipse I have projects whose subfolders are mixed "source" and "normal" folders. This is not much of a problem since those are Makefile projects but it bothers me to have my folders not being listed alphabetically (the source folders are displayed first).
I would like to convert my "normal" folders to "source" folders but I can't find anything related in the right click menu on said folders nor in the "properties" window.
Is there a way to convert folder types that doesn't involve editing the .cproject file manually ? If not, can I just edit the sourceEntries tag (it seems to work so far) ?
I am using CDT 8.0.2.
Answer: In order to do this in Eclipse, you should get in your project's properties, then expand C/C++ general -> Paths and Symbols -> Sources tab
Then click the Add Folder button, and choose the normal folders you wish to include as "source" folders.
Answer: Right click on the folder, "BuildPath" and "Use as Source Folder"
Comment: That did not work for me. There seems to be no "BuildPath" in the right-click menu in recent Eclipse CDT from 2022.
Answer: In Eclipse 2022-12, Right click on the project then New->Source folder and select the folder.


Reload de página com Jquery sem cache (Chrome)

Question: Na verdade não sei se o problema é o cache ou o script que fiz ou no server que estou usando, mas vamos lá.
Estou usando este código para carregar um documento para o servidor(ainda não avaliei questões de segurança e desempenho).

if($("#add-doc").isValid()){

$.ajax({
    url: 'api/upload-doc.php',
 type: 'POST',
 data: formData,
 beforeSend: function(){

  $("#docs-objeto3 #forms").hide();
  $("#docs-objeto3 #loader-bar").show().fadeIn('slow');

 },
 success: function (data) {
  console.log(data);
 },
 cache: false,
 contentType: false,
 processData: false
 xhr: function() {  // Custom XMLHttpRequest

  var myXhr = $.ajaxSettings.xhr();

  if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
  myXhr.upload.addEventListener('progress', function (evt) {
       if (evt.lengthComputable) {

    var percentComplete = evt.loaded / evt.total;

    var porcentagem = percentComplete * 100;

    console.log(parseInt(porcentagem)+'%');

    $('#docs-objeto3 #loader-bar .loadbar-label').text(parseInt(porcentagem)+'%');
    $('#docs-objeto3 #loader-bar .progress-bar').width(parseInt(porcentagem)+'%');

    if(porcentagem == 100){

     // window.location.reload(true);
     location.reload(true);
     // document.location.href = 'detalhe-objeto.php?objeto_id='+objeto_id+'&rt=success';
     // $(location).attr('href', 'detalhe-objeto.php?objeto_id='+objeto_id+'&rt=success')

    }

   }
  }, false);
 }
 return myXhr;

 },
 close: function(){

  $("#docs-objeto3 #forms").show();
  $("#docs-objeto3 #loader-bar").hide();

 }
});

}

Note que estou usando o método location.reload(true); que no Firefox funciona perfeitamente, localmente funciona no Chrome e firefox, mas quando envio para o servidor não funciona corretamente no Chrome. Testei outras formas como pode ser visto comentados, sempre o mesmo resultado.
Quando a página é recarregada o novo conteúdo que foi inserido não aprece, tendo que dar F5 mais uma vez para os dados aparecerem na tela, não estou carregando este conteúdo via ajax, ele é carregado via php normal na página. E como o conteúdo não carrega o formulário que deveria sumir, ainda fica ativo possibilitando o envio de mais documentos, mesmo que o envio de mais de um documentos esteja bloqueado este problema passa para o usuário que o doc não foi enviado. Já que a informação não aparece na tela.
Comment: O problema ocorre apenas no Chrome? Já testou pela navegação anônima?
Comment: Apenas no Chrome, já tentei anônima também, mesmo resultado. Estou suspeitando que pode ser do lado do servidor, pois local funciona perfeitamente. De todo modo vou abrir um chamado no server.
Comment: O reload não acontece apenas quando envio um pdf. :(
Comment: Nesses casos é muito importante acompanhar o console do navegador pra depurar o javascript e a resposta do servidor para ter uma noção mais clara do que pode estar acontecendo,
Answer: Por algum motivo que desconheço(se alguém souber), os headers do arquivo chamado não estavam sendo processados antes do redirecionamento, descobri isso enviado um arquivo maior e redirecionou normal. Então adicionei a seguinte linha que ainda precisa ser otimizada.

setTimeout(function(){
  location.reload(true);
}, 3000); //Tempo 3 segundos antes de redirecionar.
Answer: É a melhor solução? NÃO. Mas pode tentar usar para teste:
window.location.href = window.location.href;

Na minha opinião é uma maneira meio porca, mas para teste nos navegadores funciona.
Comment: Usei ela no lugar de `location.reload(true)`, da o mesmo resultado acima. O que deu certo foi usando o `setTimeout()` independente da forma que o redirecionamento está sendo feito..


Django DateTime

Question: I'm using Django and when I retrieve instance (with objects.all()) the models.DateTime are changing so that 7 hours are added.
I'm in the US Pacific time zone and I'm guessing that my DB is defined as UTC I'm using PostgreSQL and I can't figure out where is the setting for time zone.
One other thing I'm also getting this warning:

RuntimeWarning: DateTimeField received a naive datetime  while time zone support is active.

Maybe the two are connected?
Answer: settings.py:
TIME_ZONE = 'America/Los_Angeles'
# database not use UTC
USE_TZ = False

see this

Django DateTime


Evaluating a definite integral with hypergeometric function

Question: I want to evaluate
$$ \int_0^\infty e^{-x} x^{m+1} |{}_{1}F_1 (-n,m,x)|^2dx $$
where $ {}_{1}F_1 $ is the hypergeometric confluent function, that is defined by the series
$$ {}_{1}F_1 (a,b,z)=\sum_{s=0}^\infty \frac{(a)_s z^s}{(b)_s s!} = 1 + \frac{a}{b}z + \frac{a(a+1)}{b(b+1)} \frac{z^2}{2}+\dots $$
Thank you.
Answer: Using the representation of the Laguerre polynomials as hypergeometric functions DLMF,
\begin{equation}
L^{(\alpha)}_{n}\left(x\right)=\frac{{\left(\alpha+1\right)_{%
n}}}{n!}{{}_{1}F_{1}}\left(-n,\alpha+1,x\right)
\end{equation}
the integral can be written as
\begin{equation}
I=\left[\frac{n!}{{\left(m\right)_{%
n}}}\right]^2\int_0^\infty e^{-x}\left[L^{(m-1)}_{n}\left(x\right)\right]^2 x^{m+1}\,dx
\end{equation}
Now, one may use twice the recurence relation
\begin{equation}
L^{(\alpha)}_{n}\left(x\right)=L^{(\alpha+1)}_{n}\left(x\right)-L^{(\alpha+1)}%
_{n-1}\left(x\right)
\end{equation}
to obtain, for $n\geq2$,
\begin{equation}
L^{(m-1)}_{n}\left(x\right)=L^{(m+1)}_{n}\left(x\right)-2L^{(m+1)}_{n+1}\left(x\right)+L^{(m+1)}_{n-2}\left(x\right)
\end{equation}
In the integral, the factor $ e^{-x} x^{m+1}$ is just the  weight for the $^{(m+1)}_{k}$. Developping the square, the cross-products give a vanihing contribution, for orthogonality reasons. With the normalisation factor
\begin{equation}
I=\left[\frac{n!}{{\left(m\right)_{n}}}\right]^2\left[\frac{\Gamma(n+m+2)}{n!}+\frac{4\Gamma(n+m+1)}{(n-1)!}+\frac{\Gamma(n+m)}{(n-2)!}\right]
\end{equation}
which can be simplified as
\begin{equation}
I=\frac{\Gamma(n+1)\Gamma^2(m)}{\Gamma(n+m)}\left( m(m+1)+6n(n+m)\right)
\end{equation}
The extension for $n=0,1$ is simple, with $L^{(m-1)}_{0}\left(x\right)=1$ and $L^{(m-1)}_{1}\left(x\right)=-x+m-1$.


What does the dot over $x$ or $y$ mean?

Question: I am just starting to read up on differential equations. The problem is (in my materials) nowhere is explained what do these dots mean. Can anyone shed some light?
$$\begin{align}&\begin{cases}
\dot x=2x+y ,\\
\dot y=3x+4y. \\
\end{cases} \\
&\begin{cases}
\dot x+x-8y=0, \\
\dot y-x-y=0. \\
\end{cases}\end{align}$$
Answer: It usually means derivative with respect to time. The notation goes back to Newton.
By the way, $\ddot{x}$ is often used in Physics for the second derivative of $x$ with respect to time.
Comment: Yes, if by $x'(t)$ you mean the derivative with respect to time. The dot is kind of "reserved" for derivative with respect to time. In Physics, there will be plenty of derivatives not with respect to time.
Comment: For example, the heat equation can be written $\ddot u=v^2u''$, which is the same as $\frac{\partial^2 u}{\partial t^2}=v^2\frac{\partial^2 u}{\partial x^2}$.
Comment: so this would be the same as `x'(t)`?

What does the dot over $x$ or $y$ mean?


PHP BD error line 72

Question: The error is Fatal error: Call to undefined method stdClass::retrieve_all_accounts() in /home/mjcrawle/public_html/cit0215/assignment5/onlinebanking/viewaccounts.php on line 72
I am not getting any html errors so I will leave that out.
My php code  up to the error is:
<?php

require_once('footer_nav/navigation.inc.php');
require_once('../websiteconfig.inc.php');
require_once('../class/person_class.php');
require_once('../class/database.class.php');

/*Start Session*/
session_start();

$currentMember =unserialize($_session['currentMember']);

/*DataBase*/
$db = new Database;
$conn = $db->connection;
?>

Accounts

<thread>

        Account Number
        Account Balance

<php?
/*Accounts*/
$currentMember->connection = $conn;

this is where I get the error line 72:
$accounts = $currentMember->retrieve_all_accounts();

/* Loop Though Accounts*/
while($account = mysqli_fetch_assoc($account)) {
    /* Retrieve Account Balance*/
$bankaccount = new Bankaccount ($account['BankAccountID']);
$bankaccount->connection = $conn;
$balance = mysqli_fetch_assoc($bankaccount->retrieve_current_balance());

 echo '
' . "\n";
 echo "\t" . '' . $account['BankAccountID'] . '	' . "\n";
 echo "\t" . '$' .   number_format($balance['CurrentBalance'], 2) . '	' . "\n";
 echo '
' . "\n";

}

/*Closed DataBase*/
mysqli_close($db->connection);

?>

Comment: Perhaps there is no such method as retrieve_all_accounts()?
Answer: First, you are using this, in your first portion of code :
<php?
/*Accounts*/
$currentMember->connection = $conn;

If you really copy-pasted this, you have a problem here : this is not PHP code.
Instead, you should have :
<?php
/*Accounts*/
$currentMember->connection = $conn;

Note that a PHP opening tag is <?php and not <php?

Then, your $currentMember variable is set this way :
$currentMember =unserialize($_session['currentMember']);

It seems this makes $currentMember just on container, and not an instance of a class that would have a retrieve_all_accounts() method.
So, when trying to call that method :
$accounts = $currentMember->retrieve_all_accounts();

You get a Fatal error, because there is no such method in your $currentMember object.

PHP BD error line 72


Why these are equivalent?

Question: Situation: operator theory, spectrum of a operator.
We consider this as definition:

$\lambda$ is a eigenvalue if $\lambda x=Tx$ for some $x\ne 0$

but I see someone saying this:

$\lambda x-Tx=0\not \Rightarrow x=0 $ so $\lambda $ is a eigenvalue.

I cannot  see why the latest sentence implies $\lambda$ is a eigenvalue. Some help? Is this a very basic logic problem?
Comment: If $\lambda x-Tx=0$ does not imply that $x=0$, then there must exist some $x\ne0$ that satisfies it. Then apply the first definition.
Answer: The statement "$\lambda x = Tx$ for some nonzero $x$" is the same as "$\lambda x - Tx = 0$ for some nonzero $x$." So if $\lambda x - Tx$ doesn't imply $x = 0$, then there's a nonzero $x$ satisfying the equation, so you're back to the first statement.
It might help to see that both formulations are equivalent to the third formulation

$\lambda$ is an eigenvalue iff $\lambda I - T$ has a nontrivial kernel.
Answer: Note that $P\not\Rightarrow Q$ is the same as $P\land\neg Q$. But still this alternative formulation is ugly in my opinion as one must be careful with the implicit quantifiers.

Why these are equivalent?


Complex Analysis - First Principles Proof of the Chain Rule

Question: I'm trying to prove the chain rule for two complex-differentiable functions, from first principles, meaning a $\delta z$ proof.
We haven't covered Wirtinger derivatives, which keep popping up in various proofs.
I've made a start by making use of the small difference formula:
$$
\lim_{\delta z\to 0} g(z) + \delta z g'(z)  = \lim_{\delta z\to0} g(z + \delta z)
$$
And I know that I could use this to complete the proof, just repeating the process on f, but I'd like it to be more rigorous as this formula is not something that's been presented in the course, I'm just using it as tool in this proof and so I want to be able to fully explain. So this is what I have:
$$
(f \circ g)(z) = \lim_{\delta z\to0} \frac{f(g(z + \delta z)) - f(g(z))}{\delta z}\\
=\lim_{\delta z\to0} \frac{f(g(z)+\delta z g'(z)) - f(g(z))}{\delta z}\\
=\lim_{\delta z\to0} \frac{f(g(z)) + \delta z g'(z) f'(g(z)) - f(g(z))}{\delta z}\\
=\lim_{\delta z\to0} g'(z) f'(g(z))\\
= g'(z) f'(g(z))
$$
So the trouble I'm having is expanding on what happens between line 2 and 3. I can do this for line 1 to 2, using the above formula, but for the next line I'm really stuggling to prove the formula holds.
Am I overthinking this?
Answer: The proof goes the same way as for the real chain rule :
$$
\frac{\mathrm{d}}{\mathrm{d}z}f(g(z)) := \lim_{z'\rightarrow z}\frac{f(g(z'))-f(g(z))}{z'-z} = \lim_{z'\rightarrow z}\frac{f(g(z'))-f(g(z))}{g(z')-g(z)}\frac{g(z')-g(z)}{z'-z} = f'(g(z))g'(z)
$$
by definition of $f'$ and $g'$ (which are supposed to exist).
Comment: This proof does not work because the denominator of the first factor can take the value zero.
Comment: @PaulFrost How so ? The purpose of derivatives is to tackle such expressions as $0/0$ by a limit. Are you making reference to the case where $g$ is a constant function ? But in that special case, $\frac{f(g(z'))-f(g(z))}{z'-z'}$ vanishes straightforwardly because of the numeraror.
Comment: In the real case take $g(x) = x^2\sin\frac 1 x$. This is a non-constant function which has infinitely many zeros clustering at $0 = g(0)$. Thus the limit of the first factor does not exist for $x \to 0$. In the complex case this phenomemon cannot happen. If $g(z_n)= g(z_0)$ for a sequence $(z_n)$ converging to $z_0$, then $g$ must be constant. But this is a highly nontrivial theorem. The chain rule can be proved by elementary arguments.
Comment: See https://math.stackexchange.com/questions/3682308/chain-rule-proof-verification
Comment: @PaulFrost Taylor expansion, that's a way for sure. But note that my expression can be regularized and is not totally invalid (cf. https://en.wikipedia.org/wiki/Chain_rule#First_proof).


output of cat command in newline for every sentense

Question: I am using cat *.txt to for writing output in send mail , but I need each file to be on a separate line.
What is the best way to mange files  appearing on a new line?
Comment: Could you add an example file and what command are you executing?
Answer: Try this:
<code>for i in *.txt; do cat $i; echo; done | your_other_command
</code>


solve system equation: $ 2a^2 - 1 = b, 2b^2 - 1 = c, 2c^2 - 1 = a $

Question: I have this system equation:
$$ 2a^2 - 1 = b $$
$$ 2b^2 - 1 = c $$
$$ 2c^2 - 1 = a $$
From system equation we see that $ a \neq 0 , b \neq 0, c \neq 0 $ , so :
$ 2a^2 - 1 \neq 0 => a \neq \sqrt{\frac 1 2} $ .
Also we can write: $ b \neq \sqrt{\frac 1 2} $ And $ c \neq \sqrt{\frac 1 2} $
But I don't know if this is the answer or I need to find exact numbers that satisfy this system (btw, I found an answer and that's : $a = 1, b = 1, c = 1 $).
Comment: $2x^2 - 1 = \cos(2\cos^{-1}(x))$
Comment: If $a = \cos x$, then $b = 2a^2-1 = \cos(2x)$, $c = 2b^2-1 = \cos(4x)$, $a = 2c^2-1 = \cos(8x)$. You can find the 8 solutions for $a$ by solving the equation $\cos(8x) = \cos(x)$.
Comment: @AlexM. By the fundamental theorem of algebra, a polynomial of degree 8 has exatly 8 solutions in the complex numbers. You can see that the equation $\cos(8x)=\cos(x)$ gives exatly 8 different values for $\cos(x)$ and hence all the solutions are real numbers.
Comment: @Adriano, It is an 8th degree polynomial, so there are at most 8 solutions for $a$. Your graph shows 8 intersections, I don't know why it only lists 5.
Comment: By graphing, it seems there are 8 solutions to the equation $2(2(2a^2-1)^2-1)^2-1=a$. Both $a=1$ and $a=-1/2$ work.
Comment: Thank you for your help, but I need the way of solution not just solutions itself.
Comment: $2(2(2a^2−1)^2−1)^2−1-a=(a-1)(2a+1)(8a^3-6a+1)*(8a^3+4a^2-4a-1)$
Comment: You haven't specified what kind of roots you are looking for: integer, rational, real or complex? The trigonometric approach above will not easily give you the complex roots.
Answer: The given system of equations is symmetric, which means that by substituting the variables in the equations by any permutation of the set $\left (a,b,c \right )$ we get the same system all over again. Using that fact, equality $a=b=c$ must hold.
Now simply by using $a=b$ from the first equation of the system we obtain:
$$2a^2-a-1=0$$ Using quadratic formula we get $a_{1}=1$ and $a_{2}=-\frac{1}{2}$.
Therefore, the solution of the system is:
$$\left ( a,b,c \right )=\left \{ \left ( 1,1,1 \right ), \left ( -\frac{1}{2}, -\frac{1}{2},-\frac{1}{2} \right)  \right \}$$


Why would hitting the ball with the leading edge generate more spin?

Question: I have often heard it said that when brushing the ball, you should hit the ball with the leading edge of the bat for maximum spin. To make this clearer, let's assume we are doing a heavy backspin serve and so we are striking the ball with a downward motion of the bat... people say that if you want to maximise the spin you should strike the ball near the lowest point on the rubber. They may also go on to say that if you hit the ball with the trailing edge of the rubber then the ball will have very little spin. See here for example: https://www.youtube.com/watch?v=LnwhP4hs6pY.
When I've quizzed people about why this should be so they often assume that the ball will somehow be skidding along the rubber gathering rotation as it goes before rebounding and losing contact with the rubber. If the ball is struck near the trailing edge then there is no room for this rotation-gathering process and the ball will not be so spinney.
I have always been sceptical about this explanation and found this video which appears to show that the amount of skidding is tiny - perhaps a quarter of an inch at most.
I have two questions really:

Is it true that brushing with the leading edge of the rubber imparts more spin than the trailing edge?
If so - why?
Answer: I believe for this technique to be effective, the perpendicular contact of the ball needs to be reduced so that the horizontal stroke of the contacting rubber on the ball can be maximized.  This is why sound is also so very important in reading your opponent's amount of spin.
A heavy backspin serve would need to be grazed in such a way like a topspin loop is as opposed to a topspin drive.  They do not sound at all alike and I do believe that even if only a matter of milliseconds, a loop stroke does make contact with the ball noticeably longer than a topspin drive, and the same can be done with backspin, particularly on a serve, just not to the same degree.
As to the idea of producing a less-spinny backspin by making contact further back on the racquet surface, I'm not sure how much difference to the extreme of either edge would make, but I always tend to start my serves further towards the leading edge of the blade regardless of the amount of spin I'm going to put on the ball.
This is a very good question and I think it would be worth researching further.
Answer: when you hit a heavy backspin serve, the movement should not be down. try moving your elbow underneath the ball as if your serving, and then try flicking your wrists when the ball appears to be on the rubber. This will help you practice generating backspin. Backspin serves with downward movement usually end up with little to no spin.
Answer: In my personal experience, spin doesnt get faster with more dwell time on the bat. see this clip of Ma Long's forehand here.

As you can see, he doesnt exactly hit with the leading edge of the bat. He gwenerates even more spin by hitting the ball when his hand is moving at the fastest speed during the swing. My point is, when you want to generate heavy spin. looping is key.
Answer:
Yes it's in principle true, depending on how the racket is moved (see point 2). I used to play table-tennis myself and my coach taught me once a backspin service with the intention to hit the ball at the outermost point of the racket. The serve looked harmless, but when done it right, it had tremendous spin.
The pre-requisite for this is to do a quick, circle-like movement with the racket, rather than going straight. So you have to turn your wrist quite strongly and do a spin move with the wrist as fast as possible. In that case the outer edge of the rubber moves more quickly than inner edge, causing stronger spin on the ball. This does not work if you do a straight movement because the speed is the same on every spot of the racket.
Comment: If the racket is moved in a circle like manner then indeed the tip (point furthest from the handle) will indeed be moving fastest - but that's not agreeing with those that think the *leading edge* causes greatest spin.
Comment: Sigh. Don't know why you were downvoted, but your answer is absolutely correct.


Conexão Flask entre duas Máquinas

Question: Tenho uma aplicação Cliente-Servidor em Flask, executando os dois arquivos na mesma máquina a conexão funciona perfeitamente, mas quando tento executar o cliente em uma máquina diferente, a conexão não é estabelecida. Eu coloco o IP da máquina servidora no arquivo cliente mas não tenho sucesso. Alguém tem ideia do que fazer?
Servidor:
from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

valores = {}

contador = 0

class TodoSimple(Resource):

    def get(self, todo_id):
        #return {todo_id: todos[todo_id]}

        return valores[todo_id]

    def put(self, todo_id):
        global contador, valores
        contador+=1

        #print(contador)

        todos[todo_id] = request.form['data']

        if contador==4:
            contador = 0
            valores['CPF'] = todos['CPF']
            valores['Latitude'] = todos['Latitude']
            valores['Longitude'] = todos['Longitude']
            valores['Velocidade'] = todos['Velocidade']

        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=False)

Cliente:
from requests import put

put('http://localhost:5000/CPF', data={'data': '12345678910'}).json()
put('http://localhost:5000/Latitude', data={'data': '-3.10'}).json()
put('http://localhost:5000/Longitude', data={'data': '-20.4000'}).json()
put('http://localhost:5000/Velocidade', data={'data': '60.5'}).json()

Answer: Documentado no site Flask em "Servidor Externamente Visível" na página Quickstart ( em Inglês ).

Servidor Externamente Visível
Se você executar o servidor, notará que o servidor só está disponível
  no seu próprio computador e não em nenhum outro da rede. Este é o
  padrão porque, no modo de depuração, um usuário do aplicativo pode
  executar o código Python arbitrário em seu computador. Se você tiver
  desabilitado debug ou confiar nos usuários em sua rede, você pode
  disponibilizar o servidor publicamente.
Basta alterar a chamada do método run () para se parecer com isto:
app.run (host = '0.0.0.0')
Isso indica ao seu sistema operacional que escute em um IP público.

Servidor:
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=False)

Cliente:
put('http://0.0.0.0:5000/CPF', data={'data': '12345678910'}).json()
put('http://0.0.0.0:5000/Latitude', data={'data': '-3.10'}).json()
put('http://0.0.0.0:5000/Longitude', data={'data': '-20.4000'}).json()
put('http://0.0.0.0:5000/Velocidade', data={'data': '60.5'}).json()

Altere 0.0.0.0 pelo endereço de IP do servidor, altere no cliente localhost pelo IP do servidor.
Após configurar e ainda não conseguir ter acesso, verifique também se o firewall não está bloqueando a porta 5000.

Conexão Flask entre duas Máquinas