Proof in Arithmetic Progression

Question: My maths teacher at school asked a question which I am finding difficult to crack down.
We are given that $a^2 , b^2$ and $c^2$ are in AP. We need to prove that $\frac{a}{b+c} , \frac{b}{a+c}$ and  $\frac{c}{a+b}$ are in AP.
This is what I tried.
Let the common difference of the AP be d .  So,
$b^2 - a^2 = d   \implies b-a =  \frac{d}{a+b} ........(1)$
Similarly
$c^2 - b^2 = d   \implies c-b = \frac{d}{b+c}. ........(2)$
Also,
$a^2 - c^2 = -2d     \implies  a-c =  \frac{-2d}{a+c} .........(3) $
Now adding the three equations,
$$0 = \frac{d}{a+b} + \frac{d}{b+c} - \frac{2d}{a+c}
\implies \frac{2d}{a+c} = \frac{d}{a+b} + \frac{d}{b+c}$$
$$\implies \frac{2}{a+c} = \frac{1}{a+b} + \frac{1}{b+c}$$
So, $\frac{1}{a+b}, \frac{1}{a+c}$ and $\frac{1}{b+c}$ are in AP. How should I go further? Or if I am going wrong anywhere, please tell.
Comment: Instead of adding the three equations, consider $\frac{a}{b+c}=\frac{a(c-b)}{c^2-b^2}=\frac{a(c-b)}{d}$. Similarly for the other two terms.
Answer: $$\frac{2b}{a+c}=\frac{a}{b+c}+\frac{c}{a+b}\Leftrightarrow \\
2b[b^2+b(a+c)+ac]=a[a^2+a(b+c)+bc]+c[c^2+c(a+b)+ab]\Leftrightarrow\\
2b^3+2b^2(a+c)=a^3+a^2(b+c)+c^3+c^2(a+b)\Leftrightarrow\\
2b^2(a+b+c)=a^2(a+b+c)+c^2(a+b+c)\Leftrightarrow \\
(a+b+c)(2b^2-a^2-c^2)=0$$
Can you finish?
Comment: @Saksham: Is it clear?
Comment: Not really. I don't get why you have used the equation which we have to prove as a part of your proof.
Comment: @Saksham: I just did some manipulation using equivalence! You can go backward and get your proof!
Comment: Ohh. So have you used what we had to prove to go back to the original question?
Comment: @Saksham: yes, that is a common approach.
Comment: Thanks a lot for the help, but probably your method was a bit lengthier. Thanks again nonetheless.
Answer: $AP1$: $$a^2\\ b^2\\ c^2$$
 $$\text{Common Difference, }\quad d=b^2-a^2=c^2-b^2\qquad \qquad $$
$XP2$:
$$P=\frac a{b+c}\color{lightgrey}{\cdot\frac{(c-b)}{(c-b)}}=\frac {a(c-b)}{c^2-b^2}=\frac {a(c-b)}d\\
Q=\frac b{c+a}\color{lightgrey}{\cdot\frac{(c-a)}{(c-a)}}=\frac {b(c-a)}{c^2-a^2}=\frac {b(c-a)}{2d}\\
R=\frac c{a+b}\color{lightgrey}{\cdot\frac{(b-a)}{(b-a)}}=\frac {c(b-a)}{b^2-a^2}=\frac {c(b-a)}d\\$$
If $XP2$ is an AP, then $P+R=2Q$.
Testing both sides:
$$\text{LHS}=P+R=\frac {a(c-b)+c(b-a)}d=\frac {bc-ba}d=2\cdot\frac {b(c-a)}{2d}=2Q=\text{RHS}$$
Hence $XP2$ is also an $AP$, if $AP1$ is an $AP$.

NB - I had worked this out independently but credit to the hint given by @Lozenges in the comments.

Proof in Arithmetic Progression


Como é que eu posso adicionar elementos numa array multidimensional?

Question: como é que faço para adicionar elementos a uma array multidimensional. Por exemplo em vez de criar uma array em PHP desta  forma:
$i = 0;
$aArray[$i]['title'][] = 'teste';
$aArray[$i]['link'][] = 'teste de link';

Poder fazer assim
$aArray[$i] = array( 'title' => ??????, 'link' => ????? )

o ???? deve adicionar um elemento ao final dessa array
Comment: De uma olhada neste Post parece ser a mesma duvida que voce tem.
http://stackoverflow.com/a/19099153
Answer: Pelo que entendi, você deve estar querendo simplificar o processo.
Não sei se aplica ao seu caso, mas uma maneira de fazer isso é usando as referências - através do sinal &.
$test =& $array[1]['test'];

$test[] = 'stack';

$test[] = 'overflow';

print_r($array);

Resultado:
Array
(
    [1] => Array
        (
            [test] => Array
                (
                    [0] => stack
                    [1] => overflow
                )

        )

)

Comment: Interessante. Mas esse tipo de operações não foram descontinuadas?
Comment: Não. Atribuição por referência só é depreciado em instâncias de classes
Comment: Ok, já tive a ver e está óptimo! abraço
Comment: por isso amo php.. nem em sonho pode-se fazer isso em linguagens "sérias" rsrsrs


jquery isotope load

Question: I using isotope plugin for jquery, this works good if is static html blocks:
HTML:

JS:

$('#target > *').isotope([needle options]);

but, if i use "load" to load content into #target, isotope ignore them.
JS:
$('#target').load('file',function()
{
    $('#target > *').isotope([needle options]);
}
);

please help, it's very important.
Answer: You can instance onload various div items retrieved by your load.
See insert method from the isotope docs.
$.ajax({
  url: file,
  success: function( data ) {
  $('#target').isotope('insert', data);
  }
});

Comment: Ok after loading file in console typed this:

Uncaught TypeError: Object (here is all html code from loaded file(why? I don't know)) has no method 'filter'
Comment: ps. did not test the code, its more to give you some idea of how you should do this.

jquery isotope load


Is this a helpful way to think about Coltrane Substitution?

Question: More specifically, is it harmful?  From the ii-V-I I could backtrack from the I and suss out the flatVImaj7 and the IIImaj7, but what about:
Bar 1 ii-up a half step to a dominant -
Bar2 down a fourth to a maj7 - up a minor third to a dominant -
Bar 3 down a fourth to a maj7 - up a minor third to a dominant -   <-- this is the original V
Bar 4 I
Answer: That's a rule of thumb for copying them. If you want to THINK about them, understand two things.
That you can jump to just about ANY chord and start a ii, V, I pattern.  And if you jump to one (say) a major third away, then, having completed that sequence jump another major third, you're building a pattern, and patterns are very powerful things in music!  When you do something 'wrong' three times over, it starts sounding 'right'!
And the idea of b5 (or 'tritone') substitutions for a chord that has a dominant function.
Comment: Yes, I understand that.  I'm just focusing on this one pattern this month.  Don't see a "them" here.   I started looking at "Countdown" (played at amateur guitar player speed) and have been drilling this substitution in all 12 keys and all the positions I can find.
Comment: @GlueWrangler -- "Don't see a 'them' here." Multiple chord substitutions, and the fact that these seem to be called "Coltrane changes" more often than "Coltrane substitution" (though I have also seen "Coltrane substitutions") suggests that "them" is appropriate.
Comment: I'm talking about one particular pattern which I spelled out so there's no "them".  ii-V-I is also not a "them".  Do you think this is a helpful way of thinking about it or harmful, as opposed to reverse engineering the flatVI and the III?


Google Cloud Datastore: Exporting entities that match a certain query

Question: Background
I need to send out a large batch of notifications to around ~1 mil devices and I'm building it out using Google Cloud Functions.
In the current setup I enqueue each device token as a PubSub message that:

stores a pending notification in DataStore, used for keeping track of retries and success status
attempts to send the notification
marks the notification as either successful or failed if it's retried enough and hasn't gone through

This process is manually kicked off by a human uploading a CSV with all the tokens. The in-built retry should be enough in principle but I wanted to make sure that if something is off with either the cloud functions themselves or APNs/FCM that I could return a CSV of all the failed tokens in the same format it was uploaded so that the user can retry only the failed one when/if they think it's a good idea.
I run the notifications as part of a job which I use for querying together with the notification's status. To do this I've set up a compound index on job_id and status and I run a query over all the notifications that match and want to either stream that as a file to the user or store it in Google Cloud Storage so the user can download it from there.
Issue
Assuming something close to the amount of total notifications fail and that I want to get all the tokens in one file, my first implementation was just iterating through all the matching entries and building the result. The issue is that it takes around 1 minute per 100_000 entries when retrieving them this way. For something close to all notifications it would take me beyond the max timeout of a Cloud Function. Each entity is around a total of 300 bytes which makes the whole export around 300MB. I could probably reduce this to about half/two-thirds the size by adding a bigger index that would let me do a projection for just the fields I want.
The only alternative I can think of is sharding the notifications to split up the whole group in let's say 100 shards, create 100 files with 10k notifications each and then download them all and stitch them together when the user tries to download the file.
The reason I'm posting the question is that this feels like a relatively simple problem and this solution feels a bit more complicated than I'd expect so I figure I might be missing something.
Questions

Am I missing an obvious, easier way to achieve what I want?
Is sharding just the expected way to go for something like this and I should just accept the complexity?

Code
Just for clarity this is the snippet of code I'm running and I just iterate over the response that this returns in order to produce the output.
    def get_failures(job_id):
        query = client.query(kind = Notification.kind)
        query.add_filter('job_id', '=', str(job_id))
        query.add_filter('status', '=', "failure")
        return query.fetch()

Answer: The robust solution to this problem is using Google Dataflow. I currently use it to do exactly this, producing csv files in Google Cloud Storage that contain all ~500k records that match a given datastore query.
Getting it setup can be a bit involved, though.
Before getting this going I used Google Task Queue which has a 10 minute timeout instead of a 30 second timeout. I'm not sure if you can do this purely within cloud functions, or if you'd need to whip up a simple app engine project to act as the request handler for these tasks
Comment: In the end I used BigQuery for this because it was much easier to set up and worked out well for my use case. I accepted this answer because I'd guess that for a more general constant use application it would be more sensible.
Comment: I'll give Dataflow a look and see where that gets me, looks like a great lead, thanks for pointing that out. Google Task Queue is something I'd considered before but it doesn't work with purely Cloud Functions so I was trying to find a "native" solution. It is the next thing I'll try if Dataflow doesn't get me anywhere
Comment: Had a quick scan of the documentation, is there anyway to programatically kick off a dataflow job? It seems that I can have a streaming version running continuously but that sounds costly given I want this to run very rarely, or I can kick it off from the UI but I don't see anything that would let me trigger from a process.
Comment: I use an app engine flex instance as my dataflow launcher, like this: http://amygdala.github.io/dataflow/app_engine/2017/04/14/gae_dataflow.html
It looks like this person is able to launch them from cloud functions:
https://medium.com/google-cloud/how-to-kick-off-a-dataflow-pipeline-via-cloud-functions-696927975d4e


Is a velocity sensitive keyboard for music production required?

Question: I am shopping for a new keyboard, and I was wondering if I have to have a velocity sensitive keyboard. I don't use velocity in music production most of the time, and I already have a velocity sensitive electric piano I use for playing regular pieces of music, and practicing piano. Tips?
P.S. Do I have to have at least 61 keys?
Comment: Can you even buy a keyboard that *isn't* velocity sensitive these days?
Answer: No, but you can always edit most velocity sensitive midi controllers to have zero sensitivity anyway. I do that since I only use it to compose. As for the number of keys, it depends on how many instruments you write for and if you have auto octave displacement or not. Having 5 octaves is nice for writing for guitar and bass.
Comment: I'm already using my electric piano to learn, so I won't need a pressure sensitive keyboard, right?
Comment: @Epic_Taco_Dude Velocity and pressure are two separate things. A velocity sensitive keyboard, like in your question, reacts to the force the keays are struck with. A pressure sensitive keyboard reacts to the constant pressure while the keys are held down. This is also called aftertouch.
Answer: 'Required'? No. I like to use one because I can play into certain software with more 'emotion' than I could without. But I know lots of composers switch the velocity sensitivity off (as do I sometimes).


ASP.net WebApi Multiple controller types were found that match the URL

Question: I have added a new HttpPost route "api/export/error/" to my WebApi, using Attribute Routing, and I am getting an error:

Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.\r\n\r\nThe request has found the following matching controller types: \r\nMyApp.Controllers.ExportErrorController\r\nMyApp.Controllers.ExportGeneratorController

But I do not have the same routes in different controllers that i see; here are the only routes in those two controllers:
ExportErrorController.cs
[HttpGet]
[Route( "api/export/error/total/" )]
[HttpGet]
[Route( "api/export/error/channel/{channelId}/" )]
[HttpPost]
[Route( "api/export/error/" )]
[HttpDelete]
[Route( "api/export/error/{id}/" )]
[HttpPut]
[Route( "api/export/error/clear/" )]
ExportGeneratorController.cs
[HttpGet]
[Route( "api/2/export/{channelId}/" )]
[HttpPost]
[Route( "api/2/export/generate-word/{debugInfo}/" )]
[HttpPost]
[Route( "api/2/export/generate-excel/{debugInfo}/" )]
I cannot see any places that have the same between the two controllers
Answer: Apparently ASP.Net does not evaluate parameter 'types' OR methods when determining the route to use so it found and matched the route text "error" as a potential parameter for 'channelid' even though they were different methods.
Adding a type to the parameter helped it resolve it properly so:
[Route( "api/2/export/{channelId}/" )]
Is fixed by changing it to:
[Route( "api/2/export/{channelId:int}/" )]


How to get values custom metadata properties

Question: I'm trying to get the metadata for an asset in the DAM. However, it seems that the metadata comes back as empty for properties that don't have "dc:" in front of them.
Resource rs = getResourceResolver().getResource(fileReference);
Asset asset = rs.adaptTo(Asset.class);
//this works
title = asset.getMetadataValue("dc:title").toString();
//this does not work.
//I have ensured that "mine.title" is a property and has string value assigned to it.
customTitle = asset.getMetadataValue("mine.title").toString():
//this does not work either
customTitle = asset.getMetadata("mine.title").toString():

Is there a way to get the value from a custom metadata property?
Comment: In title = asset.getMetadataValue("dc:title").toString(); toString() might be redundant. asset.getMetadataValue() returns a "String" by default.
Answer: Assets at the end are simple nodes, so to get some property you can do something like this (depending on actual path of variable fileReference):
Resource metadataResource = rs.getChild("jcr:content/metadata");
ValueMap properties = ResourceUtil.getValueMap(metadataResource);
customTitle = properties.get("mine.title", "defaultValue")

Answer: "dc:title" comes with a registered namespace "dc" (Dublin Core) whereas "mine.title" does not.
That's the reason of title = asset.getMetadataValue("dc:title").toString(); giving you proper value than customTitle = asset.getMetadataValue("mine.title").toString()
You can attack this problem in many ways.

Change the property name to "dc:myTitle" and retrieve it in the same way you are retrieving "dc:title" [0]
You can retrieve the value of "mine.title" in the way Alex has described.
Resource rs = getResourceResolver().getResource(fileReference + "/jcr:content/metadata");
ValueMap damAssetValueMap = damResource.adaptTo(ValueMap.class);
String shortName = damAssetValueMap.get("shortName", String.class);
Register a new namespace and define options (in your case , its "mine").
A look at "/libs/dam/nodetypes" and "/libs/dam/options/metadata" might be helpful.

[0] Check "/libs/dam/options/metadata"


How to store sessionFactory object in context and used same object whole application

Question: I am developing application based on hibernate, but now in my application I am creating sessionFactory object per user i.e. while user is logged in which not right way.
I search lots on for same issue but I am not able find any solution on it. I read lots of on jndi but still not positive result.
I got same solution on it but they are using struts or spring but I need only hibernate application
Is anyone having the code or for sharing one sessionFactory object for ALL USERS.
I am using -

Tomcat server
Hibernate 4.0
NetBean
Answer: An easy approach can be to create a listener like this:
public class HibernateContext implements ServletContextListener {

    private static SessionFactory sessionFactory;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        sessionFactory = new Configuration().configure().buildSessionFactory();
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        sessionFactory.close();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Declare it on your web.xml:
<listener>
   <listener-class>yourpackage.HibernateContext</listener-class>
</listener>

and then, call the factory from anywhere in your code:
HibernateContext.getSessionFactory();

Comment: Yes Alberto ..your solution is work for me and thank you very much for instant reply ;)
Comment: Thanks Alberto for reply ...But my concern is only that i want to add my sessionFactory in one common place where i can serv the same object to all user.without creating new sessionFactory to each user which is currently i am doing and whuch is wrong approach.
Comment: Are you using Spring or CDI/EJB? Because an approach can be declare an application context object where you can get the sessionFactory
Comment: No I am not using CDI/EJB? I am using only hibernate,servlate,jsp,tomCat.
Comment: So it's better if you use a Servlet Context Listener in additional with a util class containing the ThreadLocal, you will be able to "inject" and use the sessionFactory into your servlet using this approach
Comment: Yes Alberto ...i tried this ThreadLocal approach but i am not able to do that and also tried Servlet Context Listener but both was not able to implement .Did u have any example of this it will really very helpful for me ? ..Thanks in advanced
Comment: I've edited my answer, I think that this approach can solve your problem


Dúvida em relação ao === e !=

Question: Estou com uma dúvida em mostrar dados apenas se estiverem preenchidos.
Já utilizei o === e o !=, mas com nenhum deles está a funcionar.

 '.$exibe["Nome1"].'

 '.$exibe["DataNascimento"].'

' .(date('Y/m/d') - $exibe["DataNascimento"] ).'

 '.$exibe["Funcao1"].'

 '.$exibe["EPISValidade"].'

 '.$exibe["MedicaValidade"].'

  Ver Documentos

    ';
        if ($exibe['Nome1'] === '') {

 }

    '

 '.$exibe["Nome1"].'

 '.$exibe["DataNascimento"].'

' .(date('Y/m/d') - $exibe["DataNascimento"] ).'

 '.$exibe["Funcao1"].'

 '.$exibe["EPISValidade"].'

 '.$exibe["MedicaValidade"].'

  Ver Documentos

';

/////
        if($exibe['Nome3'] != NULL) {
        '

 '.$exibe["Nome1"].'

 '.$exibe["DataNascimento"].'

' .(date('Y/m/d') - $exibe["DataNascimento"] ).'

 '.$exibe["Funcao1"].'

 '.$exibe["EPISValidade"].'

 '.$exibe["MedicaValidade"].'

  Ver Documentos

';}

O Primeiro mostra. Os outros dois existem e não me mostra os dados.
Comment: `===` Compara o `tipo` de dado(string, integer etc) e o `valor`, já `!=` verifica apenas se o valor é diferente. [operadores](http://php.net/manual/pt_BR/language.operators.comparison.php)
Answer: use o método is_null()
 if (is_null($exibe['Nome1'])) { //...

Comment: Seria uma boa deixar a resposta mais completa para a pergunta: "Duvida em relação ao === e !=", explicar o motivo de ter usado o is_null, pois apenas jogou uma resposta, mas o não explicou a diferença e o porque do === não ter dado certo.
Comment: Essa situação é idêntica ao do primeiro correcto?
 if (empty($exibe['Nome1'])) { //Aqui não mostra nada
Comment: Veja agora pois dará certo
Comment: E por isso dá um negativo? Valeu!
Answer: Verifique a documentação do PHP: operadores
empty() verifica se uma variável esta vazia
isset() verifica se uma ou mais variável(eis) (ou índice(s) de array) foi(ram) criada(o)(s) E se possui valor diferente de NULL @Bruno Augusto
Comment: isset() verifica se uma **ou mais** variável(eis) (ou índice(s) de array) foi(ram) criada(o)(s) **E** se possui valor diferente de NULL.
Answer: Quando você usa o operador === (ou sua contraparte !==) você está dizendo para o programa comparar o lado esquerdo com o direito não apenas em valor mas também em tipo.
De forma bem didática se você tiver dois valores 0 e '0', isto é, um inteiro zero e uma string numérica, você só poderia distingui-los com esse tipo de operador pois ambos representam a mesma coisa, mas são de tipos de diferentes.
Já seus irmãos menores, == e != comparam apenas o valor. Veja um exemplo:
$a = 0;
$b = '0';

var_dump( $a == $b, $a === $b );

A saída desse programa é:
bool(true)
bool(false)

O primeiro TRUE porque $a tem o mesmo valor de $b. Já o segundo retorna FALSE porque um é um integer e o outro uma string.
No seu caso em particular só seria possível afirmar com 100% de certeza se soubéssemos o que ou como foi definido o array $exibe, porém, mesmo sem conhecê-los é possível sugerir que seja feita a comparação não apenas com operadores, mas sim com as funções isset() e empty():
if ( isset( $exibe['Nome1'] ) && ! empty( $exibe['Nome1'] ) ) {}

Dúvida em relação ao === e !=


Real Analysis, Folland problem 3.5.28 Functions of Bounded Variation

Question: Background information:
If $F:\mathbb{R}\rightarrow \mathbb{C}$ and $x\in\mathbb{R}$, we define $$T_{F}(x) = \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1})|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}$$ $T_F$ is called the total variation of $F$. We observe that the sums in the definition of $T_F$ are made bigger if the additional subdivision points $x_j$ are added. Hence, if $a<b$, the definition of $T_F(b)$ is unaffected if we assume that $a$ is always one of the subdivision points. It follows that $$T_F(b) = T_F(a) = \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1})|:n\in\mathbb{N},a=x_0<\ldots<x_n = b\}$$  Thus $T_F$ is an increasing function with values $[0,\infty]$. If $T_F(\infty) = \lim_{x\rightarrow\infty}T_F(x)$ is finite, we say that $F$ is of bounded variation on $\mathbb{R}$, and we denote the space of all such $F$ by $BV$. And we define $NBV$ $N$ for normalized $$NBV = \{F\in BV:F \ \text{is right continuous and} \ F(-\infty) = 0\}$$
Problem 28 - If $F\in NBV$, let $G(x) = |\mu_F|((-\infty,x])$. Prove that $|\mu_F| = \mu_{T_F}$ by showing that $G = T_F$ via the following steps.
a.) From the definition of $T_F$, $T_F\leq G$
b.)$|\mu_F(E)|\leq \mu_{T_F}(E)$ where $E$ is an interval, and hence $E$ is a Borel set.
c.)$|\mu_F|\leq \mu_{T_F}$, and hence $G\leq T_F$
Attempted proof a.): If $x\in\mathbb{R}^n$ then
\begin{align*}
T_F(x) &= \sup\{\sum_{1}^{n}|F(x_j) - F(x_{j-1})|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}\\ &= \sup\{\sum_{1}^{n}|\mu_F((-\infty,x_j]) - \mu_F((-\infty,x_{j-1}])|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}\\ &= \sup\{\sum_{1}^{n}|\mu_F((x_{j-1},x_j])|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}\\ &\leq \sup\{\sum_{1}^{n}|\mu_F(E_j)|:\{E_j\}_{1}^{n}\in\mathbb{B}_{\mathbb{R}} \ \text{disjoint such that} \ \bigcup_{1}^{n}E_j = \sum_{1}^{n}(-\infty,x_j]\}\\ & = |\mu_F|(E)\\ &= |\mu_F|((-\infty,x])\\ &= G(x)
\end{align*}
Attempted proof b.) We have from part a.) $$T_F(x) = \sup\{\sum_{1}^{n}|\mu_F((x_{j-1},x_j])|:n\in\mathbb{N},-\infty<x_0<\ldots<x_n = x\}$$ and we know that the interval $(x_{j-1},x_j]$ is a half-open interval and thus is in the Borel set.
So, let $\epsilon > 0$, then since $F$ is right continuous and $|\mu_F|(E) = |\mu_F|((-\infty,x])$ there exists a $\delta_x > 0$ such that $$\left|\int|\mu_F|(E)dx\right| = \left|\int|\mu_F|((-\infty,x])dx\right| \leq \int \mu_{T_F}(x)dx + \epsilon$$
I am not really sure where to go from here or if this is even correct, I am pretty sure if I can complete part b.) then c.) should not be too hard. I just need some help with proving part b.), any suggestions is greatly appreciated.
Answer: For part (b), you can proceed as follows:
Let $(a, b]$ be any interval, let $a = x_0 < x_1 < ... < x_n = b$ be any partition, then $|\mu_{F}((a,b])| \leq \sum_{1}^{n} |\mu_{F}((x_{j-1},x_{j}])| = \sum_{1}^{n} |F(x_{j}) - F(x_{j-1})| \leq \sup\{\sum_{1}^{n} |F(x_{j} - F_{j-1}|: n \in \mathbb{N}, a = x_0 <...<x_n = b\} = T_{F}(b) - T_{F}(a) = \mu_{T_{F}}((a,b])$.


Can't add menu items to new menu

Question: I get a message: your configuration has been saved, but when I look at list links it says no links have been added.
I found a similar question and tried the answers to no luck.
I added a new menu Login Menu which worked fine and shows up with the other default menus.
I created a page content to serve as my login page for the site. When I try to add a link to my new Login Menu it says it has been saved, but it does not show up.
My objective is to move the User login block to show only on it's own page. So I need a menu for anonymous users to go to for logging in.
Comment: Is the page you are trying to add to the menu published?
Comment: Yes, I can navigate to the page via the url, and I have verified it is published.
Comment: Similar: http://drupal.stackexchange.com/questions/22645/i-cant-add-links-to-any-of-my-menu
Answer: The problem was with the hierarchical menu module 7.x-3.0-alpha5. Although no error is created when trying to add a new item to a menu, an error is generated when adding new content with a menu link. This error allowed me to search for a solution.
I disabled the module and was able to add a new menu item to my new menu.
Answer: Try clearing the menu cache: menu_rebuild().
In Drupal 7 go to: Administration -> Configuration -> Development -> Performance and click "Clear All Caches"
(example.com/admin/config/development/performance if clean URLs are enabled)

Can't add menu items to new menu


probability and combinations with the word examination

Question: how the word >examination< can be written different types. Is the solution is 11!/2! X 2! X 2! = 11!/8. Please help to get the value
Regards,
me
Comment: It is very unclear what you're asking. Could you try to rephrase the question with different words (and more of them), please?
Comment: @HenningMakholm I have seen the exact problem before. I think he is asking how many words can be written using exactly those letters.
Answer: Did you find this in Combinatorial Problems and Exercises by Laszlo Lovasz?
$examination=e*x*a^2*m*i^2*n^2*t*o$
If all of the letters where different there would be $11!$ ways to permute it. However there are $2*2*2=8$ permutations that look exactly the same, (since the letters a,i and n can be arranged in two ways each, without any noticeable difference). therefore each permutation belongs to a class of 8 permuations which all look the same. Therefore there are $\frac{11!}{8}$ classes and thus $\frac{11!}{8}$ words, you are correct.


Pointed cone contained in relative interior of another pointed cone

Question: In my studies of convex cones I have recently met the following problem:

A non-empty set $ K\subseteq \mathbb{R}^d $ is called a convex cone if for all members $ x,y\in K $ and all non-negative real scalars $ 0 \leq\alpha,\beta \in \mathbb{R} $ we have $ \alpha x + \beta y \in K $. A convex cone is called pointed if we have $ K \cap -K = \{0\} $ and we denote by "ri" the relative interior. I am asked to prove that if $ K $ is a closed pointed cone, then there exists a pointed cone $ K' $ such that $ K \backslash \{0\} \subseteq ri(K') $ and of course $ K-K $ is the Minkowski difference meaning $ K-K = \{ k_1 -k_2 | k_1,k_2 \in K \} $.
  Now I have no idea how to proceed on this and have no idea how to formulate a solution for this, I can see intuitively why this mght hold maybe using hyperplane separation but not formally, could someone please assist on this? I thank all helpers.
Answer: I assume it suffices to work with full dimensional $K\subseteq\mathbb{R}^d$, so that the dual $K^*$ is pointed. Since $K$ is pointed, $K^*$ is full dimensional, so pick any set of $d$ linearly independent vectors $v_1,v_2,\dots,v_d$ in $K^*$ that lie in the relative interior of $K^*$ to get a subcone $K'=\text{cone}\{v_1,v_2,\dots,v_d\}$ that is still full dimensional.
Then $K'\subsetneq K^*\implies (K')^*\supsetneq K^{**}=K$ since dualizing is inclusion reversing and $K'$ is pointed since $K^*$ was full dimensional. (I guess the full dimensional assumption is not strictly necessary, but then we need to be careful about the vectors we choose.)
Comment: Thanks for this nice answer, could you please just tell me why pointed implies full dimensionality of dual and vice versa? Is it a theorem of sorts?
Comment: and could you please tell me why the inclusion you wrote implies inclusion in relative interior?
Comment: Take a line $L$ contained in a cone $C$. Dualizing reverses inclusion, so $ L\subset C \iff C^*\subset L^*$ and $L^*$ is a hyperplane given by $\{x\in(\mathbb{R}^*)^d\mid \langle x,l\rangle=0\}$ where $l\in L$ is any nonzero point.
Comment: We know $K\subset (K')^*$. Thus the relative interior of $K$ is contained in the relative interior of $(K')^*$. So if there is a point $p$ in $K\backslash ri((K')^*)$, then it must be a boundary point of both, so in particular there is some $x\in\mathbb{R}^d$ such that $\langle x,p\rangle =0$. But such a point is not in the interior of $K^*$, contrary to our choice of generators for $K'$.
Comment: thanks could you please tell me how do we obtain from your answer specifically that $ K \subseteq ri((K^*)') $? Because I need a pointed cone whose relative interior contains ours


Not sure about the limit of $\frac{\log(1+x^4)}{x^2 \tan^2(2x)}$ for $x$ that goes to zero

Question: I have to find the value of the function
$\frac{\log(1+x^4)}{x^2 \tan^2(2x)}$ for $x$ that goes to zero.
It's an undefined form $\frac{0}{0}$ so I transformed the function in this way in order to use two known limits
$$\frac{\log(1+x^4)}{x^2} \frac{x^2}{x^2} \frac{1}{\tan^2(2x)} \frac{4x^2}{4x^2} $$
and so
$$\frac{\log(1+x^4)}{x^4}\frac{4x^2}{\tan^2(2x)}\frac{x^2}{4x^2} $$
It seems to me that the value of the limit in zero is $\frac{1}{4}$ but looking to the graph of the function (using Desmos) it do not have a clear behavior in zero.
Can you tell me if my reasoning is right or wrong and, if wrong, where is the mistake?
Thank you.
ps. I found the problem with Desmos. In my notation I was using log for the logarithm with e as the base. But I should use ln in Desmos for the same logarithm, which otherwise is 10 based.
Comment: Your argument looks fine to me. Computer programs are not always reliable.
Comment: Something's off with the Desmos graph : it really should show a limit of $\frac 14$, but instead it shows something like $0.11$ or something, which is miles off. Wolfram Alpha does a better job of guessing the answer (without needing to zoom in).
Comment: The way you have used is very fine, by standard limits indeed

$$\frac{\log(1+x^4)}{x^2 \tan^2(2x)}=\frac14\frac{\log(1+x^4)}{x^4}\frac{4x^2}{\tan^2(2x)}\to \frac14 \cdot 1\cdot 1=\frac14$$
Answer: A systematic method is to use asymptotic development :
All development are undermeant to be done at $x=0$.
$$ \log(1+x^4)=x^4 + o(x^4) \sim x^4$$
$$\tan^2(2x)=(2x +o(x))^2 = (4x^2+o(x)) \sim 4x^2$$
Here by the use of only multiplicative operation  on equivalent :
$$\dfrac{\log(1+x^4)}{x^2\tan^2(2x)} \sim \dfrac{x^4}{x^2\times 4x^2}\sim\dfrac{1}{4} $$
Answer: To solve the Limit, I have used a method of series expansion. I have attached an image, kindly go through the solution.
Comment: Please do not use pictures for critical portions of your post. Pictures may not be legible, cannot be searched and are not view-able to some, such as those who use screen readers.


Azure B2C: email field is blank in MFA method EMAIL

Question: I am using B2C custom policies which allows users to sign-in with the username instead of the email. and select default MFA method.
When signing in and selecting Email MFA, I don't see the email populated.
I have implemented this policy: https://github.com/azure-ad-b2c/samples/tree/master/policies/mfa-email-or-phone
 <TechnicalProfile Id="EmailVerifyOnSignIn">
      <DisplayName>EmailVerifyOnSignIn</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=184.108.40.206, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
      </Metadata>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="readOnlyEmail" />
      </InputClaims>
      <OutputClaims>

        <OutputClaim ClaimTypeReferenceId="isActiveMFASession" DefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="readOnlyEmail" PartnerClaimType="Verified.Email" />
      </OutputClaims>
      <ValidationTechnicalProfiles>
        <ValidationTechnicalProfile ReferenceId="AAD-UserWriteMFAMethod"></ValidationTechnicalProfile>
      </ValidationTechnicalProfiles>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-MFA" />
    </TechnicalProfile>

    <TechnicalProfile Id="AAD-UserWriteUsingLogonName">
      <Metadata>
        <Item Key="Operation">Write</Item>
        <Item Key="RaiseErrorIfClaimsPrincipalAlreadyExists">true</Item>
      </Metadata>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" Required="true" />
      </InputClaims>
      <PersistedClaims>
        <PersistedClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" />
        <PersistedClaim ClaimTypeReferenceId="email" PartnerClaimType="strongAuthenticationEmailAddress" />
        <PersistedClaim ClaimTypeReferenceId="newPassword" PartnerClaimType="password" />
        <PersistedClaim ClaimTypeReferenceId="displayName" DefaultValue="SomeDefaultDisplayNameValue" />

        <PersistedClaim ClaimTypeReferenceId="givenName" />
        <PersistedClaim ClaimTypeReferenceId="surname" />
      </PersistedClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="newUser" PartnerClaimType="newClaimsPrincipalCreated" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
      </OutputClaims>
      <IncludeTechnicalProfile ReferenceId="AAD-Common" />
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
    </TechnicalProfile>
    <TechnicalProfile Id="LocalAccountSignUpWithLogonName">
      <DisplayName>User ID signup</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=188.8.131.52, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="IpAddressClaimReferenceId">IpAddress</Item>
        <Item Key="ContentDefinitionReferenceId">api.localaccountsignup</Item>
        <Item Key="LocalAccountType">Username</Item>
        <Item Key="LocalAccountProfile">true</Item>
        <Item Key="language.button_continue">Create</Item>
      </Metadata>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="signInName" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" Required="true" />
        <OutputClaim ClaimTypeReferenceId="signInName" Required="true" />
        <OutputClaim ClaimTypeReferenceId="newPassword" Required="true" />
        <OutputClaim ClaimTypeReferenceId="reenterPassword" Required="true" />
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="Verified.Email" Required="true" />
        <OutputClaim ClaimTypeReferenceId="executed-SelfAsserted-Input" DefaultValue="true" />
        <OutputClaim ClaimTypeReferenceId="newUser" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" />
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
        <OutputClaim ClaimTypeReferenceId="givenName" Required="true" />
        <OutputClaim ClaimTypeReferenceId="surname" Required="true" />
      </OutputClaims>
      <ValidationTechnicalProfiles>
        <ValidationTechnicalProfile ReferenceId="AAD-UserWriteUsingLogonName" />
      </ValidationTechnicalProfiles>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
    </TechnicalProfile>
    <TechnicalProfile Id="AAD-UserReadUsingUsername-NoError">
      <Metadata>
        <Item Key="Operation">Read</Item>
        <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">false</Item>
        <Item Key="UserMessageIfClaimsPrincipalDoesNotExist">An account could not be found for the provided user ID.</Item>
      </Metadata>
      <IncludeInSso>false</IncludeInSso>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" Required="true" />
      </InputClaims>
      <OutputClaims>

        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
        <OutputClaim ClaimTypeReferenceId="signInNames.emailAddress" />
        <OutputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" />

        <OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid" />
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="upn" />
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="givenName" />
        <OutputClaim ClaimTypeReferenceId="surname" />
        <OutputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" />
      </OutputClaims>
      <IncludeTechnicalProfile ReferenceId="AAD-Common" />
    </TechnicalProfile>
    <TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Username">
      <DisplayName>Local Account Signin</DisplayName>
      <Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=220.127.116.11, Culture=neutral, PublicKeyToken=null" />
      <Metadata>
        <Item Key="SignUpTarget">SignUpWithLogonUsernameExchange</Item>
        <Item Key="setting.operatingMode">Username</Item>
        <Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
        <Item Key="IncludeClaimResolvingInClaimsHandling">true</Item>
        <Item Key="setting.showSignupLink">false</Item>
        <Item Key="setting.enableRememberMe">True</Item>
        <Item Key="setting.forgotPasswordLinkOverride">ForgotPasswordExchange</Item>
        <Item Key="setting.forgotPasswordLinkLocation">AfterButtons</Item>
      </Metadata>
      <IncludeInSso>false</IncludeInSso>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="signInName" DefaultValue="{OIDC:Username}" AlwaysUseDefaultValue="true" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="signInName" Required="true" />
        <OutputClaim ClaimTypeReferenceId="password" Required="true" />
        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" />
        <OutputClaim ClaimTypeReferenceId="email" PartnerClaimType="strongAuthenticationEmailAddress" />
      </OutputClaims>
      <ValidationTechnicalProfiles>
        <ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
      </ValidationTechnicalProfiles>
      <UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
    </TechnicalProfile>
    <TechnicalProfile Id="AAD-UserReadUsingUserNameAndValidateStrongAuthenticationEmailAddress">
      <Metadata>
        <Item Key="Operation">Read</Item>
        <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
      </Metadata>
      <InputClaims>
        <InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="signInNames.userName" Required="true" />
      </InputClaims>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="objectId" />
        <OutputClaim ClaimTypeReferenceId="accountEnabled" />
        <OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
        <OutputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" />
        <OutputClaim ClaimTypeReferenceId="displayName" />

      </OutputClaims>
      <OutputClaimsTransformations>
        <OutputClaimsTransformation ReferenceId="AssertEmailAndstrongAuthenticationEmailAddressAreEqual" />
        <OutputClaimsTransformation ReferenceId="AssertAccountEnabledIsTrue" />
        <OutputClaimsTransformation ReferenceId="CreateSubjectClaimFromObjectID" />
      </OutputClaimsTransformations>
      <IncludeTechnicalProfile ReferenceId="AAD-ReadCommon" />
    </TechnicalProfile>
    <TechnicalProfile Id="AAD-ReadCommon">
      <Metadata>
        <Item Key="Operation">Read</Item>
        <Item Key="RaiseErrorIfClaimsPrincipalDoesNotExist">true</Item>
      </Metadata>
      <OutputClaims>
        <OutputClaim ClaimTypeReferenceId="userPrincipalName" />
        <OutputClaim ClaimTypeReferenceId="displayName" />
        <OutputClaim ClaimTypeReferenceId="otherMails" />
        <OutputClaim ClaimTypeReferenceId="strongAuthenticationEmailAddress" PartnerClaimType="signInNames.emailAddress" />
      </OutputClaims>
      <OutputClaimsTransformations>
        <OutputClaimsTransformation ReferenceId="CreateOtherMailsFromEmail" />
        <OutputClaimsTransformation ReferenceId="CopyEmailToReadOnly" />
      </OutputClaimsTransformations>
      <IncludeTechnicalProfile ReferenceId="AAD-Common" />
    </TechnicalProfile>

Answer: •   It is because when you are using the 'B2C_EmailOrPhoneMFA policy' you are using the extension attributes for storing the extension properties and adding the application ObjectID due to which it is being considered as untrusted domain application since the session is interrupted by closing and reopening the same due to which the session token might be considered expired/invalid immediately. As a result of which, the 'email' claim is not getting populated.
•   Also, since you are using the user flow through the custom policy, the cache regarding the user's email ID entered in the first step is not stored in the browser cache according to the 'UserJourney' path defined in the custom policy. Thus, would suggest you to please ensure that the below 'ClaimsProvider' section is included in your custom policy for the email ID to be remembered through the 'LocalAccountSignIn' technical profile Id: -
<ClaimsProvider>
<DisplayName>Local Account</DisplayName>
<TechnicalProfiles>
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Email">
  <Metadata>
    <Item Key="setting.enableRememberMe">True</Item>
  </Metadata>
</TechnicalProfile>
</TechnicalProfiles>
</ClaimsProvider>

Please find the below link for more details regarding the above: -
https://learn.microsoft.com/en-us/azure/active-directory-b2c/session-behavior?pivots=b2c-custom-policy#add-the-metadata-to-the-self-asserted-technical-profile
Thus, by following the above, you should be able to populate the email ID automatically in the user flow of the custom policy.
Comment: In my policy users are signing in with username not email, already tried the provided TP,no joy
Comment: Do you mean to say KMSI option with remember the user email even though user dont select KMSI checkbox? by the way KMSI option in already active in my policy and its not helping with the  issue.
Comment: Ok...Kindly please try using the given technical profile in your custom policy, may be it will be of help to you since it is about remembering the local account signin email.


Positioning gameobject from canvas to a 3D gameobject (Unity 3D)

Question: I'm a newbie in Unity, I can't figure out how to get the position of 3D GameObject relative to the Camera or the Canvas.
I know that Camera.main.ScreenPointToRay(target) can be used to get the position of a GameObject. Is there a way to get the Position of a GameObject on Camera View or Canvas?
I have already made an alternative solution by just

Moving the image outside the Canvas.
Creating a Blind Image positioned on Target 3D GameObject.

But I don't like both.
Answer: I have recently spent some time with this very problem.  My intention was to position a 2D arrow over a 3D world object and found using Camera.WorldToViewportPoint() and RectTransform.anchorMin/Max to be the best solution.
Note that viewpoint point is normalized (0.0 - 1.0) and not an absolute pixel position:
Vector3 screenPos = Camera.main.WorldToViewportPoint(someObject.transform.position);
arrowImage.rectTransform.anchorMin = screenPos;
arrowImage.rectTransform.anchorMax = screenPos;

Answer: If you want to get the game object's position projected onto the canvas, use below code:
var pos = gameObject.transform.position;
var vec2 = RectTransformUtility.WorldToScreenPoint(camera, pos);
Debug.Log(vec2);

In another case, if you want to get the screen coordinate of a UI-game object, try below:
public static List<Vector2> GetScreenCoordinateOfUIRect(RectTransform rt)
{
    Vector3[] corners = new Vector3[4];
    rt.GetWorldCorners(corners);

    var output = new List<Vector2>();
    foreach (Vector3 item in corners)
    {
        var pos = RectTransformUtility.WorldToScreenPoint(null, item);
        output.Add(pos);
    }
    return output;
}

In this way, you can get the screen points of a UI game object (who has a RectTransform component), with bottom left as origin. Note that this screen point is independent of the anchor points, in all anchor point settings, this function works!
Comment: You haven't shown how to position the 2D object, and when you do you will probably find that it doesn't work.  I know, as I have been through this myself.
Comment: how to position the 2D object? Mind clarify what you mean?
Comment: Well I am assuming the OP wants the position on the UI so that he can place a 2d sprite at that position.  That part of the problem is not trivial.
Comment: It depends on the nature of the so called "GameObject" in the OP. If this refers to the UI game object, of course, this is a different story, but I think the OP means non-UI (3D) game object.
Comment: MyObj.transform.position = Camera.main.WorldToScreenPoint(NonUIGameObj.transform.position);  "WorldToScreenPoint" is just what I need. thank u.
Comment: Sorry for your misunderstandings. But its clear enough that the UIGameObject was within the hierarchy of the Canvas. And I was really pertaining to a non-UI GameObject which was called World Object in unity.


geometric question (About Pythagoras theorem) I might need two different method each

Question: Question 1:ABCD is a square and GDEF is a rectangle $BE=1,EC=3 $ find the length of GD
Question 2: ABCD is a right trapezoid, $CD=BC=10$ ,ABE is an equilateral triangle, please find the length of AB.
Answer: 1) Triangle $ADG$ is similar to $EDC$. Hence:
$$
GD:DC=AD:DE,
\quad\text{that is:}\quad
GD:4=4:5.
$$
2) If $AD=x$ and $DE=y$ then by Pythagoras' theorem:
$$
x^2+y^2=10^2+(10-y)^2=10^2+(10-x)^2.
$$
Comment: why is ADG similar to EDC?
Comment: They are both right triangles, and in addition $$\angle GDA=\angle GDE-\angle ADE=\angle ADC-\angle ADE=\angle EDC.$$
Answer: This is for part $1$ only
$$BE+EC=1+3=4$$
$$ED^2=EC^2+CD^2=9+16=25 \implies ED=\sqrt{25}=5$$
$$AG=\frac{ED}{2}=\frac{5}{2}=2.5$$
$$AD-CD=4$$
$$GD^2=AD^2-AG^2=4^2-2.5^2=16-6.25=9.75 \implies GD=\sqrt{9.75}=3.122498999$$
Answer: Question 1:
Since BC=4=AB, the distance AC is $4\sqrt 2$. Also, CDE is a 3-4-5 triangle, of area 6.  So if DE is its base, then $A=\frac 12 bh$ gives its height to be 2.4.  That means that the distance GD, which is equal to the distance from A to the intersection of DE with AC, is $4\sqrt 2 - 2.4$.
Hint for question 2:
The bottom white triangle gives you:
$10^2 + CE^2 = ANS^2$
The top white triangle gives: $(10-CE)^2+AD^2=ANS^2$
You can figure out AD by setting up trigonometric identities.
Now, solve this system of equations.
Comment: Q1: $AC$ is not perpendicular to $DE$, so your approach is not valid.


I can't create a document in my couchdb database

Question: I am new to web engineering and databases and I hope this is the right place for my question.
I am trying to create a database with couchdb but unfortunately I can't create a document with more data than the id. If the document contains just the id, then the "create document" function works.
I am really confused and do not know if I miss something.
Here is a link to a video, where I am showing my problem.
https://www.youtube.com/watch?v=24X3dk1j4WM&feature=youtu.be
Thank you for any answer that could possibly help me.
Comment: In any case, you need a comma between each key/value pair
Comment: The JSON is invalid, which is preventing the form from being submitted. That's not great UX, as I would expect it to print an error or something, maybe check the console.
Answer: As mentioned in the comments, you are missing a comma. Try this:
<code>{
    "_id": "my_doc", // => notice comma
    "number": 23
}

</code>


I'm trying to use GridbagLayout to display 2 columns of JLabels inside of a ScrollPane. What part of my code is stopping the intended results?

Question: I'm working on a program that deals with lists of jobs with a list of contractor names for each job. This part of the program will take two lists, one with an old set of contractor names and one with an updated list of names and display them next to each other. The setup for it is a JFrame with a JScrollPane inside and a JPanel inside the viewport. The JPanel uses a GridBagLayout to display the two lists with the old list in column 0 and the new list in column 1. When the program runs, the two lists are in the same column. I cannot tell what makes it do this.
private void displayUpdateInfoFrame(ParseFullDoc updatedDoc) {

    // set up the frame
    JFrame updateInfoFrame = new JFrame() {
        {
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setTitle("Update Information");
            getContentPane().setLayout(new GridBagLayout());
            setSize(1250, 600);
        }
    };
    ArrayList<Job> oldJobs = parseFullDoc.getJobList();
    ArrayList<Job> newJobs = filterUpdatedJobs(updatedDoc);

    final ArrayList<JLabel> jobLabels = new ArrayList<JLabel>();
    final ArrayList<Status> jobLabelStatus = new ArrayList<Status>();

    GridBagConstraints infoConstraints = new GridBagConstraints();

    ArrayList<JLabel> newJobLabels = getInfoLabels(JOBSET.NEW, oldJobs, newJobs, jobLabels, jobLabelStatus);
    ArrayList<JLabel> oldJobLabels = getInfoLabels(JOBSET.OLD, oldJobs, newJobs, jobLabels, jobLabelStatus);

    JScrollPane infoScrollPane = new JScrollPane();
    JPanel infoPanel = new JPanel(new GridBagLayout());

    for (int oldIndex = 0; oldIndex < oldJobLabels.size(); oldIndex++) {
        infoConstraints.gridx = 0;
        infoConstraints.gridy = oldIndex;
        infoPanel.add(oldJobLabels.get(oldIndex), infoConstraints);
    }
    for (int newIndex = 0; newIndex < newJobLabels.size(); newIndex++) {
        infoConstraints = new GridBagConstraints();
        infoConstraints.gridx = 1;
        infoConstraints.gridy = newIndex;
        infoPanel.add(newJobLabels.get(newIndex), infoConstraints);
    }
    GridBagConstraints infoFrameConstraints = new GridBagConstraints();
    infoFrameConstraints.gridx = 0;
    infoFrameConstraints.gridy = 0;
    infoFrameConstraints.fill = GridBagConstraints.BOTH; // Fill both horizontally and vertically
    infoFrameConstraints.weightx = 1.0; // Expand horizontally
    infoFrameConstraints.weighty = 1.0; // Expand vertically

    infoScrollPane.setViewportView(infoPanel);
    updateInfoFrame.add(infoScrollPane, infoFrameConstraints);
    updateInfoFrame.setVisible(true);
}

I first tried two scroll panes next to each other, but only one showed on the frame. I've tried to exclude the scroll pane, with only the JPanel inside the frame, but it still shows the two lists in the same column. I've tried to add a column in between the two lists, but it still doesn't show properly.
Answer: Rather than using a collection of JLabels, I suggest using two JLists, each in its own, separate JScrollPane and put those two JScrollPanes in a JPanel with GridLayout.
Here is a complete example.
(Note that I simply hard-coded two lists.)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class TwoLists {

    private void createAndDisplayGui() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createLists(), BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JScrollPane createList(List<String> elems) {
        String[] arr = elems.toArray(new String[]{});
        JList<String> list = new JList<String>(arr);
        JScrollPane scrollPane = new JScrollPane(list);
        return scrollPane;
    }

    private JPanel createLists() {
        JPanel panel = new JPanel(new GridLayout(0, 2));
        panel.add(createList(getOldList()));
        panel.add(createList(getNewList()));
        return panel;
    }

    private List<String> getNewList() {
        return List.of("new 0", "new 1", "new 2", "new 3", "new 4");
    }

    private List<String> getOldList() {
        return List.of("old 0", "old 1", "old 2", "old 3", "old 4");
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new TwoLists().createAndDisplayGui());
    }
}

Here is a screen capture:


Wrapping HTML table rows in  tags

Question: Is it possible to wrap entire table rows in  tags? I want the the entire row to be a clickable link.
If I try the following, the links get rendered above and outside the table:
This:

value	value

value	value

Renders like this:

value	value

value	value

Comment: It would be quite nice to mention HTML version
Comment: You can check [THIS](http://stackoverflow.com/questions/4369206/wrapping-a-table-row-in-a-element-hyperlink-in-html5) question
Answer: Edit 2021:
It seems nowadays there's better options that are more semantic and more screen-reader-friendly. Check out e.g. Jans solution.
Original answer:
as a link in each td is not a good alternative and using js is a bit dirty, here is another html/css approach:
HTML:

...

...

...

CSS:
.table { display:table; }
.table-row { display:table-row; }
.table-cell { display:table-cell; }

Comment: This is not a good approach. This is not semantic and will not work nicely with screen readers.
Comment: You could explore the use of aria-role to make it more accessible to screen readers.
Comment: This solution breaks the web. Only use if you have no care for accessibility or usability.
Comment: What if I'm using html for mailing? :D
Comment: In Mails you definitely can't use JS, and I think many clients need to have the styles inline (style="" in each html tag)
If this solution still doesn't work, you could give a try to use divs with fix widths and float, but I can't guarantee it works, html support in mail clients is a real pain actually
Comment: If your're using Bootstrap 4 these are builtin as helper classes : https://getbootstrap.com/docs/4.0/utilities/display/#notation
Answer: It renders like that because the browser is respecting the W3C specification and only allowing
 tags as direct descendents of
.
As a solution, you could either put an  tag inside each  that points to the same URL:

                First column

                Second column

Or you could bind an onClick handler to the
 with JavaScript. A jQuery example would be this:
$('table tr').click(function() {
    window.location = 'http://location/here';
});

Or, even better, use delegated events (jQuery 1.7+):
$('table').on('click', 'tr', function() {
    window.location = 'http://location/here';
});

Comment: We used the Javascript version once and regretted it. Users can't Ctrl-click or Shift-click to open in new tab/window. Worth noting that; it might even be desirable in your app/site.
Comment: @BernhardHofmann it is possible to catch the `event` on click and test for `event.metaKey` or `event.ctrlKey`, but I agree, it isn't quite ideal as sometimes it may be blocked by popup blockers. http://stackoverflow.com/a/2445640/436014
Comment: Thanks for laying out all possible solutions
Comment: @waffl And then it still doesn't work for middle click (which I use extensively). Or right click -> open in new tab. Also, no browser link target preview on hover. JS links are always a pain :(
Answer: Another simple, CSS only solution is turning  into block elements

  name 1	link 1

  name 2	link 2

The CSS would be:
td > a {
  display: block;
}

Then the  would take up the entire , and making entire row clickable without JS if the link is repeated for each cell in a row.
https://jsfiddle.net/evwa451n/
Comment: @IanGoldby What is a "-ve margins"?
Comment: As soon as any of the text wraps, this no longer works properly as the anchor doesn't fill the cell: https://jsfiddle.net/950c1284/.  This works however: https://stackoverflow.com/questions/3966027/make-link-in-table-cell-fill-the-entire-row-height#15801081.
Comment: Great idea. Using padding on the cells reintroduces non-clickable gaps, so put a equal -ve margins on the `td > a` rule to close up the gap again, then reapply the padding on the `td > a` rule.
Comment: @ChuckD exactly what it says. Set the margin to a negative amount equal to the padding, e.g. padding 4px and margin: -4px
Answer: It's invalid HTML to have any elements other than thead,tbody or tfoot as a direct child of a table, and those elements have only tr as their valid children.
Any other content must be inside of a td or th to be valid.
What you're seeing is the browser restructuring your DOM so that it's as valid as it can be. The problem with relying on that behaviour though is that different browsers react in different ways.
If you need a tr to be interactive (and for clicks on those elements to lead somewhere/do something) you should use JavaScript.
But, short answer, yes you can do it, but it's not valid to do so, so please don't.
For interactive table rows, though, one solution (in plain JavaScript):
var rows = document.getElementsByTagName('tr'),
    url;

for (var i=0,len=rows.length; i<len; i++){
    rows[i].onclick = function(){
        uri = this.getAttribute('data-url');
        window.location = uri;
    };
}

JS Fiddle demo.
(Which, obviously, requires that the tr elements have a data-url attribute to specify where they should link to.)
Comment: Much better to add one click handler on the table itself and use event delegation and the target to find out which row was clicked.
Answer: New and even better solution using CSS Subgrids (I'm excited):
We can now use Subgrids for our table rows. This way we can also add hover states or paddings to the individual rows.

Header column 1

Header column 2 (Any content size works)

Header column 3

Every column adjusts dynamically

Content 2

Content 3

Content 1

Content 2

Content 3

Content 1

Works like a table!

Content 3

New and fancy solution: It is funny that in 2021 there is still no clean solution for table rows with links - I advice you to use display grid instead. Using repeat(YOUR_COLUMN_COUNT, minmax(0, auto)) for grid-template-columns achieves a grid to behave really similar to a table - you get auto sizing and adjusting columns. In addition you can use anchor tags and even create a sticky header without going insane:

Header column 1

Header column 2 (Any content size works)

Header column 3

Every column adjusts dynamically

Content 2

Content 3

Content 1

Content 2

Content 3

Content 1

Works like a table!

Content 3

Update: Unfortunately the original solution below does not work unless the table rows are dynamically inserted with javascript (see example below). Browsers skip the syntax check when new elements are inserted via javascript, so that way it is possible to get the anchor tags to stay in the table and prevent the browser from moving them outside.

let tbody = document.getElementById("myTBody");

for (let i = 0; i < 2; i++) {
  let anchor = document.createElement("a");

  anchor.setAttribute("style", "display: contents;");
  anchor.setAttribute("href", "https://example.com");

  let row = document.createElement("tr");

  let col1 = document.createElement("td");
  let col2 = document.createElement("td");
  col1.append(document.createTextNode("Column 1"));
  col2.append(document.createTextNode("My longer Column 2"));

  row.appendChild(col1);
  row.appendChild(col2);

  anchor.appendChild(row);
  tbody.appendChild(anchor);
}

This table doesnt work with anchors around the rows:

      Column 1
      Column 2

        Column 1
        My longer Column 2

        Column 1
        Column 2

This table does work with anchors around the rows:

      Column 1
      Column 2

Original: You could also use display: contents;. This causes the a tags childs to behave like they are a child of the a tags parent.
In your HTML:

      Column 1
      Column 2

        Column 1
        Column 2

        Column 1
        Column 2

Support in different browsers should be enough most of the times (see https://caniuse.com/#feat=css-display-contents).
Comment: I think this is the best non-javascript solution; however, beware that the anchor tag is NOT included in the accessibility tree [this is a current bug in most browsers, it should be included] (see MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/display#display_contents)
Comment: I don't get why this is upvoted? This does not work in any browsers i've tried, Chrome, Firefox or Safari?
Comment: @lowkey is actually right. I just tried the code in a standalone html file and it does not work. The browser just moves the anchor tags outside of the table. **Whats strange here** - In my vue projects the markup stays like written in the file and the anchor tags do not move out of the table. So when using vue the markup above works perfectly fine. Does anyone have an idea whats going on here?
Comment: I updated my answer to address the originally provided wrong answer and suggested a really nice alternative way to html tables (imo).
Answer: You could use onclick, so you can get the content dynamically
Hello

http://jsfiddle.net/ankJw/
Comment: The only change you need to make to this is to have the `onClick` handler in the ``, instead of the ``; the OP wants to make an entire table row clickable.
Answer: Why you don't want to make click event on tr ? It's not possible to have anchor tag like you want so you can make click event and add aditional CSS for making it to look like anchor.
Jquery:
$("table tr").click(function() {
    window.location = "http://www.google.com/";
});

Comment: Because you don't know where you are going (hover and see url, like in an anchor tag), you can't right click and copy url, you cant open in a new tab, etc...
Comment: Apparently i have to- but you always look for the non-js solution first
Answer: Just in additional to others I have to add that I personnaly prefer to do like this

  Text...

in case of ASP.NET MVC do it like

Answer: The solutions provided here helped me, but I don't think that using window.location is a good approach because user cannot do ctrl+click, open in another tab, or see where the url is going to. I'm building this page and I like to see the url built without clicking it, and chrome shows this on hover. I could not get over this, so I decided to use @Bojangles suggestion above to wrap each td with a link.
First, add the data-href to each tr, as others suggested.
Then, wrap each td in a link via js:
    jQuery(document).ready(function ($) {
        //wrap each td's contents with a hyperlink targeting the data-href
        $('*[data-href]').children("td").wrapInner(function () {
            return "";
        });
    });

optionally, use css to make the hyperlink use up all of the cell
    table tr a {
        display:block; /*the link occupies the whole cell, so it's all clickable*/
    }

Wrapping HTML table rows in  tags


Can we use a hook_update_N for a module without hook_install?

Question: I am working on a custom module which does not have an install file but nevertheless uses a lot of tables. The one who worked on it previously, created the database tables manually. Now I want to add more tables to it. I could run the query manually to get the job done but I wanted to use the 'Drupal' way to do that. So I was wondering if we could use a hook_update_N for a module without hook_install?
Answer: No module needs to implement every hook. You can use hook_update_n() and not have a hook_install() function just fine.
You'll probably at 1 point want to define hook_schema() for these tables. An easy tool to get the "drupal" schema for any mysql table (already defined) in your mysql database is the Schema module.

Schema documentation: hyperlinked display of the schema's embedded
  documentation explaining what each table and field is for.
Schema
  structure generation: the module examines the live database and
  creates Schema API data structures for all tables that match the live
  database.
Schema comparison: the module compares the live database
  structure with the schema structure declared by all enabled modules,
  reporting on any missing or incorrect tables.

Note for MySQL users:
  The Schema module requires MySQL 5. Prior versions of MySQL do not
  support the INFORMATION_SCHEMA database that the Schema module uses to
  inspect the database.


Can anyone provide step by step process to implement SAML

Question: I have a situation where I currently call web focus reports from our JAVA web applications. But is not a secured way calling and I wanted to implement SAML authentication and pass parameters through SAML. Any help in this regard will be great help
Answer: Is there a reason you need SAML?
OpenID Connect is a much easier option.
For SAML, you need to implement a SAML stack.
There is more information here.
Comment: I need SAML to provide more security to WEBFOCUS calls from JAVA. I want to achieve this through passing SAML tokens instead of POST parameters which are exposed to USER.


Why was my factually correct answer deleted by the moderator?

Question: I answered this question with a factually correct answer, providing links and references. It was downvoted and deleted by the moderator with no comments or explanations.
Why was it deleted, and why are moderators allowed to behave in such an abusive manner?

The mod below admits that they were in fact somehow triggered by me mentioning the fact that the US is not very welcoming towards immigrants, but doesn't explain why they think they have the right to delete my post just because they personally don't like me pointing out facts they feel put them in not the best of lights they want.
Saying that US is not very welcoming to immigrants seems pretty on-topic for an expats forum in an answer explaining why it is not easy to immigrate to the US.
Comment: Worth noting that while my factually correct answer was summarily deleted, misleading and even plainly false comments still remain and are even upvoted by the community
Answer: I'm the moderator who deleted it. Yes, it did have the correct facts to answer, and I admit to wrestling between editing it and deleting. The downvotes were obviously coming in, and I'm surprised it wasn't flagged. The problem I had with editing it was really a problem that the answer itself introduced, that of being a political/cultural attack. I could have easily edited it (and maybe that was better thing to do - I don't know for sure), but then isn't that then just implicitly applying my own political/cultural opinion by erasing yours out? That didn't feel right either. I eventually decided that deleting was the option I would go with. My thinking was that this could be handled like a question close. If the political/cultural attack is removed, I'm quite happy to undelete it.
So why did I moderate this at all? Well we moderators are human and we bring our baggage with us just like anybody else. I've been highly active on an immigration site that tacitly allowed political and cultural attacks on nationalities. And nobody was safe. Things got nasty, and it drove me and many other long term contributors away. Moderation finally caught up and put the hammer down on it hard. Really hard. But that damage that was done has never really been undone. I just don't want to see that happen to this site. I know that at times there is a thin line between valid criticism and pointless off-topic attacks. This is not a new thing here. Immigration policies and their enforcement are easily intertwined with the politics and deeply rooted culture of any nation. It can be hard to be objective even for those of us who strive the hardest to be so, and usually are very successful at it.
In my opinion, and from my previous bitter experiences, this post crossed that line. If you wish to opine your grievances (which may indeed be justified) about the politics and culture of current American policy with regards to illegal immigration, we can head on over to Politics.se and have at it. This forum is not for that sort of discussion, and as a moderator, I'd like to keep it that way as much as we reasonably can.
(I should note, that even at Politics.se, there's a good chance that your post gets the same treatment over there, likely flagged very quickly. The mods very obviously have their own agendas and politics. Just like us here, they're human. But they do make a rather strenuous effort to also keep this kind of stuff off their site - even stuff they so very clearly agree with -, and with good reason).
Here's a snapshot of the answer in dispute for those who can't see it:
Comment: The assertion that the US has *literally started killing people…* plus its hostile tone is why I downvoted the answer. If the answer had just consisted of the first two, factually correct, paragraphs I would have upvoted it. As it stands, FWIW I agree with the deletion.
Comment: @littleadv the article you linked to does not support the assertion that the US has started killing people trying to cross the border illegally.  It is not definitively known how the person whose death is reported died.  The barrier in which his body was found is opposed by the United States, which the article reports has filed a lawsuit seeking its removal.  The tone is not the only problem with that part of the answer; it is not as you claim "factually correct."  It's also irrelevant to a question from someone seeking a visa.
Comment: These are not grievances but statements of fact. Someone considering dealing with the US immigration system should be made aware of them. I have not said anything of opinion, what exactly triggered you? It's not the first time that anything that may be even remotely interpreted as negatively describing the US is being taken here as a personal attack. It's not, it's just a description of the current state of affairs.
Comment: @littleadv, Fair enough. We'll let them get involved.
Comment: @littleadv, "why is my answer not restored yet?" You said you have contacted the T&S team. I'm waiting for their response and involvement.
Comment: @littleadv, I stand by my decision. And you are the one who contacted SE bureaucracy. I've already made what I believe to be a reasonable compromise.
Comment: "The US is generally very hostile to immigrants". So this is a 'trigger' for anybody. Just insert the nation of your choice, post some links to back up your trigger, and dare anybody to challenge. It's not even that I disagree with you. I have my own grim opinions about my home nation's behavior toward illegal immigrants. But, your answer, sans this attack stands on its own. I could have edited the attack out, but that felt like I was applying a different political opinion, one which I might not even agree with. No. I deleted. If you want, I'll edit it and undelete. Is that alright?
Comment: It's a fact and a clear policy. You'll undelete. Period. Nothing to edit. I already filed a ticket with the T&S team, you've clearly overstepped.
Comment: @littleadv please clarify, did the unfortunate wannabe undocumented immigrant intend to become a "digital nomad"?
Comment: @littleadv OK, but was his intention to become one?
Comment: @littleadv You understand my question but refuse to answer... OK. How does your claim that "The US is generally very hostile to immigrants" jive with https://www.migrationpolicy.org/programs/data-hub/charts/Annual-Number-of-US-Legal-Permanent-Residents "The United States attracts the largest number of immigrants in the world"? Are they lying about this? Is there another country that admits more immigrants than the US?
Comment: @littleadv, I have heard nothing from T&S on this. Until I hear otherwise, I will stand by this decision. I'm happy to discuss this matter with them at their convenience. They need only ping me.
Comment: @phoog I have clarified that part. The barrier was installed by Texas government, and includes bouyes and razor wire both designed to physically harm people reaching it. The governor explicitly said that his intention is to prevent migrants from passing, and called them "invasion". Several governors have engaged in kidnapping and trafficking migrants. If that's not hostile then I don't know what is. These actions are actually widely supported in the US and these governors are doing these things expecting rewards election time.
Comment: @DimitriVulis there's no such thing "digital nomad" in the US law. It's a concept invented by people who try to whitewash violations of tax and immigration laws.
Comment: @DimitriVulis becoming what? migrant worker arriving to the US without a proper visa? Yes, very likely.
Comment: @DimitriVulis "*attracts*" and "*welcomes*" are not the same things. As an immigrant in the US I can tell you that it's laws are extremely hostile and geared towards reducing immigration, not encouraging it. More than that - they're also overtly racist, specifically targeting populations from India, China and several other countries, while favoring populations from Europe and Canada. Notice that the graph shows that the amount of new LPRs per year now is the same as it was almost a hundred years ago, while world population since then quadrupled.
Comment: @DimitriVulis as to your question - I answered it. You just don't want to admit that "digital nomad" and "illegal immigrant" are the same things, first is used for rich spoiled westerners, and the second for the poor brown people.
Comment: @ouflak why is my answer not restored yet? And why, instead, I'm submitted to this pointless ridicul of your posse?
Comment: @ouflak and you can't do the right thing without being formally ordered to do so why exactly? You made a mistake - own it, don't hide behind the SE bureaucracy.  You can also clean up all the reprehensible and abusive comments here, as well, since that's literally your job.
Comment: Your compromise was to delete my answer without any notice or explanation other than "you dared to trigger some MAGA redneck snowflake". Thank you for your consideration. I hope you are fired as quickly as you've abused me here.
Comment: @ouflak pinging again. T&S said that you may undelete it. You've admitted your wrongdoing and admitted your bias. Correct your mistake.
Answer: The conclusion from the discussion in this thread is that the mod deleted my answer because they didn't like it. The mod admits that it was in fact factually correct. They just felt that it shows the US not in the best light, so it was doomed. Apparently, anything that can trigger an American to think that their country is less than perfect is forbidden and will be deleted immediately even if the mod themselves admits that they're not actually disagreeing with the facts.
I've raised the issue with the SE T&S team, and I hope the offending mod will be promptly removed from the position they so blatantly abused.


Minha função JavaScript/AJAX não está convertendo Date no formato correto

Question: Olá
Estou com um problema num projeto MVC. Minha View precisa retornar valores em Data para alguns Text Boxes (a partir da seleção do registro por uma Data Table) para que o usuário possa fazer o edit do registro.
O problema é que os dados não estão sendo mostrados no formato correto. As TextBoxes mostram Strings estranhas como essa no lugar:

/Date(1515290400000)/

Minha função JavaScript está assim:
function GetDepSecById(DepartmentSectionId) {
$.ajax({
    url: urlGetDepSecById,
    data: { DepartmentSectionId: DepartmentSectionId },
    type: 'POST',
    success: function (result) {

        $('#DepartmentSectionId').val(result.DepartmentSectionId);
        $('#ObsoleteDate').val(result.ObsoleteDate);
        $('#StartPeriodDate').val(result.StartPeriodDate);
        $('#EndPeriodDate').val(result.EndPeriodDate);

        DatePickerPadrao($('#ObsoleteDate'));
        DatePickerPadrao($('#StartPeriodDate'));
        DatePickerPadrao($('#EndPeriodDate'));
    }
  });
}

O método DataPickerPadrao é o que deveria ser responsável por converter a Data. Ele está dentro de outro JS no projeto:
function DatePickerPadrao(control) {
control.datetimepicker(
{
    locale: 'en-US',
    format: 'MM/DD/YYYY'
});
}

Comment: Pode mostrar um exemplo de como chega a data em `result.ObsoleteDate`?
Comment: No Script da Controller deste método JsonResult GetDepSecById, a ObsoleteDate retorna o dado {11/07/2018 13:35:26}. No entanto, na TextBox da View onde esse valor é jogado é mostrada esta string: /Date(1531326926000)/
Answer: Basta você pegar o retorno e converter para data usando parseInt. Antes remova as barras. Veja um exemplo:

var retorno = "/Date(1531326926000)/";
// remove as barras com o Regex, ou pode ser um replace também
retorno = retorno.replace(/[^0-9 +]/g, '');
// converte o formato numérico para data
var data = new Date(parseInt(retorno));
console.log(data);

//se quiser no formato texto:
console.log(data.getDate() + "/" + (data.getMonth() + 1) + "/" + data.getFullYear());

Uma sugestão para trabalhar com datas é usar o moment.js, que tem métodos para formatar e converter, simples de usar: http://momentjs.com
Comment: Muito obrigado, deu certo! Tanto sua solução quanto usando por moment.js


Why "gofmt -d" gives "computing diff: exec: "diff": executable file not found in %PATH%" error on windows?

Question: I would like to see what mistakes I made in my golang files. In order to figure it out, I issue a command like this:
gofmt -d myfile.go

According to the gofmt --help manual, it is supposed to list the diff of the current and the desired versions of the file. Instead of this, it produces this error message:
computing diff: exec: "diff": executable file not found in %PATH%

How could this be fixed?
Answer: The gofmt tool assumes the system has an installed and available diff. Unfortunately, this tool is not part of a standard Windows installation so you need to add it manually.
For most of us, the easiest way to add the path of the diff tool we already have on our computer. This is the one that has been installed as part of git. (If git hasn't been installed yet then do it at first.)
In order to solve this, you should issue a command from the DOS prompt in which you want to execute gofmt:
set PATH=%PATH%;c:\Program Files\Git\usr\bin

(Maybe you need to change the path according to your git installation.)
For a more permanent solution, you should add the path of diff.exe to the PATH environment variable via the Control Panel.


Estimate values of missing features. Output label and trained model given

Question: This is my first post at Cross Validated. I was having a doubt and hoped it can be cleared instead of stackoverflow.
Currently I'm working on a Predictive Model, which takes in server performance and classifies them weather there is an error in server or not. (Using RandomForest. Planning to change to NN).
My data is timeseries. Let us say our model predicts an error at t1 hours. When error is predicted, I take our feature score for that predictor. The top features are largest influencer for prediction. So, when error is predicted since I've to send out alert to support teams, I needed some more information for them to work on.
I was thinking of implementing something like this:
Lets say when error is predicted, (Label = 1), we take out top 3 features (x, y, z). We then make it blank(consider missing). I've a trained RF model which was used to make predictions. Is it possible in any way to calculate expected values of x,y,z from trained model, if Label was specified?
It is something like backpropogation. Estimating values of missing features (x,y,z) if Label is given(=0. i.e. expected value for no error) and some features are given? (n:total features. Given : n-3 features).
I was thinking of implementing Regression separately on each feature, but that seems like tedious work, plus every feature fitting into regressor isnt a guarantee.
It is something like this following equation in lay man words.:
eqn : 2a+3b+c+9x+10y+30z^2 = output.
Given : a, b, c, output.
Given : Trained model
Calculate : x, y, z.
Equation, of algorithms, or anything to guide me in right way will be really helpful. I'm working on python.
Any help will be greatly appreciated.
Thanks in advance,
PS : If any doubt, or any issues with question, kindly post it in comments, so that I can edit the question. This is my 1st post here. Thanks.
Answer: I think you're asking for a conditional expectation of your label as a function of the features. In any classic regression framework this would be a reasonably straightforward exercise using the model coefficients and whether or not a feature was "on" or "off." In the context of RFs, since the predictions aren't based on a single "model" but represent an aggregated value over many, many "mini-models" -- in other words, the label prediction's relationship with a feature is no longer a simple 0, 1. Your description of a possible solution sounds like it is based on an unconditional arithmetic average and ranking of the "importance" of the features given the prediction, which isn't terribly insightful.
You didn't say it, but I think I understand why you're using RFs -- you have too many features to fit into a reductionistic, statistical model.
My opinion is that you're going to have to switch out of RFs to a different modeling framework to do what you want to do, but I could be wrong and would be interested in hearing other posters workarounds to an RF-based solution to the OPs question.
Comment: Hi, Something of that sort. I m expecting expected value of feature so that I get a particular label as output. In my case, if label classified is 1, what should be values of top features so that my label will be 0, and not 1. I meant that. Regarding RF, I have unbalanced dataset. (1:110 initially. Now 1:20). Though I'm open to other models, and I am currently playing around with NN. Any model which can help me find expected value of missing features, I'm open to implementing those.
Comment: So, you have 1 observation for 20 features? How big is *n*x*p*, in total?
Comment: No, I meant class ratio in dataset. Current dataset:
Features : 66
Rows : 14k approx.
Class 1 Label : 500
Class 0 Label : 13.5k.
Class ratio : 1:27.
Comment: Check out David Dunson's paper on *Bayesian Tensor Regression* on his website at Duke... http://www.researchgate.net/profile/David_Dunson/publications He's developed an approach designed for genome mapping when *n* is small and *p* is massive.


Share data file (yml) between 2 GitLab projects

Question: I have 2 GitLab projects (static sites), that need to share the same yaml file. Currently the yaml file exists in project A, and project B manually clones it every week or so. I want to be able to have an automated solution that doesn't require manual synchronization. I need the data to be accessible in both local development and production.
Some ideas:

Host the file on GitLab pages from A and curl it into B.
Set up an access token and use gitlab-api, curl it into B.
Say screw it, and build out a proper API that feeds both repos.

Is there a solution that's better that I'm not thinking about? What would you do? I'm leaning towards option 2.
Answer: Automation in GitLab is synonym of pipelines.
Add a .gitlab-ci.yml file in the root folder of project B with the following content:
stages:
  - synchronize

include:
  - local: /.ci/synchronize.yml

In project root folder create ./.ci/synchronize.yml with the following content:
synchronize-job:
  stage: synchronize
  image: ubuntu:jammy-20220428
  rules:
    - if: $CI_PIPELINE_SOURCE == "schedule" # run job only for a scheduled pipeline

  script:
    - |
        apt-get update # update repo
        apt-get install --yes curl git # install tools
    - git clone -b main https://gitlab-ci-token:${CI_JOB_TOKEN}@<your_server_domain>/<project A>.git
    - cp <project A name>/<your yml file>.yml .
    - git remote rm origin && git remote add origin git@<your_server_domain>:<project B path>.git
    - git push -u origin main

Then create a scheduled pipeline from the GitLab GUI. Specify the interval of one week, as you desire.
In this solution, you have:

automation;
no manual creation of auth token: the GITLAB_CI_TOKEN is automatically created and destroyed with the job;
synchronization.

Caveat: if you include other jobs in the pipeline, they may be triggered in an infinite loop due to the final push in synchronize-job. Just configure the rules of these jobs to not run when there's a push on main branch.


Angularjs directive

Question: I want to have an attribute directive a bit similar to ng-model. I just want to additionally bind an input fields value to a scope variable (just in one direction input field -> scope variable). So I have just tried this directive but I can not get the directive called anyway.
script:
.directive('passivemodel', function () {
  return {
    restrict: "A",
    scope: {
        passivemodel: '='
    },
    link: function (scope, element, attrs) {
        scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
            console.log("passive model", newPassivemodel);
        });
    }
  };
})

html:
<input data-passivemodel="keyword">

Edit:
Hmmm .. based on vilo20 answer I am running into a very strange behavior.
while this code is working very well:
<input data-ng-model="keyword" data-passivemodel="keyword">
this one does not (note the value of passivemodel):
<input data-ng-model="keyword" data-passivemodel="keyword2">. Sure I have defined the variable in the controller.
Controller:
.controller('SearchController', function($scope, $routeParams, $search) {
        $scope.search = new $search();
        $scope.keyword = "";
        $scope.keyword2 = "";
})

Edit2: here is a fiddle http://jsfiddle.net/HB7LU/12107/
Comment: Take a look at the plunker I made for you in my answer
Answer: try this:
.directive('passivemodel', function () {
        return {
            restrict: "A",
            scope: {
               passivemodel: '='
            },
            link: function (scope, element, attrs) {
                console.log("passive model", scope.passivemodel);
                $scope.$watch('passivemodel', function(newPassivemodel, oldPassivemodel) {
                //put your logic when passivemodel changed
                });
            }
        };
    })

Hope it helps
Edit: Here is a plunker http://plnkr.co/edit/T039I02ai5rBbiTAHfzv?p=preview
Comment: Yes this works! But now I have a scope limited to the directive right? How can I access the controllers scope now?
Comment: Because of '=' both scopes are linked (bind). Try to change the passivemodel from the directive - you will see that it being changed also in the parent scope.
Comment: 2 min to go to accept it. but I still have a problem pls see my edit.
Comment: I am looking, can you create some jsfiddle or plunker? are you getting any errors in console?
Comment: In the plunker olny the keyword is working keyword2 is doing nothing. In my fiddle not even keyword is working when I use passivemodel
Answer: Use the scope attribute:
.directive('passivemodel', function () {
        return {
            restrict: "A",
            scope: {
                "passivemodel": "="
            },
            link: function (scope, element, attrs) {
                console.log("access passivemodel: ", scope.passivemodel);
            }
        };
    })

Answer: Finally it was as simple as that:
.directive('modelRed', [function(){
        return {
            require: 'ngModel',
            restrict: 'A',
            scope: {},
            link: function (scope, element, attrs, ngModel) {
                scope.$watch(function () {
                    return ngModel.$modelValue;
                }, function(newValue) {
                    scope.$parent[attrs.modelRed] = newValue;
                    //console.log(attrs.modelRed, newValue, scope);
                });
            }
        }
    }])

And in the html:

<input type="text" data-ng-model="testInput" data-model-red="redInput">{{redInput}}

Of course you have to define testInput and redInput in the $scope object.

Angularjs directive


Crontab script not generating text file

Question: Here is my crontab entry:
* * * * * /home/ec2-user/Test/test_thing.sh
Here is the script, test_thing.sh:
echo "asdf" >> ./bla.txt
When I run it manually, it does generate the "bla.txt" file. However, it does not automatically do so (create the "bla.txt" file within the /Test/ directory) with the crontab.
I have also checked my /var/log/cron file and I see that it is executed every minute, but not sure if it's running into an error or not.
If it is important, I am running this on an Amazon ec2 server, specifically the Amazon Linux AMI.
Edits:
I have also done chmod +x test_thing.sh to make sure it is executable.
Comment: The relative path "./blah.txt" might not be where you think it is. Try using an absolute path reference on a folder you know that your user has the permission writing to.  Good luck!
Answer: The cronjob runs from home directory by default. So you should see the file to be created under /home/ec2-user or /root if you run it by root account.
If you need generate the new file with the nominate path, one way is to use absolute path as @yftse said. The other way is
* * * * * cd /home/ec2-user/Test/; bash /home/ec2-user/Test/test_thing.sh

Comment: Thank you! Just a quick question (probably out of the scope of this problem so feel free to point me in a direction if necessary). When you `cd` into a directory within the crontab, I'm assuming it doesn't affect other cronjobs, even within the same file? If so, is it a temporary directory change, which then is reverted back to the home directory, or is my assumption wrong?
Comment: Yes, it is possible.
Comment: Your assumption is correct.  You could also choose to put the cd command in the script.

Crontab script not generating text file


Como usar função Max() e Count() juntas?

Question: Fala pessoal! Estou treinando um subselect com having usando as funções MAX E COUNT juntas, mas o SQLServer está me retornando um erro chamado:
"Não é possível executar uma função de agregação em uma expressão que contenha uma agregação ou uma subconsulta."
Geralmente faço os scripts no oracle sql developer não sei se é algum erro de sintaxe, alguém pode me ajudar? Segue abaixo o comando executado:
select clfDescricao
from classificacaofiscal c, notafiscaleletronica n
where c.clfCFO = n.NFE_cnatOP
group by clfDescricao
having count(n.NFE_id) = (select max(count(n.NFE_id))
from classificacaofiscal c, notafiscaleletronica n
where c.clfCFO = n.NFE_cnatOP)

Comment: Tente explicar o que deseja obter.
Comment: Qual DB engine? Vc menciona tanto o SQL Server quanto o Oracle. Para facilitar a reprodução do problema, tente criar um fiddle em http://sqlfiddle.com/
Comment: E como dito anteriormente, explique o que deseja obter. Procure não se focar em como está a fazê-lo. O erro pode estar na forma de implementar o que se deseja. Não me parece fazer sentido usar `select max(count(n.NFE_id))`, por exemplo.
Comment: Teste: `select count(n.NFE_id)
from classificacaofiscal c, notafiscaleletronica n
where c.clfCFO = n.NFE_cnatOP` com seus dados e avalie o resultado. Depois verifique se faz sentido utilizar a função max neste select.
Comment: Pessoal eu estou fazendo o script no Oracle, estou tentando responder a seguinte pergunta:
Qual CFOP teve o maior número de notas fiscais registradas?
Comment: Uma solução seria você fazer um count agrupando por CFOP, ordenar em ordem decrescente e pegar apenas o primeiro. Neste caso você pode não obter a informação completa se existirem mais de um CFOP com a mesma quantidade. Outro solução seria pegar os count em um subselect e no select mais externo pegar o max sobre o resultado do subselect.
Answer: Li pelos comentários que você está tentando fazer isso em Oracle.
Você pode fazer da seguinte forma:
/*Cria o agrupamento por descrição*/
WITH dados AS (
SELECT clfdescricao,
       MAX(COUNT(n.nfe_id)) cnt
  FROM classificacaofiscal c, notafiscaleletronica n
 WHERE c.clfcfo = n.nfe_cnatop
 GROUP BY clfdescricao)

/*Retorna apenas o que tiver maior número de notas*/
SELECT clfdescricao
  FROM dados
 WHERE cnt = (SELECT MAX(cnt) FROM dados)

Dessa primeira forma, você perde um pouco de performance, porém deixa o código mais fácil de ser compreendido. Então, é valido fazer uma avaliação do volume de dados, para ver qual será o impacto.
No seu caso, basicamente você só esqueceu de colocar o group by dentro do seu sub-select, como não há ligação com a query de fora, você poderia executa-la de forma avulsa e checar o motivo de não ter funcionado.
Segue o exemplo utilizando a função HAVING:
SELECT clfdescricao
  FROM classificacaofiscal c, notafiscaleletronica n
 WHERE c.clfcfo = n.nfe_cnatop
 GROUP BY clfdescricao
HAVING COUNT(n.nfe_id) = (SELECT MAX(COUNT(n.nfe_id))
                            FROM classificacaofiscal  c,
                                 notafiscaleletronica n
                           WHERE c.clfcfo = n.nfe_cnatop
                           GROUP BY clfdescricao)


Referance a static resource via aura:attribute

Question: I have created a new component and I want to be able to pass an image from a static resource and a custom label via aura:attribute. This is what I tried and it does not work. How can I make the image/text to show?
<aura:attribute name="profileImage" type="string" default="Standard_Profile" />
<aura:attribute name="categoryName" type="string" default="Standard_Name" />

{!$Label.'categoryName'}

I am very new to Salesforce.
Answer: Map the values from your custom label and static resource as default values in the attributes and use it in the code
<aura:component implements="flexipage:AvailableForAllPageTypes">
    <aura:attribute name="profileImage" type="string" default="{!$Resource.profileImage}" />
    <aura:attribute name="categoryName" type="string" default="{!$Label.c.categoryName}" />

        {!v.categoryName}

</aura:component>


Confusion related to marginal precision

Question: I was reading this book where it was mentioned that if my gaussian distribution has unit marginal precision, the covariance matrix equals the correlation matrix. I didn't quite get it. Any clarifications will be much appreciated
Answer: If the gaussians have unit marginal precision, they have unit variance and unit standard deviations as well. The trick is that the covariance matrix can be expressed as a correlation matrix pre- and post-multiplied by a diagonal matrix of standard deviations. With $\Sigma$ the covariance matrix and $\Omega$ the correlation matrix:
$\boldsymbol{\sigma} I \,\, \Omega \,\, \boldsymbol{\sigma} I ~=~ \Sigma$
In the case you described, these diagonal matrices are identity matrices, which means that the covariance and correlation matrices are identical.

Confusion related to marginal precision