Use Linq instead of nested foreach loops to sum values

Question: I want to find the sum of values without using a nested foreach loop
How do I write this using Linq instead?
decimal posVal = 0;
decimal negVal = 0;
foreach (var j in journal)
{
    foreach (var t in j.trans)
    {
        foreach (var l in t.line)
        {
            if (l.val > 0)
                posVal += l.val;
            else
                negVal += l.val;
        }
    }
}

Comment: `foreach (var l in journal.SelectMany(j => j.trans).SelectMany(t => t.line)) { .. }` ?
Answer: You can use SelectMany,
var allLines = journal
               .SelectMany(j => j.trans
               .SelectMany(l => l.line)
               .ToList();

var posVal = allLines.Where(x => x.val > 0).Sum(x => x.val);
var negVal = allLines.Where(x => x.val < 0).Sum(x => x.val);

Comment: A couple of questions (disclaimer: I may be wrong since it's pre-morning coffee); Doesn't this just sum up the number of positives and negatives, not the values? Also, if my caffeine is not dangerously low it enumerates the enumerable twice, so if journal is not possible to enumerate more than once, it'll break.
Comment: https://www.jetbrains.com/help/resharper/2019.1/PossibleMultipleEnumeration.html has a pretty good explanation. Let's for example say that `journal` is an enumerable that reads the data from the database. If so, calculating `posVal` and `negVal` will ask the database once each, possibly with different results if the database is updated inbetween. It may be quite ok if journal is for example a list, but in this case we don't really know for sure :)
Comment: @JoachimIsaksson, Good morning ;) For first question, Yes I updated answer now it will sum up all values instead of positive, negatives. for second question, can you please elaborate I did not understand what you want convey here. As `journal` used in foreach loop it should be enumerate right? *if journal is not possible to enumerate more than once, it'll break.* please elaborate
Comment: @JoachimIsaksson, thanks for this article, I understood and updated my answer. Now I am forcing enumeration while initializing `allLines` variable, in this way it will not give two different results if `journal` updates in between `posVal` and `negVal`.
Comment: I was not aware of this, thanks for helping me here, Have a nice day
Comment: now you iterating over `IEnumerable` three times instead of two (where you actually can iterate only once) :\ this is highly inefficient
Comment: @vasily.sib, I updated my answer, Now I am first converting `journal` to `List` and then converting `allLines` to one sequence.
Comment: @PrasadTelkikar you just made it even worse:) For example, if your `journal` is fetching data from DB you firstly get **ALL** data from DB and then filter it on client side. So if `journal` has 10M records in DB - you transfer all this 10M records over your network, store this 10M of objects in memory and only then apply filter. Things will getting even more worse if there is a relations in `journal` objects
Comment: @PrasadTelkikar and you still do not take into account the enumerated nature of `IEnumerable`. What if `journal.val` returning different values each time you read it?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196029/discussion-between-prasad-telkikar-and-vasily-sib).


Strange Foreign Key constraint in fluent mapped SQLite

Question: I have a model written using FluentNhibernate and I am trying to create some test data in an in-memory SQLite database.
var fConfig =
                Fluently.Configure()
                        .Database(config)
                        .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetAssembly(exampleClass))
                        .Conventions.Add(AutoImport.Never())
                        .Conventions.Add(new SQLiteGeometryTypeConvention())
                         .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never()))
                        .ExposeConfiguration(cfg => configuration = cfg);

The problem I am getting is that one of the tables is created like this in the generated sql something like this :
 create table myTable (
       myID  integer primary key autoincrement,
       ...{skip normal columns}
       ForeignTable1ID INT,
       ParentID BIGINT,
       constraint FK1A2E045AFEC6908F foreign key (ForeignTable1ID) references ForeignTable1,
       constraint FK1A2E045ABB4EBD1F foreign key (ParentID) references Parent,
       constraint FKE21911CF6853D06E foreign key (myID) references Parent
)

I don't want that third constraint but don't know what's causing it!
The effect being that I can only create records in myTable which have valid foreign keys BUT ALSO have a myID value which exists in the Parent table. This is unnecessary, and I can't see what's causing it.
The mapping file looks like this:
Table("dbo.PalslagInventering");
            Id(x => x.myId).Column("myID");
            References(x => x.ForeignTable1).Column("ForeignTable1ID");
            References(x => x.Parent).Column("ParentID");

            Map(x => x.{other columns here});

HasMany(x => x.Child).KeyColumn("myID");
            HasOne(x => x.Child2).ForeignKey("MyID");

            HasMany(x => x.Child2).KeyColumn("MyID").ForeignKeyConstraintName("Child2");
            HasMany(x => x.Child3).KeyColumn("MyID").ForeignKeyConstraintName("Child3");

The parent table (being referenced) has a simple
public virtual IList<MyTable> myTableRecords { get; private set; }

Type of code mapped as:
HasMany(x => x.myTableRecords)
                .KeyColumn("myID")
                .Inverse();

What is causing the "foreign key" reference back to it's own myId?
Answer: The error seems to be:
HasMany(x => x.myTableRecords)
                .KeyColumn("myID")
                .Inverse();

Where it's the Child table (i.e. "MyTable") which has the ID "myID" and the KeyColumn should point to the Parent table (i.e. the foreign key in "MyTable").
So:
HasMany(x => x.myTableRecords)
                .KeyColumn("ParentID")
                .Inverse();

Seems to have fixed the problem. That the error was in the parent class's mapping file meant I missed it at first.


Desabilitar Função .click em DIV

Question: Eu estou fazendo um jogo e preciso de uma rotina que desabilite o clique pelo menos até terminar a função.
A função é esta abaixo. Quando eu clicar no elemento e executar essa função com touchstart e click quero que dentro da div onde está esse elemento não permita a função do click até que termine essa função.
Como posso fazer ?
$('#boxes > .box').on("touchstart", function(){
        var cor = $(this.data('cor');
        media.play("cor-"+cor);
    }).mouseenter(function(){
        clearTimeout(time);
        var cor = $(this).data('cor');
        if(!$(this).is('.bigsize')){
            time = setTimeout(function(){
                media.play("cor-"+cor);
            }, 200);
        }
    }).on("touchstart click", function(e){
        if(!$(this).hasClass("move")){
            e.preventDefault();
            e.stopPropagation();
            $("div#escolha-e-clique").addClass("out");
            var elm = $(this);
            elm.addClass("move");
            $("div#boxes > .box, div#boxes > .box-lock").not($(this)).addClass('toenter');
            setTimeout(function(){
                media.play("scroll-01-ascend");
                setTimeout(function(){
                    elm.addClass('bigsize');
                    setTimeout(function(){
                        setTimeout(function(){
                            media.play("chime-01");
                            setTimeout(function(){
                                $("div#gift").addClass('anime');
                                var randomGift = Math.floor((Math.random() * totalGifts) + 1);
                                var gift = $('div#gift > .gifts > div:nth-child('+randomGift+')');
                                gift.addClass('active');
                                setTimeout(function(){
                                    gift.addClass('rotate');
                                    //Frase do objeto
                                    var audio = gift.data('audio');
                                    setTimeout(function(){
                                        media.play(audio);
                                    }, 1400);
                                }, 2000);

                                media.play("tada");
                            }, 500);
                        }, 250);
                    }, 500);
                }, 500);
            }, 500);
        }
    });

Consegui desabilitar um elemento que eu precisava.
Fiz assim. Mas depois que termina a função não consigo habilitar esse elemento de novo para clicar.
Esse elemento roda outra função, mais abaixo.
$("div#back-exit > .back").off('click');
$("div#back-exit > .back").on('click', function(e){
    media.stop("chime-01");
    media.stop("tada");
});

Answer: Você pode desabilitar eventos de mouse sobre os elementos alterando o atributo pointer-events do estilo CSS do elemento.
Em seu caso específico, no início de seu método você deve executar o código abaixo para desabilitar os clicks na div:
// Desabilita todos os eventos de mouse/click na div.
$("div#back-exit > .back").css("pointer-events", "none");

Ao final de seu método, para reativar os eventos de click na div, você executa o código a seguir:
// Habilita novamente os eventos de click/mouse na div.
$("#button_id").css("pointer-events", "auto");

Resposta adaptada de https://stackoverflow.com/a/25095924/1639385
Comment: Mas essa propriedade funciona bem em todos os browsers ?
Comment: Se o browser for muito antigo ou se for IE antes da versão 11 é necessário fazer ajustes. No seu caso específico, quais browsers e versões você quer que seu jogo suporte?
Answer: Eu costumo usar outra abordagem para este problema. Em vêz de juntar ambos os eventos ao event listener do jQuery uso
var clickDeviceEvent = 'ontouchstart' in window ? 'touchstart' : 'mousedown';

e depois:
$('#boxes > .box').on(clickDeviceEvent, function(){

Se não fôr o caso de ser útil refazeres o código com essa lógica sugiro usares uma flag. Sabendo que o touchstart dispara primeiro que o click basta colocares algo como
var clickAtivo = true;
$('#boxes > .box').on("touchstart", function(){
    clickAtivo = false;
    var cor = $(this.data('cor');
    // resto do código

e na outra função:
}).on("touchstart click", function(e){
    if (!clickAtivo) return;
    // etc...

e depois quando a função chegar ao fim (parece-me ser na linha media.play(audio);) podes colocar uma linha nova
clickAtivo = true;

que vai deixar de bloquear o click.
Answer: Você pode usas o evento setAttribute dessa forma:

function desabilitarFunção(id){
  document.getElementById(id).setAttribute('onclick', 'desabilitado()');
}

function habilitarFunção(id){
  document.getElementById(id).setAttribute('onclick', 'habilitado()');
}

function desabilitado(){
  alert("Est\u00e1 fun\u00e7\u00e3o est\u00e1 desabilitada!!");
}

function habilitado(){
  alert("fun\u00e7\u00e3o est\u00e1 habilitada!!");
  //sua função habilitada
}
.botao{
  width: 90px;
  height: 26px;

  border: 3px rgb(89,89,89) double;

  background: rgb(239, 155, 155);

  color: rgb(25,25,25);
  font-size: 20px;
  font-weight: inherit;
  font-family: inherit;
  font-style: inherit;
  text-decoration: inherit;
  text-align: center;

  line-height: 1.3em;
  -webkit-border-radius: 20px;
  -moz-border-radius: 20px;
  border-radius: 20px;

}

click-me

<input type="button" onclick="desabilitarFunção('div1')" value="Desabilitar Função da DIV">
<input type="button" onclick="habilitarFunção('div1')" value="Habilitar Função da DIV">

Se você simplesmente quiser que não execute nada é só setar o atributo como: document.getElementById(id).setAttribute('onclick', '');

Com JQuery:

function desabilitarFunção(id){
  $("#"+id).removeAttr('onclick', 'habilitado()');
  $("#"+id).attr('onclick', 'desabilitado()');
}

function habilitarFunção(id){
  $("#"+id).removeAttr('onclick', 'desabilitado()');
  $("#"+id).attr('onclick', 'habilitado()');
}

function desabilitado(){
  alert("Est\u00e1 fun\u00e7\u00e3o est\u00e1 desabilitada!!");
}

function habilitado(){
  alert("fun\u00e7\u00e3o est\u00e1 habilitada!!");
  //sua função habilitada
}
.botao{
      width: 90px;
      height: 26px;

      border: 3px rgb(89,89,89) double;

      background: rgb(239, 155, 155);

      color: rgb(25,25,25);
      font-size: 20px;
      font-weight: inherit;
      font-family: inherit;
      font-style: inherit;
      text-decoration: inherit;
      text-align: center;

      line-height: 1.3em;
      -webkit-border-radius: 20px;
      -moz-border-radius: 20px;
      border-radius: 20px;

    }

click-me

<input type="button" onclick="desabilitarFunção('div1')" value="Desabilitar Função da DIV">
<input type="button" onclick="habilitarFunção('div1')" value="Habilitar Função da DIV">
Comment: Estou utilizando jQuery.
Comment: Funciona do mesmo jeito que `JQuery`, mas eu recomendo a utilização do `JavaScript` puro
Comment: Por que você recomenda ?
Comment: http://i.stack.imgur.com/ssRUr.gif http://youmightnotneedjquery.com/
Comment: Por que VOCÊ recomenda ?
Comment: Muitas vezes nos empolgamos por facilidades que um plugin ou uma plataforma representa para nós programadores, então adotamo-as como fonte de uso para absolutamente TUDO, isso ocorre muito com o JQuery, pelo menos eu vejo isso, tanto no ambiente de trabalho quanto a nível de conhecimento... Veja bem, NÃO DESAPROVO, mas acho que pra algumas funções básicas, como setar atributo, remover atributo, e outras coisas que com JS puro podemos fazer facilmente... NESSE PONTO eu adoto uma abordagem mais cética quanto aos benefícios do uso dessa ou de outras bibliotecas.
Comment: Utilizar essa ferramenta poderosa somente por 1 ou 2 recursos que podem ser feitos com JS puro, seria algo como possuir uma Ferrari, mas só usar o câmbio da mesma.

Desabilitar Função .click em DIV


Does the Elo system work with different expected value functions?

Question: In many Elo rating systems, the expected value for player A with rating $R_A$ against an opponent with rating $R_B$ is
$$E_A = \frac1{1+10^{(R_B - R_A)/c}}$$
The original Elo system is based on a normal distribution instead of a logistic distribution, so it used the error function instead of the logistic function in the equation for $E_A$.
Would the Elo system still work if we chose a simpler function like this?
$$E_A = \frac{R_A}{R_A + R_B} = \frac1{1 + \frac{R_B}{R_A}}$$
For example, if c=400, and 1000 rating players in the logistic Elo system still have a 1000 rating in this system, then 1400 rating players in the logistic Elo system would have a rating of 10000 in this system.
If this still works, then why would they have switched to the logistic function? Is it that they wanted player ratings to follow a normal distribution, and ratings in this simpler version would follow a log-normal distribution?
Answer: Let me answer your second question, why they switched to the logistic function.
The Elo rating system comes from the Chess world. The initial Elo's premise was a normal distribution, but since more chess statistics became available, FIDE (The World Chess Federation) realized that it was better to consider the logistic function.
Have a look here for a description of Elo's rating system.
Regarding your first question, if your formula will work, well, c is the logistic parameter used to fine-tune your rating system. The value c = 400 is for the chess world. But in reality, you can pick any which fits your rating requirements. The same happens with the Distribution you pick. First, maybe you will have to draw your players' initial ratings and see which distribution they follow.
Comment: My intent is to ask why they had to change the assumption for the underlying distribution from a normal distribution to a logistic distribution. If my formula would still work, then shouldn't the underlying distribution be irrelevant to the Elo ranking system? If my formula does not work, then the explanation of why it doesn't work would explain the importance of updating the assumption from normal distribution to logistic distribution.
Answer: This subject is discussed in Prof. Mark E. Glickman, A Comprehensive Guide To Chess Ratings.

It appears as though there is very little distinction between the
shape of the logistic distribution in Figure 2 and the normal
distribution in Figure 4. Figure 5 shows both curves superimposed,
with the logistic distribution drawn as a solid line. In fact,
statistics professor Hal Stern in a 1992 article[11] has shown that
when analyzing paired comparison data it makes virtually no difference
whether one assumes the logistic distribution or the normal
distribution for differences in players' strengths. So, empirically,
the choice between the Bradley-Terry model and the Thurstone-Mosteller
model is a moot issue. Mathematically, however, the Bradley-Terry
model tends to be more tractable to work with. This is the most likely
reason that most organizations administering a probabilistic rating
system (e.g., FIDE, USCF) use the Bradley-Terry model, which uses the
logistic distribution assumption, rather than the Thurstone-Mosteller
model, which uses the normal distribution assumption.

It is easy to see from the "FIDE Rating Regulations 2022" that the original Elo tables are still in use by FIDE.
The following distributions are discussed by Elo in The Rating of Chess Players.

8.4 Logistic Probability As a Rating Basis
8.5 Rectangular Distribution as a Ratings Basis
8.8 Binomial Distribution and Small Examples
9.1 The Maxwell-Bolzmann Distribution and Chess Ratings

Since the Elo system is self-correcting using the K-factor formula, any reasonable form of the probability distribution function can be used as a starting point for a rating system (ch. 8.75).
Answer:
The original Elo system is based on a normal distribution instead of a logistic distribution
...
If this still works, then why would they have switched to the logistic function?

There hasn't been a switch. The FIDE uses Elo's original system for which a table is computed.  See the Fide handbook.
The win-probability (or score,since it includes draws), is computed as
$$p(\text{A win from B})= \Phi\left( \frac{\text{Elo}_A - \text{Elo}_B}{200 \cdot \sqrt{2}} \right)$$
For example, a $100$ Elo difference will relate to a $0.6381632$ win probability for the higher valued player. Or $0.64$ as it is in the tables of the FIDE.
The use of the logistic function/distribution is a useful trick to make an estimate of the values in the table. Also, several other competitions may be using the logistic function. There is not really a large difference between the two and it is just a practical trick to make computations easy.

Would the Elo system still work if we chose a simpler function like this?
$$E_A = \frac{R_A}{R_A + R_B} = \frac1{1 + \frac{R_B}{R_A}}$$

The system is arbitrary, so yes this would work as well. However, the computations with a linear Elo scale might be easier.

For instance, one could compute an average Elo rating for a pool of chess players and approximated the win probability of a player based on the difference with the average Elo.
Another example is that differences in Elo rating are more easier to
evaluate. If some top player has rating 13102 and another has a
rating 4996, than it is a bit awkward to compute the difference in
the level between the players because this involves a division
instead of a subtraction.
Also, the updating works as a zero sum game. Whenever a player increases by some value $x$, then another player decreases by a value $x$. If you would do this for an exponentially increasing score, then the people at the top will be changing their scores only very slowly (in some sense the system does have a way to reduce the speed of changes in scores for high level players, but it does not reduce the speed that much as what would be the case with an exponentially increasing score)
Comment: The table in Elo's original system  uses 2000 / 7 as an approximation of 200.sqrt(2).


How to access static ip windows virtual machine

Question: While logged into my Windows Server 2016 virtual machine I changed the settings of the Ethernet IP to a static address. Now I am unable to connect to this machine. Any ideas how to reconnect/ reset the IP without being logged into the machine (maybe through the azure portal)?
Answer: you can use the reset network configuration button on the portal.

Go to the Azure portal.
Select the affected Virtual Machine.
Select Network Interfaces.
Select the Network Interface associated with your machine
Select IP configurations.
Select the IP.
If the Private IP assignment is not Static, change it to Static.
Change the IP address to another IP address that is available in the Subnet.
The virtual machine will restart to initialize the new NIC to the system.
Try to RDP to your machine. If successful, you can change the Private IP address back to the original if you would like. Otherwise, you can keep it.

reference: https://learn.microsoft.com/en-us/azure/virtual-machines/windows/reset-network-interface


How to fetch form state value of a form on clicking custom button?

Question: How to fetch form state value of a form on clicking custom mobile verification(required field in register form) button ajax based suppose I want to show mobile number(Form_state value) of form on clicking ajax based button named mobile verification. Here's the code:
 if($form_id == 'user_register_form')
 {

        $form['mybutton'] = array(
        '#type' => 'button',
        '#name' => 'mybutton',
        '#value' => 'Mobile Verification',
        '#title' => t('Mobile Verification'),
        //'#submit' => array('my_ajax_callback'),
        '#prefix' => '
X
<form action="#">
                        Enter OTP

                        <input type="text" class="otp" name="otp" value="">

                        <input type="submit" class="otp_submit" value="Submit">
                        </form>

',
        '#weight' => 19,
        '#ajax' => array(
                'event' => 'click',
                'callback' => 'my_ajax_callback',
                'method' => 'replace',
                'wrapper' => 'form-wrapper',
          ),
        );

}

function my_ajax_callback(&$form, &$form_state,$form_id) {

     echo '
';
     print_r($form_state);
     die;
   // return $form;
 }

In short i just want without saving form data can we show form_state value on clicking ajax based button in popup form.
The above code not working for me not able to get form_state value
Comment: The question isn't clear, as you already are using $form_state, and it doesn't need to be fetched.
Comment: In short i just want without saving form data can we show form_state value on clicking ajax based button in popup form
Answer: In that case, you can create a container in the form, and fill it with the values after AJAX has been fired. Then you only need to return that container in your ajax callback.
if($form_id == 'user_register_form')
{
  $form['mybutton'] = array(
    // ...
    '#ajax' => array(
      'callback' => 'my_ajax_callback',
      'wrapper' => 'form_state_values_wrapper',
    ),
  );

  $form['form_state_values'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
    '#markup' => '',
  );

  if(isset($form_state_, $form_state['values']))
  {
    $form['form_state_values']['#markup'] = '
' . print_r($form_state['values'], TRUE) . '
',
  }

}

function my_ajax_callback(&$form, &$form_state,$form_id) {
  return $form['form_state_values'];
}

Comment: i think something is missing in your code i am getting blank page after submitting button
Comment: Update your code with your full code.


record guitar chords with a pedal

Question: I sometimes see on youtube that guitarists play some chords and record them by using a pedal.
So, what is the device used to record chords as home backing tracks for my own solo playing?
Comment: It's a loop station and it's not cheap.
Answer: You're looking for a "looper". Those are hardware looper pedals and they start at around $100. If you already have some other means of triggering a MIDI note with your foot, you can also use a software looper of some kind.
Note that you may hear "looper" used in another context referring to a different kind of pedal. Pedal board "loop switchers" serve as routing controllers for large pedal boards so you can hook up a bunch of pedals and quickly switch between different routes without changing any cables. Those are also sometimes called "loopers". So just be aware that you're looking for the other kind.

record guitar chords with a pedal


Pandas data frame merge select columns

Question: I want to get data from only df2 (all columns) by comparing 'no' filed in both df1 and df2.
My 3 line code is below, for this i'm getting all columns from df1 and df2 not able to trim fields from df1. How to achieve ?
I've 2 pandas dataframes like below :
df1:
no,name,salary
1,abc,100
2,def,105
3,abc,110
4,def,115
5,abc,120

df2:
no,name,salary,dept,addr
1,abc,100,IT1,ADDR1
2,abc,101,IT2,ADDR2
3,abc,102,IT3,ADDR3
4,abc,103,IT4,ADDR4
5,abc,104,IT5,ADDR5
6,abc,105,IT6,ADDR6
7,abc,106,IT7,ADDR7
8,abc,107,IT8,ADDR8

df1 = pd.read_csv("D:\\data\\data1.csv")
df2 = pd.read_csv("D:\\data\\data2.csv")
resDF = pd.merge(df1, df2, on='no' , how='inner')

Comment: Will this be of any help? https://stackoverflow.com/questions/41815079/pandas-merge-join-two-data-frames-on-multiple-columns
Answer: I think you need filter only no column, then on and how parameters are not necessary:
resDF = pd.merge(df1[['no']], df2)

Or use boolean indexing with filtering by isin:
resDF = df2[df2['no'].isin(df1['no'])]

Comment: Thank you so much. It helped me a lot.  :-)

Pandas data frame merge select columns


How to organize categories and subcategories of products in menus?

Question: I have product content type that I want to display in a menu. Every product belongs to subcategory that belongs to main category, for example:
<code>Computers:
   PC:
      - product 1
      - product 2
      - product 3
   Laptop:
      - product 1
      - product 2
      - product 3
   Tablets:
      - product 1
      - product 2
      - product 3

Phones:
   Android:
      - product 1
      - product 2
      - product 3
   iOS:
      - product 1
      - product 2
      - product 3
</code>
When clicking on products item in main menu, I need to display a horizontal menu with main categories (Computers, Phones) and a vertical menu with subcategories (PC, Laptop, Tablets). Computers > PC should be the default selection. Whenever any category/subcategory is selected it should display a list of links to the product page.
What are the most common modules use to do something like this? Are there any tutorials or basic steps I can take to accomplish this goal?
Answer: while you want to display category, sub category and node at the same time, so you have to use views.
you can use group by in the views and groups the results depending on category and subcategory.
but you also mention that you don't want to show product unless you click on the subcategory, to get this there is many ways, the simplest one is create view that shows the category and subcategory, when you click on it it will drive you automatically to the taxonomy page.
if you don't want to use views you can use taxonomy modules in Drupal there are a lot of them.


AVERAGEIF Excel function into Google Spreadsheet

Question: Alright, I was able to get it to get this formula working within excel:
=AVERAGEIFS($B$8:$B$88,$B$3:$B$83,"Coupons",$B$4:$B$84,"Holiday")
The formula averages the Open Rates for specific data-sets depending on their Type and Sub Type.
If B3 equals Coupons and B4 equals Holiday then paste the Average of the Open Rates for all the campaigns that contain the first two attributes into another spreadsheet.
As we all know, Google Spreadsheet does not recognize AVERAGEIF. I have been attempting to make a hybrid with the Formula Array function coupled with either FILTER or AVERAGE to no avail. Any help would be much appreciated. Thanks.
Image of spreadsheet
Answer: Try this version
<code>=arrayformula(AVERAGE(IF($B$3:$B$83="Coupons",IF($B$4:$B$84="Holiday",$B$8:$B$88))))</code>
Comment: Thanks for taking a stab at this but the above version gives me a "DIV/0!" error: No valid data. Appreciate the help regardless.
Comment: I think this getting close, but I feel the formula needs to have a third IF= function in order to paste the 'Open Rate' data.
Comment: I certainly have the formula working in a sample doc - DIV/0! would indicate that there are no values to average - either the criteria aren't met or there are no numbers
Comment: I simply used the ranges you specified in the question - the setup is a little odd, perhaps you can confirm how it works - if B3="Coupons" and B4="Holiday" B8 will be added to the average and the same applies shifted by one row at a time, e.g. if B13="coupons" and B14="holiday" B18 will be added to the average - is that how you understand it?
Answer: The new version of Google Docs has an averageif function


Preparing data for survival analysis

Question: Goal: build a survival analysis to understand user behavior in an online site.
I have a data set of an online site where user appear from the first time and the last time. I am trying to build a survival analysis. Using this information.
userId, firstEntry, lastEntry
001,11/6/2012,11/6/2012
002,9/9/2005,9/9/2005
003,11/13/2013,8/1/2014
004,2/2/2006,2/2/2006
005,9/17/2005,9/17/2005
006,9/1/2005,1/26/2010
007,9/21/2005,9/26/2011
008,3/30/2011,3/30/2011
009,9/5/2005,9/5/2005
010,1/14/2010,1/14/2010

How do I create the event column (censor) to really do a survival analysis. Should I apply the logic of "how many days it took to come back" and use that to create event column along with a column representing the gap.
If the firstEntry and the lastEntry are the same, that means thats the only time user enter the site.
My goal was to fallow something similar to this.
https://docs.google.com/file/d/0BwogTI8d6EEibDVxakozYVdZc0k/edit
I haven't decided yet to do this in R or Python. I am open for language agnostic answer or language specific answer.
Comment: Could you please clarify the meaning of your "lastEntry" column? If the date there is the same as the date of the "firstEntry" column, does that mean that the person came back on the same day, or that the firstEntry was the only (and thus also the last) Entry? That makes a big difference for trying to use survival analysis as in your linked example. Also, how many "Entry" times might there be overall for an individual user?
Comment: Just edited: Yes thats the only time user entered the site. And there can be as many entry times in a given month but mostly based on the data i see user only entering once a month but recurrence is the once that I think i am trying to measure via survival
Comment: You are coming at this the wrong way: you should be coming up with a hypothesis and then using survival analysis to make testable. Try to express in English how your users behave (in the question) . In loan application the death event is never paying back the loan, but since you can never know for certain you create a technical 'death'  not paying for 3 consecutive months. Maybe you could do something similar_ define death if haven't seen the customer for n months. (but your dataset would need to be redone)
Answer: You need an event for survival analysis to predict survival probabilities over a given period of time for that event (i.e time to death in the original survival analysis).  In your case, perhaps, you  are looking for a churn analysis. So chern of your customers  is equal to their death. To do a simple analysis that serves your purpose,  all you need is a table of customers with a binary value indicating whether they have churned and a time associated with that. This time measure the time passed from their FirstEntry. So, you need the following data:
Customer ID    time     churn
       1        100       0
       2        72        1
       3        590       0
       ...

I made up this data, just as an example. You have to define a dummy variable as the churn column, depending on the problem. Perhaps, you want to label them as either churned or not based on frequency or recency of visit or transactional behaviour.
Comment: Could you please explain the churn column and how i should read the record as. For example user 1 left the system after 100 days, user 2 has been in the system for 72 days and hasn't left the system yet?
Comment: No time is the $current time - Entrytime$. The definition of churn event depends on your problem but you have to defined an event. For instance you can say if a customer has not visited the site for the last 10 days he is dead in my survival analysis.
Answer: "Censored" individuals in survival analysis are those for whom the "event" hasn't yet happened. So if an individual has the same firstEntry and lastEntry times and that can only happen if the person only visited the site one time, then those are the individuals that should be considered "censored." Anyone who came back would have an "event" at the time of the lastEntry.
This might not, however, be a good application for survival analysis, at least in its simplest form. What if an individual can enter the site more than twice?
If an individual can come back multiple times then it seems that you would want to know about all the intervening visits to the site. The meaning of, say, 6 years between firstEntry and lastEntry would be different for someone who only visited those 2 times and someone who visited daily for 6 years; it's not clear how your data distinguish those possibilities. The first case is a highly infrequent visitor, while the second is very frequent. If you have information about multiple visits from the same individuals, then you should consider some analysis of recurrent events.
Even if individuals only can enter twice, how sure are you that there wasn't a second entry on the same day as the first? Again, someone who returned that quickly ought to be distinguished from someone who never returned at all.
Comment: @Null-Hypothesis it's not clear that survival analysis will address your central question of how long a user survives in the system. For survival analysis to work the "event" would have to be the time that the user leaves the system, never to come back. The `lastEntry` values do not necessarily represent those times, as a user might come back tomorrow. Also, someone who just visited once and never came back would be "censored" (no event) and assumed to still be in the system. That doesn't seem to be what you intend. Survival analysis could work for determining how _quickly_ users return.
Comment: Yes Some users have entered multiple times such as once a month for 3 years. I was hoping that Survival analysis gives me an understanding of how long user survive in the system. Like the user who came monthly for three years. Am i thinking wrong here?

Preparing data for survival analysis


How vowels are expressed in musical notation, the case of B5 in Lilypond

Question: I understand that 1000Hz is B5 plus 21 cents.
What is this note and how can it be represented in Lilypond notation?
Comment: I think the fundamental (if you'll pardon the pun) misunderstanding is: "What is this note": When we talk about "a note" we're talking about the fundamental. An oboe, a flute, and a saxophone can all play a C, and they sound different. The differences are in the overtones. Blends of overtones are not normally represented in music staff notation; it's really only customized for representing fundamental pitches.
Comment: I don't understand your question, where did you get this figure of 1000Hz from?
Comment: From Wikipedia for vowels in Spanish: https://es.wikipedia.org/wiki/Formante
Comment: If this is for human performance, an easier strategy might be simply to print the desired vowel under the note, with a textual introduction explaining to the performer what you want (and explaining Spanish pronunciation if they're unclear on it), and then leave it to them how to represent the difference. As a violinist, for *e* I'd play closer to the bridge, for *a* farther away, and for *u* maybe play at a higher point on a lower string. Some wind instruments can even "sing" through the instrument...
Comment: @DoktorMayhem I disagree. The question concerns vowels, an important topic in music, and frequency, another important topic. On top of that, it concerns staff notation and notation software: OP says, repeatedly, "the question focus on how to represent note B5 (which seems to map with frequency 1kHz) in Lilypond notation."  Suppose the question had been "trying to translate the metric system into a musical composition, I see that the factor 1 kHz would be B5 plus 13 cents...."  Should that be off topic?  Why do you think this question is unconnected to music?
Comment: It looks like you have a question about representing B5 plus 21 cents in Lilypond, and then some questions about formants that are not connected with music. Can you clean up your question to focus on the on topic bits for this site
Comment: @DoktorMayhem formants are very much connected with music. Knowing about them is useful for singers and critical for those who would program synthesizers to sound like singers.  The question may be a bit off base, but that should not doom it to closure.  I've voted to reopen.
Comment: @phoog - formants can be very connected with music, but not the question the OP has asked about them.
Comment: @phoog - as the OP didn't come back to edit, I have updated the post myself to focus on the key question. The formant bit is the red herring that isn't connected to the musical question.
Comment: To OP's defense, you can try to emulate speech using musical notes, see e.g. https://www.youtube.com/watch?v=-6e2c0v4sBM But it doesn't work very well. It has some similarity with vocoders, but also some differences.
Answer:
Trying to emulate Spanish vowels sound with musical notes,

Not going to happen, at least not if I understand what you mean by this.  I believe your thought process is as follows:

At https://es.wikipedia.org/wiki/Formante there is a chart showing formants F1 and F2 of the vowel /a/ at 700 Hz and 1000 Hz and of /e/ at 660 Hz and 1290 Hz, so if I play two musical notes with the first two frequencies, it should sound like /a/, but with the second pair of frequencies, the two notes will sound like /e/.

There are a number of problems with this line of reasoning.  First, the formant isn't a precise frequency but (from English Wikipedia) a "broad spectral maximum."  It is broad.  This is reflected in the spectrographs as a dark band.  If the formant were a distinct pitch, it would be seen as a narrow line.  If that were the case then normal speech and singing would sound like this:

Instead, this is a rare specialist skill.
The spectrum difference that distinguishes /a/ from /e/ is similar to the spectrum difference that distinguishes an oboe from a flute, a clarinet, a violin, and so on.  This sound spectrum describes the relative strength of the harmonic overtones of the sound, which determine the timbre, and, in human speech, the timbre varies, giving us distinct vowels.  The formants are broad frequency ranges within which the overtones are amplified.  They are not precise pitches.  Two instruments playing together, or two singers singing together, don't sound like a single vowel regardless of what pitches they're playing or singing.
With these thoughts in mind, now, on to your actual question:

What is [B5 plus 21 cents] and how can it be represented in Lilypond notation?

B5 plus 21 cents is most likely just B5.  Traditional staff notation is not particularly precise about frequency.  Music can be played in a variety of tuning systems, and in many of these systems notes with the same note name can easily vary by more than 20 cents even within one piece.  Even in the context of strict equal temperament, however, there are many orchestras that do not tune A to 440 Hz.  In equal temperament based on A=444 Hz, B5 is 996.75 Hz, only 5.64 cents lower than 1000 Hz.
Traditional staff notation is not very efficient at encoding and communicating such precision of tuning, but that hasn't stopped modern composers from developing extensions to do so.  You might be tempted to turn to these, but even then no musician is going to be able to play a 1000 Hz tone accurately simply because there is something on the page informing them that the note is supposed to be 1000 Hz.  This is a task for computers or electronic instruments.
If I were writing a score for a computer or electronic piece, I would probably just use the text "1000 Hz" above or below the note.
But remember that formants are not as precise as they seem because the frequency given for a formant is the center of a broad spectral range.  It's not a magic number.  If someone sings an /a/ with formants centered at 698 Hz and 988 Hz, it will still be an /a/, just maybe an /a/ of a slightly different color (though these frequency differences are probably too small to be perceptible).  As the formants change in frequency, the vowel color changes.  As you reduce both frequencies, the vowel gets closer to /o/, whereas reducing F1 and raising F2 makes the vowel closer to /i/.  (If you move the formants dynamically during the course of phonation, you get a diphthong such as /ao/ or /ai/.)
If I were, say, writing a piece using vowel formant frequencies as an organizational principle, I'd start off by just using B5 for 1000 Hz.
Comment: [The talking piano](https://www.youtube.com/watch?v=muCPjK4nGY4)
Answer: Vowels are identified not by single characteristic formants, but they comprise two at least, F1 and F2. On Wikipedia you find following:
Formant graph (why isn't that picture found, I only copy the link?; will see later) or Formant plots.
So, you will need a cluster of notes, i.e. let us rather say frequencies, since notes are associated to a scale, but vowel formants cannot be mapped to one.
Plus, hearing only the formants it is not easy to recognize vowels. That would be simpler if you also render the anti-formant sinks in between, of course damped by -30dB or so. These anti-formats lets you distinguish the same vowels from different voices.
General, design of vowel and other speech sounds is a sound design affair, it has not to do with music much.
Comment: I'm afraid a single frequency is as far off an approximation to a vowel as a hit tuning fork is far off an approximation to a burst of music.
Comment: Of course, it's just an approximation to how a vowel would sound. But the question focus on how to represent note B5 (which seems to map with frequency 1kHz) in Lilypond notation. I'm reserving the formants issue for a different question.
Answer: If you're using absolute mode, it's { b'' }, like Paco Vila said. See this Documentation.
If you want to be really specific, you could probably do something like { b''qs } and raise it to a B5 semi-sharp. That might be useful depending on what you're looking to do.
...what are you looking to do though? Like what's your end goal?
I'm curious
Answer: B5 in LilyPond is
  { b'' }

and its frequency is 987.8 Hz under the ISO 16 standard assuming the use of 12-TET tuning. I other words, for an A4=440 Hz and the most commonly named equal temperament.
Comment: Does the ISO standard specify equal temperament?  Or any tuning system at all?  If not, B5 could be anywhere from 977.8 Hz to 990.0 Hz (or perhaps even farther afield depending on which pitch is used as the basis for the tuning and on how that pitch is derived from 440 Hz).
Comment: Thanks.  I've upvoted this answer because, well, it is the only answer actually to address "how can it be represented in Lilypond?"  I posted the comment in part to counteract the idea that A=440 Hz and 12-tone ET are somehow "right" (which of course they may be in certain contexts, but certainly not in all), but mainly to reinforce the notion that the designation of formant frequencies is really very much less precise than the designation of pitches in a scale.
Comment: @phoog you are right.
I only cited the ISO standard for the sake of A4=440 Hz. A big whole tone 9/8 worth puts B5 in 990 Hz.


Gaussian Mixture Model $p(x_i | z_i = k)$ a likelihood or probability?

Question: In Gaussian Mixture models, the probability of observing the data $x$ given that it was generated from $M$ gaussian models is given by the following equation $$p(x) = \sum_{k=1}^m p(x|z=k)p(z = k)$$
People usually refer $p(x|z=k)$ as the probability that gaussian $k$ generated the data $x$ and replaces it with the gaussian density function $N(\mu_k,\Sigma_k)$. However, $N(\mu_k,\sigma_k)$ is the pdf of the gaussian which represents the likelihood of observing $x$ rather than a probability since for continuous distributions the probability for a single data point is 0 although the likelihood is proportional to the probability. Is it considered a probability or a likelihood ?
Answer: For a Gaussian mixture, the functions $p(x)$ and $p(x|Z=k)$ are probability densities, not probability mass functions. In case the mixture model has parameters $\theta$ like $\mu_k$ and $\sigma_k$, the likelihood function is the product of the $ p_\theta(x_i)$'s
$$\ell(\theta) =\prod_{i=1}^n p_\theta(x_i)\tag{1}$$
seen as a function of $\theta$ for a given sample $(x_1,\ldots,x_n)$, where, e.g.,
$$p_\theta(x_i) = \sum_{k=1}^m \mathbb P(Z_i = k) p(x_i | \mu_k,\sigma_k)$$
Formally, the case $n=1$ makes $p_\theta(x_1)$ a likelihood as well, although estimating $\theta$ from a single observation is of little interest.
Comment: the y-axis of the probability densities is essentially the likelihood of observing x ? is $p_{\theta}(x_i)  = \sum_{k=1}^m p(z_i = k) p(x_i | \mu_k,\sigma_k)$
Comment: How would we interpret $p(x)$ in terms of a probability density function ? Since $x$ is a given data point and not a random variable
Comment: I am not certain we are discussing the same objects. For me, likelihood means the likelihood function $\ell(\theta)$, introduced by R.A. Fisher, that is used in estimation by maximum likelihood. It is defined as (1) in my answer. It is equal to the density (1) of the sample $(X_1,\ldots,X_n)$ at the realised sample $(x_1,\ldots,x_n)$.


How to use JQM theme and jQueryMobile plugin with Drupal?

Question: I'm developing a mobile web site with Drupal 7 and i want to use jQuery mobile. I've found many plugins, but just one available with drupal 7 (jQuery Mobile module). I have also a jQuery mobile theme (jQM Theme). My problem is that doesn't work (there is just html, no css and jquery mobile displayed).
Is there someone who used this plugin and theme ? Or could you give me an efficient way to create a mobile web site with Drupal 7 ?
Thanks,
Gen
Answer: Please make sure you've read the readme properly. The module requires that certain files be patched and you have the libraries in the correct place.
I have had jQuery Mobile theme working but found that it was far from usable so built my own simplified theme.
Comment: Would love to see your theme in a sandbox :-)


Exactness of $\textrm{Ind}_H^G$

Question: Let $G$ be a group of td type (Hausdorff, and every neighborhood of the identity contains a compact open subgroup).  A smooth representation of $G$ is an abstract representation $(\pi,V)$ such that the stabilizer of any vector is open.
Let $H$ be a closed subgroup of $G$, and $(\sigma,W)$ a representation of $H$.  Define $\textrm{Ind}_H^G(\sigma)$ to be the smooth representation of $G$ consisting of all functions $f: G \rightarrow W$ such that $f(hg) = \sigma(h) f(g)$ for all $h \in H, g \in G$, and such that $f$ is right $K$-invariant for some open compact subgroup $K$ of $G$: $f(gk) = f(g)$.  Here $G$ acts on $\textrm{Ind}_H^G(\sigma)$ by right translation: $g \cdot f(x) = f(xg)$.
To any $H$-linear map of smooth representations $\phi: (W,\sigma) \rightarrow (U, \tau)$, define $$\textrm{Ind}_H^G(\phi): \textrm{Ind}_H^G(\sigma) \rightarrow \textrm{Ind}_H^G(\tau)$$
by $\textrm{Ind}_H^G(\phi)(f)(g) = \phi(f(g))$.  Then $\textrm{Ind}_H^G$ is an additive functor from the category of smooth $H$-representations into that of smooth $G$-representations.
Supposedly $\textrm{Ind}_H^G$ is an exact functor.  Why is this?
Answer: Frobenius reciprocity says that $\textrm{Ind}_H^G$ is a right adjoint to the restriction functor $\textrm{Res}_H^G$.  That is, for smooth representations $\pi$ of $G$ and $\sigma$ of $H$, there is a bijection, natural in $\pi$ and $\sigma$:
$$\textrm{Hom}_G(\pi, \textrm{Ind}_H^G(\sigma)) = \textrm{Hom}_H(\textrm{Res}_H^G \pi, \sigma)$$
Taking this for granted, we get that $\textrm{Ind}_H^G$ is left exact as a right adjoint.  The difficult part is then showing that $\textrm{Ind}_H^G$ preserves surjective maps.
The point is this: any smooth representation of a compact group of td type is semisimple, which is to say a direct sum of irreducible representations, or equivalently spanned by irreducible representations.  It can be shown from here that if $(\pi,V)$ is a smooth representation of $G$, and $\rho$ is an irreducible representation of a fixed compact open subgroup $K$ of $G$, then $V$ is the direct sum of $K$-stable spaces $V(\rho)$, where $V(\rho)$ is the $\rho$-isotypic component of $V$: the subspace of $V$ spanned by all $K$-subspaces which are $K$-isomorphic to $\rho$.
Any $G$-map of smooth representations $V \rightarrow V'$ is in fact a direct sum of $K$-maps of $K$-spaces $V(\rho) \rightarrow V'(\rho)$.  In particular, if $v' \in V'$ is a $K$-fixed vector (that is, $v'$ lies in the isotypic space corresponding to the trivial representation) lying in the image of $V$, then $v'$ is mapped to by a $K$-fixed vector of $V$.
So, let $\phi: (W,\sigma) \rightarrow (U,\tau)$ be a surjective map of smooth $H$-representations.  Let $f \in \textrm{Ind}_H^G(\tau)$, and let $K$ be a compact open subgroup of $G$ for which $f$ is right $K$-invariant.
Break $G$ up into orbits under the action of $H \times K$ (by $(h,k) \cdot g = hgk^{-1}$).  Let $I$ be the set of orbits, and choose for each $i \in I$ an orbit representative $g_i$ of $i$.  It is easy to see that $f(g_i) \in U$ is fixed by the compact open subgroup $H \cap g_iKg_i^{-1}$ of $H$.  Since $\phi$ is surjective, and by the "in particular" above, we can choose a vector $w_i \in W$, also fixed by $H \cap g_iKg_i^{-1}$, such that $\phi(w_i) = f(g_i)$.  We then define a function
$$f_0: G \rightarrow W$$
by specifying its values on each of the orbits $Hg_iK$:
$$f_0(hg_ik) = \sigma(h)w_i$$
To show that this is well defined, we need to show that for a fixed orbit $i$, if $h_1g_i k_1 = hg_ik$, then $\sigma(h_1)w_i = \sigma(h)w_i$.  This follows because $\sigma(h^{-1}h_1)$ stabilizes $w_i$, as $h^{-1}h_1 \in H \cap g_iKg_i^{-1}$.
It is immediate that $f_0$ lies in $\textrm{Ind}_H^G(\sigma)$.  Finally, $\textrm{Ind}_H^G(\sigma)(f_0) = f$, since
$$\textrm{Ind}_H^G(\sigma)(f_0)(hg_ik) = \phi(f_0(hg_ik)) = \phi(\sigma(h)w_i) = \tau(h)f(g_i) = f(hg_i) = f(hg_ik)$$

Exactness of $\textrm{Ind}_H^G$


Spring @Resource Expected at least 1 bean which qualifies as autowire candidate for this dependency

Question: I'm trying to run a web app and I'm having some issues. Basically I have a controller and a process and they both share a queue.
The controller manages the files that are uploaded to the server and it puts them in the queue. In the other side, the process takes the files in the queue and uses them for other things.
I've defined the queue as a LinkedBlockingQueue and the annotation @Resource on both of them, but when I run the app, the following exception appears:
Error creating bean with name 'csvQueueConsumerBean': Injection of resource
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [java.util.concurrent.LinkedBlockingQueue] found for
dependency: expected at least 1 bean which qualifies as autowire candidate for this
dependency.

The code of both clases is the following:
@RestController
@RequestMapping("/upload")
public class FileUploadControllerW {

@Resource
protected LinkedBlockingQueue<QueueObject> csvQueue;

...
}

@Component
public class CsvQueueConsumerBean{

@Resource
protected LinkedBlockingQueue<QueueObject> csvQueue;

...
}

Just for the record, both classes are not on the same package.
Comment: `LinkedBlockingQueue` bean does not exist in the Spring context that is why. You will have to initialise it the context!
Comment: where have to defined the queue? can you post that code
Comment: @theo, thanks for the answer. Could you tell me how can I do that? I'm still a noob with al this spring stuff.
Answer: The reason for this is because Spring context cannot wire the Bean called
csvQueueConsumerBean

You will need to initialize its LinkedBlockingQueue dependency in the Spring config file like this:
@Bean
public LinkedBlockingQueue<QueueObject> linkedBlockingQueue(){
    LinkedBlockingQueue<QueueObject> blockingQueue = new LinkedBlockingQueue<QueueObject>();
    // do what you need here...
    return blockingQueue;
}

Comment: Thanks, I'll try that.


Finding 2nd order differential equation

Question: Find 2nd order non homogeneous linear differential equation for which $y_1(x)=x^2$ , $y_2(x)=x^2+e^{2x}$  and $y_3(x)=1+x^2+e^{2x}$ are solution.
Don't know exactly how I should start?
Answer: Hint:  The form of your equation (moving the nonhomogeneous term to the left-hand side) is
$$  c_1(x) y''(x) + c_2(x) y'(x) + c_3(x) y(x) + c_4(x) = 0  $$
Plug your solutions into this.  You will find that $y_2$ and $y_3$ immediately constrain $c_3$.  Then $y_1$ and $y_2$ give a relation between $c_1$ and $c_2$, so rewrite the form using the relation to replace $c_2$s with an expression in $c_1$.  Then $y_1$ gives a relation between $c_1$ and $c_4$.  You now have an equation where the coefficients depend only on $c_1$, so pick your favorite $c_1$.  (I usually pick $c_1(x) = 1$.)
Answer: Let $A,B,C$ be real numbers such that $$Ay+By'+Cy''$$ is the same for your three functions.
From the equation for $y_2$ and $y_3$ you get $A=0$.
From the equation for $y_1$ and $y_2$ you then get $B=-2C$.
A simple solution is therefore $$y''-2y'=2-4x.$$

Finding 2nd order differential equation


.NET: Can you manually specify which types to include in autogenerated WSDL?

Question: Is it possible to make the auto-generated WSDL for a .NET web service include descriptions for certain data types if no web method returns that data type of takes that data type as a parameter?
I could just include a dummy webmethod that never gets called, but I'm looking for a less hacky way.  Thanks!
Mike
Answer: Arguably, they have no place in the wsdl if they aren't used... you can use [XmlInclude] to specify known subtypes, but I don't think that is what you mean. You could of course use a custom WSDL fragment, but I suspect the simplest option is, as you have hinted, to include a dummy method that involves them. To avoid having to add lots of dummy methods you could include the custom types as properties on a DummyEntity object returned from your DummyMethod - but it smells a bit ripe ;-p
What do you want these types for?
Comment: One of my web methods takes a data type called Foo, and it has a "String" property which is an encrypted Base64 serialization of type "Bar". I'd like "Bar" to appear in the proxy class so that developers have access to create one and encode it properly.  "Bar" doesn't appear anywhere else unencoded.  Normally one would use an encrypted transport like HTTPS, but in this case the data has to be encrypted and sit in a DB while it's being processed..  I think you're right though, technically the data has no business being part of the WSDL, I should just give developers a little API library to use.


Erro ao inserir dados com Mysql e laravel

Question: Tenho uma tabela chamada "item" no qual preciso inserir dados, porem por algum motivo não processa o insert. Sou novato no backend por tanto não sei se existe alguma restrição na tabela que impede de inserir o registro.
mysql> desc item;
+-------------------+---------------------------------------------------------------------------+------+-----+---------+----------------+
| Field             | Type                                                                      | Null | Key | Default | Extra          |
+-------------------+---------------------------------------------------------------------------+------+-----+---------+----------------+
| id                | int(10) unsigned                                                          | NO   | PRI | NULL    | auto_increment |
| item_id           | int(10) unsigned                                                          | NO   | MUL | NULL    |                |
| proc_id           | int(10) unsigned                                                          | YES  | MUL | NULL    |                |
| date              | datetime                                                                  | NO   |     | NULL    |                |
| code              | varchar(100)                                                              | YES  |     | NULL    |                |
| status            | enum('Waiting','Canceled')                                            | YES  |     | NULL    |                |
| user              | int(10) unsigned                                                          | YES  | MUL | NULL    |                |
| created_at        | timestamp                                                                 | YES  |     | NULL    |                |
| updated_at        | timestamp                                                                 | YES  |     | NULL    |                |
+-------------------+---------------------------------------------------------------------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)

mysql>

O código que realiza o insert é este, $item_id seria uma string como '222' por tanto passei ela para inteiro:
if ($item_id != '') {

                DB::table('item')->insert([
                    'item_id' => settype($item_id, 'integer'),
                    'proc_id' => null,
                    'date' => Carbon::now(),
                    'code' => null,
                    'status' => 'Waiting',
                    'user' => null
                ]);
    }

Comment: @AndréLins então, não tenho log disponivel no console. Estou vendo como posso habilitar ainda.
O interessante é que isso só ocorre quando uso no schedule com cronjob, mas quando uso em uma rota, ao chamar ela é realizado o insert. Intrigante!?
Comment: Opa Mário, acontece algum erro?
Comment: O laravel cria um arquivo `laravel.log` em `storage/logs/`, verifique se tem algo lá.
Comment: no log informa que ela referencia uma coluna id de outra tabela, o estranho é que este dado exist. Vou analisar melhor aqui pra ver se existe mais inconsistencia
Comment: @AndréLins na verdade o erro estava ocorrendo devido ao item_id que não existia na outra tabela, porque achei que eu estivesse alterando o tipo de dado para passar como inteiro, mas na verdade o settype retorna 1 para TRUE e 0 para FALSE. Após corrigir funcionou normalmente. Obrigado pela força, sabes se você consegue fechar a minha pergunta ou como posso fechar?
Comment: Ótimo Mário, responde a pergunta e coloca essas resposta como a correta que acredito ser o suficiente.
Answer: Conforme a ajuda do @André_Lins nos comentarios o erro estava ocorrendo devido ao item_id que não existia na outra tabela, porque achei que estivesse alterando o tipo de dado para passar como inteiro, mas na verdade o settype retorna 1 para TRUE e 0 para FALSE. Após corrigir funcionou normalmente.


How do I improve vibrato and breath volume in singing?

Question: Some people say that vibrato is a gift acquired by birth while some say vibrato has to be practiced and gained before puberty. Once puberty (10-12 yrs) is attained, and the male voice changes to a low pitch one, vibrato is no longer achievable.
I am 22 years old, and have an intense need to improve my vibrato. How do I do it?
Also, in the world I need to perform in, we need to recite for more than 35 secs in a loud voice in a single breath. At present I can hardly do that for 15 secs. Please help me increase my breath volume by suggesting some routines and exercises.
Thank you
Comment: This is really two different questions.  How about editing this down to one question (about vibrato) and asking about breath volume in a separate question?
Comment: I'm a 16-year old boy and I was told that vibrato strengthens a note, and, it really does, especially when I sing high notes. It really improves my tone.
Answer: Vibrato is more or less a natural phenomenon once you are singing with nice support and a relaxed larynx.  It's absurd that you would have to learn it at some given age: it more or less comes with a well-tended voice at whatever age.
Vibrato can be produced somewhat artificially by conscious breath and throat actions but that is rarely convincing and often is more of a wobble with more of a pitch variation than appropriate.
Basically vibrato should not be much more than the absence of forcing a "straight" tone.  While there are different degrees of acceptance in different music styles, it's one of the things that are easily overdone, particularly in the form of the continuously controlled wobble.
Comment: This is the correct answer, unfortunately it hasn't been accepted as such.
Answer: Well, I don't think the first claim is true. I didn't know how to do vibrato until I was 19. I'm 23 now and I'm still improving it. And I have a very low pitch voice. My dad learned how to do vibrato only in his 50s.
But, I don't really know how I really learned it. I was experimenting with my voice one day, and it got easier the more I played with it. It's like riding a bicycle, once you get the hang of it, it gets easier.
It sometimes happens automatically when I'm running out of breath. But I can trigger it at will too, but I don't really know how technically. But it's definitely important to use your belly breath (instead of chest).
Now, on how to increase breath volume, I swim. Swim without re-breathing as long as I can. But, I also realize that singing alone helps too. So, if you can do 15 seconds now, try do it longer next time. Challenge yourself, until you can smell your lung (it happens, it smells like fish's gill).
Comment: and this http://www.wikihow.com/Increase-Your-Lung-Capacity-for-Singing
Comment: thanks for replying. But could you please suggest something other than swimming. I don't have access to it.
Comment: I know swimming works because I tried, and it works. Other things like running or any cardio exercise and abs/core exercise should help too, but I can't guarantee you the effectiveness. Have a look at [this] (http://www.wikihow.com/Increase-Your-Lung-Capacity)
Comment: Vibrato is a natural phenomenon of singing without tension.  Some people sing this way naturally, others have to be taught or coached.  David's answer below correctly addresses this issue.
Answer: I am 14 years old and I absolutely love singing, but it seems like everyone in my class has a better vibrato than me. Vibrato majorly increases your singing performance, so I HAD to improve.
What I usually do is get to a note that I am comfortable with. Since I am a first-soprano, a comfortable note for me is probably the C one octave up from middle C or anything higher. I will start with an easy note and make sure my vibrato sounds good. Then I will slowly move down or up from that note, still keeping my vibrato. I do that everyday and it has helped me greatly.
Answer: As a singer and devoted swimmer I love vibrato, however I have been told that to much vibrato is more than a good thing.
So, I try to limit the amount of times I use it in a song, in order to make a greater impact.
What is vibrato? For me, it is wobbling my voice (on pitch). In certain sections (phrasing) this can be very favorable, as it can intensify the meaning of the story you are telling.
If you are anything like me; then wobbling can be a great addition to your singing talent. Good luck.


Expressão regular: como aplicar "Negative lookahead" em apenas um grupo de captura?

Question: Em uma tarefa de validação de domínios, necessito de uma expressão regular para validar os mesmos seguindo algumas regras, dentre elas, em que o nome do domínio não contenha apenas números.
Diante disso, criei uma expressão regular (regex) que valida o domínio, porém não consegui fazer com que a mesma falhe em caso de apenas números no nome do domínio.
Em resumo, a expressão regular está falhando por permitir domínios que contém apenas números, pois são domínios inválidos e a expressão está permitindo os mesmos.
Expressão regular:
^(^[a-z][a-z0-9]{0,30}\.)?([a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)(\.[a-z]{2,4}(?:\.[a-z]{2})?)$

Na expressão acima, estou capturando três grupos:

Grupo 1: subdomínio;
Grupo 2: domínio;
Grupo 3: TLD.

Estou tentando aplicar um negative lookahead apenas no grupo 2, porém o exemplo que encontrei aplica apenas no resultado inteiro.
Estou tentando aplicar apenas no grupo 2 (que captura o domínio), porém sem sucesso.
Fiz um exemplo no RegExr para demonstrar melhor o que estou tentando fazer.
Answer: Basta você colocar o lookahead dentro do grupo 2, e modificá-lo um pouco: o link que você viu usa os marcadores ^ e $, que indicam o início e final da string, por isso eles verificam a string inteira.
Se você não usar estes marcadores, o lookahead faz a verificação a partir da posição em que se encontra, então o grupo 2 ficaria assim:
((?!\d+\.)[a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)
 ^^^^^^^^^ basta adicionar isso

Dentro do lookahead temos \d+ (um ou mais dígitos), seguido de um ponto (\.). Ou seja, o negative lookahead verifica se a partir daquela posição, não existe uma sequência de somente números seguida de um ponto.
Como o lookahead sempre verifica a partir da posição atual, colocá-lo logo no início do grupo 2 é o suficiente, pois é a partir dali que será feita esta verificação.
Outro detalhe é que no grupo 1 não precisa repetir o marcador ^, pois ele já foi colocado antes no início da regex.
A regex inteira fica assim:
^([a-z][a-z0-9]{0,30}\.)?((?!\d+\.)[a-z0-9](?:[a-z0-9-]{0,24}[a-z0-9])?)(\.[a-z]{2,4}(?:\.[a-z]{2})?)$

Veja aqui ela funcionando.
Comment: Muito obrigado! Funcionou perfeitamente! Acho que agora compreendi o funcionamento do negative lookahead! Muito obrigado mesmo!


Trigger Rack middleware on specific Rails routes

Question: Is it possible to trigger Rack middleware only on specific Rails routes?
For example, let's say I wanted to run a rate limiter middleware only on the api namespace.
namespace :api do
  resources :users
end

Answer: I've had good success with Rack::Throttle for rate limiting. Subclass one of the built-in throttle classes and overload the allowed? method. Your custom logic can check which controller is being accessed and apply the rate limit as needed.
class ApiThrottle < Rack::Throttle::Hourly
  ##
  # Returns `false` if the rate limit has been exceeded for the given
  # `request`, or `true` otherwise.
  #
  # Rate limits are only imposed on the "api" controller
  #
  # @param  [Rack::Request] request
  # @return [Boolean]
  def allowed?(request)
    path_info = (Rails.application.routes.recognize_path request.url rescue {}) || {}

    # Check if this route should be rate-limited
    if path_info[:controller] == "api"
      super
    else
      # other routes are not throttled, so we allow them
      true
    end
  end
end

Comment: `allowed?` seems to specific to `Rack::Throttle` though. For a generic approach see: https://stackoverflow.com/a/34096415/2771889
Answer: Adding to Ian's answer, to setup up the ApiThrottle you have to:
# application.rb
require 'rack/throttle'
class Application < Rails::Application
  ...
  config.require "api_throttle"
  # max 100 requests per hour per ip
  config.middleware.use ApiThrottle, :max => 100
  ...
end

# /lib/api_throttle.rb
# Ian's code here

One important thing to add is that, for me, the path_info[:controller] came as "api/v1/cities" and not only as "api". Of course, that is due to the namespace configuration. Therefore, take care when setting up the throttler.
Answer: You can also (now) use a Rails Engine to create an isolated set of routes that adds additional middleware to the stack for its mounted routes.
See https://stackoverflow.com/a/41515577/79079
(Unfortunately I found this question while looking to see if there was any simpler way to do it. Writing a custom middleware for every middleware that I wanted to add seems even more round-about than using a Rails::Engine)


Is it safe to use setTimeout to bypass module import order issues?

Question: In my CRA project, I have a configureStore.ts file that exports my redux store:
// ...
export const store = createStore(
  rootReducer,
  initialState,
  compose(applyMiddleware(...middleware), ...enhancers)
);

and I subscribe to the store manually in staticIntl.ts, which is imported hundreds of times throughout the whole project
import { store } from "../configureStore"

class IntlManager  {
  constructor() {
    store.subscribe(this.onStoreChange);
  }
  // ...
}

const manager = new IntlManager()

But when I run the project, the store.subscribe fails due to

TypeError: Cannot read property 'subscribe' of undefined

I am practically certain this is due to import order/availability
I managed to "fix" the issue by pushing the subscribe callback to the end of the task queue via no-delay setTimeout (I know it actually rounds up to couple of MS, but I don't think I really need to mind about that):
constructor() {
  setTimeout(() => store.subscribe(this.onStoreChange));
}

Is this safe? I am mostly concerned about three things:

is it possible for the subscribe to still fail due to the same reason, even when wrapped in setTimeout ? For example if somehow processing my modules takes a long time
Is it possible for a first store update to happen before subscribtion (and thus missing on the subscribe callback call)?
Could such update happen as a result of my React app fetching data from the server and dispatching the response?

Are there any other potential pitfalls of my fix/hack?
Also, what other ways could I fix my problem? I'd be especially thankful for a link to a propper guide.
Comment: No it's not. You have no idea how long you should wait. So this might work 50% of the time and the other 50% of the time the person is likely waiting an unnecessarily long amount of time. You need to fix the underlying issue, which appears to be an observable not getting set correctly. So what you should really be asking yourself is why does `createStore` return undefined?
Comment: Perhaps you have a circular dependency in your imports?
Comment: @Liam I strongly disagree with your edit to the question tags. My question has much more to do with the event loop than reactjs. I would understand you deleting the `create-react-app` tag, but not this.
Comment: Well undo the edit then @MichalKurz. I added this tag as I'm presuming `createStore ` is returning some kind of react object. If your subscribing, I'm guessing it' an rxjs observable but not being  react developer I'm not sure if react uses rxjs (like angular does). None of this is to do with the importing of modules. Like I said, *you should really be asking yourself is why does createStore return undefined*
Comment: And thanks for your comment about my solution, @Liam . Are you 100% certain that the first callback registered by setTimeout will not always be executed after executing all of my static, already-queued code? Because It's in no way obvious to me, although certainly plausable.
Comment: @Liam Like I mentioned in my question, `I practically certain this is due to import order/availability`. `createStore` does not return undefined, but is not yet processed by the time I try to subscribe to it.
Comment: I am not sure what the correct term for my issue is
Comment: @Liam By event loop he means how the JS engine functions at runtime, how function calls to imported modules etc. evaluate. Since the setTimeout gives you another "tick". This is how I understood it at least.
Comment: Lets flip that question around @MichalKurz are **you** 100% certain that the first callback registered by setTimeout **will always** be executed after executing all of my static, already-queued code? Because that's what I'm getting at. You can't be certain. Which is why you shouldn't do this. It might work some-of-the-time. Or it might not. Which is why it's not a good solution
Comment: Ok, ley me be clear, this is nothing to do with the ordering of events. The order is undefined (generally) and can't be relied upon. This is why promises, etc. exist. If you need something to run in a particular order then you need to **chain the events yourself** using callbacks, promises or observables, etc. Which is why I keep saying, *you should really be asking yourself is why does createStore return undefined*. Nothing in this question is going to help you. Your real question is the contents of `createStore` that you haven't added
Answer:
I practically certain this is due to import order

Yes, this sounds very much like a problem with circular dependencies. Your configureStore imports something that depends on staticIntl, which in turn imports the store from a module that is not yet evaluated.
Do not use setTimeout, fix the underlying problem with your module dependencies.
In particular, I would recommend

move const manager = new IntlManager() into a different file where you clearly control that it is executed after the createStore(…) call.
Use dependency inversion - remove the store.subscribe(this.onStoreChange) line from the IntlManager constructor and instead write store.subscribe(manager.onStoreChange) after you created store.
Answer: I'm assuming IntlManager is a singleton, and you only need one of these in your app - if this is not true, ignore the following.
Following the classic redux setup https://redux.js.org/recipes/configuring-your-store my advice is to pass the store as a prop to your main App component. And then create an instance of IntlManager by passing the store prop to the constructor:
const store = configureStore()

render(
  <Provider store={store}>
    <App store={store} />
  </Provider>,
  document.getElementById('root')
)

in App component:
const { store } = this.props;
const manager = new IntlManager(store);

Wether this works depends a bit on how IntlManager is actually used by your app. You wrote that it is "imported hundreds of times throughout the whole project". This is ok I think, you might have to rewrite the class a bit so that you can instantiate it right away, but subscribe to the store later, when the store is actually available. I envision something like this:
in App component:
import manager from '.../IntlManager';
// somewhere in componentDidMount for example:
const { store } = this.props;
manager.subscribeToStore(store);


How do I change the date format of a single result?

Question: I have a view that gives me a list of nodes titles and when it was last updated.
I want to display the changed date with only time if it is today, otherwise I just want the date, e.g. 17.00 or 15 may 2016.
If I look at the result in views_pre_render it has a node_changed timestamp. It uses the date format set in the view. How do I change the format just for the first result?
Answer: You can create a template file and in that you can have and the template files you can get that in

<code>if($view->row_index == 1){
   // do your stuff
}
</code>
and put your own condition


Aplicar o princípio da responsabilidade única nos métodos que utilizam subscribe

Question: Considere a seguinte classe:
export class TesteComponent {
    //...
    public onSubmit() {
        this.checkA();
    }

    private checkA(): void {
        this.service.checkA(value)
            .subscribe(response => {
                if(response) {
                    //regra de negócio
                    this.checkB();
                } else {
                    //error
                }
            });
    }

    private checkB(): void {
        this.service.checkB(value)
            .subscribe(response => {
                if(response) {
                    //regra de negócio
                    this.checkC();
                } else {
                    //error
                }
            });
    }

    private checkC(): void {
        this.service.checkC(value)
            .subscribe(response => {
                if(response) {
                    //regra de negócio
                    //fim
                } else {
                    //error
                }
            });
    }
}

Repare que os métodos checkA, checkB e checkC executam um serviço que retorna um Obervable (podemos constatar isso através do .subscribe) que por sua vez é responsável por consumir uma API REST (não está explícito, mas interessa saber apenas que o serviço é assíncrono).
A cadeia de eventos começa com o método checkA e quando é concluído executa o método checkB, que por sua vez executa o checkC.
A questão é que os 3 métodos possuem funções bem definidas, porém ao concluir a tarefa o método executa outro método que possui uma responsabilidade completamente diferente, ferindo o princípio da responsabilidade única.
Por exemplo, quando coloco um carro a funcionar, não espero que ele começe a acelerar sozinho depois de colocar o cinto de segurança; é basicamente isso que estou a fazer ao executar métodos com diferentes responsabilidades.
Penso que o certo seria existir um elemento controlador responsável por decidir qual fluxo seguir (tal como eu decido o que fazer a seguir após colocar o cinto de segurança), mas como cada método é assíncrono, não sei como resolver o problema com Angular 5.
Como resolver esse problema?
Answer: Resolvi o problema criando uma função controladora, por exemplo:
export class TesteComponent {
    //...
    public onSubmit() {
        this.invokeChain('checkA');
    }

    private invokeChain(operation: string) {
        switch(operation) {
            case 'checkA':
                this.checkA(fakeParam).subscribe((response: boolean) => {
                    if(response) this.invokeChain('checkB');
                    else this.errorHandling();
                });
             break;

            case 'checkB':
                this.checkB(fakeParam).subscribe((response: boolean) => {
                    if(response) this.invokeChain('checkC');
                    else this.errorHandling();
                });
             break;

            case 'checkC':
                this.checkC(fakeParam).subscribe((response: boolean) => {
                    if(response) console.log('Fim');
                    else this.errorHandling();
                });
             break;
        }
    }

    private checkA(value: string): Observable<boolean> {
        return this.service.checkA(value)
            .map((response: boolean) => response);
    }

    private checkB(value: string): Observable<boolean> {
        return this.service.checkB(value)
            .map((response: boolean) => response);
    }

    private checkC(value: string): Observable<boolean> {
        return this.service.checkC(value)
            .map((response: boolean) => response);
    }
}

Os nomes utilizados são apenas para exemplo.
Não sei se existe uma outra solução ou algum padrão para resolver o problema, mas considero uma solução razoável pelos seguintes motivos:

Melhora a leitura do código.
Os métodos checkA, checkB e checkC passaram a ter uma única responsabilidade.
Como os métodos referidos acima passaram a ter uma única responsabilidade, podem ser reaproveitados em outros casos.
Os métodos não são responsáveis por invocar outro método, isso passou a ser responsabilidade do método invokeChain. Esse método é responsável por manipular o fluxo conforme a resposta do request anterior.


Apache - add http headers to requests, using script (bash, perl, php etc) to set the headers

Question: I trying to work out the feasibility of a project where I want to be able to have a script run on every request (preferably filtered by mime type), and a script run to set the headers for the response.
Basically I want requests for text/html and application/json documents to have http headers with arbitrary data generated by the system (the actual headers added will be git branch and commit hash info).
This is for local and staging webservers, so performance impact isn't a high concern.
I have investigated mod_ext_filter with bash scripts, and while I could successfully inject strings into the output, I couldn't access the headers (I assume they have already been sent?)
Are there any other options I can investigate?
My attempt so far (in vhost):
<code>    ExtFilterDefine githeaders mode=output \
                   cmd="/bin/bash /path/to/script/git_headers.sh" preservescontentlength

   <Location />
     SetOutputFilter githeaders
   </Location>
</code>
Basic bash script testing echo
<code>#!/bin/bash

echo "hello"

cat
</code>
The above works fine, injecting hello into the responses, but I can't work out how to alter headers. Any help/suggestions appreciated.
Answer: The examples I have seen typically use mod_headers to insert, remove or replace headers, like the example below from the manual.
<code># mod_ext_filter directive to define the external filter
ExtFilterDefine gzip mode=output cmd=/bin/gzip

<Location /gzipped>
# core directive to cause the gzip filter to be
# run on output
SetOutputFilter gzip

# mod_header directive to add
# "Content-Encoding: gzip" header field
Header set Content-Encoding gzip
</Location>
</code>
I can only assume that using the regular API and by writing the filter in C you get more access and will be able to modify headers.
Comment: I was unable to test this, but you are probably right that I would need take the C filter approach


Add Location CCK field and instance programmatically to content type in Drupal 7

Question: How does one add a Location CCK field and instance programmatically to a content type in a Drupal 7 module install? I am mainly concerned with what params need to be given to the field_create_field and field_create_instance functions, assuming it is created in the same way as core fields? I've put some examples of the params I give to these functions in creating core fields (in case this helps):
An example of the params given to field_create_field:
'field_property_price' => [
    'field_name' => 'field_property_price',
    'label' => $t('Price'),
    'cardinality' => 1,
    'type' => 'text',
    'module' => 'text',
    'length' => '20'
];

An example of the params given to field_create_instance:
'field_property_price' => [
    'field_name' => 'field_property_price',
    'label' => $t('Price'),
    'cardinality' => 1,
    'required' => true,
    'widget' => [
        'weight' => '0',
        'type' => 'text_textfield',
        'module' => 'text',
        'active' => 1,
        'settings' => [
            'size' => '20',
        ],
    ],
],

Thanks for reading.
Answer: Never mind I figured it out. The following params work (note that the entity type and bundle params are also needed, but for my own usage I add these later).
For field_create_field:
'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'type' => 'location',
    'module' => 'location_cck',
    'settings' => [
        'location_settings' => [
            'form' => [
                'fields' => [
                    'name' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 1,
                    ],
                    'street' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 2,
                    ],
                    'additional' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 3,
                    ],
                    'city' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 4,
                    ],
                    'province' => [
                        'collect' => 1,
                        'widget' => 'autocomplete',
                        'default' => '',
                        'weight' => 5,
                    ],
                    'postal_code' => [
                        'collect' => 1,
                        'default' => '',
                        'weight' => 6,
                    ],
                    'country' => [
                        'collect' => 1,
                        'default' => 'gb',
                        'weight' => 7,
                    ],
                    'locpick' => [
                        'collect' => 0,
                        'weight' => 20,
                    ],
                ]
            ],
        ]
    ],
],

For field_create_instance:
'field_property_location' => [
    'field_name' => 'field_property_location',
    'label' => $t('Location'),
    'required' => true,
    'widget' => [
        'weight' => '0',
        'type' => 'location',
        'module' => 'location_cck',
        'active' => 1,
    ],
     display' => [
        'default' => [
            'label' => 'above',
            'type' => 'location_default',
            'weight' => 0,
        ],
    ],
],

There are more params you can fiddle with but these are the ones that suited my needs. To figure the params (and to figure out params for other fields like this in future), first add the fields manually to the content type with the desired settings in the Drupal backend. Then in the command line go to the projects root directory and used drush eval "print_r(field_info_fields())" to see all the fields added and drush eval "print_r(field_info_instances())" to see all the field instances added.
Mirror the data and structure from the print out to use in the field_create_field and field_create_instance functions as I've done above.


Equivalences and bijections

Question: I have to show that the following are an equivalence relation on $A$ and find a bijection between $A/\sim$ and $B$.
I know that to show something is an equivalence relation it needs to satisfy the reflective, symmetry and transitive property, but I don't know how to prove that. I also don't know anything about bijections.
a) $A=\mathbb{Z}$ (integers); $m\sim n$ means that $m^2=n^2$;$B=\mathbb{N}$ (Natural numbers)
b) $A=\mathbb{R}\times \mathbb{R}; (x,y)$ is equivalent to $(x_1, y_1)$ means that $x^2+y^2=x_1^2+y_1^2$; $B=\{x \in \mathbb{R}|x \geq 0\}$
Any help would be appreciated!
Comment: Here you can find a definition of bijection: https://en.wikipedia.org/wiki/Bijection
Answer: a) You need to prove:

$\color{red}{\text{Reflexive property. }} n\sim n$ for all $n\in \mathbb{Z}$, what means $n^2=n^2$, which is clear.
$\color{red}{\text{Symmetry property. }}$ If $m \sim n$  for $n,m\in \mathbb{Z}$, then $n\sim m$. Since equality satisfies the symmetry property we have:
$$m^2=n^2 \iff n^2=m^2;\,\,\,\,\text{i.e.}\,\,\,\,m\sim n \iff n\sim m$$
$\color{red}{\text{Transitive property. }}$ If $\{m,n,p\}\subset\mathbb{Z}$ s.t. $m\sim n$ and $n\sim p$, then $m^2=n^2$ and $n^2=p^2$, so, by transitive property of the equality it follows $m^2=p^2$, which means $m\sim p$.

Therefore, $\sim$ is an equivalence relation on $\mathbb{Z}$. It is no hard to show that a equivalence class for $n\in\mathbb{Z}$ under $\sim$ is: $[n]=\{n,-n\}$.  Now, we need to prove that there is an injective and surjective mapping  $f:\mathbb{Z}/\sim \longrightarrow \mathbb{N}$. So, what about $x\mapsto |x|$?

Equivalences and bijections


What would it be an alternative for identity server 4?

Question: Identity server 4 will not longer be maintained after November 2022 so logically we want to move away from that. I was looking for alternatives but it seems there ain't much out there. We don't wanna go for Duende to avoid the license, same goes with AAD. Will rolling out own identity service for a single Kubernetes solution make sense?
Edit:
Maybe the question itself was not clearly stated. I know it would be possible to roll my own "identity solution", however, I am not aware of the implications of this. I would like to know if there is any other free or open source solution we could use to make this happen. If not, how hard or difficult will it be to do it on our own? I haven't found much information regarding doing this from scratch either.
Comment: The question, as it stands, is subjective. How you define "sense" here? Another question, how to actually write your own identity provider, would be fine, however, this would be more than just a single question to have a complete answer to that.
Comment: @WiktorZychla you are right, I added a clarification in an edit. Mainly I am looking for options, either if there is a framework or some free of use solution I could use.
Comment: Most components are there in the framework. Depending on details (which you miss in your question, like whether you want WS-Fed or SAML2 or OIDC), things can be easier or more difficult in .NET Framework vs .NET6. Anyway, try to ask about something specific, a general question "is it doable" has a general "yes" answer (e.g. I do it for years)
Comment: Duende has a Community Edition for companies turning over $1M USD or less : https://duendesoftware.com/products/CommunityEdition  yes they may pull the rug but its there if you want to take the risk. I rolled my own.
Answer: If you are looking for free IdentityServer(duende) alternatives, I would like to suggest this article: 3 Possible Alternatives To IdentityServer.

OpenIddict: open-source .NET library that helps you implement a security token service (STS).
Azure Active Directory (AAD) B2C: Microsoft's Software-as-a-Service (SaaS) identity and access management for customer-facing apps offering.
Keycloak: open-source Java-based identity and access management (IAM) solution.

I think the best option in your case is OpenIddict
Perhaps this article will be of interest to you as well:
.NET 6.0 - JWT Authentication with Refresh Tokens

IdentityServer Community Edition:
IdentityServer Community Edition: A free license that is feature equivalent to Enterprise Edition
You can still utilize IdentityServer at no cost for:

For-profit companies/individuals less than 1M USD projected annual gross revenue and with access to less than 3M USD in capital
facilities.
Non-profit organization with a published annual budget less than 1M USD
Registered charities

Kindly, be aware that the license remains valid for one year, necessitating an annual renewal.


How do I import python modules into Pycharm offline

Question: I have some offline computers which I cannot connect to the Internet. Not surprisingly, several of the modules are outdated. How do I update them and also add new ones?
I am envisioning downloading something from the Internet, putting it on a flash drive, then loading it somehow into Pycharm. This question is about the first and last steps.
Pycharm 2018, Windows 10
Comment: You can install with wheel file, open CMD and type -> `pip install D:/some-folder/your-file.whl`
Answer: You need the downloaded packages from somewhere that connected to internet then store it as  via
# in case of just single package
$ pip install <package> --download <path>/offline_packages

# incase you need a list of pakages
$ pip install --download <path>/offline_packages -r requirements.txt

Tranfer the  to your machine (by anyway you can)
Install these packages to your current Pycharm's Python directory via:
# single package
$ pip install --no-index --find-links="<path>/tranferred_packages" <package>

# list of dependencies
$ pip install --no-index --find-links="<path>/tranferred_packages" -r requirements.txt

Hope this can help you :)
Comment: Note- syntax has changed from "install --download" to download. Also, I have a question. When I run the command to download from a requirements file, I get this error: "Directory 'C:/.../newdirectory' is not installable. Neither 'setup.py' nor 'pyproject.toml' found."
Answer: If you look at the second most voted answer on this SO post you'll see the general way of doing it. You can do that with your virtualenv activated, then the packages should show up in PyCharm just fine
Answer: On a computer that has an internet connexion download your packages with :
pip download -d <download folder directory> <package name>

Then on the target computer copy the download folder then go to Pycharm's Terminal and install your packages with:
pip install --no-index --find-links <download folder directory> <package name>


How To make Preg_Match or PATTERN

Question: I have a url and i want it pattern or preg_match function
url looks like this
http://www.myurl.com/login/login.php?confirmation=1&sub=a18c6aff-614c-49b2-ab67-5d90f839dce6-299072-1

i am going to run with loop and every time i am getting a different url but i need only the last value

a18c6aff-614c-49b2-ab67-5d90f839dce6-299072-1

i tried every process that i know for preg_match but i failed
Answer: As you mentioned, its always the last value, so you can explode() and get the last value using end():
Code:
$str = 'http://www.myurl.com/login/login.php?confirmation=1&sub=a18c6aff-614c-49b2-ab67-5d90f839dce6-299072-1
';
$newStr = explode('=', $str);
echo end($newStr);

Output:
a18c6aff-614c-49b2-ab67-5d90f839dce6-299072-1

Comment: i have again second problem i need to run that value with another url then how could i put with in
Comment: i try below method   $new="https:// myurl.com/id=end(newstr)";   but i get error like in print it show array
Comment: thank you once again dear bro rally helpful for me :)
Comment: You're welcome. Happy to help! You are accept/approve this answer. Happy Coding!

How To make Preg_Match or PATTERN


Why central difference blows up Hessian when step-size is small?

Question: I'm trying to use automatic differentiation to obtain the gradient, Hessian and compare them with the analytic ones. However when I set step-size very small, the Hessian blows up and the gradient becomes less precise. Why the step-size not the smaller the better? If so, what should be a reasonable step-size for such approximation?
<code># log_likelihood

mu = 54.2
x = c(37.7,52.5,49,51,49.9,49.8,50.4,49.8,49.1,49.2)
sample_size = length(x)

log_likelihood = function (mu) {
  log_likelihood_value = 0
  for (i in 1:sample_size) {
    log_likelihood_value = log_likelihood_value + log(pi*(1+(x[i]-mu)^2))
  }
  return(-log_likelihood_value)
}
cat('log_likelihood=',log_likelihood(mu))

# Newton-Raphson

gradient = function (mu) {
  gradient_value = 0
  for (k in 1:sample_size) {
    gradient_value = gradient_value + 2*(x[k]-mu)/(1+(x[k]-mu)^2)
  }
  return(gradient_value)
}

hessian = function (mu) {
  hessian_value = 0
  for (k in 1:sample_size) {
    hessian_value = hessian_value + (2*(1+(x[k]-mu)^2)-4*(x[k]-mu)^2)/(1+(x[k]-mu)^2)^2
  }
  return(-hessian_value)
}

mu = median(x)
N = 5
eps = 0.0000000000001
for (j in 1:N) {
  cat('mu=',mu,'\n')
  cat('gard_approx=',(log_likelihood(mu+eps)-log_likelihood(mu-eps))/(2*eps),'\n')
  cat('grad=',gradient(mu),'\n')
  cat('hessian_approx=',(log_likelihood(mu+eps)-2*log_likelihood(mu)+log_likelihood(mu-eps))/eps^2,'\n')
  cat('hessian=',hessian(mu),'\n')
  mu = mu - gradient(mu)/hessian(mu)
}
</code>
and I obtain result
<code>mu= 49.8
gard_approx= -0.2309264
grad= -0.2463615
hessian_approx= 1.065814e+12
hessian= -7.707962
mu= 49.76804
gard_approx= -0.01776357
grad= 0.001049172
hessian_approx= 355271367880
hessian= -7.770681
mu= 49.76817
gard_approx= -0.01776357
grad= 1.540493e-08
hessian_approx= 355271367880
hessian= -7.770453
mu= 49.76817
gard_approx= 0.03552714
grad= 1.24345e-14
hessian_approx= 710542735760
hessian= -7.770453
mu= 49.76817
gard_approx= 0.03552714
grad= 1.24345e-14
hessian_approx= 710542735760
hessian= -7.770453
</code>
Comment: I haven't really looked at your post in detail, but a very plausible explanation is the $\varepsilon^2$-term. When $\varepsilon$ is small, its square, $\varepsilon^2$, is *really* small. Dividing by a really small number... gets big.
Comment: But the numerator is also small, though
Comment: Yes, but you have to consider computer precision as well.
$$0.0000000000001^2 = 10^{-26} $$
which is beyond standard floating precision. Computers (generally) only store numbers to a certain precision of about 16ish digits.
Answer: The evaluation of a function via floating point incurs usually a relative error that is a small random multiple of the machine constant (which is usually denoted as $\mu$, but let's use $\delta$ here). The error when using divided differences with step size $\varepsilon$ is then bounded by an expression of the form
$$
\frac{4|f(x)|δ}{ε^2}+\frac{|f^{(4)}(x)|ε^2}{12}
$$
As you can see, this is not only large for large $ε$, but also for very small $ε$. It is minimal around the point where both terms in the sum are equal, and assuming that function value and derivative are of equal magnitude, this minimal error bound can be found around $ε=\sqrt[4]δ$ which for 64bit double floats gives $δ=2\cdot 10^{-16}$ and thus $ε=10^{-4}$.
It might seem counter-intuitive, but including the floating point errors one finds that the higher the error order of the formula, the larger the $ε$ with the optimal error bound.


How can I apply some value with HTML tags to a form element?

Question: I've assigned some value with HTML tags to a form element, say the element is called name.
When it returns the form, it exactly prints the value along with the HTML. What I want in return instead, is the style applied to the text.
In this what I'm trying to do is hook_form_FORMID_alter().
This is the page where comments are listed(admin/content/comment). In this, for each comment I'm showing the subject comment and author etc. Also a collapsible tree for editing the comment with pre filled values in the fields.
$form['name'] = 'Fazeela'
return $form;

Comment: when referencing code, please post the code here, not a link to the code - if the link dies, the question will be useless for future people viewing it
Comment: What type of element is $form['name']? Are you talking about text that is in a text field or text area?
Comment: It is not a field, there is a collapsible tree, in which I am printing this value.
Comment: May you provide the full code of that function, and explain exactly what is wrong in the result you are obtaining?
Comment: @kiamlaluno Hi, I have edited the code and requirement. Please let me know if you need further clarification.
Answer:
Use css.

Example:
If your $form['name'] is a div with an id wrapper,

Fazeela

Include a css file in your module file, particularly in hook_init function.
function NameOfYourModule_init(){
   drupal_add_css(drupal_get_path("module", "NameOfYourModule") . "/mycss.css");
}

mycss.css file
#wrapper{
    font-weight: bold;
}

Comment: Did you see the code?
Comment: Is this the best way to do this?
Comment: @FazeelaAbuZohra There is no need to include a CSS style file for rendering something in bold. See my answer.