Type signature for index in Haskell

Question: Project Euler Problem 7: What is the 10 001st prime number?
This is a function that takes a single parameter (10001) and returns the 10001st prime.  GHCi gives me no problems:
p007nthPrime x = primes !! (x - 1)
    where
        primes :: [Integer]
        primes = sieve [2..]
            where
                sieve (p:xs) = p : sieve [x|x <- xs, x `mod` p > 0]

Now, being a good Haskeller, I'd like to make a type signature.  However, putting p007nthPrime :: (Integral a) => a -> a at the top throws me this error:
projecteuler.hs:81:29:
    Couldn't match type `Integer' with `Int'
    Expected type: Int
      Actual type: a
    In the first argument of `(-)', namely `x'
    In the second argument of `(!!)', namely `(x - 1)'
    In the expression: primes !! (x - 1)
Failed, modules loaded: none.

and inserting p007nthPrime :: (Num a) => a -> a does the same thing.  What is the right type signature for this function?
Comment: Just have ghci tell you what the type signature is with `:type p007nthPrime `
Comment: Well, `!!` has the type `[a] -> Int -> a` (http://hackage.haskell.org/package/base-220.127.116.11/docs/Prelude.html#v:-33--33-); the index is of fixed type `Int`. Thus, your function must have the type `(Integral a) => Int -> a`.
Answer: The (!!) list indexing operator only takes Ints, while your primes list contains Integers, so your signature needs to be
p007nthPrime :: Int -> Integer

Both Int and Integer are types of the class Integral, but a single type cannot be both Int and Integer.
If you need the argument to also be Integer, I suggest using the fromIntegral function.
Otherwise, to find out what type signature to give a function/value, a good idea is to use the :t command in GHCi:
*Main> :t p007nthPrime
p007nthPrime :: Int -> Integer

Comment: For indexing with `Integer`s and other `Integral` types, Haskell also provides [genericIndex](http://hackage.haskell.org/package/base-126.96.36.199/docs/Data-List.html#v:genericIndex) of type `Integral i => [a] -> i -> a`.

Type signature for index in Haskell


Amazon EventBridge rule S3 put object event cannot trigger the AWS StepFunction

Question: After setting the EventBridge, S3 put object event still cannot trigger the StepFuction.
However, I tried to change the event rule to EC2 status. It's working !!!
I also try to change the rule to S3 all event, but it still not working.
Amazon EventBridge:
Event pattern:
<code>     {
      "source": ["aws.s3"],
      "detail-type": ["AWS API Call via CloudTrail"],
      "detail": {
                 "eventSource": ["s3.amazonaws.com"],
                 "eventName": ["PutObject"],
                 "requestParameters": {
                 "bucketName": ["MY_BUCKETNAME"]
                 }
     }
</code>
Target(s):
<code>  Type:Step Functions state machine
    ARN:arn:aws:states:us-east-1:xxxxxxx:stateMachine:MY_FUNCTION_NAME
</code>
Reference:https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-cloudwatch-events-s3.html
Comment: Did you enable CloudTrial for S3 events? Did you verify that the S3 events are detected by the CT?
Comment: @Marcin  Yes, I follow the reference and create the  CloudTrial for S3 events. However, it still cannot trigger the stepfunction
Answer: Your step function isn't being triggered because the PutObject events aren't being published to cloudtrail. S3 operations are classified as data events so you must enable Data events when creating your cloudTrail. The tutorial says next next and create which seems to suggest no additional options need to be selected. By default, Data Events on the next step (step 2  - Choose log events - as of this writing) is not checked. You have to check it and fill up the bottom part to specify if all buckets/events are to be logged.


Como fazer para que o botão fique sempre a direita no topo dentro da div?

Question:

function customAlert(customMessage)
{
    var interface = window.document.createElement("div");
    var button = window.document.createElement("button");
    var paragraph = window.document.createElement("p");
    var body = window.document.body;

    interface.style.width = "300px";
    interface.style.height = "200px";
    interface.style.backgroundColor = "rgb(80, 80, 80)";
    interface.style.position = "absolute";
    interface.style.left = "50%";
    interface.style.transform = "translateX(-50%)";
    interface.style.borderRadius = "10px";
    interface.style.overflowX = "scroll";

    button.textContent = "X";
    button.style.border = "none";
    button.style.backgroundColor = "rgb(255, 0, 0)";
    button.style.color = "rgb(255, 255, 255)";
    button.style.width = "30px";
    button.style.height = "30px";
    button.style.float = "right";
    button.style.cursor = "pointer";
    button.style.borderRadius = "0 10px 0 0";
    button.style.outline = "none";

    paragraph.style.fontFamily = "arial";
    paragraph.style.color = "rgb(255, 255, 255)";
    paragraph.style.position = "absolute";
    paragraph.style.left = "53%";
    paragraph.style.top = "40%";
    paragraph.style.transform = "translateX(-53%) translateY(-40%)";
    paragraph.style.fontSize = "14px";

    if (customMessage == "") {
        paragraph.textContent = "Está mensagem não diz nada!";
    } else {
        paragraph.textContent = customMessage;
    }

    button.addEventListener("mouseenter", function()
    {
        button.style.backgroundColor = "rgb(255, 90, 90)";
    });

    button.addEventListener("mouseout", function()
    {
        button.style.backgroundColor = "rgb(255, 0, 0)";
    });

    button.addEventListener("click", function()
    {
        body.removeChild(interface);
    });

    interface.appendChild(button);
    interface.appendChild(paragraph);
    body.appendChild(interface);
}

customAlert();

Antes de tudo, sim fiz isso tudo com JavaScript e o arquivo é externo. Mas o que acontece o button ele não fica perfeitamente a direita quando o texto dentro do parâmetro customMessage começa aumentar. Se você executar customAlert("E alguma coisa!"); no console veram que funciona perfeitamente, mas se for algo como customAlert("sdededededededededededededededede"); o button começa a rolar junto com o texto e não fica mais a direita. Já testei quase tudo e ele não permanece a direita quem poder ajudar agradeço.
Answer: Você teria que criar uma outra div pai e colocar o botão dentro dela, e não na div que faz o scroll e que contém o parágrafo.
Aí você terá também que alterar algumas propriedades. No exemplo abaixo eu criei a div container e coloquei a div interface dentro dela, assim como o botão, que ficou com position absolute posicionado no canto superior direito da div pai, algo assim:
---------- container ----------
|                     ------- |
|                     |botão| |
|                     ------- |
| -------- interface -------- |
| |                         | |
| |                         | |
| |
parágrafo
     | |
| |                         | |
| |                         | |
| --------------------------- |
-------------------------------

function customAlert(customMessage)
{
    var container = window.document.createElement("div");
    var interface = window.document.createElement("div");
    var button = window.document.createElement("button");
    var paragraph = window.document.createElement("p");
    var body = window.document.body;

    container.style.width = "300px";
    container.style.height = "200px";
    container.style.position = "absolute";
    container.style.left = "50%";
    container.style.transform = "translateX(-50%)";

    interface.style.width = "100%";
    interface.style.height = "100%";
    interface.style.backgroundColor = "rgb(80, 80, 80)";
    interface.style.borderRadius = "10px";
    interface.style.overflowX = "scroll";
    interface.style.position = "relative";

    button.textContent = "X";
    button.style.border = "none";
    button.style.backgroundColor = "rgb(255, 0, 0)";
    button.style.color = "rgb(255, 255, 255)";
    button.style.width = "30px";
    button.style.height = "30px";
    button.style.position = "absolute";
    button.style.top = "0";
    button.style.right = "0";
    button.style.cursor = "pointer";
    button.style.borderRadius = "0 10px 0 0";
    button.style.outline = "none";

    paragraph.style.fontFamily = "arial";
    paragraph.style.color = "rgb(255, 255, 255)";
    paragraph.style.position = "absolute";
    paragraph.style.left = "53%";
    paragraph.style.top = "40%";
    paragraph.style.transform = "translateX(-53%) translateY(-40%)";
    paragraph.style.fontSize = "14px";

    if (customMessage == "") {
        paragraph.textContent = "Está mensagem não diz nada!";
    } else {
        paragraph.textContent = customMessage;
    }

    button.addEventListener("mouseenter", function()
    {
        button.style.backgroundColor = "rgb(255, 90, 90)";
    });

    button.addEventListener("mouseout", function()
    {
        button.style.backgroundColor = "rgb(255, 0, 0)";
    });

    button.addEventListener("click", function()
    {
        body.removeChild(container);
    });

    container.appendChild(interface);
    container.appendChild(button);
    interface.appendChild(paragraph);
    body.appendChild(container);
}

customAlert("1ahgashgsagashgashgashgashgashgashgahsghsaghasghasghasghasghagashgas0");
Comment: Cara, era isso mesmo que eu queria, valeu mesmo!
Answer: Visualizando por aqui, o botão nunca anda. Vi em 4 navegadores diferentes. Mas caso tenha problemas com o botão andando. Pode usar o position:absolute nele e tirar o float. Exemplo: JSFiddle
button.textContent = "X";
button.style.border = "none";
button.style.backgroundColor = "rgb(255, 0, 0)";
button.style.color = "rgb(255, 255, 255)";
button.style.width = "30px";
button.style.height = "30px";
button.style.position = "absolute";
button.style.right = 0;
button.style.top = 0;
button.style.cursor = "pointer";
button.style.borderRadius = "0 10px 0 0";
button.style.outline = "none";

Comment: O button ainda continua rolando com o texto, já tinha testando com o position sem sucesso.


Unable to change color of overlay text

Question: I have spent hours on this wasteful exercise. I am unable to set the color of text over the image to be perfect white. It takes on the color of what's behind it.
Please take a look.

@import url('https://fonts.googleapis.com/css2?family=Lato:wght@100;300;400;700;900&display=swap');
html {
  scroll-behavior: smooth;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 0;
  overflow-x: auto;
  overflow-y: scroll;
  font-family: 'Lato';
}

header {
  background-color: #e8e9ea;
  padding: 10px 0;
}

.nav-container {
  width: 85%;
  margin: 0 auto;
}

nav {
  margin: 30px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nav-top {
  margin: 15px 0;
}

.nav-brand {
  font-size: 1.8rem;
  font-weight: 300;
}

ul {
  list-style-type: none;
}

ul li {
  display: inline-block;
  margin: 0 8px;
  font-size: 14px;
  font-weight: 300;
}

li a {
  text-decoration: none;
  color: black;
}

.container {
  width: 85%;
  margin: 0 auto;
}

.mb_parallax_container {
  margin-top: 100px;
  height: 100vh;
  width: 100%;
  background-attachment: fixed;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url(https://i.ibb.co/q50nfZ1/Woman-visiting-psychologist-office-Patient-sitting-in-armchair-and-talking-to-psychiatrist-Vector-il.jpg);
  background-position: center;
  position: relative;
  z-index: 1;
}

.mb_parallax_overlay {
  height: 100vh;
  width: 100%;
  background-color: black;
  opacity: .4;
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 2;
}

.mb_parallax_caption {
  text-align: center;
  width: 70%;
  position: relative;
  z-index: 3;
  opacity: 1;
  -webkit-user-select: none;
  /* Chrome all / Safari all */
  -moz-user-select: none;
  /* Firefox all */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
}

.mb_parallax_caption h1 {
  font-size: 5.5rem;
  color: white;
  margin: 20px 0;
}

.mb_parallax_caption p {
  margin: 20px 0;
  color: white;
  font-size: 1.6rem;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css" />
  <title>Document</title>

Hello Therapy

Home

Therapist Repository

Crisis Intervention

Resources

Join Us

About

Blog

More

Welcome to Hello Therapy

Making Therapy Accessible

It would be great if someone could find a work around. Thanks in advance.
Comment: This will help you: https://codepen.io/manaskhandelwal1/pen/bGBVOZx
Answer: You have opacity: 0.4 set on .mb_parallax_overlay which means, all children are darkened as well. In this case if you have 0.4 on your parent, then the maximum opacity of the child is 0.4 (opacity: 1 for the child).
You can try the following approach to darken your background.

.container {
  width: 85%;
  margin: 0 auto;
}

.mb_parallax_container {
  margin-top: 100px;
  height: 100vh;
  width: 100%;
  background-attachment: fixed;
  background-size: cover;
  background-repeat: no-repeat;
  background-image: url(https://i.ibb.co/q50nfZ1/Woman-visiting-psychologist-office-Patient-sitting-in-armchair-and-talking-to-psychiatrist-Vector-il.jpg);
  background-position: center;
  position: relative;
  z-index: 1;
}

.mb_parallax_overlay {
  height: 100vh;
  width: 100%;
  background-color: black;
  /*opacity: .4; remove this*/
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 2;
  background: rgba(0, 0, 0, 0.5);
  /*darken background*/
}

.mb_parallax_caption {
  text-align: center;
  width: 70%;
  position: relative;
  z-index: 3;
  /*opacity: 1; not needed*/
  -webkit-user-select: none;
  /* Chrome all / Safari all */
  -moz-user-select: none;
  /* Firefox all */
  -ms-user-select: none;
  /* IE 10+ */
  user-select: none;
}

.mb_parallax_caption h1 {
  font-size: 5.5rem;
  color: white;
  margin: 20px 0;
}

.mb_parallax_caption p {
  margin: 20px 0;
  color: white;
  font-size: 1.6rem;
}

Welcome to Hello Therapy

Making Therapy Accessible

Unable to change color of overlay text


Is there a generator for $(\Bbb R, +)$?

Question: I know that the generator for $(\Bbb Z,+)$ is $<1>$, because you can get any number in $\Bbb Z$ as a sum of $1's$ and $-1's$. But what about $(\Bbb R, +)$ how can one find a generator for this group , or is it impossible ?
Comment: https://math.stackexchange.com/questions/354413/what-are-the-generators-of-mathbbr
Comment: No, there is not such a generator of $(\mathbb R, +)$.
Comment: Nice find, @user29418
Answer: Suppose the group $(\mathbb{R},+)$ is generated by some $g\in\mathbb{R}$.

Clearly, we can't have $g=0$.

But the group generated by $g$ is the set of integer multiples of $g$, none of which are equal to ${\large{\frac{g}{2}}}$.

Thus, ${\large{\frac{g}{2}}}$ is not in the group generated by $g$, contrary to the assumption that $g$ generates all of $\mathbb{R}$.

It follows that there is no element $g\in\mathbb{R}$ which generates $(\mathbb{R},+)$.

Is there a generator for $(\Bbb R, +)$?


Circle Angle chasing problem: Compute APC+BQD

Question: I was wondering if someone could give me a hint as to how to solve this problem:

Let circle C1 intersect circle C2 at P and Q. A line intersects C1 at A and B, and C2 at C and D, such that the four points lie on the line on the order A, B, C, D and that P and Q lie on the same side of the line.
Compute APC+BQD.
I found this problem on an angle chasing worksheet by Ray Li. I've tried proving APC+BQD=180°, but I'm unsuccessful because I don't know how to obtain information about the angles. If you have any ideas, please let me know.
Comment: Please provide additional [context](https://math.meta.stackexchange.com/a/9960/), which ideally explains why the question is relevant to you and our community. Some forms of context include: background and motivation, relevant definitions, source, possible strategies, your current progress, why the question is interesting or important, etc.
Answer: You have requested a hint to solve this angle chasing problem. We would like to give you a hint in the form of a diagram, Here, we have extended your sketch by adding a point $E$ and four red lines, i.e., $AQ$, $AE$, $EQ$, and $PQ$. Point $E$ is the point of intersection between extended $DQ$ and the circle $\Omega_1$. If you do the angle chase using these lines, you will be able to compute $\angle APC+\angle BQD$ easily. You have also mentioned that you are trying to prove $\angle APC+\angle BQD = {\large{\pi}}$. We think that you are on track.
Comment: Thanks, I was able to complete the problem! I'll put my solution.


Check support for Offscreen canvas

Question: I have an HTML/JavaScript SPA and I want to check whether Offscreen canvas is supported by the Browser or not.
I tried with
var canvasTest = document.createElement('canvas-test');

if(typeof canvasTest.transferControlToOffscreen === "function")
{
   return true;
}
else
{
   return false;
}

but it doesn't work (i.e. it returns false even though the Browser actually supports it)
I'm using this code to check if the function exists or not:
How to check if function exists in JavaScript?
Answer: you can check the prototype of the canvas which is a much more lightweight way to check than creating a canvas element.

if (HTMLCanvasElement.prototype.transferControlToOffscreen) {
  console.log('support for transferring control of an offscreen canvas exists');
} else {
  console.log('support for transferring control of an offscreen canvas does NOT exist');
}

Note that OffscreenCanvas and support for transferring a canvas to an offscreen canvas are technically not the same thing. It's possible though probably 0% chance of possibility for a browser to support OffscreenCanvas and not support transferring a canvas's control to one. So technically to check for OffscreenCanvas support you'd do this

if (typeof OffscreenCanvas !== 'undefined') {
  console.log('OffscreenCanvas is supported');
} else {
  console.log('OffscreenCanvas is NOT supported');
}
Answer: The problem with your code is that you create a canvas-test dom element, which is not the same as canvas.
Try this.

var canvasTest = document.createElement('canvas');

if(typeof canvasTest.transferControlToOffscreen === "function")
{
   console.log('true');
}
else
{
   console.log('false');
}
Comment: yes, silly me. I was thinking of an html id instead of the actual html element. Thanks
Comment: It's a shame that createElement() is so permissive, letting me to create HTML elements that doesn't exist
Comment: In html5 you can create any type of HTML element it's not as strict in this regard as XHTML was.
Comment: For Firefox 88 (and older) the method exists but valling it will throw NS_ERROR_NOT_IMPLEMENTED exception.

Check support for Offscreen canvas


Indefinite integral with three logarithm functions

Question: Is there a way to evaluate the following integral involving three logarithmic functions
$$
I(y)=\int \frac{\log(1+y)\log(y)\log(1-y)}{y}\mathrm{d}y
$$
?
Comment: https://math.stackexchange.com/questions/465444/evaluating-int1-0-frac-log1x-log1-x-logxx-mathrm-dx?noredirect=1 obtained using searching tool approach0.xyz
Comment: Where'd you come across the problem? What have you tried so far on it?
Comment: Is there a reason to believe that there is a closed form in terms of elementary functions? Do you care if it is in closed form of non-elementary functions?
Comment: Wolfram Alpha outputs "no result found in terms of standard mathematical functions". In other words, it seems that no closed form is possible.
Answer: According to the formula section of sequence $A049281$ in $OEIS$
$$\frac{\log (1-y) \log (1+y)}{y^2}=-\sum_{n=0}^\infty\Bigg[ \int_0^1x^{n} \log \left(1+\frac{1}{\sqrt{x}}\right)\,dx\Bigg] y^{2n}$$
$$a_n=\int_0^1x^{n} \log \left(1+\frac{1}{\sqrt{x}}\right)\,dx=\frac{1}{2 (n+1)^2}+\frac{\log (2)-\Phi (-1,1,2 n+3)}{n+1}$$ where appears s the Lerch transcendent function.
So
$$\frac{\log(1+y)\log(y)\log(1-y)}{y}=-\sum_{n=0}^\infty a_n\,y^{2n+1}\log(y)$$
$$\int y^{2n+1}\log(y)\,dy=\frac{y^{2 n+2} (2 (n+1) \log (y)-1)}{4 (n+1)^2}$$
So, here is the formula.
Integrating between $0$ and $1$ and using $30$ terms, what is obtained is
$$\frac{129331573539024596038309003920483687963710634649045728750361929932743}{444999142480969921593398700100589348217215915374013669213491200000000}$$ which is
$0.29063$ while the exact solution given in this question is, numerically, $0.29072$


Change language of a JS element when language has been changed from Drupal language switcher?

Question: First of all, sorry for the really confusing title, but I have no idea how to make it more reader friendly.
On my website, there are three languages: English, Finnish and Swedish. The user can change between these languages from the default Drupal language switcher.
Now the key part of the website comes from an API that I think is in JS. That JS element has its own language changing parameter.

src="//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=sv&leaflet_gshim=1">

So in order to change the language of the JS element I would need to change that "lang=" part to what language I want.
I have that script with the address to the API in my page.html.twig file to make the API call to work all across the site.
Is there a way to change the lang=sv to lang=en and lang=fi when the user changes the language through Druapl language switcher?
From the companys API support they said:

you have different pages for different languages:
  website.fi/drupal/ (englisch)
  website.fi/drupal/sv
  website.fi/drupal/fi
  This means that you should have a different script tag for each of these
  paths. I guess Drupal allows that with help of a language variable
  that is accessible in your page template. (But I really know little
  about Drupal, so that's just a guess)

I am sorry for a long and confusing post, but it is really crucial to get this to work and I am losing my mind.
PS! I am really new to Drupal.
Comment: How is the JS being added to the page? https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
Answer: Something like this is what you're looking for I think.
<code>theme_js_alter($js) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  foreach ($js as $key => $value) {
    if (strpos($value['data'], 'www.websiteofapi.com/alpportal/oa_head.js') !== 0) {
      $value['data'] = "//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=$language&leaflet_gshim=1"
    }
  }
}
</code>
Also see Get current language in template
Comment: Thanks! But where should I put this piece of code?


Javascript toggle or if/else on Adobe Edge Animate

Question: Eu uso o Adobe Edge Animate para animações simples no trabalho. Não consegui fazer uma delas funcionar e fiz uma gambiarra. Agora quero saber como fazer do jeito certo.
Tenho um botão. Quando clicado, ele deveria dar play na linha do tempo do início ao fim. Se clicado de novo, deveria dar play ao contrário, do fim ao início.
Tentei isso:
var x=0;
if (x==0){
    sym.getSymbol("timeline").play('start');
    x=1;
} else {
    sym.getSymbol("timeline").playReverse('finish');
    x=0 ;
}

Isso não funciona. Não sei onde errei. Acabei fazendo o seguinte:
Criei duas divs, Symbol1 e Symbol2. Elas ficam uma sobre a outra. Quando a primeira foi clicada, ela deu play na timeline e desapareceu (mostrando a div inferior), de modo que o segundo símbolo fosse clicado, dando play reverse. Após isso o Symbol1 reapareceria, reiniciando o processo.
Código:
// Symbol2:
sym.getSymbol("timeline").play('start');
sym.$("symbol2").hide();

// Symbol1:
sym.getSymbol("timeline").playReverse('finish');
sym.$("symbol2").show();

Como fazer isso funcionar? O segundo modo funciona mas é trabalho duplo (fazer isso pra um botão é fácil, quero ver fazer pra vinte, o que viraria 40, já que são dois botões pra cada parte).
Link para a arte
Answer: Infelizmente, eu não consigo testar este código porque não consigo fazer um jsfiddle que me retorne as imagens que tu estás a usar no teu servidor. No entanto, este script deverá funcionar:
Symbol.bindElementAction(compId, symbolName, "${Pimentao2}", "click", function(sym, e) {

if ($(this).attr('data-show')) {
    sym.getSymbol("Pimentao2").playReverse('volta');
    $(this).attr('data-show',false)
} else {
    sym.getSymbol("Pimentao2").play('vai');
    $(this).attr('data-show',false);
}
});

O que estavas a fazer de mal era que a variavel x estava a ser definida sempre que existia um clique, então x era sempre == 0.
Em vez de definires uma variavel, o que tens que fazer é definir um atributo, neste caso data-show. Ao clicar no pimentão, ele vê "este elemento tem data-show?" (está a mostrar a data?) - se isto for verdade, então ele faz o playReverse e retira o atributo do elemento, caso contrário ele faz play e adiciona o atributo data-show ao elemento.

Eu não sei bem como funciona o Adobe Edge Animate, mas, suponho que possas melhorar este selector para funcionar para todos os butões para não teres que repetir esta função.
Qualquer coisa como Symbol.bindElementAction(compId, symbolName, "#Stage_info > div:not(.Stage_info_largura_id)", "click", - Este selector diz "Todas as divs que são filhas do #Stage_info que não sejam a Stage_info_largura"
Claro que ao usares este selector terás que mudar parte da função acima, para não selecionar o "Pimentão2" por defeito, mas selecionar o item clicado.


Reduce the equation to canonical form. $u_{xx}+2ayu_{xy}+e^{2x}u_{yy}-u=0$

Question: Consider the equation
$$u_{xx}+2ayu_{xy}+e^{2x}u_{yy}-u=0$$
where $a$ is a real constant. Determine the value(s) of $a$ when this equation is elliptic everywhere in the $xy$-plane in which case find the canonical variables and reduce the equation to its canonical form.
I am trying to do this question for exam prep.
I got that the equation is elliptic when $(ay)^{2}-e^{2x} \lt 0$, that is that $a \lt \frac{e^{2x}}{y}$. However i'm not sure how i would determine the canonical variable and thus reduce the equation to canonical form. Any help is appreciated.
Answer: Your inequality is
$$ (ay - e^x)(ay + e^x) < 0 $$
which comes out to
$$ -e^x < ay < e^x $$
If $a\ne 0$, then the equation is ellliptic in the region bounded above and below by the curves $y = \pm \frac{e^x}{a}$. This is clearly not the entire $\mathbb R^2$ plane
Therefore $a=0$ is the only solution


How to copy and paste from cell in C1FlexGrid?

Question: I want to copy and paste from one cell to another / C1FlexGrid
copy from selected red cell and paste other value here - shown image
copy from selected red cell/ Image is here

Is there any event like KeyDown etc
Any example code ?
Answer: The events KeyDown/KeyPress/KeyUp wont work in this case since your FlexGrid is in edit mode. When in edit mode try using KeyDownEdit/KeyPressEdit/KeyUpEdit events for the FlexGrid.
VB.NET
Private Sub C1FlexGrid1_KeyPressEdit(sender As Object, e As KeyPressEditEventArgs)
Handles c1FlexGrid1.KeyPressEdit
    'Implement logic here
End Sub

C#:
public Form1()
    {
        this.c1FlexGrid1.KeyPressEdit += new KeyPressEditEventHandler(this.c1FlexGrid1_KeyPressEdit);
    }

    private void c1FlexGrid1_KeyPressEdit(object sender, KeyPressEditEventArgs e)
    {
       // Implement logic here
    }

However, I would suggest you to use ValidateEdit event to implement your use case.
Comment: Hi, it's working. One more question how can I **paste** in edit mode, and CTR+A to select all? Thank you.
Comment: @AliSilamkhanDvR Can you elaborate your use-case? I think you might implement this using any other event
Comment: Ok, I did it by using 'IDataObject iData = Clipboard.GetDataObject();' to getdata PASTE :-)


Change focus on the infragistics ultra grid?

Question: I want to change the focus on my grid cell.
Suppose I click on a cell[1,1] then I want to set the focus on cell[1,2].
Where cell[1,1] means cell of (column 1) and (row 1)
Answer: You could use the AfterCellActivate event and write this code
void grid_AfterCellActivate(object sender, EventArgs e)
{
    if (grid.ActiveCell != null &&
        grid.ActiveCell.Column.Index == 1 &&
        grid.ActiveCell.Row.Index == 1)
    {
        grid.ActiveCell = grid.Rows[1].Cells[2];

        // And if you want also to automatically
        // put your cell in edit mode add this line
        grid.PerformAction(UltraGridAction.EnterEditMode);
    }

}


Scaling custom UIView by CGAffineTransformMakeScale breaks dragging with touchesMoved

Question: I have prepared and checked into GitHub a simple test case for dragging custom UIView:

It works well and dragging is implemented in the Tile.m as:
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGPoint previous = [touch previousLocationInView:self];
    self.frame = CGRectOffset(self.frame,
                              (location.x - previous.x),
                              (location.y - previous.y));
}

However the tiles are too large for my actual game (and I will have to adjust their scaling once the game board in UIScrollView is zoomed anyway):

So I scale my custom UIViews down by calling
tile.transform = CGAffineTransformMakeScale(.5, .5);

The size changes, but the tiles are suddenly dragged "twice as quickly" as needed:

Probably the touchesMoved code (s. above) should be adjusted, but I'm not sure what has been broken there by the transform manipulation?
Answer: Nevermind, I have found the solution:
- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    CGPoint previous = [touch previousLocationInView:self];

    if (!CGAffineTransformIsIdentity(self.transform)) {
        location = CGPointApplyAffineTransform(location, self.transform);
        previous = CGPointApplyAffineTransform(previous, self.transform);
    }

    self.frame = CGRectOffset(self.frame,
                              (location.x - previous.x),
                              (location.y - previous.y));
}


Unique Solution of a Differential Equation on some Rectangular Region $\mathcal{R}$

Question: I'm trying to find a rectangular region $\mathcal{R}$ of the $ty$-plane for which the differential equation $(1+y^3)y' = t^2$ would have a unique solution through a point $(t_0, y_0)$ in $\mathcal{R}$.
When talking about uniqueness of solutions of DEs, though, the context in which I learned about them was of an initial value problem with a non-arbitrary point. Picard's Existence and Uniqueness theorem from my book has associated example problems which only show, well, existence and uniqueness of solutions. Additionally, the example problems from my book and lecture have an actual initial condition, so I'm not sure how to use Picard's theorem to determine the actual rectangular region $\mathcal{R}$. I hate to be that guy, but I'm sincerely unsure where to begin.
Answer: Rewrite the equation as
$$
y'=\frac{t^2}{1+y^3}.
$$
The right hand side has a singularity at $y=-1$. Any rectangle $[a,b]\times[c,d]$ such that $-1\notin[c,d]$ will do. That the solution goes through $(x_0,y_0)$ translates into the initial condition $y(x_0)=y_0$.


Manual incrementation of a feild column (int) form a specific point and row. (Not ID)

Question: So basically  I have an (ID) field that is auto incremented
There is another field that kinda serves as a counter (Counter_ID) for users, everytime a new user of our web site registers that feild in MySql fills up with a incremental number.
Example:

My question: How do I reset the Counter_ID to start from 1 again (1,2,3 etc)? For example I want it to reset in row where Susan is and to start incrementing from there again. The result would be the following:

I am not the original developer of this database and web site so I'm not sure how was the incrementation done in the first place, by the end of every year he always reset to start incrementation from the last user registered.
I'm currently using phpMyAdmin.
Comment: At the office so I can't see the images. Concretely: when/why do you want to reset the counter? What is the logic behind this reset and how do you want it implemented (automatically or manually) ?
Comment: Basically I want to manually increment a field that has an integer value and it's not ID. Every year it gets manually incremented , so for example on dec 31 the number is 250 and od January when new user registered it number will be  251 but it should be 1.

When I suer registers it's written in database and the php code takes those values form the table and dysplays it.
Answer: I'm not sure to fully understand the question, but, it seems that you dont know in what part of the code this Counter_ID gets updated.
Anyway, considering your example, being: -i changed the values so as counter_id and id not to be the same, just for clarity-:

Id, counter_id, name
100, 41, Susan
101, 42, Lee

You could update your table executing the query:
UPDATE table SET counter_id = counter_id - 40 WHERE id >= 100
then you will get

100, 1, Susan
101, 2, Lee
Comment: Ty for replying. It did not work tho, I got some weird decrements :D Please see my new comment with updated screenshots from the table, it's a little bit more clearer about what I'm trying to do. Please reply when you have the time. Ty.
Comment: Can you see if there is a TRIGGER defined in the table? That should be the way this field is incremented. It must take the value of the previus row and then incremented by one. If that is the case you coudl re write the trigger to change to one at the first day of the year. Or manualy update all the records added the new year, and then, for the new ones INSERTED after that, the trigger should take care of the increment. Cheers
Comment: There are no triggers but maybe I could create one? Would that work? :D
Comment: If you are sure there are no TRIGGERs involved, then I'd suggest you stick to manually update all the records of the new year (i.e. if when you arrive to work on january 1st there are 5 clients inserted, then change the 5 of them manually -the query above should work..-, then for the following ones, the database/script should take care of that index.
Comment: Thanks mate, I will try the script again, I probably didn't wrote it right :)
Comment: Hey man the script is perfect! Thank you! You solved my problem :)
Comment: Glad to help!! :) Cheers
Answer: Thank you for the replies guys. I'll explain it a little bit better. So there is this image 1. The ID is auto incremented and the counter is also incremented although I don't exactly know how because  I'm new here and I am not the one that made this database.
After every year the "counter" gets manually incremented again while the ID stays the same image 2.
I have been told that every year I have to change it to start form 1 again and it goes on incrementing by it's self until time comes to "reset" it again. This is what I'm trying to do.


How to save JSON response of HTTP GET in a .json file in C++?

Question: I have written following program to GET a JSON response from the server. The code is correct and the response from the server is as per my expectation.
<code>#include <boost/asio/ip/tcp.hpp>  //I have not shown some header for sake of readability

int main ()
{

        try
        {
            boost::asio::ip::tcp::iostream s;
            s.expires_from_now(boost::posix_time::seconds(60));
            const std::string IP = "123.456.789.000";
            s.connect(IP, "83");

            if (!s) {
                std::cout << "Unable to connect: " << s.error().message() << "\n";
            }

            s << "GET /MY_PATH HTTP/1.1\r\n";
            s << "Host: 123.456.789.000:83\r\n";
            s << "Accept: */*\r\n";
            s << "Connection: close\r\n\r\n";

            // Checking if response is OK.
            std::string http_version;
            s >> http_version;
            unsigned int status_code;
            s >> status_code;
            std::cout<<"\nHTTP " << status_code << std::endl;

            std::string status_message;
            std::getline(s, status_message);

            if (!s || http_version.substr(0, 5) != "HTTP/") {
                std::cout << "Invalid response\n";
            }

            if (status_code != 200) {
                std::cout << "\nResponse returned with status code " << status_code << "\n";
            }

            // Processing the response headers, which were terminated by a blank line.
            std::string header;

            while (std::getline(s, header) && header != "\r")
            std::cout << header << "\n";

            std::cout << "\n";

            // Writing the remaining data to output.
            std::cout << s.rdbuf() << "\n" << std::endl;

         }// try ends here

         catch (std::exception& e) {
            std::cout << "Exception: " << e.what() << "\n";
         }

}
</code>
Response from the server is as follows:
<code>HTTP 200
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft
X-AspNet-Version: 4
X-Powered-By: ASP.NET
Date: Wed, 13 May 2015 07:49:57 GMT
Connection: close
Content-Length: 345

[{"CmdID":"30b2b2ca-376d-42bf-a931-1b92679871fc","EID":"102","CID":"00000102","NAME":"ABCD","BDAY":null,"VDATE":null,"UID":null,"ImgFileType":null,"EIMAGEBASE64STR":null},{"CmdID":"83c7d70da361-4f98-9803-1d5b7771d329","EID":"00000109","CID":"00000109","NAME":"CDEF","BDAY":null,"VDATE":null,"UID":null,"ImgFileType":null,"EIMAGEBASE64STR":null}]
</code>
Now I wish to save the JSON response string into a .json file. How could I do this ?
At this moment I can store the complete server response which includes the HEADER and JSON string. But I am interested in JSON string only.
In the next steps (which I have already done) this json string will be parsed and store into sqlite3 database. But unfortunately I am stuck at this.
Kindly help. Thank you
Comment: `// Writing the remaining data to output.
            std::cout << s.rdbuf() << "\n" << std::endl;` just write to file. What's the problem?
Comment: ohhh...Yes !!!! Now I am embarassed to post this question :(
Comment: Isn't the problem skipping the headers?
Answer: Well, actually this was a cake walk. I apologise to waste your time.
To get just the JSON string output in the file I did the following.
<code>        // Writing the remaining data to output.
        freopen("JSONoutput.json","w",stdout);
        std::cout << s.rdbuf() << "\n" << std::endl;
</code>
freopen() : Reuses stream to either open the file specified by filename or to change its access mode.If a new filename is specified, the function first attempts to close any file already associated with stream (third parameter) and disassociates it. Then, independently of whether that stream was successfuly closed or not, freopen opens the file specified by filename and associates it with the stream just as fopen would do using the specified mode.
This creates a file JSONoutput.json and the only the JSON string gets stored into it and nothing else.


Problem in calculation of SVD for a matrix

Question: SVD Decomposition for the matrix: $$A=\begin{bmatrix} 3&-1&1\\3&0&2\\0&2&2\\-1&0&-2\end{bmatrix}$$
We want: $A=U\sum V^T$
We know that : $V=eigenvectors(A^T*A)$
$A^T*A =\begin{bmatrix} 19&-3&11\\-3&5&3\\11&3&13\end{bmatrix}$
then, considering the order: $\lambda_1 = 14+6\sqrt{5} > \lambda_2= 9 > \lambda_3 = 14-6\sqrt{5}$
$$V=\begin{bmatrix} \frac{5}{19}+\frac{9\sqrt{5}}{19}&-\frac{5}{7}&\frac{5}{19}-\frac{9\sqrt{5}}{19}&\\\frac{5\sqrt{5}}{19}-\frac{12}{19}&\frac{9}{7}&-\frac{5\sqrt{5}}{19}-\frac{12}{19}\\1&1&1\end{bmatrix}$$
Using the square root of the eigenvalues we have:  $$\sum = \begin{bmatrix} 3+\sqrt{5}&0&0\\0&3&0\\0&0&3-\sqrt{5}\\0&0&0\end{bmatrix}$$
For the first three columns of $U$ we can use the ecuations:  $u_1=\frac{1}{\sqrt{14+6\sqrt{5}}}*A*v1$
and the last column of $U$ is given by
$u_4=\frac{N(A^T)}{|N(A^T)|}$
Finally
$U=\begin{bmatrix} \frac{4(\frac{46}{19}+\frac{22\sqrt{5}}{{19})}}{3+\sqrt{5}}&-\frac{68}{21}&\frac{4(\frac{46}{19}-\frac{22\sqrt{5}}{{19})}}{3-\sqrt{5}}&\frac{8}{3}\\
\frac{4(\frac{53}{19}+\frac{27\sqrt{5}}{{19})}}{3+\sqrt{5}}&-\frac{4}{21}&\frac{4(\frac{53}{19}-\frac{27\sqrt{5}}{{19})}}{3-\sqrt{5}}&-\frac{8}{3}\\\frac{4(\frac{14}{19}+\frac{10\sqrt{5}}{{19})}}{3+\sqrt{5}}&-\frac{128}{21}&\frac{4(\frac{14}{19}-\frac{10\sqrt{5}}{{19})}}{3-\sqrt{5}}&\frac{4}{3}\\\frac{4(-\frac{43}{19}-\frac{9\sqrt{5}}{{19})}}{3+\sqrt{5}}&-\frac{12}{7}&\frac{4(-\frac{43}{19}+\frac{9\sqrt{5}}{{19})}}{3-\sqrt{5}}&0\end{bmatrix}$
My issue is that I belive that both $V$ and $U$ are not correct. I can´t tell in which part of the procces.
Comment: Your $V$ isn't an orthogonal matrix. Provided that you've computed the eigenvectors correctly, you should normalize them.
Comment: Thanks! My $V$ matrix seems to be correct now that I normalized the vectors. But my $U$ matrix still wrong. Do you see anything else that could let to errors?
Answer: Your $V$ isn't an orthogonal matrix. For instance, its last row, $(1,1,1)$, is clearly not a unit vector. You may normalise each column of $V$ to get the correct $V$.
After a correct $V$ is obtained, since $A=U\Sigma V^T$, the first three columns of $U$ are given by
$$
AV\operatorname{diag}\left(\frac{1}{\sigma_1},\frac{1}{\sigma_2},\frac{1}{\sigma_3}\right).
$$
The last column, can be obtained by normalising the spanning vector of $\ker(AA^T)$ and hence, as you said, it can also be obtained by normalising the spanning vector of $\ker(A^T)$.
Comment: I corrected the $V$ matrix on my maple document(I checked  using WolframAlpha).The one that still being wrong is $U$.
Is that formula the same as $$u1=\frac{1}{\alpha 1}*A*v1$$? Or what do you mean by "diag"?
Comment: @SEBASTIANMARTINEZSANTOS It means the diagonal matrix with the specified diagonal entries. What do you mean by $u1,\alpha1$ and $v1$?
Comment: $u1$ is the first column of $U$; $\alpha 1$ is the sqare root of $\lambda 1$; and $v1$ the first column of $V$
Comment: @SEBASTIANMARTINEZSANTOS $u1=\frac{1}{3+\sqrt{5}}A\frac{v1}{\|v1\|}$, if you haven't normalised $v1$.


How to create superuser in CentOS 7

Question: I am very new to Linux OS (i've started with CentOS 7), so i was wondering if it's possible to create some sort of super user who will have same privileges as root. By that i mean ability to write + read + execute folders and files who are owned by root user.
Why do i need this? I have VPS with full access. In order to increase security of my web server i have created new user and disabled root login and now i'm logging into my server with RSA public/private key through Putty and WinSCP.
This is my sshd.conf:
Port my_port_number
Protocol 2

HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key

AuthorizedKeysFile  .ssh/authorized_keys
PasswordAuthentication no
RSAAuthentication no
PubkeyAuthentication yes
ChallengeResponseAuthentication no
PermitEmptyPasswords no

SyslogFacility AUTHPRIV

LoginGraceTime 15m
PermitRootLogin no
StrictModes yes
MaxAuthTries 2

GSSAPIAuthentication yes
GSSAPICleanupCredentials no

UsePAM no

IgnoreRhosts yes

X11Forwarding no
ClientAliveInterval 120
ClientAliveCountMax 720

AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

Subsystem   sftp    /usr/libexec/openssh/sftp-server
AllowUsers user_that_i_have_created

Also, i have added this line to /etc/sudoers
## Allow root to run any commands anywhere
root    ALL=(ALL)   ALL
user_that_i_have_created ALL=(ALL) ALL

I've done this also:
usermod -aG wheel user_that_i_have_created

What is the problem now? As a new user that i've created, i'm unable to access files and folders who are allowed to read and modify only by root. As i often need to modify some root owned configuration files (apache's httpd.conf for example) i need to have access to these files through WinSCP because i got used to edit them through its' notepad. Editing these files via Putty (logged as root) would be waste of time.
I've imagined in my head that i will be able to create new user, same as root (regarding privileges and permissions) but only with a different name. Is that even possible in Linux?
Comment: You can't. Root is special not because of the name but because it's UID 0 and GID 0. There is only one 0.
Comment: It is possible to create a user equivalent to root, but it is more common to use `sudo`.
Answer: That is what sudo is for. If configured correctly, a user in the sudoers file can do everything root can do as well.
To edit a file: Instead of vim filename you just use sudo vim filename and similar for every other command.
Creating an additional actual root user is not really possible - you can give another user the id 0 as well, but then that's the actual root user with another name.
Comment: Sudo doesn't help with scp though.
Comment: @GeraldSchneider: Right. Having another user with id 0 makes restricting root login useless though. Having this restriction is more important then editing a file with notepad IMHO...
Comment: Thank you for your answer and explanation! I agree with you, but on the other hand i find that WinSCP feature of editing files, downloading (making a backup file on my local PC, which is very important also) and uploading files to web server easily very handy, so that's the main reason why i have asked this question.
Comment: @Ljubisa Livac If so, just give write access to your "favorite" config files for your personal login: chgrp mylogin /etc/http/httd.conf; chmod g+w /etc/http/httd.conf.
Answer:
Editing these files via Putty (logged as root) would be waste of time.

If the above is really your sweet spot with regards to security versus workload, then happily set PermitRootLogin without-password and login directly via WinSCP as root to edit anything you wish.
All the "don't login as root" idea is for people that can afford some of their time to use sudo. If you only allow root login with a passphrase-protected private key, the vulnerability surface is approximately the same (one private key needed + one password needed).
However I find highly debatable the assertion that the Putty approach is slower than WinSCP. It's faster for me - I don't know, maybe I don't know how to use WinSCP efficiently. Or maybe you need a refresher on your bash skills.
Comment: I've ended up with this solution, as i've returned to using root as a user and a passphrase-protected private key, because WinSCP makes my life easier and it's important for me to use it without restrictions. I'm sure that you know how to use WinSCP efficiently, but i'm bad at Putty :)
Answer: Expanding on Veniamin's comment,  an alternative to becoming root is to alter the permissions on config files such that your personal user can edit them.
Perhaps you create a wwwadmin user group and add yourself to it. Then create your web server configs in /etc/httpd/conf.d/  and make them writable by group wwwadmin.
You might also want to be able to restart httpd. You can create sudo rules that only allow that one service restart command as root.
Starting httpd as root is optional, too. You could override the systemd httpd.service to add CAP_NET_BIND_SERVICE (for ports < 1024)  and to run as a different user and group.  See the systemd.exec man page.

How to create superuser in CentOS 7


How to add version parameter to JS & CSS files to avoid browser cache?

Question: What is the best way to append the file version number in order to give to the users the right JS/CSS files?
Actually i am working on a website which has a browser cache expiration date set to 5 days.
Comment: Drupal 7 & 8 both do that automatically for every asset added through the API (drupal_add_js/drupal_add_css/#attached). If it's missing in your installation, it'll need some digging to find out what code is responsible for removing it. If you're not adding assets through the API, that'll be thing to change. Of course bear in mind that you need to think about this in terms of full page cache too. The cache buster will change automatically, when it needs to or the css/js cache is flushed, but unless the relevant page cache is cleared, users will never know because they'll be served the old HTML
Comment: You should be able to add the js via drupal_add_ja right? If not can you please explain why?
Comment: I can't vote to close questions yet, but I'd do so here, as this question is far too broad. If you find you need to disable caching for attached resources for certain reasons, please describe your use case in more detail, how you add these resources, why/for whom they shall not be cached, and why you find you have to add cache busters manually.
Comment: correct, add this as answer
Comment: @Mike Why do you want to work around what Drupal already provides via it's API? I set the browser cache to 1 year but changes to the CSS and JS files go out when I flush the cache.
Comment: @mikeytown2 it was something done by someone else in an anti-pattern way
Comment: i found some css were added without using drupal_add_css
Answer: The easiest way to achieve this is to add the 'css_js_query_string' variable to the end of your css/js path. This will have to be hard-coded or via a preprocess function in template.php.
Example:
<code><script src="/path/to/js/file/file.js?ver=<?php print variable_get('css_js_query_string', ''); ?>"></script>
</code>


How to filter any variables greater than a value in a data.frame in R?

Question: I am sure that this is a very simple question and I am upset that I can't solve it.
I have a data.frame (df) looking like this
    df <- data.frame("genus" = c("a","b","c","d","e", "f"),
                 "Kit1" =c(0,0,0,102, 10, 2),
                 "Kit2" = c(3,2,0,105,11, 12),
                 "Kit3" = c(1,20,310,102,1,99),
                 "Kit4" = c(0,0,0,190,4,0))
>df
      genus Kit1 Kit2 Kit3 Kit4
1     a    0    3    1    0
2     b    0    2   20    0
3     c    0    0  310    0
4     d  102  105  102  190
5     e   10   11    1    4
6     f    2   12   99    0

and I want to filter all rows that contain >100 counts.
filter_all(all_vars(.>100) # filters all rows, that contain >100 counts,

In my case, only genus "d" is preserved, everything else is discarded, also genus "c" although here Kit3 shows 310 counts.
if I use
filter_all(any_vars(.>100) # nothing happens, although for my understanding this would be the correct command

I want to preserve all rows, where minimum 1 x 100 counts is exceeded.
I don't know why, but I am a bit lost with this easy question.
You would help me a lot :)
Looking forward for your help!
Kathrin
Answer: We can use if_any (from  dplyr -version >= 1.0.4)
library(dplyr)
df %>%
  filter(if_any(starts_with('Kit'), ~ . > 100))

-output
#    genus Kit1 Kit2 Kit3 Kit4
#1     c    0    0  310    0
#2     d  102  105  102  190

If all the 'Kit' column should have value > 100, use if_all
df %>%
  filter(if_all(starts_with('Kit'), ~ . > 100))

If the version is older, could use filter_at with any_vars (getting deprecated)
df %>%
    filter_at(vars(starts_with("Kit")), any_vars(. > 100))

Comment: I updated my version, and now it works :) Thank you very much for your help!
Comment: When I try this, I get an error and it tells me that it doesn't know if_any(), although dplyr is loaded..

Error: Problem with `filter()` input `..1`.
x could not find function "if_any"
i Input `..1` is `if_any(contains("Kit"), ~. > 100)`.
Run `rlang::last_error()` to see where the error occurred.

Maybe the across()-fct is needed?!
Comment: @Kathrin Can you check your `packageVersion('dplyr')`.  I used `1.0.4`
Comment: @Kathrin if you have an older version, then `df %>% filter_at(vars(starts_with("Kit")), any_vars(. > 100))` should work, but it may get deprecated


how to create dynamic reports in java desktop application

Question: I am creating java desktop application. in the application i want to create many reports with different parameters. which framework is easy to use and supports for desktop application.i am new to this concept.
Comment: what is the difference between ireport and source forge dynamic report?
Answer: JasperReports is quite well known and should help you do what you need:

JasperReports is the world's most popular open source reporting
  engine. It is entirely written in Java and it is able to use data
  coming from any kind of data source and produce pixel-perfect
  documents that can be viewed, printed or exported in a variety of
  document formats including HTML, PDF, Excel, OpenOffice and Word.
Comment: @Siddharth: You could render your reports in a PDF format and then either use the systems default PDF renderer (recommended) or else refer to some other tool such as [JPedal](http://www.jpedal.org/). Also, I have never used these technologies, so you will have to make some of your own research.
Comment: whether we can view the report file inside the java frame?


Can I use titanium to build a web app and mobile apps?

Question: Are you able to use titanium to build a mobile web app, such that it can run on something like m.website.com and also have a mobile version of the app packaged to Android or iOS?
Answer: no you cannot.
titanium is complied code that needs to be deployed on a mobile device.
you are looking for something like phoneGap
Answer: Now, the answer is Yes.
Since Titanium 2.X you can also deploy your stuff as a mobile web project,
see http://docs.appcelerator.com/titanium/3.0/#!/guide/Mobile_Web_Support :

"Titanium Mobile SDK version 2.0 or newer is recommended for Mobile Web development."

At the moment Titanium 3.X deals with following platforms:

Android
Blackberry
iOS
Tizen (a free Linux-based mobile OS)
Mobile Web

see http://docs.appcelerator.com/titanium/3.0/#!/guide/Titanium_Compatibility_Matrix-section-29004837_TitaniumCompatibilityMatrix-MobileDevelopment
Answer: no you cannot do.
But you can do the mobile web


Proving that limit exist

Question: To show that limit exist and is equal to zero
$$\lim_{(x,y)\to(0,0)}\frac{\sin(x^2y + xy^2)}{xy}$$
Comment: @Kristoffer thanks
Answer: $$
0\leq\left|\frac{\sin(xy(x+y))}{xy}\right|\leq|x+y|,
$$
because $|\sin x|\leq|x|$.
Answer: $$\\start\\by\\factoring\\xy $$
Answer: $$ \lim_{(x,y)\to (0,0)} \frac{\sin(x^2y+xy^2)}{xy}= \lim_{(x,y)\to (0,0)} \frac{x^2y+xy^2}{xy} $$
$$
= \lim_{(x,y)\to (0,0)} \frac{xy(x+y)}{xy} = \lim_{(x,y)\to (0,0)} x+y=0
$$

Proving that limit exist


Problema com acentuação em um site

Question: Em um site que desenvolvi, tenho o seguinte texto:
A linha depilação da..., esse texto abre perfeitamente no Windows, em qualquer navegador.
Já, no Mac, aparece o texto da seguinte forma: A linha de depilac,a~o.
O que pode ser isso?
A codificação do site está assim:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Comment: Você já incluiu a declaração `` identificando o charset. Mas os **arquivos** HTML estão neste padrão (UTF-8)?
Comment: Isso ocorre em qual navegador?
Comment: Cara, no Mac eu conferi no Google Chrome, porém no Chrome do Windows está Ok.
Comment: Acredito que seja no safari...
Comment: No Safari do Windows está Ok.
Answer: Para poder escrever depilação e aparecer tal como escreve com a acentuação tem que alterar a codificação para:
<meta http-equiv="Content-Type" content="text/html; charset=8859-1" />

Caso contrario terá que escrever Depilação para aparecer Depilação.
Comment: Tem que pensar que quem vai usar o site não terá a fonte do browser alterada para ler a sua pagina caso o charset esteja bem configura para o que o vosso gerenciador debita, um conselho já tive um problema parecido com esse e a questão estava nas extensões que tinha bloqueado sem querer e resolvi com uma desinstação completa.
Comment: Olá. Esse texto é gerenciável, o nosso sistema já faz isso automaticamente. Ou seja, se fosse isso, ele daria problema no Windows também.
Comment: Não percebi a sua resposta
Comment: Eu não preciso informar o charset, o nosso gerenciador de conteúdo já faz isso automaticamente.
Comment: Assim o problema não é da codificação mas do browser.
Comment: Tem como forçar a codificação do browser?
Comment: Já agora qual foi a solução adoptada? A alteração do `charset` ou a desinstalação.
Comment: Cara, isso está na minha fila de bugs, só vou voltar pra ele semana que vem ahahah. Valeu :P
Answer: Utiliza um HTMLEnconde:
HttpUtility.HtmlEncode(myString);
Esse código seria para uma aplicação .NET, mas você também pode utilizar jQuery para resolver isso:
$('#campo').text(value).html();
Answer: Duas possíveis soluções:
1) Aparemente pode ser um problema de fontes do Mac.Abra o Universal Type Client, pode ser que tenha 2 versões da fonte Arial em conflito.
Selecione a copia universal da fonte Arial e a desative.
2) Alterar a codificação nas configurações do Chrome
Ferramentas (Tools) > Codificação (Encoding) e selecione a opção Detecção Automática (Auto-detect).
Comment: Pode ser isso cara. Muito estranho que isso está acontecendo só com esse site. Sendo que sempre uso as mesmas configurações.
Comment: No Mac, além do Chrome, você tentou com outro navegador? deu certo?

Problema com acentuação em um site


Query nodes with a specific word in them

Question: I'm very new to Drupal and I need to grab all nodes that have a certain word in them, for example I want to grab all nodes with the Word 'Hello' inside the body field. I need to use the EntityFieldQuery class too. I'm assuming I need to use the fieldCondition method but not sure how to set that up as there's not a lot of documentation...
Thanks
Alex
Answer: I'm not sure I'd agree there's not a lot of documentation out there (there are tons, just search Google for EntityFieldQuery).
That said, something like:
<code>$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'some_type')
  ->fieldCondition('body', 'value', '%' . db_like($input_string) . '%', 'LIKE');

$results = $query->execute();
</code>
is probably what you're looking for
Comment: Thanks, I agree there's lots of documentation but not enough code examples.
Comment: Good point actually, if it was clearer that EFQ wraps around a standard SelectQuery object it would probably be more obvious where to look for samples


Receber dados json mysql

Question: Olá, tenho a seguinte função para ler dados do BD mysql.
Aqui eu chamo ->
$clientes = DBRead('clientes', null, 'nome, telefone1');

Aqui eu exibo ->
echo $nam = json_encode($clientes);

Resultado:
[
  {
    "nome":"Davi",
    "telefone1":"654654"
  },
  {
    "nome":"Davi",
    "telefone1":null
  },
  {
    "nome":"Davi",
    "telefone1":null
  }
]

Aqui tento manipular os resultados separadamente:
$jsonObj = json_decode($nam);

    $dados = $jsonObj->nome;

    foreach ( $dados as $e ) { echo "nome: $e->nome "; }

mas da o seguinte erro

Notice: Trying to get property of non-object in...
Warning: Invalid argument supplied for foreach() in...

Já tentei colocar ", true" apos o decode mas não funcionou.
Alguém tem uma idéia de como eu posso tratar esses dados?
Aqui a Função de busca em outro arquivo->
    function DBRead($table, $params = null, $fields = '*'){
    $table = $table;
    $params = ($params) ?" {$params}" : null;
$query = "SELECT {$fields} FROM {$table}{$params}";
$result = DBExecute($query);
if(!mysqli_num_rows($result))
    return false;
else{
    while ($res = mysqli_fetch_assoc($result)){
        $data[] = $res;
    }
    return $data;
}
}

Answer: este código não vai funcionar mesmo, porque $dados não é um objeto, $jsonObj é que é. Faça assim que dá certo:
$jsonObj = json_decode($nam);

    foreach ( $jsonObj as $e ) { echo "nome: $e->nome "; }

Answer: Muito Obrigado a Todos, graças a ajuda consegui resolver da seguinte maneira.
 $clientes = DBRead('clientes', null, '*');
  $nam = json_encode($clientes);
  $res = json_decode($nam, true);
  foreach ( $res as $e )
      { echo $e['nome']}

Answer: Tenta assim
$jsonObj = json_decode($nam);
foreach ( $jsonObj as $e ) {
echo "nome: $e->nome - telefone: $e->telefone1
";
}

Receber dados json mysql


kendo grid delete command not working

Question: i have developed a web application using kendo ui tools and theres a kendo grid with batch edit mode..
but when i press the delete button for any record in kendo grid it will erase from the list in grid but actually not in the data source.when i reload the page or grid the deleted item will still exist..
here is the code of my grid

can not identify that where is the fault going and can somebody please help me to solve this matter.
Comment: Did you click on "Save changes"?
Comment: Did you check if you have any error in the browser console?
Comment: Do you use Firebug or similar? Does it show any error while executing your javascript. I've tried your code and it worked but of course I've done some modification since I do not have all your project.
Comment: then can you please send me your modifications please..
Comment: yes i cheked wit firebug and it will not fire the method that used to delete the record in controller.. that is the problem
Comment: yes i cheked with "Save Changes"..it show as record deleted when i press "Save changes" but on page refresh or grid reload, record is still there.. that is the problem.
Comment: Was my answer useful sanzy?
Comment: Bug 2.0, hello sanzy I'm asking for a response.
Comment: So any progress or...?
Comment: sanzy is there any reason why your ignoring me as I'd just like to know if my answer solved the issue (and then get it marked as correct) or if you resolved it by other means in which case I'd still be interested to find out how so I could improve my own knowledge.
Comment: @Myzifer i'm extremely sorry for couldn't response to your answer because i was not there due to another reason.. just went through your answer and it will not give me the positive feedback.
Comment: I also noticed in your other commands you set the datatype as jsonp which shouldn't be changed from just simply json so if you change that back and remove the type Post then that should work.
Comment: @Myzifer ok sir.. il check and let you know whether it is helped or not.. thank you anyway..
Comment: @sanzy have you checked my answer? I hope it help you and others who refers later. and answer your not answered question after 6 month.
Answer: There are three common reasons delete won't work:

1. Not setting editable of grid to inline or popup. The deleted items will be automatically processed through transport destroy only for "inline"/"popup" edit modes. Ex:
editable: {
   mode: "inline",
}
//or
editable: "inline"

2. If on your datasource, you have the batch flag set to true, this means the datasource will make the call only after you tell it to, e.g calling sync(). Ex:
var dataSource = new kendo.data.DataSource({
    batch: true,
    //.....
});
//... in some where e.g in a save button click event call the following line:
dataSource.sync();

3. You should define id to your primary key of database field name inside model of datasource. Ex:
   model: {
        id: "ProductID",
        fields: {
            ProductID: { editable: false, nullable: true },
        }
    }

So the problem with your code is first one, i.e you did not set editable to inline or popup
Answer: If you choose not to include editable.mode in order to utilize the in-cell editing, you can set the toolbar of the grid to include the option save:
$("#grid").kendoGrid({
    dataSource: {
        transport: {
            ....
        },
        schema: {
            ....
        }
    },
    toolbar: ["create", "save", "cancel"],
    columns: [
        ....
    ],
    editable: true
});

This will create a save button at the toolbar of the grid. After deleting any records by clicking the destroy command button, click on the save button to have the grid to make an Ajax call to the server to delete the record.
If you would rather delete the record automatically without including the save button, you could add a change event handler to the datasource of the grid:
$("#grid").kendoGrid({
    dataSource: {
        transport: {
            ....
        },
        schema: {
            ....
        },
        change: function(e) {
            if (e.action === "remove") {
                this.sync();
            }
        }
    },
    columns: [
        ....
    ],
    editable: true
});

This will automatically sync the changes you made to the grid with the server when there's a data change.
Answer: Hmm try not including type: "POST", and see if it now works since as far as I can see that bit isn't included on the demo's and I don't think I included it when I last did inline edits/deletes.
Answer: I had put an arbitray name for an int on the server Delete Method.
    [HttpPost]
    public ActionResult DeleteRandomTest(Int32 randomTestId)
    {
         ...
    }

The default modelbinder was probably looking for a property called Id (same as the primary key of my type according to the configuration of the model).
 .Model(config => config.Id(p => p.Id))

In fact, I proved this by changing the signature to the following:
    [HttpPost]
    public ActionResult DeleteRandomTest(Int32 Id)
    {
        ...
    }

My break point was hit after that.
Ultimately, I used the full type as the parameter as shown in the Kendo examples because I didn't want to have poorly named parameter names (not camel case) in the action. Shown as follows:
    [HttpPost]
    public ActionResult DeleteRandomTest([DataSourceRequest]
         DataSourceRequest request, RandomDrugTest randomDrugTest)
    {
       ...
    }

This seems to the be the reason it wasn't working.
Answer: I had the same issue. My issue was caused by having a data property in the kendo model. Example:
{id: 1, data: ""}

kendo grid delete command not working


The program doesn't end when player 1 life reaches 0

Question: I'm making a little game using the Java Swing, in which there are four bottoms: attack player 1, attack player 2, regenerate player 1, regenerate player 2. When attack player 1 or attack player 2 push bottom are pressed, it removes -25 from the life of the player, vice versa, when regenerate bottoms are pressed it adds +15 to player's life. Now, everything works perfectly here, but when life reaches zero, the player is dead and the label text changes in: "Player 1 is dead" or "Player2 is dead", but this never happens:

as you can see from the picture, player 1 life has been incremented and player 2 life even reached -50, this is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swing16 implements ActionListener {
    static int life1 = 100;
    static int life2 = 100;
    JLabel AttRig;

    Swing16() {
        // Imposta le impostazioni del frame
                JFrame jfrm = new JFrame("game");
                // Layout basico
                jfrm.setLayout(new FlowLayout());
                // Grandezza del frame (500 x 500).
                jfrm.setSize(500, 500);
                // Esci dal programma se l'utente esce dal frame.
                jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                JButton attacca1  = new JButton("Attack player one (-25)"); //Attack player two (-25)
                JButton rigenera1 = new JButton("Attack player two (-25)"); // Regenerate player one (+15)
                JButton attacca2  = new JButton("Regenerate player one (+15)"); // Attack player one (-25)
                JButton rigenera2 = new JButton("Regenerate player two (+15)");

        // Aggiungi action listeners per i push bottom.
        attacca1.addActionListener(this);
        attacca2.addActionListener(this); // rigenera1.addActionListener(this);
        rigenera1.addActionListener(this);
        rigenera2.addActionListener(this);
        // Aggiung pulsanti.
        jfrm.add(attacca1);
        jfrm.add(attacca2);
        jfrm.add(rigenera1);
        jfrm.add(rigenera2);
        // Nuovo label.
        AttRig = new JLabel("Player 1 life: 100 | Player 2 life: 100");

        // Aggiungi label al frame
        jfrm.add(AttRig);
        // Visibilità del frame
        jfrm.setVisible(true);

    }

    // Cosa succede se i bottoni vengono cliccati.
     public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("Attack player two (-25)")) {
                life2 = life2 - 25;
                AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
            }
            else if(e.getActionCommand().equals("Regenerate player one (+15)")){
                life1 = life1 + 15;
                AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
            }
            else if(e.getActionCommand().equals("Attack player one (-25)")) {
                life1 = life1 - 25;
                AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
            }
            else if(e.getActionCommand().equals("Regenerate player two (+15)")) {
                life2 = life2 + 15;
                AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
            }
            else if(life1 < 0) {
                AttRig.setText("Player 1 dies...");
            }
            else if(life2 < 0) {
                AttRig.setText("Player 2 dies...");
            }

    }

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Swing16();
        }

    });

  }
}

what may I do make restart the program through another push bottom? Thank you very much.
Comment: Try and remove the `else` from `else if(life1 < 0)` to make it a normal `if`, otherwise those 2 blocks will never be reachable i guess because one of the previous if blocks is always entered.
Comment: You might want to learn how to step through your code with a debugger to catch those things yourself. :)
Answer: You should check the life values after(!) you changed them.
In public void actionPerformed(ActionEvent e) method, the following else if part should be 2 separate if statements as follows:
        if(life1 < 0) {
            AttRig.setText("Player 1 dies...");
        }
        if(life2 < 0) {
            AttRig.setText("Player 2 dies...");
        }

So it should look like this:
 public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("Attack player two (-25)")) {
            life2 = life2 - 25;
            AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
        }
        else if(e.getActionCommand().equals("Regenerate player one (+15)")){
            life1 = life1 + 15;
            AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
        }
        else if(e.getActionCommand().equals("Attack player one (-25)")) {
            life1 = life1 - 25;
            AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
        }
        else if(e.getActionCommand().equals("Regenerate player two (+15)")) {
            life2 = life2 + 15;
            AttRig.setText("Player 1 life: " + life1 + " | " + "Player 2 life: " + life2);
        }

        if(life1 < 0) {
            AttRig.setText("Player 1 dies...");
        }
        if(life2 < 0) {
            AttRig.setText("Player 2 dies...");
        }

}


Aspas dentro de aspas e novamente dentro de outras aspas?

Question: Tenho uma variável string chamada [Conteudo] e quero atribuir a ela a tag de um botão que chama um javascript. Estou tentando assim:
        Conteudo = "<input id='btnOculta_" + lin + "' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, 'OcultaNovoMedicamento_1')' style='float:left' />"

Porém no trecho onclick='Ocultar(this, 'OcultaNovoMedicamento_1')' ele está entendo a segunda ' como um encerramento da primeira e não como uma segunda abertura. E me retorna um código todo errado.
Esperado:
<input id="btnOculta_1" type="button" value="novo" class="btn btn-default" onclick="Ocultar(this, 'OcultaNovoMedicamento_1')" style="float:left" />

Obtido (errado):
<input class="btn btn-default" id="btnOculta_1" style="float:left"         onclick="Ocultar(this, " type="button" value="novo" ocultanovomedicamento_1')'="">

uComo resolvo esse pepino?
Answer: Podes usar \ para escapar essas aspas e fazer assim:
onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")'

Exemplo:

var lin = 2;
var Conteudo = "<input id='btnOculta_" + lin + "' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")' style='float:left' />";

document.body.innerHTML += Conteudo;

function Ocultar(el, txt) {
  console.log(el.tagName, txt);
}

Em browsers modernos, ou se estiveres a transpilar, podes usar template strings assim:
Conteudo = `<input id='btnOculta_${lin}' type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, "OcultaNovoMedicamento_1")' style='float:left' />`

Comment: Valew @Sergio a sua primeira sugestão usando \ não funcionou... não sei s eporque teste correndo aqui, rsrs. Mas a segunda funcionou muito bem! Obrigado, me salvou aqui. No seu exemplo só tem uma aspas duplas sobrando no fim, mas ok.
Comment: @AlamBique corrigi, assim ficam os dois exemplos sem bugs :)
Answer: Tenta usar aspas duplas com escape em OcultaNovoMedicamento_1:
Conteudo = "<input id='btnOculta_'  type='button' value='novo' class='btn btn-default' onclick='Ocultar(this, \"OcultaNovoMedicamento_1\")' style='float:left' />"

Comment: Obrigado @italo este metodo tem uma compatibilidade maior com browsers antigos né? Muito bom! Cara onde vocês aprendem esses segredos? kkkkk!


Column indicating count in Excel

Question: Let's say I have an Excel sheet with the following columns
Year ProjectName
2001 AAA
2001 MMM
2001 XXX
2002 CCC
2003 KKK
2003 NNN

I want to generate a new column indicating the total number of projects in that year:
Year ProjectName NumberOfProjects
2001 AAA         3
2001 MMM         3
2001 XXX         3
2002 CCC         1
2003 KKK         2
2003 NNN         2

How do I do this?
Comment: Why aren't you using a pivot table for this? You can use `[year]` and `[ProjectName]` in `Rows` and again `[ProjectName]` in `Values`. This will group by `count` and you will have what you want.
Comment: Assuming your years are in column `A` with your header row in Row `1`, then stick this in C2: `=countif(A:A, A2)`. If you search your question's title in Google the first link that pops up has this exact solution.
Comment: agreed, use a pivot table
Answer: Assuming your data is in columns C and B, in column C add the following:
=COUNTIF(A$2:A$6,A2)

(example for row 2, for other rows, change A2 as needed)

Column indicating count in Excel


.NET Remoting - Multiple Channel Register on Client

Question: My application has a working HttpChannel that I can invoke a method on remote server.
Now, in the application, I need to register another HttpChannel that invokes another method on another server.
But the application fails if I don't unregister the first channel.
How can I make both of these remotings successfully invoke remote methods?
Answer: We had a similar situation and decided to just register a channel only when needed and then unregister it immediately after we were done with it, similar to the disconnected model of ADO.NET where you connect, get the data, and then disconnect.
Per the documentation:

Channels are registered on a per-application-domain basis. A single
  process can contain multiple application domains. When a process ends,
  all channels registered by it are automatically destroyed.
Channel
  names must be unique within an application domain. For example,
  because the default channels have names, to register two HttpChannel
  objects in one application domain, you must change the names of the
  channels before registering them. The following C# code example
  demonstrates this.

<code> IDictionary prop = new Hashtable();
 prop["name"] = "http1";
 prop["port"] = "9001";
 ChannelServices.RegisterChannel(new HttpChannel(prop, null, null));
</code>

You cannot register a channel that listens on a specific port more
  than once. Even though channels are registered on a
  per-application-domain basis, different application domains on the
  same machine cannot register the same channel listening on the same
  port.
If you are not sure about whether a port is available, use 0
  (zero) when configuring your channel's port and the remoting system
  will choose an available port for you.
Clients can communicate with a
  remote object using any registered channel. The remoting system
  ensures that the remote object is connected to the right channel when
  a client attempts to connect to the object. The client is responsible
  for calling ChannelServices.RegisterChannel before attempting to
  communicate with a remote object. If it expects a callback function,
  the client must register a channel and a port.

So, the Channel 's name has to be unique within your applicaiton domain, and by design, only one http channel can have one port at a time.  You can't have two different channels on the same port.
Comment: Thanks David. But, what happens to the requests that attempt to use the channel that you unregister? Isn't it a problem?
Comment: Yes.  The only option is to register two different channels on two different ports.  Having multiple channels open onteh same port is not allowed, so you have one challen on a port to listen (as the server), and use a different channel to call out to the other server (as the client).
Comment: As a client, do we need to configure "port" or "proxyPort"? And does the server need to make any changes?


How to read a response as number from server when calling a API by using FETCH in Javascript

Question: backend server API  send me a number and i have to fetch it in a response in react front end. But i am not able to read it by using response.json() or response.body(). Can anyone help me how to read the response as a number for fetch repsonse.
<code>
  let url = "API URl"
    var requestOptions = {
      method: 'GET',
      redirect: 'follow'
    };
 fetch(url + new URLSearchParams({selectedReportName: this.state.selectedRepor}), requestOptions)
        .then( response => response.json())
        .then(data =>{
           console.log ("Data " + data)} )

</code>
Comment: you don't need to call .json() function. Just console.log your response and see what you are getting
Answer: <code>      let url = "API URl"
    var requestOptions = {
      method: 'GET',
      redirect: 'follow'
    };
 fetch(url + new URLSearchParams({selectedReportName: this.state.selectedRepor}), requestOptions)
        .then( response => response.json())
        .then(data =>{
           console.log ("Data " + data)} )
        .catch(err => console.log("err:", err));
</code>
Try the above-mentioned code, It'll give you an exact error if we're not getting 200 response from the server or something is not working.
Comment: Sorry i forgot to attach catcgh statement in code. It is throwing me below eerorSyntaxError: Unexpected token B in JSON at position 0
Comment: can you paste the error here, seems like you're not getting valid json.
Comment: for testing, just console the response without .json() method
Comment: Response is Object ReadableStream and the backend service ( Node Js) is sending data as number.


Verificar data e hora do arquivo e manter o mais atual em Batch

Question: Preciso de um programa em Batch onde irei especificar dois arquivos, ele irá comparar a data e hora da criação dos mesmos e caso o primeiro seja mais atual ele deletaria o segundo e copiaria o primeiro, caso o contrário ele não irá fazer nada.
Comment: Quando você diz "batch", se refere a um programa que possa ser agendado escrito em qualquer linguagem ou um programa usando Spring Batch?
Comment: Olá @GiulianaBezerra

Preciso que esse programa seja em .bat (arquivos de lote) ou em VBA, eu irei agendar esse programa no Task Scheduler do Windows para rodar a cada 30min, verificando se alguém fez novas atualizações no programa da empresa, essa verificação será feita comparando a data e a hora de modificação do arquivo, caso tenho alguma alteração ele irá deletar o arquivo antigo e fazer a copia do arquivo novo.
Comment: O arquivo é muito grande? Porque não vejo a necessidade da comparação, sobrescreve ele é pronto, rsrs
Comment: @AlexandreUeda, esses arquivos estarão numa só pasta? Você pode usar essa resposta que coloquei, vou adicionar um comando para que copie o conteúdo de uma pasta caso o arquivo seja mais recente.
Answer: Esse comando não deleta, mas só copia e sobrescreve se o arquivo de origem for mais novo do que o de destino.
Deve colocar o caminho completo dos arquivos para que funcione corretamente.
A cópia faz com que o arquivo de destino seja substituído pelo de origem, se o nome do arquivo for diferente e o arquivo de origem for mais recente, a cópia será realizada, mas o nome continuará o do arquivo de destino.
@echo off

set /p file1=Digite o caminho e nome do arquivo 1:

set /p file2=Digite o caminho e nome do arquivo 2:

xcopy "%file1%" "%file2%" /y /d

pause

Caso queira copiar somente os arquivos mais recentes de uma determinada pasta basta fazer conforme abaixo:
xcopy "C:\PastaOrigem\." "C:\PastaDestino" /y /d

Entenda mais sobre o xcopy:
Copia arquivos e árvores de diretórios.

XCOPY origem [destino] [/A | /M] [/D[:data]] [/P] [/S [/E]] [/V] [/W]
                           [/C] [/I] [/Q] [/F] [/L] [/G] [/H] [/R] [/T] [/U]
                           [/K] [/N] [/O] [/X] [/Y] [/-Y] [/Z] [/B] [/J]
                          [/EXCLUDE:arquivo1[+arquivo2][+arquivo3]...]

  origem       Especifica o(s) arquivo(s) a ser(em) copiado(s).
  destino  Especifica o local e/ou o nome dos novos arquivos.
  /A           Copia somente arquivos com o atributo de arquivamento
               definido; nao altera o atributo.
  /M           Copia somente arquivos com o atributo de arquivamento
               definido; desativa o atributo de arquivamento.
  /D:m-d-a     Copia os arquivos alterados durante ou após a data
               especificada. Se nao for definida uma data, copia apenas os
               arquivos cujo tempo de origem seja mais novo do que o tempo
               de destino.
  /EXCLUDE:arquivo1[+arquivo2][+arquivo3]...
               Especifica uma lista de arquivos contendo cadeias de
               caracteres. Cada cadeia deve estar em uma linha separada nos
               arquivos. Quando qualquer cadeia corresponder a qualquer parte
               do caminho absoluto do arquivo a ser copiado, esse arquivo
               deixará de ser copiado. Por exemplo, especificar uma cadeia de
               caracteres como \obj\ ou .obj excluirá todos os arquivos sob o
               diretório obj ou com a extensao .obj, respectivamente.
  /P           Solicita confirmaçao antes de criar cada arquivo de destino.
  /S           Copia diretórios e subdiretórios, exceto os vazios.
  /E           Copia diretórios e subdiretórios, inclusive os vazios.
               O mesmo que /S /E. Pode ser usado para modificar /T.
  /V           Verifica o tamanho de cada novo arquivo.
  /W           Solicita que você pressione uma tecla antes de copiar.
  /C           Continua copiando, mesmo que ocorram erros.
  /I           Se o destino nao existir e mais de um arquivo estiver sendo
               copiado, pressupoe que o destino deve ser um diretório.
  /Q           Nao exibe os nomes de arquivos ao copiar.
  /F           Exibe os nomes de arquivos de origem e de destino completos ao
               copiar.
  /L           Exibe arquivos que seriam copiados.
  /G           Permite a cópia de arquivos criptografados para um destino que
               nao oferece suporte a criptografia.
  /H           Copia arquivos ocultos e do sistema também.
  /R           Substitui arquivos somente leitura.
  /T           Cria a estrutura de diretórios, mas nao copia arquivos. Nao
               inclui diretórios ou subdiretórios vazios. /T /E inclui
               diretórios e subdiretórios vazios.
  /U           Copia apenas os arquivos que já existem no destino.
  /K           Copia atributos. O Xcopy normal redefinirá os atributos
               somente leitura.
  /N           Copia usando os nomes curtos gerados.
  /O           Copia as informaçoes de ACL e proprietário do arquivo.
  /X           Copia configuraçoes de auditoria de arquivo (implica /O).
  /Y           Suprime o prompt para você confirmar se deseja substituir
               um arquivo de destino existente.
  /-Y          Exibe o prompt para você confirmar se deseja substituir
               um arquivo de destino existente.
  /Z           Copia arquivos de rede no modo reiniciável.
  /B           Copia o próprio Vínculo Simbólico, e nao o destino do vínculo.
  /J           Copia usando E/S sem buffer. Recomendável para arquivos muito
               grandes.

A opçao /Y pode ser predefinida na variável de ambiente COPYCMD.
Isso pode ser anulado por /-Y na linha de comando.


The limit of the sum of two floor functions

Question: The question asks to calculate the limits where they exist, then the following limit is given:
$$\lim_{x\rightarrow2}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor),   \text{where}\lfloor x\rfloor \text{is the floor function.} $$
Thus I approach it from the left hand side and then from the right hand side:
$$\lim_{x\rightarrow2^-}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor)\textbf{ and} \lim_{x\rightarrow2^+}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor) \\=(1)+(-3)\phantom{help me!} =(2)+(-2)$$
Am I correct in making the following conclusion:
Since $$\text{Since} \lim_{x\rightarrow2^-}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor)\neq\lim_{x\rightarrow2^+}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor),\text{ we have that}\\ \lim_{x\rightarrow2}(\lfloor x\rfloor +\left\lfloor -x\right\rfloor) \text{ does not exist.}
$$
or are my calculations wrong?
Comment: For the first limit, think of $x$ as $1.99$.  Then $\lfloor x\rfloor=1$ and $\lfloor -x\rfloor=-2$.  For the second limit, think of $x$ as $2.01$.  Then, $\lfloor x\rfloor = 2$ and $\lfloor -x\rfloor = -3$.  Note that the double bracket notation is frequently used for the integral part of a function instead of the greatest integer function (so make sure to double check your notation).
Comment: Thank you (just stared Calculus I, trying to get-the-hang-of things)
Answer: From the left, it should be
$$(1)+(-2) = -1$$
and from the right, it should be
$$(2)+(-3) = -1$$
so the limit is $-1$.

Explanation:

If $x$ is a little less than $2$, strictly between $1$ and $2$, then $-x$ is strictly between $-2$ and $-1$.
If $x$ is a little more than $2$, strictly between $2$ and $3$, then $-x$ is strictly between $-3$ and $-2$.

More generally, the behavior of the function $f(x) = \lfloor{x}\rfloor + \lfloor{-x}\rfloor$ can be analyzed as follows . . .

If $x$ is an integer, then $\lfloor{x}\rfloor=x$, and $\lfloor{-x}\rfloor=-x$, hence
$$f(x) = \lfloor{x}\rfloor + \lfloor{-x}\rfloor = (x) + (-x) = 0$$
If $x$ is not an integer, then $a < x < a+1$ for some integer $a$, hence $-a-1 < -x < -a.\;$Then $\lfloor{x}\rfloor=a$, and $\lfloor{-x}\rfloor=-a-1$, which yields
$$f(x) = \lfloor{x}\rfloor + \lfloor{-x}\rfloor = (a) + (-a-1) = -1$$

It follows that for all $p\in \mathbb{R}$, we have  ${\displaystyle{\lim_{x \to p}}}f(x) = -1$.
Answer: The floor enjoys an integer translation property:
$$\lfloor x+n\rfloor=\lfloor x\rfloor+n.$$
Then
$$\lfloor \epsilon+2\rfloor+\lfloor-\epsilon-2\rfloor=\lfloor \epsilon\rfloor+\lfloor-\epsilon\rfloor+2-2=\lfloor \epsilon\rfloor+\lfloor-\epsilon\rfloor$$ is  independent of the sign of $\epsilon$ and the limit exists.
Answer: If $r\in(0,1)$ then

$\lfloor 2-r\rfloor+\lfloor -2+r\rfloor=1+(-2)=-1$
$\lfloor 2+r\rfloor+\lfloor -2-r\rfloor=2+(-3)=-1$

So there is a flaw in your calculations.
The limit exists and equals $-1$.
Also it is handsome to note that $\lfloor -x\rfloor=-\lceil x\rceil$ so that $$\lfloor x\rfloor+\lfloor -x\rfloor=\lfloor x\rfloor-\lceil x\rceil$$
So the function takes value $-1$ on $\mathbb R\setminus\mathbb Z$ and takes value $0$ on $\mathbb Z$.


Removing a row that contains a negative float in a numpy aray

Question: I have a numpy array consisting of 3 columns and there is one value in a column that has a negative value. I need to remove the whole row that contains this value as it corresponds to an anomalous result.
The numpy array looks a little like this:
<code>[[98.4, 0.236, 0.0925]

 [95.2, -0.162, 0.0625]

 [92.3, 0.112, 0.0526]]
</code>
How would I go about removing the whole row that contains the negative value?
Answer: You can index with a boolean mask:
<code>result = array[(array >= 0).all(axis=1)]
</code>


Enterprise Edition Code in Examples

Question: I have seen, on occasion, a few snippets from EE-only modules slip into answers. I have even very nearly been guilty of it myself.
What is the policy for flagging these other than an edit to remove the offending code? Is there an appropriate or suggest moderator flag?
Comment: Mosses has been pinged. Can you post links to posts in question? I've seen on instance but all of the functional bits had been stripped.
Comment: Examples: http://magento.stackexchange.com/questions/3464/email-template-variable-missing-when-overriding-observer-of-core-module/3512#3512 and http://magento.stackexchange.com/a/5017/5
Comment: I think basically this is for Magento Inc. to decide? Let's ping them?
Comment: Related: http://meta.stackexchange.com/questions/12527/do-i-have-to-worry-about-copyright-issues-for-code-posted-on-stack-overflow
Comment: I will look for an example. I saw one yesterday - stay tuned.
Comment: Good question indeed! Thanks for taking up the communication lines, @benmarks. :)
Answer: Per the direction of Mosses Akizian, I have just sent the following email to email@example.com, with cc to Mosses and to Vinai Kopp:

To whom it may concern:
I am a two year veteran of Magento U developer training, working under
  Vinai Kopp, Beth Gomez, and Susie Sedlacek. I am also a moderator pro
  tempore of the Magento-specific StackExchange site located at
  http://magento.stackexchange.com. This site is a community-driven
  question and answer forum for asking and solving application and
  development questions regarding Magento.
Recently a question was asked
  (Enterprise Edition Code in Examples)
  in the meta section of the site regarding the inclusion of Enterprise
  Edition code in the body of questions or answers. While the community
  has a sense that (unnecessarily) including vast sections of EE code
  should not be allowed, there is a question as to how much code would
  be acceptable.
I/we believe it is in the best interest of eBay to allow for the fair
  and reasonable inclusion of a few relevant lines of restricted-license
  code on the rare occasion when the need arises. We the community would
  appreciate some guidance on this issue, and we the moderators will
  gladly edit posts as appropriate should those posts include an
  excessive and unnecessary amount of restricted-license code.
Please feel free to reply to me directly or to respond to the question
  which I have linked in the body of this email
Kind regards, Ben Marks
Comment: No. Haven't heard anything. Pinged Mosses again.
Comment: Any update on this, Ben?
Comment: Per Mosses's request, I've resent this to firstname.lastname@example.com.
Comment: Curious... any word here
Comment: No response. I say GO FOR IT!

Enterprise Edition Code in Examples


Criar condição em instrução

Question: Olá, eu possuo o seguinte select:
SELECT CONSTRAINT_NAME FROM user_cons_columns WHERE COLUMN_NAME = 'CANCELAMENTO' and table_name = 'NAVIO';

Após pegar o nome o mesmo vai pra outra query porém se retornar null eu acabo tendo um erro e interrompe meu script. Como que seria uma condição para vericar se tem resultado ou não? Caso retorne algo, será executado:
alter table NAVIO DROP CONSTRAINT || constr_name;

Answer: Se você estiver utilizando PL-SQL no seu script, pode resolver desta maneira:
DECLARE
  CURSOR C_CONSTRAINT IS
    SELECT CONSTRAINT_NAME
      FROM user_cons_columns
     WHERE COLUMN_NAME = 'CANCELAMENTO'
       AND table_name = 'NAVIO';
  V_CONSTRAINT C_CONSTRAINT%ROWTYPE;
BEGIN
    OPEN C_CONSTRAINT;
    LOOP
      FETCH C_CONSTRAINT INTO V_CONSTRAINT;
      EXIT WHEN C_CONSTRAINT%NOTFOUND;
      EXECUTE IMMEDIATE 'ALTER TABLE NAVIO DROP CONSTRAINT ' || V_CONSTRAINT.CONSTRAINT_NAME;
    END LOOP;
END;

Criar condição em instrução


Drupal $custom_theme caching issues?

Question: I have a hook_boot() module that detects certain circumstances and changes the theme using $custom_theme to a specific theme. All works good, however if Drupal has a cache of the page that page will be served regardless of the fact it is not the correct theme.
Is there anyway to force drupal not to use and caches for that specific theme? Or is there a way to force drupal to keep two caches? One for each theme?
I am using Drupal 6 btw.
Comment: See this answer for some ideas on what to do.
http://drupal.stackexchange.com/questions/9093/cache-page-based-on-cookie-value-and-url/9117#9117
Answer: From my point of view, the better way is to use your own cache system, but don't worry is nothing very complicate.
Copy the includes/cache.inc and put it somewhere in sites/all/libraries or whatever you want. After in your settings.php you've to add $config['cache_inc'] = 'sites/all/...'; and Drupal will replace is own cache system by yours. This file contains three functions, clear_cache_all, cache_set and cache_get. Here the idea is to add the name of your theme before all $cid.
I never tried it, so I'm not sure if you can have access to this informations, but you can try .
Comment: The problem I can see with this solution is that the cache contains also data that are not output, or that don't change basing on the theme being used. Unconditionally adding the theme name to the cache ID is not something I would suggest.

Drupal $custom_theme caching issues?


Determining a Statistically Significant Result

Question: I feel like this is an easy question if I just knew the right words to Google, but apparently I don't, so I'm sorry if it's been asked before.
I'm simply looking to determine how long I need to collect data to be relatively confident in the result.
For example, if I flip a coin 4 times and it comes up heads 3 times, it's a big leap to say the coin is weighted.  However, if I flip it a billion times and it comes up heads 75% of the time, I can be pretty confident it is weighted.
At what point between 4 and a billion can I feel confident my results are probably accurate.
My real world use case is I just want to ensure that the base conversion rate I will use to base acceptable advertising costs on is accurate. I know if 4 people visit my site and I sell to 1 of them, I can't be sure of much. But if a billion came, and I sold to 25% of them I'd feel pretty confident in that rate.
I know once you get into A/B testing and multivariate testing there is a lot more you need to know, but I feel like understanding how to determine the initial significance will help me a lot moving forward.
Thanks so much!
Comment: I *think* it might be along the lines of determining the confidence level based on the  sample size. Does that sound right?
Answer: The idea you're looking for is Statistical Hypothesis Testing. This is a method of quantifying the amount of evidence you have towards rejecting a 'null' hypothesis that you define (ie. the coin is a fair coin, in this case). This evidence is affirmative evidence towards the opposite of your defined 'null' hypothesis, or the 'alternative' hypothesis. This evidence is usually quantified in the p-value of the statistic you would like to compare (ie. the proportion of heads after multiple coin flips).
Collect as much data as you can reasonably collect. It won't hurt, and the more data you collect, the more evidence towards either the 'null' or 'alternative' hypothesis you will have, and the more confident you can be with your results.


Is it possible to streamline the logic in this?

Question: I am trying to make a visualized way of seeing an inventory list. There are around 200 items and I am trying to format the diagrams to show green if we have a surplus of the item, yellow if we only have one set and red if we are out of stock. This is my first project with VBA and gleaned what I could from Google results. This is what I have so far, where I have the first item (it's a shape on the diagram named "1". Cell C2 is formatted to show either "Order", "1 Set" or "In Stock" based on another cell's value for the actual number on hand.
Private Sub Worksheet_Change(ByVal Target As Range)

    ActiveSheet.Shapes("1").Fill.ForeColor.RGB = vbWhite

        If ActiveSheet.Range("C2") = "1 Set" Then
            ActiveSheet.Shapes("1").Fill.ForeColor.RGB = vbYellow
            ActiveSheet.Shapes("1").Fill.Transparency = 0.75
        End If

        If ActiveSheet.Range("C2") = "In Stock" Then
            ActiveSheet.Shapes("1").Fill.ForeColor.RGB = vbGreen
            ActiveSheet.Shapes("1").Fill.Transparency = 0.75
        End If

        If ActiveSheet.Range("C2") = "Order" Then
            ActiveSheet.Shapes("1").Fill.ForeColor.RGB = vbRed
            ActiveSheet.Shapes("1").Fill.Transparency = 0.75
        End If

And it just goes on from there. It was working perfectly for me until I got about halfway through and began getting errors for its size. So is there a way to have a main function system that can look at each of the items and apply it to the respective shape? Or, is there a way to break it into sections so each sub is smaller, but still behaves as a single process? Thank You!
Comment: Look into `Select Case` - https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/select-case-statement
Comment: One basic refactoring rule: find out code duplication, then extract it.  In your code, ``ActiveSheet.Shapes("1")`` and ``ActiveSheet.Range("C2")`` are repeated many times, so it is better to use variables to avoid the duplication.
Comment: How does it "go on" ?  C3/"2" etc ?
Answer: Something like this should work
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim clr as long,  c As Range

    'Me is the sheet with this code
    For Each c in Me.Range("C2:C100").Cells 'for example
        Select Case c.Value
            Case "1 Set": clr = vbYellow
            Case "In Stock": clr = vbGreen
            Case "Order": clr = vbRed
            Case Else: clr = vbWhite
        End Select
        Me.Shapes(CStr(c.Row-1)).Fill.ForeColor.RGB = clr
    Next c
End sub