Composição não é basicamente injeção de dependência?

Question: Li alguns artigos e vi respostas de usuários à essa mesma pergunta que faço mas ainda não entendi.
Um exemplo simples em Python:
class Processador:
      def __init__(self, processador):
          self.processador = processador

class Ram:
      def __init__(self, RAM):
             self.RAM = RAM

class Placamae:
      def __init__(self, placamae):
           self.placamae = placamae

class computer:
      def __init__(self, processador, placamae, RAM):
           self.processador = processador
           self.placamae = placamae
           self.ram = ram

New_computer = computer(Processador('intel I7'), Placamae('Asus TUF Gaming'), Ram('DDR4'))

O que eu acabei de fazer não pode ser considerado tanto uma injeção de dependência como uma composição de uma classe ?
Comment: Já vi composição feita de uma maneira que gerou o **acoplamento ruim**, onde no construtor da classe, apontava diretamente para classes/objetos externos, onde quem programou, não usou Inj. de dependencias (não passou os objetos no construtor). Para facilitar a escrita de testes de unidade, mative a composição, mas tive que implementar Injec. de depen. para facilitar a criacao de mocks e spy das classes que faziam a composição.
Comment: Esqueci de mencionar, no meu caso foi em projeto feito Node.js.
Answer: A Composição é uma técnica em que um objeto contém uma referência para outro objeto e delega parte do seu comportamento para ele. Basicamente o objeto composto é construído a partir de outros objetos, que são combinados para formar um todo funcional. A composição é uma forma de construir objetos complexos a partir de objetos mais simples e reutilizáveis, promovendo a flexibilidade e modularidade do código.
Exemplo:
class Motor:
    def __init__(self):
        self.velocidade = 0

    def acelerar(self, quantidade):
        self.velocidade += quantidade

    def frear(self, quantidade):
        self.velocidade -= quantidade

class Carro:
    def __init__(self):
        self.motor = Motor()

    def acelerar(self, quantidade):
        self.motor.acelerar(quantidade)

    def frear(self, quantidade):
        self.motor.frear(quantidade)

Nesse exemplo, a classe Carro utiliza a classe Motor para acelerar e frear. A composição ocorre na linha self.motor = Motor(), onde a instância do objeto Motor é criada dentro da classe Carro.
Já a injeção de dependência é uma técnica em que as dependências de um objeto são injetadas nele por meio de um mecanismo externo, como um container de inversão de controle (IoC) ou Inversion of Control. Em vez de criar as dependências dentro do objeto, ele recebe essas dependências de um contêiner, que é responsável por fornecer e gerenciar essas dependências. A injeção de dependência promove a separação de preocupações e o desacoplamento dos objetos, o que pode facilitar a manutenção e o teste do código.
Exemplo:
class Motor:
    def __init__(self):
        self.velocidade = 0

    def acelerar(self, quantidade):
        self.velocidade += quantidade

    def frear(self, quantidade):
        self.velocidade -= quantidade

class Carro:
    def __init__(self, motor):
        self.motor = motor

    def acelerar(self, quantidade):
        self.motor.acelerar(quantidade)

    def frear(self, quantidade):
        self.motor.frear(quantidade)

Nesse exemplo, a classe Carro depende da classe Motor, mas em vez de criar uma instância de Motor dentro de Carro, a instância é passada para Carro como um argumento na inicialização. Isso permite que outras instâncias de Motor (ou de outras classes que implementam a mesma interface) possam ser injetadas em Carro por meio do parâmetro motor. Isso é útil porque, se em algum momento for necessário substituir a implementação de Motor por outra, basta criar uma nova instância e injetá-la em Carro.
Resumindo, a composição é uma técnica em que objetos são construídos a partir de outros objetos, enquanto a injeção de dependência é uma técnica em que objetos recebem suas dependências de um contêiner externo. Ambas as abordagens podem ser úteis em diferentes situações, dependendo das necessidades específicas do projeto.
Refs.:

Injeção de Dependência em Java e Python
Composição em Python: Classe usando Classe
Comment: Mas, o que diferencia um componente de uma dependência ?
Comment: Ou seja, a injeção de dependência usa a composição, mas a composição, não necessariamente, usa injeção de dependência. A composição pode ser feita criando o objeto dentro da instância que o utiilza, em vez de ser criado fora dela e então injetado


Which table should be Parent table and which should be child table?

Question: Hi have two tables Auther and Books.
I am confused that to which table should i keep as parent table and which should be child table for making foreign key constraint.
CREATE TABLE author
 (
    author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY KEY,
    author_name VARCHAR2(30)
 );

 CREATE TABLE books
 (
    book_id NUMBER(3),
    book_title VARCHAR2(30),
    book_price NUMBER(3),

 );

Please explain me which table should be Parent table and why?
Answer: Answer: None.
Reason: This is a many-to-many relationship. An author can have any number of books written, also a book can have more than one author.
Solution: Make a separate table with two columns author_id, book_id both are foreign keys.
Comment: This makes a very valid sense if OP is allowed to create a new table +1
Answer: You have been given the correct answer already. I'd like to add the technical view: columns to add.
A foreign key constraint means you have a column or a set of columns in a table that uniquely identify a record in another table.
In order to have a foreign key on a book in table author you'd add book_id to that table. But that wouldn't make sense. Which of the author's books would you reference in this field? So books simply cannot be the parent table for the relation.
Then you can have it vice versa: Have author_id in table books, which would mean a book can only be written by one author. Does this suffice for what your database is to contain? Then this is the way to go.
These mentioned relations are 1:n relations (one author can write several books or one book can be written by several authors). But as mentioned, it is more typical for an author/book realation to be n:m (one author can write several books and one book can be written by several authors).
To introduce an n:m relation in a database you add a bridge table containing the IDs of both tables. And this bridge table would reference both parent tables with foreign keys.
Answer: You can make Author as your parent table and Books as child table.
Reason: An author can write multiple books but a book(usually) is written by one author only.
Comment: @SubrataDeyPappu:- Yes thats why I added `usually`. Also the chances of multiple authors contributing to one book would be very rare/less
Comment: I agree with you. But multiple authors can also contribute to one book too. @Rahul Tripathi
Comment: That's a valid solution. (You could even add abstract authors, such as writing duos, e.g. 'Kami Garcia & Margaret Stohl', to the authors table, so as to cover multiple authors for one book. That would be perfectly fine as long as it doesn't matter to you that there is no relation between the single author and their collaborations in the database then.)
Answer: I'd go for another approach than having a parent and a child table.
Create an extra table like this:
CREATE TABLE authors_books
 (
    author_id NUMBER(3),
    book_id NUMBER(3),
    PRIMARY KEY (`author_id`, `book_id`),
    CONSTRAINT `FK_author_books__author`
        FOREIGN KEY (`author_id`)
        REFERENCES `author` (`author_id`)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
    CONSTRAINT `FK_author_books__book`
        FOREIGN KEY (`book_id`)
        REFERENCES `books` (`book_id`)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
 );

This way you'll avoid any trouble with your n to m relationship between authors and books. Now one book can be written by multiple authors as well.
You probably wanna have an extra field orderas well to always maintain a unique PK. So the PK would be PRIMARY KEY (author_id,book_id,order).
Answer: Explanation 1
If you think about one to many relation from author to book then author will be parent. Actually author will be the owner of the relationship. He will map the realtion from author to books table.
Explanation 2:
If you think about many to many relation from author to book then none of will be parent. Both of them will have equal importance.
Answer: A FOREIGN KEY declaration says that each subrow of values that appears under listed columns of the table that REFERENCES also appears under the listed columns of the referenced table. The referenced columns have to be UNIQUE NOT NULL or a PRIMARY KEY. The "parent" table is the referenced one.
Whenever that's the case, declare a FOREIGN KEY. Otherwise don't.
It happens that if you JOIN on the two column lists, the result will have exactly one row per referencing table row.
With your two tables there's no foreign key to declare.
If you add a table author_books holding rows where "author AUTHOR_ID authored book BOOK_ID" then its author_id values have to be in author and its book_id values have to be in books. So declare two FOREIGN KEYs:
FOREIGN KEY (author_id) REFERENCES author (author_id)
FOREIGN KEY (book_id) REFERENCES books (book_id)

(If an author always wrote exactly one book then you could add book_id to author with a foreign key to books. If a book always had exactly one author then you could add author_id to books with a foreign key from author. But that's not the real situation with authors and books.)
Constraint declarations allow the DBMS to disallow erroneous changes that would make the database have a value that cannot be right. You don't need constraints to query a database. (Including UNIQUE NOT NULL, PRIMARY KEY or FOREIGN KEY.)


Short exact sequence with four terms

Question: We want to build an exact sequence
$$
0 \longrightarrow A \longrightarrow B \longrightarrow C \longrightarrow D \longrightarrow 0
$$
such that $A \oplus C \cong B \oplus D$ and other in which that property does not hold.
Is it possible to obtain this with all modules not being null? I am trying to extend the idea of inclusion and projection with the direct sum in the middle term but doesn't seem to work.
Answer: $R$ a ring, take $A = R$, $B = R \oplus R$, $C = R \oplus R$ and $D = R$. We name our morphism in order $\alpha$, $\beta$, $\gamma$.
Take
$$\alpha = 1_R \oplus 0$$
$$\beta \circ(1_R\oplus 0) = 0 \oplus 0 , \, \beta \circ(0\oplus 1_R) = 1_R \oplus 0$$
$$\gamma \circ (1_R \oplus 0) = 0 , \, \gamma\circ(0 \oplus 1_R) = 1_R$$
For the non-split version, take $A = \mathbb{Z}$, $B = \mathbb{Z} \oplus \mathbb{Z}$, $C = \mathbb{Z}$ and $D = \mathbb{Z}/2\mathbb{Z}$
And
$$\alpha(1) = 1\oplus 0$$
$$\beta(1\oplus 0) = 0 , \, \beta(0\oplus 1) = 2 $$
$$\gamma(1) = 1$$
You can easily extend the length of your sequence for both examples
Comment: Yes, thanks. I think it should be $\alpha(n) = (n, 0)$ in both cases instead of $\gamma$. Also, nice remark!
Comment: Yes a small typo :)
Comment: And $\gamma(n, m) = m$ in the first example :)
Comment: Yes, also I used $1_R$ as the identity function on $R$ to avoid imposing $R$ unitary :)
Comment: Beware: you can't give general counterexamples since for some rings like fields, you only have split sequences!

Short exact sequence with four terms


Copying offsets from screen to string asm 8086

Question: I'm working on a project and I'm trying to create a file editor that basically coping the text from a file to the screen edit it and copying the offsets from the screen back to the file.
Any ideas and codes about hole those steps will be wonderful especially about the last one, I'm using asm 8086 16 bit
Answer: The issue you have is what OS you are using. For example say you are using MS-DOS then to read a file from disk the method is to populate the filename into a memory address and then initiate the operation using a software interrupt. However if you were using something like MINIX then it would you would still populate the filename into memory but the file open operation for some versions of MINIX would put a value in AX and the call a specific software interrupt. There simply is not enough data to help you.
Comment: I'm using dosbox


Linha tracejada apenas css?

Question: alguém sabe como fazer esta linha tracejada apenas com css? já tentei com imagens porém não consegui obrigado!
Comment: Tracejada como? Pela imagem não dá pra entender.
Comment: Você pode usar `border-style:dashed`, mas não vai ficar como na imagem. https://developer.mozilla.org/pt-BR/docs/Web/CSS/border-style
Comment: por que só pode ser com css? Usando duas tags span da para reproduzir tranquilamente com `border-style`.
Answer: Se quer o traço da forma colocada na imagem da pergunta, você pode criar uma classe com os pseudo-elementos ::before e ::after:

/* tirei o underline do "a" apenas para exemplificar no resultado*/
a{
   text-decoration: none;
}

.trasso{
   position: relative;
}

.trasso::before,
.trasso::after{
   content: '';
   border-bottom: 2px solid #090;
   position: absolute;
   top: 100%;
}

.trasso::before{
   width: 5px;
   left: 0;
}

.trasso::after{
   width: 30px;
   left: 10px;
}

Conheça o projeto

   Conheça o projeto

Answer: Da para fazer com linear-gradient

.linha {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: #48958C;
    font-size: 2.5rem;
    position: relative;
}
.linha::after {
   content: '';
   position: absolute;
   width: 6rem;
   height: 0.2rem;
   top: 100%;
   left: 0.25rem;
   background: linear-gradient(to right,#48958C 0%, #48958C 15%, transparent 15%, transparent 30%, #48958C 30%)
}

Conheça o projeto

Linha tracejada apenas css?


Remove node edit form field validation

Question: I am working on the node edit form, and I want to remove all field validation when users click on Save as unpublished.
Is it possible?
I didn't write any code right now, so I don't have any code to show.
Comment: Yes, it's possible, this module does the same based on user roles [Bypass Form Validations] (https://www.drupal.org/project/bypass_form_validations). take look how they do that. take look at the module to see how they implement that and it could be a good start to write your code.
Answer: You could do this approach in HOOK_form_alter. Depending on validation that you want to remove... I provide you a simple example of required fields: Suppose you have an Image field that it's required, you could make it unrequired using the following:
<code>$form['field_image']['widget']['0']['#required'] =  TRUE;
</code>
Also if you want to remove the "Alt field" for a image you could use:
<code>$form['field_image']['widget']['0']['#alt_field'] =  FALSE;
</code>
Comment: You are altering the field configuration and not how validation works

Remove node edit form field validation


Difference between nav vs div.navbar in Bootstrap

Question: Some of Bootstrap's examples use div.navbar to hold the navigation bar, and other examples (e.g., in the Components documentation page) use nav.navbar. What is the difference between these two approaches? And are there guidelines for using one instead of the other?
Answer: Both will output same design but using nav tag is more semantic in approach. It represents main navigation of your page. using nav tag helps search engine recognize which is your main navigation on the page. there might be other links too but your top menu is the main menu.
Hope this helps
Comment: Yes. Its the most appropriate tag to use. As you can see in the documentation section over here http://getbootstrap.com/components/#navbar
nav tag is used which is semantic.
Comment: Thanks for the reply, Vivek. Are you suggesting it's better always to use `nav.navbar` instead of `div.navbar`?
Answer: Nav is semantically more correct and is preferred over Div. As to some answers I have read, Div is often regarded as the last option to use in any element but we often see the opposite.
MDN Definition Nav

The HTML  element represents a section of a page whose purpose is to provide navigation links, either within the current document or to other documents. Common examples of navigation sections are menus, tables of contents, and indexes.
Here's the MDN Page Link for Nav Element

As I searched some more on the internet for Navbar, all I can get from that is Navbar is specifically for Links and Button Elements. It is used inside Nav, as we see it being used in bootstrap docs.


Forward name server for faster load times

Question: I have a website hosted in China, which must be hosted there for various reasons. I also cannot change hosting companies for various reasons. It is a website that is accessed worldwide, however it has atrocious ping rates from everywhere but China.
This is just an idea, so this may be impossible and/or not make any sense, but here it goes. A friend of mine has used proxies which helped his ping and load times from servers in Korea. Is there any way I can do this with my server? Perhaps a service which forwards my name servers to somewhere with much better global ping rates?
Any other ideas which will make pings/load times fester other than this are greatly appreciated as well. Please keep in mind when answering:

I cannot change servers
I do not have access to configure the server itself.
Answer: No, you have no way to serve the content from china and get better times.
What you can do is:

Crap your chinese DNS setup. There is no need for the NAME servers to be in china at all. Get DNS Servers registered from a DNS provider and just use those.
If possible (makes no sense for some totally dynamic apps) use an external server )outside china) with a reverse proxy. Anything the proxy serves will be fast ,but whenever a request has to be answered from your server it wil be slower. The question now is how much can be cached (static files, images etc.).

Both requre you to have access to the domain so you can change the IP addresses for the DNS Servers and the IP Addresses serves for the website.
Comment: I found this: www.varnish-cache.org.

Is this what I need?
Comment: No idea. Never head of this.
Comment: Varnish is a pretty cool reverse proxy.  There is even a tag "varnish" on SF: http://serverfault.com/questions/tagged/varnish


What sequence should I study these topics in?

Question: I will shortly list a series of topics that amount to what is essentially the first two years of an undergraduate degree.
I'd like to know what is considered best order in which to study these topics. I understand that some of these are related topics i.e. Analysis, so if like topics could be grouped together that would be appreciated. Any other suggestions that you feel are relevant would be great too.

Topics
1. Groups: Examples of groups, Lagrange's theorem, Group actions, Quotient groups, Matrix groups, Permutations.
2. Vectors and Matrices: Complex numbers, Vectors, Matrices, Eigenvalues and Eigenvectors.
3. Numbers and Sets: Introduction to number systems and logic, Sets relations and functions, the integers, elementary number theory, the real numbers, countability and uncountability.
4. Differential Equations: Basic calculus, first-order linear differential equations, nonlinear first-order equations, higher-order linear differential equations, multivariate functions: applications.
5. Analysis I: Limits and convergence, continuity, differentiability, power series, integration.
6. Probability: Basic concepts, axiomatic approach, discrete random variables, continuous random variables, inequalities and limits.
7. Vector Calculus: Curves in $R^3$, integration in $R^2$ and $R^3$, vector operators, integration theorems, Laplace's equation, Cartesian tensors in $R^3$.
8. Linear Algebra: self explanatory
9. Groups, Rings & Modules: self explanatory
10. Analysis II: Uniform convergence, uniform continuity and integration, $R^n$ as normed spaced, differentiation from $R^m$ to $R^n$, metric spaces, the Contraction Mapping theorem
11. Metric & Topological Spaces: Metrics, topology, connectedness, compactness
12. Complex Analysis: Analytic functions, contour integration and Cauchy's theorem, expanions and singularities, the residue theorem.
13. Complex Methods: Analytic functions, contour integration and Cauchy's theorem, Residue calculus, Fourier and Laplace transforms.
14. Geometry: Groups of rigid motions of Euclidean space, spherical geometry, Riemannian metrics, embedded surfaces in $R^3$, length and energy, the second fundamental form and Gaussian curvature.
15. Variational Principles: Stationary points for functions $R^n$, Functional derivatives, Fermat's principle, second variation for functionals.
16. Methods: Self-adjoint ODEs, PDEs on bounded domains, Inhomogenous ODEs, Fourier transforms.
17. Numerical Analysis: Polynomial approximation, computation of ordinary differential equations, systems of equations and least squares calculations.
18. Statistics: Estimation, hypothesis testing, linear models.
Comment: For reference, these topics form a large subset of the courses offered in the first two years of an undergraduate maths degree at Cambridge. The best advice, really, is to study the topics in the order they are offered, the course is designed that way for a reason. You've left a few out, so I assume that those are the ones you're not interested in, and conversely that you want to eventually learn all of these topics.

If you have this much information, you've probably seen the course schedule, which also details which terms the topics are in, and what the prerequisites are...
Comment: [continued] So my advice would be to learn the topics in approximately that order, i.e. the first year courses first, starting with the ones in Michaelmas, and then go chronologically. If you want to jump around, just make sure you know enough of the prerequisites as detailed in the schedule. The most obvious change would be to do some combination of Met&Top, GRM and VP after having finished the first year courses but before starting on the second year ones. Met&Top is particularly good to do early since it helps a lot for Analysis II and Geometry, and a bit with the complex courses (12&13)
Comment: @tomoldfield you're right, however I felt like this wasn't the best sequence to do things for me, hence why I asked here. Thank you for your suggestions.
Comment: @TomOldfield your profile says that you attended Cambridge, how is it? if you dont mind me asking.. The schedule looks gruelling..
Comment: I'd be more than happy to discuss it with you in chat if you like? I've set up a room in chat: "Cambridge discuss room" and will be on it when possible for the next few days.
Comment: @TomOldfield that's very nice of you, I'd love to talk
Answer: Here's my take, in diagram form:

The diagram is organized from basic (top) to advanced (bottom).
A solid arrow indicates a more or less definitive prerequisite. For instance, I consider numbers and sets a prerequisite for both groups and discrete math because working with sets is essential in both subjects, and because numbers and sets are a good place to learn to prove things. Also, many examples of groups arise from number-theoretic constructions.
A dotted arrow indicates that one subject might be useful for learning another, although not essential. For instance, it would good to have experience in real analysis before learning topology, largely because topology requires so-called "mathematical maturity", which learning real analysis is likely to supply. Topology and geometry are linked to each other via a dotted line because general theorems from topology will apply geometric objects, and objects from geometry will supply good examples of topological spaces.
The red bubbles are additional topics that came to mind. Perhaps you'll want to add some of these to your studies if you particularly like subjects that precede them. For instance, if you find you love basic abstract algebra, I'd recommend learning a little Galois theory. If you love topology, you might look into some algebraic topology-- study of the fundamental group. There are lots of other "elective"-type topics: if you come across something in your studies and find it interesting, consider changing your plans to include it.
I haven't included calculus on the diagram. If you haven't learned that yet, you'll need to do so before vector calculus, differential equations, and complex analysis. Technically, you could learn real analysis without (or in place of) calculus, since most real analysis books rigorously prove results of calculus from scratch. However, depending on the analysis book, skipping a more typical introduction to calculus might be confusing: many texts seem to assume the reader has some sort of intuition for calculus.
I've omitted (15)-(17) because these are subjects with which I have less familiarity (that doesn't mean that I think you shouldn't study them, though! Just seek guidance elsewhere). For (16), if you have in mind a "methods of mathematical physics" approach, this could be studied soon after multivariable calculus.
I'd suggest that you pick a few subjects from the top of the diagram, and begin studying them. As you finish a subject, replace it with a successor on the diagram, or with a different topic near the top of the diagram. Over the next few years, you'll work "downward" through the diagram until you know all the material.
General advice: do lots of exercises. If you're not sure about your answer and can't find a solution, post it on MSE for verification.
I hope that this is helpful, and isn't entirely overwhelming. Please let me know if I can clarify things.
Edit: to be more specific about where to start, vector calculus and linear algebra are the most canonical choices. I'd recommend studying them at the same time, if you are comfortable with this. If you prefer to choose one, vector calculus is probably best. See the comments on this post for further discussion.
Comment: Topic 0: Basic graph theory so he can understand your directed graph, aka flowchart. ;) Nice diagram!
Comment: This is brilliant! Thank you!
Comment: I'll let this question ran for a bit, to see what other people say, but thanks for your answer!
Comment: @seeker, sure, this makes sense =) glad you found it useful.
Comment: I like the diagram!  I wonder though about not having Vector Calculus prior to Linear Algebra, Complex Analysis, and Probability. I gained a better understanding of limits and two dimensional space in Vector Calculus, which helped with CA.  Double/Triple Integration is needed for Probability. And I think Linear Algebra is more comprehensible if you can relate vector spaces back to two/three dimensional euclidean space, and the intuition for this I gained in vector calculus.
Comment: @David those are good points that you make. I tend to advocate learning linear algebra as soon as possible, because it was in linear algebra that things really clicked for me. Students who don't adore calculus benefit from seeing a very different type of mathematics early on. However, thinking about what you've said, I did take linear algebra and vector calculus simultaneously and definitely benefited from interaction of the two. With your comments in mind, I'd like to refine my suggestion to begin at the "top of the diagram:" perhaps the best idea is to start vector calc and linear algebra.
Answer: I suggest the following sequence:
3-5-2-8-4-7-1-9-10-6-18-11-14-12-13-16-15-17.
Exact contents and prerequisites of your material may call for some permutations, but this shouldn't be too bad.
The list of topics seems good to me.
As you proceed, you will develop a taste that will tell you what you want to focus on and what requires clarification.
When reading a book, don't hesitate to decide that you need to study some other theory first before you can lay hands on what you want to do.
What you need is a good start, and that looks like one.
Answer: You pretty much need #3 and #7 before anything.  Which order you do these in doesn't matter. A lot of stuff on your list will require multivariate calculus, which is why I say #7.  And in #3 you will build up your mathematical maturity/proof skills.
Then a whole world will open up to you, so you could do whatever you find interesting. I wouldn't recommend trying to plan much beyond that because you'll probably change your mind later anyway.
9 comes after 1. (EDIT: I would study this after Linear Algebra/Complex Numbers because many of your groups will come from Matrices/Complex Field)
8 comes after 2.
17 and 16 come after 4.
10 and 11 come after 5.
13 comes after 12
14 whenever.
18 comes after 6.
Answer: This may be useful for a somewhat different perspective. My personal feeling is that it is (I would say) of foremost importance that you become comfortable and nurture a proficiency with proofs.
The topics you mention, when studied in the depth I would think you want to explore all have a "proof component."
While this point could be argued, typically in most math curricula Real Analysis is the entry point to this amazing world. A good RA text (link to an excellent free notes by an outstanding teacher - Vaughan Jones)
https://docs.google.com/viewer?a=v&pid=sites&srcid=ZGVmYXVsdGRvbWFpbnxtYXRoMTA0c3AyMDExfGd4OjJiNTJkM2M2ZWUzZGIwYWQ
will be self-contained and develop proof skills from a beginning level.
One cannot but appreciate the excellent answers given which specifically address your question. But, if I may suggest, pick a starting point with a rigorous, proof content. Once you have "completed" that course or text, you will have begun cultivating a degree of math skills - typically referred to as maturity. Then you can see where your interest lies for your next step.
Comment: I've just re-read this after some time and it's quite sound advice, thank you.
Comment: @seeker My pleasure. Thanks for the kind remark. Regards,


Why exponent of exponent multiplied?

Question: If I have an expression like ${2^2}^3$, then why are the powers multiplied? In other words, why is the above expression equal to $2^6$ not $2^8$?
Comment: The expression you wrote doesn't compile in LaTeX. Do you mean `2^2^3` or $2^{2^3}$ or $(2^2)^3$?
Answer: Exponentiation is not associative, there is a real difference between $(2^2)^3$ and $2^{(2^3)}$.
Answer: As @Rolf Hoyer writes, exponentiation is not associative, hence ${2^2}^3$ would result in an ambiguity: for this reason, when we write $2^{2^3}$ it is always meant to be
$$2^{(2^3)}=2^8.$$
Otherwise, if we mean
$$(2^2)^3=2^{2\cdot 3}=2^6$$
brackets must appear.
In general,
$$x^{a^{b^{c^{\cdots}}}} =
x^{{\left(a^{\left(b^{\left({c^{(\cdots)}}\right)}\right)}\right)}}\ne
(((x^a)^b)^c)^{\cdots}=x^{a\cdot b\cdot c\cdot \ldots}$$
while, for example,
$$
{{\left(x^{(a^b)}\right)}^c}^{\ldots}
\qquad\text{or}\qquad
x^{{\left({(a^b)}^c\right)}^{\ldots}}$$
must be explicitly denoted with brakets.
This, by the way, is one of the things making it difficult to correctly type your examination text by sms... ;)
Comment: I disagree. Exponentiation is usually considered to be *right associative*! See [Wikipedia on exponentiation](http://en.wikipedia.org/wiki/Exponentiation#Identities_and_properties).
Comment: @Christoph: uff! fixed all brackets! Leave your comment as a reference, thank you!

Why exponent of exponent multiplied?


Printing out translated Views' variables

Question: I have a View, with its title translated to all enabled languages. When in tpl file I say: print $views->human_name, the title printed is stuck at the original language though. Any workaround for that, please?
Comment: Did you translate it with http://drupal.org/project/i18nviews?
Comment: Yes, from the Views' dropdown I chose "translate view" and provided the translations.
Comment: @kalabro Have you tried that? Does this work for you?
Comment: Yes, i18nviews works well.
Answer: $title = $view->get_title();

Views' human-readable name is just for developers and is not translated by i18nviews. You might want to get title.


AWS instance Stop and Terminate don't execute systemd stop script

Question: I have a shutdown script that executes just fine after cli reboot or shutdown, but never executes when an instance is stopped or terminated from aws console.
[Unit]
Description=Gracefully shut down remnode to avoid database dirty flag
DefaultDependencies=no
After=poweroff.target shutdown.target reboot.target halt.target kexec.target
RequiresMountsFor=/data
Requires=network-online.target network.target data.mount

[Service]
Type=oneshot
ExecStop=/root/node_shutdown.sh
RemainAfterExit=yes
KillMode=none

[Install]
WantedBy=multi-user.target

What am I missing?
EDIT
Here is the journalctl log for my service. The first two entries are reboot via cli, the last 3 entries are 2 instance stops from AWS console. As you can see, there's not even a mention of winding down my service during instance stop. Rebooting from cli however outputs my echo and system logs startup as well as shutdown of the service.
-- Logs begin at Sun 2019-10-13 13:02:54 UTC, end at Mon 2019-10-14 19:41:01 UTC. --
Oct 13 13:03:24 ip-10-0-1-182 systemd[1]: Started Gracefully shut down remnode to avoid database dirty flag.
Oct 14 19:27:23 ip-10-0-1-182 systemd[1]: Stopping Gracefully shut down remnode to avoid database dirty flag...
Oct 14 19:27:23 ip-10-0-1-182 node_shutdown.sh[10635]: RUNNING SHUTDOWN SCRIPT
Oct 14 19:27:23 ip-10-0-1-182 systemd[1]: Stopped Gracefully shut down remnode to avoid database dirty flag.
-- Reboot --
Oct 14 19:27:37 ip-10-0-1-182 systemd[1]: Started Gracefully shut down remnode to avoid database dirty flag.
Oct 14 19:28:17 ip-10-0-1-182 systemd[1]: Stopping Gracefully shut down remnode to avoid database dirty flag...
Oct 14 19:28:17 ip-10-0-1-182 node_shutdown.sh[1712]: RUNNING SHUTDOWN SCRIPT
Oct 14 19:28:18 ip-10-0-1-182 systemd[1]: Stopped Gracefully shut down remnode to avoid database dirty flag.
-- Reboot --
Oct 14 19:28:32 ip-10-0-1-182 systemd[1]: Started Gracefully shut down remnode to avoid database dirty flag.
-- Reboot --
Oct 14 19:34:05 ip-10-0-1-182 systemd[1]: Started Gracefully shut down remnode to avoid database dirty flag.
-- Reboot --
Oct 14 19:40:26 ip-10-0-1-182 systemd[1]: Started Gracefully shut down remnode to avoid database dirty flag.

EDIT 2:
Because it seems like shutdown trigger is basically never pulled, I've also tried setting kernel sysctl kernel.poweroff_cmd to /bin/systemctl poweroff following this thread. Hoping it would trigger the even, but no luck.
Comment: have you tried to put `RemainAfterExit` before `ExecStop`? also can you confirm it is executing during script execution or even not calling at all?
Comment: @asktyagi I have tried various orders, they don't seem to have any impact. Also, I added logs to my post. As you can see, it doesn't even seem to log shutdown of my process.
Comment: I'll update my post when I have more information, but after reaching out to AWS support, the answer seems to be that their primary, canonical Ubuntu 18.04 AMI is the reason for this bug. Using a different AMI, like .NET edition, fixes the issue.
Comment: If You are relying on systemd-logind to initiate shutdown/poweroff on power button press as usual, there can be applications that acquire some inhibtor-lock on shutdown/poweroff event handling of systemd which may cause systemd to ignore or delay this events, leading to EC2 instance externally powered off after timeout of 4 minutes.
Comment: You could try ewith wetting `PowerKeyIgnoreInhibited=yes` in /etc/logind.conf and restart systemd-logind to ensure that no application can inhibit systemd-logind from powering off after power button press using inhibitor.
Comment: @SergChernata did you ever find a solution to this?
Answer: Just a hunch, but might be worth exploring:
Have you tried using Before= with ExecStart= instead of After= with ExecStop=? i.e. start the node_shutdown.sh script before the final state of a shutdown/halt/reboot is reached. There are answers to similar questions here and here that allude to this.
That said, the accepted answer for the first linked question uses neither option! And why it works on a manual shutdown but not a console shutdown I'm not sure. I know a console shutdown registers as a "power button pressed" event - maybe this event is treated differently by the OS?
A power button press triggers an ACPI event which (I think) runs /etc/acpi/events/hibinit-power => /etc/acpi/actions/hibinit-power.sh, which itself sends a poweroff command to the message bus. It might be worth checking the contents of that .sh in case there's anything funky in there. My vanilla Ubuntu 18.04 looks like this:
#!/bin/sh

# shut down system in a way that respects inhibitors
# see: https://github.com/systemd/systemd/pull/9356
dbus-send --system --print-reply --dest=org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager.PowerOff boolean:false

As asktyagi suggests it's probably worth determining if the script is actually running - maybe try writing to a log at the top of the node_shutdown script?
Edit - here are the contents of the following files:
/etc/acpi/events/hibinit-power
event=button/power
action=/etc/acpi/actions/hibinit-power.sh "%e"

/etc/acpi/events/hibinit-sleep
# ACPID config to power down machine if powerbutton is pressed, but only if
# no gnome-power-manager is running

event=button/sleep.*
action=/etc/acpi/actions/sleep.sh %e

/etc/acpi/actions/sleep.sh
#!/bin/sh

#PATH=/sbin:/bin:/usr/bin

do_hibernate() {
    if [ -d /run/systemd/system ]; then
        systemctl hibernate
    else
        pm-hibernate
        swapoff /swap-hibinit
    fi
}

case "$2" in
    SBTN)
        swapon /swap-hibinit && do_hibernate
        ;;
    *)
        logger "ACPI action undefined: $2" ;;
esac

One thing to also check is /etc/systemd/logind.conf to see how the system handles the power key being pressed. Mine appears to have all the defaults set, notably the ones below:
[Login]
...
#HandlePowerKey=poweroff
#HandleSuspendKey=suspend
#HandleHibernateKey=hibernate
...
#PowerKeyIgnoreInhibited=no
#SuspendKeyIgnoreInhibited=no
#HibernateKeyIgnoreInhibited=no

I double checked this with a fresh Ubuntu instance built from the AWS stock image (ami-02df9ea15c1778c9c in EU-West-1)
Comment: I did try using `Before` configuration, unfortunately. And I am writing to log, see the last portion of my question. The second part of your answer is interesting. I'm also using Ubuntu 18.04 but my files are different from yours. I have `hibinit-sleep` instead of `hibinit-power`.
Comment: Can you include your contents of `/etc/acpi/events/hibinit-power` ?
Comment: Just edited my answer :)
Comment: But You should note the acpi scripts are only used from acpid service, not for systemd. So it needs to be started to handle them.
Answer: I had exactly the same problem on Ubuntu 18.04 AMI. I read the above article and tried updating packages.
> sudo apt update
> sudo apt upgrade

I don't know why, but it works fine now even when EC2 instance is shutdown via web console. And there are new acpi related scripts that were missing(hibinit-power, hibinit-power.sh). Would you like to try it out?


Issue transferring Angular2 example from Plnkr to real application

Question: I am trying to use HighStocks in an Angular2 app by copying this plnkr example...
http://plnkr.co/edit/2xSewTZ9b213vA0ALmFq?p=preview
I'm trying to figure out how to pull in highstock.js into my app as I am getting an error saying...
core.umd.js?e2a5:3004 EXCEPTION: Error in ./XXX class XXX- inline template:1:25 caused by: StockChart is unknown chart type.

on this line of code in the template...
<chart type="StockChart" [options]="options"></chart>

In a 'real' ng2 app where/how would you bring in the below two packages/scripts. I think this is my problem...
  'angular2-highcharts':        'https://cdn.rawgit.com/gevgeny/angular2-highcharts/v0.3.0/dist',
  'highcharts/highstock.src':   'https://cdn.rawgit.com/highcharts/highcharts-dist/v4.2.1/highstock.js'

In the example they are done in the systemjs.config.js file. My ng2 app has no such file.
Where is the best place to do this?
Comment: What sort of configuration files *does* your app have, then? Are you using e.g. Angular-CLI?
Comment: I'm using a basic webpack setup. I've uploaded an example to https://github.com/bencameron00/HighStocksSetup . As you can see in mainViewer.component.html the type attribute is causing the issue. They use this in the plnkr example however. What have I missed? Thank you for your help.
Comment: The github link gives 404 error.
Comment: I've readded the project to Github at https://github.com/bencameron00/Ng2HighStocks
Answer: I found the solution. The solution for me was to add the below lines to my webpack.common.js file...
 resolve: {
      alias: {
        // NOTE: You should set 'highcharts/highcharts.src.js'
        // if you are not going to use <chart type="StockChart"
        highcharts$: "highcharts/highstock.src.js"
      },

I have updated my demo in GitHub with this change https://github.com/bencameron00/Ng2HighStocks
Comment: thanks Ben, this helps me in having my chart rendered in Browser but on Server-Side Terminal it still generates the error "EXCEPTION: StockChart is unknown chart type." and thus, server-side rendering is cancelled. Followed by "Error in SSR, serving for direct CSR".
Comment: I've not tried server side rendering with it so I can't advise I'm afraid. If you find a solution please add it to the post as others might find it helpful. Sorry I can't be of more help. Good luck.


Why is it common to hammer-on a second note on the base string of a sweep-picking part, and is there a technique to playing it correctly?

Question: For example, an excerpt from Animals as Leaders' CAFO—

    Db|                13 12
    Ab|             13       13             13       12       13
    E |          14             14       14       14       14    14
    B |       14                      14       14       14          14
    Gb| 12h15                      12
    B |

Don't mind the tuning—it's just a drop D tuning, 1.5 steps down. And it's not what Tosin Abasi uses. Also, only the beginning is relevant, but I may have more questions about the rest of this part, so I figure it's better to familiarize readers with the complete part and repeat it over separate posts than show fragments in each question. If it matters, the above are all sixteenth-triplets, for 7 eighth notes in total.
I'm new to sweeping and a bit confused by the presence of this hammer-on in many sweep-picking examples and exercises. I feel like instead of being able sweep across all the strings at a constant rate, you have to awkwardly spend double the time on the base string because of the hammer-on.
Is it purely to complete the arpeggio that it's common? (I suspect that's the case.) If so, are there any techniques to "suspending" your picking hand just after the base string, before continuing through the rest of the strings? Trying to do it consciously is maddening!
Comment: It has to do with the 3rd in the arpeggio.  If you play it on two separate strings you have to reach back a couple frets, so the arpeggio moves towards the headstock rather than in an upward direction towards higher frets. I actually prefer those for sweep picking. See link below for an example that puts the hammer on at the end of the run, on the high E string, similar to Bob's answer. I find its much easier to pause for the hammer on the high E when you are getting ready to come back down anyway, it's a natural place to pause: https://www.youtube.com/watch?v=-tob2N4dze8 (good lesson too).
Answer: I think you're right. The reason you need a hammer-on here is to get the full arpeggio. One other way to get these notes is to start with finger 4 on fret 12 string 5 and play the second note with finger 2 on fret 10 string 4:

The timing of the hammer-on on the top string, at the end of the arpeggio, might be easier, but it is quite a stretch, and then you have to jump up to twelfth position.
In reply to your general point, about having to "consciously" think about waiting longer on a string with two notes during a sweep picked arpeggio, I think the only way around it is to gradually build the speed up from very slow with a metronome, taking great care always to keep the rhythm even. Doing this, you should eventually find that the timing becomes automatic (i.e. something you don't have to think about). Also, this will be of great value if you want to do sweep picked scales, where every string has a number of notes played with hammer-ons (although you can of course find patterns for these with the same number of notes on each string which makes the timing more "even").
Comment: Hm, I think you're right! I just needed to "have some faith" (as helped by your answer) and dedicate myself to it, which I have been doing for a few hours now. I was afraid it'd be one of those things that might develop sloppily (_e.g._ blurring the hammer-on to make 5 eighth-quintuplets instead of 6 sixteenth-triplets) regardless of practice, unless helped by some technique. But I notice my picking hand is beginning to "think" of it as an emphatic note (embellished by the hammer-on) followed by 4 sixteenth-triplets, the first of which feels more and more like a pick-up note, which it should.


Find the domain of $f(x)=\log_{10}(1-\log_7(x^2-5x+13))+\arccos\left(\frac{3}{2+\sin\frac{9\pi x}{2}}\right)$

Question: Find the domain of definition of $$f(x)=\log_{10}(1-\log_7(x^2-5x+13))+\arccos\left(\frac{3}{2+\sin\frac{9\pi x}{2}}\right)$$

I found the domain of $\log_{10}(1-\log_7(x^2-5x+13))$ to be $x\in(2,3)$ and the domain of $\arccos\left(\frac{3}{2+\sin\frac{9\pi x}{2}}\right)$ to be $\sin\frac{9\pi x}{2}=1$ i.e. $x=1,5,9$ etc but the answer given is $\frac{21}{9},\frac{25}{9}$.I dont know where i am wrong.
Answer: Since $\sin(\frac{9\pi x}{2})=1$,
$$\frac{9\pi x}{2}\in(\frac{\pi}{2}, \frac{5\pi}{2}...\frac{21\pi}{2}...) \quad or \quad x\in(\frac{1}{9}, \frac{5}{9},..., \frac{21}{9}, \frac{25}{9}...)$$
We have seen that the domain of the first part of equation should be in $(2,3)$, So the only feasible solution is $\frac{21}{9}$ and $\frac{25}{9}$.
Answer: $\left|\dfrac3{2+\sin{\frac{9\pi x}2}}\right|\leq1$
$⇔3\leq|2+\sin\frac{9\pi x}2|$
$⇒\sin\frac{9\pi x}2=1$
$⇒\frac{9\pi x}2=2k\pi+\frac{\pi}2$
$⇒x=\dfrac{1+4k}9$
$k=5,6$ satisfy that condition.


Apache 2 mod_rewrite - How to read POST parameters?

Question: I would like to use mod_rewrite to read parameters sent in POST requests. I need to check the value and process the request.
Answer: Mod_rewrite will not work on POST variables.
You would need to use mod_security to examine, and possibly run a url-rewriting script, on any POST variables.
Answer: I don't believe that it's possible.
mod_rewrite can only work on the contents of the initial request line, headers and environment variables. Whereas the parameters of a POST request are found within the request body.
Comment: Is there a module I can use to access the request body ?
Comment: @Julien: normally you would use a CGI script for that. Or some sort of web application (mod_python, mod_perl, Java servlet, PHP page, etc.)


Sql Server differential backup : Simple vs Full recovery model

Question: I need to better understand the backup process under SQL Server 2008.  Since drive space is a kind of matter for us and we want to have a better disaster recovery solution, I decided that we will implement differential backups throughout the day (every hour).
Am I right to think that if I keep the recovery model of my databases to Simple, the differential backup will be almost the same size as Full Backup (too big to make one every hour) ? I already tried to switch to Full recovery and it seemed to have fixed the issue (differential backups were way smaller). I heard that the recovery model must be set to Full to use Log backups (to the minute recovery etc., but we don't need that) but never about differential backups.
So, is the recovery model really having an impact on differential backups or am I missing something ?
Thank you
Answer: Under the simple recovery model differential backups can only have a single base. You can have multi-based differential backups (see Working with Multibase Differential Backups for some details) using the full recovery model.


Can we migrate and keep the same user, taxonomy, and node IDs?

Question: When we are migrating a Drupal 7 site to Drupal 10, we have some custom tables which store taxonomy, node, user, and role IDs.
Is their a way to migrate a content type preserving the IDs?
Comment: Can you please share the example yml, it would be of great help
Comment: Yes, you can preserve id, in the migration yml. Just map old id to new id.
Answer: The default is to migrate and keep the same ID. Look at web/core/modules/node/migrations/d7_node.yml, and you can see the nid: tnid line.
id: d7_node
label: Nodes
audit: true
migration_tags:
  - Drupal 7
  - Content
deriver: Drupal\node\Plugin\migrate\D7NodeDeriver
source:
  plugin: d7_node
process:
  # If you are using this file to build a custom migration consider removing
  # the nid and vid fields to allow incremental migrations.
  # In D7, nodes always have a tnid, but it's zero for untranslated nodes.
  # We normalize it to equal the nid in that case.
  # @see \Drupal\node\Plugin\migrate\source\d7\Node::prepareRow().
  nid: tnid
  vid: vid
  langcode:
    plugin: default_value
    source: language
    default_value: "und"
  title: title
  uid: node_uid
  status: status
  created: created
  changed: changed
  promote: promote
  sticky: sticky
  revision_uid: revision_uid
  revision_log: log
  revision_timestamp: timestamp
destination:
  plugin: entity:node
migration_dependencies:
  required:
    - d7_user
    - d7_node_type
  optional:
    - d7_field_instance
    - d7_comment_field_instance

You can also look at d7_user.yml, d7_taxonomy_term.yml, and d7_user_role.yml.
If you do end up needing to customize them, create a custom module, copy the YAML file into my_module/config/install/d7_node.yml and modify it.
Answer: As others have already said: yes you can keep this. And it is the default if you use the core migration templates. It is even mentioned in the inline documentation there.
The examples for user and taxonomy term migrations are a bit cleare than the ones for nodes.
See for example in the core user migration template web/core/modules/user/migrations/d7_user.yml :
process:
  # If you are using this file to build a custom migration consider removing
  # the uid field to allow incremental migrations.
  uid: uid

And the taxonomy example in web/core/modules/taxonomy/migrations/d7_taxonomy_term.yml :
process:
  # If you are using this file to build a custom migration consider removing
  # the tid field to allow incremental migrations.
  tid: tid


Firebase query does not display chat

Question: I have a method for a chat app, everything seems to run with no errors but every time I try to type something nothing pops up.
When users log in, the onActivityResult shows the success message:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == SIGN_IN_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Snackbar.make(activity_main, "Success. Welcome.", Snackbar.LENGTH_SHORT).show();
        }
        else {
            Snackbar.make(activity_main, "Error", Snackbar.LENGTH_SHORT).show();
            finish();
        }
    }
}

However, it does not show my onCreate welcome message after:
if(FirebaseAuth.getInstance().getCurrentUser() == null) {
    startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), SIGN_IN_REQUEST_CODE);
}
else {
    Snackbar.make(activity_main, "Welcome " + FirebaseAuth.getInstance().getCurrentUser().getEmail(), Snackbar.LENGTH_SHORT);
    //Load content
    displayChat();
}

When a message is typed, nothing shows up too. Am I querying incorrectly?
private void displayChat() {

    ListView listOfMessage = findViewById(R.id.list_of_message);

    Query query = FirebaseDatabase.getInstance().getReference();
    FirebaseListOptions<Chat> options = new FirebaseListOptions.Builder<Chat>()
            .setLayout(R.layout.list_item)
            .setQuery(query, Chat.class)
            .build();

    adapter = new FirebaseListAdapter<Chat>(options) {
        @Override
        protected void populateView(View v, Chat model, int position) {
            //Get reference to the views of list_item.xml
            TextView messageText, messageUser, messageTime;
            messageText = v.findViewById(R.id.message_text);
            messageUser = v.findViewById(R.id.message_user);
            messageTime = v.findViewById(R.id.message_time);

            messageText.setText(model.getMessageText());
            messageUser.setText(model.getMessageUser());
            messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)", model.getMessageTime()));
        }
    };
    listOfMessage.setAdapter(adapter);
}

My database seems to be fine, with no errors on input:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Comment: show your DB structure
Comment: @faiiziiawan done
Comment: sorry i didn't mean rules i mean how are you storing data in firebase database
Comment: Just through the Firebase email authentication option.
Comment: check this question https://stackoverflow.com/questions/52128852/getting-data-from-firebase-using-orderbychild-query/52129459?noredirect=1#comment91218444_52129459
Comment: Please add your database structure and please responde with @.
Answer: You need to get the refrence for a database and then query on it:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

Query on it something like this, based on you requirement :-
Query query = reference.child("Chat_room");
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            // dataSnapshot is the "chat_room" node with all children
            for (DataSnapshot issue : dataSnapshot.getChildren()) {
                // do something with the individual "issues"
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

Note :- make sure your database has been created , the structure in which you are saving the chat messages to the databse  is important for way you want to retrieve and display the chats.

Firebase query does not display chat


Relate to another table in a check constraint?

Question: Lets say i have a table called Stock_item and it contain a column called Price.I have another table say Purchase that has a column called Buying_Price.Now i want to set a constraint for the Price so that Price > Buying_Price .
Answer: You can't do this using SQL constraints.  Check constraints only work on a single table and foreign keys only enforce equality.
The ANSI SQL standards include a construct called Assertions which are supposed to support this sort of business logic but no DBMS vendor has implemented them.  They're pretty tricky to do efficiently.
We can simulate assertions with a before insert or update trigger.  Something like this:
<code>  create or replace trigger stock_item_price
  before insert or update on stock_item
  for each row
  declare
       l_buy_price purchase.buying_price%type;
  begin
      select p.buying_price
      into l_buy_price
      from purchase p
      where p.item_code = :new.item_code;

      if l_buy_price <= :new.price
      then
          raise_application_error(-20000
           , 'Price must exceed Buying_Price');
  end;
</code>
This comes with several caveats. Because it fires for each row it would be pretty inefficient in a bulk update scenario.  It might not work in a multi-user environment (say if somebody has uncommitted changes to PURCHASE).  And it won't enforce anything in the other way; if somebody increases the BUYING_PRICE this trigger won't fire.  So maybe you need another trigger on PURCHASE.  But that might not be desirable.
As you can see, triggers are a messy way of enforcing application logic, not least because they are easily overlooked.  A procedural API is would be a better approach.  At the very least put the logic in stored procs and call it from a trigger.

"can a check contraint like Price > 0"

Oh yes, that the sort of validation check constraints are for.
<code>alter table stock_item
     add constraint stock_item_price_chk
         check ( Price > 0 )
/
</code>
Comment: Thanks for such an insightful response but can a check contraint like `Price > 0` exist ?


How to solve this type of ratio problem?

Question: The ratio of balls in three boxes is $6:8:9$. In what ratio should the balls in the second and third boxes be increased, so that the final ratio becomes $1:3:4$?

To have a $1:3:4$ ratio, I think I need to change the given ratio to $6:18:24$. That means I need to add $10$ balls in the second box and $15$ balls in the third box. So the ratio in which second and third boxes to be increased should be $2:3$. Is this correct?
Comment: Welcome to Math.SE! Please show your efforts towards soving this problem. What have you tried so far?
Comment: Hint: Just pretend that a $1$ in the first ratio expression correspond to $1$ ball.
Comment: What have you tried?
Answer: I think you need of two distinct ratios: one for the second box and one for the third box.
Since
\begin{align}
(1:3:4)
&=(6:18:24)\\
&=\left(6:8\cdot\frac 94:9\cdot\frac 83\right)\\
&=\left(6:8\left(1+\frac 54\right):9\left(1+\frac 53\right)\right)\\
\end{align}
hence the second box should be increased by $\frac 54$ while the third box by $\frac 53$.
Answer: You start with $6x,8x,9x$ and end with $6x,18x,24x$ since the first box doesn't change. You added $10x$ to the second and $15x$ to the third, so you're adding balls to the second and third in the ratio $2:3$ but the total number of balls you add is related to the (fixed) number in the first box by the ratio $25:6$, that's also important.
Answer: The best way to approach this problem is to work backwards. The final ratio is $1:3:4$. To make this answer more concrete, let's imagine that there are white balls, red balls, and black balls. This means that for $1$ white ball, there will be $3$ red balls, and $4$ black balls. One important thing to note about ratios is that they can be scaled up:
This means that $1:3:4=6:18:24$. Scaling this ratio is useful because it allows us to consider how we can get the final ratio to be $1:3:4$, without changing the number of white balls, as per the requirements of the question. This seems to be the approach that you have took.
We need to go from
$$
\text{6 white balls, 8 red balls, and 9 black balls}
$$
to
$$
\text{6 white balls, 18 red balls, and 24 black balls}
$$
The number of red balls we need is $10$, and the number of black balls we need is $15$. Can you take it from here?


How to validate a domain name using Regex & PHP?

Question: I want a solution to validate only domain names not full URLs, The following example is what I'm looking for:
example.com -> true
example.net -> true
example.org -> true
example.biz -> true
example.co.uk -> true
sub.example.com -> true
example.com/folder -> false
exam*$ple.com -> false

Comment: http://stackoverflow.com/questions/399932/can-i-improve-this-regex-check-for-valid-domain-names has lots more information about using regular expressions to match domain names.
Answer: The accepted answer is incomplete/wrong.
The regex pattern;

should NOT validate domains such as:
-example.com, example--.com, -example-.-.com, example.000, etc...

should validate domains such as:
schools.k12, newTLD.clothing, good.photography, etc...

After some further research; below is the most correct, cross-language and compact pattern I could come up with:
^(?!\-)(?:(?:[a-zA-Z\d][a-zA-Z\d\-]{0,61})?[a-zA-Z\d]\.){1,126}(?!\d+)[a-zA-Z\d]{1,63}$

This pattern conforms with most* of the rules defined in the specs:

Each label/level (splitted by a dot) may contain up to 63 characters.
The full domain name may have up to 127 levels.
The full domain name may not exceed the length of 253 characters in its textual representation.
Each label can consist of letters, digits and hyphens.
Labels cannot start or end with a hyphen.
The top-level domain (extension) cannot be all-numeric.

Note 1: The full domain length check is not included in the regex. It should be simply checked by native methods e.g. strlen(domain) <= 253.
Note 2: This pattern works with most languages including PHP, Javascript, Python, etc...
See DEMO here (for JS, PHP, Python)
More Info:

The regex above does not support IDNs.

There is no spec that says the extension (TLD) should be between 2 and 6 characters. It actually supports 63 characters. See the current TLD list here. Also, some networks do internally use custom/pseudo TLDs.

Registration authorities might impose some extra, specific rules which are not explicitly supported in this regex. For example, .CO.UK and .ORG.UK must have at least 3 characters, but less than 23, not including the extension. These kinds of rules are non-standard and subject to change. Do not implement them if you cannot maintain.

Regular Expressions are great but not the best effective, performant solution to every problem. So a native URL parser should be used instead, whenever possible. e.g. Python's urlparse() method or PHP's parse_url() method...

After all, this is just a format validation. A regex test does not confirm that a domain name is actually configured/exists! You should test the existence by making a request.

Specs & References:

IETF: RFC1035
IETF: RFC1123
IETF: RFC2181
IETF: RFC952
Wikipedia: Domain Name System

UPDATE (2019-12-21): Fixed leading hyphen with subdomains.
Comment: Does not match this: go.xn--fiqs8s
Comment: underscore is not a valid character.
Comment: Minor addendum, but given vanity gTLDs, it would be better to only enforce the max possible length of 63 characters (see http://stackoverflow.com/questions/9238640/how-long-can-a-tld-possibly-be).
Comment: However, it doesn't validate test--0.com, which is invalid.
Comment: That is a valid domain and the regex above validates it as a domain. See a demo here: http://regex101.com/r/fC7zU9/1
Comment: @MarinosAn That's an international domain extension. The post clearly indicates that the regex does not support IDNs.
Comment: Can't get this to work in bash. Would someone explain why? I realize the OP requests PHP but I'd like to use this in a shell script if possible.
Comment: @OnurYıldırım the said regex is still vulnerable to multiple dashes like so: `exam----------ple.com`
Comment: @AbelCallejo that's a valid domain, so it passes the regex. Register it from  https://www.godaddy.com/domainsearch/find?checkAvail=1&tmskey=&domainToCheck=exam----------ple
Comment: For some reason this passes subdomain.-domain.com
Comment: This fails domains such as _subdomain.example.com which is valid
Answer: How about:
^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$

Comment: Whoever downvoted took it back. @Lauri `.museum` and `.travel`.
Comment: This answer is (not fully wrong) but **incomplete**. See the correction in my answer.
Comment: It only works in PHP if you put REGEX as this: `/^(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,6}$/`. It works with `preg_match` function for example, otherwise not.
Comment: Why the downvote? I tested it at http://regexpal.com/ and it matches all the OP's test data.
Comment: @zildjohn01 Learned something new today as well ;-) Thanks
Comment: +1 from me. And for the record, depending on what is what you want to do with that regexp, keep in mind that example.{com,net,org} are reserved and can't be registered (cf. http://en.wikipedia.org/wiki/Example.com).
Comment: This will work - however now that we're about to get a bunch of new gTLD's, some are 12+ characters long. For the sake of future proofing a bare minimum of 20 characters should be allowed. Even then you might eventually hit a brick wall.
Comment: RickM is correct; based on new vanity gTLDs, it would probably be safer to enforce the max possible limit of 63 characters (ref http://stackoverflow.com/questions/9238640/how-long-can-a-tld-possibly-be).
Comment: Length, you have to keep it at 64 chars or less!
Answer: Please try this expression:
^(http[s]?\:\/\/)?((\w+)\.)?(([\w-]+)?)(\.[\w-]+){1,2}$

What it actually does

optional http/s://
optional www
any valid alphanumeric name (including - and _)
1 or 2 occurrences of any valid alphanumeric name (including - and _)

Validation Examples

http://www.test.example
test.com.mt
Comment: This example is the perfect and covers http(s)://www.abc.com www.abc.com abc.com subdomain.abc.com
Answer: In my case, domain name is considered as valid if the format is stackoverflow.com  or xxx.stackoverflow.com
So in addition to other stack answers, I have added checking for www. also.
function isValidDomainName($domain) {
  if (filter_var(gethostbyname($domain), FILTER_VALIDATE_IP)) {
      return (preg_match('/^www./', $domain)) ? FALSE : TRUE;
  }
  return FALSE;
}

you can test the function with this code
    $domain = array("http://www.domain.example","http://www.domain.example/folder" ,"http://domain.example", "www.domain.example", "domain.example/subfolder", "domain.example","sub.domain.example");
    foreach ($domain as $v) {
        echo isValidDomainName($v) ? "{$v} is valid
" : "{$v} is invalid
";
    }

Answer: Remember, regexes can only check to see if something is well formed. www.idonotexistbecauseiammadeuponthespot.example is well-formed, but doesn't actually exist... at the time of writing. ;)  Furthermore, certain free web hosting providers (like Tripod) allow underscores in subdomains. This is clearly a violation of the RFCs, yet it sometimes works.
Do you want to check if the domain exists? Try dns_get_record instead of (just) a regex.
Answer: I made a function to validate the domain name without any regex.
<?php
function validDomain($domain) {
  $domain = rtrim($domain, '.');
  if (!mb_stripos($domain, '.')) {
    return false;
  }
  $domain = explode('.', $domain);
  $allowedChars = array('-');
  $extenion = array_pop($domain);
  foreach ($domain as $value) {
    $fc = mb_substr($value, 0, 1);
    $lc = mb_substr($value, -1);
    if (
      hash_equals($value, '')
      || in_array($fc, $allowedChars)
      || in_array($lc, $allowedChars)
    ) {
      return false;
    }
    if (!ctype_alnum(str_replace($allowedChars, '', $value))) {
      return false;
    }
  }
  if (
    !ctype_alnum(str_replace($allowedChars, '', $extenion))
    || hash_equals($extenion, '')
  ) {
    return false;
  }
  return true;
}
$testCases = array(
  'a',
  '0',
  'a.b',
  'google.com',
  'news.google.co.uk',
  'xn--fsqu00a.xn--0zwm56d',
  'google.com ',
  'google.com.',
  'goo gle.com',
  'a.',
  'hey.hey',
  'google-.com',
  '-nj--9*.vom',
  ' ',
  '..',
  'google..com',
  'www.google.com',
  'www.google.com/some/path/to/dir/'
);
foreach ($testCases as $testCase) {
  var_dump($testCase);
  var_dump(validDomain($TestCase));
  echo '

';
}
?>

This code outputs:

string(1) "a" bool(false)

  string(1) "0" bool(false)

  string(3) "a.b" bool(true)

  string(10) "google.com" bool(true)

  string(17) "news.google.co.uk" bool(true)

  string(23) "xn--fsqu00a.xn--0zwm56d" bool(true)

  string(11) "google.com " bool(false)

  string(11) "google.com." bool(true)

  string(11) "goo gle.com" bool(false)

  string(2) "a." bool(false)

  string(7) "hey.hey" bool(true)

  string(11) "google-.com" bool(false)

  string(11) "-nj--9*.vom" bool(false)

  string(1) " " bool(false)

  string(2) ".." bool(false)

  string(11) "google..com" bool(false)

  string(14) "www.google.com" bool(true)

  string(32) "www.google.com/some/path/to/dir/" bool(false)

I hope I have covered everything if I missed something please tell me and I can improve this function. :)
Answer: Time ago i was over to discover if i were able to find the solution, but checking for all possibilities, and due to subdomains possible values, i've been may wrongly convinced (maybe) that the unique way to know if something is valid or not, were to check against this array (that can be extracted as in the example by icann site)
http://www.axew3.com/www/data-hints/w3-all-top-level-domains-names-array.php
with something like this:
// this extract ever the correct cookie domain (except for sub hosted/domains like: mydomain.my-hostingService-domain.com)

function extract_cookie_domain( $w3cookie_domain ) {

require_once( WPW3ALL_PLUGIN_DIR . 'addons/w3_icann_domains.php' );

$count_dot = substr_count($w3cookie_domain, ".");

     if($count_dot >= 3){
      preg_match('/.*(\.)([-a-z0-9]+)(\.[-a-z0-9]+)(\.[a-z]+)/', $w3cookie_domain, $w3m0, PREG_OFFSET_CAPTURE);
      $w3cookie_domain = $w3m0[2][0].$w3m0[3][0].$w3m0[4][0];
   }

   $ckcd = explode('.',$w3cookie_domain);
// $w3all_domains array come from file inclusion where icann domains are stored- This is the unique way to check if a domain is valid and to complete any answer, or any answer, will be incomplete
  if(!in_array('.'.$ckcd[1], $w3all_domains)){
   $w3cookie_domain = preg_replace('/^[^\.]*\.([^\.]*)\.(.*)$/', '\1.\2', $w3cookie_domain);
  }

    $w3cookie_domain = '.' . $w3cookie_domain;

$pos = strpos($w3cookie_domain, '.');
if($pos != 0){
    $w3cookie_domain = '.' . $w3cookie_domain;
}

return $w3cookie_domain;

}

but maybe i'm wrong. What you say?
p.s i did not re-checked the logic of the function, may it can be shortened and surely improved
$w3all_domains array come from file inclusion where icann domains are stored- This is the unique way to check if a domain is valid and to complete any answer: or i think that any solution above or below, will be sometime incomplete.
[EDITED]
Comment: This question is asking for "validation", but your answer seems to be demonstrating an "extraction" process.  Are you answering the asked question?
Comment: well, it is the unique way to get the right result, or you'll be never sure, if you before, do not pass through something like this. Isn't it?


How do you get the last star to be only star shown in a rating?

Question: The out of the box process with fivestar will show star 1,2,3,and 4 highlighted (it will show all stars up to the actual vote). I need stars except the actual vote to be the neutral or the unselected star.
Say for example, someone votes 4 out of 5. How do I show ONLY 4th star highlighted while all the others are either the neutral or unselected star?
EDIT: After reviewing fivestar.js, I believe the code that handles highlighting is the following;
<code>$container.find('.star:lt(' + index + ')').addClass('on');
      $container.addClass('fivestar-widget-' + ($options.length));
      $container.find('a')
        .bind('click', $this, Drupal.behaviors.fivestar.rate)
        .bind('mouseover', $this, Drupal.behaviors.fivestar.hover);

      $container.bind('mouseover mouseout', $this, Drupal.behaviors.fivestar.hover);

      // Attach the new widget and hide the existing widget.
      $select.after($container).css('display', 'none');
    });
  },
  rate: function(event) {
    var $this = $(this);
    var $widget = event.data;
    var value = this.hash.replace('#', '');
    $('select', $widget).val(value).change();
    var $this_star = $this.closest('.star');
    $this_star.prevAll('.star').andSelf().addClass('on');
    $this_star.nextAll('.star').removeClass('on');
    event.preventDefault();
  },
</code>
Answer: I haven't used Fivestar but if you use rate it has an option to show the users vote. Rate has a fivestar widget as well.
Comment: That wouldn't work as it would still show 4 out of the 5 stars highlighted. I already tried using rate.
Comment: I think you'll have to modify the javascript (rate.js) if you just want to customize the display right after a star has been clicked.
Comment: Until the vote as been submitted. I don't care that the stars would show up (Its actually easier for a user to review their overall review). I need to modify the code once the vote has been cast.
Answer: fivestar.theme.inc on line 206
<code>FROM: elseif ($rating >= $star_value) {

TO: elseif ($rating == $star_value) {
</code>


Hahn Banach Theorem implying existence of a nonzero linear functional taking 0 in a linear subspace

Question: I am reading this paper. In the proof of theorem 1, it is stated

By the Hahn-Banach theorem, there is a bounded linear functional on $C(I_n)$, call it $L$, with the property that $L\ne 0$ but $L(R) = L(S) = 0$.

$C(I_n)$ is space of continuous functions on $[0,1]^n$. $S$ is a linear subspace in it. $R$ is the closure of $S$.
Can you explain to me why this statement is true?
Comment: This is true as long as $R$ is not the entire space. What version of the Hahn-Banach Theorem do you know? There's one that's almost exactly this statement.
Comment: I was looking at Rudin 1991. Also Friedman's lemma and theorem. I see on Wikipedia they list something very similar as an important consequence.
Comment: They do assume $R$ is not all of $C(I_n)$.
Answer: Let $M=\{f+af_0:a\in \mathbb R\}$ where $f_0$ is any fixed element not in $R$. Define $T(f+af_0)=a$. If we show that this is continuous on the space spanned by $R \cup \{f_0\}$ we can use Hahn Banach Theorem to get a continuous linear functional which is $0$ on $R$ and has the value $1$ at $f_0$. I will let you verify that $T$ is well defined. Suppose $f_n+a_nf_0 \to g$. If $(a_n)$ is unbounded it has a subsequence ${a_{n'}}$ converging to $\pm \infty$. Dividing by this we get $\frac {f_n'} {a_{n'}} +f_0=0$ which shows that $-f_0$ is the limit of  sequence from $R$ which is a contardiction. Hence $(a_n)$ is bounded and it has  subsequence converging to some $a$. we then get $f_n+a_nf_0 \to g=f+af_0$ for some $f \in R$ and $a=T(g)=\lim a_{n'} =\lim T(f_{n'}+a_{n'}f_0)$. By arguing with subsequences we see that $T$ is continuous.
Comment: @ztyh No you cannot show continuity this way because we don't know that $\lim a_n$ exists.
Comment: What exactly do I have to say about $T$ being well defined?
Comment: Also can I just say $T(\lim [f_n+a_nf_0])=\lim a_n=\lim T(f_n+a_nf_0)$ to show that it is continuous and then say $T$ is linear?
Comment: Can I just use bounded iff continuous? When you prove $(a_n)$ cannot tend to $\infty$, you can say $T$ is bounded and that is the end of the proof?
Comment: @ztyh What Kavi has proved is that, if $f_n+a_nf_0 \to g$ for some $g\in M$, then $(a_n)$ is bounded, which doesn't imply the boundedness of $T$. And for the argument of continuity and subsequence, you may find this [property](https://math.stackexchange.com/questions/174281/sequences-subsequences-and-continuity-of-functions) useful.
Answer: This is true if $R \neq C(I_n)$. We shall assume that $C(I_n)$ is a real space.
Choose $x_0 \in C(I_n) \setminus R$. $C(I_n)$ is locally convex, $\{x_0\}, R \subseteq C(I_n)$ are disjoint, nonempty and convex sets. Furthermore, $\{x_0\}$ is compact and $R$ is closed, so by the geometric Hahn-Banach theorem we can find a bounded functional $L$ on $C(I_n)$ and constants $\gamma_1, \gamma_2 \in \mathbb{R}$ such that
$$ \forall y \in R : L(x_0) \leq \gamma_1 < \gamma_2 \leq L(y). $$
Note that $L \mid_R \equiv 0$, since otherwise we could (by linearity of $L$ and $R$) find a $y_0 \in R$ with $L(y_0) < \gamma_2$, contradicting the inequality above.
Since $L(x_0) < 0$ we have $L \neq 0$, but $L \mid_R \equiv 0$, and since $S \subseteq R$ we also get $L \mid_S \equiv 0$.
This statement holds in general as long as $R \neq X$ is a linear and closed subspace of a real or complex, locally convex topological vector space $X$.


CSS variable 2 Column Layout

Question: So I've looked up stuff all over the internet and I can't find the answer I'm looking for.
I'm just trying to make a 2 column layout for a part in my page with each column being the same width, 50% of the container.
Now for some reason when I set both divs to 50% and float:left, the second div wraps underneath. The closest thing I can get is floating the second div right and making width 49% but I'd like it to be 50% because I want to have them touching.
Here is a demonstration:
JSFiddle Example
So what am I doing wrong?
Answer: The border widths are set to 1px, so they will be adding an additional 2px to each of the two divs. Therefore, your content is 4px too wide to fit into that div.
What you need to do is encase the content of your divs within another div, and apply the border to the inner div. Like seen in this fiddle.
Answer: Use CSS3 box-sizing: border-box;
Add this-
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing:border-box;

in #info and #textBooks
Fiddle
Comment: This would not work in IE7 and lower. See [compatibility chart](http://caniuse.com/css3-boxsizing).
Comment: @Eric that's right! The example you have posted works in all browsers but kills semantic values - too many divs :)
Comment: Sometimes values have to be sacrificed for compatibility... (Just ask any Android programmer.)
Comment: @Eric OP use **display:table** property in his code. Which support till IE8 & above.
Answer: You define border to your DIV's. Which add width to it for example 50% + 2px . So, use box-sizing: border-box;
Write like this:
div#textBooks,
div#info{
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

check this http://jsfiddle.net/VbWbc/4/
Note: it's work's till IE8 & above.
For all browsers
Check  this http://jsfiddle.net/VbWbc/5/
write like this:
div#info{
    width:50%;
    border:1px solid black;
    background-color:red;
    float:left;
}

div#textBooks{
    border:1px solid black;
    background-color:green;
    overflow:hidden;
}

Comment: That helped a lot thanks, but is there a way to make it so the inner divs are as tall as the container? because if one is taller than the other and i have background colors it looks bad. I'd like them to stay the same height

CSS variable 2 Column Layout


How to list all available reviews for coder?

Question: I am using drush with Coder (7.x-2.x) and I would like to know what are available options for reviews:
$ drush help coder
...
--reviews Run the specified review(s), "all" runs all reviews, also accepts a comma separated list (no spaces).

Where I can find them?
Answer: The list will depend on which modules you have that implemented hook_reviews(); hook implementations return a keyed array that has the name of the review. These items are combined with a default list that come from the coder_review module.
The default list come from that dir is: upgrade47,   upgrade5x, upgrade6x, upgrade7x, upgrade8x, comment, druplart, i18n, i18n_po, production, security, sniffer, sql, style
Answer: So far I've found the following drush command as workaround:
drush ev 'require_once dirname((new ReflectionFunction("drush_coder_review"))->getFileName()) . "/coder_review.common.inc"; print_r(array_keys(coder_review_reviews()));'

or:
drush ev 'require_once str_replace("drush.inc", "common.inc", (new ReflectionFunction("drush_coder_review"))->getFileName()); print_r(array_keys(coder_review_reviews()));'

Note: I'm not using module_load_include() in above examples, as Coder module could be downloaded outside of Drupal directory.
I've also raised feature request for Coder to achieve that in more convenient way.


Find the unknown area by different methods

Question: this problem has many ways of calculating, could provide some solutions, particularly using proportions
EDIT : A it's not midpoint
Comment: "Is A the midpoint of CB? (It seems so,..)"  That is not a good enough reason to make any such assumption.
Comment: "Is A the midpoint of CB?"  No.  It most certainly is not.
Comment: Is $A$ the midpoint of $CB$? (It seems so, in which case you will notice that $ABF$ is a quarter of the total rectangle area.
Comment: I'm *pretty sure* this question has been asked here before, but I can't find it at the moment. There could be other approaches in answers there.
Answer: If we view $AEB$ as having base $AE$ and triangle $FEB$ as have base $FE$, then the both have the same height--- the altitude of line $AF$ to point $B$.
Since triangles $AEB$ and $FEB$ both have the same height then their bases are in proportion to their areas.  So $EF = \frac 32 AE$.
Triangle $DEF$ is similar $AEB$ and the sides are that $EF$ corresponds to $AE$ and so the sides are $\frac 32$ as long.  So the area of the $DEF$ (white) area is $2cm^2 *(\frac 32)^2 = 4.5 cm^2$.
So the area of the white plus the yellow is $4.5cm^2 + 3cm^2 = 7.5 cm^2$.
As this is a rectangle triangles $DCB$ and $DFB$ are congruent and have the same area.
And so the area of the blue plus the green is $7.5 cm^2$.  So the area of the blue is $7.5 cm^2 - 2cm^2 = 5.5 cm^2$
Comment: @Bungo, Now I see it, I was seeing something else, thanks
Comment: I think there are several places where you have $B$ and mean $F$. "One decimal place accuracy" is s strange request since your answer is exact if the inputs are.
Comment: ""One decimal place accuracy" is s strange request since your answer is exact if the inputs are. "  Yeah, I thought so too.  I wonder if one method was to solve for one the the sides which are probably an irrational root.  "I think there are several places where you have B and mean F"  Yikes.  In the first paragraph even...
Comment: Regarding the "one decimal place," there seems to be a tendency (especially in software systems that grade homework) to specify the format of results in this fashion.
Comment: @fleablood ,hi ..   I must be very sleepy, I do not see what you say  **Since triangles AEB and FEB both have the same height**
Comment: Turn the picture sideways so that the base of the triangles are $AE$ and $EF$.  Then both triangles have point $B$ on the top and they are both the same height.
Comment: @Walter Draw the perpendicular from point B to segment AF. The length of that perpendicular is the height of both triangles.
Answer: Here are some hints toward different approaches:

The shoelace algorithm allows you to calculate the area of any polygon given that you know the coordinates of their vertices
The law of cosines paired with the formula for the area of any triangle could also be useful.  The law of cosines states that for triangle $ABC$, with side lengths $a,b,c$ which are the sides opposite to the angles they correspond with, that $a^2=b^2+c^2-2ab(cos(A))$ and the area of any triangle is $\frac{1}{2}ab(cos(C))$

These are obviously not answers, if you are looking for new ways to break down those geometries, these are both powerful methods.
Answer: Slightly shorter: Let $w$ be the width of the rectangle, $h$ the height, and let $x$ be the length of segment $AB$. Argue as in @fleablood's answer (+1) that $AE=\frac23 EF$. By similar triangles, conclude $x=\frac23 w$.
The area of triangle $\triangle ABF$ is then $\frac12xh=\frac13wh$. Since this equals $5$, the area of the rectangle is $wh=15$.
Answer: Area of the triangle $ABF=5$.
And $A$ is the midpoint of the side $CB$.
So the area of rectangle $BCDF$= 4 × area  of triangle$ ABF$
$=4×5= 20$.
Thus area of the triangle $BDC$ is half of the area of the rectangle =$10$.
Thus area of the blue reigion= $10-2=8$.
Comment: "And A is the midpoint of the side CB."  WHY???  And no, it isn't.


Can my employer force me to backup my personal machine?

Question: Here's the background:
Approximately 1.25 years ago, the company I work for was acquired by a larger 400 person company. Before acquisition (and today still) we are all remote employees using our own personal hardware for work-related duties (coding, email, etc). We are approximately 15 employees within the larger organization.
Some time after acquisition, the now owning company was slapped with a civil lawsuit. Part of this lawsuit (discovery) is requiring them to retrieve & store from us any related information. Because we were a separate company up until acquisition, there is a high probability that our personal machines might contain information about what the lawsuit alleges (email, documents, chat logs?, etc). Obviously, this depends largely on the person's job function (engineer vs. customer support vs. CEO). All employees are being required to comply.
Since acquisition (1.25 yrs), the new company has not provided us with company laptops/desktops. We continue to use personal hardware, licenses, etc for work.
Email is via POP3s and not hanging around on the mail server - it's on everyone's client.
Documents are spread across personal machines.
So, now they want us each to backup our complete personal machines. They are allowing us to create a "personal" folder where we can place personal documents. That single folder will be excluded from backup. Of course, that means total re-arrangement of documents, etc. For most of us, 99% of the data on the machine is NOT related to work.
So, what's the consensus? Should we comply? What is their recourse if we do not?
Comment: You need to seek advice of a lawyer on this. My personal feeling is that that you need to either find alternate employment or refuse to use your personal equipment for work related activities. It's *never* a good situation for anyone involved to have work data on non-work-owned equipment.
Comment: ... and it is not good to have personal data on work-owned equipment.
Comment: Buy a second computer.  Use one for work, and one for home stuff.  Or setup a virtual machine on your hardware, and then only do your work in the VM.
Answer: Keep in mind you are in a sense, under court order through your employer.  So be careful - pissing off your employer is one thing, the court, another.  If it were me, I'd be looking for other employment.
You could consider creating a virtual machine that you do all company work on and backing it up rather than your personal machine.
Comment: +1 for the VM. Isolate them. Simple. If you are using WIndows, WIndows 8 brings finally Hyper-V to the client. Employer in a sandbox - best way. If they are public and in the US the anyway violate SOX for example with POP3 and no proper archiving ;)


JointJs - event onConnect Link

Question: I am trying to create a board where an user can dynamically add blocks and connect the blocks with links. (Something like this but dynamically)
I'm using JointJs framework and till now everything is working as expected, but I need to show some info when the user connect two blocks.
My problem is that I cant find an event to handle when connecting the blocks.
I looked in this question but in my example I do not have the link instance to attach the event.
Here you can see my example
And here is how the block are added to the board. the magnet: true in the text property is what makes the text connectable. I really need some help finding an event to handle when the link is connected.
 var rect = new joint.shapes.basic.newRect({
     position: { x: position, y: position },
     size: { width: 100, height: 40 },
     attrs: {
         rect: { 'stroke-width': '1',  stroke: 'black', rx: 3, ry: 3, fill: 'blue'},
         text: { text: 'Block', magnet: true,  }
     }
 });
 graph.addCell(rect);

I also looked to the mouseUp event and coordinates but came out with nothing..
I really appreciate some help
Answer: The change:source and change:target events (as the all other events triggered by cell models) propagate to the graph so you don't need a reference to your links, you can do something like:
graph.on('change:source change:target', function(link) {
    if (link.get('source').id && link.get('target').id) {
        // both ends of the link are connected.
    }
})

Comment: Does it exist a way to avoid link without target node?
Comment: You can react on paper.on('cell:pointerup blank:pointerup', handler) where you discard all links that do not have both source.id and target.id set.
Comment: dave, this will only fire when a connection is fully made, but not when one end of it is cut. What is the proper way of getting an event when a connection is made or lost, but *not* if an open end is just moved (as it would be the case with `change:source` unfiltered).

JointJs - event onConnect Link


Proof writing involving union and intersection: $A\cap B=A\cup B=B\cap C=B\cup C \Rightarrow A=B=C$

Question: Prove: $$A\cap B=A\cup B=B\cap C=B\cup C \Rightarrow A=B=C$$
Part 1:
Suppose $x_1\in A$, then $x_1\in A\cup B$. So then $x_1\in A\cap B$. Thus $x_1\in B$ and thus $A\subseteq B$.
Suppose $x_2\in B$, then $x_2\in A\cup B$. So then $x\in A\cap B$. Thus $x_2\in A$ and thus $B\subseteq A$.
Therefore, $A = B$.
Part 2:
Suppose $x∈B$, then $x∈B∪C$. So then $x∈B∩C$. Thus $x∈C$ and thus $B⊆C$
Suppose $x∈C$, then $x∈B∪C$. So then $x∈B∩C$. Thus $x∈B$ and thus $C⊆B$
Therefore, $B = C$.
Thus, if part 1 & 2 are equal, then $A=B=C$
Is this correct? Another way to prove this? Tips for a better proof writing?
Comment: I guess what I'm saying is that stylistically, it's neater to first show that for any sets $X, Y$ with $X\cap Y = X\cup Y$, we must have that $X=Y$ (which is what you did in Part 1). Then, directly from your assumptions, you have $A=B$ and $B=C$ and you're done.
Comment: I would get rid of "Thus, if part 1 & 2 are equal". What does it mean for parts to be equal?
Comment: Looks good to me :)
Comment: Additionally, relabeling $A$ from part 1 as $C$ proves part 2, without having to go through all the steps again.
Comment: @AdinaGoldberg elaborate please?
Comment: I mean, you've done the same proof twice, once to show $A=B$, assuming that $A\cap B = A\cup B$ and once to show $B=C$, assuming that $B\cap C = B\cup C$. They are exactly the same except for what you call the sets.
Comment: Either way, your proof looks correct to me!
Comment: Okay I see. Thanks for the tip :)
Comment: @AdinaGoldberg how could you break this statement into two? is this valid A∩B=A∪B → A=B ↔ B∩C=B∪C→B=C or A∩B=A∪B = A=B ↔ B∩C=B∪C = B=C or simply A∩B=A∪B  ↔ B∩C=B∪C ?
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/29546/discussion-between-adina-goldberg-and-steve).
Answer: Your work is correct. This is an alternative proof without using elements:
We have
$$A\cup B=(A\setminus B)\cup(A\cap B)\cup(B\setminus A)$$
and this union is disjoint so since $A\cup B=A\cap B$ then $A\setminus B=B\setminus A=\emptyset$ so $A=B$. Do the same method for the set $C$.


How to deal with categorical independent variables with numerous levels

Question: How to deal with regression when most of the independent variables are categorical having numerous (more than 10) levels and the dependent variable is continuous?
For this would it make sense to perform dummy coding? What could be a better way to deal with this situation?
I want to predict CPM (Cost per mille) based on certain categorical independent variables.
Answer: I can recommend CatBoost if you want an out-of-the-box solution for categorical features.
Here's a link to a great example on Target Feature encoding (really like this one, I used it few times to similar problem), it might be very useful, however, you must be very attentive to train/test splits and overfitting using it.
Also, there's a library for categorical encoding as well, I only skimmed the documentation, but haven't had a chance to use it so far.
And random tutorial I've just found.
Despite there're models and libraries which can do preprocessing of categorical features for you, I would recommend writing at least some part of pipeline yourself understand the concept and be sure you're not missing anything (e.g. different categories in train and test, which is very common issue).


Show That There Is One and (Essentially) Only One Field With 3 Elements

Question: My thought process is the following: By default, 0 and 1 have to be in this set of 3 elements since they are the neutral additive and neutral multiplicative elements, respectfully. So the set of the 3 elements that make up this field must be {0,1,x}. But for any element "a" in the set, there must be some "-a" element such that a + (-a) = 0. Therefore there is only one option for x; x=-1. My set must then be {-1,0,1}. Is this correct? It seems too simple, so I wanted a second opinion.
Comment: No, it is *not* right. What if $1+1=0$ and $x$ is another element? You have to handle the case where $(-1)=1$. @user251257
Comment: What does this have to do with real analysis? It looks like algebra to me.
Comment: @ThomasAndrews Well we need to have that $x+1$ is one of $0,1,x$. If $x+1=0$ then $x=-1$ since inverses are unique. If $x+1=1$ then $x=0$, which means we don't have three elements. If $x+1=x$ then $1=0$, which means the field is trivial. So we need to have $x=-1$ necessarily. In your example, we'd then have $x=1$ and the field has only two elements. So it's not a counterexample.
Comment: No, you are wrong. You are actually missing the point of the definitions - the above field you are creating with three elements is exactly the field of $\mathbb Z$ modulo $3$. So if you are counting the field of two elements as "not a regular set," whatever that means, then you are also calling the field of $3$ elements  "not a regular set." The key to getting math is reading and understanding the definition. @FrenchToastCrunch
Comment: It is right ... but what have it to do with real analysis?
Comment: @FrenchToastCrunch $\mathbb Z_2$ is a field, and $1+1=0$ there. There are many other fields where $1+1=0$ - they are called "fields of characteristic $2$." You can show that a field of three elements can't be a field of characteristic $2$, but that is part of this question. The definition of a field never indicated that $(-x)$ was different from $x$.
Comment: @FrenchToastCrunch I'm afraid I agree with the others that you are assuming something which is part of the question. You might do better to consider the element $1+x$ - what is that equal to? There are three possibilities, and you should be able to eliminate two of them.
Comment: People here have a *lot* of mathematical experience, and this is a very standard problem, @FrenchToastCrunch Saying "I know what the teacher wants here" is being myopic. Try reading and understanding the people here trying to help you, and don't make assumptions.
Comment: I think using the word isomorphism might be helpful.
Comment: The name of the book that our class is using is called "Introduction to analysis".
Comment: Punchline: French Toast is correct. But this still isn't a real analysis question.
Comment: @ThomasAndrews I'm a bit confused. I'm not sure why 1+1 would ever be equal to 0. There is probably some explanation to what you're suggesting, but so far we have only had two lectures in this course and nowhere in the book leading up to this homework assignment does it mention anything similar to what you're suggesting.
Comment: @FrenchToastCrunch look up $\mathbb{Z}$ modulo 2. That's a field with two elements, which has $1+1=0$.
Comment: @JahanClaes : Oh, I understand now. So if we had Z in modulo 5 then we would have things like 4+1 = 0, right?
I think we're just dealing with regular sets in this course for now. For the intents and purposes of this particular problem, I think my answer is correct.
Comment: @FrenchToastCrunch in a couple of weeks you're going to realize that $\mathbb{Z}_n$ are just about the most regular sets around. You should really try to understand why your reasoning is faulty, it will pay off down the road.
Comment: @FrenchToastCrunch Something to think about: In your 3-element field, what does $1+1$ equal?
Answer: Your answer is correct, your reasoning is not. I realize you're new to abstract algebra, so I'll just say this: when we write down things like $1$ and $0$, we mean only that these things are the multiplicative and additive identities, respectively. We do NOT think of them as subsets of the real line. For example, we can define a perfectly good field with only two elements $\mathbb{Z}_2=\{0,1\}$ where multiplication is defined as usual, and addition is defined as $1+1=0$.
Now, we want to show that there's only one field with three elements. We know $0$ and $1$ must be in this field, and that $0\neq 1$. So if we call the remaining element $x$, we have to find if there is more than one possible thing for $x$ to be.
We know, by closure, that $x+1$ has to be in our field, so either $x+1=0$, $x+1=1$, or $x+1=x$. In the first case, we get $x=-1$, where by $-1$ I do NOT mean "negative one", but rather simply "the additive inverse of one". In the second case we get $x=0$, which is wrong because we want $x$ to be a NEW element of our set. In the third case, we get $1=0$, which is also bad. So we know $x=-1$!
Now, we still haven't fully determined our field. Why? Well, we know there's only one possible third element, but we still have to fully define what addition does on the elements. In particular, we want to show that there's only ONE way to define addition on the elements consistent with the field axioms. We already know what happens if you take $1+0$, $1+-1$, and $-1+0$. We just need to figure out what happens when you take $1+1$ and $-1+-1$. We know $1+1$ has to be in our set, so $1+1=1,0,-1$. If $1+1=1$ then $1=0$, if $1+1=0$ then $-1=1$ and there's only two elements in your field. So $1+1=-1$. Similarly, $-1+-1=1$. Then you just have to check there's only one way to define multiplication (there is), and you're done.
Comment: Hmm, I see. This type of reasoning is very different from what I'm used to. Are there any good videos online for this subject that you can recommend? There is very little online that I could find. The name of my course is technically "advanced calculus", but we use an "analysis" book.
Comment: @FrenchToastCrunch There's video series about abstract algebra online (see, e.g.,  [this](http://math.stackexchange.com/questions/146774/khan-academy-for-abstract-algebra)). But in general, I would just read the wikipedia articles on groups, rings, and fields, paying particular attention to the examples.