Como encontro a primeira terça-feira de um mês?! (SQL)

Question: Estou a realizar o seguinte exercício:

As tabelas são as seguintes :

Eu já tenho o seguinte código:
SELECT NOME
FROM CLIENTES C,VENDAS V, LIVROS L
WHERE V.CODIGO_CLIENTE=C.CODIGO_CLIENTE AND L.CODIGO_LIVRO=V.CODIGO_LIVRO AND TO_NUMBER(TO_CHAR(DATA_VENDA,'HH24'))<17 AND GENERO='Informática'

Mas não estou a ver nenhuma maneira de obter a primeira terça-feira do mês, alguém me consegue explicar a parte do código que me falta?!
Comment: https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions001.htm    dica use uma combinação de trunc e next_day
Answer: Tente usar as funções de data do Oracle por exemplo DAYNAME() se você comparar DAYNAME([sua_data]) = 'TUESDAY' irá retornar apenas terça feira. Em seguida limite usando LIMIT 1
Answer: Fiz esta solução para Sql Server porque é o banco que tenho instalado aqui no trabalho, mas acho que você consegue converter para PL Sql fácilmente, só não faço porque não teria como testar.
declare @weekdays table(id int, name varchar(10))

insert into @weekdays values (1, 'Sunday')
insert into @weekdays values (2, 'Monday')
insert into @weekdays values (3, 'Tuesday')
insert into @weekdays values (4, 'Wednesday')
insert into @weekdays values (5, 'Thursday')
insert into @weekdays values (6, 'Friday')
insert into @weekdays values (7, 'Saturday')

declare @data date = getdate() //usei data de hoje como exemplo
declare @inimonth date = dateadd(day, (day(@data)-1) * -1, @data)
declare @weekidDayOne int = 0

select top 1 @weekidDayOne = id from @weekdays where name = datename(dw, @inimonth)

select case when @weekidDayOne < 3 then dateadd(day, (3 - @weekidDayOne), @inimonth)
            when @weekidDayOne > 3 then dateadd(day, (7 - (@weekidDayOne - 3)), @inimonth)
            else @inimonth
        end

Usei uma variável Table porque precisava dos números para calcular, se você quiser fazer diferente, talvez fique melhor.
Versão sem variáveis, usando apenas query
select case when weekdays.weekIniMonth < 3 then dateadd(day, (3 - weekdays.weekIniMonth), weekdays.inimonth)
            when weekdays.weekIniMonth > 3 then dateadd(day, (7 - (weekdays.weekIniMonth - 3)), weekdays.inimonth)
            else weekdays.inimonth
        end firstTueday, weekdays.*
from (
select case when datename(dw, datas.inimonth) = 'Sunday' then 1
            when datename(dw, datas.inimonth) = 'Monday' then 2
            when datename(dw, datas.inimonth) = 'Tuesday' then 3
            when datename(dw, datas.inimonth) = 'Wednesday' then 4
            when datename(dw, datas.inimonth) = 'Thursday' then 5
            when datename(dw, datas.inimonth) = 'Friday' then 6
            when datename(dw, datas.inimonth) = 'Saturday' then 7 end weekIniMonth, datas.*
from (select dateadd(day, (day('2017-07-14')-1) * -1, '2017-07-14') iniMonth) datas) weekdays

Answer: Obrigado pelas respostas, já encontrei a resolução final do meu problema.
SELECT NOME
FROM CLIENTES C,VENDAS V, LIVROS L
WHERE V.CODIGO_CLIENTE=C.CODIGO_CLIENTE AND L.CODIGO_LIVRO=V.CODIGO_LIVRO
AND TO_NUMBER(TO_CHAR(DATA_VENDA,'HH24'))<17 AND GENERO='Informática'
AND TO_CHAR(DATA_VENDA,'YYYY.MM.DD')=TO_CHAR(NEXT_DAY(TRUNC(DATA_VENDA,'Day')-1,'TERÇA-FEIRA'),'YYYY.MM.DD');


Choosing the right AWG for Server Power Cables?

Question: When getting power cables for servers, there are various AWG (American Wire Gauge) choices to make. The ones I have noticed are 18 and 14; 14 is thicker so will be a little more stiff. But, I am also wondering how I determine if I really need the heavy duty or thicker 14 AWG cables, or if 18 would be fine?
In my particular case, this is for 6 foot runs from a power strip to servers. The power will be run at 208v single phase. Using this online calculator, it looks like maybe at most .1 volts would be dropped which sounds negligible (assuming copper).
Are there other concerns here? For instance:

Maximum rating
Bundled temperature (I have vertical PDUs, so doesn't apply to me, but still is this a concern?)

How do I know which AWG I actually need for my server's power cables?
Comment: The usual IEC C13/C14 connectors are technically 10 Amp rated, so that is likely what calculations will have to be based upon when it comes to formal safety business etc (notice that C13/C14-fed PDUs will usually have a separate fuse or breaker limiting their intake to 10 Amps). In practice, it is unlikely that all devices fed from a PDU will come CLOSE to 10 amps, given your standard PDU will get 13, 16 or 25 amps upstream only ;) - and heating of a cable follows an amps-squared relation, so 1 amp = 1/100 heating of 10 amps...
Comment: From a *power strip*? I hope you mean PDU :)
Comment: @MDMarra: So as not to be confused with the floor units. From wikipedia, *"The term (PDU) may refer to two major classes of hardware power devices; the first and typically the general unqualified term refers to the category of relatively higher-cost floor-mounted power distribution devices which transform one or more larger capacity raw power feeds into any number of lower capacity distributed power feeds .... The second type of PDU is sometimes called a Smart-PDU, Rack-based PDU, Intelligent PDU or simply "Power Strip" by various IT professionals"*
Comment: Please verify any advice given here by people who are not licensed electricians or inspectors (I am not any of these either) yourself.
Comment: If in doubt, you can always set up an experiment (take it outside, bundle some cables and load one with a space heater and a few with computers, and measure temperatures... Also, make sure the cables you use are, if they are from the IEC cable grab bag, indeed 18 AWG and not 20-22 AWG that sometimes come with small devices and .. I always throw these out instantly.)
Comment: A handful of portable 300W/500W floodlights are handy to have around anyway, to build test loads for testing and calibrating UPSes from (sorry for the comment deluge ;)
Answer: DISCLAIMER:  This is personal opinion/knowledge from an IT admin, not an electrician.
Wire gauge is chosen for many reasons, but typically for people like us it is based on amperage used/needed.  There's probably lots of other reasons/rules, but for you and I that's basically it.
Kyle, you can look here if you haven't already:  http://www.powerstream.com/Wire_Size.htm
Also:
Comment: Doesn't voltage matter as well?
Comment: @KyleBrandt not really. if it did, the recommendations would be based on kVa or watts instead. it's current that really drives the cable diameter.
Comment: Voltage matters more for "flow" (I'm not an electrician sorry).  See here:  http://www.jamestowndistributors.com/userportal/document.do?docId=1098&title=Voltage+and+Recommended+Wire+Sizes+-+ARCO  I know that's only for 12/24 volts but it might help explain voltage and "flow".
Comment: I'm curious why this was downvoted. This is a very similar answer to mine which currently has a positive score.
Comment: @MDMarra - Probably cause I'm not an electrician. Edited post. :)
Comment: None of us are, otherwise we'd be on [diy.se] or something :)
Comment: Of course voltage matters.  Your recommendation chart is working under the assumption of a specific voltage.  The link that TheCleaner posted is for DC systems where wire resistance plays a much larger factor.
Comment: http://phd.boschsecurity.com/wiregage_cal.cfm maybe that will help
Answer: This Wikipedia Article has a nice table that outlines the exact specifications of the different AWG ratings.
The one to look out for is ampacity at various temperatures. Considering the draw of most modern power supplies, I'd imagine that an 18 or 16 would be fine in most cases, but many servers ship with 14s, so that's what I tend to stick with.
Comment: **We used 14s, combined with cable arms, that is a bad choice.** They end up popping out of the servers even when you velcro them in nice and tight. **We are redoing everything with 16 now** (Which is thinner). So this is something to keep in mind.
Comment: But cable arms are for the birds, @Kyle :)
Comment: I don't like them myself, but I'm usually not the one working in the datacenters, so I leave it up those guys.
Answer: Simple rule that allow to choose right wire - "4A through 1 square mm of copper wire".
Rule based on Joule's law Q=RI^2. Thinner wires becomes hot, thicker - are unreasonable expensive.
Answer: Amperage is what is important. Amperage is what does harm to you and or the wire. For such a close wire run (6') the loss will be minimal. But amperage can burn the wire, blow the breaker. Etc..... But higher the voltage means less amperage. A quick example is 120v 20amp allows 12 AWG ( American wire gauge). 208/240 voltage can go down to 14-16 AWG I beleave. My suggestion is, r mindfull of your amps being used for that system.


PHP mysqli Commands out of sync; you can't run this command now

Question: In my db I have some stored procedures.
I want to call the one of them, and according to the results I get from this procedure, i will determine weather to call the second one or not.
As you can see in the isUserValid() method I've used $result->free_results()
but still when calling the other procedure I get: Commands out of sync; you can't run this command now
This is my calling to the db functions:
    /**
     * Run a new query on the db.
     * this will open an close the connection to the db
     * @param $query string the query to run
     * @param $verifyAccessToken boolean true if user validation is needed before query is executed, false otherwise
     * @return bool|mysqli_result the result of the query if any or true or false in a non query
     * @throws Exception on connection and query errors
     */
    private function queryDb($query,$verifyAccessToken)
    {
       // if ($this->test)
//            echo $query . "
";
        //create a new mysqli connection
        $mysqli = new mysqli($this->DB_HOST, $this->DB_USER, $this->DB_PASS, $this->DB_NAME);
        //set the charset for the connection
        if (!$mysqli->set_charset("utf8"))
        {
            $mysqli->close();
            throw new Exception ("Error setting UTF 8 DB connection");
        }
        //check if the connection was ok
        if (mysqli_connect_errno())
        {
            $mysqli->close();
            throw new Exception("Error connecting DB");
        }

        //if verification is needed - verify access token
       if ($verifyAccessToken && !$this->isUserValid($mysqli))
       {
          $mysqli->close();
          throw new Exception(ACCESS_TOKEN_INCORRECT);
       }

        //get results
        $result = $mysqli->query($query);
        //check if there were now error in query. if so - throw an exception
        if (!$result)
        {
            $mysqlError = $mysqli->error . __LINE__;
            //close the connection
            $mysqli->close();
            throw new Exception ("mySQL Error: " . $mysqlError);
        }
        //fetch the results into an array
        $rows = $result->fetch_all(MYSQLI_BOTH);
        //close the connection
        $result->close();
        $result->free();
        $mysqli->close();
        //return the results if any
        return $rows;
    }

    /**
     * Check if user is valid
     * @param $mysqli mysqli connection to db
     * @return true if user is valid, false otherwise
     */
    function isUserValid($mysqli)
    {
        //Check if there is a saved access token. if not - throw an exception
        if (is_null($this->user) || $this->user->getPicoAccessToken() == null)
          throw new Exception(ACCESS_TOKEN_INCORRECT);
        //get user details
        $facebookId = $this->user->getFacebookId();
        $picoAccessToken = $this->user->getPicoAccessToken();
        //create verification query
        $verificationQuery = "Call isUserValid('$facebookId','$picoAccessToken')";
        //execute query
        $result = $mysqli->query($verificationQuery);

        //if query had error - throw exception
        if (!$result)
        {
         $mysqlError = $mysqli->error . __LINE__;
         //close the connection
         $mysqli->close();
         throw new Exception ("mySQL Error: " . $mysqlError);
        }
        $rows = $result->fetch_all(MYSQLI_ASSOC);
        $rows = $rows[0];
        $result->free_result();
        //return user valid status
        return isset($rows["isUserValid"]) && $rows["isUserValid"] == 1;
    }

Answer: Every stored procedure returns at least two results

one (or many) actual results
one empty result to tell the client there are no more results.

You have to use mysqli_more_results()/mysqli_next_result() to clean them.
If your procedure returns only one result, or you just don't want any extra results but the first one, you can clean up the results queue with this code snippet:
while($mysqli->more_results())
{
    $mysqli->next_result();
    if($res = $mysqli->store_result())
    {
        $res->free();
    }
}

Comment: this is really helpful and solved my problem. FYI: there is not  $mysqli->free_result() method.. its under the $res object..
Comment: Wow. Thank you for this. I have not seen this second result set mentioned anywhere else.
Answer: The currently accepted answer wont work as-is, i think next_result() should not be called before the first result.
This is an example that does work:
if (!$mysqli->multi_query("CALL p()")) {
    echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

do {
    if ($res = $mysqli->store_result()) {
        printf("---\n");
        var_dump($res->fetch_all());
        $res->free();
    } else {
        if ($mysqli->errno) {
            echo "Store failed: (" . $mysqli->errno . ") " . $mysqli->error;
        }
    }
} while ($mysqli->more_results() && $mysqli->next_result());

From the PHP manual http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Answer: re connect database $this->db->reconnect(); // likes in codeigniter


Length of the common chord of $y^2 = x$ and $x^2 = y$ .

Question: What is the way to find this? Just hint and a little help is required.
Comment: Hint: (i) Where do the two parabolas meet? (ii) A picture will help you see what the question asks for.
Answer: $y^2 = x$ and $x^2 = y$ share only two points in common.  One is $(x=0,y=0)$.  What is the other? Hint:  It will solve $(x^2)^2 = x$.
A common chord must be between two common points.  So what is the distance ($\sqrt{x^2+y^2}$)  between $(0,0)$ and the other solution for the other common point?


Convert byte to int using bitwise operators

Question: I'm documenting some code in Java. The goal is to read and process an OSRM file which is a file containing hex codes.
The flow is as follows: Read in some byte to a ByteBuffer using a FileChannel. Once the buffer is filled, convert every byte to a signed integer. This is done using the bitwise & operator and the signed left shift operator <<, and looks like this:
return  (0x000000ff & (bb.get() << 0)) |
        (0x0000ff00 & (bb.get() << 8)) |
        (0x00ff0000 & (bb.get() << 16)) |
        (0xff000000 & (bb.get() << 24));

Where bb is of course the ByteBuffer.
I have totally no clue how and why this code works, I Googled a bit and the closest thing I found was the following Stack Overflow question: Converting Java method to C#: converting bytes to integers with bit shift operators.
Still, I have no clue and I'm wondering if someone could help me figure out this code snippet.
Comment: Much better to use ByteBuffer.asIntBuffer
Comment: Then at least use ByteBuffer.getInt
Comment: This is not possible because the file also includes unsigned ints, booleans, ....
Comment: The code is poor - it's reinventing the wheel and might as well use a simple array..  Just put 4 bytes in then call getInt().
Answer: This reads four bytes from the underlying byte buffer and stitches them together into an int value like this:
                        11111111 (first byte read)
                22222222         (second byte read)
        33333333                 (third byte read)
44444444                         (fourth byte read)

To achieve that, a bitwise OR operation is performed on all subresults, where each subresult prepares one row in the above diagram. For example, the third row is prepared as
(0x00ff0000 & (bb.get() << 16))

which does the following:

read the byte:
xxxxxxxx

expand the byte into an int:
000000000000000000000000xxxxxxxx

shift the bits to the left by 16 slots:
00000000xxxxxxxx0000000000000000

finally, push this through an AND mask which lets only the x bits through. This is needed because byte is signed, so the conversion to int may actually result in the following:
111111111111111111111111xxxxxxxx

The code would perhaps be simpler if a constant AND-mask was performed before shifting:
(bb.get() & 0xFF) << 16

This is actually the standard idiom for Java in these bit-twiddling operations.

Although not an answer to the question you have asked, using the provided API would certainly be preferred (the getInt method). Your byte order is little endian, so you would just need to set it up:
bb.order(ByteOrder.LITTLE_ENDIAN);

For reference, this is the JDK's implementation of the same code:
static private int makeInt(byte b3, byte b2, byte b1, byte b0) {
    return (((b3       ) << 24) |
            ((b2 & 0xff) << 16) |
            ((b1 & 0xff) <<  8) |
            ((b0 & 0xff)      ));
}

Comment: Is there another way of doing so? and if so, does it lower the process speed?
Comment: You mean, in addition to the way recommended at the end of my answer and through the comments?
Answer: Basically, it reads in four bytes, each of which is eight bits and it combines them together into an integer which is 32 bits. It does this by shifting each successive byte an extra 8 places to the left, so the first byte read is placed into the last (lowest order) 8 bits of the integer (0-7); the next byte goes into the next 8 bits (15-8), etc.
It would be a lot easier to use the actual functionality of the ByteBuffer to do this though:
bb.order(ByteOrder.LITTLE_ENDIAN); // Called once on the buffer
int intFromNextFourBytes = bb.getInt(); // Read the same value as your code.


SyntaxError: unexpected token: string literal -Javascript

Question: Estou tendo esse erro na seguinte função:
function formaQueryConta(cpf){

        var numConta= jsonDtContasCliente[(document.getElementById("listaContas").value)-1];
        console.log(typeof(cpf)); //Diz que é String
        console.log(typeof(numConta)); //Diz que é String
        var parms = "&cpf="+cpf"&conta="+numConta; //O ERRO É APONTADO NESTA LINHA
        ajaxCall("Persistencia.php?action=buscaConta" +parms, formaCanvas);

}

Não encontrei no Stack nada que me ajudasse. Alguma luz?
Answer: Falta um + na concatenação:
var parms = "&cpf="+cpf"&conta="+numConta; //O ERRO É APONTADO NESTA LINHA
//                     ^---aqui

Não encontrei no Stack nada que me ajudasse

Isso é normal, pois esse erro pode ser por diversos motivos e é mais ou menos genérico. Ele simplesmente indica que quando estava a construir a string encontrou algo que não estava à espera, neste caso o ".
O que eu aconselho para as próximas vezes e tentar ler a linha com calma e ter atenção a cada caratere.
Uma alternativa comum nos dias de hoje em ES6 é utilizar template literals, que funciona como interpolação e que pessoalmente acho mais legível. Nesse caso ficaria assim:
var parms = `&cpf=${cpf}&conta=${conta}`;


Is there any possible way to make hook flash to any extension throoght software?

Question: I like to make conference call following this step.

2222 make call to 3333 (phone)
3333 receive phone call (phone)
simulate push flash button to 2222 thought AMI/? (software)
originate call to 4444 throught AMI (software)
4444 receive phone call (phone)
simulate push flash button to 2222 thought AMI/? again (software)
222 333 4444 speaking to each other in the same channel (phone)

I know that AMI doesn't have exactly function to make hook flash. (some trick?)
Is there any suggestion to complete step 3 and 6 through software it may be AMI or anything else.
Resource:

AMI = Asterisk Manager Interface
http://en.wikipedia.org/wiki/Hook_flash
Answer: You can connect two parties by originating a call with the originate command, using the "application" parameter. From the console it's like this:
originate SIP/2222 application Dial SIP/3333
That will originate a call to extension 2222 and when it's answered, a call to extension 3333 will be placed.
To place the third call, you can have something like this in your dialplan:
[thirdcall]
exten => s,1,Dial(SIP/4444)
exten => s,2,NoOp
And change the originate command to something like this:
originate SIP/2222 application Dial SIP/3333,G(thirdcall^s^1)
This will place a call to ext. 2222, and when the call is answered, a call is placed to ext. 3333. Then when the call to 3333 is answered, it will send ext. 3333 to to thirdcall,s,1 on the dialplan, which is a dial command to extension 4444 (and it also sends extension 4444 to s,2 which is a NoOp, upon answer).
Try it and let us know if the three calls are bridged and all parties can talk among themselves.
Personally I think it would be easier to call all three parties and send them to a conference room...


randomly change the background color of a react app by a click

Question: i tried to randomly change the background color of the entire page by a clicking a button but instead it was only changing the background of the div element. here is my code
  import React from "react";
  class Home extends React.Component {
      constructor(props) {
    super(props);
    this.state = {
        quotes: ["red", "yellow", "blue", "green", "purple", "pink"],
        colors: [],
    };
    this.nextColor = this.nextColor.bind(this);
}
// moves to display next quotes
nextColor() {
    const random = this.state.quotes[Math.floor(Math.random() * this.state.quotes.length)]
    console.log("receiving ", random);
    this.setState({
        colors: random
    })
}
render() {
    return (

{this.state.colors}

            <button onClick={this.nextColor}>Next Color</button>

    )
  }
  }

   ReactDOM.render(<Home />, document.getElementById("app"));

i need the background color of the entire page to change when the nextColor button is clicked. your help would be appreciated
Answer: The body tag is not controlled by React. To modify the body tag hook on to componentDidMount life cycle and set the color using vanilla javascript
Here is a way https://jaketrent.com/post/update-body-class-react/
In a nut shell add the below logic
  componentDidMount() {
    document.body.style.backgroundColor = this.state.colors;
  }

Comment: it still changes the div background and not the entire page
Answer: Ramesh give the right answer, here is the demo:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      colors: ["red", "yellow", "blue", "green", "purple", "pink"]
    };
  }

  changeBg() {
    const { colors } = this.state;
    const color = colors[Math.floor(Math.random() * colors.length)];
    document.body.style.backgroundColor = color;
  }

  render() {
    return (

        <button onClick={() => this.changeBg()}>Change Color</button>

    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Answer: import React from "react";

function MyComponent({ name }) {
  // I found this formula
  // here: https://css-tricks.com/snippets/javascript/random-hex-color/
  let randomColor = Math.floor(Math.random() * 16777215).toString(16);

  // The trouble I had was about how to use
  // the variable randomColor in "style:{}" tag
  return (

      <div
        className="child-container"
        style={{ backgroundColor: "#" + `${randomColor}` }}
      >

{name}

  );
}

export default MyComponent;


Visual Studio 2017 won't open websites in browser tabs anymore

Question: I recently had some of my Visual Studio 2017 settings change on me due to a lisence renewal. One in particular is that I used to have VS configured to open different websites in different tabs of the same browser instance. Now the websites open in separate browser instances.
I fixed this problem once before but the same fix no longer works. Here is the link which helped me fix my problem before:
Open site in new tab of existing Chrome instance when debugging
The image they have for Tools > Options > Debugging > General ... looks like this:

Mine looks slightly different:

Microsoft must have made some updates since the above link was posted because not only do I see differences in the Options window but leaving "Enable Javascript..." unchecked no longer works.
What is the current way of getting multiple web apps to show up in different tab of the same browser instances rather than in separate browser instances?
Comment: Did you see this comment on that post? _" for VS 15.7.0 you also need to uncheck "Stop debugger when browser window is closed".... that option is under "Projects And Solutions\Web Projects\Stop debugger when browser window is closed"_
Answer: I have faced same issue today in vs 2017. To solve this problem simple follow below steps:
1) Click on Tool => options
2) Find Projects and Solutions on left side
3) Extend Projects and Solutions => Click on Web Projects
4) On right side you will see some option you need to uncheck: Stop debugger when browser window is closed,
close browser when debugging stops
Note: It is 2nd last option from bottom.
I think it will help you!


Como implementar dicionários no padrão Multithreaded Singleton

Question: O padrão Multithread Singleton me atende no sentido de possibilitar o uso de "variáveis globais" em minha aplicação. Seu uso ocorre através dos recursos de get e set, como é possível notar.
Como de forma semelhante, posso fazer o mesmo com uma variável do tipo Dictionary?
using System;

namespace Program
{
    class Global
    {
        public sealed class Session
        {
            private static volatile Session instance;
            private static object sync = new Object();

            private Session() { }

            public static Session Instance
            {
                get
                {
                    if (instance == null)
                    {
                        lock (sync)
                        {
                            if (instance == null)
                            {
                                instance = new Session();
                            }
                        }
                    }
                    return instance;
                }

            }
            public bool glb_login   { get; set; }
            public string UserID    { get; set; }
            public string IPAddress { get; set; }
            public string PortName  { get; set; }
        }
    }
}

Comment: até onde eu sei um `Dictionary` não é um elemento serializável, você teria de implementar sua prórpria serialização para ele. Se quer serializar, seria mais fácil usar uma estrutura mais simples, como `IList` por exemplo
Comment: Caio, não sei se te ajuda, mas tem um exemplo em 2 partes de C# Singleton no VBMania, a saber:
DESIGN PATTERN - SINGLETON PARTE #1 - http://www.vbmania.com.br/index.php?modulo=detalhe&id=8830
Comment: @FabioIn. Eu agradeço, mas não consigo ter acesso ao conteúdo por não ter cadastro no site.
Comment: @CaiodePaulaSilva, o cadastro é 100% gratuito...
Answer:
O padrão Multithread Singleton me atende no sentido de possibilitar o
  uso de variáveis globais em minha aplicação

De acordo com o código que você postou é difícil de perceber se você realmente entende a afirmação que você deu.
Este padrão dá garantias absolutas que a variável é instanciada apenas uma vez, mas não dá qualquer outra garantia. Ou seja ainda é possível que duas threads escrevam numa propriedade do objecto existente ao mesmo tempo, causando problemas de estado.
Se o objetivo for garantir que duas threads não podem escrever ao mesmo tempo, então o código não está correto. Uma possível solução seria a seguinte:
class Global
{
    public class SessionState
    {
        public bool glb_login   { get; set; }
        public string UserID    { get; set; }
        public string IPAddress { get; set; }
        public string PortName  { get; set; }
        //Outras propriedades

        public SessionState Clone(){
            //Atenção este método copia as propriedades por valor!
            //Isto quer dizer que se você tiver uma referência, o objeto alterado será o mesmo
            return MemberwiseClone() as SessionState;
        }
    }

    public sealed class Session
    {
        private static volatile Session instance;
        private static object sync = new Object();
        private SessionState _sessionState;
        private Session() { }

        public static Session Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (sync)
                    {
                        if (instance == null)
                        {
                            instance = new Session();
                            _sessionState = new SessionState();
                        }
                    }
                }
                return instance;
            }

        }

        public SessionState State {
            get{
                lock (sync)
                {
                    return _sessionState.Clone();
                }
            }
            set{
                lock (sync)
                {
                    _sessionState = value;
                }
            }
        }
    }
}

Agora adicionar o seu dicionário seria uma questão de mudar o método Clone para retornar uma instância nova com o dicionário novo, com os mesmos dados. E aceder à sua sessão seria feito através de Session.Instance.State.
Por curiosidade esta confusão toda deste padrão pode também ser substituída por uma versão bem mais simples:
private static Session instance = new Session(){
    State = new SessionState()
};


Usando @import no CSS

Question: Gostaria de saber quanto ao uso do @import para importar folhas de estilo dentro de uma outra folha de estilo, como por exemplo:
Dentro do arquivo style.css:
@import url("css/layout.css");

body{
    background: #F0F0F0;
}

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

Preciso declarar algo mais para que possa usar os estilos do layout.css, como no HTML por exemplo?
Fica mais lento o carregamento de páginas dessa forma em relação a declaração direta no head?
Comment: O uso do @ import pode trazer um impacto negativo na performance do seu site. De acordo com um post de Steve Sounders, ao contrário do tag , se você tem múltiplos comandos @ import em sequência, eles podem não ser carregados em paralelo no momento em que a sua página é aberta. Fonte https://pt.stackoverflow.com/questions/8763/como-utilizar-import-em-um-arquivo-css
Answer: De acordo com o site da Mozilla, todas estas formas estão corretas:
Exemplos
@import url("fineprint.css") print;
@import url("bluish.css") projection, tv;
@import 'custom.css';
@import url("chrome://communicator/skin/");
@import "common.css" screen, projection;
@import url('landscape.css') screen and (orientation:landscape);

Algumas formas já incluem o media query incluso para definir se o CSS será somente para algum tipo específico de tela ou para impressão.
Como já foi dito, esta forma não é o ideal de se importar uma folha de estilo e deve ser usado somente em último caso. A melhor forma de linkar folhas de estilo, ainda é pelo  do html.

Usando @import no CSS


Erro ao executar mysqli_query() em Select do BD

Question: Quando vou cadastrar algo no Banco de Dados da isso

Código PHP

<?php
session_start();
include_once("../seguranca.php");
include_once("../conexao.php");
$nome_nivel     = $_POST["nome_nivel"];

$query = mysqli_query("INSERT INTO nivel_acessos (nome_nivel, created) VALUES ('$nome_nivel', NOW())");
?>

Conexão

<?php
 $servidor = "localhost";
 $usuario = "root";
 $senha = "";
 $dbname = "tcc";

 //Criar a conexao
 $conn = mysqli_connect($servidor, $usuario, $senha, $dbname);
Answer: Você precisa por a conexão no mysqli_query:
$query = mysqli_query($conn,"INSERT INTO nivel_acessos (nome_nivel, created) VALUES ('$nome_nivel', NOW())");

Syntax:
mysqli_query($conn,"query");

https://secure.php.net/manual/pt_BR/book.mysqli.php
Comment: @rray corrigido ! rs


Trying to understand how to work with Maven and Eclipse

Question: I import a project into eclipse from svn and then go and run 'mvn install' from the command line and everything compiles fine. But I don't understand why the code is not compiled in Eclipse too.
From my previous experience I know that I need to go ahead in Eclipse and import "existing maven projects" to have Eclipse compile the code, I just don't understand why.
Thanks!
Comment: you might have to provide the error stack trace.
Comment: Is there an error in Eclipse? There is a view named 'Problems' in Eclipse you should check out (Window->Show View->Problems) that will list all build problems
Comment: Good question. I already imported "exiting maven projects" so now I have no problems and it compiles. The only thing is that the code appears twice -- once as a single project that is not compiled, and once again as multiple compiled projects. When I make a change to one of the sub-projects it's reflected immediately in the single un-compiled project as well.
Comment: Hmm I've seen that when I import a directory of maven projects I get both the root pom project listing all sub-projects and one project per sub-project. I ususally just close to root project and work on each project separately.
Comment: What is the issue listed in the Problems tab of Eclipse?
Answer: How have you imported the projects to Eclipse? By runnint mvn eclipse:eclipse to import them as 'Java project' or importing the maven projects directly with the m2eclipse plugin?
By default maven builds each project into a directory target in each project whereas Eclipse builds into eclipse-out. mvn install builds each maven project to create an archive (jar, war, ear etc) whereas Eclipse needs to build to be able to run the code in Eclipse.
Comment: I used the svn plugin to import the project to Eclipse and that's it. Then from the command line I ran 'mvn install' in the project directory inside the workspace where the main pom.xml resides.
Comment: The method you listed will only work if they have the "maven-eclipse-plugin" plugin defined in their pom file.


Copying taxonomy

Question: I am working on a website of restaurant company. On the front page i am able to visit one of its restaurants. Each of this restaurant subpages has its own taxonomy (Menu, About us, Contact) and content assigned to them.
Is there any elegant solution for copying this taxonomy, and therefore creating new restaurant? (lets suppose, we have two restaurants in Berlin and Paris, and we want to add new restaurant in London)
Answer: I am not sure whether it can be considered an "elegant" solution, but the Taxonomy CSV import/export module might be of help.
You would need to export your taxonomy, edit the CSV, and then import the new data back into your site.
Hope that helps,
Comment: it works, but it is not user-friendly for non-developers.

Copying taxonomy


Changing the Firebase Cloud rules

Question: I have the following rules in my Firebase Cloud database:
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

I keep getting emails saying that:

We've detected the following issue(s) with your security rules:

any user can read your entire database
any user can write to your entire database

In our main screen, user can enter the app only by signing with email + password or with his phone number + code that he gets via SMS. Both work with the Firebase auth serivce. What should be the rules in that case?
Comment: In order to write effective rules, they must be paired with specific specific queries that should be allowed or denied by the rules.  Without seeing queries, there's no way how to write a rule that implement the desired security.  Please edit the question to be more clear about the query are you working with.  I suggest also starting with the documentation to learn how rules work: https://firebase.google.com/docs/firestore/security/get-started
Answer: If you only want to allow access to authenticated users, you would modify your rules as follows:
// Allow read/write access on all documents to any user signed in to the application
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

Having said that, note the following two points:

By doing /{document=**} (i.e. using recursive wildcard) you apply these rules to all the collections/document of the Firestore database. It may be better to explicitly define the rules for each collection, in order to control the access to each collection in a more fine-grained manner. This way, you avoid any mistake in the future where you create a new non-public collection but forget to adapt the security rules.
Do not forget that anyone that has the Web API Key of your Firebase project (which is not difficult to find in the source code of your app) can create an account to your Firebase project, for example with a simple call to the Firebase Auth REST API. In other words, this rule only allows authenticated users to access your DB, but, by default, anyone can become an authenticated user.
Comment: In the sign up activity, it contains an option "Group" which user should chose an existing group. The group names are stored in the database `/groups/`. I guess that with those rules it won't work right? Because it could not fetch this information. Sorry for not mentioning it before.
Comment: Ooh, indeed this totally changes the situation!! You need to give more details on what you want to do with this groups collection. Do you want to check if the user belongs to a group?
Comment: Sorry! no, just to fetch all groups and each user can try to "sign up" to that group but it will work only if he has permissions to that group (added by another member).
Comment: It seems that this should be a totally new question. Please write a new question with all the details of your exact goal. You may accept and/or upvote my current answer if you think it answers your original question (i.e. how to solve the fact that you are getting alert emails about your rules)

Changing the Firebase Cloud rules


Não consigo utilizar boundary(\b) para validar uma palavra que comece com "@"

Question: No caso de /\b@MYVAR\b/i, eu não consigo utilizaro boundary,  Vide: https://regex101.com/r/4bFElA/1
Eu preciso validar uma string que contenha uma palavra @MYVAR (Exemplo).
Há alguma restrição quanto à este caracter? Qual seria uma alternativa?
Fiz um teste em javascript e o resultado é falso.

console.log(`/\b@MYVAR\b/i.test("@MYVAR")`,/\b@MYVAR\b/i.test("@MYVAR"));

Em php o código ficaria algo assim:
<?php
$value = "@MYVAR";
if(preg_match("#/\b@MYVAR\b/i#i", trim($value))){
 echo "ok";
}

Comment: amigo, já tentou usar a regex (@userid)? @LeonanCarvalho
Comment: Em que linguagem vais usar essa regex? Podes explicar melhor o problema que estás a tentar resolver?
Comment: Preciso validar uma string que contenha uma palavra @MYVAR, postei um exemplo em javascript mas poderia ser em php  ou outra linguagem qualquer.
Answer: O boundary (\b) se aplica apenas a letras, números e o underline que seria o equivalmente ao \w ([a-zA-Z0-9_]) por isso sua regex falha.
Nesse caso teria que deixar a arroba fora do boundary. Algo como @\buserid\b ou @?\buserid\b
Comment: Apenas um detalhe `\w` = [`[a-zA-Z0-9_]`](https://regex101.com/r/2KprQT/1)
Comment: @GuilhermeLautert obrigado pela correção já editei :)
Answer: O problema é que @ não é considerado um caracter válido para word. Ou seja: \b refere-se ao inicio de uma palavra mas os caracteres válidos para \w são [a-zA-Z0-9_], e @ não está lá.
Comment: mais rapido que eu, DAMN
Comment: Vocês se movem tão rápido que meus olhos mal podem acompanhá-los!
Comment: @Paz sorry :) Fica para a próxima :)
Answer: Complementando o conceito:
O \b não faz seleção. Ele é um anchor assim como ^ e $ e posiciona o cursor para as posições que estão entre: (^\w|\w$|\W\w|\w\W). Em outras palavras:

No começo da string, dado que o primeiro char seja um char word.
No fim da string, dado que o último char seja um char word.
No meio da string, onde um char é uma word e o outro não.

É considerado um char word o que estiver em [a-zA-Z0-9_], ou seja, letras, dígitos e underline.
Por exemplo: dito "i'm looking @ you", o \b posicionaria (vou marcar com |):
|i|'|m| |looking| @ |you|

Acho que essas considerações podem ser útil para alguns.
Answer: Como citado pelos anciões rray e Sergio, uma word boundary é definida por iniciar em caracteres [a-z A-Z 1-9], porém isso pode ser revertido com uma regex como essa:
(@\buserid\b)

Explicação:
Essa regex identifica o caractere @ e só da match se existir a palavra "userid" em seguida.


Modify Existing Crystal Report

Question: Please help me. I want to add field into exsting Crystal Report. once i add new field i want to filter using that field. I now how to filter but dont know how to add new field to existing crystal report.
Thanks in advance
Comment: +1 For referring to SO as a deity.
Comment: Does that make this a prayer request?
Comment: @Orbling: More of a pantheon than a deity
Comment: @skaffman: So SO is polytheist, who knew? ;-)
Answer: I'm not sure what tools you are using. Using the Crystal Reports IDE, I just drag a field from the data source to the report surface to add it.

Modify Existing Crystal Report


Setting a standard value to a field

Question: I've created a field with drupal console. That made the following standard folder structure.
FieldFormatter
FieldType
Fieldwidget

These all have their respected php classes.
Now this field is in a content type that always is used in a Book.
I want to this Books name into that field.
I know how to retrieve this name trough code but i don't know how to get this value into this field in all new instances of this content type.
I thought i just needed to use a default value but that doesn't seem to work because even though i added 'default' to the schema with that value it doesn't show up?
Answer: Normally a default value is configured in the field configuration. Either static in default_value or dynamic in default_value_callback pointing to a callback function which returns the default value.
For your original question, how to do this in one of the field plugins, see No way for a field to dynamically set default value and especially #6:

I resorted to creating widgets (extending the base widgets), whose
  only concern is to set the default value dynamically according to
  contextual values, e.g. I have a widget that presets a default value
  to an entity name referenced by the logged in user, something like
  this:

/**
 * Define the {@link AcmeWidget} class.
 *
 * @FieldWidget(
 *   id = "acme_widget",
 *   label = @Translation("Acme Textfield"),
 *   field_types = {
 *     "string"
 *   }
 * )
 *
 * @package Drupal\acme\Plugin\Field\FieldWidget
 */
class AcmeWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    // Call our parent but set the value using our default value function.
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    // Get the current user organization's name.
    $user = User::load(\Drupal::currentUser()->id());
    $organization = $user->get('field_organization')->entity->title->value;

    // Set the default value if a value hasn't been set.
    $element['value']['#default_value'] = $organization;

    return $element;
  }

}

Setting a standard value to a field


How can I show Arabic dates in a block?

Question: I have used Drupal7 and I want to add Arabic date in Hijri formate; I have used the Calendar Systems module, but it doesn't add dates as block. How can I implement hook_block() to show dates in Hijri format?
Answer: its approved now I just added the new release yesterday
Hijri

This is a smart module that basically extends Drupal's display date to provide Hijri Date integration with Drupal core date field and with other Drupal contributions.
Answer: There is a sandbox module that should allow you to format dates this way:

This is a smart module that basically extends Drupal's display date to
  provide Hijri Date integration with Drupal core date field and with
  other Drupal contributions.
This module is integrated very well with Views module. You can use it
  to display Hijri date instead of Gregorian date or you can have them
  both by mention "[had to remove Arabic text]". Also this module coming with Hijri block
  that will showing Hijri today date on your website wherever you want
  to show today date in your header for example.

I do not know when/if this module will be approved and promoted to a full project.

How can I show Arabic dates in a block?


Jquery .on or .click not working, alert does not appear

Question: I have this code:
$("#top").on('click',function(){
        alert('I am here');
        $('html, body').animate({scrollTop:200}, 'slow');
        return false;
});

and when I click the button (which is generated by jquery, but before the click code)
html += "
Back to Top
";

the alert does not appear. I have also tried this:
$("#top").click(function(){
            alert('I am here');
            $('html, body').animate({scrollTop:200}, 'slow');
            return false;
    });

I have tried moving this code into the footer, but that didnt do anything and this code is wrapped in the $(document).ready(function(){
I dont know what I am doing wrong.
Answer: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
As you are creating elements dynamically, You need to use Event Delegation using .on() delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)

Example
$(document).on('click', "#top", function(){
    //Your code
});

In place of document you should use closest static container for better performance.
Comment: Well, even though there already are two upvotes, it worth to mention: _when I click the button (which is generated by jquery, but before the click code)_. For all that I understood it is like in [this fiddle](http://jsfiddle.net/bk9bLxbb/), so it should work without event delegation.
Comment: @Regent, I totally agree with your example, if thats the scenario the OP's will surely work.


Collecting and centralizing information from many servers, sort of like Puppet's facter

Question: We manage hundreds of RedHat Enterprise Linux servers happily with Puppet. One of the cool side effects is that we can go to /var/lib/puppet/yaml/facts and look at the output of the "facter" utility (part of Puppet).
Now I would like the same kind of convenience for more information, such as which services are up and running or deactivated, or the list of packages installed. I'm not quite talking about monitoring, since I'm not so much interested in generating alerts or graphs on this, but more on having the information centralized for analysis.
I see two parts to doing this:

first a mechanism for connecting the central repository to the clients. I remember that net-snmp already exposes the RPM database if allowed to do so, I guess it might or might be made to expose chkconfig.
second a tool to store said information.

Which tool could help with this? I'm looking for something that stores data in a convenient way, either SQL, YAML, XML or consistently formatted text files, and can be easily told who to talk to.
Comment: I think the tag [remote-execution](http://serverfault.com/questions/tagged/remote-execution) would be appropriate to this question.
Answer: You may also want to checkout mcollective, it's been taken on by puppetlabs as an official project. It does orchestration and allows real time querying of your systems.
There are various screen casts and an simple plugin mechanism, it makes ad-hoc questions easy and uses puppet's RAL and facter, but other plugins are available and you can write your own. The screencast shows it in action.
Answer: For installed packages, net-snmp is probably the best way to go.
If you want a good interface for puppet facts, you can try Foreman. The git version also has a REST api what you can use in scripts.
You could possibly write custom puppet facts and access them via foreman.
Comment: Heres a post about using the query interface for Foreman.
Comment: http://abigant.wordpress.com/2010/10/25/pulling-a-list-of-hosts-from-foreman-for-puppet/


Permutation on $1,\dots,n$. Expected value of the number of people with a blocked sight.

Question: Let $n\ge10$. $n$ people numbered $1$ to $n$ are standing in line, while the height of person $i$ is $i$. We'd say that the sight of person $i$ is blocked if there exists a $j$ such that $j>i$ which stands in front of it in line. Let $X$ be the number of persons that their sight is blocked.

What is the expected value and variance of X?

I'd appreciate any hint or direction.
Answer: Let $X_i$ be a random variable which is $1$ if person $i$ has their sight blocked, for $1\le i \le n$. Notice that
$$
X=X_1+X_2+\dots+X_n.
$$
Using linearity of expectation, $EX=EX_1+EX_2+\dots+EX_n$, and each $EX_i$ is just the probability that person $i$'s sight is blocked.
For the variance,
$$
\text{Var }X = \sum_i \text{Var }X_i + \sum_{i\neq j}\text{Cov}(X_i,X_j)
$$
The first summation ranges from $i=1$ to $n$, while the second is over all ordered pairs $(i,j)$ with both $i,j$ in $\{1,2,\dots,n\}$ for which $i\neq j$. Be careful to include both $(i,j)$ and $(j,i)$!
Letting $E_i$ be the event that $i$'s vision is blocked, its not too hard to show $\text{Var }X_i=P(E_i)(1-P(E_i))$, while $\text{Cov}(X_i,X_j) = P(E_i\cap E_j)-P(E_i)P(E_j)$. Once you compute these probabilities, you have your answer.
Comment: Thank you for your answer. I have been able to compute $\mathbb{P}(E_i)=1-\frac{1}{n-i+1}$. However, how can I calculate $\mathbb{P}(E_i\cap E_j)$? They are not independent.
Comment: This is where the tricky combinatorics comes in. You need to count the number of permutations where both persons $i$ and $j$ are shorter than someone ahead of them. Instead, count the complement; permutations where either $i$ is taller then those in front, or $j$ is. Principle of inclusion-exclusion is useful here.
Comment: This problem would have been much cleaner if it instead asked about $Y$, the number of people whose vision was _not_ blocked. Writing $Y=\sum_i Y_i$ as before, the $P(Y_i=1)=1/(n-i+1)$, while $P(Y_i=1\cap Y_j=1)$ is much nicer to compute. Note $Y=n-X$, so Var $X=$ Var $Y$.
Comment: I don't really understand how to use inclusion-exculsion here.


O que significa o teste alfa, teste beta e produção no Google Play Developer Console?

Question: Estou fazendo meu primeiro aplicativo e quando fui fazer upload para o Google Play Developer Console fiquei em dúvida em qual área faço o upload pois aparece 3 opções: Teste Alfa, Teste Beta e Produção.
Comment: Isso pode ajudar: [Como se decide se uma aplicação está em alfa, beta, RC ou RTM?](http://pt.stackoverflow.com/q/20999/91)
Answer: Não há muita diferença entre os testes alfa e beta exceto pelo fato que você começa com um grupo pequeno para os testes alfa e passa para um grupo maior para os testes beta.
Produção é o termo que se usa quando seu aplicativo está disponível para seus usuários finais, aqueles para os quais você fabricou o aplicativo (ou seja, quando está disponível para qualquer um baixar ou comprar na Play Store).
Para fazer os testes alfa e beta você precisa enviar convites para os interessados em suas contas Google+ de forma que eles possam acessar seu aplicativo e baixá-lo. Os convites costumam ter a forma de um link direcionando-os para seu aplicativo na Play Store, que só fica visível para eles quando eles tiverem aceito o convite.
Do Google Developer Console:

Como eu começo?
Recomendamos começar com um pequeno grupo de
  testadores Alfa e, em seguida, expandir seu teste para um grupo de
  teste Beta maior.
Devo usar testes Beta abertos ou fechados?
Beta fechado: use esta
  opção se quiser realizar um teste com um grupo menor (como em sua
  empresa ou equipe) ou quando você souber exatamente com quais usuários
  deseja testar seu app. Se você testar um app já publicado, somente os
  usuários no seu grupo de testes receberão uma atualização da versão
  Alfa/Beta.
Beta aberto: use esta opção se quiser realizar um teste com um grupo
  grande e exibir a versão Beta do seu app na Play Store. Se você
  realizar um teste Beta aberto, qualquer pessoa poderá participar do
  seu programa Beta e enviar comentários privados para você. Verifique
  se o app está pronto para ficar visível na Play Store antes de
  escolher essa opção.
As versões Beta abertas e fechadas do seu app não terão avaliações
  públicas.


Compound Interest Differential Equation Question

Question: I'm positive someone else has asked a nearly identical problem in the past but I can't find an example of this specific variation.
Let's say initially you invest some principal amount ($I_P$) into a savings account with interest rate ($r$) continuously compounding interest. Additionally you invest a varying percentage ($p(t)$) of your wages ($w(t)$) such that your total investment into this account is given by:
$$
I_{T}( t) =I_{P} +I_{w} ,\ \ \ \ \ \ \ \ I_{w} \ =\int p( t) w( t) \ dt
$$
How would one set up a d.e. to determine the time value $V(t)$ of the investment? How would a variable interest rate $r(t)$ affect this?
Answer: At time $T,$ each amount that was invested in the interval $[t,t+dt]$ has compounded by $e^{\int_t^Tr(s)ds}.$ Therefore, taking the initial investment to have been at time $t=0,$ for each later time $T,$ $$V(T)=I_Pe^{\int_0^Tr(s)ds}+\int_{t=0}^Tp(t)w(t)e^{\int_t^Tr(s)ds}dt.$$


Adicionar propriedades HTML À um input via Razor

Question: Quando eu crio um campo input-type-text via Razor, faço algo parecido com isso:
@Html.TextBox("nomeTxt", null, new { @class = "form-control",
                                     @placeholder = "Exemplo de placeholder",
                                     @type = "text" })

Quando quero adicionar propriedades HTML à esse input, eu as coloco como fiz com o @class, @placeholder, @type
Por exemplo, se eu quiser colocar um MaxLength, bastaria adicionar ao final, como em:
@Html.TextBox("nomeTxt", null, new { @class = "form-control",
                                     @placeholder = "Exemplo de placeholder",
                                     @type = "text",
                                     @maxlength="10" })

Porém, alguns tipos de propriedades eu não consigo adicionar dessa forma. É o caso da data-date-format. O Razor não aceita esses hífens.
Como eu poderia criar, via Razor, um input como o exemplo abaixo?
<input id="txtData" name="txtData"
                    placeholder="Ex.: 13/10/2019"
                    data-date-format="dd/mm/yyyy"
                    maxlength="10">

Answer: Neste caso você deve trocar os hífens por underscore.
Note que os arrobas são desnecessários nos atributos (fora o class), este operador serve apenas para usar como nome alguma palavra reservada da linguagem (class, int, string, etc.).
@Html.TextBox("nomeTxt", null, new { @class = "form-control",
                                 placeholder = "Exemplo de placeholder",
                                 type = "text",
                                 maxlength="10"
                                 data_date_format="dd/mm/yyyy" })

Comment: Funcionou perfeito, obrigado!


R terra: equivalent stretch() values to match plotRGB(, stretch="lin")

Question: What are the actual parameters to be set in terra::stretch to emulate terra::plotRGB(,stretch="lin")?
I do:
library(terra)
b <- rast(system.file("ex/logo.tif", package="terra"))
plot(stretch(b[[1]],minq=0.02, maxq=.98),col=grey.colors(64),axes=FALSE,legend=FALSE)
plotRGB(b, stretch="lin", r=1,g=1,b=1)

and it is not exactly the same.
Answer: It seems to me that the difference is in the plotting, not in the stretching. To compare the stretching, a better comparison would be
library(terra)
b <- rast(system.file("ex/logo.tif", package="terra"))
s <- stretch(b, minq=0.02, maxq=.98)

par(mfrow=c(1,2))
plotRGB(s, r=1, g=1, b=1)
plotRGB(b, stretch="lin", r=1, g=1, b=1)

And then I do not see any differences. Or compare like this (use the entire gray palette, from black to white)
plot(s[[1]], col=grey(c(0:255)/255), axes=FALSE, legend=FALSE, mar=0)
plotRGB(b, stretch="lin", r=1, g=1, b=1)


Autoloader Zend Framework 1.12

Question: Estou iniciando (estudando) projeto com zf onde ainda não estou utilizando módulos.
Tenho inicialmente o seguinte arquivo .../projetozend/application/models/Dbtable/Actor.php
<?php
class Application_Model_Actor extends Zend_Db_Table_Abstract
{
    protected $_name = 'actor'; // Nome da tabela
    protected $_id = 'actor_id'; // campo id da tabela
}

Tenho também o controller index onde tem aactionIndex e estou tentando instanciar essa model de cima.
public function indexAction()
{
   $actor = new Application_Model_Actor();
}

Ai beleza porém estou com o seguinte problema: Fatal error: Class 'Application_Model_Actor' not found [...]
Estou vendo que preciso configurar o autoloader do projeto na qual eu já dei uma pesquisada na web, mas não conseguir entender e implementar. A final qual é a maneira mais correta de fazer essa configuração?
Bem estou usando o ZF1 pois estou no estágio e aqui é usando essa versão.
Answer: O ideal seria que o nome da classe fosse:
class Application_Models_Dbtable_Actor extends Zend_Db_Table_Abstract
{...

Assim seguiria o padrão PSR-0, pois o autoload segue esse padrão.

Autoloader Zend Framework 1.12


Symantec Mail Security 8240 OS

Question: What's the operating system and version on a Symantec Mail Security 8240 appliance?
Answer: According to the Implementation Guide, "Symantec Mail Security 8200 Series appliances use the Linux kernel 2.6.7."
I would imagine it's a custom distribution, but I don't know which one it's based on.
Comment: Dennis, I think you're right. Indeed, the only info Symantec gives is that: the Linux kernel version. On it they're surely built a Symantec-custom distrubution for appliances 8200 series. Thank you :)

Symantec Mail Security 8240 OS


why is it a compact operator

Question: let $B(H)$ the $*-$algebra of bounded linear functions on a separable $\mathbb{C}$-Hilbert space and $\tau:B(H)\to B(H)$ a bounded linear multiplicative map with $\tau(x^*)=\tau(x)^*$ for all $x\in B(H)$.
Given $S\in B(H)$ such that: $S\tau(x)-\tau(x)S$, $(S^2-id_H)\tau(x)$, and $(S^*-S)\tau(x)$ are compaxt for all $x\in B(H)$.

Is $((\frac{S+S^*}{2})^2-id_H)\tau(x)$ compact for all $x\in B(H)$?

I think so, but I'm not sure how to proof it.
It can be possible that there are redundant assumptions, I'm not sure what will be needed. It is $((\frac{S+S^*}{2})^2-id_H)\tau(x)=(\frac{S^2+(S^*)^2+2SS^*}{4}-id_H)\tau(x)$ and it follows from the assumptions that $S^*\tau(x)-\tau(x)S^*$, $((S^*)^2-id_H)\tau(x)$, and $(S-S^*)\tau(x)$ are compaxt for all $x\in B(H)$.
But I don't know how to proceed. I was thinking about to use spectral theorems or some functional calculus arguments, but still haven't solved it.
Comment: Your expansion of the binomial is incorrect unless $S$ is a normal operator.
Comment: Hint: compact operators are closed under addition.
Comment: @JacobManaker I don't see why you can argue like that. S does not have to be compact and $id_H$ is in general noncompact (for $H$ infinite dimensional)
Comment: Yes, but you know some compact operators already.  Can you write the operator of interest as a linear combination of those operators?
Comment: @Jacob Manaker first of all thank you for your help and for the corrrection. I can't expand the binomial like this in general? Or what exactly is wrong? I tried to write this as an linear combination already but I don't get this in this case that I can't expand the term $(\frac{S+S^*}{2})^2$ as in my question
Comment: We don't necessarily have that $S$ and $S^*$ commute.  I'll write up an answer.
Answer: The proposed operator, which I will call $\DeclareMathOperator{\id}{id} M$, is compact iff $H$ is finite-dimensional.
To see this, first note that the adjoint of a compact operator is compact, and vice-versa, so the conditions on $S$ are preserved if we swap $S\mapsto S^*$.  That is, $S*\tau(x)−\tau(x)S^*$, $((S^*)^2−\id_H)\tau(x)$, and $(S−S^*)τ(x)$ are all compact.
Now consider the operator $\tilde{M}=\left(\frac{(S-S^*)^2}{2}-\id_H\right)\tau(x)$.  We may rewrite $$\tilde{M}=\left(\frac{S-S^*}{2}\right)(S-S^*)\tau(x)-\id_H\tau(x)$$ and recall that the product of a compact operator and a continuous operator is compact.  (Why?  Take $K$ the compact operator and $F$ the continuous one.  To show $FK$ is compact: the image of $K$ is compact, and $F$, being continuous, maps (pre)compact spaces to (pre)compact spaces.  To show $KF$ is compact: $\DeclareMathOperator{\im}{im} \im{(F)}\subseteq H$, so $\im{(KF)}\subseteq\im{(K)}$, which is precompact.)  Given this recollection, the first term in our expansion is compact, as it is the product of continuous $\left(\frac{S-S^*}{2}\right)$ with compact $(S-S^*)\tau(x)$.  The second term is compact iff $H$ is finite-dimensional.  So $\tilde{M}$ is compact iff $H$ is finite-dimensional.
Now expand $\tilde{M}$ another way: \begin{align*}
\tilde{M}&=\left(\frac{(S-S^*)(S-S^*)}{2}-\id_H\right)\tau(x) \\
&=\left(\frac{S(S-S^*)-S^*(S-S^*)}{2}-\id_H\right)\tau(x) \\
&=\left(\frac{S^2-SS^*-S^*S+(S^*)^2)}{2}-\id_H\right)\tau(x) \\
&=\left(\frac{(S^2-\id_H)-SS^*-S^*S+((S^*)^2-\id_H)}{2}\right)\tau(x) \\
&=\left(\frac{(S^2-\id_H)\tau(x)}{2}\right)+\left(\frac{((S^*)^2-\id_H)\tau(x)}{2}\right)-\left(\frac{(SS^*+S^*S)\tau(x)}{2}\right)
\end{align*}  The first two terms of this sum are compact, but $\tilde{M}$ is not and compact operators are closed under addition.  So the remaining term is a compact operator iff $H$ is finite-dimensional.
Now return to $M$.  We can expand $M$ similarly: \begin{align*}
\tilde{M}&=\left(\frac{(S+S^*)(S+S^*)}{2}-\id_H\right)\tau(x) \\
&=\left(\frac{S^2+SS^*+S^*S+(S^*)^2)}{2}-\id_H\right)\tau(x) \\
&=\left(\frac{(S^2-\id_H)+SS^*+S^*S+((S^*)^2-\id_H)}{2}\right)\tau(x) \\
&=\left(\frac{(S^2-\id_H)\tau(x)}{2}\right)+\left(\frac{((S^*)^2-\id_H)\tau(x)}{2}\right)+\left(\frac{(SS^*+S^*S)\tau(x)}{2}\right)
\end{align*}  Again, the first two terms must be compact, so $M$ is compact iff the last term is compact.  But we just showed that that last terms is compact iff $H$ is finite-dimensional, so we've proven our claim.
Comment: Thank you! Now I understand

why is it a compact operator


Menu link that uses title from router item's title callback?

Question: In the user menu, I would like the menu link for the "user" path to use the dynamic link title from the title callback, instead of a custom link title.
I know I could alter this on the theme layer, e.g. with hook_preprocess_menu_link(). But somehow I have the feeling there must be something simpler, that works out of the box..
Any ideas?
Answer: Menu links that are registered through hook_menu() do this already, so if you are using the system-provided menu link, it should pick up whatever you have altered "title callback" to be instead.
The system-provided 'user' menu link is being altered by user.module to prevent it from showing up to anonymous users (see user_menu_link_alter(), user_translated_menu_link_alter()). That might be getting in the way of what you want, in which case you could bypass/unset the user module implementation in a hook_module_implements_alter() function.
If you're using a custom menu link created through the UI, I don't believe you will be able to make that link title dynamic short of implementing hook_menu_link_alter() and hook_translated_menu_link_alter(). That's probably more work than intercepting it at the theme layer, though.
Comment: I assume this behavior (taking the title from the title callback) only works if the menu link is not "overridden", right?
Comment: Yep. Overriding a menu link title in the UI more or less makes it static.
Comment: I swear I knew all of this once :)


Computing the free-part

Question: I wanted to ask about some existing algorithms for computing points over elliptic curves.
Background : We know that the famous theorem of Mordell and Weil says that " Group of rational points on an elliptic curve is finitely generated " . i.e. $E(\mathbb{Q})=\mathbb{Z}^{r}\oplus E_{\rm{torsion}}(\mathbb{Q})$ . So we can find the torsion points a bit easily by using  theorem of Nagell and Lutz.

My main question is that

How can we find the free part ? ( I mean points of infinite order ) . I have read that we can just use the homogeneous spaces ( Torsors ) and just dig for some points with infinite order. But its well known that they are not such efficient methods that apply universally and work every time. So  are there any other known ( Efficient ) methods for computing the points of infinite order ? , apart from using Homogeneous spaces.

P.S : Apart from this, giving rational points on the original elliptic curve corresponds to giving sections of the projection $S \to C$ ( where $S$ is elliptic surface over curve $C$ ). To determine such sections essentially amounts to determining all the curves lying on $S$ that can be defined over $\mathbb F$ ( where $F$ is a finite field where $C$ lies ).
So is there any anagolous way of finding the points of infinite order by considering the associated surfaces. Is there any work done in that direction ? ( Any good references to read further )
Thank you.
Answer: The method of descent is the only "algorithm" we know that will determine the points of infinite order on an elliptic curve. It is not an algorithm until someone proves that Sha(E/Q) is finite... and even if someone proves this, the algorithm is not very efficient on curves with large conductor (i.e., it may take an enormous amount of time for the method to work, and it might require several consecutive descents, which is hard to implement - and not implemented in the generality that it would be needed for the method to work every time).
The method of descent (and a discussion about its efficiency and dependency on Sha) is very nicely described in Silverman's "The arithmetic of elliptic curves".
Comment: No, the correct path is to read Silverman's book first, cover to cover. Study that book well!
Comment: This is not a new idea. But just for fun, let $E: y^2=x^3-157^2x$. This curve has rank $1$. Can you find the generator using your method?
Comment: But, I have some idea in my mind. Can we use the coefficient predicted by Birch and Swinnerton-Dyer to compute the Regulator and later compute the heights of points and then search for homogeneous spaces that have the obtained height and then obtain the corresponding point of finite order. Sir, I need to learn some methods for computing coefficients and then try this. I realized that B.S.D apart from giving the cardinality of Mordell-Weil group, also should suggest some good way of computing points of infinite order. And some constraints have to be fulfilled to do so, like the one you said.
Comment: But am I going in right path sir ? . Thanks a ton, for answering my question. $+\infty$, but my ability is limited in only giving $+1$.
Comment: BS-D is a conjecture so, at best, you would get an "algorithm" until BS-D is proved. However, if the rank > 1, how do you get the height of each generator point from the regulator?
Comment: Yes sir, it would indeed fail if rank$\gt1$ , and many considerations like parity conjecture etc, come into play. But will my idea atleast work when rank$=1$ ( and if B.SD is assumed to be true ) ? , if so, I wanted to do some calculations, and submit my work to a journal. But does idea makes sense ? , and is new ? . Thank you. @Alvaro Lozano-Robledo
Comment: Lozano-Robledo : Sir, I am trying my level, to attempt a solution, but I dont have any sophisticated environment, and even proper books and teachers to guide me, I have been learning these things myself. If my answer doesn't make any sense, please forgive me. I know that $157$ is a congruent number, I don't know routines to compute the things, but I have been trying to compute things by hands, B.S.D predicts the coefficient to be $\large \frac{|Sha(E/\mathbb{Q})| . \Omega . \prod_p c_p. Reg(E/\mathbb{Q})}{ E_{\rm{torsion}}(\mathbb{Q})}$ contd...
Comment: But I don't know how to find all those things, but if there is some way to find that coefficient, we can just find out regulator, by sending all terms to the other side. As $Reg(E/\mathbb{Q})$ is nothing but twice the canonical height, we can obtain the height and later on if we can make a database of all heights ( I think it takes some years to make so ) we can search for homogeneous spaces and match the height and get the coordinates of points. But I don't know how far it works, I recently heard here (at MO ) that there is some software called Sage, where we can compute these things. Contd..
Comment: But I don't know how can one learn all those things, and I even doubt the computation of coefficient, are there any machine codes to find the taylor expansion sir. If I am provided with all those things I can surely compute a coordinate, but I dont know how far I would be successful, Ball now is in your court, its you who needs to judge. @Alvaro Lozano-Robledo
Comment: My hand computations take months for just computing small expansions of L-functions , I am looking forward for some computational help sir. My place is very unsophisticated, only few people know what is a computer, and I am currently at Internet cafe, so I can install some softwares @Alvaro Lozano-Robledo
Comment: But is 157 a congruent number ? , I have read this somewhere in a short material of Andrew Wiles
Comment: Lozano-Robledo : Am I in correct path ? , and is it possible to make such computations in a finite time ? .
Comment: Lozano-Robledo : But you didn't comment about the method I described above, will it work ?
Comment: Yes, it will work but it will be *very* inefficient and slow for curves of large conductor, or curves with a generator of high height.
Comment: Lozano-Robledo : Thank you for your valuable interaction, I duly follow your advice and start mastering the Silverman's book . Thanks a lot !!! sir .

Computing the free-part


Java - Difference between for loop terminating expression

Question: I'm just curious: Is there a difference on speed and performance between this two loops implementation? Assume that size() method returns the length of the array,collection, or object that handles a group of elements (actually it's from XOM api).
Implementation 1:
int size = someArray.size();
for (int i = 0; i < size; i++) {
    // do stuff here
}

Implementation 2:
for (int i = 0; i < someArray.size(); i++) {
    // do stuff here
}

Answer: From a performance point of view, there is little difference.  This is because a loop can be optimized so that the size() lookup is inlined, resulting in very little performance difference.
The main difference is if the size changes while looping. The first case will try to iterate a fixed number of times. In the second case, the number of iterations will depend on the final size().
Answer: The 1st snippet is bound to execute faster since it calls size() once only. The 2nd snippet calls size() N times. Depending on the impl. it might pose significant penalty, esp. if the compiler finds hard to inline the method and/or the size() method doesn't just return non-volatile variable, etc.
I'd have rewritten it like for(int i=0, s=someCollection.size(); i<s; i++)
Note: arrays don't have size() method.
Comment: @bestss that's why I specified it in general (for groups of elements) :)
Comment: @Jairo, there is Huge difference between arrays and collections. arrays cannot change their size under any circumstances. `for(int i=0;i<array.length;i++)` is **a lot more performance friendly** than collection traverse. JVM doesn't add code for bounds checking for such loops (only once).
Comment: @bestsss: surely an ArrayList does have a *size()* method and is, somehow, an array ;)
Comment: @SyntaxT3rr0r, an ArrayList is not an array. It's a wrapper, and it can change its size (not like an array) by allocating a new array. That's why you can't always optimize away the size() call for an ArrayList, while for true arrays it's trivial.
Comment: @Sergey Tachenov: I've got 5K+ rep only on Java questions, I know what a Java array is, thanks ;)   My point what that if some god at Sun decided to name that "thing" ArrayList well... it means that, somehow, it must be related to an "array" (now you can keep arguing: but either it's somehow an array and I'm right **or** the Sun gods where wrong and stupid when they decided to name that collection *ArrayList*... I think you won't like it either way ;)
Comment: @SyntaxT3rr0r, "related to array" and "is an array" are obviously different things. If it was an array, it would probably be named ListArray or something. You aren't going to say that CharSequence is a char? But terminology is really irrelevant here. What's relevant is the difference between regularArray.length and arrayList.size().
Comment: @Sergey Tachenov: but surely I **NEVER** wrote "is an array".  I wrote  "is, **somehow**, an array".  And, of course, laking any intellectual honesty and any sense of humor you choosed to ignore that... Somehow ;)  Now you can have the last word, I'm not responding to you anymore... Somehow ;)
Comment: @Sergey Tachenov, the reference (to array) is a glaring sarcasm, no need for such daft offenses here.
Comment: @bestsss, I understand now... somehow. My English just isn't good enough to detect sarcasm promptly. Never indented to offend anyone, though.
Comment: @Sergey, yeah, my native language is written in cyrillic as well :) but the smile " ;) " at the end is a good pointer.
Answer: Yes, there is a difference. In the first loop, the size() method is only called once. In the second one, it's called at each iteration.
If the iteration modifies the size of the collection (which is very very uncommon), the second one is needed. In most cases, you should prefer the first one, but limit the scope of the size variable :
for (int i = 0, size = someArray.size(); i < size; i++) {
    // ...
}

But most of the time, you should prefer the foreach syntax anyway :
for (Foo foo : collection) {
    // ...
}

which will iterate over the array or collection efficiently, even for a LinkedList for example, where indexed access is not optimal.
Comment: if the size can vary during the iteration then there's probably a verious serious design/synchronization issue.  Moreover in such a loop it's highly probable that there will be a *get(i)* and if the size change, it can change, for example, *after* re-reading the size but *before* doing the get, in which case the code shall throw an exception.
Comment: I think I cannot use **foreach** in my case. The XOM API's Elements feature cannot be traversed that way. (XOM is an XML-processing library for Java)
Comment: @SyntaxT3rr0r: agreed. I was thinking about a loop which adds/removes items from the collection inside the iteration (no multithreading). But I agree it's very very uncommon. I'll edit my answer to be clearer.
Comment: if you add/remove during the loop, make well sure you change size variable accordingly. Simple solution is `size=collection.size()`, other include size++ or size-- and so on.
Answer: Don't worry about it, JVM optimization is very aggressive these days.
Use the 2nd form, for it's more readable, and most likely as fast. Premature optimization yada yada.
And when you do need to improve speed, always profile first, don't guess.
It is extremely unlikely that caching size() in a local variable could benefit your app noticeably. If it does, you must be doing simple  operations over a huge dataset. You shouldn't use ArrayList at all in that case.
Answer: Maybe it is worth to note that this construct:
for (String s : getStringsList()) {
    //...
}

invokes getStringsList() only once and then operates on iterator behind the scenes. So it is safe to perform lengthy operations or change some state inside getStringsList().
Comment: *So it is safe to perform lengthy operations or change some state inside getStringsList().* most likely if that happens a ConcurrentModificationException is on the line (erm stack)
Comment: I don't quite understand. What I meant is that `getStringsList()` might be an expensive method (e.g. from DAO) because it is called only once, before the loop starts. After that the for loop operates on returned list, or - to be more precise - on the iterator. Where is the place for `ConcurrentModificationException`? I assume getStringsList() does not hold the reference to returned list.
Answer: Always avoid anything that can be done outside of the loop like method calls, assigning values to variables, or testing for conditions.
Method calls are more costly than the equivalent code without the call, and by repeating method calls again and again, you just add overhead to your application.
Move any method calls out of the loop, even if this requires rewriting of the code.
Benefits :-
Unless the compiler optimizes it, the loop condition will be calculated for each iteration over the loop.
If the condition value is not going to change, the code will execute faster if the method call is moved out of the loop.
Note :-
If the method returns a value that will not change during the loop, then store its value in a temporary variable before the loop.
Hence its value is stored in a temporary variable size outside the loop, and then used as the loop termination condition.


react native debug tools and techniques?

Question: I'm working on a RN app in VS Code.  I'm using an Android AVD loaded from AS. My Android emulator is currently displaying the following error:  "Could not connect to development server."  I've seen the following debug steps listed as part of an answer to a similar question on SO:

Open the in-app Developer menu.
Go to Dev Settings → Debug server host for device.
Type in your machine's IP address and the port of the local dev server (e.g. 10.0.1.1:8081).
Go back to the Developer menu and select Reload JS.

But I don't see a way to "Open the in-app Developer menu" via my AVD:

Alternatively, I get the impression that react-devtools could potentially be used to help with debug purposes for a RN app.  When I launch the React Dev Tools, RDT states that I should add the following line of code to the top of the page that I want to debug, before importing React DOM:

I'm not totally clear on this instruction.  My app has App.js and it has child components.  Am I supposed to insert this line of code as the first line of code in App.js or some other file?  I currently have this as the first line in App.js but it doesn't seem to have any effect.  Should I be using this hook differently or am I way off base in some other way here?
Comment: Press d on metro cli to see a developer menu pop on on Simulator/Device
Answer: Please execute this command from the command: adb reverse tcp:8081 tcp:8081
Then run the project again.


Basic: Where to initialize/set the function

Question: I am working on a .Net project(solution) which is having 25 projects. I want to set the value in some function/method so that It can be set once for the entire application. Where to set this method so that I dnt need to set it again in the individual winforms. That function/method is in some dll so i required to set that like this:
Logger obj = Logger.GetInstance();
obj.SetLogLevel(1);

I need to use the above code only once.
Kindly help?
Thank You...
Answer: Since you talk about pages, I assume you have a web site or a web application.
What you can do, in this case is to create a static class in App_Code and do this in it's static constructor. This way the first time any page accesses the static class the code will run and it won't run again.
public static class AStaticClass {

    public static Logger Obj;

    static AStaticClass() {
        Obj = Logger.GetInstance();
        Obj.SetLogLevel(1);
    }
}

EDIT:
In case this is a window application, just put this static class in one of the libraries. It doesn't really matter where the class is.


Understanding Exchange User Monitor (ExMon) Output

Question: I recently downloaded and ran ExMon while trying to troubleshoot Outlook connectivity problems due to high CPU usage on Exchange Server 2010 SP2 UR8.
The tool provides a great set of data, but I have not yet figured out how to make great use of it.
My first question is why the Exchange Server itself shows up as a high-use MAPI client in the ExMon data.

Among the users' client versions I see build numbers listed for Outlook 2013, 2010, and yes, even 2007 clients. I also see build number 14.2.387.0, which represents Exchange Server 2010 SP2 Update Rollup 8 (+/- some other patch that makes it not quite match the UR8 number).
There are many user rows that list only "::1" and/or the short hostname of my Exchange server in the 'Client IP Addresses' column. Some other columns include the end-user's actual IP address and the Exchange server's IP address.
ExMon shows that it is actually Exchange Server that is utilizing the highest percentage of CPU that is used for MAPI calls.

I had expected to see 1 IP address and version number for each user reported by ExMon. Instead, most records show multiple version #'s (Exchange ver and Outlook ver) and multiple IPs (Exchange IP and client IP).
Can anyone explain the reason for this to me, please?
Comment: What's your exchange topology like? single standalone server? Is anyone using OWA?
Comment: Single server with all roles. OWA does get some use. We also have mobile devices using ActiveSync through an MDM system.
Answer: Strictly speaking, the MAPI connections from client >> Exchange 2010 mailbox server runs through the CAS, so if you've got CAS and mailbox roles installed on the same server, it makes sense that you'd see that your only server creating most of the MAPI activity.
Comment: Accepting because this does answer the bold part of my question. Additional comments to the rest of my question are welcome!
Comment: Would this indicate clients who are not using cached Exchange mode, or is that reflected elsewhere in the output? The column that I thought should contain that data has the same results for ALL users, but I know we have a mixture of CEM OFF (for VDI users) and ON (for non-VDI users).
Comment: Not sure how cached exchange mode affects that output.


ASP.NET webAPI Framework Slowness issue

Question: I have implemented a web service using ASP.NET WebAPI framework.
The response time is faster in my local system (target framework4.5) that deploying to the server.
After deployment to Windows2012R2 IIS8.5, a response takes about 30 seconds for each request. I have tried the sample web service without any data retrieval from database. This also takes about longer time. I installed Fiddler and identified that TTFB took about 26 seconds.
I created the web service using this url:
https://www.c-sharpcorner.com/article/create-simple-web-api-in-asp-net-mvc/
Even displaying "welcome" message itself takes about 30 seconds.
Any thoughts on where to look to investigate the performance issue?
Here is sample code as in URL
<code>namespace Demo1.Controllers
{
    [System.Web.Mvc.SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)]
    public class DemoController : ApiController
    {
     public string Get()
        {
            return "Welcome To PARIS Web API";
        }
        public List<string> Get(int Id)
        {
            return new List<string> {
                "Data1",
                "Data2"
            };
        }
</code>
}
}
Comment: Can you include some sample code? It may not be a code issue, but providing more details would be helpful.
Comment: @Nata please edit your post and put the code in that. Do not use comments to write code.
Comment: Have you deployed to a _cloud_ server? Also are you deploying to IIS? Or are you using containers?
Answer:
Performance of compiled code on two different servers is almost always related to the physical resources that have been made available at the time to code runs.

Keep in mind that we as developers usually code on PCs with far better specs than the servers we deploy to!

For API deployments, it is common to deploy to cloud or minimal servers that have either reduced CPU or Core counts, or the resources available to your deployed app have been restricted to allow for the server to run multiple apps.

Sometimes to reduce costs we deploy to servers with the resources that we think our app needs, without remembering that the OS of that server will have basic requirements that will need to be met.

You have already isolated the issue about the available bandwidth between the deployed server and the database, for other punters keep this in mind as a potential bottleneck, keep your database close to your APIs.
If every request to a simple site is slow, check the logs on the slow server, look for errors or indications of slow starts, or that the app is restarting for every request. It is common and we accept slow cold starts of our web apps, but the web app should remain alive between requests, even if it is session/state less.
It would help to know if you are deploying to a physical server, virtual machine, cloud app service or a container host, if the server is in the cloud or on the ground and if you known the general bandwidth available from the server?

Just spit-balling, this was an old .Net gotchya: Check that your server or firewall is not blocking outbound internet calls!
Due to low level calls in .Net trying to perform SSL Certificate Revocation checks your code may wait at startup trying to make external calls. This post discussed options to disable that. Something to try if all else fails.

ASP.NET webAPI Framework Slowness issue


Create custom URL pattern

Question: Using the pathauto module, we could have created custom URL patterns using the hook_pathauto(). I could not find any such way to achieve the same in D8.
ref. https://envisioninteractive.com/drupal/using-the-pathauto-api-drupal-module-a-simple-example/
Can someone please explain is this possible in D8 and if so how.
Thanks
Answer: In Drupal 8, pathauto patterns are configuration entities. You have  at least two choices to provide them with your custom module:
(1) Provide your pattern as YAML configurations in your module's config/install folder. They will be considered and installed to your Drupal, when your module will be installed. Easiest to create using the UI and doing a configuration export afterwards. Just remove the generated UUID of the pattern.
(2) On run-time or in your install/update hooks, you can use Drupal\pathauto\Entity\PathautoPattern::create() or the \Drupal::entityTypeManager() to create them dynamically:
$data = [
  'id' => 'my_pattern_machine_name',
  'type' => 'canonical_entities:node',
  'pattern' => 'my-path/[node:title]',
  'weight' => 0,
];
$pattern = \Drupal::entityTypeManager()->getStorage('pathauto_pattern')->create($data);

You can then use the returned pattern entity in $pattern to add selection conditions (e.g. bundles, language, ...) as required. Don't forget to save the entity afterwards, and - of course - check, if the pathauto module has been installed before or make it a dependency of your custom module.
Comment: As an aside, @Mario, when might the generated UUID cause an issue? I have lazily left UUIDs in place when exporting config and not seen any problems (yet). Or is it merely a matter of tidiness?
Comment: It IMHO shouldn't matter for the import/installation, as the probability for collisions with existing elements is far too small. Yet, where the code is publicly available for review (as within contrib modules), I always prefer to tidy up any such IDs so they can be generated uniquely for the target system. It just feels like leaving less room for any kind of malicious actions to third parties.
Comment: Understood. But this will simply create another pathauto pattern. I was more curious about the customization that we had in `hook_pathauto()` like the `patterndefault`, `patternitems`, batch operations etc. Actually what I am trying to achieve here is create a separate customized pattern group for one of my vocabulary which will have separate pattern for the parent items and another for the child items.
Sorry I was not precise about my requirement before.
However, thanks for you input nevertheless. I didnt knew this. :)
Comment: You can do this by mixing up the above mentioned custom pattern for your vocabulary/bundle and implementing hook_pathauto_pattern_alter(), which is invoked just after a pattern has been applied for an entity and before tokens will be replaced.

Create custom URL pattern


What are SPF records and how are they related to emails?

Question: I changed the hosting of a website and their email is hosted with another company. There is also an SPF record for that host.
What is the function of that SPF record?
Answer: SPF Stands for Sender Policy Framework.  What it allows an administrator to do is specify what servers or internet hosts are allowed to send mail originating from that domain.  See this article for more information: http://en.wikipedia.org/wiki/Sender_Policy_Framework
Comment: +1 for a clear and concise answer.
Comment: if user are not receiving the emails o their end. Does it has anything to do with SPF
Comment: It's "possible" but it would have to meet some specific circumstances.  If there are SPF entries in DNS that do not match the host name of the server you are sending mail from some mail servers will think that your email is spam and throw it away.  Hotmail for example is not a big fan of invalid SPF entries.
Answer: Sender Policy Framework.  It's a method of using DNS TXT records in order to reduce SPAM mail.  The receiving email server needs to read these records.
See: http://en.wikipedia.org/wiki/Sender_Policy_Framework
Comment: +1 for posting moments before I did and linking to the same wiki entry :)


Why do these two code fragments differ

Question: I just noticed that when I change the last line in the code fragment from potential =+ rep_pot  to potential = potential + rep_pot, I get completely different behaviour. Has anybody got any idea why this is happening?
double potential = euclideanDistance(i, goal);
for (IntPoint h: hits){
    double dist = euclideanDistance(i, h);
    double a = range - dist;
    double rep_pot = (Math.exp(-1/a)) / dist;
    potential =+ rep_pot;
}

Comment: what are two different behavior you are seeing?
Comment: what is =+ ? did you mean += ?
Comment: and it should be `+=`, instead of `=+` :)
Answer: There is no =+ operator in Java. See the Java Language Specification for all legal operators.
=+ are two operators: = followed by +.
Answer: That is because
potential = potential + rep_pot

is similar to
potential += rep_pot

and
potential =+ rep_pot;

is the same as
potential = rep_pot;

Answer: You probably meant +=. In your case it is interpreted as x = +x which is x = x
Use += :
potential += rep_pot;

Answer: Yes, because these two things are not equivalent.
potential =+ rep_pot;

Here we have potential assigned a value of the expression 'unary plus rep_pot'
The thing you intendet to write looks differently:
potential += rep_pot;

And this is equivalent to
potential = potential + rep_pot;

Why do these two code fragments differ


How can I time taken between 2 events

Question: I am trying to record the time taken between 2 sensors being activated
I am using ladder logic for my university project although struggling with code to record time taken between two events so as to store the information
Comment: What have you tried so far?
Comment: just using TON timer and tried messing with RTC, but very limited knowledge in this area.. unsure if needs to be all code or all ladder logic or comprise of both.. any help would be greatly appreciated
Comment: @GaryMcdevitt Ladder logic features like Timers can be different depending on the PLC used, can you let us know which one you are using?
Answer: It would be interesting if you included which PLC you are trying to use as the timer block can vary a little between some brands of PLCs, below I will put an answer that works for Codesys, Twincat, Omron, Delta and others similar, but some blocks may vary from format or in the name of the inputs and outputs, but the concept is the same.
You also didn't specify if you intend to measure between the rising or falling edges of the sensors, this could influence the measured time. Let's assume you want to measure between the rising edge of S1 and the rising edge of S2.
The idea is to start a TON timer (fbTimer) when sensor S1 is turned on and keep this timer running even if S1 is turned off and, when S2 is turned on, capture the elapsed time (fbTimer.ET) on the timer and store it in a variable (using the MOVE block) before restarting the timer (when the elapsed time is reset).
Some notes:

Because the PLC program is cyclic, the order of the Networks (ladder lines) will matter, as you need to capture the timer time before resetting it in the same cycle.
You must use sensor S2's rising edge capture when recording the time, or the value will be overwritten in the next cycle, as the timer will have been reseted.
Problems can occur in this example if the order of activation of the sensors changes in time, or if S1 is activated more than once and you want, for example, only the time difference in the last activation of it (in this example a second pulse of S1 before S2 being triggered will be ignored).
Note that there are other ways to do this, including using other types of timers such as TOF and TP.

How can I time taken between 2 events


How to interpret output of a moderation with 2 moderators (1 Dichotomous, 1 continuous) and a dichotomous predictor?

Question: I have conducted a moderation analysis with two independent moderators. (Using Hayes Process model 2). I have attached the output for your reference.
I am looking for the impact that financial wellbeing and gender has the relationship between marital status and loneliness.
My variables are:

Y: Loneliness (continuous variable - low values indicating low
loneliness)
X: Marital status (single or married- dummy coded to have    single
as the reference category)
W (mod1): Financial wellbeing
(continuous- low values indicating low financial wellbeing)
Z (mod2): Gender (male or female- dummy coded to have male as the
reference    category)

All the p-values show significance
I have two questions:

Is this selection of variables appropriate for the moderation analysis I am undertaking? Is the combination of a  dichotomous predictor and moderator suitable for this?
Can someone please help me interpret the output? When looking at the conditional effect, I am seeing all the values under 'effect' are negative- some closer to 0 than others but I am not sure how to interpret this in relation to the dichotomous predictor (being single coded as 0).

Any guidance would be greatly appreciated!
Comment: Please edit the question to provide the program output as text. If you paste text into the editor, select it, and use the code `{}` tool, it's easier to read than in a picture, values can be copied for further analysis, and those who use speech-to-text can "see" the values.
Comment: Thank you for your suggestion! Each time I copy the text into the question to edit - it forces it into an image format without the option to use the code tool. Even when first selecting the code tool to then copy and paste the output in -It still wants to convert it into an image. I'm unsure why it's doing that and how to prevent it, I'm afraid!
Answer: This is a linear model with two interaction terms, expressed in R formula syntax as:
Y ~ X + W + Z + X:W + X:Z

The "moderation" is via the interaction terms X:W and X:Z, with X (marital status here) being of primary interest but with individual terms also needed for W and Z. Interactions are possible in principle between categorical predictors, continuous predictors, or any combination, so you have no problem there. The interaction terms are simply products of the included predictor-variable values.
I'm not sure, however, how this PROCESS Procedure works together with standard SPSS coding of categorical predictors like X and Z here. The SPSS default is to express coefficients as differences from the highest level of a categorical predictor, unlike R which uses differences from the lowest level. You will have to check the manual(s) or play with some example data to determine whether, for example, the coefficient for Z (Male) is for (Male - Female) or (Female - Male). (Highly software-specific questions are off-topic on this site.)
For the "conditional effects," each "Effect" is the difference associated with marital-status difference at the indicated combination of the moderators. Again, whether that's for (Married - Single) or (Single - Married) is a question of how SPSS and this PROCESS Procedure together are handling categorical predictors.
With such a large sample it's not surprising that all your results are "statistically significant." You have to use your understanding of the subject matter to gauge whether they are practically significant.