How to remove default mouse-over effect on WPF buttons?

Question: My problem is that in WPF, whenever I try and change the colour of a button's background using triggers or animations, the default mouseover effect (of being grey with that orange glow) seems to take priority.
After extensive searches I'm clueless as to how to remove this effect.
Answer: This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black.
The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown).
<UserControl.Resources>

</UserControl.Resources>

<Button Style="{StaticResource MyButtonStyle}">Hello!</Button>

Comment: You sir are a saint.
Comment: I like that solution a lot. However, the mouse over triggers activates only when the mouse is over the text on the button. I added a textblock with a specified width inside the button to fix that problem.
Answer: Just to add a very simple solution, that was good enough for me, and I think addresses the OP's issue. I used the solution in this answer except with a regular Background value instead of an image.

No re-templating beyond forcing the Background to always be the Transparent background from the templated button - mouseover no longer affects the background once this is done. Obviously replace Transparent with any preferred value.
Answer: You need to create your own custom button template to have full control over the appearance in all states. Here's a tutorial.
Comment: For some reason there's 100 answers about creating custom templates for WPF controls, and they are all unnecessarily wrong. There's no reason to struggle to write 50 lines of template code for a button in order to change 1 thing. All you have to do is in the xaml designer right click the control and create a copy of the template code. VS will create a style from that exact button and you can tweak it from there. Takes literally 2 seconds.
Comment: Thanks, that was perfect. It was more complicated to do than I thought it would be, but it all works well now.
Comment: @TheMuffinMan Fantastic, but do you find it even slightly strange that it takes 50 lines of template code to stop a button from changing the background color on mouse hover? What a stupidly over complicated framework WPF is.
Comment: @Ash Or one could argue it's guiding the user in the direction they *should* be going. If you have a button that requires a new hover state, that's likely a new TYPE of button; perhaps a navigation button, a tray button, etc. If so, you shouldn't be modifying one-off properties for it, it should have its own control or style group. And that's kind of what this makes you do.
Comment: @TheMuffinMan: you truly are *the* man! 10 years of working with WPF and just found out about the "Edit Template" option!
Comment: Ho good so I don't have to go fetch those templates myself in C:\Program Files (x86)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP\10.0.18362.0\Generic\generic.xaml
Best tip ever!
Answer: The Muffin Man had a very simple answer which worked for me.
To add a little more specific direction, at least for VS 2013:

Right-click the control
Select Edit Template => Edit a copy...
I selected 'Application' for where to save the style

From here you can directly edit App.xaml and see the intuitively named properties. For my purposes, I just set RenderMouseOver="False"

Then, in the MainWindow.xaml or wherever your GUI is, you can paste the new style at the end of the Button tag, e.g. ... Style="{DynamicResource MouseOverNonDefault}"/>
Comment: Who is the Muffin Man?
Comment: LOL. He made the second reply to the question-owner-accepted answer. Wasn't sure if you were asking seriously or joking. Hard to tell with a name like Muffin Man.
Answer: This Link helped me alot
http://www.codescratcher.com/wpf/remove-default-mouse-over-effect-on-wpf-buttons/
Define a style in UserControl.Resources or Window.Resources
 <Window.Resources>

    </Window.Resources>

Then add the style to your button this way Style="{StaticResource MyButton}"
<Button Name="btnSecond" Width="350" Height="120" Margin="15" Style="{StaticResource MyButton}">
    <Button.Background>
        <ImageBrush ImageSource="/Remove_Default_Button_Effect;component/Images/WithStyle.jpg"></ImageBrush>
    </Button.Background>
</Button>

Answer: If someone doesn't want to override default Control Template then here is the solution.
You can create DataTemplate for button which can have TextBlock and then you can write Property trigger on IsMouseOver property to disable mouse over effect. Height of TextBlock and Button should be same.
<Button Background="Black" Margin="0" Padding="0" BorderThickness="0" Cursor="Hand" Height="20">
    <Button.ContentTemplate>
        <DataTemplate>
            <TextBlock Text="GO" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" TextDecorations="Underline" Margin="0" Padding="0" Height="20">
                <TextBlock.Style>

                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </DataTemplate>
    </Button.ContentTemplate>
</Button>

Answer: An extension on dodgy_coder's answer which adds support for..

Maintaining WPF button style
Adds support for IsSelected and hover, i.e. a toggled button

examples..
<Button Content="Wipe On" Selector.IsSelected="True" />
<Button Content="Wipe Off" Selector.IsSelected="False" />
Answer: Using a template trigger:


.FindControl() on GridView OnRowDeleted?

Question: I'm trying to FindControl() a HiddenField in my GridView's OnRowDeleted Event.
<code>protected void gridviewPersonPhoto_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
    //string strFileName = (the name of the file that needs to be deleted by System.IO
    //which i will know after I FindControl() the HiddenField in the deleted row that contains the name)
}

<asp:GridView id="gridviewPersonPhoto" DataKeyNames"PersonPhotoId"
    DataSourceId="sqldatasourcePersonPhoto" OnRowDeleted="gridviewPersonPhoto_RowDeleted">
    <TemplateField>
        <ItemTemplate>
            <asp:HiddenField ID="hiddenfieldFileName value='<%#Eval("FileName")%>' />
            <asp:Button ID="buttonDelete" CommandName="Delete" />
        </ItemTemplate>
        <ItemTemplate>
            <asp:Image ID="imgPhoto" ImageUrl='<%# "~/pub/photo/"+(Eval("FileName")) %>'  runat="server" />
        </ItemTemplate>
    </TemplateField>
</asp:GridView>
</code>
Comment: can you give and the html code here ?
Answer: try this code in Row_Deleted Event.
<code> GridViewRow gvRow= (GridViewRow)(((Button)e.CommandSource).NamingContainer);
 HiddenField HF = gvRow.FindControl("hiddenfieldFileName") as HiddenField;
</code>
Comment: This worked, but I soon found an easier solution: string FileName = e.Values[0].ToString(); But it requires me to use Bind instead of Eval though.


Error distributions and consistent and unbiased OLS

Question: If OLS estimator is unbiased and consistent, what does it imply about the distribution of error terms?
In linear regression model:
$ y_i = \boldsymbol{x_i' \beta} + \epsilon_i $
if the OLS estimator of $\boldsymbol{\beta}$ is unbiased and consistent, what are the implications for the distribution of $\epsilon_i$? Mainly, does it imply that the distribution is symmetric?
Comment: No, symmetry is not required, only that $\mathbb{E}\epsilon_i = 0$ and that $X$ and $\epsilon$ are independent (actually, I believe the latter is stronger than required.)  A finite variance is not required, but of course the existence of the expectation is.
Answer: Let's write out the expression for $\hat{\beta}_{OLS}$:
$$\hat{\beta}_{OLS} = (X^TX)^{-1}X^Ty = (X^TX)^{-1}X^T(X\beta+\epsilon) = \beta+(X^TX)^{-1}X^T\epsilon$$
Therefore
$$\mathbb{E}\hat{\beta}_{OLS} = \mathbb{E}[\beta+(X^TX)^{-1}X^T\epsilon]$$
If $X$ and $\epsilon$ are independent, $\mathbb{E}(X^TX)^{-1}X^T\epsilon = (X^TX)^{-1}X^T\mathbb{E}\epsilon$, so, rewriting,
$$\mathbb{E}\hat{\beta}_{OLS} = \beta + (X^TX)^{-1}X^T\mathbb{E}\epsilon$$
and all that is left for unbiasedness is that $\mathbb{E}\epsilon = 0$.
This can obviously be weakened somewhat by noting that as long as $\mathbb{E}(X^TX)^{-1}X^T\epsilon = 0$, we will have unbiasedness, but the assumption that this holds when $\mathbb{E}\epsilon = 0$ does not is typically hard to check or justify, although it can occur.
Symmetry does not appear anywhere in this derivation, nor does the existence or finiteness of of $\sigma^2_{\epsilon}$.
Comment: Math is undeniable. But I was conceptually expecting a symmetric distribution because the average square error function is symmetric. I think it is a happy case of linearity.


URL encoding of en-dash

Question: I had a link:
www.example.com/issues/issue-week-2012–2013/poem1

But it is encoded as:
www.example.com/issues/issue-week-2012%25E2%2580%25932013/poem1

This is an URL alias, the en-dash (between "2012" and "2013") is encoded as %25E2%2580%2593, which shows a 404 error. But when I removed the "25" after each % in the URL manually it works.
Please tell me about the issue?
Comment: @Clive actually that url alias is created by the issue name typed by the client. And i don`t know from where he got this bloody en-dash..:-)
Comment: Where do you see encoded URL which is causing problem ? I mean how is URL alias getting generated ? Using Path Auto ?
Comment: Why do you need an en-dash? Can't you just use a dash and avoid all this?
Comment: And i think % is again got encoded to %25 thats why %E2%80%93(encoded string for en-dash) is being encoded to %25E2%2580%2593
Comment: @AnilSagar yes..and i can`t do anything in that. because it is creating as generated by the user`s input.
Comment: It's strange .. Since using path auto i am unable to replicate above encoding issue.. Path Auto does convert and work with all special characters..
Comment: @AnilSagar So what are you at? Share you point.I am very needy in this situation
Comment: so, What i would like to know is more details so that we can replicate issue and try figure out what's wrong.. With out more details where we can not replicate the issue it's highly impossible to solve your issue.... What exactly user input is when created node content ? What is your pattern setting in path auto ? If you cannot give more details this question will be either closed as "Off Topic - This question was caused by a problem that can no longer be reproduced or a simple typographical error. "
Answer: I think there may be a solution using a RewriteRule in .htaccess.
Imagine I have the url /some-page
Now if I go to /someTESTpage
and I put this in .htacess:
RewriteEngine on
RewriteRule ^(.*)TEST(.*)$ /$1-$2 [L,R=301]

Then it redirects to:
/some‒test

Problems still to solve:
1) In the redirect URL that is an en-dash so is still the wrong url. Not sure how to get it to insert the correct character.
2) When I put a percentage sign in the string to be replace the whole thing stops working. Not sure how to escape a percentage sign in a RewriteRule.
Answer: Got the solution for the bug.
Actually the edit page (node/*/edit) is a secure page (HTTPS) and view page is not (HTTP). So while clicking any URL in the edit page, it will encode that URL in to HTTPS and then to HTTP (if the redirected page is not a secure page).
Here the URL gets encoded twice:
First:
https://example.com/issues/poems-week-2012%E2%80%932013/storyname

And then:
http://example.com/issues/poems-week-2012%25E2%2580%25932013/storyname

This bug can be fixed if the edit page is a normal page (not a secure page). And it seems that this will not make any security breach for the system.

URL encoding of en-dash


Prevent setx to expand an environment variable?

Question: I can add to the PATH variable from the console using the following command:
setx PATH "%JAVA_HOME%\bin;%PATH%" /m

However, when I check the PATH variable afterwards the JAVA_HOME variable has been expanded so that the actual PATH looks like X:\Path\To\Java\bin;... instead of %JAVA_HOME%\bin;.... Is there a way to use setx like I do here without having the JAVA_HOME variable expanded?
Tried using double %% but that just gave me the expanded version with a percentage on each end. Also tried \%, but that just messed it up.
Answer: The command shell escapes with the ^ character, so what you need is to escape the % characters like so: ^%. Try this as a replacement command line:
setx PATH ^%JAVA_HOME^%\bin;"%PATH%" /m
Be careful though, where %PATH% is getting expanded.
EDIT
I think this is a safer way to do it. The first can be pasted right into a command prompt:
FOR /F "usebackq skip=2 tokens=2,*" %i IN (`REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) DO set origpath=%j
SET newpath=^%JAVA_HOME^%\bin;%origpath%
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /f /v Path_ /t REG_EXPAND_SZ /d "%newpath%

And this version can be used in a batch file:
FOR /F "usebackq skip=2 tokens=2,*" %%i IN (`REG QUERY "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) DO set origpath=%%j
SET newpath=%%JAVA_HOME%%\bin;%origpath%
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /f /v Path_ /t REG_EXPAND_SZ /d "%newpath%

In both cases, please test and be careful on production systems. I believe I got all the funky escaping correct, but I may have missed something. Also note the missing trailing " on the end of both line 3's is intentional. You should also be able to modify it to run against remote systems by prepending \\HOSTNAME\ in front of HKEY_LOCAL_MACHINE.
Comment: So existing environment variables in PATH will be expanded as well? Is there a way to avoid that then? Would be nice to *only* append/prepend a value to PATH without changing anything existing in it :S
Comment: I'm not sure if you can do what you're asking with `setx`. What about if you instead read the existing `Path` value from `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment`, prepend your string to it, and write it back?
Comment: Can you do that from the console?
Comment: See my edits above, I think they may be a better approach.


Input1 = input.replaceAll not working

Question: So I have a scanner that takes in a string and saves it to input then I try to do
    input.replaceAll("?/.,!' ", "");

and print the line below to test it but it just doesn't replace anything
    import java.util.Scanner;

    public class Test2 {
        public static void main (String[]args){
            Scanner sc = new Scanner (System.in);
            System.out.print("Please enter a sentence: ");
            String str = sc.nextLine();

            int x, strCount = 0;
            String str1;

            str1 = str.replaceAll(",.?!' ", "");

            System.out.println(str1);

            for (x = 0; x < str1.length(); x++)
            {
                strCount++;
            }
            System.out.println("Character Count is: " + strCount);

       }

    }

Here is the code I am working with. all I need is to replace all punctuation and spaces with nothing.
Comment: you need to put your code inside the `for` loop
Comment: possible duplicate of [String replace a Backslash](http://stackoverflow.com/questions/5596458/string-replace-a-backslash)
Comment: Try this instead:

    `str1 = str.replaceAll("[\\p{Punctuation}\\p{Space_Separator}]", "");`
Answer: This line :
str.replaceAll(",.?!' ", "");

will search the entire string ",.?!' " to be replaced.
The argument of the replaceAll method is a regex.
So, it will surely be better with something like that :
str.replaceAll("[,.?!' ]", "");

Answer: The first parameter must be a regular expression, here alternative character classes [ ... ].
String str1 = str.replaceAll("[?/.,!' ]", "");

or more generalized s=whitespace, Punct=punctuation:
String str1 = str.replaceAll("[\\s\\p{Punct}]", "");

Answer: Unless the characters ,.?! appear together in the input String no replacement will be made. You could use a character class to specify a range of characters
str1 = str.replaceAll("[,.?!' ]", "");

Answer: replaceAll takes a regular expression as the first argument, so it needs to be formatted as such:
str1 = str.replaceAll("[,.?!' ]", "");

More information: http://www.regular-expressions.info/tutorial.html

Input1 = input.replaceAll not working


android studio Arraylist sort by descending order

Question: I have a custom listview which fetch data from firebasedatabase ,question is how im i able to sort my arraylist ex. "1 alexander" , "500 Airene" , "3 Airene","200 Aiexa"
Expected output :
500 Airene
200 Aiexa
3 Airene
1 Alexander
Im fetching and sorting it this way
 FirebaseDatabase database = FirebaseDatabase.getInstance();
        database.getReference()
                .child("Users").child("Displayname")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()){

                            System.out.println(snapshot.getKey());

                            Map<String, Object> map =(Map<String, Object>) snapshot.getValue();

                            for (Map.Entry<String, Object> entry : map.entrySet()){

                                System.out.println(entry.getKey());

                                System.out.println(entry.getValue().toString());
                                Cred = (String) entry.getValue();
                                int numberOfUsers = (int) dataSnapshot.getChildrenCount();

                                UsersNumber.setText("Total Users : "+String.valueOf(numberOfUsers));

                                professions = new String[numberOfUsers];
                                Prof.add(Cred);
                                professions = new String[Prof.size()];
                                Prof.toArray(professions);

                                friend = snapshot.getKey();
                                names = new String[numberOfUsers];
                                Usersname.add(Cred+"  "+friend);
                                names = new String[Usersname.size()];
                                Usersname.toArray(names);
                                names = new String[Usersname.size()];
                                Usersname.toArray(names);

                                customListView=(ListView)findViewById(R.id.custom_list_view);
                                userInfos=new ArrayList<>();
                                Arrays.sort(names, Collections.reverseOrder());
                                //Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
                               // Arrays.sort(professions, String.CASE_INSENSITIVE_ORDER);
                                customListAdapter=new CustomListAdapter(userInfos,MainActivityCustonlistViewnew.this);
                                customListView.setAdapter(customListAdapter);
                                getDatas();
                             //   Toast.makeText(MainActivityCustonlistViewnew.this,String.valueOf(numberOfUsers) , Toast.LENGTH_SHORT).show();

                                customListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                                    //    Toast.makeText(MainActivityCustonlistViewnew.this, "Name : " + names[i] + "\n Profession : " + professions[i], Toast.LENGTH_SHORT).show();

                                    }
                                });

                            }

                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

But when using this code my output is :
500 Airene
3 Airene
200 Aiexa
1 Alexander
Arrays.sort(names, Collections.reverseOrder());
is not working for me may be, because  " number and alphabet" are combine as string"??
Usersname.add(Cred+"  "+friend);
Comment: Right, if you use a generic `Comparator`, it's going to use [natural order](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#compareTo(java.lang.String)). It doesn't know the meanings of the fields inside your `String`. You'd have to write your own `Comparator` for that, pass it as the second argument to `sort()`: [something like this](https://stackoverflow.com/questions/16541314/sorting-an-array-of-string-with-custom-ordering).
Answer: Here is a custom comparator that meets your need:
String[] mArray = new String[] {
        "1 alexander",
        "500 Airene",
        "3 Airene",
        "200 Aiexa"
};

Comparator comparator = new Comparator<String>() {
       @Override
            public int compare(String o1, String o2) {
                String num1 = o1.split(" ")[0];
                String num2 = o2.split(" ")[0];
                return Integer.parseInt(num2) - Integer.parseInt(num1);
            }
 };
 Arrays.sort(mArray, comparator);
 System.out.println(Arrays.toString(mArray));

This outputs:
[500 Airene, 200 Aiexa, 3 Airene, 1 alexander]
This will work assuming that all of your strings has the format: "<integer> <letters>"
Comment: yeheey!! it worked..thank you very much!! ``` I/System.out: [500 Airene, 200 Aiexa, 3 Airene, 1 alexander]```
Comment: @AiexaAlexander if it answers your question mark it as correct!!
Comment: Hi Christilyn my system printout goes like this ```I/System.out: [500 Airene, 3 Airene, 200 Aiexa, 1 alexander]```
Comment: @AiexaAlexander Can you update your post with your new implementation?
Comment: it should be 500 Airene,200 Aiexa, 3 Airene,1 alexander
Comment: @AiexaAlexander make sure you are not calling `Arrays.sort(names, Collections.reverseOrder());` anywhere because that yields you the wrong result you just had.
Comment: oh..okie ill try again
Comment: @AiexaAlexander Glad I could help :D


Split column to multiple rows

Question: I have table with a column that contains multiple values separated by comma (,) and would like to split it so I get earch Site on its own row but with the same Number in front.
So my select would from this input
table Sitetable

Number             Site
952240             2-78,2-89
952423             2-78,2-83,8-34

Create this output
Number             Site
952240             2-78
952240             2-89
952423             2-78
952423             2-83
952423             8-34

I found something that I thought would work but nope..
select Number, substr(
    Site,
    instr(','||Site,',',1,seq),
    instr(','||Site||',',',',1,seq+1) - instr(','||Site,',',1,seq)-1)  Site
from Sitetable,(select level seq from dual connect by level <= 100) seqgen
where instr(','||Site,',',1,seq+1) > 0

Edit2: I see that I have actually had a part working select all the time (I was a crappy tester :(), the above one works but the only problem is that it looses the last Site value but Ill try to work a bit on that..
Edit3: Now its working
select Number, substr(
Site,
instr(','||Site,',',1,seq),
instr(','||Site||',',',',1,seq+1) - instr(','||Site,',',1,seq)-1)  Site
from Sitetable,(select level seq from dual connect by level <= 100) seqgen
where instr(','||Site,',',1,seq) > 0

Comment: possible duplicate of [SQL query to translate a list of numbers matched against several ranges, to a list of values](http://stackoverflow.com/questions/2635930/sql-query-to-translate-a-list-of-numbers-matched-against-several-ranges-to-a-lis)
Comment: Check out my answer to the other SO post I identified as a possible duplicate.  It is a 10g solution to your problem.
Comment: I think I got my select to work a bit better now
Comment: is there a way to do this in SQL Server 2008??
Answer: And the correct answer is.
select Number, substr(
Site,
instr(','||Site,',',1,seq),
instr(','||Site||',',',',1,seq+1) - instr(','||Site,',',1,seq)-1)  Site
from Sitetable,(select level seq from dual connect by level <= 100) seqgen
where instr(','||Site,',',1,seq) > 0

Answer: Did you Try Michael Sofaer's answer to How to best split csv strings in oracle 9i
create or replace function splitter_count(str in varchar2, delim in char) return int as
val int;
begin
  val := length(replace(str, delim, delim || ' '));
  return val - length(str);
end;

create type token_list is varray(100) of varchar2(200);

CREATE or replace function tokenize (str varchar2, delim char) return token_list as
ret token_list;
target int;
i int;
this_delim int;
last_delim int;
BEGIN
  ret := token_list();
  i := 1;
  last_delim := 0;
  target := splitter_count(str, delim);
  while i <= target
  loop
    ret.extend();
    this_delim := instr(str, delim, 1, i);
    ret(i):= substr(str, last_delim + 1, this_delim - last_delim -1);
    i := i + 1;
    last_delim := this_delim;
  end loop;
  ret.extend();
  ret(i):= substr(str, last_delim + 1);
  return ret;
end;

Answer: ------------Create Result Table-------------------------------------------
create table resulTable(
cnumber number,
Site varchar2(1000)
);
------------Create Splitter Procedure--------------------------------------
/Here I replaced numbers for example:  2-78 by s2ss78s for using
DBMS_UTILITY.comma_to_table(it doesn't work on numbers)/
create or replace procedure split_list_to_rows(num number,plist varchar2) as
ptablen BINARY_INTEGER;
ptab DBMS_UTILITY.uncl_array;
begin
DBMS_UTILITY.comma_to_table (
list => replace(replace(CONCAT('s', plist),',',',s'),'-','ss'),
tablen => ptablen,
tab => ptab);
FOR i IN 1 .. ptablen LOOP
insert INTO  resulTable VALUES (num,replace(ltrim(ptab(i),'s'),'ss','-'));
END LOOP;
END;
------------PL/SQL Block To Execute Procedure For Each Row-------------------
begin
for i in (select cnumber,Site from Sitetable)
loop
split_list_to_rows(i.cnumber,i.Site);
end loop;
end;
------------------------See The Result---------------------------------------
select * from resulTable;
Answer: I think you have a max limit of 100 comma separated values which is unnecessary, though probably not harmful in your case.
instead of
from Sitetable,(select level seq from dual connect by level <= 100)

this should work for any number of values (level limited by the max number of commas present).
from Sitetable,(select level seq from dual connect by level <=  (select max((LENGTH(site)-LENGTH(REPLACE(site,',', '' ))) + 1) from sitetable)

Answer: Use cross join:
SELECT Number, SiteNumber
FROM Sitetable
    CROSS APPLY STRING_SPLIT(Site, ',');

Split column to multiple rows


Force JPA to remove NOT NULL flag after boxing the Entity field

Question: I use Hibernate with Java, and at some point I had the following entity (simplified):
@Entity
public class A {
    private int value;
};

I had this class for a long time, and, of course, some rows were added to the database.
But, soon, I changed int to Integer(to support nullable on that column).
Now, it looks like as follow:
@Entity
public class A {
    private Integer value;
};

When JPA creates the column for the Integer it makes column nullable, but when creates column for int, that column has property NOT NULL. And that's the same for all boxed types in Java.
But, when I run my app, JPA doesn't remove the NOT NULL flag from the already defined schema of the table in the database.
I know that I may remove it manually, but, unfortunately, I described very simplified example, and in the real life I have a lot of similar classes with the similar properties.
So, how to force JPA to update the schema correctly and don't loose data already created?
Comment: "schema evolution" is not something covered by current JPA specifications. You are responsible for doing updates to tables that you need, maybe by using your JPA provider to generate the DDL into a file, and then you write an update script to migrate your data
Answer: The problem: Changing the schema definition is potentially dangerous, which is probably why JPA does not support changing existing columns. For example if the column width is smaller than the existing one, it could lead to data loss. Also changing a big table on deployment could mean actually long waiting, until the data gets changed (imagine how long you would wait for your change, if it is made on 20 tables, each of 1mln entries).
Solution: You will have to do that manually. What I do is keep in my source control system an .sql file (or one for each bigger released feature) that contains all DB changes I have made, so that I know what/when I have to change the DB on production.


Get result from cancelled asyncio.gather tasks

Question: I need to get some values from an async generator concurrently, and I also need to handle KeyboardInterrupt correctly so that whenever the application is quit I have a chance to write to disk whatever was retrieved at the moment of the exception. I came up with the following code:
import asyncio

async def some_task():
    try:
        yield 1
        yield 2
        yield 3
        await asyncio.sleep(10000)
    except asyncio.CancelledError:
        pass

async def run_tasks():
    async def _task(gen):
        return [value async for value in gen]

    try:
        result = await asyncio.gather(_task(some_task()))
        return result
    except asyncio.CancelledError:
        # Do something here to get the result from the gathered tasks
        ...

async def amain():
    value = await run_tasks()
    print("Returned", value)

if __name__ == '__main__':
    asyncio.run(amain())

I tried using asyncio.shield but asyncio.gather still throws an exception instead of returning the value from _task
Answer: An exception - be it KeyboardInterrupt or another, will break the functions at the point they occur, and return statements won't be reached. The same takes place for list comprehensions or other expressions: the inner for loop will be cancelled.
But just by unfolding the comprehension in a multi-line for statement, and adding elements one at a time, one gets full control of the flow with try/except blocks, with no other changes needed.
Here, I write an alterantive path with except BaseException:  (just Exception won't catch a  KeybordInterrupt)-  but you can even have a single code path for both exceptions ocurring and normal flow by using the finally clause instead.
(Also, when handling an exception you don´t care about, but just want to perform some action when it occurs, it is important to re-raise it, so code further in the call stack can know what took place)
...
import asyncio

async def some_task():
    try:
        yield 1
        yield 2
        yield 3
        await asyncio.sleep(10000)
    except asyncio.CancelledError:
        pass

async def run_tasks():
    results = []
    async def _task(gen, results):
        # a nested funciton could just use the "results" from the outer scope. parameter included so it can be used in not-nested functions
        async for item in gen:
            results.append(item)

    try:
        await asyncio.gather(_task(some_task(), results))
        return results
    except BaseException:
        # Do this here to get the result from the gathered tasks
        print(f"Something stopped the task. Partial results: {results}")
        raise
        ...
    return results

async def amain():
    try:
        value = await run_tasks()
    finally:
        print("Returned", global_results)

if __name__ == '__main__':
    asyncio.run(amain())

Comment: I actually tried using a queue for this same purpose, so every concurrent task can communicate to the parent task the result as soon as it sees it. In any case I also came up with a solution by adding a `loop.add_signal_handler` to capture SIGINT and just cancelling the tasks, so gather never throws, but I'm not sure how that works, is a subsequent call to `loop.add_signal_handler` going to override the last handler?
Comment: loop.add_signal_handler callbacks replace the last added handler for the same signal: if other code is using the same approach, you can be caught short-handed.
It is possible to write your hander in a colaborative way, if you keep track of other handlers already installed and call then explicitly in your handler - but that does not ensure other players do the same.

Actualy: `try..finally` is both a lot easier and some 2 orders of magnitude more "mundane" code for this kind of thing.
Comment: Using queues would be a nice idea - for sure.
Comment: I agree, I think letting it throw and catch it "naturally" is a better approach
Comment: In any case, for the sake of the op: the problem was not that the task was being cancelled, but rather that a `KeyboardInterrupt` was being thrown from `asyncio.gather` while `asyncio.run` cancels the tasks and also that `gather` does not set the result when that happens: https://stackoverflow.com/a/59291518/2625090


How can I dynamically change the default value for views exposed filter based on the terms weight?

Question: I have an exposed filter in a view is referencing taxonomy terms from specific vocabulary. The operator allows selecting a term as the default value for that filter. What I want to achieve is to dynamically select the default value when the term weight = 0.
This should allow less privileged roles like Content Contributors to set the default value for the exposed filter by changing the order (weight) of the term without the need to edit the views settings.
I tried to research this and so far, it seems the best way to achieve this is by using (hook_views_pre_build) but I just don't know how.
Comment: I don't understand how to reproduce this or how your filters are built and what's dynamic in that.
Comment: @leymannx Sorry for the confusion. I've updated my question and added a screenshot for the exposed filter settings.
Answer: After extensive search and experiment, this code worked for me:
<code>use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_build().
 */

function YOUR_MODULE_NAME_views_pre_build(ViewExecutable $view) {
  if ($view->id() == 'YOUR_VIEW_ID' && $view->current_display == 'YOUR_DISPLAY_ID') {
    // Get the exposed filter for the taxonomy terms.
    $filter = $view->display_handler->getHandler('filter', 'YOUR_FILTER_ID');
    if ($filter) {
      // Query the database for taxonomy terms with a weight of 0.
      $query = \Drupal::entityQuery('taxonomy_term');
      $query->condition('weight', 0);
      $term_ids = $query->execute();
      if (!empty($term_ids)) {
        // Load the first term found with a weight of 0.
        $term = Term::load(array_shift($term_ids));
        if ($term) {
          // Set the default value for the exposed filter to the term's ID.
          $filter->options['value'] = $term->id();
        }
      }
    }
  }
}
</code>
This code will query the database for taxonomy terms with a weight of 0 when the specified view is pre-built and set the default value for the exposed filter to the ID of the first term it finds. If no terms are found with a weight of 0, it will not change the default value.


So now struct can have virtual function and support inheritance ? What difference with classes then ? What the true purpose of information hiding?

Question:
Possible Duplicate:
What are the differences between struct and class in C++

http://www.cplusplus.com/reference/std/typeinfo/type_info/
I guess my "teacher" didn't tell me a lot about the differences between struct and classes in C++.
I read in some other question that concerning inheritance, struct are public by default... I also guess struct doesn't have constructors/destructors...
What are the other differences then ? Do they matter that much ?
And when speaking about private/protected attributes/methods, they aren't accessible at runtime, only because the compiler tells it so at compile time and reports an error, right ? Then comparing those features with classes, what does "information hiding" really bring to the programmer ? Is it here so that when somebody reuse the class, this person won't misuse the class because the private/protected stuff will be reported by the compiler ?
I still struggle with the real purpose of information hiding, it still want to sound in my head like it brings more security in programs, meaning less security breaches, but I'm really confused about the goal of such design in the language... (And I Don't intend to be against C++ in any way, I just to understand in what cases this feature can be interesting or not; if not, that's not a problem, but I just like to know...).
Comment: and your other question is a possible duplicate of [How do I explain loose coupling and information hiding to a new programmer?](http://stackoverflow.com/questions/594698/how-do-i-explain-loose-coupling-and-information-hiding-to-a-new-programmer) and [Abstraction VS Information Hiding VS Encapsulation](http://stackoverflow.com/questions/24626/abstraction-vs-information-hiding-vs-encapsulation). Btw please strive to ask one question per post.
Comment: This sounds like two separate questions. Ask them separately (or read the questions they're duplicates of, of course)
Comment: A third piece of the puzzle: you can make unions of class & struct (as long as they don't have ctor/dtor but the union can have a ctor.
Answer: As far as the compiler is concerned, there is no difference between struct and class other than the default accessibility. They're just two different keywords for defining the same thing. So, structs can have constructors, destructors, base classes, virtual functions, everything.
As far as programmers are concerned, it's a common convention to use struct for classes with none of those things (specifically which are POD), or to go even further and use struct only for classes with no user-defined member functions at all, only public data members. People sometimes mess this convention up, because it's surprisingly easy to think a class is POD when it isn't, but at least they're trying.
In C++, at least, information hiding is absolutely nothing to do with security. Put that right out of your mind. It does not provide any security, except in the same general way that any good coding practice makes for code that's easier to reason about, and hence programmers make fewer mistakes.
The purpose of information hiding is to allow you to change the implementation later, perhaps to remove or rename private members, safe in the knowledge that none of the users of your class, outside the class itself and friends, is referring to them. Obviously it's useful to do exactly that, but less obviously and perhaps more importantly, its useful because it makes explicit in the code what your class's interface is, that you want clients to use, and that users of your class can rightfully expect to work. You can achieve the same thing in principle with documentation, but in practice it's nice for the compiler to enforce the rules.
It's not "secure" because on any given compiler it's possible to work around public/private protection. But if users of your class do that, they're using some grotesque hack, they deserve for their code to stop compiling/working when you change your class, and if they come to you to complain you can laugh at them.
Comment: @gokoon: you didn't ask about the purpose of inheritance, that's a whole other question from the purpose of information-hiding. I'd advise you to stop thinking much about code speed and memory footprint, though. My PC has approximately 10-100 times the speed and memory I usually need, so I can afford quite a lot in return for source that's easier to work with. In the unusual cases where speed or memory use is within a factor of 10 of the danger zone, that's when you spend a lot of time thinking about it. The rest of the time just avoid totally inappropriate algorithms and structures.
Comment: @gokoon: regarding interitance vs. embedding, the main difference is whether you want your objects of type `b` to *actually be* whatever it is that `a` represents, or whether you just want them to *have/use* an object of type `a`. For instance if `a` is `std::fstream`, then is your class `b` a specific kind of filestream (inherit), or is it just that it has a filestream that it uses for some purpose (embed)?
Comment: Well, humorous incongruity. That while you're worried about the overheads of C++, other games programmers are bashing out vast amounts of code that's far less run-time efficient. Actually, though, the reason they do this is so that skilled developers can focus their time optimising the few bits that matter, rather than dispersing their efforts worrying about the whole code base. Even a solo developer should do likewise: most code doesn't need optimisation.
Comment: These are very little advantages... And I still don't understand what is the purpose of inheritance when you can just spawn an object from another class inside it... OOP is really my progamming nightmare... When thinking about code speed and memory footprint I still can't really know what's the purpose, except making the source more "reality friendly"...
Comment: And I'm sorry, I don't know what you mean by, "you can just spawn an object from another class inside it".
Comment: in game programming speed is some kind of vital matter... maybe I'm not yet at the level of making a game with a lot a cpu requirements, but I think about it...
Comment: I meant struct a; struct b { a A; }; here the object is inside, but instead I could have done struct b : public a {}; to just inherit from a... I can do both, and I can't find any advantage...
Comment: Ironically, many high-performance games write a significant amount of code in lua, which is an object-oriented, scripting-style language that typically runs in an interpreter in the game. For the unusual cases demanding high performance (physics engine, graphics manipulation) they break into C++, or into GPU stuff like shader pipelines that I don't understand.
Comment: I don't understand the irony...
Comment: I meant that when you implement code, you answer a problem with a solution. That's what programming is all about. What is bugging me, is that embedding vs. inheriting is just a design or philosophical choice, not a programming one. Also, polymorphism is not really a feature if you constantly require to cast your objects pointers.
Comment: @jokoon: You should not be casting object pointers. If you are, you aren't doing polymorphism right.
Comment: How so? How do you not cast while using polymorphism?


Whether to change a piano teacher

Question: I am a piano adult learner and has been learning piano for five years. I have attained only grade 3 of practical piano and just completed my exams for Grade 5 theory today.
I used to enjoy practicing sight reading for piano and when in doubt I will ask question. The problem now is that my teacher will sometimes show her impatience when I ask her some relevant question on playing a short piece. This has really affected my interest on continuing practicing sight reading. She is still a good teacher compared to the previous teachers who just touch on the topic without going in depth. I will try to explain to her my concerns and if worst come to the worst, I am thinking of finding a better teacher before I end my lessons with her
Should I do this?
Comment: The customer is always right. You are probably paying a good bit of money for piano lessons - at least they are not cheap in my area. For that much, you should be very satisfied with what you're getting. I say move on, unless there are really very few teachers in your area at all. Instead, you could politely raise your concerns with your teacher and see if you can adjust the relationship to make it more mutually beneficial.
Comment: A teacher who is impatient is not a good teacher in my eyes.
Comment: "Should you do this" is really a matter of opinion, and can't really be answered here. Maybe change it to "What should I consider or try before changing teachers," which is what the best answers here reflect anyway?
Comment: You have your own objectives, and it's your own money you are spending,  but I can understand that a teacher might feel a bit frustrated that you apparently "want to sight-read" but your playing actual technique is progressing rather slowly (3 grades in 5 years, not about 3 years). Maybe you should think about whether your enjoyment of sight-reading would be greater if you improved your technical skills first. But in the end it's your decision, not mine.
Answer: I believe that is a decision you will have to make yourself after taking everything into consideration.  It is impossible for anyone on this site to really gain a complete understanding of the whole situation in its entirety given the limitations of the site.  What I mean is there are so many factors to consider that it would be cumbersome for a site like this to provide a format wherein all the relevant information could be properly ascertained.
Having said that - I will note that a good match between teacher and student is vitally important and can make a difference in the velocity of your progress.  I have known many piano students and guitar students who grew disenchanted with their original teacher and switched to a different teacher with a different teaching style and reported that the new teacher was a much better fit for them.
Factors that may matter include teaching style and methods as well as personality.  Are you comfortable with your teacher's approach to teaching?  Are you comfortable with the pace (how fast you are expected to advance)?  Does your teacher challenge you to make progress at a level that you are comfortable with?  Do you feel that your teacher is not challenging you enough?
Some of the factors that may influence your satisfaction may be a matter of negotiation.  In other words - talk to your teacher (as you suggest you will) and let her know what your goals are and how well you feel those goals are being addressed in the lessons.  Let her know how you feel about her attitude and how you feel her impatience and how it affects your attitude about your lessons.
It appears from your question that you have changed piano teachers at least once already and seem to find your current teacher superior in at least some ways to others.  That does not mean she is the best teacher for you going forward.  But on the other hand, you have seen that there are certainly teachers out there who are worse (for you).
There is no guarantee that switching will result in a better experience for you.  But then on the other hand it could. I would start with communicating your needs to your current teacher and see if she responds favorably.  If you continue to feel frustrated to the point that you no longer enjoy your lessons or worse, you start dreading your lessons, it might be time to start looking for a new teacher.
You want a teacher who will help you continually improve, is able to prescribe a learning program that works for you (based on your learning style), is willing to understand your personal goals and tailor the lesson plan and frequency accordingly, and whose personality and level of patience contributes to a comfortable and enjoyable experience for you.
Good luck and mostly have fun as you improve your skills.  Music is supposed to be fun!
Comment: Hi Rockin Cowboy, thank you very much for your advice.  After reading your comment, it is a really simple decision to make !
Answer: It seems that your teacher may be getting as frustrated at your (rather slow) progress as you are with her.  Sure, try a different teacher.  Just tell her you're going to, in a straightforward manner.  No need to make a speech about why.
Comment: Sure, tell her why.  Clearly and briefly.  But no need for the sort of strategy we sometimes see discussed, which usually boil down to telling a pack of lies!
Comment: As a teacher, I value knowing reasons why a student ceases to have lessons with me. It gives me better ideas as to how I could accommodate pupils better.
Answer: There's something about 'better the devil you know'. We don't know if you've been with her for most of that 5 yrs, but an average rate of exam taking is around one grade per year. It seems you are mostly concerned with her approach to you sight-reading. The very best way to go forward with sight-reading is to do it in the presence of a teacher, who should help you through the tough bits and be capable of steering your reading in the right direction  - something that's almost impossible by yourself. On your own, how do you know if you've sight-read a piece accurately?
In fairness to both of you, there needs to be a heart-to-heart conversation. You probably give her money in exchange for lessons. A fair deal is only reached when both parties are happy with their end of the deal. It could even be that she's not happy with you as a pupil, and has her way of showing this. With all the cards on the table, honesty will shine through, and you'll both know where you stand. Things could change in that she understands that you haven't grasped something, and will try harder to teach more effectively, and/or you might try harder to be a better pupil. Speak!
Answer: You have had this teacher for five years, without issue? Perhaps you have hit an obstacle you are having trouble communicating to your teacher. It is not a sin for a teacher to become frustrated, however you are paying for a service. Perhaps you could arrange a meeting with your teacher to discuss the issue away from the instrument.
Answer: Is there any consistent aspect to the questions she is impatient about that might help you to diagnose what is going on?
The existing answers have some great advice and here are some other explanations:

Perhaps you are asking about areas that your teacher herself feels less equipped to answer;
Perhaps she feels that your questioning is getting in the way of your playing - sometimes we can play something long before we understand how.

In either case (or the explanations in the other answers) this is not necessarily the end of the line. You say "this has really affected my interest on continuing practicing sight reading" which is definitely a problem, but it may be a problem that you can change without changing your teacher 'just' by changing your attitude. There is a time for asking questions and a time for playing, perhaps your intellectual desire to understand is overwhelming the more child-like have-a-go side of your learning?
Ideally you'd be able to chat this through with your teacher but even if you cannot, and her attitude saps your interest in sight reading, her other strengths may still outweigh those problems. Only you can know that.
I once attended a klezmer workshop in Cambridge (ye olde, not MA). The tutor rudely refused to answer any questions and got visibly irritated if anyone asked one. At first this really annoyed me - how mad is it to run a workshop in a small city famed for its 800 year old university and not expect question-loving-intellectuals to attend? But then I thought that I'd just get on with it and forgive her, and thereafter I got much more out of the workshop which focussed on playing by ear (not something I'd learnt before).
Comment: Good answer, +1. Your point 1 - she should do more homework herself. I had to!!   Point 2 - some folks need to understand, others definitely don't. Want to or need to!
Comment: Thanks. I guess I feel that if you think you are, like me, a person who needs to understand then try this experiment: learn something without understanding it. You may find that as a result you grow as a musician. This isn't a general rule, just something to play with.
Comment: I did that as a kid for years, and generally played like a parrot because of it. Only when I understand can I build on what I know.

Whether to change a piano teacher


How wide can a unit-length planar curve be?

Question: The width of a bounded set in the plane is the minimum distance between two parallel lines bounding the set.
Suppose that we have some curve $C: [0,1]\to\mathbb{R}^2$ of unit length. How large can its width be? Equivalently, if we would like to bend a wire into a shape of unit width, how much wire do we need? (I'll use the latter framing in this post because it makes the numbers a little nicer.)
If one tries forming the wire into a circle or semicircle, $\pi$ units of length are needed. All but one of the sides of a unit square only takes $3$ units. Using $270$ degrees of a circular arc one can do better, with length $\frac{3\pi(2-\sqrt{2})}{2}=2.7604\ldots$.
After playing around with different natural options for a bit, the winner appears to be $\frac{4}{\sqrt{3}}\approx2.3094$, given by forming the wire into a $60$-degree angle so that its convex hull is the equilateral triangle of width 1.
However, it turns out that this is not optimal! Consider the following construction: Fix $0.5<x<\frac{\sqrt{3}}{2}$. Start with the triangle formed by the points $(0,1), (-x,0), (x,0)$. Then, add the circular arcs of radius $1$ from each of the latter two points as they pass through the opposite side of the triangle. Take the convex hull of these three points and two circular arcs, and omit the line segment of length $2x$ at the bottom; the resulting set is our wire.

Above is a diagram of this construction: the original triangle is marked in blue, the circular arcs (of which only part make it to the convex hull) are marked in red, the straight-line tangents to said arcs are in black, and the portion of the convex hull not on the wire is marked with a dashed line.
It is fairly easy to see that this construction has width $1$, and that the resulting length is
$$2\left(x+\sqrt{4x^2-1}+\arctan(1/x)-\arctan(x)-\arccos(1/2x)\right)$$
As it turns out, this function is minimized around $x=0.521795$, with a wire length of around $2.2783$. (In fact, the derivative of the above function is a rational function, so we can be more precise: $x$ is the unique positive real root of the polynomial $3x^6 + 9x^4 + x^2 - 1$.)
Is this construction optimal? I do not believe there are any obvious local improvements one can make, but it's possible that a radically different wire shape could improve on this configuration.
Obviously, there is a lower bound of $1$ on the length of any solution, and by considering the width in two orthogonal directions one can increase this to $\sqrt{2}$. It's tempting to say that the length must be at least $2$, because there must be a point at distance $1$ from the midpoint of the wire, but this only follows if one makes the assumption that the wire lies on the boundary of its convex hull, which I cannot see a good way to justify.
I would be curious to see any improved lower bounds, better solutions than the one given above, or pointers to discussion of this question in the literature.
Comment: A simple lower bound is $\sqrt 5=2.236\dots$ and it is easy to see that it cannot be attained, so your construction is, most likely, optimal. However I cannot prove it at the moment.
Comment: Reminds of both the Moser's worm problem and Reuleaux triangle.
Comment: Interesting problem! As a final outcome I found for the length of wire: $\,\arctan(3/4) + 1/2 \approx 2.2870\,$, which is slightly above your $\,2.2783\,$. I have not been able to improve my outcome, though. Besides this, I'm preoccupied of [detailed explanation](http://www.alternatievewiskunde.nl/jaar2021/2021feb20.htm)s :-)
Comment: @IvanNeretin: +1.  Yes to Reuleaux triangle, but where we don't need to close the figure.  At first glance, it seems to involve some kind of minimal figure of constant width, but I don't think it is, quite, since closing the figure uses up more wire (shrinking the scale), then is worth the while.
Comment: What about a broken line resembling the teeth of a saw. Taking $m$ "tooth" of side $2m$  each,the curve has lenght $1$.
Comment: @Piquito: I don't understand your construction; can you link to a diagram? If by "broken" you mean "discontinuous", then I am not permitting such constructions, as they can be made arbitrarily short.
Comment: Sorry dear friend.it is difficult for me to write in English what i want to mean.
Comment: @fedja: Interesting! Could you elaborate on that lower bound? If you wrote it up into an answer, I'd rather award it the bounty than let the 50 reputation go to waste.
Comment: @RavenclawPrefect OK, done. I will still think of it a bit more and update my answer if I have any bright ideas :-)
Comment: Oops, must be twice that outcome: $2\arctan(3/4)+1$.
Answer: A simple lower bound is $\sqrt 5>2.236$. Just choose the $x$-axis along the line joining the endpoints and $y$-axis perpendicular to it. Then, if your wire is $(x(t),y(t)), t\in I$, we must have $\int_I|y'(t)|dt\ge 2$ (you make a swing of width $1$ in the $y$-coordinate but you have to return to the start) and $\int_I|x'(t)|\ge 1$, so $L=\int_I\sqrt{x'(t)^2+y'(t)^2}\ge\sqrt{2^2+1^2}=\sqrt 5$.
Comment: @RavenclawPrefect Yep. That is a fine way too. It looks like it might be possible to prove that your construction is optimal at least among the curves that lie on one side of the line joining the endpoints (though I still need to iron out some details) but the possibility to swing both ways still gives me trouble (though intuitively it is clear that it should be a losing configuration).
Comment: @DaniloGregorinAfonso Rectifiable will work for that argument too, but, as you correctly said, it is, indeed, irrelevant. You may think it is a broken line, if you want, just show an inequality for such case and pass to the limit to get the general bound.
Comment: Ah, I see - thanks! A more intuitive way to see this for me is to imagine reflecting portions of the curve along the $x$ and $y$ axes so that one "straightens it out" to point northeast; then it must travel from $(0,0)$ to at least $(1,2)$.
Comment: Arent you assuming that the curve is differentiable everywhere? And, as I understand, that is not really a constraint. I have the same question as Han de Bruijn in another "answer"


If performance is not a issue software vs hardware raid

Question: If performance is not a issue what makes hardware raid better then software raid.
so far i have drawn the following conclusions.
Hardware raid is limited to the raid controller if that pacs up you need another of the exact raid controllers, Where as if your server or OS pacs up with software raid you can switch all the disks to another computer and use the exact same OS.
What are your guys view on the matter since so far thats the only benefit of hardware raid that i have found out.
Comment: Keep in mind that some of the new filesystems (ZFS, and someday BTRFS) solve some of the problems which occur with older software RAID methods. The "Copy on Write" and "full-stripe writes" features in ZFS ensure that the data is written to the disk atomically, which means that a battery backed cache (and therefore, a hardware RAID card) isn't always necessary.
Answer: Your question basically encapsulates my philosophy.
I prefer hardware RAID controllers in "enterprise" deployments. If I know I'm going to have warranty, spares availability, and vendor support I'd typically rather have the performance and features of hardware RAID.
In small business scenarios where the likelihood is that the Customer is going to let support lapse I'd rather take the (increasingly very slight) performance "hit" and go with software RAID (typically RAID-1 in small businesses I work in, anyway). This is typically cheaper than a hardware solution. In the end, I'd rather have some kind of protection against disk failure than none at all.
As you say, with software RAID I know I'll be able to read the disks using the same software RAID implementation on any other computer without a special controller. Typically the Customer isn't pushing the performance envelope of their server and doesn't need fancy features so they end up losing nothing and gain some ability to recover in the event of catastrophic failure of the server computer.
Software RAID performance has gotten quite good in the last few years, but I've been using it in small deployments all the way back to Windows NT 4.0 with good results. It's a cheap insurance policy.
Comment: thanks for your input i am working in a small business environment so i was thinking software raid is the way to go.
Answer: There are two major benefits to hardware RAID:

Performance.  If that's not a consideration, don't consider it.
Battery-Backed Cache.

2 really goes hand-in-hand with 1, but it also plays a role from a data integrity standpoint: Let's consider two identical machines, one with Software RAID, one with a battery-backed hardware RAID, both with write cacheing enabled.
If we write a whole bunch of data to these two machines, then rip the plug out of the wall before the data is sync'd to disk (by the OS on the software RAID box, or the controller on the hardware RAID box), we now have two different scenarios:
The Hardware RAID machine will, when power is restored, see that there are writes in the cache, spin up the drives, sync the data to disk and move on with its life.
The Software RAID machine will, when power is restored, reboot normally. Since the system RAM lost power the writes that were stacked up waiting to be flushed out to disk are gone forever.  The results here could range from inconvenient (a little data loss) to catastrophic (the partition table has been eaten, vital irreplaceable data has been left in a half-written, corrupted state, etc.).

Now that I have portrayed the nightmare scenario, consider the likelihood of it happening.  Presumably your server is on a UPS, ideally with redundant power supplies fed from different UPS circuits.  The chance of a catastrophic failure in that scenario is relatively low, and you may be fine trusting software RAID here.
In exchange for taking that (theoretically small) risk you aren't beholden to a particular brand of controller and revision of the controller firmware in the event something goes horribly wrong, and you have the flexibility afforded you by software RAID (which often includes mirroring only part of a drive, or being able to mirror across drives of different sizes, spindle speeds, etc. -- Possibly a consideration if you have Frankenstein hardware).
Comment: ye thing is that i got 2 huge UPS with battery packs that should last a hour and then onsite generators that take 15 min to kick in, so ye it is a small/medium sized business so we looking to reduce costs on a new file server i mean user's dont need to access data at lightning speeds so performance is not a issue and we have daily rotating bakcups aswell as ounce a week we swap out a nas that gets backed up at the managers house to another nas =D just trying to make a final decision, thanks for your input
Comment: Reducing costs? Hardware raid is going to cost what another £300 on the cost of a server, over a 5 year life they're saving £60 a year? Is it worth it to save £500?
Comment: @ITHedgeHog - It actually can be a substantial cost savings - Our analysis servers can't be virtualized (they're CPU-Heavy), but don't really need fast disks, just fault-tolerance in case one fails.  We build them with software RAID and tiny slow hard drives to the tune of about USD$400 less per box.  Build five machines and the 6th is effectively free :-)
Comment: well the cheapest raid card i can get is 500Euro unless i ship got a very small selection that i can use since i live in south Africa. And also that 500 Euro could be to more ram or hard drives or upgrading the CPU to take on the extra task. I really currently dont see unless you got a huge budget to spend why small companies would go for hardware raid unless there going for Branded servers that come with raid cards.


Solving Stochastic Differential Equation using integrating factor

Question: Now I try to solve the following stochastic differential equation:
$$
\frac{dX_t}{X_t} = \left(-1+\frac{1}{2}t + (\beta - 1)\frac{X_t-1}{t}\right) dt + \alpha dB_t,
$$
where $\alpha, \beta$ and $X_0=x_0$ are some constants.
Here what I have tried.
By multiplying integrating factor
$$
  F_t = \exp(-\alpha B_t + \alpha^2 t / 2),
$$
we have
$$
\frac{dY_t}{dt}=F_t F_t^{-1} Y_t \left(f'(t) + (\beta-1)\frac{F_t^{-1}Y_t-1}{t} \right)  \\
 = \left\{ \left(-1+\frac{1}{2}t-\frac{\beta-1}{t}\right) + (\beta - 1)  e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{Y_t}{t} \right\} Y_t
$$
for $Y_t=F_t X_t$. Then this equation is just a deterministic differential equation.
For the homogeneous equation, we can use seperation of variable to solve
$$
\frac{1}{Y_t}\frac{dY_t}{dt} + (1-\beta)e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{Y_t}{t}=0
$$
with
$$
Y_t=\left((1-\beta)\int e^{\alpha B_t - \frac{\alpha^2}{2}t}dt + C\right)^{-1}.
$$
But for the inhomotegenous equation
$$
\frac{1}{Y_t}\frac{dY_t}{dt} + (1-\beta)e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{Y_t}{t}=-1+\frac{1}{2}t-\frac{\beta-1}{t},
$$
I have trouble to solve.
Can anyone help me with the above SDE?
Comment: What is exactly $\beta_t$ ?
Comment: $\beta$ is just a constant like 0.5. If you mean $B_t$, it is one path of standard Brownian motion.
Comment: I see then your equation is a Bernouilli's equation
Answer: $$\frac{dY_t}{dt}= \left\{ \left(-1+\frac{1}{2}t-\frac{\beta-1}{t}\right) + (\beta - 1)  e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{Y_t}{t} \right\} Y_t$$
Looks like a Bernouilli's equation of the form
$$y'+\alpha(t)y=\beta (t) y^n$$
Here you have $n=2$. Divide by $Y^2(t)$ both side.
$$\frac{dY_t}{dt}\frac 1 {Y^2_t}= \left\{ \left(-1+\frac{1}{2}t-\frac{\beta-1}{t}\right)\frac 1 {Y_t} + (\beta - 1)  e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{1}{t} \right\} $$
Then substitute $Z(t)=\frac 1 {Y_t}, Z'(t)=-\frac {Y'_t} {Y^2_t}$.
$$Z'(t)+ \left(-1+\frac{1}{2}t-\frac{\beta-1}{t}\right)Z(t)= -\left\{ (\beta - 1)  e^{\alpha B_t-\frac{\alpha^2}{2}t}\frac{1}{t} \right\} $$
The equation is now a first order linear DE. Use any techniques you know to solve it ( integrating factor ). But it's not going to be easy to integrate not because of the DE but because od the functions that  are really complicated.


The app is closed when I click the button

Question: Hi this is my first question here.
MainActivity.java
package com.example.kerry.chellenge04;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText)findViewById(R.id.text);
    }
    public void button(View view){
        String string=name.getText().toString();
        Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="288dp"
        android:layout_height="346dp"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        tools:layout_editor_absoluteY="8dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="button"
        android:text="Button"
        tools:layout_editor_absoluteX="58dp"
        tools:layout_editor_absoluteY="401dp" />

</LinearLayout>

It's very simple code. When I press the button, the app is supposed to show you what you typed in edittext, but it stops. Can you guys please tell me what the problem is?
Comment: set android:id="@+id/text" to your `EditText` in `activity_main.xml`
Comment: No Id for EditText. Please give it ID
Comment: Where is id for `text`?
Answer: You need to assign an id to your EditText:
android:id="@+id/text"

otherwise this line:
name=(EditText)findViewById(R.id.text);

will assign null to name.
So when you try to access any property or method of the object name
a Null Pointer Exception will be thrown and your app will crash.
Comment: wow it works after I modified. I put Id on design tab and I thought It's weird that there is no id in text. I should've tried adding it beforehand thank you so much
Answer: Try this one
You need to assign an id to your EditText:
<EditText
    android:id="@+id/text"
    android:layout_width="288dp"
    android:layout_height="346dp"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    tools:layout_editor_absoluteY="8dp" />

Comment: wow it works after I modified. I put Id on design tab and I thought It's weird that there is no id in text. I should've tried adding it beforehand thank you so much
Comment: @KerryLee Thank you, Happy to help you.
Answer: you should you the activity context rather than the application context.
try to replace
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show();
with
Toast.makeText(view.getContext(), string, Toast.LENGTH_LONG).show();
then, as already said, you should add the id, but I believe you did, as you can access the generated R.id.text


Championship points decided by a net cord?

Question: In 1988, Boris Becker dramatically beat Ivan Lendl in 5 sets in the Masters tournament at Madison Square Garden. The final set went to tie breaks, ending with a backhand net cord by Becker.
Have there been other major tournaments where the championship point was decided by a net cord shot?
Answer: Yes, there have been a few instances of the net cord deciding championship point in both the Men's and Women's tours:
ATP

Final - CA-TennisTrophy (Vienna) 2002, Roger Federer vs. Jiří Novák - The 21 year old Federer claimed his 8th title by striking a forehand which clipped the tape and fell on the side Novák.
6–4, 6–1, 3–6, 6–4
Final - Miami 2006, Roger Federer vs. Ivan Ljubicic - To cap off a thrilling final that went into a tiebreak all three sets, Roger ended it with a lucky net cord on the return.
7-6(5), 7-6(4), 7-6(6).
Final - Gerry Weber Open 2010, Lleyton Hewitt vs. Roger Federer - The three set final victory ended in a mid-rally net cord that fell the way of Hewitt at the gasp of the crowd. This victory broke a 15-match losing streak against Federer for Hewitt, and was the first time Federer had lost since 2002 in Halle.
3–6, 7–6(4), 6–4.
Final - Gazprom Hungarian Open 2018, Marco Cecchinato vs. John Millman - The net cord shot was struck by the eventual champion and 1st time ATP Tour tournament winner Marco Cecchinato.
7-5, 6-4.

WTA

Final - Wimbledon 1988, Steffi Graf vs. Martina Navratilova - In what proved to be a hard fought match, Graf pulled it out against then 6-time defending champion on a net cord return. Graf's slam victory proved to be a crucial one as it was the penultimate slam that enabled Graf to achieve the only Calendar Year Golden Slam in tennis history.
5–7, 6–2, 6–1.
Final - St. Petersburg Open 2019, Kiki Bertens vs. Donna Vekic - On her 4th championship point, Kiki Bertens was able to strike a backand that clipped the tape, and proved to be too great of a distance for Donna Vekic to run down.
7-6, 6-4.


How to benefit from playing a racquet game with a player on a much lower level?

Question: Suppose you're teaching a beginner how to play (let's concentrate on various racquet games for that matter).
Do you have some tips on how the more experienced player can also benefit on some level from such games? A squash player once told me that one idea is to play with one's non-dominant hand, although I'm not sure what benefit would one get from that, (except perhaps in tennis, for the two-handed backhand), apart from the challenge/developing general dexterity (which I do find fun, but wondering whether there's more to that).
Are there any additional tips?
Answer: My answer addresses tennis.
Perhaps the most important advice is mental. If you want to improve, do not have an arrogant or superior mindset on court. Focus on improving yourself.
If your partner is not able to consistently return your balls, you are essentially limited to polishing your own footwork, technique, accuracy, and feel.
Otherwise, there are many additional things you can practice - depending on your own level. For low-level players, I suggest focusing on technique, footwork, and accuracy. For mid-level players, force yourself to work on the strokes you're less comfortable with e.g volleys, slices etc. Eliminating gaping weaknesses is the main obstacle to becoming a high(er)-level player. When you feel more-or-less comfortable everywhere in the court, work more on your feel.
If you are a high-level player you will find it surprisingly difficult to play normally against much weaker opponents, since you'll have far less pace to work with. Given that you will have ample time to think on court, I suggest thinking about the mechanics of your strokes. From my experience, this is very helpful in quickly making the necessary adjustments against different players e.g lefties, big hitters, pace changers etc. Apart from this, you should know what it is you need to be working on.
Answer: The more experienced player could benefit in this scenario by seeing if the less experienced player is open to suggestions on how to improve. The process of passing along knowledge this way helps the experienced player to mature, because knowing something and being able to impart it are two different things.
Further reading


O que significa quando o console retorna a própria função?

Question: Editado. O console está retornando a própria função como resposta, não o resultado da função.
O objetivo é que a função diga se um valor é ou não maior que o outro.
let primeiraVariavel = 34;
let segundaVariavel = 10;

function resultado() {
 return primeiraVariavel > segundaVariavel ? "verdadeiro" : "falso";
}
console.log(resultado);

Answer: Porque você explicitamente está mandando exibir a função:
console.log(resultado);

E não o retorno dela. Para exibir o retorno você precisa efetuar a chamada da função:
console.log(resultado());
// ------------------^^

Assim será exibido verdadeiro.

let primeiraVariavel = 34;
let segundaVariavel = 10;

function resultado() {
 return primeiraVariavel > segundaVariavel ? "verdadeiro" : "falso";
}

console.log(resultado());
Answer:
console.log(resultado); substitua por console.log(resultado());

Quando você não coloca o "()", você faz apenas referência e não chama a função.


Airplane travel with heavy music gear

Question: I have Pioneer DJ mixer that weighs 17 lbs.
along with an oddessey case that weighs 36 lbs.
And I want to dj for my cousin's wedding which is overseas but I'm not sure what would be a good way to bring the heavy music gear there.
One thought was to downgrade the mixer case to a mixer bag.
Any recommendation from experts musicians who carry heavy toolset overseas?
Comment: Is it possible to rent equipment in the country which you plan to play?
Comment: Maybe you should ask this in the "travel" section, but anyway, I think that it depends on every airplane company. In some of them you can pay some extra charges to put them in a safe place, with other music instruments or bikes, pets etc... Otherwise, I have no idea.
Answer: I've never done this before -- my one time taking an instrument during travel, it was a POS acoustic I cared nearly nothing about -- but when I see musicians talk about short-trip travel, they tend to bring an instrument and a pedalboard and rent a back-line. I'd look into renting a DJ rig rather than travelling with your own.
Answer: You could rent the equipment rather than taking it on the plane. Check out https://www.sparkplug.it. It's an instrument rental marketplace where you can rent gear from another musician.

Airplane travel with heavy music gear


How do I set images from gallery to slider?

Question: I have one fragment, there is an imageView and 2 buttons (previous and next). So in that imageView I'm adding the first picture from gallery. Then clicking next I want to see the next image from gallery. The path of images I already got.
Let me show you the code.
public class PhotoFragment extends BaseFragment{
View mainView;
private ImageView photoView;
private Button prev, next;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate(R.layout.photo_fragment, container, false);

    photoView = (ImageView) mainView.findViewById(R.id.photoView);
    prev = (Button) mainView.findViewById(R.id.prevPhoto);
    next = (Button) mainView.findViewById(R.id.nextPhoto);

    getAllShownImagesPath(getActivity());
    return mainView;
}

ArrayList<String> getAllShownImagesPath(Activity activity) {
    Uri uri;
    Cursor cursor;
    int column_index_data;
    final ArrayList<String> listOfAllImages = new ArrayList<>();
    String absolutePathOfImage;
    uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    String[] projection = {MediaStore.MediaColumns.DATA,
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME};

    cursor = activity.getContentResolver().query(uri, projection, null,
            null, null);

    column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
    while (cursor.moveToNext()) {
        absolutePathOfImage = cursor.getString(column_index_data);
        listOfAllImages.add(absolutePathOfImage);
    }

    Bitmap myBitmap = BitmapFactory.decodeFile(listOfAllImages.get(0));
    photoView.setImageBitmap(myBitmap);
    photoView.setRotation(90);

    Bitmap myBitmap1 = BitmapFactory.decodeFile(listOfAllImages.get(1));
    Bitmap myBitmap2 = BitmapFactory.decodeFile(listOfAllImages.get(2));
    Bitmap myBitmap3 = BitmapFactory.decodeFile(listOfAllImages.get(3));
    Bitmap myBitmap4 = BitmapFactory.decodeFile(listOfAllImages.get(4));
    Bitmap myBitmap5 = BitmapFactory.decodeFile(listOfAllImages.get(5));
    Bitmap myBitmap6 = BitmapFactory.decodeFile(listOfAllImages.get(6));

    final ArrayList<Bitmap> bitmap = new ArrayList<>();
    bitmap.add(myBitmap);
    bitmap.add(myBitmap1);
    bitmap.add(myBitmap2);
    bitmap.add(myBitmap3);
    bitmap.add(myBitmap4);
    bitmap.add(myBitmap5);
    bitmap.add(myBitmap6);

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

        }
    });

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

        }
    });

    cursor.close();
    return listOfAllImages;
}

You see here I'm getting the first image and setting it in imageView.
Bitmap myBitmap = BitmapFactory.decodeFile(listOfAllImages.get(0));
    photoView.setImageBitmap(myBitmap);

But I can't do the sliding part. How can I do this?
Answer: int imagePosition = 0;

next.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          imagePosition++;
      photoView.setImageBitmap(BitmapFactory.decodeFile(listOfAllImages.get(imagePosition)););
          photoView.setRotation(90);
        }
    });

prev.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          imagePosition--;
      photoView.setImageBitmap(BitmapFactory.decodeFile(listOfAllImages.get(imagePosition)););
          photoView.setRotation(90);
        }
    });


Gettext and locales

Question: I heard from a relatively trustworty source that gettext doesn't require system locales for it to work. But I have tried a few tutorials, and unless I have locale-gen'd (in arch) fi_FI.utf8, I can't get any translations to show.

root@junior:~/programming/Projects/Cpp/web/test# LANG=fi_FI.utf8 bin/hello
Hello world!
This is package: web-cms
root@junior:~/programming/Projects/Cpp/web/test# sed -i 's/#fi_FI.UTF-8/fi_FI.UTF-8/' /etc/locale.gen && locale-gen
Generating locales...
  en_GB.UTF-8... done
  en_US.UTF-8... done
  fi_FI.UTF-8... done
Generation complete.
root@junior:~/programming/Projects/Cpp/web/test# LANG=fi_FI.utf8 bin/hello
Terve maailma
Tämä on paketti: web-cms
Answer: Did you hear right? As far as I know, you do need system locales for gettext to work. However, you do not need to install all the translations for those system locales just to make your "hello world" work.
Comment: You could be right in that. Is there a way to install locales as normal user?
Comment: Not that I know of. It depends on your Linux distribution I suppose but I think they all require root access to generate the locales. That means that someone using your CMS must ask their sysadmin to generate the proper locales.

This requirement for system locales is quite annoying in a web environment where you want to provide your website in a couple of dozen languages. That is probably also why most web frameworks don't use gettext but something like ICU or a custom library that functions like gettext but doesn't depend on it.
Comment: Hmm... Apparently Django is using gettext for translations, as well as PHP, and they seem to be succeeding in it.
Comment: circir: Django does not use gettext for the actual tanslation lookups. It uses it's own internal functions that mimic gettext but do not require system locales to be installed. Django does use some of the gettext binaries to extract translatable strings from source code and to compile .po files, but these operations do not require system locales to be installed.

PHP's gettext system does use the real gettext and as such does require system locales installed. That's one of the reasons so few projects use PHP gettext and prefer their own i18n system.
Answer: <code>setenv("LANGUAGE", languagecode);
</code>
If languagecode is "fr", and you have an "fr/LC_MESSAGES/.mo" file in the directory pointed to by bindtextdomain, it should work.

Gettext and locales


How does one find any polynomials common roots

Question: I was wondering if there was a way to find the common roots of 2 polynomials.
For example let $P_1(x) = x^5+x^3+2x^4-5x^2-7$ and $P_2(x) = 2x^7 +3x^3+4x^6+6x^2-14x^4-21$
Is there an algorithm or a method to find $P_1$ and $P_2$'s common roots?
Comment: is there a typo in $P_1(x)$?
Comment: $P_1(x)=?x^5+x^3+2x^4-5x^2-7$?
Answer: The general way to do this is to take the GCD of the two polynomials. In particular, one can apply the Euclidean algorithm to this, just like taking the GCD of two integers. In particular, the computation goes as follows: We start with
$$\gcd(x^5+2x^4+x^3-5x^2-7,2x^7+4x^6-14x^4+3x^3+6x^2-21)$$
Then, we take the second polynomial mod the first. That is, we subtract multiples of $P_1$ from $P_2$ until we get a polynomial of degree 4. In particular, $P_2-(2x^2-2)P_1=5x^3+10x^2-35$, so we reduce the above to
$$\gcd(5x^3+10x^2-35,x^5+2x^4+3x^3-5x^2-7)$$
Then, we take the polynomial remainder of the second polynomial mod the fist again, which results in $0$ since
$$x^5+2x^4+3x^3-5x^2-7-(-1/5x^2-1/5)(5x^3+10x^2-35) = 0$$
thus, we can reduce to
$$\gcd(0,5x^3+10x^2-35)$$
meaning that $5x^3+10x^2-35$ is the GCD of the two polynomials. This means that $x$ is a root of both $P_1$ and $P_2$ if and only if it is a root of $5x^3+10x^2-35$ or, equivalently, of $x^3+2x^2-7$.
This essentially works on the principle that if a polynomial has roots $r_1,\ldots,r_n$, then $(x-r_1)(x-r_2)\ldots (x-r_n)$ divides it. Thus, the product of all the shared roots must divide both polynomials and, in particular, must divide their GCD as well.
Answer: The general method for this is to consider that if the two polynomials $P_1$ and $P_2$ have a root in common, then the polynomial $$P_3=\lambda P_1+\mu P_2$$ also has the same common root for all choices of $\lambda$ and $\mu$.
So, for example, $$P_2-3P_1=P_3=2x^7+4x^6-3x^5-20x^4+21x^2$$
Now remove the factor $x^2$ since $x=0$ is clearly not the common root, and continue.
Subtracting $2P_1$ from this now gives $$P_4=-5x^3-10x^2+35$$
So the only common root of the original two polynomials is the single real root of the equation $$x^3+2x^2-7=0$$ which can be found as $1.4288...$


Comparing two discrete distributions (with small cell counts)

Question: I need to compare sample distributions with theoretical ones, which is typically done with a chi-squared test. The problem is that I have distributions where one or more cells have low values, and consequently the chi-squared test reports very small p-values.
For example, a typical expected and observed frequencies are  [152   2   9]  and [140   5  18], with a p-value of 0.0007. Based on domain knowledge, these two distributions are not significantly different.
What test could be used instead of chi-squared, which would take out the bias that occurs with the small-valued cells?
Edit: adding some background information for this problem.
I have a number of processes which produce as output certain technical parameters, recorded as time series. I have around 4000 of such process, each producing around 150 such time series (the number of time series a process has follows a power law). I would like to find which of these processes are anomalous, i.e. producing output which is significantly different from others.
To do this I cluster the time series using k-means, and then based on the clusters, produce the "expected" distribution (average over all time series) and the distribution of clusters for each process.
For example, after clustering I might have 4 clusters with following sizes.
<code>Cluster number | Cluster size
-----------------------------
1              | 100
2              | 200
3              | 300
4              | 400
</code>
The distribution of the clusters among the processes might be the following
<code>          | Cluster 1 | Cluster 2 | Cluster 3 | Cluster 4
----------------------------------------------------------
Process 1 | 11        | 19        | 35        | 42
Process 2 | 3         | 10        | 14        | 19
Process 3 | 30        | 8         | 12        | 12              <----anomaly
....
</code>
In this case, process 1 and process 2 are sufficiently close to the expected, while process 3 has a different distribution from the average. I would like to find a good test to measure this discrepancy. (Any other suggestion for the anomaly detection is also welcome)
Comment: It is noteworthy that the edit almost completely changes the question.  (This is no longer a comparison of a distribution against a reference: it involves multiple comparisons and *no* reference.)  There are now good reasons to suspect correlations among the counts, too, which could be induced by the nature of the clustering and the nature of the processes themselves.  Answers can be derived by ignoring these complications, but they might then lead you to erroneous conclusions.  A good answer would incorporate some model (or understanding) of the relationships between processes and clusters.
Answer: There are two technical issues to deal with: (1) measuring the discrepancy between observed and expected and (2) computing the p-value.
We can retain the chi-squared measure of discrepancy (thereby finessing issue 1) and compute an exact p-value.  The simple way is to simulate sampling from the expected distribution.  Here is the distribution of 10,000 samples performed in R:

The actual chi-squared statistic for these data is $549/38 \approx 14.447$.  Apparently it is far out in the upper tail of this histogram: only $25$ of the $10,000$ results (0.25%) equal or exceed it.  Yes, this proportion is almost four times greater than the approximation of $0.0007$ reported by the chi-squared test, but it's still tiny.  We conclude that the observed distribution is significantly different from the expected distribution.
The "domain knowledge" may indeed correctly suggest the amount of difference is not material.  That, however, is independent of the finding that the observed frequencies are unlikely to arise randomly from a distribution with the expected frequencies.  That is all that statistical significance means.
Comment: Thanks for the reply. Could you also elaborate on point (1). I.e. why the chi-squared measure in the first place. Could another test statistic to measure the discrepancy be more useful?
Comment: Yes, Ash, another statistic could be more useful.  That would depend why you are conducting this test, about which I and all other readers are ignorant.  If you could like to elaborate on that, perhaps we can make more progress in this direction.  It might also be helpful to disclose the basis of the expected frequencies: if they cannot be taken as given by theory, but are rather derived from other data or assumptions, then we have failed to incorporate that additional uncertainty in our reasoning.
Comment: Added some background info to the question


Exam Question on Real Analysis

Question: For a continuous function $f$ on $[0,1]$, $\int_0^1f^3(x)x^ndx = 0 $ for each integer $n \geq 1$. Prove $\int_0^1f^4(x)dx = 0 $. (where $f^n(x)$ is the nth power of $f$). And hence prove $f = 0$.
I am able to prove the second part i.e. $\int_0^1f^4(x)dx = 0 \Rightarrow$ $f = 0$, but the first part eludes me.
Any hints are welcomed.
Thanks for your efforts.
Comment: Use Weierstrass Approximation Theorem: http://mathworld.wolfram.com/WeierstrassApproximationTheorem.html.
Comment: Thanks again for your help.
Answer: Let's approximate $f^3$ by polynomials $p_n$.
$$
\| f-p_n \|_\infty \leq \frac1{n}
$$
$f^3$ is continuous, so we have $M>0$ that
$$
\| f^3 \|_\infty \leq M
$$
Now
$$
0 = \int f^3 p_n = \int (f^3 - p_n + p_n) p_n = \int (f^3 - p_n)  p_n + \int p^2_n
$$
from this we get inequality
$$
\left| \int p^2_n \right| \leq   \int  \left|(f^3 - p_n)  p_n \right| \leq 1 \cdot \frac1{n} \cdot (M+1) \rightarrow 0 \text{  as } n\rightarrow \infty
$$
because $p_n$ converge uniformly to $f^3$ we get that
$$
\int p^2_n \overset{n\rightarrow \infty}{\rightarrow} \int f^6 = 0
$$
I showed that $\int f^6 = 0$ and not $\int f^4 = 0$ but from this point the argument for $f=0$ should be the same.

Exam Question on Real Analysis


equally-likely discrete probability models

Question:
I am not really sure about the answer of question b. Thanks for helping.
Comment: http://stats.stackexchange.com/tags/self-study/info. Please add your own thoughts about the problem.
Comment: Think about using the compliment rule, i.e., $$P(A)=1-P(A^c)$$ then you don't have to calculate an infinite series. This is of course just a hint, but if you need more please do say so.
Comment: Is the answer 1-3/n ?
Comment: That is not the answer.
Comment: Is it linked to question (a) ?
Answer: Let $k$ be the value of the outcome of the experiment, then
\begin{align}
P(k>3)&=1-P(k\leq3)\\
&=1-[P(k=1)+P(k=2)+P(k=3)]\\
&=1-\left[\frac{3}{4}+\frac{3}{4^2}+\frac{3}{4^3}\right]\\
&=0.015625
\end{align}
=====================================================================
If you didn't use the complement rule, then the answer would be
$$P(k>3)=\sum_{i=4}^\infty\frac{3}{4^k}=0.015625$$ which is indeed an infinite sum.
Comment: I was first thinking that both questions are not interrelated . By the way , thanks for helping .


How to space first_name + last_name C++

Question: My question is how can i use spaces between first_name and last_name after i instruct the user to input his name.
I am using code blocks and I'm kinda confused.
In Dev C++ i can do
<code>   cout<<first_name<<" "<<last_name;
</code>
Now what I am doing is just practicing C++ using variables in a class.
Here is my code.
<code>    #include<iostream>
    #include<string>
    using namespace std;

    class DanielClass
      {
     public:
        int setNameFunction(string first_name, string last_name)
        {
    cout<<"Enter your first name here: ";
    cin>>first_name;
    cout<<"Enter your last name here: ";
    cin>>last_name;
    name = first_name + last_name;
        }

        string getNameFunction()
        {

    return name;
        }

    private:
       string name;
    };

    int main()
    {

       DanielClass NameObject;
       NameObject.setNameFunction("", "");
       cout<<NameObject.getNameFunction();

       cout<<"\n\n";
       return 0;
     }
</code>
Answer: You can add string literals (which is just a term for a string entered directly into the code with quotes around it -- like the " " in the second line of code below) to string variables using the '+' operator.
You just need to change the line that reads:
<code>    name = first_name + last_name;
</code>
to:
<code>    name = first_name + " " + last_name;
</code>
Comment: Wow Sir Barry Gackle, Really Thank you!

How to space first_name + last_name C++


Proof of $f'(x) = \frac{1}{n} \cdot x^{\left(\frac{1}{n}\right) - 1}$ when $f(x) = x^{\frac{1}{n}}$ by limit definition

Question: how can I prove
$$f'(x) = \frac{1}{n} \cdot x^{\left(\frac{1}{n}\right) - 1}$$ when $$f(x) = x^{\frac{1}{n}}$$ by limit definition?
Thank you.
Comment: hint: $x^u-x_0^u=(x-x_0)(x^{u-1}+x^{u-2}x_0+x^{u-3}x_0^2+ \cdots + xx_0^{u-2}+x_0^{u-1})$
Comment: Closely related: [Differentiation using first principles with rational powers](http://math.stackexchange.com/questions/382796/differentiation-using-first-principles-with-rational-powers)
Answer: $$\lim_{x\to x_0}\frac{x^{1/n}-x_0^{1/n}}{x-x_0}=\lim_{x\to x_0}\frac{x-x_0}{(x-x_0)\left(\left(x^{1/n}\right)^{n-1}+\left(x^{1/n}\right)^{n-2}x_0+\ldots+\left(x_0^{1/n}\right)^{n-1}\right)}=$$
$$=\frac1{\left(x_0^{1/n}\right)^{n-1}+\left(x_0^{1/n}\right)^{n-2}x_0+\ldots+\left(x_0^{1/n}\right)^{n-1}}=\frac1{n\,x_0^{1-1/n}}=\frac{x_0^{1/n-1}}n$$
Comment: Is there a way to prove through $h \to 0$ ?
Comment: @bru1987 Just let $x = x_0+h$ then $x\to x_0\iff h\to 0$.


Under what minimal conditions on $d,c>0$, do we have $\lim_{n \to \infty}\sum_{n/2 \le k \le n}{n\choose k}(1-1/n^c)^{k\choose d} = 0$?

Question: Let $n$ and $d$ be positive integers and $c > 0$.

Question. Under what minimal conditions on $d$ and $c$ do we have $\lim_{n \to \infty}\sum_{n/2 \le k \le n}{n\choose k}(1-1/n^c)^{k\choose d} = 0$ ?

Intuitively, this should be the case if $c$ is sufficiently small compared to $d$. Just how small, that's the question...
Answer: This holds if and only if $c<d-1$.
I'll write $f(n)\sim g(n)$ for $g(n)=f(n)(1+o(1))$, that is, $\lim_{n\to\infty}g(n)/f(n)=1$. Also, $n/2$ stands for $\lceil n/2\rceil$. Let
$$S_{d,c}(n)=\sum_{k=n/2}^n\binom nk(1-n^{-c})^{\binom kd}$$
be the quantity we want to estimate. We have
$$\binom{n/2}d\sim\frac{n^d}{2^dd!}$$
and
$$\log(1-n^{-c})\sim-n^{-c},$$
thus
$$\log\left((1-n^{-c})^{\binom{n/2}d}\right)\sim-\frac{n^{d-c}}{2^dd!}.$$
Also, for $n/2\ge d$,
$$\binom n{n/2}(1-n^{-c})^{\binom{n/2}d}\le S_{d,c}(n)\le\sum_{k=n/2}^n\binom nk(1-n^{-c})^{\binom{n/2}d}\le2^n(1-n^{-c})^{\binom{n/2}d},$$
while
$$\log\binom n{n/2}\sim\log2^n=n\log2,$$
hence
$$\log S_{d,c}(n)=n(\log2+o(1))-\frac{n^{d-c}}{2^dd!}(1+o(1)).$$
Thus, if $d-c>1$, the $n^{d-c}$ term dominates, and
$$S_{d,c}(n)=\exp\left(-\frac{n^{d-c}}{2^dd!}(1+o(1))\right)\to0\qquad(n\to\infty),$$
whereas if $d-c<1$, the $n$ term dominates, and
$$S_{d,c}(n)=\exp\bigl(n(\log2+o(1))\bigr)\to+\infty\qquad(n\to\infty).$$
If $d-c=1$, we have
$$\log S_{d,c}(n)=\left(\log2-\frac1{2^dd!}+o(1)\right)n,$$
and since $\log2>1/(2^dd!)$ for $d\ge1$, again
$$S_{d,c}(n)\to+\infty\qquad(n\to\infty).$$
Comment: Nice! This is some super cool real analysis. Thanks!