saveOrUpdate many-to-many table with Hibernate + MySQL

Question: I have webapp, which uses Hibernate 4, Spring 3 and MySQL. Hibernate sessions and transactions are managed by spring.
Right now I am confused about how to insert data into computer_app table using Hibernate.
Here's the script for creating a database:
CREATE TABLE computers (
computer_id INT AUTO_INCREMENT,
computer_name VARCHAR(15) NOT NULL,
ip_address VARCHAR(15) NOT NULL UNIQUE,
login VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
PRIMARY KEY(computer_id)
) ENGINE=InnoDB;

CREATE TABLE applications (
app_id INT AUTO_INCREMENT,
app_name VARCHAR(255) NOT NULL,
vendor_name VARCHAR(255) NOT NULL,
license_required TINYINT(1) NOT NULL,
PRIMARY KEY(app_id)
) ENGINE=InnoDB;

CREATE TABLE computer_app (
computer_id INT,
app_id INT,
FOREIGN KEY (computer_id)
    REFERENCES computers(computer_id)
    ON DELETE CASCADE,
FOREIGN KEY (app_id)
    REFERENCES applications(app_id)
    ON DELETE CASCADE
) ENGINE = InnoDB;

And here are 2 corresponding classes, which which was generated by NetBeans for computer_app table:
ComputerApp.java:
@Entity
@Table(name="computer_app" ,catalog="adminportal")
public class ComputerApp  implements Serializable {

    @EmbeddedId
    @AttributeOverrides( {
        @AttributeOverride(name="computerId", column=@Column(name="computer_id") ),
        @AttributeOverride(name="appId", column=@Column(name="app_id") ) } )
     private ComputerAppId id;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="app_id", insertable=false, updatable=false)
     private Application applications;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="computer_id", insertable=false, updatable=false)
     private Computer computers;

    public ComputerApp() {
    }

    public ComputerApp(Application applications, Computer computers) {
        this.applications = applications;
        this.computers = computers;
    }

    public ComputerAppId getId() {
        return id;
    }

    public void setId(ComputerAppId id) {
        this.id = id;
    }

    public Application getApplications() {
        return applications;
    }

    public void setApplications(Application applications) {
        this.applications = applications;
    }

    public Computer getComputers() {
        return computers;
    }

    public void setComputers(Computer computer) {
        this.computers = computer;
    }

    @Override
    public String toString() {
        return applications.getAppName();
    }

}

ComputerAppId.java:
@Embeddable
public class ComputerAppId implements Serializable {

    @Column(name = "computer_id")
    private Integer computerId;

    @Column(name = "app_id")
    private Integer appId;

    public ComputerAppId(){

    }

    public ComputerAppId(Integer computerId, Integer appId) {
        this.computerId = computerId;
        this.appId = appId;
    }

    public Integer getComputerId() {
        return this.computerId;
    }

    public void setComputerId(Integer computerId) {
        this.computerId = computerId;
    }

    public Integer getAppId() {
        return this.appId;
    }

    public void setAppId(Integer appId) {
        this.appId = appId;
    }

    public boolean equals(Object other) {
        if ((this == other)) {
            return true;
        }
        if ((other == null)) {
            return false;
        }
        if (!(other instanceof ComputerAppId)) {
            return false;
        }
        ComputerAppId castOther = (ComputerAppId) other;

        return ((this.getComputerId() == castOther.getComputerId()) || (this.getComputerId() != null && castOther.getComputerId() != null && this.getComputerId().equals(castOther.getComputerId())))
                && ((this.getAppId() == castOther.getAppId()) || (this.getAppId() != null && castOther.getAppId() != null && this.getAppId().equals(castOther.getAppId())));
    }

    public int hashCode() {
        int result = 17;

        result = 37 * result + (getComputerId() == null ? 0 : this.getComputerId().hashCode());
        result = 37 * result + (getAppId() == null ? 0 : this.getAppId().hashCode());
        return result;
    }

}

How can I saveOrUpdate() data inside the computer_app datatable with Hibernate? Which instance of 2 generated classes must be created - one or both?
Please, point me to the solution or provide some code..I realy need to make this till tomorrow! Every answer is highly appreciated and responded immidiately! If you need some additional code - just let me know.
Thank you.
Answer: Deffine @manytomany relationship between your Computer and Application tables as follows hibernate will take care of inserting records into your computer_app table there is no need to define separate table for computer_app table as follows
Computer
@Entity
@Table(name="computers")
public class Computer {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "computer_id")
private int id;

@ManyToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER)
@JoinTable(name="computer_app",
        joinColumns={@JoinColumn(name="computer_id")},
        inverseJoinColumns={@JoinColumn(name="app_id")})
private Set<Application> applications = new HashSet<Application>();

//Setter && Getters methods

}

Application
@Entity
@Table(name="applications")
public class Application {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column (name = "app_id")
private int id;

@ManyToMany(mappedBy="applications",fetch=FetchType.EAGER)
private Set<Computer> computers = new HashSet<Computer>();

//Setter && Getters methods

}

save entities
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();

Application app1 = new Application();
Application app2 = new Application();
Computer comp = new Computer();
comp.getApplications().add(app1);
comp.getApplications().add(app2);
session.saveOrUpdate(comp);

session.getTransaction().commit();
session.close();

this will automatically insert records into all three tables
for more reference read this article
Hibernate Many To Many Annotation Mapping Tutorial
hope this will solve your problem ...!
Answer: You just need to create one new Computer as:
Computer c = new Computer(computer_name,ip_address,ip_address ,login, password );

and one Application as:
Application a = new Application(app_name,vendor_name,license_required );

Then you will do:
ComputerApp ca = new ComputerApp(a,c);

and then you can persist it as Janus mentioned. Hibernate will take care of the foreign keys since you will pass computer c and application a as parameters in the constructor
Answer: You could save an object with the EntityManager:
public void save(ComputerApp t){
// begin transaction
em.getTransaction().begin();
if (!em.contains(t)) {
    // persist object - add to entity manager
    em.persist(t);
    // flush em - save to DB
    em.flush();
}
// commit transaction at all
em.getTransaction().commit();

}
Comment: But what about ComputerAppId? Do I have to provide it as well? Or it will be somehow generated from ComputerApp?
Comment: To my mind, it will remain null in the database table, if it is not set during runtime. You could generate a auto-incremented id with @GeneratedValue(strategy=GenerationType.IDENTITY), but it does not work for Objects.
Comment: Are the annotations for persisting missing in the ComputerApp class?


How to make the output of a list index start with 1?

Question: I have 2 lists. the first is:
city_indices = list(range(0 , len(cities))) # There are 12 cities in that list
Its output is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
The second list is the city names:
city_names = ['Buenos Aires',
 'Toronto',
 'Marakesh',
 'Albuquerque',
 'Los Cabos',
 'Greenville',
 'Archipelago Sea',
 'Pyeongchang',
 'Walla Walla Valley',
 'Salina Island',
 'Solta',
 'Iguazu Falls'
]

I have to put the result of combining the two lists in a variable, names_and_ranks = []
The code I have to combine the lists is:
for index in list(range(0,len(cities))):
       print(f'{city_indices[index]}' '. ', city_names[index])

its output:

Buenos Aires
Toronto
Marakesh
Albuquerque
Los Cabos
Greenville
Archipelago Sea
Pyeongchang
Walla Walla Valley
Salina Island
Solta
Iguazu Falls

Here's where I'm stuck. I can't figure out how to start the list with 1. and end in 12 or how to put the whole thing in names_and_ranks = []
Answer: Just add 1 to city_indices[index]:
for index in list(range(0,len(city_names))):
    print(f'{city_indices[index] + 1}' '. ', city_names[index])

Output:
1.  Buenos Aires
2.  Toronto
3.  Marakesh
4.  Albuquerque
5.  Los Cabos
6.  Greenville
7.  Archipelago Sea
8.  Pyeongchang
9.  Walla Walla Valley
10.  Salina Island
11.  Solta
12.  Iguazu Falls

Comment: I will do that, for sure, Sushil. I'm still unsure how to put it all into names_and_ranks = [ ]
Comment: Can u elaborate more on what u wanna do?
Comment: I came up with this solution:                                                             names_and_ranks = [ ]
for index in range(0,len(cities)):
    names_and_ranks.append(f'{city_indices[index] + 1}' + '. ' + city_names[index])
print(names_and_ranks)       It seemed to work nicely. Let me know if that doesn't make it more clear. Thanks for the help.
Comment: Sorry @Sushil, forgot to check your answer as correct until now. Thanks for your help


doctrine: many to many relation with join table: how to add WHERE condition

Question: I have three tables:
Clients: (id, name, ...)

Files: (id, filename, type, data)

and join table:
Clients2Files (id, id_clients, id_files, created_at, deleted_at)

in php class Clients I want to get access to all client's files, but only to the files that hasn't been deleted (in sql speak WHERE deleted_at IS NULL)
Now I have code like this (in entity class Client), which selects all (even deleted) files:
/**
* @ManyToMany(targetEntity="File")
* @JoinTable(name="Clients2Files",
*      joinColumns={@JoinColumn(name="id_clients", referencedColumnName="id")},
*      inverseJoinColumns={@JoinColumn(name="id_files", referencedColumnName="id")}
*      )
*/
private $files;

How can I add condition WHERE deleted_at IS NULL to this doctrine code? To select only files that are not "deleted".
Answer: The annotations you added don't actually "SELECT" anything. All they do is tell Doctrine about your objects and their relations. What you want to do is:
$qb = $em->createQueryBuilder();
$qb->select('clients, files')
   ->from('Clients', 'clients')
   ->join('c.files', 'files')
   ->where('files.deleted_at IS NULL');

If you find yourself doing this often, and are using Doctrine 2.2+, you can take a look at filters: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/filters.html
Comment: Thank you! this means that instead of `private $files` and all the anotations i will write getFiles() method and my custom select as you wrote it?
Comment: No! You have to keep the annotations, they tell Doctrine how to fetch your data. What I'm saying is, when you want to find new Client objects using doctrine, instead of using the generic `find*` methods, you have to create your query to find objects.


Generalised logaritmic function

Question: I was wondering if there was a function that extends the domain of the following function to non-negative real numbers. For non-negative integer $n$ and real $y$, $y = f(x,n)$ is given by:
$$f(x,n) = \ln\underset{n-2}{\cdots}\ln x$$
e.g. $f(x,3) = \ln \ln \ln x, f(x,0) = x$.
Do any well known functions, defined instead for $n\in\mathbb{R}_0^+$, have this property?
Answer: This is not a full answer, but some remarks that are related to your problem. So let us start with an abstract setup. Let $f(x)$ be an invertible real valued function. Define a new function $F(n,x)$ defined by $F(0,x)=x$ and $F(n+1,x)=f(F(n),x)$. Since $f$ is invertible, we may extend this to negative numbers by setting $F(-1,x)=f^{-1}(x)$, and iterating backwards. Let us denote $F(r,x)=f^r(x)$ The question is whether nor not we are able to extend this all real numbers (or in your case non-negative reals). But we do not want any old extension, we could simply take a piecewise linear extension (or many other types of extensions in fact). A sensible property to ask for is to ask that $f(r+s)=f^r\circ f^s$ for all real numbers. We might also ask that our function is continuous. To solve this problem in general, it suffices to find a function to  Schröder's equation. What this is a pair $(\phi,s)$ where $\phi$ is an invertible real valued function and $s$ is a non-zero (positivity would be nice) such that $$\phi(f(x))=s\phi(x).$$ From this it is easy to see that $f^r(x)=\phi^{-1}(s^r\phi(x))$ solves our problem (although whether or not the solution is unique or not is another issue). A nice condition that makes the existence possible is the existence of a fixed point. Unfortunately, the natural log does not have a fixed point. See Here.
This also seems to be of interest.
Comment: Cool, seems the problem is much deeper than I thought when I wrote the question.

Generalised logaritmic function


How to store a safevalue of a field in addition to the original?

Question: I have a custom field type that I create with a custom module. It is a plain text field where the user type in a string. I want to retain two copies of this field:

The exact string value as typed by the user.
A safe value of the same string.

This is how I create the field:

class MyItem extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'value' => [
          'type' => 'text',
          'size' => 'tiny',
          'not null' => FALSE,
        ],
        'safevalue' => [
          'type' => 'text',
          'size' => 'tiny',
          'not null' => FALSE,
        ],
      ],
    ];
  }
…

}

I assume I should generate a safevalue of the string in hook_node_presave() and somehow get into the entity there (but corrections to these assumptions are welcome).
I have no problem getting the string value as typed by the user and to compute a safe value:
$value = $entity->field_myfield->getString();
$safevalue = makeSafe($value);

But I do not know how to get the $safevalue stored in the database.
Edit
I see that this has two nearly identical answers. Both work fine if the cardinality of the field is one, so I've upvoted both.  Since I cannot accept both, I've accepted the one from apaderno for the extra detail about propertyDefinitions().
I am still not able to get this to work with a multivalue field, but I think that probably need to be a separate question.
Answer: For saving:
$value = $entity->field_myfield->getString();
$entity->field_myfield->safevalue = makeSafe($value);

For loading:
$safe_value = $entity->field_myfield->safevalue;

Answer: If safeValue has been defined as field property in propertyDefinitions(), it can be accessed as $entity->field_myfield->safeValue, either to read it or write it.
In Drupal core, an example of field that stores a processed copy of the field value is the TextItem class, whose propertyDefinitions() method contains the following code.
$properties['value'] = DataDefinition::create('string')
  ->setLabel(t('Text'))
  ->setRequired(TRUE);
$properties['format'] = DataDefinition::create('filter_format')->setLabel(t('Text format'));
$properties['processed'] = DataDefinition::create('string')
  ->setLabel(t('Processed text'))
  ->setDescription(t('The text with the text format applied.'))
  ->setComputed(TRUE)
  ->setClass('\\Drupal\\text\\TextProcessed')
  ->setSetting('text source', 'value')
  ->setInternal(FALSE);

That class defines the property as computed. That's why its schema() method doesn't include that property.


How do I Combine Delete filter statements in MYSQL

Question: I want to be able to delete records from a table where ID is from 7970 to 9805 if sales amount is between 200 and 850.
I need your help.
Thank you in advance.
Here's my individual mysql delete statements.
DELETE FROM `fin_sales` WHERE `sale_id` BETWEEN 7970 AND 9805;

DELETE FROM `fin_sales` WHERE `total` BETWEEN 200 AND 850;

but its not working
Comment: So why not just use `and` ?
Comment: "It's not working" is not a problem description. What happens instead? Nothing? Too much? Computer explodes?
Answer: I believe, you need to make one delete statement as below:
DELETE FROM fin_sales WHERE sale_id BETWEEN 7970 AND 9805 and total BETWEEN 200 AND 850;

I have not tested it so use it on your own discretion
Comment: Thank you too and your warning caption gave me heads up with precaution.
Answer: Please try the below query
DELETE FROM `fin_sales` WHERE `sale_id` BETWEEN 7970 AND 9805 AND `total` BETWEEN 200 AND 850;


How do I tell if a VPN client's traffic is going through our network?

Question: We have a VPN accessible by a customer (we host a database and other stuff he uses via VPN). However, how do we tell if this person is browsing the internet through our network instead of his own's ?
The VPN is configured using Windows only (Windows server).
Answer: Configure your firewall rules to not allow traffic other than what is required. Then you won't have to worry about what the customer does.
As far as auditing what the customer is doing? Well packet captures and netflow come to mind.
Comment: We don't want to block her but we would like to know if he uses our network to navigate, and see how much is that affecting us.
Comment: Sounds like you're setting up your customer, which is fishy. If you don't trust your customer, then fire them. Otherwise, just put in firewall rules to block traffic and your problem is solved.
Answer: You can stop Internet access from the VPN by disabling internet routing to the VPN.  "routing and remote access" on the windows server is where you would configure this .
Depending on your OS this url may help configure remote client activity logging .
https://technet.microsoft.com/en-us/library/jj592691.aspx
Search terms like "enable remote gateway" , "enable Ip routing" for more help


Access-Control-Allow-Origin: * is not working when doing axios post in React

Question: I am trying to post an object to API. However, I am getting the following error:
Access to XMLHttpRequest at 'https://ciboservis.herokuapp.com/api/v1/filial/adm' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have read other questions and found out that I needed to include Access-Control-Allow-Origin: *. So, here is my code now:
axios
  .post("https://ciboservis.herokuapp.com/api/v1/filial/adm", {testName: 'foo'}, {
    headers: {
      "Access-Control-Allow-Origin": "*",
      Authorization: `Bearer ${token}`,
    },
  })

  .then((res) => {
    console.log(res);
  })
  .catch((err) => console.log(err));

However, I am still getting the same error
Comment: `"Access-Control-Allow-Origin": "*"` this header needs to added from your server response and not from client who is requesting the resource. You can see if the response that you are getting when you hit this URL contains this header
Answer: As mentioned by Pratik in the comment, you need to apply these headers from the server side, which is hosted on Heroku.
Or For development purposes, you can install a chrome plugin to bypass this issue, but a long-term and better solution is to add this header on the server side
You can try this plugin - CORS Bypass Extension


Show that $E[(Y-E[Y|X])*(E[Y|X]-g(X))]=0$

Question: $g$ is a measurable function and $X$ and $Y$ are continuous random variables, we need to show that:
$E[(Y-E[Y|X])*(E[Y|X]-g(X))]=0$
My attempt:
$E[(Y-E[Y|X])*(E[Y|X]-g(X))]=E[E[(Y-E[Y|X])*(E[Y|X]-g(X))|X]]$
$(Y-E[Y|X])*(E[Y|X]-g(X))=Z$, where Z is a random variable.
$E[Z|X]=h(X)$ and $E[E[Z|X]]=E[h(X)]=\int_{-\infty}^{+\infty} h(x)f_X(x)dx=\int_{-\infty}^{+\infty} \int_{-\infty}^{+\infty}z \frac{f_{X,Z}(x,z)}{f_X(x)} dz f_X(x)dx$.
If I go down this road, all I get is $E[h(X)]=E[Z]$ which is true but does not take me where I want to.
Any hints?
Answer: More generally,
$$
\mathrm{E}[(Y-\mathrm{E}[Y\mid X])\cdot Z]=0
$$
for any $\sigma(X)$-measurable random variable $Z$. Use this with $Z=\mathrm{E}[Y\mid X]-g(X)$.
To show the claim just note that the expectation, by the tower property, can be written as
$$
\mathrm{E}[\mathrm{E}[(Y-\mathrm{E}[Y\mid X])\cdot Z\mid X]]=\mathrm{E}[Z\cdot\mathrm{E}[Y-\mathrm{E}[Y\mid X]\mid X]]=0.
$$
Comment: Also, no need to assume that $X$ and $Y$ are continuous. This holds more generally.


Show that the system of all matrices of the special form is isomorphic to the field of complex number.

Question: Show that the system of all matrices of the special form
$$
    \begin{pmatrix}
    \alpha & \beta \\
    -\beta & \alpha \\
    \end{pmatrix}
$$
combined by matrix addition and matrix multiplication, is isomorphic to the field of complex number.
How do i start showing this ?
And first of all how can matrix have a one to one connection with complex numbers
Answer: An isomorphism is given by $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix}\mapsto\alpha+\beta i.$$ Another isomorphism is given by $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix}\mapsto\alpha-\beta i.$$ You just need to show that one of the maps really does preserve addition, multiplication and multiplicative identity.
(Edit: You may want to ask how I come up with these two maps, or why do we even consider the matrices of such form in the first place. If you want, I can add details.)
(Edit 2: You need to show the map is bijective as well.)
Added: To show it preserves multiplication, you are trying the prove the equality $$F\left(\begin{bmatrix}\alpha&\beta\\-\beta&\alpha \end{bmatrix}\begin{bmatrix}\gamma&\sigma\\-\sigma&\gamma \end{bmatrix}\right)=F\left(\begin{bmatrix}\alpha&\beta\\-\beta&\alpha \end{bmatrix}\right)F\left(\begin{bmatrix}\gamma&\sigma\\-\sigma&\gamma \end{bmatrix}\right)$$ holds, where $$F\left(\begin{bmatrix}\alpha&\beta\\-\beta&\alpha \end{bmatrix}\right)=\alpha+\beta i.$$ It is just a slightly tedious calculation: $$F\left(\begin{bmatrix}\alpha&\beta\\-\beta&\alpha \end{bmatrix}\begin{bmatrix}\gamma&\sigma\\-\sigma&\gamma \end{bmatrix}\right)=F\left(\begin{bmatrix}\alpha\gamma-\beta\sigma&\alpha\sigma+\beta\gamma\\-(\beta\gamma+\alpha\sigma)&-\beta\sigma+\alpha\gamma\end{bmatrix}\right)=\color{red}{(\alpha\gamma-\beta\sigma)+(\alpha\sigma+\beta\gamma)i},\\ F\left(\begin{bmatrix}\alpha&\beta\\-\beta&\alpha \end{bmatrix}\right)F\left(\begin{bmatrix}\gamma&\sigma\\-\sigma&\gamma \end{bmatrix}\right)=(\alpha+\beta i)(\gamma+\sigma i)=\color{red}{(\alpha\gamma-\beta\sigma)+(\alpha\sigma+\beta\gamma)i}.$$
As for how we came up with the isomorphisms, we may do this algebraically:

Multiplicative identity must be mapped to multiplicative identity. In this case, the identity matrix must be mapped to $1+0i$.
The complex polynomial equation $z^2+1=0$ has complex number solutions $i$ and $-i$. If there is isomorphism from the set of matrices to complex numbers, it means the matrix polynomial equation $X^2+I=\boldsymbol0$ has two solutions $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix},\ \begin{bmatrix}-\alpha&-\beta\\\beta&-\alpha\end{bmatrix}$$ where $I$ is the identity matrix, $\boldsymbol0$ is the zero matrix, and the two solutions shall be mapped to $i$ and $-i$ by an isomorphism. When you solve the matrix polynomial equation, you would find out the two unknowns $\alpha,\beta$ has to satisfy $$\begin{cases}\alpha^2-\beta^2=-1\\2\alpha\beta=0\end{cases}.$$ This would mean $\beta$ cannot be zero ($\alpha^2=-1$ cannot hold for a real number $\alpha$), $\alpha$ must be zero, and $\beta=1$ or $\beta=-1$.
The facts that isomorphism preserves real scalar multiplication (if you do consider scalar multiplication), and that $\begin{bmatrix}1&0\\0&1\end{bmatrix}$ is sent to  $1$, $\begin{bmatrix}0&1\\-1&0\end{bmatrix}$ is sent to $i$ or $-i$, force us to define $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix}\mapsto\alpha+\beta i$$ or $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix}\mapsto\alpha-\beta i.$$

As for why we came up with these matrices of special form, it follows from a fact about complex number multiplication: multiplication by a complex number is the same as doing a proper rotation and then a scaling. The matrix $$\begin{bmatrix}\alpha&\beta\\-\beta&\alpha\end{bmatrix}$$ represents a linear transformation that does a rotation and then a scaling. You may notice that the matrix may be written as $$\begin{bmatrix}r\cos\theta&r\sin\theta\\-r\sin\theta&r\cos\theta\end{bmatrix},$$ where $r$ is the scaling factor and $\theta$ is the rotation angle. This is a whole new story I won't extend further.
Comment: And how do i show that it preserves the multiplicative identity ?
Comment: Yeah please add
Comment: $\begin{bmatrix}1&0\\0&1\end{bmatrix}\mapsto1+0 i=1.$
Answer: It will be sum of kronecker product of

$\begin{bmatrix}1&0\\0&1\end{bmatrix}$ and $\alpha$
$\begin{bmatrix}0&1\\-1&0\end{bmatrix}$ and $\beta$

By block multiplication property of matrices:

the 1 behaves as a real $1$
the 2 behaves as an imaginary $i$.

1) should be obvious.
We can verify 2) by calculating it's first few powers up to 4 to see it shifts through $-1,-i,1,\cdots$ corresponding to $\begin{bmatrix}-1&0\\0&-1\end{bmatrix} ,\begin{bmatrix}0&-1\\1&0\end{bmatrix}, \begin{bmatrix}1&0\\0&1\end{bmatrix}$ above.


Show that $\int_{E} \vert f_{k} − f \vert dm \to 0.$

Question:
Problem: Let $f_k$ be a sequence of non-negative measurable functions such that
  $f_k \to f$ a.e on $E,\; f \in L(E)$ and $\int_{E} f_{k}dm \to\int_{E} f dm$. Show that $\int_{E} \vert f_{k} − f \vert dm \to 0.$
What I know:
  I cant use the Scheffe's Lemma because I don't know $f_{k}$ are integrable or bounded. So I can't use the $g_{k}=\vert f_{k}-f\vert\leq f_{k}+f$ and consequently DCT.

I need just a hint, not the whole solution.
Comment: $f_k$ must be integrable for large enough $k$. Use Fatou's lemma on $f_k + f - \lvert f_k - f\rvert$.
Comment: \begin{align}
2\int_E f\,dm &= \int_E \liminf g_k\,dm \\&\leqslant \liminf \int_E g_k\, dm \\
&= \liminf \Biggl(\int_E f_k\,dm + \int_E f\,dm - \int_E \lvert f_k - f\rvert\,dm\Biggr) \\
&= 2\int_E f\,dm - \limsup \int_E \lvert f_k - f\rvert\,dm\,.
\end{align}
Comment: @DanielFischer I used but it did not work. Actually, at this condition, I have to use $\int \vert f_k \vert \to \int \vert f\vert $ which is incorrect.
Answer: By Fatou's lemma,
\begin{align*}
\int 2f = \int \lim_{k\to\infty} \left(f_k+f - \lvert f_k-f\rvert\right)
&\leq \liminf_{k\to\infty} \int\left(f_k+f - \lvert f_k-f\rvert\right)\\
&\leq \int 2f - \limsup_{k\to\infty} \int\lvert f_k-f\rvert
\end{align*}
Thus,
$$
0\leq\limsup_{k\to\infty} \int\lvert f_k-f\rvert \leq \int 2f - \int 2f = 0
$$
Which proves the result.
Answer: For large enough $k$, $f_{k}$ is integrable. Using the reverse Fatou's Lemma (which requires precisely this condition on $f_{k}$), we have
$\lim_{k\to\infty}\int_{E} |f_{k} - f|dm \leq \lim_{k \to \infty}\sup \int_{E}|f_{k} - f|dm \leq \int_{E} \lim_{k \to \infty}\sup |f_{k} - f|dm = 0$.


Boot gets stuck after PXE agent exits

Question: After installing Ubuntu via PXE onto one of our new servers, the machine keeps getting stuck here on boot:
<code>Intel(R) Boot Agent GE v1.3.27
Copyright (C) 1997-2008, Intel Corporation
CLIENT MAC ADDR: 00 30 48 FF 96 2C  GUID: 99845D56 9B90 FE2D 39E6 003048FF962C
PXE-E51: No DHCP or proxyDHCP offers were received.

PXE-M0F: Exiting Intel Boot Agent.
</code>
When I configure the DHCP server to send PXE replies to this machine again, it PXE boots fine, but it just hangs like this when there are no PXE offers.
I'm not sure why it would stop here with no additional messages. Any clues why?
Answer: You are still trying to PXE boot, but you should be booting to the disk where you installed Ubuntu. The server should then proceed onto the next boot device after not getting PXE options. You could also hit escape when the network boot agent starts doing its thing.
Go into setup/BIOS/EFI and make sure that the boot devices (and order) are sane (probably not).
Answer: There are a few things this could be:

As Keith mentioned, the BIOS boot order may not have the hard drive listed.
(This is what actually happened to me) your boot loader is not actually installed properly. In my case, I'm using a relatively old installer which is only partly aware of GPT partitioning. GPT partitions the disk correctly but then GRUB doesn't get installed correctly. The short term fix for me was to use the SSD, which has enough blocks to be partitioned using MBR partitioning, as the boot device, instead of the larger RAID volume.
Answer: If the PXE boot was the last available boot device, and it failed, it will stop there.
If you want failover for this, ensure that there is another bootable device with a lower priority.  Some BIOSes also allow you to automatically reboot in this case, but this is rare.

Boot gets stuck after PXE agent exits


Masking BERT subword tokens for NER?

Question: I have the following named-entity recognition (NER) model: (BERT > LSTM > CRF)
Extracting BERT vectors needs that we tokenize the input text using BERT tokenizer which tokenizes the text into subword tokens.
Next, these subword tokens are passed through LSTM and finally classified using a final CRF layer.
However, the final classification using the CRF layer requires that we mask these subword tokens because we do not want them to be a new state in the CRF layer. These subword tokens are also masked when calculating the loss because we do not want to predict on these subword tokens or make them contribute to the loss.
My question is: Do these subword tokens require masking at the LSTM layer?
Answer: TLDR: No, the subword tokens are not masked during the LSTM layer. Only the <PAD>, <CLS>, and <SEP> tokens are masked at the LSTM layer. However, these subword tokens are masked during last fully connected layer or if the layer is a CRF layer.

Masking BERT subword tokens for NER?


Playing recorder with bandaged finger

Question: Stupid me decided to drill half-inch holes with a drill-press in a piece of aluminum trying holding the piece with my bare hands. I ended up with a good sized cut on the pad of my left fourth digit and have to keep a bandaid on it to protect it.
Now, when I play recorder, I can't feel where my finger is on the recorder. Completely covering the hole is challenging too. How can I effectively play recorder for the time being?
Comment: If the problem is air tightness for the covered hole: there are finger protectors (like a cut of finger of a rubber glove), which may help. The missing feeling is hard to compensate however.
Comment: Well, there are still 11 playable notes even without the left fourth digit. You could compose and/play pieces where you do not need that finger :D
Answer: I would say, fall back on technique. If you have a proper grip, just trust that your fingers will be where they are supposed to go. And a rubber finger tip glove should solve any sealing problems.
That said, I would wait for fresh skin to develop on the pad before really trying to play anything. Especially an open hole instrument.
Answer: Ok, so I don't have 50 reputation right now, so I'll just post a comment here: do you have to play the recorder while waiting for the injury to heal? It's most likely not as severe as trying to play with a broken arm, but imo it's comparable; if you try too hard to cover up the hole (there's definitely some pressure needed) and hurt your finger in the process that's no good. Also, is there a way to wrap something around the finger that can cause it to cover the hole more effectively?
Another question is whether you actually have to feel where the finger is on the recorder, since the left ring finger/fourth digit only has one hole to cover, and thus the movement of the finger can be muscle-memo'd, or you can just look at the fingers while playing. =P
Anyway, if you really want to continue playing recorder (which'd be fine, because music>no music) just don't hurt yourself further. :3
(Then of course there's the extreme recorder player who learns alternative fingerings for each note that requires that finger in the first place)
Answer: Of course you don't want to do anything that will endanger your recovery, increase the chance of infection or anything like that.
You might try wrapping the bandaid and top knuckle in gauze to make it easier to cover the entire hole. You might experiment with that idea by wrapping down to the 2nd knuckle and holding that finger in a straighter position than do with the other fingers.
Comment: It' not a serious cut, but deep enough that it's taking a while to heal.
Answer: Two other possibilities, which both work but are both a bit awkward:
Use your left hand little finger instead of the ring finger, or play further in with the left hand, inboard of the bandage so to speak.
Being an instrument maker who also cuts his hands sometimes, and a recorder player, I've had occasion to do both, but of course they do limit virtuosity unless you practice them some.  But they might be worth trying.

Playing recorder with bandaged finger


Can a convergent sequence exist such that the limit of the sequence is not a fixed point of the sequence rule?

Question: Can a sequence defined by $$x_{n+1} = f(x_n)$$ exist such that it converges to $x$ but $$f(x)\ne x,$$ that is, $x$ is not a fixed point of $f$?
Motivated by this question. I wrote an answer there but something seems fishy and I cannot pinpoint what.
I see that it is obvious if you define the function pathologically (say $f(x) = (x+2/x)/2$ for real $x$ but $f(x)=0$ for imaginary x), so feel free to assume any "nice" properties for the function.
Comment: If $f$ is continuous, $\lim_{n\rightarrow\infty}f(x_n)=f(\lim_{x\rightarrow\infty}x_n)=f(x)$.
Answer: Sure. Take $f(x) = \frac{x}{2}$ for $x \neq 0$ and $f(x) =1$ for $x = 0$.
Answer: If $f$ is continuous at $x$, then
$$
x=\lim_{n\rightarrow\infty}x_n=\lim_{n\rightarrow\infty}f(x_n)
$$
by the definition of $x_n$.  Since $f$ is continuous, we can interchange the limit and the function so that
$$
\lim_{n\rightarrow\infty}f(x_n)=f\left(\lim_{n\rightarrow\infty}x_n\right)=f(x).
$$
Therefore, you're looking for a function which is not continuous at $x$ in order to have the property that you're looking for.
Note that you can construct examples where the desired property holds, but $f$ is not continuous, so the precise requirements are hard to state.
An interesting related question might be if $\lim_{n\rightarrow\infty}x_n=x$ such that $x_{n+1}=f(x_n)$, can we find a continuous function $g$ that agrees with $f$ on $\{x_n\}$.


When is the homomorphic image of a Fuchsian group into ${\rm PSL}(2,\mathbb{R})$ Fuchsian?

Question: Let $G$ be a Fuchsian group, by which we mean a discrete subgroup of ${\rm PSL}(2,\mathbb{R})$. Or equivalently: $G$ is a subgroup of the automorphisms of $\mathbb{H}$ which acts properly discontinuously.
Let $\phi: G\to{\rm PSL}(2,\mathbb{R})$ be a homomorphism. When can we say $\phi(G)$ is also Fuchsian?
I believe it's not true in general, but I've been having trouble constructing a counterexample. Here's what I have so far:
Let's suppose $G$ is finitely generated with at least two generators $g_1,g_2$, and suppose further there is no relation between them. Define $\phi(g_1)$ to be $z\mapsto z+1$ and $\phi(g_2)\mapsto kz$ for $0<k<1$, and then send everything else in $G\setminus \langle g_1,g_2\rangle$ to the identity. I believe(?) this gives a well-defined homomorphism by extending in the natural way. The image $\phi(G)$ is not Fuchsian then since one can construct indiscrete orbits (for example, $\phi(G)\cdot i$ includes points of the form $i+mk^n$, and so $i$ is not isolated in the orbit).
There seems to be issues with this idea though. For one thing, one can't send the generators of $G$ to elements of arbitrary type. For example, if $g\in G$ is elliptic and of finite order, then $\phi(g)$ must be elliptic as well. It would also be nice to not have to assume $G$ is finitely generated, or make arbitrary assumptions about the generators. Does anyone have a more general construction?
A softer question: what conditions can be imposed to ensure that $\phi(G)$ is Fuchsian? Does assuming $G$ is, e.g., nonelementary and elliptic-free win you anything? Or does one need to impose restrictions on $\phi$ (say, make it continuous)?
Comment: Examples are easy to construct, just take any homomorphism of free group such that one of the generators maps to an elliptic element of infinite order. Once you assume that $G$ is finitely generated, there are various algorithmic criteria for discreteness of subgroups of $PSL(2,R)$.
Comment: The full answer to your question is quite complicated and depends on which abstract group you are asking about. I would suggest narrowing the scope of your question. For instance, if $G$ isomorphic to the rank $2$ free group, and discreteness of images of homomorphisms $F_2 \mapsto PSL(2,\mathbb R)$ is a complicated subject; see [this MathOverflow post](https://mathoverflow.net/questions/96469/matrices-generating-non-discrete-subgroups-of-sl2-r), in particular the references to Gilman's book.
Comment: If on the other hand $G$ is isomorphic to the fundamental group of a closed, oriented surface of genus $g$, there is a lot of information in Goldman's thesis, which you can also be referred to in that same MathOverflow link.
Comment: And, yes, a nonelementary subgroup of $PSL(2,R)$ containing no elliptic elements is necessarily discrete.
Comment: Thanks! The surface fundamental group case was actually exactly the case I am most interested in, so the reference to Goldman's thesis is very helpful!
Answer: This is not a full answer, just too long for a comment.
Any map from a Fuchsian group is continuous, as the topology on the group is discrete. Requiring that the homomorphism is a homeomorphism on its image is clearly sufficient, as being Fuchsian is a purely topological property.
Being a discrete subgroup is a strong condition, as the group structure forces the group to be uniformly discrete, i.e. there is a radius such that a ball of this radius around any point in the group intersects the group only in that point. Thus, you can reduce to trying to find some Fuchsian group that contains in its image a non-repeating sequence in $PSL_2(\Bbb{R})$ that approaches $I$. In a Fuchsian group, any sequence approaching $I$ must eventually be constant $I$, so this would show the claim.
This is difficult, and might be impossible. For example, there is no matrix $A\neq I$ such that $A^n\to I$ (this can be shown by an eigenvalue argument), so there is no hope that $\Bbb{Z}$, embedded as a Fuchsian group, could map to something non-Fuchsian.


conditional skipping of the files using pandas.read_sql

Question: I am trying to read the values in the columns which I would like to use from the database files such as MS Access file only if the certain condition are met.
I have 26 different MS access files representing the database for 26 different years.
import pyodbc
import pandas as pd
import numpy as np
k = 1993 + np.arange(24)

for i in k:
    print(i)
    DBfile = r'D:\PMIS1993_2016'+'\\'+str(i)+'\\pmismzxpdata_'+str(i)+'.mdb'
    print(DBfile)
    conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+DBfile)
    cur = conn.cursor()
    qry = "SELECT JCP_FAILED_JNTS_CRACKS_QTY, JCP_FAILURES_QTY, JCP_SHATTERED_SLABS_QTY, JCP_LONGITUDE_CRACKS_QTY, JCP_PCC_PATCHES_QTY FROM PMIS_JCP_RATINGS WHERE BEG_REF_MARKER_NBR = '0342' and BEG_REF_MARKER_DISP LIKE '0.5' and RATING_CYCLE_CODE = 'P'"
    dataf = pd.read_sql(qry, conn)
    print(dataf)
    D = list(dataf.values[0])
    print(D)

    conn.close()

Here I have tried to read values of variables of JCP_FAILED_JNTS_CRACKS_QTY, JCP_FAILURES_QTY, JCP_SHATTERED_SLABS_QTY and  JCP_LONGITUDE_CRACKS_QTY, JCP_PCC_PATCHES_QTY  when BEG_REF_MARKER_NBR = '0342' and BEG_REF_MARKER_DISP LIKE '0.5' and RATING_CYCLE_CODE = 'P'.
However, not every year meets the conditions of BEG_REF_MARKER_NBR = '0342' and BEG_REF_MARKER_DISP LIKE '0.5' and RATING_CYCLE_CODE = 'P'.
So, I would like to skip the years which does not meet these condition such as if else function indicating the years which does not satisfy.
If you have any help or idea, I would really appreciate.
Isaac
Answer: You can use the .empty attribute:
In [11]: pd.DataFrame().empty  # This DataFrame has no rows
Out[11]: True

e.g. to skip the empty datafs:
if not dataf.empty:
    D = list(dataf.values[0])
    print(D)

Comment: Thank you Andy, I really appreciate your help.


Share image and text message with Wechat not working in objective c

Question: Hi I am trying to share an image URL and description with a wechat user using UIActivityController but it fails to share the image. I have tried with the following code:
<code> UIActivityViewController *activityView = [[UIActivityViewController alloc]   initWithActivityItems:@[@"TestMessage", [UIImage imageNamed:@"pauseImage"], [NSURL URLWithString:@"http://www.google.com"]] applicationActivities:nil];

 activityView.excludedActivityTypes = @[UIActivityTypeAssignToContact,
 UIActivityTypeCopyToPasteboard, UIActivityTypePrint];

 [self presentViewController:activityView animated:YES completion:nil];
</code>
I am getting output as shown in following image:
Any help or suggestions would be appreciated. Thanks.
Answer: In Swift, the below code works for me.
Sorry, I do not have exact code in Objective C but thought this might also be helpful.
<code>        let objectsToShare : NSMutableArray = NSMutableArray()
        //add title and description
        objectsToShare.addObject(titleToShare)
        objectsToShare.addObject(myWebsite)
        if(self.pageThumbImage.image != nil)
        {
            //here pageThumbImage is an UIImageView object
            objectsToShare.addObject(self.pageThumbImage.image!)
        }
        let activityVC = ActivityViewController(activityItems: objectsToShare as [AnyObject], applicationActivities: nil)
        //New Excluded Activities Code
        activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr, UIActivityTypeCopyToPasteboard,
        UIActivityTypeSaveToCameraRoll, UIActivityTypeAssignToContact, UIActivityTypeMessage,
        UIActivityTypeMail, UIActivityTypePostToTwitter]
        activityVC.popoverPresentationController?.sourceView = sender as? UIView
        self.presentViewController(activityVC, animated: true, completion: nil)
</code>


Is there a Relative Pitch Clef?

Question: To start out: I am more-or-less familiar with all the standard musical clef notations, including F, C, and G clefs; as well as the fact that clefs can be movable (tenor clef, french violin clef...) and have octave displacements (8va/8vb). I'm also aware of the unpitched percussion clef. With the exception of the later, these are all ways to map staff positions to absolute pitches. (I should also mention that in the case of transposing instruments, like Clarinets or Horns, this absolute pitch may not be the pitch it first appears to be.)
My question is whether anyone has ever seen a clef that maps staff positions to relative pitches (i.e. scale degrees) rather than absolute pitches. I realize this would be of limited use, especially for performers, who need to know which note on their instrument to play. But I could see such a system being useful in certain harmonic or analytical contexts, where the absolute pitch is unimportant (for example, notating chord progressions, or melodic motifs, irrespective of key). I could also see it being used for initial steps of transcriptions done by-ear, where the key isn't immediately important.
The "work around" is just to pick some specific key (which may or may not be correct, and which may often end up being 'C'), and just notate in that key. That works fine, I suppose, but it makes an explicit statement about key which may not be accurate or relevant. Of course, there are also numbers and solfege symbols which can be used, but these use alphanumeric characters, rather than standard music notes, and thus lose rhythmic information. One similar thing I've seen is shape-notes, in which the shape of note heads indicate scale degree. But this is non-standard notation practice (thankfully!), and it still uses normal clefs to indicate absolute pitches. I suppose transposing instruments are probably closest to what I'm looking for, if they were notated without a specific transposition in mind.
I have not been able to find any information on Google about the existence of such a clef, so I presume it doesn't exist, but I might not be using the right keywords, or it might be very obscure, so I'm wondering if anyone else has ever come across something like this? I'd be mildly surprised if no music theoretician anywhere has ever proposed some such system.
Comment: This is a great question (+1). So far it appears that this form of notation is either so obscure that it is not easily found or begs to be developed and nurtured. This might be like cosmologists trying to define dark matter, ok that's a bit of a stretch. However, if no one here can find an answer, we then should turn to you to develop this new system which as you have pointed out could be a very useful to define analytical contexts. Have you looked into speech cognition, or speech therapy to see if there are tools like this?
Comment: The system you're describing is the "movable do" or Solfege system. (Without the clef and notes, though...!)
Comment: Yeah, I mentioned solfege. It's specifically the clef and notes that I'm hoping to have!
Comment: Have you checked http://musicnotation.org/?
Comment: Oops, yes I missed that, mea culpa! Sorry, Caleb...
Comment: Although it's not a specific "scale degree" clef and stave, just wondered if you'd seen or used the wide-spaced three line stave, which shows how relatively high or low pitches are, without being specific within a key.
Comment: This would be similar to the Nashville Number System for chord players, but with reference to dots?
Comment: @dan04 That's an interesting concept.  Seems like it would be more useable for dodecaphonic and atonal works than traditionally-harmonized music.  That may actually make it a good answer for the question, though.
Comment: "all ways to map staff positions to absolute pitches": in modern times, A can be anywhere from 392 Hz to 466 Hz.  When the clefs were developed, there was probably even more variability.  The clefs started out as a mechanism to help identify where the half steps were -- a relative pitch system.
Answer: In western staff notation every clef represent fixed set of notes so the what is written can easily be conveyed to any musician without much knowledge of the theory behind the notes just the knowledge of this is X note. Also note the key signatures themselves are set in a fixed pattern to simplify the reading for musicians. Even in the more loosely defined percussion (or neutral) clef, there is an understanding that the first space is for bass drum, the third space is for snare, and the space above the staff is for some kind of cymbal. The notation is meant for precision and not for theory and relativity.
There are analysis techniques that can reduce harmony (chords) into relative ideas. The most widely used analysis is Roman Numeral Analysis and it's modern form the Nashville number system. These are extremely useful for chords and making them relative to any key, but it's not for melodies.
There is a numbered musical notation popular in Asian countries. The basic idea is that the key is given and the notes are all numbers based on the scale degree. There is no clef because we are dealing with numbers instead notes on a staff. Here is the Wikipedia entry for the kind of notation.
Comment: @BraddSzonye - I completely disagree with you here. Figured bass is *not* a compromise - it was a short-hand used primarily in the Baroque period for the continuo to realize the harmony to support the melody.  If anything, it may be considered a predecessor of macro-analytical notation used in lead sheets and jazz charts used by contemporary musicians.
Comment: @jj And it also expresses harmony in terms of abstract intervals rather than specific notes for each voice, much like the question asks for. Perhaps *compromise* is the wrong word for it, but it does seem to be partly in the spirit of what the OP wants.
Comment: You might want to mention figured bass notation as it's kind of a compromise between using a conventional staff and Roman numeral notation. Good answer!
Answer: I encountered the same question when I started playing the jammer (in the form of the Hexiano Android app).  Due to its isomorphic keyboard layout (and thus ease of transposition), this instrument lends itself very well to a relative-pitch notation.
Eventually, I developed my own system of jammer tablature.  Of course, it suffers from a lack of musical scores written in it, and for that reason may not be a suitable answer for your question.  But just in case anyone here is curious, here's what it looks like.
Pitch Notation
Notes are written on a vertical staff consisting of 4 lines and 3 spaces.  The spaces correspond to the "root row" (do-re-mi) on the jammer keyboard, and the lines correspond to the "dominant row" (fa-so-la-ti) above.
  do
fa  so  la  ti
  do  re  mi

Notes of the major scale
│ │
├─┼─┬─┐
│●│ │ │ do
│ │●│ │ re
│ │ │●│ mi
● │ │ │ fa
│ ● │ │ so
│ │ ● │ la
│ │ │ ● ti
│▲│ │ │ do
└─┴─┴─┘

Notes of the minor scale
Uses the same root and dominant rows of the relative major, but starts on "la" of the row below.
    │
┌─┬─┼─┐
│ │ ▼ │ la
│ │ │ ▼ ti
│●│ │ │ do
│ │●│ │ re
│ │ │●│ mi
● │ │ │ fa
│ ● │ │ so
│ │ ● │ la
└─┴─┴─┘

Chromatic notes
continue the same jammer keyboard-based arrangement.
  C♭  D♭  E♭  F   G   A   B   C♯  D♯  E♯
F♭  G♭  A♭  B♭  C   D   E   F♯  G♯  A♯  B♯
  C♭  D♭  E♭  F   G   A   B   C♯  D♯  E♯
F♭  G♭  A♭  B♭  C   D   E   F♯  G♯  A♯  B♯
  C♭  D♭  E♭  F   G   A   B   C♯  D♯  E♯
F♭  G♭  A♭  B♭  C   D   E   F♯  G♯  A♯  B♯
Ledger lines are added as necessary.
Here's an ascending melodic minor scale:
    │
┌─┬─┼─┐
│ │ ▼ │     la
│ │ │ ▼     ti
│●│ │ │     do
│ │●│ │     re
│ │ │●│     mi
│ │ │ │●    fi
│ │ │ │ │●  si
│ │ ● │     la
└─┴─┴─┘

Octaves
The "main" octave uses circular (●) noteheads.  The octave above it uses upward-pointing triangles (▲), and the octave below it uses downward-pointing triangles (▼).  Pieces that span 3 or more octaves need to use "8va" notation.
Chords
Multiple notes played together are written in the same horizontal row.  Here are the triads within the major scale:
┌─┬─┬─┐
│●● │●│ I
● │●● │ ii
│ ● │●● iii
●▲│ ● │ IV
│ ●▲│ ● V
│▲│ ●▲│ vi
▲ │▲│ ● vii°
└─┴─┴─┘

Key signatures
Because jammer tablature is a relative-pitch notation, these are optional!
Major key
Above the staff, write the tonic ("do") on the first space.
 C
│ │
├─┼─┬─┐
│●│ │ │
│ │●│ │
│ │ │●│
...
Minor key
Above the staff, write the tonic ("la") on the third line.
    A
    │
┌─┬─┼─┐
│ │ ▼ │
│ │ │ ▼
│●│ │ │
...
Note length
Notehead colors

▽ ○ △ = whole note (4 beats unless otherwise specified)
▽ ∅ △ = half note (2 beats)
▼ ● ▲ = quarter note
X = quarter rest (longer rests are written as a sequence of multiple X's)

Length modifiers
Placed to the right of the note, chord, or rest.

/ = multiply by 1/2 (thus ●/ = 8th note, ●// = 16th note, etc.)
3 = multiply by 1/3
· = multiply by 3/2

Example
The melody to "Frère Jacques"
│ │
├─┼─┬─┐
│●│ │ │
│ │●│ │
│ │ │●│
│●│ │ │
├─┼─┼─┤
│●│ │ │
│ │●│ │
│ │ │●│
│●│ │ │
├─┼─┼─┤
│ │ │●│
● │ │ │
│ ∅ │ │
├─┼─┼─┤
│ │ │●│
● │ │ │
│ ∅ │ │
├─┼─┼─┤
│ ●/│ │
│ │ ●/│
│ ●/│ │
●/│ │ │
│ │ │●│
│●│ │ │
├─┼─┼─┤
│ ●/│ │
│ │ ●/│
│ ●/│ │
●/│ │ │
│ │ │●│
│●│ │ │
├─┼─┼─┤
│●│ │ │
│ ▼ │ │
│∅│ │ │
├─┼─┼─┤
│●│ │ │
│ ▼ │ │
│∅│ │ │
└─┴─┴─┘

Answer: All of the clefs used in Gregorian chant notation represent relative pitch only. A Gregorian C or F clef only tells you the position of the half steps, but the absolute pitch is up to the people singing.
The very earliest chant notation is "adiastematic"--not on a staff, which hadn't been invented yet, and not showing specific intervals. The symbols indicate only relative up and down movements. The problem is that you can only sing from this notation if you already know how the melody goes. This is why the staff and clefs were invented---not to indicate absolute pitch, but to clarify the position of the half steps and the exact intervals between notes.
Also before the eighteenth century, pitch varied so widely from place to place, and local customs varied for how to interpret clefs, so written clefs did not correspond to modern pitches.
Comment: This same procedure could be used (as partially mentioned in the OP) with any current clefs. The absolute frequency of Middle C isn't really fixed, especially with some orchestras tuning high to sound more brilliant.
Comment: @ttw Most orchestras tune Middle C to 261.6 Hz. Transposing instruments transpose music notation in a different key.
Answer: Check out the chromatic staff -- looks similar to standard notation but the interval from one line to the next space (and vice verse) is always a semi-tone, and thus doesn't imply any particular key.
Answer: It's possible that some of Schoenberg's Sprechstimme notation is close to what you are looking at. In works such as A Survivor from Warsaw or the Ode to Napoleon, he used a single line without a clef, with ledger lines above and below the "staff", and even with accidentals, although these are bit "impressionistic" without an idea of where Do is, and might be too imprecise for what you're looking at.
He also came up with a chromatic notation system that might serve well without clefs - it's fairly extensible, accommodates standard rhythmic notation well. Musicnotation.org (Dave's link) has a bit about it, but the real detail is to be found in his book Style and Idea.
Answer: Clefs and related symbols "are all ways to map staff positions to absolute pitches"
Yes and no. A clef's function is only to fix one specific pitch on the staff. The staff itself denotes relative pitches. That is, for example, an adjacent line and space always form a second; adjacent lines (or adjacent spaces) always form a third; and so forth.
The problem is ...
... that while the staff denotes the magnitude of intervals, it does not consistently denote the quality of the interval. Adjacent lines and spaces are always seconds, but whether they are major or minor seconds is dependent on the specific clef — similarly so for thirds, fourths, etc.
Regarding the chromatic staff
User Dave points out the chromatic staff. This works after a fashion, but it removes enharmonic distinctions between intervals. An augmented second and minor third, for example, are indistinguishable, which is fine in non-tonal music, but is problematic for Tonality. In the chromatic staff, for example, modulation is effectively hidden — or rather, can be recognized only by looking at large enough swaths of notes to realize they fall into the pattern of a new key. (A new key might also be recognized by ear.)
A proposal
I suggest that the "best" way to achieve the desired goal is not a new clef (or staff) but rather to simply "notate" intervallically. The starting "pitch" is arbitrary, followed by a "list" of M2^ m6v m2^, where ^ and v indicate up and down. Duration could be notated with standard symbols below (or above) the interval designations. This also has the potential advantage (for example, with transcription) of allowing for pitch and rhythm to be dealt with separately — notate all the intervals, say, first, then go back and fill in the rhythm.

Is there a Relative Pitch Clef?


Ember/Rails end-to-end testing error

Question: I have an Ember CLI app with a Rails back-end API. I am trying to set up end-to-end testing by configuring the Ember app test suite to send requests to a copy of the Rails API. My tests are working, but I am getting the following strange error frequently:
<code>{}
Expected: true
Result: false

at http://localhost:7357/assets/test-support.js:4519:13
at exports.default._emberTestingAdaptersAdapter.default.extend.exception (http://localhost:7357/assets/vendor.js:52144:7)
at onerrorDefault (http://localhost:7357/assets/vendor.js:42846:24)
at Object.exports.default.trigger (http://localhost:7357/assets/vendor.js:67064:11)
at Promise._onerror (http://localhost:7357/assets/vendor.js:68030:22)
at publishRejection (http://localhost:7357/assets/vendor.js:66337:15)
</code>
This seems to occur whenever a request is made to the server. An example test script which would recreate this is below. This is a simple test which checks that if a user clicks a 'login' button without entering any email/password information they are not logged in. The test passes, but additionally I get the above error before the test passes. I think this is something to do with connecting to the Rails server, but have no idea how to investigate or fix it - I'd be very grateful for any help.
Many thanks.
<code>import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from 'mercury-ember/tests/helpers/start-app';

module('Acceptance | login test', {
  beforeEach: function() {
    this.application = startApp();
  },

  afterEach: function() {
    Ember.run(this.application, 'destroy');
  }
});

test('Initial Login Test', function(assert)
{

  visit('/');

  andThen(function()
  {
      // Leaving identification and password fields blank
      click(".btn.login-submit");

      andThen(function()
      {
        equal(currentSession().get('user_email'), null, "User fails to login when identification and password fields left blank");
      });
   });
});
</code>
Answer: You can check in the Network panel of Chrome or Firefox developer tools that the request is being made. At least with ember-qunit you can do this by getting ember-cli to run the tests within the browser rather than with Phantom.js/command-line.
That would help you figure out if it's hitting the Rails server at all (the URL could be incorrect or using the wrong port number?)
You may also want to see if there is code that needs to be torn down. Remember that in a test environment the same browser instance is used so all objects need to be torn down; timeouts/intervals need to be stopped; events need to be unbound, etc.
We had that issue a few times where in production there is no error with a utility that sent AJAX requests every 30 seconds, but in testing it was a problem because it bound itself to the window (outside of the iframe) so it kept making requests even after the tests were torn down.
Comment: Thanks. It is definitely hitting the Rails server - the requests are visible in the Chrome console and my tests are passing as expected, which wouldn't happen if it wasn't hitting the server. This weird error is _in addition_ to pass/fail messages about my tests.
Comment: Thanks but again I don't think it is due to teardown issues. The error appears when first running tests in a new incognito browser with caches disabled. As I understand it, code that should be torn down shouldn't affect the first run in a fresh browser instance.
Comment: The issue must be on the Rails side then, if you know which requests seem to cause the error you can add some print/logging statements to see what's happening, you can also add a debugger call (binding.pry) into the request. At this point it doesn't seem like an ember issue (but add some extra logging to be sure?)

Ember/Rails end-to-end testing error


htaccess redirect url to page

Question: I want to redirect a particular page using a 301 but my htaccess is also redirecting pages that contain the same start.
Example:
I want to redirect:

http://domain.com/advantage

To:

http://domain.com/index.php?page=some advantage

My current rule is
RewriteRule ^advantage "index.php?page=some advantage" [L,R=301]

This rule also redirects

http://domain.com/advantage-form.php

To the "some advantage" page
How do I fix this?
Answer: ^advantage should be ^advantage$
i.e. Instead of "Start, then advantage" it should be "Start, then advantage, then End".
Answer: This site is an expert on using mod_rewrite. Have a look at it. He is got lot of resources, if you are dealing with lot of rewrite rules. However whatever David said should work for the above question

htaccess redirect url to page


Get the Columns of an Inner Join LINQ query

Question: I am trying to inner join 2 DataTables on 2 DataColumns using Linq, I can get the rows using Linq how ever I cannot get the columns. I have commented out what I tried to do to get the columns, shown below.
The reason for doing this.
I am planning on making 3 methods, LEFT JOIN, FULL JOIN and INNER JOIN that will return a DataTable, I am trying to make it as generic as possible, I am not show if the below is a good way or not, I need to do this to be as Optimized as possible.
     public static DataTable InnerJoin
     (DataTable dt1, DataTable dt2,DataColumn Parent,DataColumn Child)
     {
          DataTable result = new DataTable();

          var query =
              from d in dt1.AsEnumerable()
              join c in dt2.AsEnumerable() on d[Parent] equals c[Child]
              select new { d, c };
         /*
         var columns  = from d in dt1.Columns.Cast<DataColumn>()
                        from c in dt2.Columns.Cast<DataColumn>()
                          select new{c,d}
          foreach (var column in columns)
          {
              result.Columns.Add(column);
          }
          **/

          foreach (var row in query)
          {
              result.Rows.Add(row);
          }

         return result;
     }

Comment: [codereview.stackexchange.com](http://www.codereview.stackexchange.com).
Comment: That won't compile since row is an nonymous type which you cannot [add to the RowCollection](http://msdn.microsoft.com/en-us/library/9yfsd47w.aspx). Edit: It compiles since there's an overload which takes a params object[]. But then you need to add two columns with type `DataRow`.
Comment: yeah.rows are in anonumous type.
Answer: Your code  compiles since there's an overload which takes a params object[]. But then you need to add two columns with type DataRow.
public static DataTable InnerJoin(DataTable dt1, DataTable dt2, DataColumn Parent, DataColumn Child)
{
    DataTable result = new DataTable();
    result.Columns.Add("Row1", typeof(DataRow));
    result.Columns.Add("Row2", typeof(DataRow));

    var query =
        from row1 in dt1.AsEnumerable()
        join row2 in dt2.AsEnumerable() on row1[Parent] equals row2[Child]
        select new { row1, row2 };

    foreach (var x in query)
    {
        result.Rows.Add(x.row1, x.row2);
    }

    return result;
}

If that's what you need, it should work.
Edit: and here's a (working) test
DataTable table1 = new DataTable("table1");
table1.Columns.Add("ID", typeof(int));
table1.Columns.Add("Name", typeof(String));

object[] a1 = { 1, "T1Row1Name" };
object[] a2 = { 2, "T1Row2Name" };
object[] a3 = { 3, "T1Row3Name" };
object[] a4 = { 4, "T1Row4Name" };
table1.Rows.Add(a1);
table1.Rows.Add(a2);
table1.Rows.Add(a3);
table1.Rows.Add(a4);

DataTable table2 = new DataTable("table2");
table2.Columns.Add("ID", typeof(int));
table2.Columns.Add("Name", typeof(String));
table2.Columns.Add("Table1ID", typeof(int));

object[] b1 = { 1, "T2Row1Name", 1 };
object[] b2 = { 2, "T2Row2Name", 2 };
object[] b3 = { 3, "T2Row3Name", 2 };
object[] b4 = { 4, "T2Row4Name", 2 };
object[] b5 = { 5, "T2Row5Name", 3 };
table2.Rows.Add(b1);
table2.Rows.Add(b2);
table2.Rows.Add(b3);
table2.Rows.Add(b4);
table2.Rows.Add(b5);

var joinedTable = InnerJoin(table1, table2, table1.Columns["ID"], table2.Columns["Table1ID"]);

foreach (DataRow r in joinedTable.Rows)
{
    DataRow r1 = r.Field<DataRow>("Row1");
    DataRow r2 = r.Field<DataRow>("Row2");
    String r1Name = r1.Field<String>("Name");
    String r2Name = r2.Field<String>("Name");
}

Comment: @Dreamer78692: Maybe you want to wrap the return value in a custom class which inherits `DataTable` or _has_ a `DataTable` e.g. `JoinedTable` which you could extend to enable multiple tables. Then you could make the code more readable.


Zipping files not appearing in correct location

Question: I'm new to C# and would appreciate a little help.
I've a windows console application that emails logs and is scheduled to run every hour.
What I want is to zip those logs(after they have been emailed) in the same folder. ie. the folder the application is reading the logs from.
This is snipped of my code so far.
string[] files = Directory.GetFiles(@"C:\Users\*\Documents\target", "*.txt");

try
{
    using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) //i'm using dotnetzip lib
    {
        foreach (var file in files)
        {
            Console.WriteLine(file);
            sendEMail(file);

            zip.AddFile(file,"logs");
        }

        zip.Save("mailedFiles.zip");
    }
}

What's happening with the above code is I'm able to create a zip file but not in the same folder where the application is reading from. Instead it creates the zipfile in my program's location(which makes sense).
How do I go about changing the location of the created zipfile. Also I want the individual logs to be replaced by the one zipfile that's created.
Answer: You can save the zip file to any of the special folders available in the user folder. You can get paths for the special folders with the following line of code:
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

If you want to save the zip file other than these special folders then there might be permission issues.
Answer: Try saving it by using the directory.
For example:
{
    string directory = @C:\Users*\Documents\
    zip.Save(directory + "mailedFiles.zip");
}

You should also use System.IO to get the directories instead of hardcoding them.


I am trying to submit an object that contains some data and a file from the client app to the API app using ASP.CORE 5

Question: I have tried to submit an object from client app to an API which contains some data and a file, but I failed to do so.
Here is the code:
(1) The model:
<code>public class ABC
{
    public int Id { get; set; }
    public string Image { get; set; }
    public string Name { get; set; }
    [NotMapped]
    public IFormFile File { get; set; }
}
</code>
(2) The client app controller
<code>    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(ABC aBC)
    {
        using (var httpClient = new HttpClient())
        {
            StringContent content = new StringContent(JsonConvert.SerializeObject(aBC), Encoding.UTF8, "application/json");
            using (var response = httpClient.PostAsync(BaseURLManager.BaseUrl + "ABCs", content))
            {
                var apiResponse = response.Result.Content.ReadAsStringAsync();
                aBC = JsonConvert.DeserializeObject<ABC>(apiResponse.Result);
            }
        }
        return View(aBC);
    }
</code>
(3) The API controller
<code>    // POST: api/ABCs
    [HttpPost]
    public async Task<ActionResult<ABC>> PostABC([FromForm] ABC aBC)
    {
        _context.ABC.Add(aBC);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetABC", new { id = aBC.Id }, aBC);
    }
</code>
Could any one provide me a working code, I am using ASP.NET Core 5.
Thank you in advance
Comment: what is the error you are getting. which part of this code is not working.
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: What is the "object" you expect? Please clarify
Comment: I would like to create an ABC object that contain all data including the file and send it to the API. I got no error, instead the API end point (PustABC) receive the ABC object with null values.
Comment: can you check in app controller if stringcontent is correctly serialized ?
Comment: Yes it is correctly serialized, and I have checked the object before posting it to the API endpoint (it contains the correct data), but it arrived at the API endpoint with null value
Answer: Since you use the FromForm attribute inside the api method, you should send request in formdata instead of json format.
More details, you could refer to below codes:
<code>        var client = new HttpClient
        {
            BaseAddress = new("https://localhost:7105/api/")
        };

        var path = $"{_hostEnvironment.ContentRootPath}test.json";

        var stream = System.IO.File.OpenRead(path);

          var request = new HttpRequestMessage(HttpMethod.Post, "PostABC");

          var content = new MultipartFormDataContent
                {
                    // file
                    { new StreamContent(stream), "File", "test.json" },

                    // payload
                    { new StringContent("1"), "Id" },
                    { new StringContent("bbbb"), "Image" },
                    { new StringContent("ccc"), "Name" }
                 };

        request.Content = content;

         var re = client.SendAsync(request).Result;
</code>
Result:


Is it possible to have custom, default fields added to all new product types In Commerce 2?

Question: I have multiple custom fields that will need to be on all new product types (Commerce 2). The fields are already created on the 'default' product type. But new product types do not inherit the custom fields.
Is there a way to have custom fields automatically added to all new product types?
Answer: Nothing that just works.
You could define them as a base field through code by defining them in hook_entity_base_field_info(), so for example how scheduler module does that. Then they will be non-configurable fields that are always there. If they're not multiple, they will even be added to the product base tables.
Those kind of fields are a bit tricky to uninstall.
The other option is implementing a hook_commerce_product_type_insert() and then copy the configurable fields you want from the default type and add them to that new bundle as well.
Comment: Thanks. I think using hook_commerce_product_type_insert()  will be the route for me to use. That way I can optionally use logic to determine if I want to install the fields on the product. Thanks!


How to post json data containing a file field with Guzzle?

Question: I'm trying to send the following data to a REST API with Guzzzle

{
    "documents": {
        "id_proprietaire": 28,
        "nom_proprietaire": "rash",
        "prenom_proprietaire": "rash",
        "code_identification": "9LS9PB094MIL9CPL",
        "dossier_initial": "path_to_data"
    },
    "dossier_final": null
}

But I don't find how to use multipart and json requests together. Can someone help?
This is what I have done and I got a 404 bad request error field documents is required

$httpClient = new Client();
$token = 'Token 7480ea9a692f98ad943e810820ced48aa09ca174';
$response =  $httpClient->post('http://127.0.0.1:8000/api_memoire/signed/', [
            'headers' => [
                'Authorization' => $token,
                'Accept'        => 'application/json',
            ],
            'multipart' => [
                [
                    'name' => 'documents',
                    'contents' => json_encode(
                        [
                            'id_proprietaire' => $id_demande,
                            'nom_proprietaire' => $demande->nom,
                            'prenom_proprietaire' => $demande->prenoms,
                            'code_identification' => $code,
                            'dossier_initial' => $document,
                        ]
                    ),
                ],
                [
                    'name' => 'dossier_final',
                    'contents' => null,
                ]
            ]
        ]);
Answer: You can send data via Guzzle like that:
$httpClient = new Client();
$token = 'Token 7480ea9a692f98ad943e810820ced48aa09ca174';
$response =  $httpClient->post('http://127.0.0.1:8000/api_memoire/signed/', [
            'headers' => [
                'Authorization' => $token,
                'Accept'        => 'application/json',
            ],
            'form_params' => [
                'documents' => json_encode(
                        [
                            'id_proprietaire' => $id_demande,
                            'nom_proprietaire' => $demande->nom,
                            'prenom_proprietaire' => $demande->prenoms,
                            'code_identification' => $code,
                            'dossier_initial' => $document,
                        ]
                    ),
                'dossier_final' => null
            ]
        ]);

Also, you can read more detail in official documentation


I need to loop a section of HTML code with php/javascript, suggestions?

Question: I've attempted using a for loop and heredoc in php using similar code:
 $options = '';

for($Year = date("Y"); $Year <= date("Y") + 5; $Year++)
{ $options .= "<option>$Year</option>\n"; }

$Select = <<<QQxQQ
<select>
$options
</select>
QQxQQ;

print "$Select";

But no luck...
EDIT
These examples are great, thanks guys.
This is what I'm trying to iterate

$looped

Where $looped is a value of a fetched mysql column. As you can probably see, I'm trying to iterate an element of a list x amount of times (where x = number of rows of sql query).
I thought trying to put the results into an array and then cycling through the array, however I still couldn't get the HTML code to go through the parser accordingly without being considered a string.
Comment: The interpreter is complaining about a whitespace after your heredoc declaration, otherwise it's fine - [test](http://codepad.org/sAkIjWPV)
Comment: Is it necessary that you want to use heredoc?
Comment: Based on the update you posted, try this then [Echoing mysqli queries](http://stackoverflow.com/questions/8806998/echoing-mysqli-queries)
Answer: How about this?
<select>
<?php
    for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) {
        echo "<option>".$Year."</option>";
    }
?>
</select>

Answer: You could try something like this:
<?php

$year = date('Y');
$end = ($year + 5);
do {
    $option .= '<option>'.$year.'</option>';
} while (++$year <= $end);

echo '<select>'.$option.'</select>';

?>

Answer: Heredocs have their place, but imo they are overrated and often used in the wrong context.
Try this:
$year = date("Y");
for( $Year = $year; $Year <= ($year+5); $Year++ ) {
    $options .= "<option value=\"$Year\">$Year</option>\n";
}

echo "<select name='years' id='years'>";
echo $options;
echo "</select>";

Answer: <select>
<?php
for($Year = date("Y"); $Year <= date("Y") + 5; $Year++)
{ echo "<option>$Year</option>\n"; }
?>
</select>


Parar requisição com Jquery ao atualizar a página ou clicar em algum link

Question: Estou usando long polling com PHP + JQuery, quando o usuário entra no site é aberta uma conexão em segundo plano com o servidor através do Jquery dessa forma:
var req  = $.post //(resto do codigo aqui).

Essa conexão fica aberta por 20 segundos e depois é fechada automaticamente.
Bom como vocês podem perceber eu gravo em uma variável para poder abortar a requisição com o req.abort();
Mas eu queria abortar ela apenas quando o usuário atualizasse a página ou desse um clique em algum link da página, pois quando ele faz isso o site só "responde" depois que a requisição é terminada, dessa forma o usuário teria de esperar 20 segundos + o tempo que o site poderia vir a demorar para por exemplo upar uma imagem após o fim da requisição, então eu gostaria de saber se tem como não fazer uma nova requisição quando ele der uma atualizada nela?
Ps: Usei como teste o setTimeout colocando ele para dar um req.abort(); depois de x segundos, e a requisição foi cancelada normalmente, então como não tinha nenhuma nova conexão aberta com o servidor aguardando resposta, quando a página foi atualizada ela não demorou 20 segundos para dar procedência, mas isso não é viável, visto que estou fazendo verificações em tempo real rsrs
Código atual do arquivo js abaixo:

$(function(){
pegaNotificacoes();
});

var totalnot = 0;
var totalparc = 0;

function limpatotal()
{
totalparc = 0;
$('#notifinum').html("");
}

function pegaNotificacoes(timestamp)
{

var data = {};

if (typeof timestamp != 'undefined')
 data.timestamp = timestamp;

var req  = $.post('controllers/longpolling.php', data, function(res){

 for(i in res.notificacoes)
 {

  if (totalnot == 0)
  {
   $('#notificacao').html("");
   $('#notificacao').prepend("
"+res.notificacoes[i].not_assunto+"
");
  }
  else
  {
   $('#notificacao').prepend("
"+res.notificacoes[i].not_assunto+"
");
  }

  totalnot = totalnot + 1;
  totalparc = totalparc + 1;
  $('#notifinum').html("").fadeOut('slow', 'linear');
  $('#notifinum').html(totalparc).fadeIn('fast', 'linear');

  if (totalnot > 1)
  {
   if ($("#notificacao").height() < 350)
   {
    var altura = ($("#notificacao").height()) + 55;
    $("#notificacao").height(altura);
   }
  }
 }

 pegaNotificacoes(res.timestamp);

}, 'json');

}
Answer: Cara pelo que eu entendi você pode verificar se ocorreu o evento reload, conforme o exemplo:
if(location.reload)
{
    req.abort();
}

Assim caso ele ocorra vc chama sua função que aborta a requisição.
No caso do click em um link, você pode adicionar na tag   no html uma classe, por exemplo:
 Aborte a requisição
E utilizando o jquery você pode pegar o click desta tag com o exemplo:
$('a').on('click','.abortar',function()
{
   req.abort();
});

Comment: A ideia do Marcos Henrique funcionou direitinho, ta cancelando a requisição toda vez que atualiza a página ou clica em um link exatamente da forma que eu queria, vlw parceiro :D :)
Comment: que bom que funcionou cara, estamos ai pra ajudar mesmo!


Producing two functions from a rotated parabola that graph the parabola in question

Question: The following is my attempt at splitting a rotated parabola into two real functions of one real variable (the $x$-coordinate). Let $P$ be the parabola, $V = (x_V, y_V)$ the vertex of $P$, $\alpha$ the angle between the $x$-axis and the line perpendicular to the axis of symmetry of $P$ and growing in counter-clockwise direction. Finally, let $g(t) = \beta t^2$ define the "geometry" of $P$.

Now, the line perpendicular to the axis of symmetry of $P$ and passing through $V$ (call it $\ell$) is given by equation
$$
y = (x - x_V) \tan \alpha + y_V.
$$
Let $x$ be given. We wish to calculate two values $y_1$ and $y_2$ such that $(x, y_1)$ and $(x, y_2)$ are located at the parabola's "lower" and "upper" parts. To do that, I start from $(x, 0)$, go up or down until I reach $\ell$ at point $B$, travel through the line segment $BT$, and finally travel through $TF$. If we fix $V$, $T$ becomes
$$
T(t) = (x_V + t \cos \alpha - \beta t^2 \sin \alpha, y_V + t \sin \alpha + \beta t^2 \cos \alpha).
$$
Next, we set $x = x_V + t \cos\alpha - \beta t^2 \sin \alpha$ and solve for $t$
$$
-\beta \sin(\alpha)t^2 + \cos(\alpha)t + (x_V - x) = 0,
$$
which has solutions
$$
\begin{aligned}
t &= \frac{-\cos\alpha \pm \sqrt{\cos^2\alpha - 4(-\beta\sin\alpha)(x_V - x)}}{-2\beta\sin\alpha} \\
  &= \frac{\cos\alpha \pm \sqrt{\cos^2\alpha + 4\beta\sin\alpha(x_V - x)}}{2\beta\sin\alpha}.
\end{aligned}
$$
Next, we need to find out $|VB|$:
$$
\begin{aligned}
|VB| &= \sqrt{(x - x_V)^2 + (\tan(\alpha)x - \tan(\alpha)x_V + y_V - y_V)^2} \\
     &= \sqrt{(x - x_V)^2 + (\tan(\alpha)x - \tan(\alpha)x_V)^2} \\
     &= \sqrt{(x - x_V)^2 + \tan^2(\alpha)(x - x_V)^2} \\
     &= \sqrt{(x - x_V)^2 (1 + \tan^2(\alpha))^2} \\
     &= (x - x_V)\sqrt{1 + \tan^2 \alpha}.
\end{aligned}
$$
Finally, the desired $y_1$ or $y_2$ are given by
$$
\begin{aligned}
y &= y_S + \sqrt{(|VB| - t)^2 + (\beta t^2)^2} \\
  &= y_S + \sqrt{(|VB| - t)^2 + \beta^2 t^4},
\end{aligned}
$$
where $y_S = \tan(\alpha)(x - x_V) + y_V$.
Question: is this calculation correct? Does it work for all $\alpha$, $\beta$, $V$? (Except $\alpha = n\pi$.)
Comment: @coderodde: [N.G. de Bruijn](https://nl.wikipedia.org/wiki/Nicolaas_Govert_de_Bruijn) has been a professor of mine at the [Eindhoven University of Technology](https://en.wikipedia.org/wiki/Eindhoven_University_of_Technology)
at the time I was a student. But he is not a relative or family; neither is [Inge de Bruijn](https://en.wikipedia.org/wiki/Inge_de_Bruijn), for example. De Bruijn (and its variations such as "de Bruyn" and "de Bruin") is quite a common last name in the Netherlands.
Comment: It would be a good check on your calculations to plug in some simple values and see if their evaluation comes out sensibly.
Comment: @hardmath Have a program (https://github.com/coderodde/ParabolaDrawer) for that. Unfortunately, something breaks when $\beta > 0$ **and** the parabola is oriented downwards (which is up to the value of $\alpha$), so I had no other options but asking here.
Comment: I'm having difficulty seeing how the ultimate expressions for $y$ answer the problem of breaking the rotated parabola into two curves, each of which is a function of $x$.  It seems to me you've left a dependence on $t$ in the formulas that prevents them from defining two functions of $x$.
Comment: @hardmath Most often $t$ would have two solutions, one producing the point on the upper part and another one on the lower part. Also, the discriminant may become negative, which has no real solution, so that would seem as the mechanism that for some $x$ there is no such $y$.
Comment: Yes, there may be some $x$ for which "there is no such $y$", so breaking the parabola into two curves, both functions of $x$ will involve identifying an interval of $x$ values over which both curves are defined.
Comment: The derivation hits a snag for $\alpha=n\pi$: dividing by zero is invalid.
Comment: @amd I consider it a non-interesting case.
Comment: Maybe relevant : [Understand 1D FEM solution using quadratics elements](https://math.stackexchange.com/questions/548856/understand-1d-fem-solution-using-quadratics-elements) ,
Comment: Maybe relevant : [What is wrong with this method for a rotated and shifted parabola?](https://math.stackexchange.com/questions/711004/what-is-wrong-with-this-method-for-a-rotated-and-shifted-parabola)
, [Proving that for each two parabolas, there exists a transformation taking one to the other](https://math.stackexchange.com/questions/667467/proving-that-for-each-two-parabolas-there-exists-a-transformation-taking-one-to)
Comment: @HandeBruijn Maybe relevant, but definitely above my level.
Comment: @HandeBruijn Wait, this is an off-topic question, but do you have anything to do with de Bruijn graphs?
Answer: The form of the solution will depend on the form in which you put the parabola. Any parabola (or circle or ellipse or hyperbola) in the plane can be expressed in the form $By^2 + Ax^2 + Cx + Dy + Exy + F = 0$. In the case of parabolas of interest here, that do not open up or down, $B$ will not be zero, so without loss of generality we can divide out by $B$ and assume the parabola is of the form $y^2 + Ax^2 + Cx + Dy + Exy + F = 0$. The problem is relatively easy to solve in this form. First, separate all terms with a $y$:
$y^2 + (Ex + D)y = -Ax^2 - Cx - F.$
Then complete the square in $y$ on the LHS:
$y^2 + (Ex + D)y + (\frac{Ex+D}{2})^2 = (\frac{E^2}{4} -A)x^2 + (\frac{ED}{2} - C)x + (\frac{D^2}{4} - F)$
That is,
$(y + \frac{Ex+D}{2})^2 = (\frac{E^2}{4} -A)x^2 + (\frac{ED}{2} - C)x + (\frac{D^2}{4} - F)$
so that
$ y + \frac{Ex+D}{2} = \pm\sqrt{(\frac{E^2}{4} -A)x^2 + (\frac{ED}{2} - C)x + (\frac{D^2}{4} - F)}$
or
$ y = -\frac{Ex+D}{2} \pm\sqrt{(\frac{E^2}{4} -A)x^2 + (\frac{ED}{2} - C)x + (\frac{D^2}{4} - F)}$
with the "upper" curve for $y$ being given by the choice of + in the $\pm$ and the lower by -. (Aside: and there is no solution when the expression inside the square root is negative. If $E^2 < 4A$, that clearly happens whenever $x$ is sufficiently negative or sufficiently positive. On the other hand, we know a rotated parabola either "opens to the right" or "opens to the left", so there will at least be two solutions for all sufficiently positive or all sufficiently negative $x$. Hence, we conclude that if the original curve was a parabola, then in fact $E^2 \geq 4A$.)
Anyhow, to use this solution in your case, I suggest you convert your parabola into this form. In particular, you can start with the upward-opening parabola with vertex $(a, b)$ which has equation $u - b = \beta(v-a)^2$ and then simply rotate about the origin by an angle $\alpha$, e.g. by substituting $u = x\cos\alpha - y\sin\alpha$ and $v = x\sin\alpha + y\cos\alpha$. You can arrange that the rotated vertex ends up at $(x_V, y_V)$ by taking $a = x_V\cos\alpha - y_V\sin\alpha$ and $b = x_V\sin\alpha + y_V\cos\alpha$.
I recognize that this is not a direct answer to the question of whether the expressions you list are correct, but I hope it will still be helpful, given that the original question of what are the expressions for the "upper and lower branches" of the rotated parabola is much simpler starting from the general quadratic equation in the plane as expressed in this solution.
Comment: I can't quite follow your text, neither I want to waste my 50 karma points, so the bounty is yours.
Comment: Well, I certainly would like to help. Would you like to suggest a specific example parabola that I could work out in the above fashion? Would that help? The main point is that if you just work from a general algebraic form of a parabola in the plane, then no trigonometry arises in generating the two functions you want. So the trigonometry can be left entirely to putting the parabola into that standard form. Let me know if a worked example would help, and if so what example, or if there's any other question I can answer about what I wrote.


Why will my not Background change on click with hexadecimal colors?

Question: I have an html document where i wanted to change the background color of the document by clicking on a button.
This works totally fine as long as i am using colors like "yellow, "blue", "red", etc.
But when i am using hexadecimal colors like "#000000" the if-condition doesnt seem to notice, that color and uses the else function.
If i use "black" instead of "#000000" the function works and the background turns red.
I've uploaded the working sample on jsfiddle.
Do you know where the mistake is?
https://jsfiddle.net/c2gv9x01/
<button>COLOR SWITCH</button>

Comment: What do you see if you log `backgroundColor` ?
Comment: seems to be working fine: https://jsfiddle.net/8v5s06w9/
Comment: @JonasWilms How to log backgroundColor in this example?
Comment: @gautam1168 Thanks, but in your version the if-condition works with the word 'black'. If I put in a hex number, it wont work again.
Comment: You have to parse the color into a uniform rgb format. You can use a library like (https://github.com/deanm/css-color-parser-js)
Comment: Here is your fiddle with color parser https://jsfiddle.net/jqvo7dp5/ . With this you can set the color as 'black' or '#000' or '#000000'. As long as you parse the color before checking it will work.
Comment: OK, thank you! The rgb solution worked for me!

So is the answer that I have to use the same format for alle colors? Or is there a problem with the hex-format?
Comment: Thanks @gautam1168!
Answer: There are many different string representations for the same color, so simply matching the hex color string won't necessarily work as that amy not be what your browser is using to report it:

window.onload = function() {
  let body = document.querySelector("body")
  body.style.backgroundColor = "#000000"
  console.log(body.style.backgroundColor) // rgb(0, 0, 0) in most browsers
}

When possible, avoid trying to match colors at all; not all browsers will use the same representation, so just switching to rgb instead of hex won't be guaranteed to work. Instead set a classname on the element which sets the colors you need, and test for the presence of that classname instead:

window.onload = function() {
  document.querySelector("body").classList.add("black")
  document.querySelector("button").addEventListener("click", color);
}

function color() {
  let body = document.querySelector("body")
  if (body.classList.contains("black")) {
     body.classList.add("red")
     body.classList.remove("black")
  } else {
     body.classList.add("black")
     body.classList.remove("red")
  }
}
.black {
  background-color: #000
}

.red {
  background-color: #F00
}
<button>COLOR SWITCH</button>

If you need to match a color, the safest way is to create a temporary element with the same background color, read the color from both that element and the one you're examining, and compare to see if they're the same; that will work regardless of the string representation the browser happens to be using.
Comment: I wanted to change the colors of several Elements on a website. Such as SVG´s and Background colors. So thats why i have to change specific colors of Elements.
Comment: That shouldn't make any difference; the same technique I showed here can be used on any element, not just the document body.
Comment: (If you need to style parts of an svg rather than the whole thing, [see here](https://stackoverflow.com/a/34284230/3412322).)
Comment: ok perfect, this really seems like the more efficient way, thanks!


Is there any difference between badminton and squash shoes?

Question: I'm asking because I didn't find any answer on the Internet, even on the sites dedicated to these sports.
Answer: Both badminton and squash are played on similar surfaces and both require quick changes of direction. They both require shoes with flexible, grippy and non-marking soles. Shoes marketed as for badminton shoes might be lighter as there is more focus on jumping than in squash, but the variation is minimal and mostly just marketing/labelling.
(Tennis shoes on the other hand are usually intended for outdoor use and will have different characteristics)
I know plenty of people who play badminton at local league level using shoes marketed as "squash shoes". No doubt some squash players play in shoes primarily intended for badminton too.
Whichever sport you play, you should probably try on shoes marked as for badminton and those marked as for squash to see which is more comfortable for you. This is far more important than having a label which matches your sport.