Bash script to read a particular after time stamp

Question: 29/08/2023,11:26:42,Info,========== Cognos Configuration =========
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/opt/sw/cognos/analytics/bin/slf4j-nop-1.7.23.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/opt/sw/cognos/analytics/configuration/utilities/config-util.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory]
29/08/2023,11:26:48,Info, Silent exit with error code: 0

This is the log file. In this file, there are 2 timestamps I want to grep on "Cognos Configuration" This means logging has started. After the 2nd timestamp (29/08/2023,11:26:48) I want to grep "Info, Silent exit with error code: 0" This confirms my application has started/stopped correctly.
The timestamps are not consistent as they will change every time the application is started or stopped so I bash the script to check after the timestamp and see an error code if 0 says success other than 0 shows as failed.
Thir
with
sed -n "/$(date +'%d\/%b\/%Y')/,/*/p" cogconfig.log |grep -i "with error code:"

I am not able to see the error code
Comment: Did you try just typing the `date` command to see if it produces what you want? `%b` is a month name, not numeric. You want `%m`.
Comment: `/*/` may not mean what you think. Is it a typo for `//` ?
Comment: `grep "$(date +%d/%m/%Y).*with error code:" cogconfig.log`
Comment: If you would debug your statement (with `set -x`), you would see that your `date` command produces for today the string `29\/Aug\/2023`, which is different in syntax from what is in the logfile.
Comment: You have `date +'%d\/%b\/%Y'` which outputs `29\/Aug\/2023` — a string for the month name instead of the month number.  Change the `%b` to `%m` to get `29\/08\/2023`.  With `sed`, you can use a different character than `/` for the search marker by using a backslash before the marker — for example, `\@29/08/2023@` — which avoids having to generate backslashes in the date format.  I'm not sure what you expect the `/*/` term to match.  What it does match is a line containing an asterisk.  You should probably anchor the date to the start of the line with a caret `^`.
Answer: Assuming;

The logging starts with the line containing Cognos Configuration.
You want to find the line containing the second timestamp after the line
above.
The timestamp is not consistent. You cannot use the fixed string.
You want to extract the string after the matched timestamp.

Then would you please try:
awk '
    f && sub("^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9],[0-9][0-9]:[0-9][0-9]:[0-9][0-9],", "") {
        print
    }
    /Cognos Configuration/ {
        f = 1
    }
' cogconfig.log

Output:
Info, Silent exit with error code: 0

/Cognos Configuration/ {f = 1} sets the flag f so the preceding lines
(including this line) are skipped with f.
The regex ^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9],[0-9][0-9]:[0-9][0-9]:[0-9][0-9], matches the timestamp followed by a comma.
The sub() function removes the matched substring.

Here's a one-liner version just in case:
awk 'f&&sub("^[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9],[0-9][0-9]:[0-9][0-9]:[0-9][0-9],", ""){print} /Cognos Configuration/{f=1}' cogconfig.log

With GNU awk which supports {n} quantifier:
awk 'f&&sub("^[0-9]{2}/[0-9]{2}/[0-9]{4},[0-9]{2}:[0-9]{2}:[0-9]{2},", ""){print} /Cognos Configuration/{f=1}' cogconfig.log

Comment: @Fravadona I've updated my answer considering the majority of the cases.  Thanks.
Comment: That gets an A for effort and thoroughness. (no meat left on the bone for other answers)
Comment: It might be worth using `{n}` in the ERE
Comment: @Fravadona thank you for the comment. I was just thinking to be POSIX awk compliant which does not support {m,n} quanifier. I'd admit the regex looks busy without using it.
Comment: `{n}` is POSIX though; but there's indeed a few older `awk`s that don't support it


Solve $X$ from $AXA^{-1}T = BXB^{-1}$

Question: Suppose we have four matrices $A, B, X, T$ from the special Euclidean group SE(3). How can we solve $X$ from this equation: $AXA^{-1}T = BXB^{-1}$? Or, how to represent $X$ in terms of $A,B,T$ given $AXA^{-1}T = BXB^{-1}$?
Answer: First of all, we can simplify the equation somewhat. If we make the substitution $Y = AXA^{-1}$, then this equation can be written as
$$
YT = (BA^{-1})Y(BA^{-1})^{-1} \implies YT = CYC^{-1},
$$
where $C = BA^{-1}$.
From there, I do not believe that there is a nice "closed form solution" for $X$. However, a solution can be obtained using vectorization. Note that each element of $SE(3)$ can be represented with an augmented matrix. In particular, the map that associated the affine transformation $T(x) = Ax + b$ with the augmented matrix
$$
[T] = \pmatrix{A & b\\0 & 1}
$$
is an injective Lie group homomorphism. Thus, we may replace each of the elements $C,T,X$ with their associated $4 \times 4$ matrices, so that $YT = CYC^{-1}$ is a linear equation over the entries of the matrix $Y$.
With vectorization, we can see that the equation can be expressed as
$$
(T^\top \otimes I_4) \operatorname{vec}(Y) = (C^{-\top} \otimes C)\operatorname{vec}(X) \implies\\
[T^\top \otimes I_4 - C^{-\top} \otimes C]\operatorname{vec}(X) = 0,
$$
where $I_4$ denotes the size $4$ identity matrix.
We can limit the solution set among the set of all $4 \times 4$ matrices to only those corresponding to elements of $SE(3)$ by applying the following additional constraints:

The last row of $Y$ must be $(0,0,0,1)$,
The upper left $3 \times 3$ matrix $M$ of $Y$ must be an element of $SO(3)$, which is to say that $M^TM = I_3$ with $\det(M) = 1$.
Answer: Rewrite the equation as $X(A^{-1}TB)=(A^{-1}B)X$ or, in block form,
$$
\pmatrix{R&v\\ 0&1}\pmatrix{R_1&v_1\\ 0&1}=\pmatrix{R_2&v_2\\ 0&1}\pmatrix{R&v\\ 0&1}.
$$
Multiply out and simplify, we get two equations $RR_1=R_2R$ and $(I-R_2)v=v_2-Rv_1$. Once $R$ is determined from the first equation, the second equation is just a non-homogeneous linear equation in $v$. Since $R_2$ is a $3\times3$ rotation matrix, $I-R_2$ is necessarily singular. Thus the second equation has either no solution or infinitely many solutions. In particular, if $v$ is a solution, then $v+u$ is also a solution for every vector $u$ lying on the rotation axis of $R_2$.
The similar can also be said to the first equation. Let $q=w+xi+yj+zk,\ q_1=w_1+x_1i+y_1j+z_1k$ and $q_2=w_2+x_2i+y_2j+z_2k$ be the unit quaternion representations of $R,R_1$ and $R_2$ respectively. The equation $RR_1=R_2R$ can then be rewritten as
$$
\pmatrix{
w_1-w_2&x_2-x_1&y_2-y_1&z_2-z_1\\
x_1-x_2&w_1-w_2&z_1+z_2&-(y_1+y_2)\\
y_1-y_2&-(z_1+z_2)&w_1-w_2&x_1+x_2\\
z_1-z_2&y_1+y_2&-(x_1+x_2)&w_1-w_2
}\pmatrix{w\\ x\\ y\\ z}=0
$$
and we are looking for a unit vector solution $(w,x,y,z)$. Since the $4\times4$ matrix on the left is in the form of $(w_1-w_2)I+K$ for some skew-symmetric matrix $K$, the multiplicity of the zero eigenvalue, if any, is even. It follows that the equation has either no unit vector solution (this occurs, e.g., when $R_1=I_3\ne R_2$) or infinitely many solutions.

Solve $X$ from $AXA^{-1}T = BXB^{-1}$


Trying to post json in angularjs will 400 bad request

Question: I am trying to post a static new entry using angularjs $http call but it will throws 400 bad request I am not getting why? Here I am passing the exact same type of json object in input.
Below is my main json file in which I want to add new record .
{
    "count": 384,
    "next": "http://22.214.171.124:8000/v1/tracks?page=2",
    "previous": null,
    "results": [
        {
            "id": 38,
            "title": "Hey Jude",
            "rating": "4.9",
            "genres": [
                {
                    "id": 5,
                    "name": "ramesh"
                }
            ]
        },
        {
            "id": 39,
            "title": "hello adele",
            "rating": "4.0",
            "genres": [
                {
                    "id": 4,
                    "name": "bollywood"
                },
                {
                    "id": 8,
                    "name": "metakai"
                }
            ]
        }
    ]
}

Data which I want to post:
var data = {
    "id": 79,
    "title": "new song anand",
    "rating": "4.0",
    "genres": [
        {
            "id": 4,
            "name": "bollywood"
        },
        {
            "id": 8,
            "name": "metakai"
        }
    ]
}

Syntax for posting data:
$http({
          method: 'POST',
          url: 'http://220.127.116.11:8000/v1/tracks',
          dataType: 'json',
          data: data,
          headers: { 'Content-Type': 'application/json; charset=UTF-8' }
          }).success(function (data) {
            console.log(data,"success");
          }).error(function (data) {
            console.log(data,"fail");
          });

Answer: Remove dataType: 'json' and charset=UTF-8 from headers.
$http({
          method: 'POST',
          url: 'http://188.8.131.52:8000/v1/tracks',
          data: data,
          headers: { 'Content-Type': 'application/json'}
          }).success(function (data) {
            console.log(data,"success");
          }).error(function (data) {
            console.log(data,"fail");
          });
It must work .
And if not re-check your JSON format. Something must be missing.


ascx'es javascriptscript

Question: I want my asp.net .ascx user control to use some javascript. How to do it properly? I am not sure what I should do? Should I use the scriptmanager object?
Answer: It depends on the situation.  It's perfectly reasonable just to drop the script into your ascx files.  This is what I do with simple scripts that don't have any sort of dynamic components.  Also good for client-side validatation functions referenced by CustomValidator objects.
For complex scripts it's nice to separate them into their own .js files and link them or add dynamically.
Answer: Drop a script manager on the master page and then:
<code>ScriptManager sm = (ScriptManager)master.ScriptManager1;
sm.Scripts.Add(new ScriptReference("~/Scripts/banners.js"));
</code>

ascx'es javascriptscript


Running logistic regression on a sales data

Question: In R I'm setting up a dataset to run a logistic regression on. I have two question regarding the selection of independent variables.
I will first briefly explain the dataset: The dataset contains of visits to a website. Some of these visits will eventually lead to a sale. Some will not. Each visit shows the time the user spend on the website and the number of pages they have viewed. If a user eventually buys the data entry also gets field called relevance and a field called recency (how long it takes until the order is made). Visits can come from multiple parties and several visits can lead to one sale (e.g. customer enters yesterday via an channel, and does not buy, next day customer enters via another channel and buys). I have the following questions:

the time spend on the website and the number of pages viewed are available for all visits (thus visits that turn into a visit that assisted to a sale (1) and visits that don't (0). Visits that do not turn into a sale have no relevance and thus would get a value appointed of 0. Recency however is only measured for visits that eventually lead to a sale, thus only when the dependent variable has a value of 1. How to incorporate this?
Furthermore there are also some general measures which are channel specific and thus not row specific. (for instance: the conversion rate of visits to visits that contribute to a sale). I suppose it is not right to put this variable in on a per row basis, since these variables are not row specific. How to incorporate these in the model?
Answer: As far as the problem with recency goes, there is no way around it given your current system of assigning values.  Recency is a simple function of purchase:  no purchase, no value assigned for recency.  Thus the variable is of no use in predicting purchase.  Relevance has a similar problem, being the other side of the coin.  One could make a single variable out of the recency and relevance values (if purchase, call this new variable 1; if no purchase, call it 0) and still this would contribute nothing to prediction of purchasing behavior.
In your last paragraph you ask about

the conversion rate of visits to visits that contribute to a sale.

This can be treated just like time spent or pages viewed--in other words, analyzed at the level of each individual.  If you include it in a logistic regression with multiple predictors, you might want to use each individual's a) number of visits  b) mean time spent per visit  c) mean number of pages viewed per visit. Or you might substitute median for mean.  Each of these can be included as main effects.  You may also want to interact number of visits with the other two.
Comment: Thank you for your reply. The first part regarding the recency and relevance is clear.
Regarding the last paragraph  I do not completely understand what you mean. The records in the datafile are like this (simplified):
[image](https://dl.dropbox.com/u/19154683/image.PNG)

Thus tos and pageviews here are row specific. For Assist rate: this would be 100% for channel 1 (both involved in sale) and 50% for channel 2, these are not row specific. How to incorporate them? Can I just add them on a per row basis? So every row with channel 1 gets Ratio=100 and every row with channel 2 gets Ratio=50?
Comment: I'm only partially understanding your problem, I fear, so I hope someone else chimes in.  But you may need to look into more ways of dealing with person-record data sets (1 row per person) and data sets with multiple rows per person.  You may end up wanting to convert the latter to the former, using as your predictors each person's average across rows on several variables, but assigning each person a single value when it comes to sale or no sale.  I.e., if any of that person's rows resulted in a sale, Sale = 1.
Comment: Yes that would make sense, but the goal of this research is to find connections on a visit base level. So in this case I can at least use tos and pageviews since these are unique for every 'row' (i.e. visit) in the datafile. My final question is: can more general variables (i.e. assist rate which is number of visits that turn into assist per channel / total number of assists per channel) which are thus not unique per row be taken into account on a per row basis, so as an extra variable to run the logistic regression with?
Comment: @Max In general, yes - but you need to make sure that that information isn't already contained in the regression.  E.g., if you add the channel to each visit, the regression model adjust its estimates to account for each channel's proportion of visits that result in purchases.  [I put together a little example](https://gist.github.com/3219819) to help clarify. Similarly, I don't think that adding a variable like "average tos of visits from this channel" would add any new information if tos and channel were already in the model.
Comment: But if you get into more complex efforts to model this, you ought to look into generalized multilevel models. That's a big step in complexity, but also in flexibility. You could nest visits within channels, or perhaps nest visits within users within channels. A good book for that is "Data Analysis Using Regression and Multilevel/Hierarchical Models" by Gelman and Hill - the first few pages of Chapter 11 lay out the point of multilevel models and when to use them pretty succinctly.
Comment: Thank you for your time. I will try to work with this. First efforts (with only tos and pageviews) did not give any significant answers.


Decide whether each triangle below lies in the Euclidean plane, on a sphere (of radius 1), or in the hyperbolic plane

Question: A triangle has sides of length $a$, $b$, $c$ (given correct to $2$dp) and a right angle opposite $c$. Decide whether each triangle below lies in the Euclidean plane, on a sphere (of radius $1$), or in the hyperbolic plane

$a=b=1.00, c=1.27$
$a=0.50, b=1.20, c=1.34$
$a=1.0,  b=2.40, c=2.60$
$a=b=3.00, c=0.20$

In each case, answer "Euclidean", "spherical" or "hyperbolic".
How to do this without calculator? I have an exam tomorrow please help.
Answer: The Pythagorean theorem says $a^2+b^2=c^2$ for the Euclidean case, the left hand side would be larger than the right one in spherical geomatry and smaller for the hyperbolic one. Thus you would have to calculate simply $\sqrt{a^2+b^2}$ and compare that to $c$.
That root would become $1.41$, $\ 1.3$, $\ 2.6$, $\ 4.23$ respectively.
You even could do all this without calculator. Because of $\sqrt{2}=1.41$ respectively $13^2=169$. The remainder is just a multiplication by $2$ respectively $3$.
--- rk
Comment: ah thanks that makes sense! :)
Answer: You may need a little bit of a calculator to square the numbers, but here is a rigorous proof that the proposition suggested in another answer works.  To wit, in the spherical case $c^2\color{blue}{<}a^2+b^2$ while for the hyperbolic one $c^2\color{blue}{>}a^2+b^2$.
Consider the spherical case.  The formula $\cos c=\cos a\cos b$ which we usually see applies only on a sphere whose radius matches the length unit for $a,b,c$.  What if the sphere might have some other radius?  If the triangle is spherical, we have to allow the possibility that $\cos(c/R)=\cos(a/R)\cos(b/R)$ for some other radius $R$ and we are not allowed to try to solve for $R$.  The hyperbolic case gives a similar problem with $\cosh(c/R)=\cosh(a/R)\cosh(b/R)$.  Even if a sphere is given to have unit radius (which I saw only later), we cannot use a calculator in this problem to check the cosine.
Pythagoras's Revenge: The Return of the Squares
Suppose we were to take the spherical law and use the double-angle formula to reintroduce the squared quantities from the familiar Pythagorean Theorem, to wit:
$[1-2\sin^2(c/2R)]=[1-2\sin^2(a/2R)][1-2\sin^2(b/2R)]$
and just multiply out the terms.  The constant terms cancel out and we can ditch a factor of $2$ from the rest, thus
$\sin^2(c/2R)=\sin^2(a/2R)+\sin^2(b/2R)-2\sin^2(a/2R)\sin^2(b/2R)$
Split the term in half and apply the identity $\sin^2u+\cos^2 u=1$ to obtain
$\sin^2(c/2R)=[\sin^2(a/2R)-\sin^2(a/2R)\sin^2(b/2R)]+[\sin^2(b/2R)-\sin^2(a/2R)\sin^2(b/2R)]$
$\color{blue}{\sin^2(c/2R)=[\sin^2(a/2R)\cos^2(b/2R)]+[\sin^2(b/2R)\cos^2(a/2R)]}$
This is the half-argument form of the spherical law, which involves a sum of squares similar to the Euclidean Pythagorean Theorem.
So we have, since the cosines lie between $0$ and $1$:
$\sin^2(c/2R)<\sin^2(a/2R)+\sin^2(b/2R)$
Now consider this picture in which, for unit radius, the sine function is concave down while the hyperbolic sine arising from the hyperbolic case is concave up (created by the author).

Thus with the concave down relation for the sine, the last inequality above implies:
$\color{blue}{c^2<a^2+b^2}.$ (spherical right triangles)
I will let the reader handle the hyperbolic case, which is analogous.  Watch your signs:  in the hyperbolic world we have $\cosh =1+2\sinh^2 u$.  Also watch your second derivative sign:  the plot above shows the hyperbolic relation is concave up.  You should find
$\color{blue}{c^2>a^2+b^2}.$ (hyperbolic right triangles)


How to scrape incapsula protected website?

Question: https://www.genecards.org/cgi-bin/carddisp.pl?gene=ZSCAN22
On the above webpage, if I click See all 33, I will see the following GET request is sent in Chrome DevTools.
https://www.genecards.org/gene/api/data/Enhancers?geneSymbol=ZSCAN22
Direct accessing of it is blocked.
I have try to use a puppeteer. I can click "See all 33" with puppeteer, but then I need to parse the resulted HTML file. It would be best to directly get the results from https://www.genecards.org/gene/api/data/Enhancers?geneSymbol=ZSCAN22. I am not sure how to get it after clicking "See all 33" with puppeteer.
I am not sure if apify can help.
Can anybody let me know how to scrape it?
Comment: In the headers of the request you can see `rvhk: xxxx`. Probably that is a token of some sort generated by a prior request. You might need to send that request, receive the token and update your headers.
Answer: I used selenium it working fine
from selenium import webdriver
browser = webdriver.Chrome(executable_path="C:/src/webdriver/chromedriver.exe")
genesLocations = 'https://www.genecards.org/cgi-bin/carddisp.pl?gene={}'

Extract Genomic Locations
gene='ZSCAN22'
browser.get(genesLocations.format(gene))
location = browser.find_element_by_xpath('//*[@id="genomic_location"]/div/div[3]/div/div')
print(location.text)


Javascript - Ler HTML atualizado ao executar função

Question: 1 - Possuo duas funções javascript:
var linhas = document.getElementById("tabela").getElementsByTagName("tr");
var linhaSelecionada = "";

function selecionarLinha(){
    for(var i = 0; i < linhas.length; i++){
        var linha = linhas[i];
        linha.addEventListener("click", function(){
            this.classList.toggle("selecionado");
        });
    }
    teste();
}

function teste(){
    var selecionados = document.getElementById("tabela").getElementsByClassName("selecionado");
    for(var i = 0; i < selecionados.length; i++){
        var selecionado = selecionados[i];
        selecionado = selecionado.getElementsByTagName("td");
        linhaSelecionada = selecionado[0].innerHTML;
    }
    console.log(linhaSelecionada);
}

2 - O que o código faz e qual é a minha dúvida:
Ao chamar a função selecionarLinha() através de um botão, eu defino a classe da linha selecionada na tabela com class="selecionado" até aqui está funcionando corretamente. Porém ao chamar a segunda função que deveria fazer a leitura do html e verificar quais linhas estão com class="selecionado" não é encontrado nenhuma linha com essa classe. Gostaria de saber como faço para que a segunda função consiga encontrar quais linhas a primeira função definiu com class="selecionado" sem que eu precise clicar em um botão para selecionar e clicar em outro botão para exibir o que foi selecionado, ou seja, através de um único clique selecionar e exibir a linha selecionada.
Answer: Boa noite amigo, tente fazer o seguinte:
function teste(){
    const selecionados = document.querySelectorAll('#tabela .selecionado')
    let linhaselecionada

    selecionados.forEach(selecionado => {
      const td = selecionado.querySelector('td')
      linhaselecionada = td.innerHTML
    })

    console.log(linhaSelecionada);
}

Caso ainda assim esteja dando erro, abra o console do navegador e copie e cole aqui o erro pra que eu tenha mais detalhes e possa te orientar melhor.
Espero ter ajudado!


Create FTP accounts with access to just some folders in the web directory

Question: I own a VPS server. At the moment I havent installed any FTP server on it, I am using SSH and SFTP only. I am using Debian 6 Squeeze and Apache2 service. The web directory is in /var/www/
Well, I wanted to create different FTP accounts and give access to some people to them (one account per user). In my web directory I have an structure like this:
/var/www/mtaplugins/music/mplayer/music/
/var/www/mapuploader/
and more folders inside. I want to create an FTP account which should be able to just access one of those folders and the folders inside them.
I would appreciate some recomendations or stept to follow before installing anything or doing anythong, because I dont have any idea about this.
I was thinking in using ProFTPd but as I saw in the documentation it would just create an account for each user in my server, and I want to not create more users (I always use root)
Thanks in advance
Comment: What you are looking for are called "Virtual Users".  You'll need to find an FTP server that supports them if ProFTPd doesn't (I'm sure it does, though)
Answer: In this situation, you may install vsftpd and make settings that allow access via ftp for system users to his home directory that will be /var/www/mapuploader/USER1, /var/www/mapuploader/USER2, /var/www/mapuploader/USERN.
So. For Example:
useradd -d /var/www/mapuploader/userN -m -s /bin/bash userN

After this step you'll have a user acoount with the home dir as /var/www/mapuploader/user1, but you need to set the password for this user:
passwd userN

Ans type and re-type the new password, that you should use later to login via ftp. Now install vsftpd
apt-get install vsftpd

And add some changes to the default config file
nano /etc/vsftpd.conf

There you need to set some values for several variables:

anonymous_enable=NO
local_enable=YES
write_enable=YES
local_umask=022
chroot_local_user=YES

And the other variables do not touch. Save changes.
Now you need to restart vsftd to re-read the config file:
/etc/init.d/vsftpd restart

Now your system users can access your home directory via ftp.


Sequelize.js insert a model with one-to-many relationship

Question: I have two sequelize models with one-to-many relationship. Let's call them Owner and Property.
Assume they are defined using the sails-hook-sequelize as such (simplified).
//Owner.js
module.exports = {
options: {
  tableName: 'owner'
},
attributes: {
  id: {
    type: Sequelize.BIGINT,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING(255)
  },
  associations: function () {
     Owner.hasMany(Property, {
     foreignKey: {
       name: 'owner_id'
     }
   });
 }
}

//Property.js
module.exports = {
options: {
  tableName: 'property'
},
attributes: {
  id: {
    type: Sequelize.BIGINT,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: {
    type: Sequelize.STRING(255)
  }
}

Now assume I want to insert an Owner record in my database and insert a few property records to associate with the owner. How do I do this?
I'm looking for something like
Owner.create({name:'nice owner',
              property: [{name:'nice property'},
                         {name:'ugly property'}]});

Surprisingly I can't find this in the Sequelize documentation.
Answer: You can't associate property existing records when you create the owner, you have to do that right after, with promise chain.
Owner.create({name:'nice owner'}).then(function(owner){
    owner.setProperties([{name:'nice property'}, {name:'ugly property'}]).then(/*...*/);
});

To avoid any problems with those associations (owner created but some associations failed), it's better to use transactions.
sequelize.transaction(function(t) {
    return Owner.create({name:'nice owner'}, {transaction: t}).then(function(owner){
        return owner.setProperties([{name:'nice property'}, {name:'ugly property'}], {transaction : t});
    });
});

However, if you want to create new Owner associated to new Properties you can do something like
Owner.create({
   name: 'nice owner',
   property: [
      { name: 'nice property'},
      { name: 'ugly property'}
   ]
},{
   include: [ Property]
});

See http://docs.sequelizejs.com/en/latest/docs/associations/#creating-with-associations
Comment: I would recommend to also use a transaction for your third `create` example because otherwise if the INSERT of the properties fails you are stuck with the half-finished owner.
Comment: I struggled some hours because the syntax was slighty different in the latest release, for anyone that can't make this work I recommend you to check out the integration tests to see how to use the create method in the most recent version https://github.com/sequelize/sequelize/blob/master/test/integration/model/create/include.test.js


Is there a topological definition of an interpretation from one structure to another in the sense of model theory?

Question: Is there a topological definition of an interpretation in the sense of model theory?
Wikipedia has a definition of an interpretation, reproduced below for convenience.
This definition seems really close to just the definition of continuity where the closed sets are precisely the definable sets.

An interpretation of $M$ in $N$ with parameters (or without parameters, respectively) is a pair $(n,f)$ where $n$ is a natural number and $f$ is a surjective map from a subset of $N^n$ onto $M$ such that the $f$-preimage (more precisely the $f^{k}$-preimage) of every set $X \subset M^k$ definable in $M$ by a first-order formula without parameters is definable (in $N$) by a first-order formula with parameters (or without parameters, respectively). Since the value of n for an interpretation $(n,f)$ is often clear from context, the map $f$ itself is also called an interpretation.

For any given structure $M$ and a fixed arity $n$, however, we can define a topology $\tau^{(M, n)}$ as the topology generated by taking the definable-with-parameters sets as primitive closed sets. Let $M_n$ refer to $(M^n, \tau^{(M, n)})$.
The continuous maps $f : N_k \to M_n$ are precisely those that reflect definability, which lines up with the definition given by Wikipedia.
However, I'm not sure how to capture the surjectivity constraint and whether it has a topological characterization.
I'm also not sure whether this re-characterization using basic topological language is missing anything big that would make this re-characterization awkward or unworkable.
Comment: "The continuous maps ... are precisely those that reflect definability, which lines up with the definition given by Wikipedia." That's wrong: if you allow parameters in your definition, the topology you get is discrete since every co-singleton is definable with parameters.
Comment: The issue is that you're mixing up "open" and "basic open" - the continuous image of a basic open set is a *union* of basic opens, not necessarily a basic open, and so you can't conclude "preimage of definable is definable" as you want to.
Comment: @ZhenLin Oh, of course, you are right. I was thinking of the syntactic categories, where this issue does arise. The embarrassing thing is that I actually made your comment precise (in the form of a functor) in a recent paper, see section 8 [here](https://doi.org/10.1007/s00153-022-00825-7). For the OP: this paper also provides a topological definition of interpretation, but not in the sense you are asking about, because it is expressed in terms of the type spaces.
Comment: In some sense this is what a geometric morphism between classifying toposes is: an interpretation of one theory in another.
Comment: @ZhenLin An important difference though is that then equality must be interpreted as equality, while an interpretation allows it to be interpreted as a definable equivalence relation.
Comment: @MarkKamsma In the classifying topos of a theory, we have quotients of definable equivalence relations, so I don't think it is a significant difference.
Answer: Turning my comments into an answer:
This question makes an incorrect assumption early on:

The continuous maps [...] are precisely those that reflect definability, which lines up with the definition given by Wikipedia.

This is in fact false. Since every co-singleton is definable with parameters (trivially), the topology you suggest is discrete regardless of the structure in question, so all maps are continuous. Even if we disallow (or otherwise keep track of) parameters the problem persists: in a structure in which every element is definable (such as $\mathbb{N}$), every self-map would be continuous in the relevant sense but most would not be self-interpretations.
The core issue is that you are conflating basic open sets and general open sets: all we get is "the preimage of a definable set is a union of definable sets," which is far from what is required. Continuity is simply too flexible a condition compared to "definability-reflection."


Hide record from continuous form if checkbox is marked in query

Question: I have a continuous Form with records, the records contain a yes/no. So if the checkbox in the form is marked I want the record to be hidden from the form next time you open it, but it does not seem to work.
Private Sub Form_AfterUpdate()
If Me.Checkbox = False Then
Me.Checkbox.Visble = True
Else
Me.Checkbox.Visible = False
End If
End Sub

Answer: Add a Boolean field named Hidden having a DefaultValue of False in the table and, in the form, bind this field to the checkbox.
Then, when opening the form, filter on [Hidden] = False.
Comment: Thanks I will try that but I've also tried: Query for the check box, criteria: "True" or -1 but then messes up because there's many records also in other forms. Edit: Creating a new query fixed it.


A finite graph G is $d$-regular if, and only if, its adjacency matrix has the eigenvalue $λ = d$

Question: Show that a graph $G$ finite with $n$ vertices is $d$-regular if, and only if, the vector with all the coordinates equals to 1 is  eigenvetor from eigenvalue $λ = d$  from the  adjacency matrix
 $A$ from the graph $G$.
The question itself was a little confused for me...
Answer: Suppose that $G$ is $d$-regular. Then every vertex of $G$ is adjacent to $d$ other vertices, so each row of its adjacency matrix $A$ will have $d$ $1$'s and $n-d$ $0$'s. Let
$$A=\pmatrix{a_{11}&a_{12}&\dots&a_{1n}\\
a_{21}&a_{22}&\dots&a_{2n}\\
\vdots&\vdots&\ddots&\vdots\\
a_{n1}&a_{n2}&\dots&a_{nn}}\;,$$
and $\vec v$ be the $n\times 1$ vector whose entries are all $1$:
$$\vec v=\pmatrix{1\\1\\\vdots\\1}\;.$$
The product $\vec u=A\vec v$ is an $n\times 1$ vector whose $i$-th entry is $$u_i=\sum_{j=1}^na_{ij}\cdot1=a_{i1}+a_{i2}+\ldots+a_{in}\;.$$ Since $d$ of the numbers $a_{i1},\dots,a_{in}$ are $1$ and the rest are $0$, $u_i=d$ for every $i$. Thus, $$\vec u=\pmatrix{d\\d\\\vdots\\d}=d\vec v\;.$$ That is, $A\vec v=d\vec v$, so by definition $\vec v$ is an eigenvector of $A$ for the eigenvalue $d$.
To show the other direction, you can try to reverse this argument; that works. Alternatively, you can assume that $G$ is not $d$-regular and show that $\vec v$ is not an eigenvector for an eigenvalue $d$; that also works and may be even easier.
Comment: Would the downvoter care to explain what is wrong with the answer?
Comment: They don't know a damn thing to explain.
Answer: Funny thing, I just learned this myself this week. It is proposition 3 on page 2 of these excellent lecture notes by Padraic Bartlett. The entire set of lecture notes on spectral graph theory is here.
(I promised in 2012 to write up the proof here, but I hereby retract that promise. I would not be able to improve upon Brian Scott's writeup elsewhere in this thread.)
Comment: @ Mark Dominus I took Ten!!!!
Comment: Today was my test...this question was in it....
Comment: @MarylinM.J I hope you passed!
Comment: @HipsterMathematician Congratulations!


overloaded methods

Question: function Activity() {

this.LoadFile = function (path, targetElement) {

    $.ajax({
        url: path,
        dataType: 'html',
        success: function (data) {
            targetElement.html(data);
        }

    });
};

this.LoadFile = function (path, targetElement, onSuccess) {

    $.ajax({
        url: path,
        dataType: 'html',
        success: function (data) {
            targetElement.html(data);
            onSuccess(data);
        }

    });
};

}
If i try to pass 2 arguments, i get onSuccess is not a function so i suppose this isnt working. Is it possible to use overloads in javascipt?
Answer: There's no way of directly specifying overloaded methods as such in JS.
There are many workarounds.
In your case, you can define the function with 3 parameters:
function (path, targetElement, onSuccess)

and if the function is called with only 2 parameters, onSuccess will be undefined:
function (data) {
  targetElement.html(data);
  if (onSuccess) {
    onSuccess(data);
  }
}

You may want to look at jQuery.Callbacks for handling event callbacks, although your function could be rewritten using .load.

For programmers coming from the Java/C# world of overloading learn the JavaScript way you can use a structure like this (not recommended, it's simply an example for familiarity):
function foo() {
  var fns = {};
  fns[0] = function () {
    //no params
  };
  fns[1] = function () {
    //1 param
  };
  fns[2] = function () {
    //2 params
  };
  fns[arguments.length]();
}

to provide separate functions for each "overload", however it's not very flexible and symptomatic of a poorly planned function.

Oftentimes rather than using a large set of parameters, a single options parameter will be used to contain the available parameters:
function foo(options) {
  var settings = $.extend({}, foo.defaultSettings, options);
  //do stuff with settings
}
foo.defaultSettings = {
  bar: 'baz',
  fizz: 'buzz'
}

Comment: That recommended structure is simply stupid. Tell them to stop doing it wrong and learn javascript
Comment: Maybe its better to pass one argument as an object, containing different number of arguments...
Comment: @Raynos, i never recommended that structure. I was trying to make a point about it. It's ridiculous hence the "symptomatic of a poorly planned function". I guess i wasn't clear enough, so I'll edit it.
Answer: No.
Javascript does not support method overloading.
Instead, you can make a single method that takes all three parameters, then check inside the method whether the third parameter was actually passed.  (all Javascript function parameters are optional)
Comment: @Johan: Yes; treat the parameter as optional.
Answer: There is still another way to go. Don't give any parameters in the function definition and then examine the arguments array(). You can even examine the types of the parameters given, to branch inside your function. The example below will alert # 1 # and Num(2)
/**
 * Usage
 * example(number param1)
 * example(string, number)
 */
function example() { // no parameters
    if (arguments.length == 1 && typeof arguments[0] == 'number') {
        alert(' # ' + arguments[0] + ' # ')
    }
    if (arguments.length == 2 && typeof arguments[0] == 'string' && typeof arguments[1] == 'number') {
        alert(arguments[0] + '(' + arguments[1] + ')')
    }

}
example(1);
example('Num', 2)

overloaded methods


Find a polynomial that has two algebraic numbers as a root

Question: If you have two algebraic numbers $\alpha$ and $\beta$ with two polynomials $u(x)$ and $v(x)$ such that $u(\alpha)=0$ and $v(\beta)=0$ you can, for example, find out a polynomial $q(x)$ that has $\alpha+\beta$ as a root using the multivariate resultant:
$q(x) = res_y(u(x-y),v(y))$
then:
$q(\alpha+\beta) = 0$
Now my question is:
If $\alpha$ is the kth root of $u(x)$ and $\beta$ is the nth root of $v(x)$, is there a way to find out which root of $q(x)$ is $\alpha+\beta$ ?
Comment: In what sense is $\alpha$ the $k$th root? Do your polynomials have only real roots?
Comment: No, they could be also complex. By the kth root I mean this: $x^2-2$ has $\sqrt{2}$ and $-\sqrt{2}$ as a root. We could order them by their positions in the complex plane: {$\sqrt{2},-\sqrt{2}$} . Using this ordering, $\sqrt{2}$ is the 1st root and $-\sqrt{2}$ is the 2nd.
Comment: I don't understand the way you order your roots, can you give a clear definition?
Comment: Given 2 complex numbers $a$ and $b$: $a > b$ if $\arg(a) > \arg(b)$. And if $\arg(a) = \arg(b)$, then $a > b$ if $|a| > |b|$. We order the roots by this ordering: {$a_1,a_2,...$} and $a_i < a_j$ if $i < j$
Comment: Sorry, I meant $a_i>a_j$ if $i<j$
Comment: @Hans, I believe OP just means any pair of roots
Answer: I am not aware of any direct way to calculate the "index" of $\alpha+\beta$ as a root of $q$. However, you can isolate the roots of $u$, $v$ and $q$, to get disjoint intervals $(a^-_i,a^+_i)$ with rational endpoints s.t. $\alpha \in (a^-_k,a^+_k) =: I_\alpha$ and similarly for $\beta$ and $\alpha+\beta$.
Then refine the intervals $I_\alpha$ and $I_\beta$ around $\alpha$ and $\beta$ and the "candidate intervals" containing the roots of $q$ until $I_\alpha + I_\beta$ overlaps with exactly one of the "candidate intervals" of $q$. This is an isolating interval of $\alpha+\beta$, and it allows you to compute its "index" among all roots of $q$.
Depending on the method you use (e.g., for most algorithms based on Descartes' rule of signs), you have to make the polynomials $u$, $v$ and $q$ square-free first. Also, if you do a square-free factorization of $q$, the isolating interval for $\alpha+\beta$ as computed above will contain a root of exactly one of the factors, which can easily be found by computing the sign of the factors at the endpoints of the interval. This factor will be the minimal polynomial of $\alpha+\beta$.
By the way, I was assuming that you deal with real roots (since you have that order on the roots). But the same procedure will also work for complex roots; just replace the concept of an isolating interval on the real line by isolating discs in the complex plane.
[edit]
Sorry, I did not recognize that the case of complex roots was specifically asked for.
With respect to your specific ordering, the problem is that it is not trivial to compare the argument of algebraic numbers (in particular because the argument is not algebraic itself).
I think the problem would be somewhat easier if the magnitude were the dominant key in the comparison.
Nevertheless, both imaginary and real part of an algebraic number are again algebraic, so you can decide whether the argument is zero, and you can represent the magnitude.
To compare two algebraic numbers $0 \ne \alpha \ne \beta \ne 0$ (those conditions can be checked "easily") according to your definition, first check whether their imaginary part has different sign.
If so, they lie in different halfplanes, and sufficient refinement will show which one has the smaller argument.
Similarly, if both imaginary parts are zero, both $\alpha$ and $\beta$ are real, and it the comparison can be done by refining against zero.
Otherwise, compute $\gamma = \alpha / \beta$, which again yields an algebraic value, and compute its imaginary part.
If it is zero, then $\arg\gamma = \arg\alpha - \arg\beta = 0$, hence their argument is the same.
(Note that the case $\arg\gamma = \arg\alpha' - \arg\beta' = \pi/2$ cannot occur, since it implies that exactly one of $\alpha$ or $\beta$ is a positive real and the other negative real, and this case has been dealt with already.)
However, if the imaginary part is not zero, you know the argument of $\alpha$ and $\beta$ differs, and again sufficient refinement of both numbers will allow a comparison.
Note that it is not sufficient to blindly start refining in the hope that you will be able to distinguish the argument - you need to know in advance that the procedure will terminate, and that's why the "boilerplate" checks need to be there. Also note that the computations involved in this approach will be very inefficient; essentially, you will need to compute the minimal polynomial (or at least a representing polynomial) for all algebraic values occuring throughout the computation.
Comment: OP made it clear in the comments that we are not just dealing with real roots.
Comment: Oh, you are right - sorry, I must have been asleep when reading through that part. But as mentioned, the same approach works just as well for complex roots w.r.t. finding the correct root of $q$ that is $\alpha+\beta$.
W.r.t. that specific ordering: I edited my answer to take that into account.


epoch time conversion

Question: how can I convert this epoch time to human readable date time
1331515367

I used the following code but this gives me the current time in my zone
$time = 1331515367
echo date('Y-m-d H:i:s', $time);

thannks
Comment: What timezone do you want it in?
Comment: Maybe because the timestamp 1331515367 *is* the current time, or at least used to be at the time of writing?
Answer: Dates generated on your server are going to be in whatever time zone your server says to use.  If you want to change it use: http://php.net/manual/en/datetime.configuration.php
date.timezone ="timezone";

For a list of time zones: http://php.net/manual/en/timezones.php
All of this was found using this google search: php date timezone
https://www.google.com/search?sourceid=chrome&ie=UTF-8&q=php+date+timezone

epoch time conversion


Buscar valor input de outro arquivo php

Question: Estou fazendo um upload de imagens para uma pasta do servidor, usando o seguinte código:

            * Foto 01

                   <input id="fotofundo" name="fotofundo" type="text" placeholder="" class="form-control input-md" onClick="txfoto()" />

No arquivo que realiza o envio, eis o meu input:
<input id="foto" name="foto" type="text" class="form-control input-md" value="***************">

A foto vai para a pasta do servidor, imprime no input acima, mas não consigo puxar ele para meu outro formulário, quando tento ativar o evento "onClick" no input.
O que pode estar errado?
Comment: Você conseguirá melhores respostas se der às pessoas código que elas possam usar para reproduzir o problema.
Comment: Posto aqui ou no pastebin?
Comment: Tanto faz, onde vc achar melhor.
Answer: Há dois problemas no código:
Um é aqui:
window.parent.frmfoto.document.getElementById('foto').value;

Para pegar o valor de um elemento no documento-pai, deveria usar window.parent.document:
window.parent.document.getElementById('foto').value;

O outro é aqui:
$('#foto').val(valor);

Neste a id #foto é inexistente. O correto seria pegar a id #fotofundo usando JavaScript puro (isso evita que você carregue o jQuery no frame apenas para fazer isso):
document.getElementById('fotofundo').value = valor;

Comment: Obrigado pela ajuda. Não tinha visto sua postagem, acabei usando a solução abaixo.
Answer: O window.parent não é necessário, pois window.parent vai buscar na página acima, como o script esta sendo executado já na pagina acima então ele é irrelevante, basta pegar o .
Para não conflitar com variáveis globais (no escopo de window.) seria mais interessante usar o próprio jQuery, no seletor do jQuery vocÊ pode mudar o contexto, usando .contentWindow, desta maneira:
 $("<seletor>", <janela>.contentWindow.document);

Nota: <seletor> e <janela> são exemplos e não código

Outro problema é que você na página acima esta usando fotofundo e não foto, então troque isto:
$('#foto').val(valor);

Por isto:
$('#fotofundo').val(valor);

O código todo deve ficar assim:

    * Foto 01

           <input id="fotofundo" name="fotofundo" type="text" placeholder="" class="form-control input-md" onClick="txfoto()" />

Comment: Ficou certinho, obrigado. Só mais uma coisa: Existe algum meio de eu conseguir atualizar o input sem o click? Sabe como é usuário...
Comment: @HebertRichardMassenoDias tente usar `.load` no ``
Comment: meu conhecimento é muito pouco em javascript. Poderia me dar uma exemplo ou como devo pesquisar?
Comment: @HebertRichardMassenoDias coloca assim na sua página `$(function () {  $("iframe[name=frmfoto]").on("load", txfoto) });`, não testei ainda, mas creio que deva funcionar. Qualquer coisa cria uma nova pergunta só sobre isto, se não funcionar, que eu irei tentar responder.
Comment: Não funcionou, vou criar outra pergunta. Obrigado!
Comment: https://pt.stackoverflow.com/questions/278930/atualizar-input-com-dados-vindo-de-um-iframe-automaticamente

Buscar valor input de outro arquivo php


Drawing AWT BufferedImage on SWT Canvas

Question: I am trying to write a SWT component, that is able to take and draw an instance of java.awt.BufferedImage. My problem is that SWT's Image and AWT's BufferedImage are incompatible: SWT components can't draw java.awt.Image, AWT/Swing components can't draw org.eclipse.swt.graphics.Image.
There are several approaches that try to solve this problem in other ways (which also may have some variations, but basically there are these two):

Convert between SWT Image and AWT BufferedImage
Swing/SWT Integration

They all have shortcomings and didn't satisfy my expectations:

The first approach, to convert an SWT Image  to a BufferedImage, results in poor performance for large images due to the creation of a new RGB instance for every Pixel.
The second approach has several shortcomings in usability. See the "workarounds" at the end of the linked article.

This lead to the conclusion that I'd try my best to write a component (based on org.eclipse.swt.widgets.Canvas or org.eclipse.swt.widgets.Composite) which allows to draw a BufferedImage directly without any conversion of images.
My approach was to draw it pixel by pixel. Therefore I simply had to get an instance of GC, walk the source BufferedImage line by line, left-to-right and drawing the corresponding Color using GC.setForeground(Color color) and GC.drawPoint(int x, int y).
First, I created a new instance of Color for every pixel, which uses quite a lot of memory and adds an additional delay, since new Color acquires system resources and creating a new object for every pixel also takes its time.
Then I tried to pre-load all possible (24 bit) Colors into an array before drawing the image. This lead to an explosion of memory usage (>= 600 MB), which was clear before I was trying it, but I had to verify it.
Caching only the used Colors also lead to more memory consumption than would have been required.
I think there has to be a more low-level approach that doesn't require that much memory, since SWT is able to draw whole (SWT) Images without consuming that much memory.
I would appreciate any ideas or solutions.
Comment: The method described in your first reference using RGB looks like it would be a lot faster - have you actually tried it?
Comment: I imagine that there is such an approach.  However, both AWT and SWT rely on native code to implement the low level graphics.  Therefore your low-level bridging would most likely involve some gnarly native code that operates on the native data structures used in the AWT and SWT cases.  And that would code would need to be implemented across multiple hardware and OS platforms.  Not pretty.
Comment: @greg-449 Yes, but I wasn't satisfied with the `new RGB` calls for every pixel. It really is a lot faster than my own approach.
Comment: @StephenC Probably yes. But maybe somebody knows a better approach.
Answer: I found out there's a way to "convert" an BufferedImage to an Image by using the original image's data buffer if it is 24 bit RGB. This is possible, since the image formats are compatible.
final BufferedImage original = ImageIO.read(new File("some-image.jpg");

final PaletteData palette =
        new PaletteData(0x0000FF, 0x00FF00, 0xFF0000);

// the last argument contains the byte[] with the image data
final ImageData data = new ImageData(original.getWidth(), original.getHeight(),
        24, palette, 4,
        ((DataBufferByte) original.getData().getDataBuffer()).getData());

final Image converted = new Image(getDevice(), data);

This way, one doesn't have to create thousands of new objects. This approach comes with the disadvantage that one needs to ensure that the original image is of type RGB 24 bit. Otherwise the image has to be converted to this format.
After that, an image can be drawn with the following code:
// get the GC of your component
gc.drawImage(image, 0, 0);

Probably other bit depths can be converted in a similar way, but this is all I need for the moment.
Comment: Just curious, but why don't you simply load the image with SWT directly? Is there a reason to use the detour with Swing/AWT?
Comment: I get the image from another library I use and wanted to work around the hassle to save it do a temporary file and re-load it with SWT. That would take additional unnecessary seconds.
Comment: I adapted your code in this way to work with monochrome images:
    RGB[] colors = new RGB[]{new RGB(0,0,0), new RGB(255,255,255)};
  PaletteData palette = new PaletteData(colors);
  ImageData data = new ImageData(original.getWidth(), original.getHeight(),
          1, palette, 4, ((DataBufferByte) original.getData(
            ).getDataBuffer()).getData());

Drawing AWT BufferedImage on SWT Canvas


Valor não está sendo gravado no banco

Question: Tenho as seguintes entidades:
package br.com.pokemax.modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "habilidade", uniqueConstraints = @UniqueConstraint(columnNames = { "nome" }))
public class Habilidade {

    @Getter
    @Setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(length = 150, nullable = false)
    private String descricao;

    @Getter
    @Setter
    @NotBlank
    @Size(max = 150, message = "Máximo de 150 caracteres permitidos.")
    @Column(name = "texto_in_game", length = 150, nullable = false)
    private String textoInGame;

    @Getter
    @Setter
    @Column(length = 150, name = "efeito_secundario", nullable = true)
    private String efeitoSecundario;

    @Getter
    @Setter
    @ManyToOne
    private Geracao geracao;

    public Habilidade() {

    }

}

package br.com.pokemax.modelo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotBlank;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = "geracao")
public class Geracao {

    @Getter
    @Setter
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Getter
    @Setter
    @NotBlank(message = "Nome não pode estar em branco.")
    @Pattern(regexp = "[A-z]*", message = "Atenção, digite somente letras")
    @Size(max = 20, message = "Máximo de 20 caracteres permitidos.")
    @Column(length = 20, nullable = false)
    private String nome;

    @Getter
    @Setter
    @Min(1)
    @Max(7)
    private Integer numero;

    @Getter
    @Setter
    @Column(name = "total_pokemons", nullable = false)
    private Integer totalPokemons;

    public Geracao() {

    }

}

O seguinte Controller:
package br.com.pokemax.controle;

import java.io.Serializable;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.inject.Inject;

import br.com.pokemax.modelo.Geracao;
import br.com.pokemax.modelo.Habilidade;
import br.com.pokemax.negocio.GeracaoDAO;
import br.com.pokemax.negocio.HabilidadeDAO;
import br.com.pokemax.util.MensagensUtil;
import br.com.pokemax.util.ValidadorUtil;
import lombok.Getter;
import lombok.Setter;

@ViewScoped
@ManagedBean(name = "habilidademb")
public class ControleHabilidade implements Serializable {

    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private Habilidade habilidade;

    @Inject
    private HabilidadeDAO dao;

    @Getter
    @Setter
    private Boolean efeitoSecundario;

    @Getter
    @Setter
    private List<Habilidade> lista;

    @Inject
    GeracaoDAO gDao;

    @Getter
    @Setter
    private Geracao geracao;

    @Getter
    @Setter
    private List<Geracao> geracoes;

    @PostConstruct
    public void inicio() {

    }

    public void novo() {
        habilidade = new Habilidade();
    }

    public void gravar() {
        try {
            if (habilidade.getId() == null) {
                dao.insert(habilidade);
                MensagensUtil.msg("Info", "cadastro.sucesso", new Object[] { MensagensUtil.get("habilidade") });
                habilidade = new Habilidade();
            } else {
                dao.update(habilidade);
                MensagensUtil.msg("Info", "alterado.sucesso", new Object[] { MensagensUtil.get("habilidade") });
            }

        } catch (Exception e) {
            e.getMessage();
            return;
        }

    }

    public void pesquisar() {
        try {
            lista = dao.findAll();
            for (Habilidade habilidade : lista) {
                habilidade.setDescricao(ValidadorUtil.checkTipoPokemon(habilidade.getDescricao()));
                habilidade.setTextoInGame(ValidadorUtil.checkTipoPokemon(habilidade.getTextoInGame()));
                habilidade.setDescricao(ValidadorUtil.checkAtributoPokemon(habilidade.getDescricao()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void excluir(Habilidade h) {
        try {
            dao.delete(h);
            MensagensUtil.msg("Info", "removido.sucesso", new Object[] { MensagensUtil.get("habilidade") });
            pesquisar();
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public void editar(Long id) {
        try {
            setHabilidade(dao.find(id));
        } catch (Exception e) {
            e.getMessage();
        }

    }

    public void cancelar() {
        habilidade = null;

    }

    public List<Geracao> listarGeracoes() throws Exception {

        this.geracoes = gDao.findAll();
        return this.geracoes;
    }

}

Estou implementando um autoComplete que está assim:

E meu Converter:
package br.com.pokemax.modelo.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import br.com.pokemax.modelo.Geracao;
import br.com.pokemax.negocio.GeracaoDAO;

@FacesConverter(value = "geracaoConverter", forClass = Geracao.class)
public class GeracaoConverter implements Converter {

    GeracaoDAO dao = new GeracaoDAO();

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) {
        try {
            Geracao d = dao.find(Long.parseLong(value));
            return d;
        } catch (Exception e) {
            e.getMessage();
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object object) {
        if (object != null) {
            return String.valueOf(((Geracao) object).getId());
        } else {
            return null;
        }
    }

}

Quando clico no autocomplete, ele mostra as Gerações, porém quando eu seleciono e mando gravar, ele não grava a geracao_id no banco. Debugando eu percebi que o objeto geracao está indo null, alguém sabe como posso resolver ?
Estou com o erro:

18:27:50,276 ERROR [stderr] (default task-6)
  java.lang.NullPointerException 18:27:50,277 ERROR [stderr] (default
  task-6)   at
  br.com.pokemax.modelo.converter.GeracaoConverter.getAsObject(GeracaoConverter.java:28)
  18:27:50,277 ERROR [stderr] (default task-6)  at
  org.primefaces.component.autocomplete.AutoCompleteRenderer.getConvertedValue(AutoCompleteRenderer.java:670)
  18:27:50,278 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
  18:27:50,278 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIInput.validate(UIInput.java:975) 18:27:50,278
  ERROR [stderr] (default task-6)   at
  javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
  18:27:50,278 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIInput.processValidators(UIInput.java:712)
  18:27:50,278 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
  18:27:50,278 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
  18:27:50,279 ERROR [stderr] (default task-6)  at
  org.primefaces.component.panel.Panel.processValidators(Panel.java:299)
  18:27:50,279 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIForm.processValidators(UIForm.java:253)
  18:27:50,279 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
  18:27:50,279 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
  18:27:50,279 ERROR [stderr] (default task-6)  at
  javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
  18:27:50,280 ERROR [stderr] (default task-6)  at
  com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
  18:27:50,280 ERROR [stderr] (default task-6)  at
  com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) 18:27:50,281
  ERROR [stderr] (default task-6)   at
  com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
  18:27:50,282 ERROR [stderr] (default task-6)  at
  javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
  18:27:50,282 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85)
  18:27:50,284 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
  18:27:50,285 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
  18:27:50,285 ERROR [stderr] (default task-6)  at
  org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
  18:27:50,285 ERROR [stderr] (default task-6)  at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
  18:27:50,286 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
  18:27:50,287 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,288 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,289 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
  18:27:50,289 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
  18:27:50,289 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
  18:27:50,289 ERROR [stderr] (default task-6)  at
  io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
  18:27:50,289 ERROR [stderr] (default task-6)  at
  io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
  18:27:50,290 ERROR [stderr] (default task-6)  at
  io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
  18:27:50,290 ERROR [stderr] (default task-6)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  18:27:50,290 ERROR [stderr] (default task-6)  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  18:27:50,290 ERROR [stderr] (default task-6)  at
  java.lang.Thread.run(Thread.java:745)
Answer: Vou deixar também uma implementação de um conversor genérico muito bom. Nós usamos um semelhante na empresa. A vantagem é que não é necessário buscar em um BD, o objeto fica gravado no próprio componente.
public class SimpleEntityConverter implements Converter {

public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
    if (value != null) {
        return this.getAttributesFrom(component).get(value);
    }
    return null;
}

public String getAsString(FacesContext ctx, UIComponent component, Object value) {

    if (value != null
            && !"".equals(value)) {

        BaseEntity entity = (BaseEntity) value;

        // adiciona item como atributo do componente
        this.addAttribute(component, entity);

        Long codigo = entity.getId();
        if (codigo != null) {
            return String.valueOf(codigo);
        }
    }

    return (String) value;
}

protected void addAttribute(UIComponent component, BaseEntity o) {
    String key = o.getId().toString(); // codigo da empresa como chave neste caso
    this.getAttributesFrom(component).put(key, o);
}

protected Map<String, Object> getAttributesFrom(UIComponent component) {
    return component.getAttributes();
}

}

Fonte: http://www.rponte.com.br/2008/07/26/entity-converters-pra-da-e-vender/
Answer: Pesquisando, descobri que pro Inject funcionar no converter é preciso usar o @Named ao invés do @FacesConverter, meu converter ficou assim:
@Named(value = "geracaoConverter")

Fonte: https://stackoverflow.com/questions/7531449/cdi-injection-into-a-facesconverter
Answer: Não faltou o @Inject do GeracaoDAO no Converter? Tente debugar o converter para ver se os retornos estão corretos.
Comment: Eu estava trabalhando na hora do almoço, acredita que depois que voltei ao trabalho fiquei pensando nisso ? Ou seja, estava convicto, em casa vou testar e te falo, obrigado.
Comment: Muito estranho, o dao ainda continua null. :(
Comment: Ele não está passando desta linha: `Geracao d = dao.find(Long.parseLong(value));`
Comment: Vc não gostaria de tentar um conversor genérico? Tem um conversor muito bom que serve para a maioria dos casos (SimpleEntityConverter) http://www.rponte.com.br/2008/07/26/entity-converters-pra-da-e-vender/
Comment: Editei a pergunta com o meu erro
Comment: Agora passou no converter, porém o atributo geracao está indo como null.
Comment: Vc disse que o dao está null ou o resultado dele?
Comment: Ele está null quando chego no método getAsObject.
Comment: Talvez ele não possa ser injetado no converter. Não tenho certeza. Aconselho fazer um teste com esse SimpleEntityConverter, ele grava os dados no próprio componente. No caso da sua classe, acho que funciona sem problemas pois ela tem o getId().
Comment: Consegui, vou postar a resposta.
Comment: Muito bom, obrigado pelo retorno.

Valor não está sendo gravado no banco


Projeto MVC DDD

Question: Eu estou criando uma aplicação, utilizando o padrão DDD, então, na minha camada de Apresentação, eu crio as viewModel, e na controller eu uso o Mapper.Map<Entidade, EntidadeViewModel> . eu gostaria de saber o seguinte. no meu dominio, eu uso alguns Enuns, eu preciso criar as ViewModel desses Enuns? na verdade, eu ja criei, mas não deu muito certo.
Segue o Cód Enum:
public enum EstadoViewModel
    {
        [Description("Rondônia")]
        RO = 11,
        [Description("Acre")]
        AC = 12,
        [Description("Amazonas")]
        AM = 13,
        [Description("Roraima")]
        RR = 14,
        [Description("Pará")]
        PA = 15,
        [Description("Amapá")]
        AP = 16,
        [Description("Tocantins")]
        TO = 17,
        [Description("Maranhão")]
        MA = 21,
        [Description("Piauí")]
        PI = 22,
        [Description("Ceará")]
        CE = 23,
        [Description("Rio Grande do Norte")]
        RN = 24,
        [Description("Paraíba")]
        PB = 25,
        [Description("Pernambuco")]
        PE = 26,
        [Description("Alagoas")]
        AL = 27,
        [Description("Sergipe")]
        SE = 28,
        [Description("Bahia")]
        BA = 29,
        [Description("Minas Gerais")]
        MG = 31,
        [Description("Espírito Santo")]
        ES = 32,
        [Description("Rio de Janeiro")]
        RJ = 33,
        [Description("São Paulo")]
        SP = 35,
        [Description("Paraná")]
        PR = 41,
        [Description("Santa Catarina")]
        SC = 42,
        [Description("Rio Grande do Sul")]
        RS = 43,
        [Description("Mato Grosso do Sul")]
        MS = 50,
        [Description("Mato Grosso")]
        MT = 51,
        [Description("Goiás")]
        GO = 52,
        [Description("Distrito Federal")]
        DF = 53

    }

Dessa maneira ta salvando no banco na minha tabela que recebe o enum, como 0.
Então, eu preciso criar os enumViewModel? ou basta usar os enum da camada de dominio mesmo? adicionando assim, uma referencia na minha camada de Apresentação, para a camada de dominio.
Answer: Tópico aberto a bastante tempo hein! Já conseguiu resolver?
Vamos lá, o bom seria você isolar os Enumeradores em outro projeto da solução, fixando na camada de aplicação, pois tu pode vir a utilizar em outros projetos da solução, Digamos que assim tu estará utilizando uma nova tipificação de atributo e referencia nos projetos ao qual farão uso do mesmo.
No domínio o campo da entidade que tu irá submeter tu poderá declarar como o Enum criado:
EstadoViewModel estado{ get; set;}

para o banco será reconhecido como Int.
Mas caso não queira criar nesse modelo você pode lidar com o teu Enum na camada de Apresentação e no domínio colocar o campo como Int.
No teu mapeamento o teu Enum você deve fazer a conversão para Int. Assim odado irá para o banco corretamente.
Comment: Já resolvi.. eu coloquei os enums separados, e uso eles em qualquer parte do proejto.. ou seja o meu `ClienteDominio.Enum` tem o mesmo enum que o `ClienteViewModel.Enum`. Até o momento nao tive problema ao usar assim. Obrigado!!
Comment: Show de Bola. Agora que vi o teu post.

Projeto MVC DDD


If $f$ is a function such that $f'(x)$ exists for all $x\in\mathbb{R}$. Then $f'$ has period $2\pi $.

Question: If $f$ is a function such that $$ \int_{-\pi}^{\pi}f(x)dx=\int_c^{c+2\pi}f(x)dx \quad\forall c\in\mathbb{R}$$ and $f'(x)$exists for all $x\in\mathbb{R}$.
Then $f'$ has period $2\pi $.
I know I've to show that $f'(x)=f'(x+2\pi)$ for all  $\quad x\in\mathbb{R}$. Any suggestions would be great!
Comment: I've rarely seen a more misleading title lol
Answer: By the second Fundamental Theorem of Calculus, after taking derivative for both sides w.r.t $c$, we have
$$ f(c+2\pi)-f(c) =0. $$
Changing $c$ into $x$ gives
$$ f(x+2\pi)=f(x). $$
Taking derivative for both sides w.r.t $x$, we have
$$ f'(x+2\pi)=f'(x). $$
Namely $f'(x)$ is a periodic function with period $2\pi$.
Comment: Maybe you should precise that you differentiate w.r.t. $c$...
Comment: Yes, you are right. Thanks.


How to create a single MongoDB Container in Kubernates Cluster

Question: I am running a Kubernates Cluster in GCP. Each one of my clients/customer will need their own Kubernates Cluster.
Each Cluster/client needs to have their own database. What is the best way to go about this? I would like each cluster to have a MongoDB service so every pod in the cluster can communicate with the DB, but what is the correct way to do this? Create a pod running MongoDb with persistent storage on the node?
Create a replica set of mongoDB pods inside the cluster?
Have a single large MongoDB that each client's cluster can communicate with?
Answer: For running database service such as Mongodb, I would recommend to use Stateful Sets.

StatefulSets are intended to be used with stateful applications and
  distributed systems.

You can follow this nice tutorial to run stateful set Mongodb service on GKE and also it will be helpful to understand components, or you can use easily mongodb-replicaset helm chart on each of your cluster.


Broken Unity project after git clone

Question: I have a Unity project (github link), that doesn't work after being cloned. Even though the files are there, they have incorrect contents. For example .png files are replaced with text:

version https://git-lfs.github.com/spec/v1
oid sha256:089f8198df161233681006c4243f6d6babb2e125062a21ea727d0d6c97889d26
size 1035

Some DLLs that I have from external asset packages (for example DOTween), are also probably not stored correctly, because the compiler complains about undeclared namespaces.

Assets/External Dependencies/Demigiant/DOTween/Examples/Basics.cs(3,7): error CS0246: The type or namespace name `DG' could not be found. Are you missing an assembly reference?

UPDATE:
Actually, the dlls are not even there. Why? They're not part of the gitignore.
I have made sure to set Version Control Mode to Visible Meta Files and
Asset Serialization Mode to Force Text.
I tried moving the project to a new directory, deleting the .git folder, deleting Library, remaking everything (reopening with Unity, and then git init), and pushing to a new repo. The new repo has the exact same issues as the previous one.
I'm using the default .gitignore for Unity
And the following .gitattributes (to enable LFS):
# 3D models
*.3dm filter=lfs diff=lfs merge=lfs -text
*.3ds filter=lfs diff=lfs merge=lfs -text
*.blend filter=lfs diff=lfs merge=lfs -text
*.c4d filter=lfs diff=lfs merge=lfs -text
*.collada filter=lfs diff=lfs merge=lfs -text
*.dae filter=lfs diff=lfs merge=lfs -text
*.dxf filter=lfs diff=lfs merge=lfs -text
*.fbx filter=lfs diff=lfs merge=lfs -text
*.jas filter=lfs diff=lfs merge=lfs -text
*.lws filter=lfs diff=lfs merge=lfs -text
*.lxo filter=lfs diff=lfs merge=lfs -text
*.ma filter=lfs diff=lfs merge=lfs -text
*.max filter=lfs diff=lfs merge=lfs -text
*.mb filter=lfs diff=lfs merge=lfs -text
*.obj filter=lfs diff=lfs merge=lfs -text
*.ply filter=lfs diff=lfs merge=lfs -text
*.skp filter=lfs diff=lfs merge=lfs -text
*.stl filter=lfs diff=lfs merge=lfs -text
*.ztl filter=lfs diff=lfs merge=lfs -text
# Audio
*.aif filter=lfs diff=lfs merge=lfs -text
*.aiff filter=lfs diff=lfs merge=lfs -text
*.it filter=lfs diff=lfs merge=lfs -text
*.mod filter=lfs diff=lfs merge=lfs -text
*.mp3 filter=lfs diff=lfs merge=lfs -text
*.ogg filter=lfs diff=lfs merge=lfs -text
*.s3m filter=lfs diff=lfs merge=lfs -text
*.wav filter=lfs diff=lfs merge=lfs -text
*.xm filter=lfs diff=lfs merge=lfs -text
# Fonts
*.otf filter=lfs diff=lfs merge=lfs -text
*.ttf filter=lfs diff=lfs merge=lfs -text
# Images
*.bmp filter=lfs diff=lfs merge=lfs -text
*.exr filter=lfs diff=lfs merge=lfs -text
*.gif filter=lfs diff=lfs merge=lfs -text
*.hdr filter=lfs diff=lfs merge=lfs -text
*.iff filter=lfs diff=lfs merge=lfs -text
*.jpeg filter=lfs diff=lfs merge=lfs -text
*.jpg filter=lfs diff=lfs merge=lfs -text
*.pict filter=lfs diff=lfs merge=lfs -text
*.png filter=lfs diff=lfs merge=lfs -text
*.psd filter=lfs diff=lfs merge=lfs -text
*.tga filter=lfs diff=lfs merge=lfs -text
*.tif filter=lfs diff=lfs merge=lfs -text
*.tiff filter=lfs diff=lfs merge=lfs -text
# Collapse Unity-generated files on GitHub
*.asset linguist-generated
*.mat linguist-generated
*.meta linguist-generated
*.prefab linguist-generated
*.unity linguist-generated

UPDATE:
After further investigation, it seems that the png files, get overwritten (by unity?) when the project gets opened after cloning. They exist correctly in the remote repository. The external dlls on the other hand do not get uploaded at all.
Comment: For me it's a problem with git-lfs. Is it installed on your computer?
Comment: Yes it's installed. I'm also pretty certain it's with git-lfs. I'll reinstall it.
Comment: @K.Gkinis Has your problem been solved yet?
Comment: @MarinaLiu-MSFT No, but I haven't had the time to try anything new.
Comment: @K.Gkinis Ok, you can have a try and feedback the result when you are free.
Answer: Your .gitattributes file is wrong.

*.png filter=lfs diff=lfs merge=lfs -text

Text? TEXT? Why on earth would you want to treat .png files as text? Same goes for most of those other attributes.
Looking at my own .gitattributes file, I have this:
(Yes, most of the lines are comments)
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs     diff=csharp

###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln       merge=binary
#*.csproj    merge=binary
#*.vbproj    merge=binary
#*.vcxproj   merge=binary
#*.vcproj    merge=binary
#*.dbproj    merge=binary
#*.fsproj    merge=binary
#*.lsproj    merge=binary
#*.wixproj   merge=binary
#*.modelproj merge=binary
#*.sqlproj   merge=binary
#*.wwaproj   merge=binary

###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg   binary
#*.png   binary
#*.gif   binary

###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc   diff=astextplain
#*.DOC   diff=astextplain
#*.docx  diff=astextplain
#*.DOCX  diff=astextplain
#*.dot   diff=astextplain
#*.DOT   diff=astextplain
#*.pdf   diff=astextplain
#*.PDF   diff=astextplain
#*.rtf   diff=astextplain
#*.RTF   diff=astextplain

This file was created automatically for me when I created the git repository through the GitHub desktop application. I've heard that it's "not very good" but I've found that it does what I need it to. Namely not get in the way of making commits and pushing to GitHub.
Comment: the -text attribute is for removing text property and treat this file as binary file. So I think your answer is misleading.
Answer: Remove this section for git clone to fetch your lfs files.
# Collapse Unity-generated files on GitHub
*.asset linguist-generated
*.mat linguist-generated
*.meta linguist-generated
*.prefab linguist-generated
*.unity linguist-generated

git clone reads the .gitattribute file before deciding whether to resolve lfs files. If it finds syntax it can't understand it aborts the process. I thik linguist-generated is a non-standard attribute that's causing your repo to not pull in the changes.
I don't have the reputation to comment on the other answer, but -text is not the problem.
In gitattribute files adding a - before a property "unsets" the property. In this case it means do not treat it as text.
From https://git-scm.com/docs/gitattributes:

"Unsetting the text attribute on a path tells Git not to attempt any
  end-of-line conversion upon checkin or checkout."
Answer: You shouldn't use LFS to track DLL files, it will cause your DLL compile error.
I also encounter this problem. Error: namespace doesn't exist. It turns out that a DLL containing that namespace was not downloaded. DLL contained symbolic link text instead. C# ignored that DLL and did load symbols -> compilation failed.
You can use the following commands to bring back the DLL files to normal:
git lfs untrack *.dll
git rm --cached *.dll
git add *.dll
git commit -m "add dll back to non-LFS files"

And then you do a fresh checkout could fix your problem.
Some part of my error messages are:

the class com.tencent.pandora.WsOPCancelSubscribe could not be loaded,
used in Assembly-CSharp, Version=184.108.40.2068, Culture=neutral,
PublicKeyToken=null The class
com.tencent.pandora.WsOPCancelSubscribeAck could not be loaded, used
in Assembly-CSharp, Version=126.96.36.1998, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsSendMsgAck could
not be loaded, used in Assembly-CSharp, Version=18.104.22.1688,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsBarrageItem could not be loaded, used in
Assembly-CSharp, Version=18.104.22.1688, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.BulletWebSocket
could not be loaded, used in Assembly-CSharp, Version=188.8.131.528,
Culture=neutral, PublicKeyToken=null The class
c__Iterator0 could not be loaded, used in
Assembly-CSharp, Version=18.104.22.1688, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsEventData could
not be loaded, used in Assembly-CSharp, Version=22.214.171.1248,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsEventScene could not be loaded, used in
Assembly-CSharp, Version=184.108.40.2068, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsEventItem could
not be loaded, used in Assembly-CSharp, Version=22.214.171.1248,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsTerminalPage could not be loaded, used in
Assembly-CSharp, Version=220.127.116.118, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsOPSubscribe could
not be loaded, used in Assembly-CSharp, Version=184.108.40.2068,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsOPHeartBeat could not be loaded, used in
Assembly-CSharp, Version=18.104.22.1688, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsOPHeartbeatAck
could not be loaded, used in Assembly-CSharp, Version=18.104.22.1688,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsOPCancelSubscribe could not be loaded, used in
Assembly-CSharp, Version=18.104.22.1688, Culture=neutral,
PublicKeyToken=null The class
com.tencent.pandora.WsOPCancelSubscribeAck could not be loaded, used
in Assembly-CSharp, Version=184.108.40.2068, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsSendMsgAck could
not be loaded, used in Assembly-CSharp, Version=184.108.40.2068,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsBarrageItem could not be loaded, used in
Assembly-CSharp, Version=184.108.40.2068, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.BulletWebSocket
could not be loaded, used in Assembly-CSharp, Version=220.127.116.118,
Culture=neutral, PublicKeyToken=null The class
c__Iterator0 could not be loaded, used in
Assembly-CSharp, Version=22.214.171.1248, Culture=neutral,
PublicKeyToken=null The class com.tencent.pandora.WsEventData could
not be loaded, used in Assembly-CSharp, Version=220.127.116.118,
Culture=neutral, PublicKeyToken=null The class
com.tencent.pandora.WsEventScene could not be loaded, used in
Assembly-CSharp, Version=188.8.131.528, Culture=neutral,
PublicKeyToken=null

If anyone encounters the same problem as me, you could just check your ProjectSettings.asset file, you shouldn't set LF line endings to it, leave it as LFCR and my problem magically disappeared.

Broken Unity project after git clone


Qt setPermissions not setting permisions

Question: I'm not sure why but my code bellow does not set permissions for a file.
Not sure what could be wrong with the code.
SYSTEM:
Windows XP Pro SP2.
Running in Admin account as admin.
Newest Qt framework and files.
//Get file permissions of ref file.
QFile::Permissions qpPerm1;
qpPerm1 = QFile::permissions("E:/dir1/dir2/File1.txt");

//Set file permissions of a file.
bool isOK=0;
isOK = QFile::setPermissions("E:/dir4/dir5/file2.txt",qpPerm1);
qout << "Perms set? " << isOK << endl;

Return value is TRUE... claims it set the permissions but it did not.
To be clear, file2.txt is a copy of file1.txt.
I set permisions of file1 to be something but file2.txt has different permissions after I run my code.
Answer: As it was written QT doesn't support changing access rights for groups on windows. For full control over file permissions try using Access Control List which is located in security descriptor.
MSDN suggests this:

To retrieve the security descriptor of a file or directory object,
  call the GetNamedSecurityInfo or GetSecurityInfo function. To change
  the security descriptor of a file or directory object, call the
  SetNamedSecurityInfo or SetSecurityInfo function.

I think in your case you could try GetNamedSecurityInfo from the first file and pass it to SetNamedSecurityInfo for the second one.

Also you can assign NULL ACL and it will reset all group permissions and grant full access for everyone:
SetNamedSecurityInfoA("C:\file.txt", SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);

Answer: Since you're mentionning WinXP Pro SP2, I'll assume your files are on NTFS.
According to Qt's documentation :

Note that Qt does not by default check for permissions on NTFS file
  systems, as this may decrease the performance of file handling
  considerably. It is possible to force permission checking on NTFS by
  including the following code in your source:
extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;

Permission checking is then turned on and off by incrementing and
  decrementing qt_ntfs_permission_lookup by 1.
qt_ntfs_permission_lookup++; // turn checking on
qt_ntfs_permission_lookup--; // turn it off again

Comment: Correct NTFS. Unfortunately, what you suggested did not work. The returned bools is 1 but still no change in perms. In fact there is no difference except code runs slower.


Prove any consistent system with coefficient matrix A has exactly $p^{n-rank(A)}$ solutions in $\mathbb{Z_p}$.

Question: "Prove that in the field $\mathbb{Z_p}$ ($_p$ being a prime), when we have a matrix A that is $m⨯n$. Any consistent system with coefficient matrix A has exactly $p^{n-rank(A)}$ solutions."
I got this question and I can't find the solution to it, I don't even know where to start. Does anyone know how to solve this? I feel really stupid.
P.S. How do you deal with anger when doing a maths question?
Thank you.
Answer: Here is something that might work. First of all I am assuming that you are referring the field with $p$ elements (I would recommend you use the notation $\mathbb{Z}/p\mathbb{Z}$ and not $\mathbb{Z}_p$ in the future).
Try viewing $A$ as a map from $(\mathbb{Z}/p\mathbb{Z})^n \to (\mathbb{Z}/p\mathbb{Z})^m$ and try to see how many elements are there in a subspace of given dimension. Now try to compute the number of elements in the solution space of the system using the rank nullity theorem.
Hope this helps.
Comment: A map is just another word for a function, in this case a linear transformation.


User relationship one way relation block and unblock option

Question: Im using user relationship module for twitter like one way relationship ,
But i find any option to block the user from following me and in future.
Only remove option is there to remove and once removed, the user again start following me.
Any option to block the user from following me?
Thanks,
Edie :)
Answer: This feature does not currently exist, you can not implement it without hacking the module.
There are feature requests open for this, I suggest have a look at these:
http://drupal.org/node/203364
Comment: so i want to hack into the module huh okie will try