Intersection of a circle and a triangle

Question: If we have a point $(0,6)$ which is the vertex of an equilateral triangle the distance of whose all vertices are equal from origin.Draw a circle of radius 3 centered at $(0,1)$.How many number of maximum intersection of circle and triangle?
I don't know how to solve because i am week in geometry, from picture i find it may be 3 or 4,but i am not sure.Please give me some direction to solve this.
Comment: Yes i edit the question that what i have tried
Comment: No,i don't know.
Comment: Eyeballing it, to me there is either $2$ or $4$ intersections.
Comment: I 'think' I came up with the solution algebraically. I haven't been on here that long, are we allowed to give a partial solution and then a link to another question on Math.SE on how to finish where I leave off? Is that too cumbersome? I find that the lack of effort from the asker would suggest I don't need to do all the work for him/her.
Comment: Then please give some hint,iwill try myself.
Comment: @Vincent The coordinates of the vertices aren't actually what's important here. Once you realize that the given vertex is at the top of the circle, you know what the orientation of the triangle is. And since it's equilateral, the slopes of the slanted sides will be $\pm\sqrt{3}$. You also know the y-intercept for these lines, so...
Comment: Hmm. The given vertex is at $(0,6)$ and the circle is centered at $(0,1)$ with $r=3$. Doesn't that make the the top of the circle at $(0,4)$ and not at the top vertex?
Comment: @Vincent Not that circle. The vertices of the triangle are equidistant to the origin. The distance between vertex $(0,6)$ and the origin is $6$. Hence all three vertices lie on the circle of radius $6$ centered at the origin. Vertex $(0,6)$ is at the top of this circle.
Comment: Ahh, I understand that part now.
Comment: @vincent the vertices $(0,6),(-3\sqrt{2},-3\sqrt{2}),(3\sqrt{2},-3\sqrt{2})$ do not make equilateral triangle because the disance between $(0,6) and (-3\sqrt{2},-3\sqrt{2})$ and distance between $(-3\sqrt{2},-3\sqrt{2}) and (3\sqrt{2},-3\sqrt{2}) $ are different.
Comment: The points for the vertices I gave before were wrong. Yah, Rizwan, I noticed I mistook a triangle for a right triangle when it wasn't. But as David said, the other vertices don't matter.
Comment: @RizwanAhmed It might be helpful if you review the basic facts about equilateral triangles here: http://www.wolframalpha.com/input/?i=equilateral+triangle.
Comment: yes it is helpful @DavidH by using the vertices it is clear that there are 4 intersection.Since i need maximum number of intersections so i think it is 4.
Answer: This may not be the fastest or most sophisticated method, but I "think" it works. It is an algebraic approach to solving this type of problem. A more clever person than I can attest one way or the other.
First recognize that the slope of an equilateral triangle is $\pm\sqrt{3}$. From here, we can find the equation of the line that is a side of the triangle. Either one will work as whatever result we get for the number of intersection points for one side will be equal to the other. Thus, we can just double our answer.
Equation of a line $y=mx+b$, where $m=\pm\sqrt{3}$ (we will choose $+\sqrt{3}$), and $b=6$. Thus, we get:
$$y=\sqrt{3}x+6$$
What we are ultimately looking for is the number of intersection points between our line and the circle. The equation of a cicle is $(x-a)^2+(y-b)^2=r^2$. Where we have $a=0$, $b=1$ and $r=3$. Giving us:
$$x^2+(y-1)^2=9$$
Substitute, $y=\sqrt{3}x+6$ into $x^2+(y-1)^2=9$. After doing a little algebra we get:
$$4x^2+10\sqrt{3}x+16=0$$
Which is a quadratic with $a=4$, $b=10\sqrt{3}$ and $c=16$.
Using the discriminant of the quadratic:
If $b^2-4ac<0$, there are no points of intersection.
If $b^2-4ac=0$, the line is tangent to the circle and therefore has one point of intersection.
If $b^2-4ac\gt 0$, there are two points of intersection.
$$(10\sqrt{3})^2-4(4)(16)=44$$
Thus, each line intersects the circle at two points giving us $4$ total points of intersection.
Comment: You made a mistake somewhere. There are four points of intersection. Here's two of them: http://www.wolframalpha.com/input/?i=y%3Dsqrt%283%29*x%2B6%2C+x^2%2B%28y-1%29^2%3D9
Comment: Same as the first two points, only reflected through the y-axis. And as to your previous question, your method is sound but algebra is off. The quadratic you should get is $4x^2+10\sqrt{3}x+16=0$.
Comment: @Vincent yor quadratic equation after sustitution should be $4x^2+10\sqrt{3}x+16=0$, which has two real roots.
Comment: Yah. I am correcting it now. I forgot to take $-1$ into account when I substituted the $y$ in.
Comment: @Vincent thanks for this method, now we can see that there are 4 intersection points.
Comment: Also thanks to @DavidH
Comment: And that is why you don't answer questions with a baby on your lap. =)
Comment: I typed that up with a fussy baby on my lap so you may be right. Let's see here.
Comment: What were your other two points of intersection? In my solution I didn't consider the base of the triangle. I'm checking that now to see if there are points of intersection.
Comment: @Vincent you can also consult with your baby.

Intersection of a circle and a triangle


What is this function notation

Question: I am studying functions and equations and in my textbook I have this definition:
A function $f:A\to B$ is invertible if there is a function $g:B\to A$ such that $f\circ g=1_B$ and $g\circ f=1_A$.
What are $1_B$ and $1_A$? I have never seen this notation.
Thanks.
Comment: By the way, you can use ``\to`` for $\to$, which is easier to type than ``\rightarrow``.
Comment: If $S$ is a set then $\mathbb 1_S$ is the identity function from $S\to S$.
Comment: E.g. $1_B$ is the function $B\to B$ prescribed by $b\mapsto b$. Such functions are called identities.
Comment: @Neox: Yes, that is correct. Here is a translation of your definition into more familiar words: a function $f:A\to B$ is invertible if there is a function $g:B\to A$ such that $f(g(x))=x$ for all $x\in B$ and $g(f(x))=x$ for all $x\in A$. This function $g$ is conventionally written as $f^{-1}.$
Comment: So $1_A=f:A\rightarrow A$ st $f(x)=x$ ?
Comment: @lulu: Isn't it called an indicator function, not an identity function?
Comment: @Joe  An indicator function, usually defined on a subset $S\subset T$ , is $1$ on $S$ and $0$ on $T-S$.    The same notation may sometimes be used for that, but the context the OP provides makes it clear that we are speaking of the identity function.
Comment: @lulu: Oh, I see. Thanks for clarifying.
Comment: @Joe Thanks for advice.
Comment: @Neox: No problem! I'm glad I could help.
Answer: In this context, $1_A$ means the identity function $\DeclareMathOperator{\id}{id}\id:A\to A$ such that $\id(x)=x$. I have also seen the notation $1_{A}$ to refer to an indicator function: that is, a function $f$ defined on a subset $A$ of $X$ such that
$$
f(x)=\begin{cases}
1 &\text{if $x\in A$,} \\
0 &\text{if $x\in X\setminus A$,}
\end{cases}
$$
so it is important to be aware of different conventions.
Here is a translation of your definition into more familiar words: a function $f:A\to B$ (where $B$ is the range of $f$) is invertible if there is a function $g:B\to A$ such that $f(g(x))=x$ for all $x\in B$ and $g(f(x))=x$ for all $x\in A$. We typically write $f^{-1}$ for $g$.

What is this function notation


Finding the probability that a person is positive given a negative test?

Question: Given the problem of a patient taking a test for a disease where having the disease is denoted by X and the a positive test is denoted by Y,

the rate of occurrence of the disease in the general population is 1%
The odds of getting tested positive is 90% if you have the disease
the probability of a false positive  is 3%

is it appropriate to solve the following through rearranging the total probability
$P(A) = P(A|B)P(B) + P(A|Not B)P(Not B)$
Into
$P(A|B) = (P(A) -P(A|B)P(B))/P(Not B)$
and then getting P(B) from the total probability
$P(B) = P(B|A)P(A) + P(B| Not A)P(Not A)$
then given B is binary P(Not B) from
$1 = P(B) + P(Not B)$
and getting P(A|B) from Bayes
$P(A|B) = = P(A)P(B|A)/P(B)$
and then substituting that all back into the first equation to get the result
Any help on this would be much appreciated
Comment: This is hard to read, as you seem to switch notation from $X,Y$ to $A,B$ without explanation.  In any case, this problem (with different numbers) has been asked over and over again on this site.  Just do a simple search.  [here](https://math.stackexchange.com/questions/2740647/bayes-theorem-disease-probability) is one duplicate for example.
Comment: Perhaps you mean "probability" in place of ["odds"](https://en.wikipedia.org/wiki/Odds)?
Comment: Refer to the probability tree at the top of, and scroll down to "false omission rate" in, [this post](https://math.stackexchange.com/a/4319216/21813).
Answer: We have by Bayes' rule
$$P(X|Y^c)=\frac{P(Y^c|X)P(X)}{P(Y^c|X)P(X)+P(Y^c|X^c)P(X^c)}.$$
Your setup has $P(X)=0.01,P(Y|X)=0.9,P(Y|X^c)=0.03.$


transfer of the value inside function

Question: public boolean judge(Parcelle p) {
    int xx,yy;
    int co;

    for(int aa=0;aa<9;aa++) {
        for(int bb=0;bb<5;bb++) {
            if (p.equals(alist.get(aa).get(bb))) {
                xx=aa;
                yy=bb;
                break;
            }
        }
    }
    co=alist.get(xx+1).get(yy).exist+alist.get(xx-1).get(yy-1).exist+alist.get(xx-1).get(yy).exist+alist.get(xx).get(yy-1).exist+alist.get(xx+1).get(yy+1).exist+alist.get(xx).get(yy+1).exist;
    return co>=2;
}

Here alist is a 2-dimension arraylist of class Parcelle.
and Parcelle has a public int exist.
I wrote this loop for judge if the sum of the exist of Parcelles around this Parcelle is bigger than 2.
and it alerts that I should initialize the int xx,yy,
but in the loop I've set the value of them.
So I don't know what the problem is!
Comment: Unfortunately we don't know what the problem is either. Could you please explain in which way this code fails to do what it is intended to.
Comment: You forgot to initialize `aa` and `bb`. In your mind, what is their value if the `equals()` call never returns true?
Answer: I don't really get what you're doing here either (no context), but I'd start by setting the variables to zero first:
int xx = 0;
int yy = 0;
int co = 0;

I have a suspicion that is not going to fix everything, but that's where I start when hitting that particular error in java. For some reason, it's really finicky about declaring without setting a value.
Comment: `co = 0` isn't needed but `xx` and `yy` being set is.

transfer of the value inside function


Is there a way in JetBrains IDE's to set a keyboard shortcut to move the caret/cursor to the center?

Question: I am looking for a command in JetBrains IDE's (specifically WebStorm and Rider) to set a keyboard shortcut that will center the caret in the center of the editor page.
Is this possible with a shortcut or extension?
Just to be clear, I don't want to move the page to center the caret (which already exists with s shortcut), I want to move the caret to the center of the page, without moving the editor page view.
Comment: Could you add some screenshots to better demonstrate the desired feature?
Comment: Why are people voting to close this???
Comment: Would you mind explaining what you're trying to achieve with this?
Comment: There is "Scroll to Center" action (the one you must be referring to), but nothing like "Move Caret to Center". What are you trying to achieve with this? Maybe there are better tools/plugins for that...
Comment: I am trying to achieve moving my caret to the center.
Comment: What benefits it will provide when the caret is in the center of the screen? Or is it "I wanted it for my own reasons"?
Comment: Because generally I like the code I am editing to be in the center of the screen. So I press ctrl+down to scroll the view to where I want to edit, then I want to center the caret to the view to being editing.
Comment: It's not the same ofc, but what about AceJump or alike plugin -- that allows to quickly move your caret to a certain position on a screen with just a few keys. Will that be any good?
Answer: Sure, you can just use Ctrl + M to move the caret to centre of the screen.
If you don't want to have to hit Ctrl + M all the time, you can also achieve what you want by using the IdeaVim plugin

Open the Settings dialog (Ctrl+Alt+S)
Select Plugins.
Find the IdeaVim plugin and install.

Create $HOME/.ideavimrc
Add set scrolloff=XX where XX is at least half the total lines you would usually see. Setting 'scrolloff' to a large value causes the cursor to stay in the middle line when possible. e.g. set scrolloff=999
Restart your IDE.

Tested and working in PHPStorm and PyCharm
Comment: This is not an adequate answer, as the number of lines shown can change depending on view size, so a fixed value would not work.
Comment: @Scorb - So why doesn't  `Ctrl + M`  work as I suggested first? Also you can just Setting 'scrolloff' to a large value causes the cursor to stay in the middle line when possible. e.g. `set scrolloff=999` see my edit.
Comment: @Scorb The scrolloff setting is the desired number of lines above and below the caret, so setting a large fixed value, e.g. `999` - would absolutely work all on all view sizes. Have you even tried it?


T-SQL Override special rates and generate final date range

Question: I have transaction table which has date range and basic rate for the range. I have another table for special rate which has date range for special rate and its rate. I would like to split my original transaction in multiple records if special rates falls in transaction date range.
Just for simplicity I have created two tables with limited columns
DECLARE @ClientTrx AS TABLE (ClientId int, StartDate Date, EndDate Date, Rate decimal(10,2))
DECLARE @SpecialRate AS TABLE (ClientId int, StartDate Date, EndDate Date, Rate decimal(10,2))

insert into @ClientTrx select 1, '1/1/2020', '1/15/2020', 10
insert into @ClientTrx select 1, '1/16/2020', '1/31/2020', 10
insert into @ClientTrx select 2, '1/1/2020', '1/15/2020', 20
insert into @ClientTrx select 2, '1/16/2020', '1/31/2020', 20
insert into @ClientTrx select 2, '2/1/2020', '2/13/2020', 20

insert into @SpecialRate select 1, '12/25/2019', '1/3/2020', 13
insert into @SpecialRate select 1, '1/4/2020', '1/6/2020', 15
insert into @SpecialRate select 1, '1/11/2020', '1/18/2020', 12

insert into @SpecialRate select 2, '1/25/2020', '1/31/2020', 23
insert into @SpecialRate select 2, '2/4/2020', '2/8/2020', 25
insert into @SpecialRate select 2, '2/11/2020', '2/29/2020', 22

I need help write a query which produce following results:
ClientId    StartDate   EndDate Rate
1   2020-01-01  2020-01-03  13.00   special rate
1   2020-01-04  2020-01-06  15.00   special rate
1   2020-01-07  2020-01-10  10.00   regular rate
1   2020-01-11  2020-01-15  12.00   special rate
1   2020-01-16  2020-01-18  12.00   special rate splitting pay period
1   2020-01-19  2020-01-31  10.00   regular rate
2   2020-01-01  2020-01-15  20.00   regular rate
2   2020-01-16  2020-01-24  20.00   regular rate
2   2020-01-25  2020-01-31  23.00   special rate
2   2020-02-01  2020-02-03  20.00   regular rate
2   2020-02-04  2020-02-08  25.00   special rate
2   2020-02-09  2020-02-10  20.00   regular rate
2   2020-02-11  2020-02-13  22.00   special rate

I think using CTE its possible but I can't figure it out. can anyone please help?
Note: I have made some changes in my input and expected output, i think I need one more group level, can you please help?
Answer: This is an approach which uses and ad-hoc tally table to expand the datasets and then applies a Gaps-and-Islands for the final summary
Example
;with cte as (
Select A.ClientId
      ,D
      ,Rate = coalesce(NewRate,A.Rate)
      ,Grp  = datediff(day,'1900-01-01',D) - row_number() over (partition by ClientID,coalesce(NewRate,A.Rate) Order by D)
 From  @ClientTrx A
 Cross Apply (
                Select Top (DateDiff(DAY,StartDate,EndDate)+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),StartDate)
                 From  master..spt_values n1,master..spt_values n2
             ) B
 Outer Apply (
               Select NewRate=Rate
                 From @SpecialRate
                 Where D between StartDate and EndDate
                   and ClientId=A.ClientID
             ) C
)
Select ClientID
      ,StartDate= min(D)
      ,EndDate  = max(D)
      ,Rate     = Rate
 From  cte
 Group By ClientID,Grp,Rate
 Order by ClientID,min(D)

Returns
ClientID    StartDate   EndDate     Rate
1           2020-01-01  2020-01-03  13.00
1           2020-01-04  2020-01-06  15.00
1           2020-01-07  2020-01-10  10.00
1           2020-01-11  2020-01-18  12.00
1           2020-01-19  2020-01-31  10.00
2           2020-01-01  2020-01-24  20.00
2           2020-01-25  2020-01-31  23.00
2           2020-02-01  2020-02-03  20.00
2           2020-02-04  2020-02-08  25.00
2           2020-02-09  2020-02-10  20.00
2           2020-02-11  2020-02-15  22.00

Notes:
Cross Apply B generates a record for each date between startDate and endDate in @ClientTrx.
Outer Apply C attempts to find the Exception or NewRate
the CTE generates one record per date and toggles the default or exception rate.  It looks like this

Notice how GRP changes.   This is a simple technique to "feed" the Gaps-and-Islands
Then is becomes a small matter to group the results from cte by ClientID and Grp
Comment: I could not understand fully but it gives me what I needed. Can you please explain role of master..spt_values?


Why does my site use SSR on my custom domain but but client-side rendering in the vercel-generated domain?

Question: (For context I'm using next version 14.0.3, testing on chrome, and am using the hobby plan on Vercel for deployments)
So I have a site with a header containing some links to other pages (using nextjs' <Link> component). When I click on a link I expect the site to navigate to the page using client-side rendering (i.e. no page reload), which it does on the vercel-generated domain. But on my custom domain, it uses SSR instead (i.e. when I click on a link, the site makes a network request to fetch a new page from the server causing a page reload).
Does anyone have any idea what's going on here? Is there some sort of DNS issue going on?
Thank you in advance, been banging my head against this all day.
Answer: So I figured it out.. this was happening because I added an umami tracking event prop to my <Link> component. This wasn't occurring in my non-prod environments because I configured umami to only collect events from my custom domain. wild stuff check your  props kids


Change field settings for text field from plain to formatted while data exists

Question: anyone know of a quick example of how to change the field settings for a text area (plain) to formatted and set the input formatter (or maybe it will use default)? Will this require a resave of all the data or can it just be changed for the entity type? I currently have a lot of existing data on this site.
The field is currently stored as the type string, Text (plain). I need to change it to text_long, Text (formatted, long).
Thanks
Comment: In Drupal 7 you could've used Helper module's FieldChangeHelper class
https://git.drupalcode.org/project/helper/blob/7.x-1.x/lib/FieldChangeHelper.php
Alas, nothing similar yet exists for Drupal 8
Answer: Attention for Drupal 8:
You need to update at least 3 or 4 yml files
field.field.node.page.field_description.yml
(same change)

field.storage.node.field_description.yml
--- a/config/default/field.storage.node.field_description.yml
+++ b/config/default/field.storage.node.field_description.yml
@@ -4,13 +4,13 @@
 dependencies:
   module:
     - node
+    - text
 id: node.field_description
 field_name: field_description
 entity_type: node
-type: string_long
-settings:
-  case_sensitive: false
-module: core
+type: text_long
+settings: {  }
+module: text
 locked: false
 cardinality: 1
 translatable: true

core.entity_form_display.node.page.default.yml
-type: string_textarea
+type: text_textarea

core.entity_view_display.node.page.default.yml
-type: basic_string
+type: text_default

Maybe the last 2 ones you can deal with those changes on UI(go to each teaser and save). But I did in config folder.
Comment: While this will have changed the appearance of the node form, the data will not be saved correctly, and will not be displayed correctly.
Comment: While this didn't work per se, it did work with the help of this blog article because the formatter and widget settings were hidden with that approach and this allowed me to adjust those in the YAML files, thanks @carlos  https://blog.42mate.com/change-field-type-with-existing-data-on-drupal-8/
Answer: Oh wow, I just tried something in hopes of it being easy and it was a breeze!...
I already have all my config exported to code so I compared a text_long field to my current string_long field and just merged the differences, it worked beautifully. Something like the changes in the following example patch:
--- config/prod/field.field.node.page.field_description.yml (revision 3ef14eada9090087d33a10ec532732e515fef151)
+++ config/prod/field.field.node.page.field_description.yml (revision )
@@ -5,6 +5,8 @@
   config:
     - field.storage.node.field_description
     - node.type.page
+  module:
+    - text
 id: node.researcher.field_description
 field_name: field_description
 entity_type: node
@@ -16,4 +18,4 @@
 default_value: {  }
 default_value_callback: ''
 settings: {  }
-field_type: string_long
+field_type: text_long

imported the changed config et voila! Just beautiful.
Comment: I doubt it really just works like that. Note that the field type is also in the storage, and that changing the field type results in a different field schema, which drupal will actually prevent you from changing if you try it on the field storage config.
Comment: @Berdir of course you are correct. Guess I am still looking to solve this. Seemed good at first but then I noted the display was rendering with html markup.
Answer: You can use the module Druidfire by CHX.
https://gitlab.com/chx_/druidfire
Drush 10 command: drush druidfire:string2formatted entity_type field_name
It's not hosted on drupal.org and is unlikely to be. Use with caution.
Example update hook for your module_name.install file:
/**
 * Change field my_field to formatted text.
 */
function module_namee_update_8001() {
  \Drupal::service('druidfire')->kaboom('string2formatted', 'node', 'field_my_field');
}

Comment: This seems useful, why isn't it on Drupal.org?
Comment: @Kevin See: https://www.drupal.org/project/drupal/issues/3079843#comment-13250398 "But note the standard "there is no warranty" clause, even more so than usual because this module bypasses the entity APIs. Even if I moved this module to drupal.org it very likely would become a sandbox because there is absolutely no way I would want to support it. "


How to get list of module folders which can be deleted safely?

Question: I've uninstalled a lot of unnecessary modules recently through admin/modules/uninstall.
Now I want to understand what folders of the modules can be deleted from sites/all/modules.
I've tried drush pmi, but there is too much information.
How can I get list of folders which can be deleted safely now? Any drush command may be?
Answer: Use this:
drush pmi --fields=type,project,title,status,path --format=table|sort

This gives you a module list with five columns:

First is the type of project: module or theme.
Second one is the module project, for exampe views, logintoboggan, admin_menu, etc.
The third one is the installation status: enabled (in use), disabled (not in use but install info in DB) and not installed (it hasn't been installed yet or it have been already uninstalled).
Fourth column is module name. A module downloaded from drupal.org can have several modules inside (the downloaded module is the project and the inside modules are the real modules).
The fifth column is the path to the module.

With this information you can safely remove every project (second column) that all of its modules are in 'not installed' state.
For example, see this fragment list:
module  job_scheduler  Job Scheduler                enabled        sites/all/modules/contrib/job_scheduler
module  job_scheduler  Job Scheduler Trigger        not installed  sites/all/modules/contrib/job_scheduler/modules/job_scheduler_trigger
module  jquery_update  jQuery Update                enabled        sites/all/modules/contrib/jquery_update
module  l10n_client    Localization client          enabled        sites/all/modules/contrib/l10n_client
module  l10n_update    Localization update          enabled        sites/all/modules/contrib/l10n_update
module  languageicons  Language Icons               enabled        sites/all/modules/contrib/languageicons
module  ldap           LDAP Authentication          not installed  sites/all/modules/contrib/ldap/ldap_authentication
module  ldap           LDAP Authorization - Roles   not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_drupal_role
module  ldap           LDAP Authorization           not installed  sites/all/modules/contrib/ldap/ldap_authorization
module  ldap           LDAP Authorization - OG      not installed  sites/all/modules/contrib/ldap/ldap_authorization/ldap_authorization_og
module  ldap           LDAP Feeds                   not installed  sites/all/modules/contrib/ldap/ldap_feeds
module  ldap           LDAP Help                    not installed  sites/all/modules/contrib/ldap/ldap_help
module  ldap           LDAP Query                   not installed  sites/all/modules/contrib/ldap/ldap_query
module  ldap           LDAP Servers                 not installed  sites/all/modules/contrib/ldap/ldap_servers
module  ldap           LDAP SSO                     not installed  sites/all/modules/contrib/ldap/ldap_sso
module  ldap           LDAP Test Module             not installed  sites/all/modules/contrib/ldap/ldap_test
module  ldap           LDAP User Module             not installed  sites/all/modules/contrib/ldap/ldap_user
module  ldap           LDAP Views                   not installed  sites/all/modules/contrib/ldap/ldap_views
module  libraries      Libraries                    enabled        sites/all/modules/contrib/libraries

You can safely remove the ldap module because all modules are not installed but not job scheduler because one of its modules is enabled.
Comment: I have error: Unknown options: --fields, --format (drush stable version 5.10.0 at Ubuntu). I think I need more fresh release.
Comment: Yes, you should update your drush installation
Comment: I've made [Drush update](http://docs.drush.org/en/master/install/). Now I can execute command. It's not ideal solution, but now I see what folders can be deleted safely. ty
Answer: This works on Linux Machines. But you can do something similar on windows also I think.
Use the following command to get a list of disabled or uninstalled modules.
    drush pml --type=Module --status="disabled,not installed" --no-core
--pipe | paste -s -d,

You will get a comma separated list like this
    admin_toolbar,admin_toolbar_tools,features,features_ui,entity_browser,
entity_browser_example,config_update,content_types_full_export

If you want to remove only the uninstalled module you can remove disabled from status option in the first query.
Once you have the comma separated list of un-installed modules you can pass it on to the drush pmi query like this.
drush pmi --format=csv --fields=path
admin_toolbar,admin_toolbar_tools,features,features_ui,entity_browser,
entity_browser_example,config_update,content_types_full_export

You will get the ouput as
modules/admin_toolbar
modules/admin_toolbar/admin_toolbar_tools
modules/features
modules/features/modules/features_ui
modules/entity_browser
modules/entity_browser/modules/example
modules/config_update
modules/features_modules/content_types_full_export

You can use this to safely delete the folders :)
Comment: `Unknown option: --status.` when doing this in drush 8.1.12
Answer: I have two suggestions for you on how to filter that drush command. One is with pipes and grep. The other is with the option arguments.
First off I think you want drush pml (lowercase "L", not lowercase "I").
(1) Pipes and Grep
See the command below to list everything with status of "Not installed". The following may help give you a better picture of what's around your site. For example, here is what is there but "not installed" on my dev box.
$ drush pml | grep 'Not installed' | grep -v Core
 Administration                       Actions permissions (VBO) (actions_permissions)               Module  Not installed  7.x-3.2
 BackgroundField                      BackgroundField (backgroundfield)                             Module  Not installed  7.x-1.5
 Chaos tool suite                     Better Jump Menus (jump_menu)                                 Module  Not installed  7.x-1.4
 Chaos tool suite                     Chaos Tools (CTools) AJAX Example (ctools_ajax_sample)        Module  Not installed  7.x-1.6
 Chaos tool suite                     Chaos Tools (CTools) Plugin Example (ctools_plugin_example)   Module  Not installed  7.x-1.6
 Chaos tool suite                     Custom content panes (ctools_custom_content)                  Module  Not installed  7.x-1.6
 Chaos tool suite                     Custom rulesets (ctools_access_ruleset)                       Module  Not installed  7.x-1.6
 Chaos tool suite                     Page manager existing pages (pm_existing_pages)               Module  Not installed  7.x-1.4
 Chaos tool suite                     Stylizer (stylizer)                                           Module  Not installed  7.x-1.6
 Chaos tool suite                     Term Depth access (term_depth)                                Module  Not installed  7.x-1.6
 Chaos tool suite                     Views content panes (views_content)                           Module  Not installed  7.x-1.6

Taken individually that is
drush pml \               # Shows table of modules/themes and their status
| grep 'Not installed' \  # Filters for any line WITH 'Not installed'
| grep -v Core            # Filters OUT any line containing string 'Core'

Given that you could do the following too :
$ drush pml  | grep 'Enabled'
$ drush pml  | grep 'Disabled'

(2) With options arguments to drush pml
You could also vary it up a bit with different arguments in the drush pml command
$ drush help pml
Show a list of available extensions (modules and themes).

Options:
 --core                                    Filter out extensions that are not in drupal core.
 --no-core                                 Filter out extensions that are provided by drupal core.
 --package                                 Filter by project packages. You can use multiple comma separated values. (i.e. --package="Core
                                           - required,Other").
 --pipe                                    Returns a whitespace delimited list of the names of the resulting extensions.
 --status=<disabled>                       Filter by extension status. Choices: enabled, disabled and/or 'not installed'. You can use
                                           multiple comma separated values. (i.e. --status="disabled,not installed").
 --type=<module>                           Filter by extension type. Choices: module, theme.

For example, you could use
$ drush pml --no-core --status="not installed" --type=module
 Package                                Name                                                                     Version
 Administration                         Actions permissions (VBO) (actions_permissions)                          7.x-3.2
 BackgroundField                        BackgroundField (backgroundfield)                                        7.x-1.5
 Chaos tool suite                       Better Jump Menus (jump_menu)                                            7.x-1.4
 Chaos tool suite                       Chaos Tools (CTools) AJAX Example (ctools_ajax_sample)                   7.x-1.6

***Note and caution:***  Always try this stuff on a development or vagrant box first. NEVER blindly do this to a production box.

Comment: I understand idea. Thanks. But how can I separate submodules? For example, I see _Node Limit User_ as _Not installed_, but I can't delete _node_limit_ folder because of I use main _Node Limit_
Comment: Can you give a named example of a module with submodules that you're trying to remove? Submodules are sometimes just nested inside the parent module. Though, if they're packaged together, it may not hurt to leave it be. If not authored well, some modules may use libraries or code in child folders. My gut is, if it's packaged together, leave it.
Comment: Otherwise, you could also do a dry run in a VM/Vagrant Box. Do you have a dev or throw away drupal install? Install the module, use devel_generate to make random content, remove and delete folders. See what breaks. Always best to test these things on throw away machines first!
Answer: You could also query the DB.
List of disabled but NOT uninstalled modules (can't be deleted from the codebase)
drush sqlq "select name from system where type = 'module' and status = 0 and schema_version NOT IN (0, -1)"

List of disabled AND uninstalled modules (can be deleted from the codebase)
drush sqlq "select name from system where type = 'module' and status = 0 and schema_version IN (0, -1)"


Imap subfolders not shown in list command - perhaps acls misconfiguration

Question: My goal is to copy the whole folder structure with all mails from one imap account to another.
The tool I am using for this is imapcopy (the java based version from code.google.com since the unix/linux tool packaged with debian doesn't support imaps).
Now, there is one problem: The tool only copies the top-level folders and not the nested ones.
To narrow down the problem I have downloaded the source code of imapcopy and debugged into the code. There I noticed that the folder.list() (which is mapped to the list "%" imap command) returns an empty list. But when I do a getFolder(<subfoldername>) I can access those subfolders. After reading some documentation about the features of imap I think that the problem might be some misconfigured ACLs which prohibit the listing of those folders but allow to read ad write to them.
How should I check this ACLs? which tools do I need for this task?
Answer: I found the solution by myself: It seems that calling open() for a particular folder results in an empty list of subfolders for the same folder. By moving the line calling list() before the line calling open(), imapcopy works as expected. I also appended my changed java code to the already existing issue ticket at the imapcopy project.


Hide users without email address in Exchange GAL

Question: I have some user account without email address in my active directory I , for example admins users, service users and so on.
I found them in the Global address list of Exchange 2013, how can I remove them? I want to leave only users with email address.
This is my current settings checked with Get-GlobalAddressList command  (I think this is the default):
RecipientFilter              : ((Alias -ne $null) -and (((((((((((ObjectClass -eq 'user') -or (ObjectClass -eq 'contact'))) -or (ObjectClass -eq 'msExchSystemMailbox'))) -or (ObjectClass -eq 'msExchDynamicDistributionList'))) -or (ObjectClass -eq 'group'))) -or (ObjectClass -eq'publicFolder'))))
LdapRecipientFilter          : (&(mailNickname=*)(|(objectClass=user)(objectClass=contact)(objectClass=msExchSystemMailbox)(objectClass=msExchDynamicDistributionList)(objectClass=group)(objectClass=publicFolder)))
LastUpdatedRecipientFilter   : ((Alias -ne $null) -and (((((((((((ObjectClass -eq 'user') -or (ObjectClass -eq  'contact'))) -or (ObjectClass -eq 'msExchSystemMailbox'))) -or (ObjectClass -eq  'msExchDynamicDistributionList'))) -or (ObjectClass -eq 'group'))) -or (ObjectClass -eq 'publicFolder'))))

Answer: Seems that there is an attribute to set in AD user settings instead of edit the global query:
Answer: Normally an user without Exchange attributes should not come up in the GAL (it also wouldn´t make sense to show them here). So there are multiple options:
1.)
If the user is a exchange user you can simply hide it from the GAL. There is an option in every AD object which you can set via the Exchange GUI (more infos here). Via that way you can exclude the users you do not wish to come up in the GAL.

2.)
I have seen that some admins copy AD objects and then perform some "hacks" in order to remove the propperies they do not need. Thats not a good option if the user is Exchange mail enabled as for example the following propperties
showInAddressBook, msExchHideFromAddressLists, msExchHomeServerName, msExchUserAccountControl might not be removed, which therefore might cause such issues you experience as the system still discover them as valid Exchange users. So if those accounts are copies by hand, make sure that the accounts do not have Exchange attributes.
3.)
Per out of the box the GAL filter is (taken from Exchange 2016):

(Alias -ne $null -and (ObjectClass -eq 'user' -or ObjectClass -eq
  'contact' -or ObjectClass -eq 'msExchSystemMailbox' -or ObjectClass
  -eq 'msExchDynamicDistributionList' -or ObjectClass -eq 'group' -or ObjectClass -eq 'publicFolder'))

That means only users which have an Exchange mailbox are added to the GAL. However in your environment it might mean the default GAL was adjusted or you are using an additional created GAL with a different setup. You should check the filter here and make sure that it is correct and is excluding the users which aren´t supposed to be in the GAL.
Comment: This is not applicable because these users don't have an email address therefore this page of ECP is not available
Comment: Per default only MailEnabled users will show up/come up in the GAL. So if the user isn´t supposed to be an Exchange mailbox user, did the user has some AD properties which are Exchange related as mentioned in nr2? Additional you should check the GAL filter as per default only Exchange user are part from the GAL. However on your side it might have been changed for some reasons or you are using a 2nd GAL which we do not know.
Comment: I think the problem is that these users were made copying an exinting user with email, than they get all exchange attributes but without a real mailbox...
Comment: Yes if that is done the account still has some exchange attributes and will therefore added to the gal. But it should be very easy to fix as you can use aduc to delete the wrong attributes very quickly.
Answer: had the same issue, this fixed it
Get-GlobalAddressList "Default Global Address List" | Update-GlobalAddressList


Proving that there is no unique factorisation into S-primes

Question: Let $S = \{a+b*\surd(−5) : a, b ∈ \mathbb{Z}\}$. $S$ is a subset of $\mathbb{C}$. We can add and multiply elements of $S$ to get another element of $S$ and all the normal rules (as for $\mathbb{Z}$) hold. We can now define factorizations, divisibility, etc, in $S$ in the same way as for $\mathbb{Z}$. The units of $S$ are the elements $u$ such that there exists an element $v$ so
that $uv = 1$. A factorisation $t = xy$ in $S$ is called trivial if either $x$ or $y$ is a unit.
An element $t \in S$ is called an S-prime if it has no non-trivial factorisations. We define the norm of an element $s = a + b√(−5)$ to be $N(s) = a^2 + 5b^2(= ss^*)$.

Show that there are no elements in $S$ of norm 2 or 3
By considering factorisations of 6 and using norms, show that $S$ does not
have unique factorisation into S-primes

In (1) I can see that no $a$ or $b$ exist such that $a^2 + 5b^2 = 2$ and $a^2 + 5b^2=3$. However, I am not sure how to prove it more explicitly other than do this:
$a^2+5b^2=(a+b)^2 - 2ab + 4b^2$ has to be divisible by $2$ for the norm to exist. Clearly $2|2ab$ and $2|4b^2$ and so any linear combination will divide 2. But we then expect $2|(a+b)^2$ $\rightarrow$ $(a+b)|\surd(2)$ which is impossible since $a$ and $b$ are integers. Similarly, for the norm of $3$ we have that $3|(a+b)^2$ which is again not the case since $a$ and $b$ are integers.
In (2) I am not sure what approach to use. Following the hint I did that $N(6) = N(2*3) = N(2) * N(3)$
 But then if we consider $N(2)$ which implies that $t = a+b\surd(-5) = 2$ we have that there are multiple values of $a$ and $b$ that give $t$. For instance, $a=2$ and $b=0$ or $a=7$ and $b=-5$ and so on. I cannot see at the moment if this helps or not as I do not even know where to start.
I would appreciate any advise!
Thank you in advance!
Answer: No, your proof for (1) is not correct. How did you "deduce" that "$(a+b)\mid\sqrt{2}$"? There are at least two issues with that. First, you can't switch the two numbers in a divisibility statement: $a\mid b$ does not imply that $b\mid a$ (so these two statements are not equivalent). Quick counterexample: $2\mid6$, but $6\nmid2$. Second, taking the square root of a divisibility statement (relation) is a highly questionable operation, exactly because it may introduce non-integers into a relation that was originally defined for integers only, so you end up with a meaningless statement.
But that proof can be done much easier. Let's say $a^2+5b^2=2$, where $a$ and $b$ are integers. If $b\neq0$, then $b^2\ge1$ and $a^2+5b^2\ge5$, so it can't be equal $2$. Therefore, $b$ has to be $0$. With $b=0$, we get $a^2=2$, which is impossible for integer $a$.
In the second part, you seem to be confused with inputs and outputs of the norm function. $N(2)$ does not mean the norm of a number being equal to $2$. On the contrary, here you're given a number, which is $s=2=2+0\sqrt{-5}$ (so $a=2$ and $b=0$), and then $N(2)$ is the norm of this number specifically, which is $N(2)=2^2+5\cdot0^2=4$.
The key to the second question is to find two different factorizations of $6$ into $S$-primes. You will have to prove that the numbers involved are indeed $S$-primes, and you will have to use part (1) for that. You already have one factorization $6=2\cdot3$. You need to show that both $2$ and $3$ are $S$-primes. For example, for $2$, you can start by observing that $N(2)=4$. If $2=pq$, a product of two non-units, then $N(p)N(q)=N(2)=4$, where neither norm can be $1$ (because they are non-units). Then the only remaining way to factor $4$ is $4=2\cdot2$, so $N(p)=2$ and $N(q)=2$ — but we already showed that this is impossible. Similarly for $3$.
This gives you one factorization of $6$ into $S$-primes. The other one is $6=\left(1+\sqrt{-5}\right)\left(1-\sqrt{-5}\right)$.
Comment: When we say that $N(p) = 2$ and $N(q) = 2$ is impossible by the 1st part, how does it show that 2 is S-prime?
Comment: @Blondie: Because we're looking for non-trivial factorizations, other than $2=1\cdot2$ (which isn't much of a factorization is it?). If we show that it's impossible to factor $2$ in any other way, we'll have shown that $2$ is $S$-prime.The key is $N(pq)=N(p)N(q)$, where all norms are non-negative integers. So if $pq=2$, then $N(p)N(q)=N(pq)=N(2)=4$. In other words, $N(p)N(q)=4$ is a factorization of $4$ into two positive integers. How can we factor $4$? Only as $4=1\cdot4$ or $4=2\cdot2$. The first option doesn't really count because $N(p)=1$ implies $p=1$ producing $2=1\cdot2$.
Comment: Thank you for your comment! Having proved that the factorisation is not unique for 6, how can I prove it that it is not unique in general for S?
Comment: @Blondie: That's it -- this is the proof. Unique factorization property means that **each element** has a unique factorization. If at least one element has multiple factorizations, that already means that the property doesn't hold. (We're not trying to show that all elements have multiple factorizations -- that's simply not true. Many elements still have have a unique factorization, but **not all**, and that's what we needed to demonstrate, and that's exactly what we achieved by showing two different factorizations for $6$.)
Comment: Thank you for taking your time to explain this! I now understand it :)
Answer: For 1, you can use the fact that $a^2$ and $5b^2$ are both positive. For there to be any chance of a solution, $b$ must be $0$ (otherwise $a^2+5b^2\ge 5$). It's then clear that no values of $a$ work.
For 2, the idea is to find a different factorisation of $6$ other than $2\times 3$. Norms come in because you still need to check that the elements in this factorisation are $S$-primes – there are primes of $\mathbb Z$ which are not primes in $S$.
For example, $2$ is irreducible. Indeed, if $ab = 2$, then $N(ab) = N(a)N(b) = 4$. This means that either

$N(a)$ or $N(b)$ is $1$, so $a$ or $b$ is a unit, or
$N(a) = 2$, which is impossible by part 1.
Comment: The formatting in the previous comment went wrong & I somehow cannot edit it. So I am reposting the comment so that it is easier to read :) Thank you for your reply! Following your example I did: $N(ab) = N(a) * N(b) = 6$. Hence, we either have that $N(a) = 2$ and $N(b) = 3$ or vice versa which is impossible since by previous part no such norms exist. Or we have that $N(a) = 6$ and $N(b) = 1$ or vice versa which implies that ether $N(a)$ or $N(b)$ is a unit and so there is no unique factorisation. However, this is the case for $6$ and I am not sure how one can generalise to prove for all $S$?
Comment: @Blondie: While it's impossible to edit a comment after a few minutes from posting it (5 minutes or so, I don't remember), you can always delete a comment.
Comment: @Blondie: As for your reasoning in this comment, note that according to the given definition of the norm, $N(6)\neq6$, but $N(6)=N(6+0\sqrt{-5})=6^2+5\cdot0^2=36$.
Comment: @Blondie to show that $S$ does not have unique factorisation, you need to find distinct primes $a,b,c,d\in S$ such that $ab = cd$. So if you can find primes $a,b\in S\setminus\{2,3\}$ such that $6 = ab = 2\times 3$, then your done. The first step is to find such $a,b$ (they exist! Think difference of two squares). Then you need to prove that $2,3,a,b$ are all prime.


Reading non tabular html pages and writing into sql tables

Question: I wanted to create a sql database containing table in which one column is for question , 4 columns are for options and one is for right answer (there may be extra column containing topic name as well ) and i want to enter a lot of questions into this table but the problem is the questions i am getting are in the form of html pages that are not in table form . They are in this form screenshot . So how do i do it?
The sample html page
Comment: I don't know Python, but if you view the HTML table as a DOM component, then figuring out how to iterate it to generate SQL rows becomes much easier.
Comment: What do you mean by " the questions I am getting are in the form of HTML pages"? Do you need to scrape or obtain these pages first? Why do you have tagged your question as PHP and Python? I feel your question is too broad.
Comment: Yeah i have to obtain those pages first . I have tagged php and python coz i think it could be done by using anyone of those ..i am basically interested in script that will enter the data into tabular format fetching data from source that are in non tabular format
Answer: Well, You can maintain it in one single table as there are only four answer options but that is not the effective way to do it. As Database Design logic dictates that you have to Normalize the Database tables in order to maintain consistency. The best approach for this, as per database design, is to have 3 tables. One for holding the questions, the second for holding the options and the third for the right answers (You can merge the right answer with the first if you like).
When you want to get the answer options then you can get them using JOINs. The main advantage of this approach is its very expendable i.e., if, in the future, your number of options and number of correct answer changes, then they can be easily maintained.
I have prepared a sample Db structure on how you can achieve this. You can find it Here. The code that I have shared is a sample one. Please let me know if this is what you were looking for.
Hope this helps.


Dimension of affine variety mod $p$ can only increase

Question: Let $X$ be an affine variety defined by polynomials over $\mathbb{Z}$.
Reducing the polynomials modulo $p$, we obtain a variety $X_p$ defined over the finite field $\mathbb{F}_p$.

Is it true that the dimension of $X_p$ is larger or equal to the dimension of $X$?

Note: It seems likely to me that the dimension stays the same for all but finitely many primes $p$, and this answers says that it is the case for projective varieties. My question is different: I'm asking about affine varieties, I'm asking about all primes, and I'm only asking for an inequality.
EDIT: To make the second part of the question explicit:

In addition, is it also true that $\dim X_p=\dim X$ for all but finitely many primes $p$?
Comment: I assume "dimension of $X$" means "dimension of $X$ as a variety over $\mathbf Q$" or something equivalent. In that case the answer to the first question is no: If $X$ is the subvariety of $\mathbf A^1$ defined by $2x=1$ then its dimension is 0, but its reduction mod 2 has dimension $-\infty$.
Comment: Dear Sean, for sure it is true in the projective case. There is a great discussion at this MO question: https://mathoverflow.net/questions/193/when-is-fiber-dimension-upper-semi-continuous
Comment: @LazzaroCampeotti: Yes, you are right. Do you know if "dimension cannot decrease" is true for projective varieties, as implied without proof by the answer to the question I linked to?
Answer: Let me state the following result (Lemma 05F7 in the Stacks Project):

Let $f:X\rightarrow S$ be a morphism of finite type where $S$ is an
irreducible scheme (with generic point $\eta$). If $n=\mathrm{dim}X_\eta$
then there exists a nonempty open $U\subseteq S$ such that for
all $s\in U$ one has $\mathrm{dim} X_s=n$.

Hence, whenever you have a variety $X$ over $\mathbf{Z}$ (which means a $\mathrm{Spec}(\mathbf{Z})$-scheme of finite type), the dimension of $X\otimes_\mathbf{Z} \mathbf{F}_p$ (the fiber over $(p)$) is equal to that of $X\otimes_\mathbf{Z}\mathbf{Q}$ (the fiber over the generic point of $\mathrm{Spec}(\mathbf{Z})$) for all but finitely many primes $p$.
Finally, your question amounts to knowing if $\mathrm{dim}X\leq\mathrm{dim}(X\otimes_\mathbf{Z}\mathbf{Q})$, but this is not always true: consider $X=\mathrm{Spec}(\mathbf{Z}\left[ X\right] /(2))=\mathrm{Spec}(\mathbf{F}_2\left[ X\right] )$ so that $\mathrm{dim}(X)=1$ while $\mathrm{dim}(X\otimes_\mathbf{Z}\mathbf{Q})=-\infty$.


Commerce product entity not being saved by EMW from another entity form submit

Question: I'm using the module Commerce Stock Sources to manage different stock locations for my products.
When saving the Commerce stock sources form, on form submit, I want to update a field value on the Commerce product entity. The field is an Entity reference field.
The problem is that I can't get the field updated. No notice or error returning.
    //first I'm getting the values to be set; will have a simple array of IDs
    if (!empty($form_state['values']['plugins']['plugin_settings'])){
                $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
        }
    //next I'm loading the product entity; I have checked, the product is loading OK
    //and then the wrapper and the operations
    $product_entity = entity_load_single('commerce_product', $form_state['complete form']['#product']->product_id);
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

The field is not updated. I've checked to see if I can read values from product using entity_metadata_wrapper() and it works. When I try to update any field, it doesn't work.
I tried updating with field_attach_update(), but it doesn't work either.
        for($i=0; $i<count($selected_sources); $i++){
          $product_entity->field_product_location_store[LANGUAGE_NONE][$i]['target_id'] = $selected_sources[$i];
        }
        field_attach_update('commerce_product', $product_entity);
        entity_get_controller('commerce_product')->resetCache(array($product_entity->product_id));

Any thoughts?
Answer: It's seems that by using the product entity directly from $form_state['complete form']['#product']; the entity_metadata_wrapper() works as expected and it saves the values.
if (!empty($form_state['values']['plugins']['plugin_settings'])){
    $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
}
    //get directly the product, without entity_load_single()
    $product_entity = $form_state['complete form']['#product'];
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

Although the object loaded by entity_load_single() is identical with the object obtained by $product_entity = $form_state['complete form']['#product']; the entity_metadata_wrapper() works only for the second case, which seems more logical and is faster.


Splitting field of $X^2-2$

Question: I have a question about the uniqueness of splitting field $L$ of polynomial $X^2-2$ over $\mathbb{Q}$. By factorizing $X^2-2 = (X-a)(X-b)$, we know the splitting field is $L = \mathbb{Q}(a,b)$, and we can show $\mathbb{Q}(a,b) = \mathbb{Q}(a) = \mathbb{Q}(b)$. An obvious choice of $a$ would be $\sqrt{2}$.There is a proposition saying here any two splitting fields over $\mathbb{Q}$ of this polynomial are $\mathbb{Q}$-isomorphic, but another splitting field of this polynomial can be $L$ generated by two elements $u,v$ unrelated to $a,b$, so I am wondering if there exists an isomorphism $\phi: \mathbb{Q}(a,b)\rightarrow \mathbb{Q}(u,v)$ which is not the identity map? Or there is only one possibility of $\phi$?
Thank you in advance.
Comment: Yes, there does exist an isomorphism between $\mathbb{Q}(a,b)$ and $\mathbb{Q}(u,v)$, which doesn't need to be the identity. (see [here](https://websites.math.leidenuniv.nl/algebra/algebra3eng.pdf), theorem $21.16$ on page $15$)
Comment: It's important to note that a splitting field is unique inside every algebraic closure. If you take a different algebraic closure, the splitting field will be a totally different field (with possibly different roots of the polynomial), and in this case the identity map makes no sense at all.
Comment: It is also possible that $\Bbb{Q}(a,b)$ and $\Bbb{Q}(u,v)$ are two different sets. For example, we could have $\Bbb{Q}(a,b)\subseteq\Bbb{R}$ with $a=\sqrt2$, $b=-\sqrt2$. And we can also have $L=\Bbb{Q}[X]/(X^2-2)$, which has, a priori, relatively little to do with real numbers. We would then have $u=X+(X^2-2)$ and $v=-X+(X^2-2)$. Still we have an isomorphism between $\Bbb{Q}(\sqrt2)$ and $L$ as promised by the uniqueness (up to isomorphism) of the splitting field. Actually two isomorphsims, because $a$ can be mapped to either $u$ or $v$.
Answer: There are exactly two possibilties for $\varphi$ and that is because there are two automorphisms of ${\mathbb Q}(\sqrt2)$, namely the identity and the one that sends $\sqrt2$ to $-\sqrt2$.
Comment: You seem to assume that $\mathbb{Q}(\sqrt{2})$ is the only splitting field of $X^2-2$. The comments have shown that this is just not true.
Comment: I did try to formulate my answer carefully so it works even if the OP is not (implicitly) working within a single algebraic closure. It is unclear to me if the OPs question is really about the existence of multiple (isomorphic) splitting fields or about multiple automorphism between two (equal or unequal) splitting fields.

Splitting field of $X^2-2$


How to remove a views template file in theme folder?

Question: I put .tpl.php file inside my theme folder to override views output. Then I deleted this file because it was no use for me. And did "Rescan template files". Now it cannot find this file and gives errors on the page.

File not found, in folder sites/all/themes/mytheme/templates/

I also cleared all my caches.
How can I remove this file for good?
Answer: It looks like my problem is related with APC or some sort of caching. After removing the file, I run

$ httpd restart

from the command window on the server, then the errors are gone. Probably it cleared the APC cache.


ajax/jquery help - displaying a dynamically created list item when clicked

Question: I'm new to the ajax world and was hoping you guys can help.
Currently, I can dynamically create a list of items via ajax. The problem I'm running into is that when I click on a list item created by ajax, it displays all of the list items.  I only want to display the list item i clicked on.
Below is a code snippet to give you an idea of what i'm trying to do.
  $(document).ready(function() {

$('div.calendar_content').click(function() {
    $('#product_list ol li').remove();
        day_num = $(this).prev().text();
        if(day_num.length == 1)
        {
            day_num = 0 +day_num;
        }
        today_date = <?=$year ?> +'-'+<?= $month; ?>+'-' +day_num;

        $.ajax({
            type: "POST",
            url: "<?= site_url()?>/admin/post_rooms",
            data: {'today_date':today_date},
            dataType: 'json',
            success: function(data){
                $.each(data.returned_val, function(key,value){
                    content = '
Dorm Room '+ value.room_no +' '+value.first_name+' '+value.last_name+'
';
                    $(content).appendTo("#product_list ol");
                });
            }
        });
   });

   $("#product_list ol ").click(function(){
        alert($('#product_list ol li').text());
   });
});

Answer: $("#product_list ol li").on('click', function(){
   alert($(this).text());
});

Comment: hello, thanks for your help.  I tried it but received an error in firebug:  $("#product_list ol li").on is not a function
Comment: Maybe your jQuery version is too old, they added the `on` feature in v1.7 (check http://api.jquery.com/category/version/1.7/)
Answer: success: function(data){
    $.each(data.returned_val, function(key,value){
        content = '
Dorm Room '+ value.room_no +' '+value.first_name+' '+value.last_name+'
';
        $(content).appendTo("#product_list ol");
    });
    //The hiding part
    $("#product_list ol > li").click(function(){
        $(this).siblings().hide();
    });
}

In this way you register a click event on the list items afer you generated them. When you click on the item the function takes all the item's siblings and hides them.


What is bad about Roman Numeral Analysis?

Question: I have studied Roman numeral analysis in my theory courses, and I think that it's a good way of describing and understanding classical music, especially that of the classical and early romantic periods.
I have heard from my colleagues that some theorists disagree.  I've tried to find arguments online that Roman Numeral analysis is not useful, but I have not found any. What case (or cases) do theorists make against RNA?
Comment: If your friends are arguing it's uselessness,get them to provide arguments why.
Comment: You're not going to find any arguments that Roman Numeral Analysis isn't useful, because of course it *is* useful.  But that doesn't mean it has to be everyone's favorite way of analyzing or understanding music, and it doesn't mean that it is equally useful for all types of music or for all kinds of analysis.  It's not particularly useful for atonal music, for example, nor is it useful for non-Western music.  Dr. Mayhem is right: if your colleagues say "some theorists" disagree, ask them which theorists, and why do they feel the way they do?
Comment: Are you looking for the antithesis of harmonic analysis or just the use of Roman Numerals vs some other means of representation?
Comment: Check out the Nashville Number System.Similar to Roman, but using Arabic numbers! I prefer the Roman as it's easier to differentiate the chord from its kind, e.g. VI7 is simpler to read than 67.Food for thought.
Comment: It's not worth answering the question without an alternative.  These "colleagues" who disagree should offer an alternative.  What is it?
Comment: This is a very good question. Most musicians it's true are completely unaware of the alternatives that being Functional Analysis and this is because of a huge lack in our music training colleges. Both are good but both should be taught.
Comment: @Ootagu, your comment about alternatives is valid but saying "what's bad about..." is not in my opinion.  This is a big red herring designed to pit one method against others.  Other methods can be great without this method being "bad".  I've never come across something I cannot express with Roman Numerals, and I am sure given creativity one can break other notation systems with a funky new chord or functional relation.
Comment: I agree; I just want to clarify the original question was not mine. Maybe my contributions below were voiced too conflicted however.
Answer: The obvious shortcoming is that after we leave the classical period, music and tonality becomes too complex for Roman numeral analysis to be completely useful. So, we don't need to mention 9th chords or jazz 7ths and the like, and I believe you understand that already from the question.
For classical music, Roman numeral analysis is the most widely accepted method for describing common practice harmony, and I would agree that it is useful enough that every musician should be familiar with it. Furthermore, figured bass notation is highly related to Roman numeral notation in its more basic formats, and as such is important for musicians to learn especially if they are to be performing Baroque and early music.
However, the very obvious shortcoming of Roman Numeral analysis is that it analyzes music primarily in a vertical fashion, which is contrary to how we as listeners perceive music: as changes in sound over time, i.e. horizontally.
The works of J.S. Bach have, in many cases, eluded academic consensus on how they should be analyzed for centuries, and it is in the music of J.S. Bach that other methods of analysis become truly useful.
One such method is known as the Heptachord Shift. In short, rather than analyzing the harmony and function of each chord in isolation, this method tracks changes in the heptachord (that is, the set of seven pitches that defines musical tonality, or Do through Ti) over time by classifying notes outside of the current tonality to be alterations to the existing heptachord. In doing so, it aims to more accurately approximate how we experience music by analyzing change over time. In other words, a horizontal analysis.
The resource for this system of analysis is a 2001 paper by Marianne Ploger, who developed it, titled:
Heptachord Shift: A Real-Time Approach to Tracking Tonal Modulation Employing Precepts Observed in the Works of J.S. Bach. Marianne Ploger, 2001. (link)

(Your best bet on finding the article might be the University of Michigan master's thesis archives, or by emailing the writer directly.)
Comment: Why does this fail in Jazz?  I've seen jazz piano books that present full chord charts completely in roman numeral form with no key chosen.  It's actually very cool.  You can read it down in any key on any instrument.
Comment: This is an old thread which somehow got revived, but I am wondering about your characterization of horizontal and vertical. Are you saying that the "vertical" concept is, say 3 notes, stacked in a moment in time (a time-slice) whereas the "horizontal" is looking at those three notes stacked as the convergence of three melodic lines (etc)?
Comment: @horatio Yes, essentially. Bach F minor fugue from WTC I (I think) has a moment with three notes in stacked whole steps. You can't really call that anything sensible if you look at that chord in isolation, but you _can_ follow each voice and just observe the chord as a neat outcome.
Answer: The only thing that I have found difficult to describe in Roman Numerals is 9th and higher chords in inversions.  For example, a C9 chord with the G in the bass would be described in lead sheet notation as C9/G but my theory class never really came up with a consistent way to describe inversions beyond 7ths.
I sadly don't have any texts or examples beyond my own experience there.  The downside to the lead sheet notation listed above is that it does not describe chordal relationships and harmony. :-P
I think you'll find pros and cons for any method -- and the more complex it is, the simpler it'll be to just use the notes!
Answer: Let me add my US $0.02.
Roman numeral analysis is very good for studying a piece of music and figuring out the harmonic progression.
However, if all you want to do is sight-read and play the music on your instrument, it's more efficient to name chords by their letter name because it's easier to read and play.
Let me give a very simple example. If you are presented with I - IV - V and asked to play it, you have to figure out the key center at that moment in the music, and which chord names correspond to those numbers. However, if you are presented with D major - G major - A major, you don't have to stop and think so much about what to play. The more complex the chords, as in jazz, and the more the music modulates from one key center to the next, the more that Roman numeral analysis gets in the way of performance. Borrowed chords (V7 of V or vii dim 7 of V, for example) would be hard for anybody to figure out what to play on sight-reading, but if you just label the chord by its root note and give a slash indicating the bottom note (indicating the inversion of the chord), it's easier to sight-read and to improvise on top of it.
Comment: @WheatWilliams On guitar I find it much easier to play using roman numerals. That's because the scales have the same shape in all 12 keys. Also when playing anything other than jazz it's easier to improvise while reading numerals because the scale doesn't change at every chord, so the numbers tell you what you are going to hear next (i.e the function of the chord), so that the idea you'll come up with sound appropriate for the upcoming cord (with no need to think about chord tones). Note names give you technical information however roman numerals musical information.
Comment: What's that in yen?
Answer: I agree with much of the answers. For me they are great but yes it can get tricky with modern key changes, but if you think of modulations as phrases that arrive at a goal (unless abruptly jumping right into a new key with out prep) then thinking in terms of common harmonic patterns into the new goal key as I can be useful.
Let's say I'm in Cmajor and now I start a II-V-I pattern into Bb. But this is an analysis prep tool. Also using the flat/sharp signs in conjunction with romans ie.bVI7-V7-I etc helps to see how the chords are functioning chromatically. I think they're more objective and easier to keep track of when looking for musical patterns (Substitutions in jazz).
Also when I consider the function of voicings that I like by ear I can consider the notes over many different roman based patters and see how far out or in it really is. So I say use them but in conjunction with other symbol naming systems and mostly in analysis pattern observing/composition mode. I don't have much experience with atonal music. Sorry if my answer is too much in praise and jazz based.
Answer: Roman numeral analysis (RNA) has a variety of limitations — such as in analyzing non-Tonal music — as outlined in other answers. However, there is a specific and ongoing "controversy" among music theorists with regard to RNA.
Beginning in the mid 1980s, a number of influential theorists began constructing what is now known as neo-Riemannian theory, which provides an alternative to RNA for describing harmony and voice-leading. Neo-Riemannian theory developed in part to better describe late Romantic music (as opposed to Classical or early Romantic), which is to say, the highly chromatic music created at a time when composers were actively attempting to undermine the Tonal system (that RNA describes). The case for neo-Riemannian theory is that it better describes the harmonic transformations in highly chromatic music (say, Brahms or Wagner) than RNA. Although it can be (and has been) applied to earlier composers (particularly when they wrote highly chromatic music), its development has primarily focused on the late Romantic and later musics.
There can be heated debate between adherents of each theory as well as among those developing neo-Riemannian theory itself. This is what I suspect you and your colleagues were hearing about, as it continues to be a highly active area of research.

For a broad introduction to neo-Riemannian theory, try Wikipedia's "Neo-Riemannian theory".
For a more detailed history and explication of the theory, the major paper is Richard Cohn's "Introduction to Neo-Riemannian Theory: A Survey and a Historical Perspective".
For an engaging article about the application of neo-Riemannian theory, plus a taste of the debate, there is Kyle Gann's article "So I'm Neo-Riemannian: Who Knew?" and the comments following. (The "Dmitri" in the comments is, presumably, Dmitri Tymoczko, an influential theorist, and Richard Cohn [see above] is one of the major developers of neo-Riemannian theory.)
For a very brief discussion with some very useful links, see Neo-Riemannian Theory and Tonal Music on our very own SE site.
Comment: I look forward to reading that Gann article. I've never heard of it, and I sense that it will lack some of the heavy-handedness that scholarly theory writing typically has. Nice find!
Answer:
What is bad about Roman Numeral Analysis?

I don't actually recall hearing criticism of RNA, but there are things I dislike about it.

There are several, incompatible notation standards. E.g. wikipedia lists: conventional notation, alternative notation, chord symbols (https://en.wikipedia.org/wiki/Roman_numeral_analysis#Diatonic_scales) and Jazz/pop numerals (https://en.wikipedia.org/wiki/Roman_numeral_analysis#Jazz_and_pop_numerals).
I can see people on Music SE getting confused if they follow different conventions on when to put accidentals or when to use capital or small letters.

It doesn't provide that much understanding of functional harmony. There are only 3 primary functions (T, S, D), but as many as 7 RN. The numerals don't tell anything about functions of chords other than I, IV and V. Why does ii-V-I sound good? (Could it be ii has something to do with IV?) Why V can resolve deceptively to vi? (Could it be vi and I have something in common?) You just have to accept it and learn by heart.

An advantage of RN is that many people recognize it, but it fails to be a consistent notation system or informative analysis tool.
Comment: @user1079505  Ok, will do. I really found the kernal of your answer was right on the mark and so I did not want to make a new post since I felt indebted to your insight but since you are ok with that I will post it as a separate answer.
Comment: By "fails as a notation system", do you specifically mean that it's inconsistent / people follow different conventions, or are there other downsides?
Comment: Also, did you mean to say 3 primary "functions" rather than triads? (I would argue that memorizing which chords have which functions is just as arbitrary as memorizing which roman numerals have which functions. Is there a way in which the chords don't accurately reflect the function?)
Comment: @awelotta 1. There are multiple conflicting conventions, and some users seem even unaware of that. That's bad enough for me. 2. Yes, I meant 3 functions, T, S and D. But RNA gives us things like supertonic, mediant, submediant, and "one that shall not be named". These are not functions. One could argue that this allows to write RN without trying to understand the underlying harmony, but then it cannot be called "analysis".
Comment: This answer is actually the best one and not only for it's correctness but also because it answers the question directly. The poster asked about Common Practice harmony. Yes the main fault is in RNA's inability to link relations between chords. What is the relation between I and ii...? Only Functional Theory can show this relationship!
Comment: @Ootagu your proposed edit is a complete rewrite of my answer. I appreciate the effort, and I don't criticize what you wrote, but it would feel more appropriate if you posted it as a separate answer.
Comment: "It doesn't provide that much understanding of functional harmony." Au contraire. RNA is exactly designed to describe functional harmony, and every numeral has a specific (set of) functional role(s) and relationships. The language of RNA is well established and understood, but requires study -- in the same way any language requires study. Also, chord symbols in particular, have nothing to do with RNA; they're just a shorthand for indicating chord names.
Comment: @Aaron The fact that it is designed to do something, doesn't mean it does it well. It's my personal observation, based e.g. on how people use and understand RNA on Music SE. Looking at languages... how about programming languages? There are languages that are easier or more difficult to understand. Those that communicate the idea better, and more directly or others than do it in a complicated and confusing way.
Answer: The main criticism against Roman Numeral Analysis (RNA) regards its foundational premise. Although RNA appears to clarify the music by naming each chord within a key by its scale degree value (I, ii, IV, etc.); this does not actually amount to any understanding of how chords are related to each other or what the chords mean within a given key.
The lack of real meaning in RNA can be illustrated as follows. Why does ii-V-I sound good? (Could it be ii has something to do with IV?) Why can V resolve deceptively to vi? (Could it be vi and I have something in common and if they do how does the naming of vi and I show any type of relationship). Or consider this, why is vii related to V? If they are related shouldn't their numerical value be closer together or even the same? You just have to accept it and learn it by heart as in RNA there is no underlying logic which governs the relationship of chords or their logical progression.
Functional Analysis (FA) does however show how chords are related and offers how to make logical progressions. For example in FA, the I chord and the vi chord are termed Tonic (T) and Tonic Parallel (Tp) (note: parallel means relative in German theory). So immediately you can see how those two chords (I and vi) are very near in function because they are both given the base name T (one is T, the other is Tp). Take for example V and vii; in FA those are termed "Dominant" and "Dominant 7 with omitted root"; again you can see how they are shown to be near to each other as they both have the same Dominant base. Hugo Riemann is the main proponent of Functional Theory but his theory is so little understood in North American that many musicians are not even aware of this system.
Comment: This post doesn't reflect a solid understanding of RNA. The Roman numeral assigned to each chord also has well understood and accepted meanings in terms of how that chord relates to the others around it. That's why, for example, a C Major chord has different Roman numeral designations depending on its harmonic context and function. You are correct, however,  to point out that neo-Riemannian analysis is more directly tied to voice leading rather than harmonic function relative to a tonic. Neo-Riemannian analysis is named for Hugo Riemann, but is a separate from his theories.


Como ponho barra de rolagem no card do materialize?

Question:

Título da Reunião

    <form name="form_message" id="form_message" method="post" action="set_message.ajax.php">
      <input name="nickname" type="hidden" id="nickname" value="<?php echo $_SESSION['nickname']; ?>">

     <input name="message" type="text" autofocus required class="textbox_message" id="message">

  <button class="btn-large red darken-3  waves-effect waves-light" id="btn_send" name="action">
      send
  </button>

Estou criando um chat, mas queria que o card ficasse fixo em vez de aumentar de tamanho toda vez que aparece uma msg.Como faço para colocar uma barra de rolagem?
Comment: Coloque o código que já desenvolveu se possível para obter maior ajuda no site.
Answer: Limite a altura do card com a classes de tamanho, coloque a classe small para o card ter tamanho máximo de 300px, a classe medium para o card ter tamanho máximo de 400px ou a classe large para  o card ter tamanho máximo de 500px;

Título da Reunião

Mais informações acesse aqui.


Vinculum number of 989?

Question: To find vinculum number I was subtracting finding the complement of 989 and cosidering the number to be 0989 I raised the 0 to 1 so my answer was 1011 , but why was the answer given 1111 ? Do I also have to raise the 0 by 1 if the next number is above 5 ?
Comment: Some googling makes me think you mean *vinculum, but even so I don't understand the use of this technique. What computations are you trying to do, and why must you do them mentally instead of on paper or with a calculator?
Comment: @ZubinMukerjee sorry its vinculum my fault . I am trying to learn mental math because we are not allowed calculators in exams .
Comment: Do your exams also not allow pencil and paper? :)
Comment: Do you mean [square root](https://en.wikipedia.org/wiki/Radical_symbol#Origin)?
Comment: It seems to me that $0989=10\bar1\bar1=1\cdot10^3+0\cdot10^2+-1\cdot10+-1$, not $1\bar1\bar1\bar1$ or $1\bar1\bar1\bar1$ or any number with four digits that are $1$ or $\bar1$.
Comment: @SteveKass you answer gives 1089. Actually consider 1000-10-1
Comment: Blincer, I'm confused. My answer is 1000-10-1, which is what you say I should consider.
Comment: @ZubinMukerjee they allow pen and paper , but the rough space is limited , and also I want to understand this and to learn this technique I dont see anything wrong with it .
Answer: 1011 is the right answer.
In fact, when you take the complement of the numbers directly preceding a number greater than 5 you have to add to 9 instead of 10.
I recommend the following slide show:
https://slideshare.net/culturalcomputingindia/vedic-mathematics-vinculum-numbers.
Comment: For those who might be puzzled, my understanding of Vedic vinculum numbers is that they are base-$10$ numbers that can use negative digits, which are represented either with a vinculum (overbar) or as boldface. Any integer can be written in base $10$ using digits between $-5$ and $5$, so it can be simpler to convert to a vinculum number before performing mental (or by-hand) arithmetic, since you only need the "times table" up to $5\times5$. For example, $27\times82$ equals $3\bar3\times1\bar22=3\bar300+\bar660+6\bar6=3\bar960+6\bar6=3\bar82\bar6=2214$.
Comment: @SteveKass thanks

Vinculum number of 989?


flutter - android - http.get never returns in release mode

Question: I am writing a flutter app for android and ios. To log in, the app uses the http package (version 0.12.2) : http.Response response = await http.get(url);.
In iOS, everything works fine. In Android, the debug mode works also fine, however, if I build the apk and install the app from this release apk, the async method http.get never returns.
I use Android 9 on a OnePlus 3 (OxygenOS 9.0.6).
I am very new to flutter and can't figure this out.
A similar issue is open in github but concerns flutter for web.
Here is a minimal code to reproduce.
To test it, you should build the apk (Build > Flutter > Build apk)), copy and paste the apk in your phone files, install the app from the apk, press the button PRESS ME, done will never be displayed.

main.dart

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Test flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _status = "Press the button";

  void _test() async {
    String url = "http://dummy.restapiexample.com/api/v1/employees";

    // Send HTTP request to the server
    http.Response response = await http.get(
        url
    );

    setState(() {
      _status = "done";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // Test button
            RaisedButton(
                onPressed: _test,
                child: Text(
                  "PRESS ME",
                ),
              ),
            Text(
              '$_status',
            ),
          ],
        ),
      ),
    );
  }
}

pubspec.yaml

name: flutter_test_app
description: Test app for reproducing minimal example

publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.2

  cupertino_icons: ^0.1.3

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

Answer: Hi you need to add networking permission to AndroidManifest.xml
check this official documentation on flutter networking
https://flutter.dev/docs/development/data-and-backend/networking
it is located in android/src/main/AndroidManifest.xml
<manifest xmlns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET" />
 <application ...
</manifest>

Comment: I've already added the INTERNET permission, but the issue still present, I've the same problem described in the question
Comment: @MouaadAbdelghafourAITALI were you able to find a solution ?
Answer: Apart from allowing access to the internet with the abovementioned permission line, (or get a hostname lookup error) to use http.get from an app in RELEASE mode you need to add the following more lines within the application section of your main manifest file else it just silently hangs (times out, if you have one).
It is beyond me why these restrictions do not apply when debugging.
<intent-filter>
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
   <data android:host="YOUR.DOMAIN.NAME"
                    android:scheme="https" />
</intent-filter>

I am not sure if this can be trimmed further.


How to sort numpy array by row sum and extract top N rows

Question: For example, given matrix
array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [ 0,  1,  2,  3,  4,  5],
       [24, 25, 26, 27, 28, 29]])

and top_n=3, it should return
array([[24, 25, 26, 27, 28, 29],
       [18, 19, 20, 21, 22, 23],
       [12, 13, 14, 15, 16, 17]])

This function should return a np.ndarray of shape (top_n, arr.shape[-1]), given the input 2D matrix arr.
Here's what I tried:
def select_rows(arr, top_n):
    """
    This function selects the top_n rows that have the largest sum of entries
    """
    sel_rows = np.argsort(-arr,axis=1)[:top_n]

    return sel_rows

I also tried:
sel_rows = (-arr).argsort(axis=-1)[:, :top_n]

to no avail.
Comment: Casting the array to negative with `-` is less efficient that slicing the data at the end. For the small sample this isn't an issue, but casting all the values to negative in a large array will be somewhat slower, which is verified with a `%%timeit` test.
Answer: You can use this simple 1-liner a[np.argsort(a.sum(axis=1))[:-top_n-1:-1]]
a.sum(axis=1) sums along axis 1
np.argsort(..., axis=0) argsorts along axis 0 (axis=0 is default option anyway so could be omitted)
...[:-top_n-1:-1] picks the last top_n indices in reverse order
a[...] then grabs the rows
%%timeit comparison
# data sample
a = np.random.randint(0, 101, (100000, 1000))

%%timeit
a[np.argsort(a.sum(axis=1))[:-3-1:-1]]
[out]:
9.73 ms ± 122 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
a[np.argsort(-a.sum(axis=1))[:3]]
[out]:
9.9 ms ± 303 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%%timeit
sorted(a, key=lambda x: sum(x))[:-3-1:-1]
[out]:
1.04 s ± 36.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Answer: Your code almost works, but you need to compute the sum of each row before sorting. You can try this:
import numpy as np

top_n = 3
arr = np.array([[ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23],
       [ 0,  1,  2,  3,  4,  5],
       [24, 25, 26, 27, 28, 29]])

arr[np.argsort(-arr.sum(axis=1))[:top_n]]

It gives:
array([[24, 25, 26, 27, 28, 29],
       [18, 19, 20, 21, 22, 23],
       [12, 13, 14, 15, 16, 17]])

Comment: The answer should explain that the purpose of the `-` is to reverse the order
Answer: Without numpy, you can use the built-in function sorted combined with argument key:
sorted(A, key=lambda x: sum(x))[:-top_n-1:-1]

Comment: This implementation is highly inefficient and should not be used with numpy arrays. For an array, `np.random.randint(0, 101, (100000, 100))`, this is 107 times slower than the numpy implementations.


How can I extract id attribute in the same file to be used in query

Question: In my website I have drop down box  and I made event to know which element selected from the user .. and it works .
I can retrieve the value and print it on the screen using id attribute !!
This function will work when user Select from drop down

The drop down box reads from database
echo "<select name = \"services\" id = \"services\" onchange = \"SelServ()\">";
//my connection
$myCon = new mysqli("localhost","root","","mss");
if(mysqli_connect_errno()){
    printf("Connect Failed : %s\n",mysqli_connect_error());
}
else{
    $sql = "SELECT ServID ,ServName FROM service";
    $result =  mysqli_query($myCon,$sql);
    if($result){
        while($StaffArr = mysqli_fetch_array($result,MYSQLI_ASSOC)){

            $servName = $StaffArr['ServName'];
            $ServiceID = $StaffArr['ServID'];
            echo "<option value = \"".$ServiceID."\">".$servName."</option>";
        }
    }
    else{
        printf("Couldn't retrive records !
 %s",mysqli_error($myCon));
    }
}
echo "</select>";

And I'm using div to retrieve selected item
$servIDHTML = "

";

I want to extract the value of id and included in sql statement to affect in seconed drop down box in the same page !!
Any idea?
Comment: You need ajax to be able to populate the 2nd select box. http://api.jquery.com/jquery.ajax/
Comment: you need to provide some code, what you have done and what are your issues, you question is very open and can be done in a lot of different ways. you have to be specific.
Answer: You must use ajax:-
Let's say you have 2 dropdown parent_id and children:-

<select name="parent_id" id="parent_id">
  <option value="">Select ID</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

<select name="child" id="child">
  <option value="">Select Children</option>
</select>

Include the following ajax at the bottom of your page:-

PHP file where you can execute the SQL query based on your selection and return the result in options:-
ajax.php
if($_POST){
    $parentId = $_POST['parentId'];
    $sql = "SELECT * FROM TABLENAME WHERE parent_id=".$parentId;
    /*
     Fetch the result, prepare options for select and echo them
    */
}

Comment: What do you mean by if($_POST)?? is that mean if the user click on the button on the page or what ?
Comment: Actually I tried those codes but they didn't give me results!!
Comment: Those are just the explanation, how you can implement this.It's a simple concept where you can pass the parent id using ajax and load the next dropdown based on the previous selection.
Comment: I know that . I modified them according to my code! .. But also it doesn't work !!


502 Bad Gateway on editing or creating only for one content type

Question: Drupal 9 project. I can create and edit all content types but one. I get a 502 Bad Gateway from Nginx. Theese are the logs:
<code>2022-05-05 10:39:11 Error   ***.**.***.***  503 GET /node/6095/edit?destination=/admin/content HTTP/1.0 https://dev.mywebsite.com/admin/content Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36 20.8 K  Acceso SSL/TLS a Apache
2022-05-05 10:39:14 Error   ***.**.***.***      AH01068: Got bogus version 100, referer: https://dev.mywebsite.com/admin/content                Error de Apache
2022-05-05 10:39:14 Error   ***.**.***.***      (22)Invalid argument: AH01075: Error dispatching request to :, referer: https://dev.mywebsite.com/admin/content             Error de Apache
2022-05-05 10:39:14 Error   ***.**.***.***      11051#0: *1230277 upstream sent too big header while reading response header from upstream
</code>
Answer: This appears to be a well-understood, standard NGinx as proxy occurrence.


Why does this output print a blank file?

Question: This little code snippet should output a file that contains text:
public static void main(String[] args) {
    try{
        Path gabblePath = Paths.get("C:/Users/AlterionX/Documents/"
                 + "NetBeansProjects/File Creator, Function Example/src/file/"
                 + "gabble.txt");
        Charset cs = Charset.defaultCharset();
        Scanner scanner = new Scanner(System.in);
        String total = scanner.nextLine();
        System.out.println(total);
        BufferedWriter writer = Files.newBufferedWriter(gabblePath, cs);
        writer.write(total);
        System.out.println("total printed");
    }catch(IOException ex){
        System.out.println("IO Exception");
    }
    System.exit(0);
}

Instead, it creates and returns a blank file. It runs successfully, and all the other stuff, it just creates a blank file.
Should I be closing the scanner or is it something else?
EDIT
I took out the scanner and changed it to an actual string, still didn't work.
Comment: I might be off here - but try flushing it.
Comment: yeah, call `flush` or `close` on `writer` instance
Comment: close the `BufferedWriter` via `writer.close()`
Answer: Try the FileWriter class instead.
FileWriter fw = new FileWriter(gabblePath);

fw.write(total);
fw.flush();
fw.close();

You just need the path to your output file and the contents.
Answer: Close the Writer and make sure you do it unconditionally (i.e. a finally block).
public static void main(String[] args) {
    BufferedWriter writer = null;
    try{
        Path gabblePath = Paths.get("C:/Users/AlterionX/Documents/"
                 + "NetBeansProjects/File Creator, Function Example/src/file/"
                 + "gabble.txt");
        Charset cs = Charset.defaultCharset();
        Scanner scanner = new Scanner(System.in);
        String total = scanner.nextLine();
        System.out.println(total);
        writer = Files.newBufferedWriter(gabblePath, cs);
        writer.write(total);
        System.out.println("total printed");
    }catch(IOException ex){
        System.out.println("IO Exception");
    } finally {
        if (writer != null) {
            try {
                writer.close();
            }
            catch (IOException e) { /* ignore */ }
        }
    }
    System.exit(0);
}

I think there is a cleaner way to handle the try/catch within the finally cleanup code in Java 7 or 8, but I haven't worked with it yet so I'm not sure.


Using binomial vs central limit theorem in hypothesis testing

Question: This is the question that I was working on:
"An airline claims that the proportion of luggage that is lost is less than or equal to 0.06. A random sample of size 200 is taken. Out of the 200 independent observations, 23 pieces of luggage were lost. Test whether the airline's claim is true at a 1% significance level."
My approach was to model the number of lost luggages as X~Bin(200, p) and use binomial distribution to find the p-value.
However, the answer used the fact that sample proportions are normally distributed (by CLT) to find the p-value.
Would both approaches be correct, and if so, which one is "better"?
Comment: What's your criterion for "better"?
Comment: I think you should add the self study tag. The normal approach is an approximation though probably reasonably good with 200 observations.  Using the binomial is an exact test.
Comment: Well it depends whether the assumptions underlying the binomial are fulfilled (independence and same p) and how Well the normal approximates the binomial with n=200 and p=0.06 but if you compute the p value using the binomial ( and you do it correctly) then it makes sense
Comment: @Michael The Normal approximation is problematic here because the expected count is only 12.  Its p-value is less than one-third the correct one (although both are small).
Answer: This is probably a case of asking your professor which convention he expects you to use in the exam and then obeying. It's not worth losing a grade for trying to be smarter than the professor. Not for such a benign matter anyway.
If hypothetically your professor expected you to answer that p-values express direct probabilities that the hypothesis is true or a similarly colossal mistake, then I wouldn't only advice to obey but mostly to look for a better professor.
Know for the future that it is not a mistake to use binomial distributions with very high $n$. (Under the condition that the trials are independent and have the same $p$ etc. But similar conditions would apply to the normal approximation anyway.) The approximation was invented for reasons of computational complexity that really don't matter in the 21st century anymore.
It is still interesting to understand how the central limit theorem allows you to approximate a binomial distribution by a normal distribution because the central limit theorem has other domains of application unrelated to computational complexity. This is probably the reason your professor taught that approximation.


Read input different menu c#

Question: Im trying to make a menu where an array will store input from a user (enterednumber 1) and then an admin can check the contents of the array in a different menu(enterednumber 9), but I can't seem to make it readable inside the admin menu.... I've left out the methods for login & startmenu, that part works. - the relevant part of the code currently looks like this:
<code>    static void Main(string[] args)
    {
        while (true)
        {
            int enteredNumber;

            int[] myArray = new int[10];

            Startmenu();
            enteredNumber = Convert.ToInt32(Console.ReadLine());

            if (enteredNumber == 1)
            {
                for (int i = 0; i < 1; i++)
                {
                    Console.WriteLine("Insert Number:");
                    myArray[i] = Convert.ToInt32(Console.ReadLine());
                }
                Console.Clear();
                Console.WriteLine("blabla");
                Thread.Sleep(2000);
                Console.Clear();
            }

            if (enteredNumber == 9)
            {
                if (Login(1234, 3) == true)
                {
                    foreach (int number in myArray)
                    {
                        Console.WriteLine(number);
                    }
                }
            }
        }
    }
</code>
Comment: `for (int i = 0; i < 1; i++)` really?? LOL
Comment: your myArray is declared **inside** the scope of the body of the *while* loop. This while loop is your actual menu loop. The thing is, with every iteration of the while loop, its formerly existing scope with all its variables and objects disappear (vanish from existence) unless those objects are referenced by some variable/field/whatever outside the while loop. And with each iteration of the loop the scope is reestablished again with a new fresh, empty myArray. Solution: Move the declaration of the array outside the while loop...
Comment: I just set it to 1 quickly to test it without having to type in a million numbers
Answer: try this:
<code>static void Main(string[] args)
{
    int[] myArray = new int[10];

    while (true)
    {
        int enteredNumber;
        // int[] myArray = new int[10]; //when you create a new int array , the array not contain values.
        Startmenu();
        enteredNumber = Convert.ToInt32(Console.ReadLine());

        if (enteredNumber == 1)
        {
            for (int i = 0; i < 1; i++)
            {
                Console.WriteLine("Insert Number:");
                myArray[i] = Convert.ToInt32(Console.ReadLine());
            }
            Console.Clear();
            Console.WriteLine("blabla");
            Thread.Sleep(2000);
            Console.Clear();
        }

        if (enteredNumber == 9)
        {
            if (Login(1234, 3) == true)
            {
                foreach (int number in myArray)
                {
                    Console.WriteLine(number);
                }
            }
        }
    }
}
</code>
when you create a new int array, the array contains no values, you have creation of an array within the while loop, then, int [] myArray = new int [10]; this empty when you start the cycle again, place the creation before starting the loop.

Read input different menu c#