After installing PowerShell-7.4.1-win-x64.msi, $PSVersionTable still shows 5.1.22621.2506

Question: I have installed PowerShell-7.4.1-win-x64.msi, but $PSVersionTable still shows version 5:
PS C:\Users\firerose> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.22621.2506
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22621.2506
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           220.127.116.11

PS C:\Users\firerose>

Answer: The name of the application in the Start menu is PowerShell 7 (x64) instead of Windows PowerShell.
PowerShell 7.4.1
PS C:\Users\firerose> $PSBoundParameters
PS C:\Users\firerose> $PSVersionTable.PSVersion

Major  Minor  Patch  PreReleaseLabel BuildLabel
-----  -----  -----  --------------- ----------
7      4      1

PS C:\Users\firerose>

Answer: Indeed both versions 5.1 and 7.4 are installed and run "side-by-side". That information is for the 5.1 installation, which is considered bundled with and part of Windows starting with Windows 10.0.14393 (1607)/ Windows Server 2016. You're probably looking for pwsh.exe.
Versions prior to 5.1 were installable or updated as part of the Windows Management Framework.

"PowerShell 7.4 installs to a new directory and runs side-by-side with Windows PowerShell 5.1."
"PowerShell 7.4 is an in-place upgrade that removes previous versions of PowerShell 7. Preview versions of PowerShell can be installed side-by-side with other versions of PowerShell."
"PowerShell 7.4 is installed to:  $env:ProgramFiles\PowerShell\7"
"The $env:ProgramFiles\PowerShell\7 folder is added to $env:PATH"
Installing PowerShell on Windows
https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows?view=powershell-7.4#installing-the-msi-package
Migrating from Windows PowerShell 5.1 to PowerShell 7
https://learn.microsoft.com/en-us/powershell/scripting/whats-new/migrating-from-windows-powershell-51-to-powershell-7?view=powershell-7.4
PowerShell Versions
https://en.m.wikipedia.org/wiki/PowerShell#Windows_PowerShell_5.1


User field imported with Feeds but not showing in user edit page?

Question: I'm using Feeds Importer to create users from a csv file, in my Drupal 7 site.
It works perfectly, except one case. I added some custom fields to user profile and I can set all them with my importer, except one (a simple text field, let's say 'foo').
The value for 'foo' is correctly imported: if I open the 'View' page for a user profile I can see it, listed as supposed. In the 'Edit' page of the user profile, however, the value of the field is showed empty. If I modify the value in this edit page and save, the value is stored AND showed in the edit page.
I tried even to create another custom field similar to 'foo' and it works perfectly in any case. (I can't delete foo and recreate it for it contains several data)
How could this be debugged? I checked the csv, the importer, even the database (in the table field_data_field_foo the value is stored correctly), and all seems fine. No error in drupal log, neither in importer log.
Answer:
I can't delete foo and recreate it for it contains several data

Here is how I would try to fix this:

Backup your entire Drupal Database.
With phpmyadmin or some other database manager/viewer, find the field_foo table and extract the table as a CSV file.
In Drupal, go to user manage fields and Delete field foo
Flush the cache (not necessary, but eh, just in case)
Add a new field, foo
Edit user 1 and put something for field foo. (This is just so we get the table structure on step 7)
Find field_foo in DB and extract.
Open Original field foo .csv in excel and highlight all data and copy.
Open new field foo .csv and paste data and save
Import new field foo .csv to DB.
Flush/Clear the Cache
Try importing with feeds again and see what happens.
Comment: @SashaGrievus make a copy of your live site and test on the copy dev site. If you confirm that it works, then do the same on live site. You can put live site in maintenance mode for a few mins to do this.
Comment: Fair enough! :) I'll try to make it work in Acquia and see what happens. Thank you very much.
Comment: Not a bad idea, but the website is up and running. I can't risk to mess it up like this... It would be useful to know if the db structure of a new field goes beyond the table field_foo. Do you know something about this?
Comment: can this process will work in D8?
Comment: @ManmeetKhurana yes :)
Comment: I have field with plain text field type and created the new field with type number and inserted the record into the new field type table
Record is showing properly but I have to perform sorting according to the new field  and its showing result according to the plain text not the number.
Ex :10 is showing first and 2 is later


Exibir mensagem de usuario bloqueado no membership

Question: Preciso exibir uma mensagem quando o usuario bloqueado tentar logar no membership...
Defino o usuario bloqueado com a propriedade IsApproved = false; no momento do cadastro
MembershipUser lockUser = Membership.GetUser(txtEmail.Text);
lockUser.IsApproved = false;
Membership.UpdateUser(lockUser);

Existe alguma forma?
Comment: Se puder explicar melhor o problema que tem em concreto e, se possível, mostrar código que já tenha feito onde se encontre esse problema. Está demasiado ampla a sua pergunta, veja na [Central de Ajuda Como Perguntar](http://pt.stackoverflow.com/help/how-to-ask).
Comment: Como é que estás a definir um user bloqueado na bd?
Comment: Reformulei a pergunta, preciso agora exibir uma mensagem se o usuário não tiver desbloqueado o acesso que foi enviado por email.
Answer: No seu botão de login:
protected void Button1_Click(object sender, EventArgs e)
{
    MembershipUser user = Membership.GetUser("Yourusername");

    if(user != null && !user.isApproved) {
        ClientScript.RegisterStartupScript(
           this.GetType(), "myalert", "alert('O usuário não está aprovado.');", true);
    }
}


One sample or two sample when comparing the same points over time

Question: I have 425 sample points that have been classified according to land cover in two time periods. When comparing how percent land cover has changed over time, is this a one sample test (ie. because the same points are sampled), or a two sample test (ie. because two separate time periods)? I'm pretty sure that each time period should represent a separate sample and so a two sample approach should be used, but just want to check!
Answer: You have paired data, the two observations of the same point constitutes a pair. The basic analysis here could be a paired t-test, see for instance Paired t-test between different algorithms: Properties of paired t-test, or the same way with some other one-sample test applied to the differences.
But this assumes that the different pairs are independent, and it seems you have some kind of spatial data, so independence might not hold. So look also at maps of the differences, and other plots.


How to get jQuery to open a page in the current tab rather than a new one

Question: Before saying  that the answers are already on the forum take note that I have already tried them to no avail. Basically the problem is that when I press enter to search it opens the google page in a new tab. How do I get it to open in the current tab?
This is the HTML

    <form class="websearch">
        <input autofocus placeholder="Google" type="text" id="GGLSite">
        <input type="button" id="GGLmeme" onclick="DoGGL()" style="display: none;" value="Search GGL">
    </form>

This is the Javascript
function DoGGL(){
    var GGLVar = document.getElementById("GGLSite").value; //this grabs the variable (search terms) from the textbox
    var NewURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + GGLVar; //this puts the site they typed into the wayback machines URL

    var NewTabGGL = window.open(NewURL, "_blank"); //this opens a new tab with the URL.
    if (NewTabGGL){ //make sure the browser can allow it
        NewTabGGL.focus(); //switches them to the new tab -- done!
    }
    else{
        alert("Popup didnt work");
    }
}

$(document).ready(function(){
    $('#GGLSite').keypress(function(e){
      if(e.keyCode==13)
        $('#GGLmeme').click();
    });
});

Comment: If you don't want to open in a new tab so why do you have this line:
`var NewTabGGL = window.open(NewURL, "_blank"); //this opens a new tab with the URL.`
Your comment there saying that it will open it in new tab ?!
Comment: use the target = "_self" instead of "_blank". i.e, window.open(NewURL, "_self")
Comment: Did you try using window.location.href = "desiredUrl"?
Comment: @DinoMyte I tried that, it still didn't work.
Comment: @wilsotobianco I tried that earlier, that didn't work aswell.
Comment: Understood. Can you provide a jsFiddle or something like that so we can help?
Comment: Here it is. https://jsfiddle.net/p8wp0m8u/
Answer: If you are trying to just get to the page from this page, window.location = NewURL; would work. I don't see exactly what you're trying to do.
Comment: Why don't you add a `` and an ajax request to the google API. then load the html into your div
Comment: That didn't work. It doesn't bring me to the google link. What I am trying to do is: I have a custom splash page for my browser. I have various links that I commonly visit. I also have a search bar that put whatever I put in it in a google search for me. I just want the results to open in the same tab that I write them in. Not open a new tab.
Answer: I did some tweaks on your code (read the comments):
Javascript
// Remember capitalized functions are supposed to be used with the new operator, hence, this function must not be capitalized
function doGGL(event){

    // Here we prevent the default behavior of the form submit
    event.preventDefault();

    // Javascript variables must not be capitalized
    var gGLVar = document.getElementById("GGLSite").value;
    var newURL = "https://www.google.se/?gws_rd=ssl#safe=off&q=" + gGLVar;

    // This sentence navigates to desired URL in the same window
    window.location.href = newURL;
}

$(document).ready(function(){
  // There's no need to catch the enter key because that's the form default behavior. So I'm attaching the submit event to the function defined above
  $('.websearch').on('submit', doGGL);
});

This didn't work in jsFiddle so I tried it in a local file called index.html with the same HTML, CSS but replacing the javascript with the latter.
Hope it helps!


Adicionar dados a um objeto/imagem no FabricJS

Question: Preciso adicionar dados a um objeto no FabricJS e buscar eles novamente na hora de exportar o canvas.
Função que eu uso para adicionar um objeto:
function _addImageObject(imageURL) {
  fabric.util.loadImage(imageURL, function (imageLoaded) {

    var image = new fabric.Image(imageLoaded);

    image.set({
      borderColor: 'black',
      cornerColor: 'black',
      cornerStrokeColor: 'white',
      cornerSize: 11,
      transparentCorners: false,
    });

    canvas.add(image);
    canvas.centerObject(image);
    canvas.setActiveObject(image);
    canvas.renderAll();
  });
}

Função usada para buscar os objetos:
 function _canvasJSON() {
      try {
        let canvasCopy = _copyCanvas(canvas);

        let canvasJSON = {
          canvasImage: JSON.stringify(canvasCopy),
          svg: canvas.toSVG()
        };
        return canvasJSON;
      } catch (e) {
        canvas.renderAll();
      }
    }

function _copyCanvas() {
     let canvasString = JSON.stringify(canvas);
     return JSON.parse(canvasString);
}

Queria adicionar um objeto dentro dessa image, exemplo:
image.set('key', { values: 123});

E conseguir buscar ele no retorno do _canvasJSON();
Answer:
Para adicionar uma nova informação, é preciso criar um objeto, utilizar obj.set() e renderizar o canvas. Exemplo:

 var obj = canvas.getActiveObject();
 obj.set('foo','bar');
 canvas.renderAll();

Feito isso, a nova informação já estará dentro do seu objeto, porém ela ainda não está disponível no JSON.
Para isso, basta especificar no JSON.stringify.Exemplo:

var json = JSON.stringify(canvas.toJSON(['foo']));

Para buscar a informação inserida, basta busca-la dentro de um objeto. Exemplo:

 var obj = canvas.getActiveObject();
 console.log(obj.foo);


Não obtendo resposta Socket IO

Question: Olá,
Podem me dizer por favor onde está o erro ?
Criei um arquivo na pasta raiz, server.js

var socket  = require( 'socket.io' );
var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = socket.listen( server );
var port    = process.env.PORT || 3000;

server.listen(port, function () {
    console.log('Server listening at port %d', port);
});

io.on('connection', function (socket) {
 socket.on( 'new_message', function( data ) {
  io.sockets.emit( 'new_message', {
   id: data.id,
   titulo: data.titulo,
   mensagem: data.mensagem,
   created_at: data.created_at
  });
 });
});

Agora em uma requisiçao ajax, faço a inclusão dos dados no banco e retorno em json.
O meu retorno no ajax, possui o seguinte código
if(data.success == true) {
    let socket = io.connect( 'http://'+window.location.hostname+':3000' );
    socket.emit('new_message', {
        id: data.id,
        titulo: data.titulo,
        mensagem: data.mensagem,
        created_at: data.created_at
    });
}

E estou tentando obter a resposta socket conforme abaixo, mas não estou tendo sucesso.

let socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'new_message', function( data ) {
 console.log(data);
});
Answer: Problema resolvido, o retorno json estava como string, adicionei header('Content-Type: application/json'); no retorno PHP e obtive sucesso.

Não obtendo resposta Socket IO


What do you call the left hand side variables in a regression/classification?

Question: If I have a regression or classification problem
y ~ x1 + x2 + ... + xn

I might call the xi the regressors or the predictors. But what do you call y?
The terms regressand and predictand are clunky, don't seem particularly standard, and have the disadvantage that they're very similar to the words for the right-hand-side variables (I'm going to be using these terms in type declarations and documentation for a program, so minimizing the potential for confusion is a priority).
Also, using regressor and regressand is inappropriate when you have a classification problem, rather than a regression.
Is there a commonly used term?
Comment: I think the "response" or "outcome" variable are commonly used terms.
Comment: In regression it is also called the dependent variable or DV and the Xs are called the independent variables or IVs.  However the independent variables do not have to be and usually are not statistical independent.
Comment: What if you are using regression to do classification?
Comment: 'outcome' also seems fine for classification.  Or try 'class' or 'category'.  If you're really fitting regression models for classification purposes you should probably stop, and use a proper model instead ;-)
Comment: @ConjugatePrior Is logistic regression considered a regression method?  Since glm is a generalization of the linear model, cannot glm be considered regression too?
Comment: @ConjugatePrior I can think of a few cases where you'd want to fit a regression model for classification - for example, logistic regression (if you want to classify a binary variable).
Comment: @jkd.  Folks, this just is a terminology issue.  I was using regression in the original 'regression to mean' sense (and also the machine learning sense, see e.g. Bishop 2006) as a contrast to 'classification'. I agree GLMs are certainly regressions in the wider sense.  However, some people really do use linear regression to perform classification, which now looks rather old-fashioned.  *They* were the target of that offhand remark.
Answer: The "response" or "outcome" variables are commonly used terms.
Comment: Some fields talk of "criterion" variables.


`bGAMM` and other `GMMboost` algorithms for large data sets

Question: Regularized generalized linear mixed models and generalized additive mixed models are exactly what I need. I'm an R user, so it looks like bGAMM and maybe glmmLASSO are possibilities outside of doing my own implementation (which I don't have time to do for this project). My question is whether these packages can handle reasonably large numbers of observations (up to 150K) and random effects (over 500) along with, say, up to 1000 parameters. I'll be using a beefy Amazon instance for this use case.
Answer: Thanks to Fabian Scheipl, developer of package::spikeSlabGAM among other things, for pointing me toward mboost, which is more scalable than spikeSlabGAM, GMMBoost, and glmmLASSO, and includes all of the model specifications of these packages as subsets. It is more scalable because it does not use MCMC. So it is good for use cases when what you are looking for are point estimates, and you've got large-ish data.


Arrangement of 5 letters with a specific order

Question: how to calculate the arrangement of the 5 letters a,b,c,d,e when a,b,c must be in the written order: abcde,adbce,daebc,...
I know the answer is 20 by another way but want to know what's wrong with my following method:
OOaOObOOcOO so we need to select 2 place of from the 8 'o's ,that's the combination  c(8,2) and considering their order we have 2!*c(8,2) .
I know that's wrong but don't know why!
Comment: Surely, it is easier to select one of the five positions for the d and one of the remaining four places for the e, after which the a, b, and c can only be placed in one way.
Answer: It's wrong because the four choices
<code>dOaOObOOcOe
dOaOObOOceO
OdaOObOOcOe
OdaOObOOceO
</code>
all give the same final order, but your method counts them as distinct.
Comment: thanks,that's helpful. now how to calculate the exact number? I mean how to trim the redundancy
Comment: @mahyarp I would come at it from a different angle. For instance, start with `OaObOcO`, then pick one of the four spaces to put `OdO`, then pick one of the (now five) spaces to put an `e`. Or count the cases where `d, e`are adjacent separate from the cases where they are not. Or note that when taking all the the $5! = 120$ possible arrangements without restrictions, and then rearranging `a, b. c` within each of them to alphabetic order, they go neatly into groups of $3! = 6$ who have all become equal. So there are $\frac{120}6 = 20$ different groups.
Comment: thanks a lot , and please say if the modified answer of mine is correct.                      ( - )a( - )b( -)c( - ) , we can choose one of the double places and put 'e' and 'c' in it. that's c(4,1)*c(2,2)2!  or choose two of the double places and put the remaining letters in them separately that's c(4,2)*c(2,1)*c(2,1)*2! divided by 2!*2! for handling the repetition .
Comment: @mahyarp That lookos good. I would personally treat them as single places capable of holding two letters rather than double places, though. It gets rid of a lot of the unnecessary terms.


Usando Java junto com C

Question: Estou trabalhando num projeto de micro controlador. Meu fonte está todo em C entretanto gostaria de interagir com esse programa utilizando Java. Isto seria possível? Por exemplo: O programa em C executa comandos de controle do microcontrolador e por uma interface gráfica em Java gostaria de enviar os comandos para o programa em C.
Answer: Se você quer apenas fazer a comunicação entre dois programas, não há grande dificuldade se o dispositivo prover recursos para tal. Programas se comunicam o tempo todo e não importam em que linguagens eles estejam.
Mesmo que desejasse que código em Java se comunicasse como código em C no mesmo programa ainda seria possível através de JNI. Se a comunicação for muito difícil integrar o código em C ao Java pode ser uma alternativa. Mas já aviso que não é tarefa das mais fáceis.
Precisaria analisar se o controlador tem alguma forma de processos se comunicarem de forma eficiente. Eventualmente, em casos extremos seja necessário utilizar algum código em C junto ao Java para criar esta forma de comunicação provavelmente acessando memória de forma compartilhada (há diversas implicações nisto se o sistema operacional não ajuda).
Também poderia usar o protocolo TCP para fazer a comunicação desde que ambos estejam aptos para fazer esta comunicação. Isto depende de bibliotecas apropriadas nos dois programas ou código especializado.
Além disto é possível usar a troca de informações por arquivos se o controlador utiliza alguma forma de armazenamento.
Teria que analisar a documentação do controlador e/ou sistema operacional que roda nele além de verificar as bibliotecas disponíveis para ele nas duas linguagens. Mas se nada disto for possível, é melhor desistir de fazer isto no controlador.
Coloquei no GitHub para referência futura.
Comment: Vlw bigown. Vou dar uma pesquisada em JNI derrepente pode me ajudar.
Answer: É possível sim, verifique se o seu microcontrolador permite comunicação serial (USART) e simplesmente implemente a comunicação usando Java.
Existe uma classe muito boa que pode te auxiliar nesse processo chamada RXTX.
Essa é apenas uma das formas de se comunicar entre sistemas embarcados e demais dispositivos como um PC, por exemplo. Entretanto, de fácil implementação e amplo uso no mercado.

Usando Java junto com C


Hide records on click in the front end temporarily - rails 4.2

Question: Actually I want to hide the respective records when Hide link is been clicked.
Please refer the screen-shot for better understanding as shown below;

Before the link is clicked, hidden attribute is false as shown in the terminal as below;

After the link is clicked, it grabs the respective id and calls the hide method on the controller which is as shown below;

The problem is that it doesn't either hide that respective row or escape those values from the balance calculation and gets redirected to xvaziris_url.
I tried again and again in order to sort out this issue but unfortunately unable to get the desired result.
xvaziris_controller.rb
def index
        @xvaziris = Xvaziri.find_by hidden: false
        @xvaziris = Xvaziri.search(params[:search])

        respond_to do |format|
            format.js
            format.html
        end
    end

def hide
        @xvaziri = Xvaziri.find(params[:id])
        @xvaziri.hidden = true
        flash[:notice] = 'Xvaziri was successfully hidden.'
        redirect_to xvaziris_url
    end
end

routes.rb
resources :xvaziris do
        member do
            get :hide
        end
    end

_xvaziri.html.erb
<%= link_to "Hide", controller: "xvaziris", action: "hide", id: xvaziri, method: :get %>

Any suggestions are most welcome.
Thank you in advance.
Comment: Please post text as text whenever possible rather than as images.  Images have a great many shortcomings compared to plain text.
Comment: Thanks for your kind suggestion.
Answer: You don't save the result of your action. This code @xvaziri.hidden = true just sets the hidden attribute into true. You need to save the @xvaziri.
Try this solution.
def hide
  @xvaziri = Xvaziri.find(params[:id])
  @xvaziri.update_attribute(:hidden, true)
  flash[:notice] = 'Xvaziri was successfully hidden.'
  redirect_to xvaziris_url
end

UPDATE
I just made a clone of your application and find out the issue.
First of all find_by returns only first result as describet here
And second you are always getting xvaziris instances which has been found by your search method not by find_by
So, let's go through you controller's index action
def index
    @xvaziris = Xvaziri.find_by hidden: false
    # find first not hidden xvaziri and
    # store in into @xvaziris variable

    @xvaziris = Xvaziri.search(params[:search])
    # find xvaziris according to search performed
    # and store it into @xvaziris variable
    # so, at this place you always have xvaziris
    #that has been found but they may be hidden.

    respond_to do |format|
        format.js
        format.html
    end
end

Here are some suggestions
First of all implement some methods in Xvaziri model
class Xvaziri < ActiveRecord::Base

  scope :visible, -> { where(hidden: false) }
  # returns only visible xvaziri's

  def hide
    update_attribute(:hidden, true)
  end

  def show
    update_attribute(:hidden, false)
  end
end

Then in your controller:
def index
  @xvaziris = Xvaziri.search(params[:search]).visible

  respond_to do |format|
    format.js
    format.html
  end
end

def hide
  @xvaziri = Xvaziri.find(params[:id])
  @xvaziri.hide
  flash[:notice] = 'Xvaziri was successfully hidden.'
  redirect_to xvaziris_url
end

Show hidden xvaziri
# app/models/xvaziri.rb
scope :hidden, -> { where(hidden: true) }

# app/controllers/xvaziris_controller.rb
def hidden
  @xvaziris = Xvaziri.search(params[:search]).hidden
end

def unhide
  xvaziri = Xvaziri.find(params[:id])
  xvaziri.show
  flash[:notice] = "Xvaziri is now visible."
  redirect_to hidden_url
end

#app/views/xvaziris/hidden.html.erb

<%= notice %>

Listing Xvaziris

      ID
      Description

    <% if @xvaziris.any? %>
      <% @xvaziris.each do |xvaziri| %>

          <%= xvaziri.id %>
          <%= xvaziri.description %>
          <%= link_to 'unhide', unhide_xvaziri_path(xvaziri), method: :put %>

      <% end %>
    <% end %>

# config/routes.rb
resources :xvaziris do
  member do
    get :hide
    get :unhide
  end
end
get "hidden" => "xvaziris#hidden"

But it's not good to use :get methods to modify the model. Consider yo use :put method instead.
In my view example link uses :put method
Comment: Thanks for the reply.I tried but it is not working for me.What's next? As it is not taking hidden attribute as true...
Comment: Pretty weird. Could you please pass a log messages you are seeing with `update_attribute`?
Comment: Thanks for the reply.That's for sure.
Comment: Started GET "/xvaziris/125/hide?method=get" for 127.0.0.1 at 2016-08-01 10:49:25 +0400
Processing by XvazirisController#hide as HTML
  Parameters: {"method"=>"get", "id"=>"125"}
  Xvaziri Load (0.0ms)  SELECT  "xvaziris".* FROM "xvaziris" WHERE "xvaziris"."id" = ? LIMIT 1  [["i
d", 125]]
   (0.0ms)  begin transaction
   (0.0ms)  commit transaction
Redirected to http://localhost:3000/xvaziris
Comment: As I can see transaction has been made. Let's discuss that in chat https://chat.stackoverflow.com/rooms/info/118774/hide-records-on-click-in-the-front-end-temporarily-rails-4-2?tab=general
Comment: I'm really sorry for that delay. I just updated the answer and it works for me.
Comment: Excellent! It worked but how to show up the hidden records back.
Comment: Thanks for the reply.At present I can hide rows from index page and how do I access hidden rows that is how about routing?
Comment: For hide I have,                                                                                root 'xvaziris#index'

    resources :xvaziris do
        member do
            get :hide
        end
    end                                                                                but how about unhide?
Comment: Thanks. I my index page I have the hide links when I execute the link it is hidden but the confusion is where do I find the unhide link in order to get back that hidden row to appear in my root_path.
Comment: Consider `hidden` action in the controller. It displays hidden xvaziris
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/120197/discussion-between-muhammad-yaseen-and-retgoat).


Existence of NFA of a reverse of a language

Question: Hi, I'm really stuck on how to prove the following:
Given that $L$ is a language and $L'$ is a set such that $L' = \{w \mid w' \in L\}$ where $w$ is the reverse of $w'$, e.g., if $w = a a b$ then $w' = b a a$ (i.e. you flip the string around), prove that $L$ is NFA-recognizable if and only if $L'$ is NFA-recognizable
Comment: See also [this question](http://cs.stackexchange.com/questions/3251/how-to-show-that-a-reversed-regular-language-is-regular) on [cs.SE].
Answer: Reverse all transitions. Add a fresh starting state. Connect them to the old accepting state with $\varepsilon$-transitions. The old starting state now becomes accepting.
Answer: You can more or less 'reverse' the NFA, but we have to take care of $\epsilon$-transitions (where $\epsilon$ denotes the empty word), therefore assume that a NFA $A = (\Sigma, Q, \delta, S, F)$ without $\epsilon$-transitions is given with $L = L(A)$, that is $A$ recognizes $L$. Here

$\Sigma$ is the alphabet
$Q$ denotes the set of states
$\delta\colon Q \times \Sigma \to \mathscr P(Q)$ is the transition function.
$S \subseteq Q$ is the set of starting states
$F \subseteq Q$ is the set of final states

Now we define an automaton $A' = (\Sigma, Q, \delta', S', F')$ by - just reversing the transitions:

$S' := F$, $F' := S$
$\delta'(q, a) := \{q' \in Q \mid q \in \delta(q', a)\}$

We will prove $L' = L(A')$ now:
$\subseteq$: Let $w = a_1 \ldots a_n \in L'$ be given, then $a_n \ldots a_1 \in L$, hence there is a sequence $q_0, \ldots, q_n$ of elements of $Q$ such that $q_0 \in S$, $q_n \in F$ and $q_{i+1} \in \delta(q_i, a_{n-i})$ for $0 \le i \le n-1$. But then $q_n, \ldots, q_0$ is a sequence of states such that $q_n \in S'$, $q_0 \in F'$ and $q_{n-i-1} \in \delta'(q_{n-i}, a_{i+1})$ by definition. Hence $A'$ recognizes $w$.
$\supseteq$: Let $w = a_1 \ldots a_n \in L(A')$, then there is a sequence $q_0, \ldots, q_n$ of states with $q_{i+1} \in \delta'(q_i, a_{i+1})$ and $q_0 \in S'$, $q_n \in F'$. This means by definition $q_n \in S$, $q_0 \in F$ and $q_i \in \delta(q_{i+1}, a_{i+1})$. This proves $a_n \ldots a_1 = w' \in L(A) = L$, hence $w \in L'$.
So if $L$ is NFA-recognizable, $L'$ is also. On the other side, if $L'$ is recognizable, then $L''$ is (by what we have proved), but $L = L''$, so we are done.
Comment: How do we take care of $\epsilon$ transitions when there are any in the original NFA?


How to show the least square estimator of $b$ has the minimum variance in the class $\sum a_iy_i$

Question: Consider the regression model:
$$
y_i=bx_i+e_i,1\leq i\leq n.$$
where $x_i$'s are fixed non-zero real numbers and $e_i$'s are independent random variables with mean zero and equal variance.
$(a)$Consider estimator of the form $T=\sum_{i=1}^{n}a_iy_i$(where $a_i$'s are non random real numbers)that are unbiased for $b$.Show that the least square estimator of $b$ has the minimum variance in this class of estimators.
Minimizing $\sum e_i^{2}=\sum(y_i-bx_i)^2$ $w.r.t$ $b$,we get the least square estimate of $b$ as, $$\hat b=\frac{\sum y_ix_i}{\sum x_i^{2}}$$
Now,$var(\hat b)=\frac{\sigma^{2}}{\sum x_i^{2}}$,where $\sigma^2=var(y),$I assume.
Now,I tried to minimize $Var(T)=\sum a_i^2\sigma^{2}$ subject to $\sum a_i=1$ and I am getting $a_i=\frac{1}{n}$,i.e.,$T=\bar y$ as the $BLUE$ of $b$.I don't know where I am making the mistake.May be,my approach is not right.
Comment: Have you heard of the Gauß-Markov theorem?
Comment: $T=\hat b$ in your problem, not $T=\bar y$.
Comment: @ChristophHanck: We know that least square estimate is the BLUE.Could you please tell me how can we find the BLUE from the class $\sum a_iy_i$ and show that it is equal to $\hat b?$
Answer: Your minimum variance problem is:
$$ \begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $a_i$)} &  \mathrm{Var}\left(  \sum_i a_i y_i \; \middle| \; \{x_i\}\right)  \\
 \mbox{subject to} & \mathrm{E}\left[\sum_i a_iy_i \; \middle|\;\{x_i\}\right] = b
 \end{array}
\end{equation}$$
Remember you can always substitute $y_i = b x_i + \epsilon_i$
$$ \begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $a_i$)} &  \mathrm{Var}\left(  \sum_i a_i (bx_i + \epsilon_i) \; \middle| \; \{x_i\}\right)  \\
 \mbox{subject to} & \mathrm{E}\left[\sum_i a_i(bx_i + \epsilon_i) \; \middle|\;\{x_i\}\right] = b
 \end{array}
\end{equation}$$
Simplifying, you can show this is an equivalent problem to:
$$ \begin{equation}
 \begin{array}{*2{>{\displaystyle}r}}
 \mbox{minimize (over $a_i$)} & \sum_i a_i^2 \\
 \mbox{subject to} & \sum_i a_i x_i = 1
 \end{array}
\end{equation}$$
Which will have a nice solution! You'll see that the solution $\mathbf{a}^*$ to the above optimization problem will make your estimator $T$ equal to $\hat{b}$.


Reading in space seperated dataset in R for frequent items

Question: I have a .txt file that consists of numbers separated by spaces.  Each row has a different amount of numbers in it.  I need to do market basket analysis on the data, however I can't seem to properly load the data (especially because there is a different number of items in each 'basket').  What is the best way to store the data so I can find the frequent items and then check for frequent items in each basket?
Example of data:
1 2 4 3 67 43 154
4 5 3 21 2
2 4 5 32 145
2 6 7 8 23 456 32 21 34 54

Comment: You can construct a matrix (user,product) with the number of products for the user in each cell
Answer: You should be able to input with readLines and then use lapply to separate into numerics. Assume that is in a file named txt.txt:
   dat <- lapply( readLines("txt.txt"), function(Line) scan(text=Line) )

The reason I didn't suggest read.table with fill=TRUE (which would give yiu something similar to the otehr answer that has appeared is that the column stucture was not  needed. unless there was information encoded in the position of those numbers. I'm wondering whether the might be additional information encoded in the individual lines such as regions or stores or some other entity as the source of particular numbered items. This would be the reason for keeping it in a list structure with an uneven count. You can get a global enumerations just with table:
table( unlist(dat) )

  1   2   3   4   5   6   7   8  21  23  32  34  43  54  67 145 154 456
  1   4   2   3   2   1   1   1   2   1   2   1   1   1   1   1   1   1

Comment: How would I extract which items in the table have a count greater than a certain threshold (for example 3)?
Comment: It depends on whether the line position matters. If you just want the number associated wtih items having higher counts then just `which(  table( unlist(dat) ) >= 3)` or `names( which(  table( unlist(dat) ) >= 3) )`. If you wanted the line positions then you might use lapply to get a listing by line.
Answer: my_text = '1 2 4 3 67 43 154
                    4 5 3 21 2
                    2 4 5 32 145
                    2 6 7 8 23 456 32 21 34 54'

my_text2 <- strsplit(my_text, split = '\n')

my_text2 <- lapply(my_text2, trimws)

my_text2           %>%
do.call('rbind',.) %>%
t                  %>%
as.data.frame()    %>%
separate(V1, sep  = ' ',into = paste('col_', 1:10))

col_ 1 col_ 2 col_ 3 col_ 4 col_ 5 col_ 6 col_ 7 col_ 8 col_ 9 col_ 10
1      1      2      4      3     67     43    154   <NA>   <NA>    <NA>
2      4      5      3     21      2   <NA>   <NA>   <NA>   <NA>    <NA>
3      2      4      5     32    145   <NA>   <NA>   <NA>   <NA>    <NA>
4      2      6      7      8     23    456     32     21     34      54


VueJS v-select submit

Question: Estou usando o V-SELECT para fazer um select estilo Chosen. Bom, ele funciona! Mas quando eu uso "ENTER" para inserir novos elementos, ele dá SUBMIT no form. Tem como eu dar submit apenas quando clicar no botão e não quando dar ENTER no input?
Código Exemplo CODE PEN
HTML

Vue Select

Try to add items in input using "ENTER"

  <form v-on:submit.prevent="submited()">
  <v-select multiselect :options="options"></v-select>
    <button type="submit">Submit</button>
  </form>

JS
Vue.component('v-select', VueSelect.VueSelect)

new Vue({
  el: '#app',
  data: {
    options: ["some", "thing", "another", "things"]
  },
  methods: {
    submited(){
      alert('submited!')
    }
  }
})

Answer: Esse select não parece ter como parar o evento de submir no DOM. Assim tens de colocar uma div por exemplo à volta do componente para poder parar o event.
Podes fazer isso assim:

    <v-select multiple :options="options"></v-select>

Codepen: https://codepen.io/sergiocrisostomo/pen/dVRZmx?editors=1010
Não conhecia esse componente. Eu uso muito a biblioteca iview.
Comment: Eita, curti essa `iview`
Comment: vou começar a usar tambem, eu estava utilizando o `Vuetify`
Comment: Legal @Sergio !! Obrigado pela ajuda e pela dica do iview :)
Comment: @RafaelAugusto eu também, por isso escolhi usar no trabalho :)

VueJS v-select submit


Frechet derivative of a nonlinear operator on Sobolev spaces

Question: Consider a simple nonlinear operator $F:W^{2,2}(0,1)\to L^2(0,1)$ where $F: w \mapsto w^3$. Assume $F$ is Frechet differntiable with derivative $DF_{w}h=3w^2h$. To prove it, we need to show:
$$\frac{\|(w+h)^3-w^3-3w^2h\|_2}{\|h\|_{2,2}}\to0$$
This boils down to
$$\frac{\|h^3+3h^2w\|_2}{\|h\|_{2,2}}\to 0$$
Sobolev embedding theorem of $W^{2,2}\subset \subset L^6 $ tells us that
$$\frac{\|h^3\|_2}{\|h\|_{2,2}}\to 0$$
But the last part still remains to prove; that is; showing that
$$\frac{\|3h^2 w\|_2}{\|h\|_{2,2}}\to 0 \quad \forall w\in W^{2,2}$$
Please comment on this!
Comment: Shouldn't you be showing that $$\frac{\|(w+h)^3-w^3-3w^2h\|_{2}}{\|h\|_{2,2}}\to0\, ?$$
Comment: yep, my bad, thanks!
Answer: You can use the same embedding $W^{2,2}\hookrightarrow L^6$:
$$
\|h^2w \|_{L^2} \le \|h\|_{L^6}^2 \|w\|_{L^6} \le \|h\|_{W^{2,2}}^2\|w\|_{W^{2,2}}.
$$
Comment: How do you drive the first inequality? How do you split it into two norms?
Comment: H\"older inequality


Jquery, .val() não pega o texto do input

Question: Eu tenho um seguinte código:
INPUT

                <input id="contact-input" type="text" id="search" class="form-control input-search-doc" placeholder="Documento" required>

                    <button class="btn btn-default btn-search-doc" type="button">

                </button>

AJAX
$(".btn-search-doc").on("click",function(){
    var title = $(this).find('input.input-search-doc').val();
    alert(title);
    $("#result").html("");

    $.ajax({
        type:"post",
        url:"../connect/post/select.php",
        data:"title="+title,
        success:function(data){
            $("#result").html(data);
            $("#search").val("");
         }
      });

});

Ele deveria pegar o texto dentro do input e enviar via Ajax para meu select, mas ele não consegue pegar o texto dentro do input "input-search-doc", sempre retorna para mim no var_dump : string 'undefined' (length=9)
Alguém tem uma ideia porque ele não está pegando valor nenhum?
Comment: Seu seletor deveria ser assim:   var title = $('.input-search-doc').val();  não faz sentido nenhum usar o this neste caso, só faria se fosse um form, e você fosse dar um submit
Comment: Obrigado era isso mesmo.
Answer: Simplesmente use:
$('#contact-input').val();

Ou
$('.input-search-doc').val();

Comment: Para pegar um componente passando o ID do controle no seletor, utilize "#" como no exemplo do @Jonathan. Nada mais.
Answer: Olá, tudo bem?
Acredito que o problema está quando você instancia a variável 'title':

$(".btn-search-doc").on("click",function(){
    var title = $(this).parents('.input-group').find('input.input-search-doc').val();
    alert(title);

});

                <input id="contact-input" type="text" id="search" class="form-control input-search-doc" placeholder="Documento" required>

                    <button class="btn btn-default btn-search-doc" type="button">

                </button>

Para vc manter o contexto onde está englobado seu botão utilizando o $(this), é necessário utilizar o ".parents('.input-group')" para mudar o contexto do botão para o div que contém o botão e o campo de entrada, para somente então utilizar o ".find()" para achar o campo.
Ou
Já que você está definindo um identificador único pro input, vc poderia buscar o mesmo assim: $('#contact-input').


using jackson instead of DTO in POST mapping?

Question: I have the following one to many relationship :
public class Product {
        @Id
        @SequenceGenerator(name = "product_id_seq", sequenceName = "product_id_seq")
        @GeneratedValue(strategy= GenerationType.SEQUENCE,generator = "product_id_seq")
    private Long pid; // initiate it for just a random value in order to hanlde hibernate bug

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="manufacturer",referencedColumnName = "id")
    @JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
    @JsonIdentityReference(alwaysAsId=true)
    private Manufacturer manufacturer;

   private String name;
   ......more data members...

and manufacturer :
public class Manufacturer {
    @Id
    @SequenceGenerator(name = "manufacturer_id_seq", sequenceName = "manufacturer_id_seq")
    @GeneratedValue(strategy=GenerationType.SEQUENCE,generator = "manufacturer_id_seq")
    private Long id;
    private String name;
    private String country;
    @OneToMany(mappedBy = "manufacturer",fetch = FetchType.LAZY,cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Product> products;

}

my POST body contain the following json :
{
    "name":"chocolate",
    "manufacturer": 2,

}

Right now I'm using DTO and mapping function to map the productDTO to a product:
public class ProductCreationDTO {
    private String name;
    private Long manufacturer;
}

private Product mapProductCreationDTOtoProduct(ProductCreationDTO pcd)
{
    Product p = modelMapper.map(pcd,Product.class); // maps fields with same name that arent nested(like manufacturer)
    Optional<Manufacturer> o = manufacturerService.getManufacturer(pcd.getManufacturer());
    o.ifPresent(m->p.setManufacturer(m));
    return p;
}

I suceeded doing this converstion in my get calls for objects by adding those 2 annotations above the manufacturer obj in the Product class:
@JsonIdentityInfo(generator= ObjectIdGenerators.PropertyGenerator.class, property="id")
@JsonIdentityReference(alwaysAsId=true)

Is there a way to using jackson (annotations) to map the post json into a product object (deserialize ) the same it happens during rest get calls(serialize) ?
Comment: I strongly advise not to use persistence entities for data transferring layer. You should stick with the DTO and using conversions between DTOs and entities, or even better between DTO and domain models and between domain models and entities to have cleaner architecture.
Comment: Yeah I guess in aspect of architecture it will far better. Thanks !
Answer: So instead of using the objectMapper and the DTO I changed the json that I passed to the following :
{
    "name":"chocolate",
    "manufacturer": {"id":2}

}

Thanks to @Lkopo for the tip - In aspect of architecture it is better to create DTOs in order to transfer data.
Full example with DTO - https://github.com/marielcherkassky/simple_spring_boot_jpa_project


Are integrable, essentially bounded functions in L^p?

Question: Given an arbitrary measure space (of possibly infinite measure), if $f \in L^1 \cap L^\infty$, then by Hölder's inequality, $f^2 \in L^1$, so $f \in L^2$.
Intuition suggests that $f \in L^p$ even for any $1 \le p \le \infty$ (since we have eliminated the only two things that can go wrong for $f$ to be in $L^p$; blow-up & non-decay).
This does not seem to follow from the common inequalities, hence my question: Is it true that
$L^1 \cap L^\infty \subset L^p$
in general, and if so how can I prove it? Many thanks in advance for any hints!
Comment: Note, the only interesting case is indeed if the measure is not finite. Otherwise $L^p\subset L^q$ for $p\ge q$
Answer: Yes, it's true. Let us define $A = \{x : \lvert f(x)\rvert > 1\}$. Then $\mu(A) \leqslant \int_A \lvert f(x)\rvert\,d\mu \leqslant \lVert f\rVert_1$, and hence
$$\int_X \lvert f(x)\rvert^p\,d\mu = \int_A \lvert f(x)\rvert^p\,d\mu + \int_{X\setminus A} \lvert f(x)\rvert^p\,d\mu \leqslant \lVert f\rVert_\infty^p\cdot \lVert f\rVert_1 + \lVert f\rVert_1 < \infty$$
since $\lvert f(x)\rvert^p \leqslant \lvert f(x)\rvert$ on $X\setminus A$.
Comment: Brilliant, both brief and comprehensible. Thanks!
Answer: More generally we have a family of interpolation inequalities: assume $1\leq q \leq r \leq p \leq \infty$ with
$$
\frac1r = \frac\theta q + \frac{1-\theta}{p},\qquad \theta\in(0,1).
$$
Then, if $f \in L^q \cap L^p$ we have
$$
f\in L^r \qquad\text{and}\qquad
\| f\|_r \leq \| f \|_q^{\theta} \, \| f\|_p^{1-\theta}.
$$
To prove this, just write
$$
\int_X |f(x)|^r \, d\mu = \int_X |f(x)|^{\theta r} \, |f(x)|^{(1-\theta)r}\, d\mu
$$
and then use Holder's inequality with exponents $a = q/(\theta r)$ and $a' = p/[(1-\theta)r] $.
Comment: We know that $f\in L^q\cap L^p$. When we write what you suggest, aren't we implicitly assuming that $f^\theta\in L^q$ and $f^{1-\theta}\in L^p$ in order to use Holder's inequality? How do we know this?
Comment: I may have answered my own comment: $$|f|^\theta|f|^{1-\theta}\le \theta |f|+(1-\theta)|f|=|f|.$$ This is just a generalized arithmetic/geometric mean inequality, right?


Sobolev space $H^s(\mathbb{R}), s<s_0$

Question: I read articles where they talk about functions being in  $H^s(\mathbb{R})$ for all $s<s_0$ for some specific $s_0$. For example in my case it is 1/2 or 3/2. I see this set can be written as an intersection of infinitely many Sobolev spaces. My question is: is that a Sobolev space? If so what would be the inner product in that space?
Comment: Actually, probably a _union_... And, no, not literally a Sobolev space in the simplest sense. So probably not Hilbert or Banach...
Answer: No, this is not a Sobolev space.
Take for example $f(x) = \mathcal{F}((1+|y|^2)^{-(s_0+1/2)/2})$ where $\mathcal{F}(u) = \hat{u}$ is the Fourier transform. Then
$$
∫_{\mathbb{R}}|\widehat{f}(x)|^2 \,(1+|x|^2)^s \,\mathrm{d}x = ∫_{\mathbb{R}} (1+|x|^2)^{s-s_0-1/2}\,\mathrm{d}x
$$
which is finite if and only if $s<s_0$. So $f∈H^s$ for every $s<s_0$. So if there is a Sobolev space $H^{s_1}$ such that $H^{s_1} = \bigcap_{s<s_0} H^s$, then $s_1<s_0$. But then we can take $s'\in(s_1,s_0)$ and $g(x) = \mathcal{F}((1+|y|^2)^{-(s'+1/2)/2})$ is in $H^{s_1}$ but not in $\bigcap_{s<s_0}H^s$.
Therefore, $\bigcap_{s<s_0} H^s$ is not a Sobolev space.

Actually, you have some more refined spaces $B^s_{2,q}$ called Besov spaces verifying
$$
H^{s_0} = B^s_{2,2} ⊂ B^s_{2,\infty} \subset \bigcap_{s<s_0} H^s ⊂ H^{s_0-\varepsilon}
$$
but even here I think the inclusion is strict.
Comment: The spaces $B^s_{p,q}$ are called Besov spaces. They are an extension of Sobolev spaces $W^{s,p}$, the index $q$ being the additional refinement.

Actually, if you want a Hilbert space more precise than $∩_{s<3/2} H^s$ *for the particular function* $u = e^{-|x|}$, you can take the norm
$$
∫ |\hat{f}(x)|^2\,\frac{(1+x^2)^{3/2}}{1+\ln(1+|x|)^2}\,\mathrm{d} x
$$
(I think it defines a Hilbert space), but there might be other functions in $∩_{s<3/2} H^s$ that are not in this space.
Comment: Thank you! So, to give a concrete example: u=exp(-|x|). Just computing the Fourier tranform, it tells you that it is in $H^s$ for all s<3/2.  So, I could say it is in H^1.49 for example, but I could not characterize u as part of a "optimal" Hilbert (instead of asking it to be Sobolev) space other than by making s closer to 3/2?
Comment: Yes, this function is actually in $B^{3/2}_{2,\infty}$, which is a bit more precise than $\bigcap_{s<3/2} H^s$, which is a Banach space but I think it is not a Hilbert space. You can also look at the non $L^2$ setting and say that this function is Lipshitz continuous (Which is the Sobolev space $C^{0,1} = W^{1,\infty}$), but once again, this is not a Hilbert space.
Comment: @ LL 3.14 Thank you again. A Banach space would work for me. Would you mind telling me the name of the B space you mention so I can look it up please?
Comment: @ LL 3.14 If I can still pull your chain: that norm is really a good idea. I would not mind having a little bit more, as long as the functions I want are in. So, I would have to check the Cauchy property, right? Also, I read a little about Besov spaces. Is there a way to say if a given function is in a Besov space. Also, why choose $q=\infty$? Thank you again.
Comment: So the reason for the $\infty$ index is that this is the largest Besov space included in $\bigcap_{s<s_0} H^s$ since
$$
B^{s}_{2,1} ⊂ B^{s}_{2,p} ⊂ B^{s}_{2,2} = H^s ⊂ B^{s}_{2,q} ⊂ B^{s}_{2,\infty} ⊂ \bigcap_{s<s_0} H^s
$$
for any $1≤ p≤ 2≤ q≤ \infty$
Comment: To compute the Besov norm, you can use the Littlewood-Paley decomposition (you can look at whatever book on Besov spaces, for example "Fourier Analysis and Nonlinear Partial Differential Equations" by Bahouri, Chemin & Danchin, or https://webusers.imj-prg.fr/~isabelle.gallagher/littlewoodpaley.pdf Definition 6.2.1. Then you get
$$
\|\Delta_j e^{-|x|}\|_{L^2} ∼ 2^{-3j/2}
$$
so that
$$
\|e^{-|x|}\|_{B^{3/2}_{s,\infty}} = \|2^{3j/2}\|\Delta_j e^{-|x|}\|_{L^2}\|_{\infty} < C
$$
Comment: @LL3.14 I am going through the stated book, however I find the book quite terse but the linked note proved to be very helpful in following the book. Do you know where can I access the remaining notes in this series, as it is chapter 6?

Sobolev space $H^s(\mathbb{R}), s<s_0$


How can I use material symbols in the search bar submit input?

Question: Background
I have a Drupal 10 site with a search bar that appears on the front page. Using this search bar redirects the user to a search page with a similar search bar, underneath which are the results. By default, both of these search bars just have the word "search".
I added the material-icons module and have successfully used material symbols on other parts of the site, but I do not know how to do this with the submit input in the search bar.
I found a similar question where the user added a fontawesome icon, and the solution (to use unicode) is not applicable for me.
Attempts
Attempt 1
I had a partially successful attempt by creating a module with a function that alters the search form:
<?php
use Drupal\Core\Render\Markup;

function search_bar_icon_form_search_block_form_alter(&$form, &$form_state) {
  // Set a placeholder for the search input
  $form['keys']['#attributes']['placeholder'][] = t('Search');

  // Replace the submit button with a Material Icon
  $icon_html = 'search';
  $form['actions']['submit']['#markup'] = Markup::create($icon_html);

  // Optionally, you can hide the original submit button text
  $form['actions']['submit']['#value'] = '';
}

This solution is not ideal because html input does not allow children, so instead, it places the span as the input's sibling. This requires CSS to pad the empty input and translate the  sibling over the empty button. This solution feels messy and overly complicated, so I wanted to explore better options before I go with this.
Attempt 2
I attempted to create a twig template in my custom theme to override the way that the search bar is being generated. To do this, I went into the core/modules/search/templates
to locate the default template, however there was only one template named search-result.html.twig which renders single search results, not the search bar itself. I cannot find the correct default twig template so I don't know what to name my custom one to override the styling.
My goal with this attempt is to replace the input with a button that can hold an icon if possible.
Summary
I feel like adding an icon shouldn't be so complicated and I must be missing something obvious. What is the best way to theme my search bar so that it shows a material symbols magnifying glass instead of the word "search"?
Answer: I found a way to do this in a relatively simple way.
This answer presumes you are using the Material Icons module, although I configured this module to use Rounded Material Symbols instead. I also created a custom module and form_search_block_form_alter to alter the search block form and add in this icon.
Custom Module
The form alter code is housed in a custom module comprised simply of an info.yml file, and the .module file containing the code.
.
└── web/
    └── modules/
        └── custom/
            └── search_bar_icon/
                ├── search_bar_icon.info.yml
                └── search_bar_icon.module

Once the module is created, make sure you install it in the Extend menu.
Form Alter
In order for an element to use a Material Symbol, it must be assigned a material-symbols class, and the content of the element must be the name of the required icon. In my case the search form-submit button already had "search" as the content, which is the name of the material symbol I wanted to use, so all I had to do was add the material-symbols-rounded class to this button.
<?php
use Drupal\Core\Render\Markup;

function search_bar_icon_form_search_block_form_alter(&$form, &$form_state) {
  // Set a placeholder for the search input
  $form['keys']['#attributes']['placeholder'][] = t('Search');

  // Add a class to the submit button
  $form['actions']['submit']['#attributes']['class'][] = 'material-symbols-rounded';
}

This resulted in the "search" text being replaced by the Material Symbols magnifying glass.


Populating the ForeignSecurityPrincipals Container?

Question: I'm trying to figure out how to populate the ForeignSecurityPrinipals container that is built-in to Active Directory. I have added foreign members to groups in my domain which is how I though this was populated, but the container still remains empty. Am I going about this the completely wrong way?
Answer: There's no manual intervention with the ForeignSecurityPrinicpals container required.
You don't say if the objects you're expecting to see come from domains foreign to your forest. You're only going to see objects created in that container for security principals from foreign domains / forests. Principals from other domains within your forest won't create entries in the ForeignSecurityPrincipals container (because information about them is already available in the Global Catalog).
Answer: From Mastering Active Directory for Windows Server 2003:

Foreign Security Principals Container When a trust is made with a domain outside of the
  tree, this container is used to hold references to objects from the outside environment that have
  been granted local permissions.

In my understanding this container would only populate when you have AD forest and trust between two domain from different trees.


How allow moderators to give a rebuke to user

Question: I'd like to allow moderators to give a rebuke for users. If user has e.g. 3 rebukes, the account of user should be removed or blocked - automatically or moderator should be inform about it.
Answer: You can use Flag module for that. You can set flag for users or posts created by users or something else as per your requirement.
Use rules to set rule on flagging & their counter value. There is very nice tutorial series on flag here by Johan Falk. You can see his rules tutorials to have better understanding about setting rules based on flagging.
Comment: Ok, thanks for your answer. I'll go through the tutorial.
Comment: Unfortunately, every page in tutorial you recommended isn't found.
Comment: Can't you access next tut by clicking on the given link under next items in right hand side?
Comment: You're right. I'm sorry.
Comment: I read about it, yet there is too much information. Could you give me some directions how can I do it with Flag module.


Law of total probability and conditioning on multiple events

Question: Pearl et al. "Causal Inference in Statistics: A Primer" (2016) p. 56-57 includes the following equations (I have omitted a subscript $_m$ to $P$ as it plays no role in my question):
\begin{align}
&P(Y=y|X=x)= \\
& \sum_{z} P(Y=y|X=x,Z=z)P(Z=z|X=x) \tag{3.3}=\\
& \sum_{z} P(Y=y|X=x,Z=z)P(Z=z). \tag{3.4}
\end{align}
The first equality is said to be obtained using the law of total probability; the second is said to use independence between $Z$ and $X$. Let me also add
$$
P(Y=y|X=x) =\\
 \sum_{z} P(Y=y|X=x,Z=z)P(Z=z) \tag{3.5}
$$
just to have a reference for this particular equality.

I am a little uncomfortable with the equations $(3.3)$ and $(3.4)$. Here is how I approached the problem myself. If conditioning on $X=x$ were omitted, we would have
$$
P(Y=y) = \sum_{z} P(Y=y|Z=z)P(Z=z)
$$
and that would be a straightforward application of the law of total probability. But we have the conditioning on $X=x$. First, let us treat $Y=y|X=x$ as an event $A$$\color{blue}{^*}$ and then
$$
P(A) = \sum_{z} P(A|Z=z)P(Z=z)
$$
thus directly producing eq. $(3.5)$ when $Y=y|X=x$ is substituted back for $A$. On the other hand, we could partition $Y=y$ by $Z$ first and only then condition on $X=x$, thus
$$
P(Y=y|X=x) = \\
\sum_{z} P(\color{red}{(}Y=y|Z=z\color{red}{)}|X=x)P(Z=z|X=x),
$$
i.e. eq. $(3.4)$. It appears to me at this point that I got eq. $(3.4)$ without invoking independence between $Z$ and $X$, but probably I am missing something.
Questions

Did I indeed prove eq. $(3.4)$ without invoking independence between $Z$ and $X$? If not, what did I miss?
Are there cases where eq. $(3.5)$ does not hold? (Perhaps if $Z$ and $X$ are dependent?) If so, why?

$\color{blue}{^*}$Pohoua noted that one cannot define an event like this. Let us just define $A:=(Y=y|X=x)$ without calling it an event. Not that that should make the following expressions correct, but at least an incorrect use of a term is avoided.
Comment: This seems relevant:  https://stats.stackexchange.com/questions/406950/confused-about-conditional-counterparts-to-traditional-probability-laws/407142#407142
Comment: I edited to change the layout of some (long) formulas, since, at least on my screen, they were put in scroll boxes, making them difficult to read.
Comment: Thank you, @kjetilbhalvorsen.
Answer: Your purported proof of $(3.4)$, without using independent of $Z$ and $X$, is not correct.  It is not valid to form an event that includes a condition, because that condition then escapes the other probability operator in the law of total probability.  In fact, the equation is not true in general (i.e., without the independence condition), as can be seen by considering the counterexample with joint mass function:
$$\mathbb{P}(X=x,Y=y,Z=z) = \begin{cases}
\tfrac{1}{2} & & \text{if } x = 0, y = 0, z = 1, \\[6pt]
\tfrac{1}{2} & & \text{if } x = 1, y = 1, z = 0, \\[6pt]
0 & & \text{otherwise}. \\[6pt]
\end{cases}$$
In this case, we have:
$$1 = \mathbb{P}(Y=x|X=x) \neq
\sum_z \mathbb{P}(Y=x|X=x, Z=z) \cdot \mathbb{P}(Z=z) = \tfrac{1}{2}.$$
Comment: Thank you, Ben.
Answer: I think there is a mistake in your proof when you define the event $A$ as $Y=y|X=x$, this definition does not make sense. You cannot include conditionality in an event (what would be a realization of such an event?), you can just talk about probability of an event conditionally to some other event. Conditioning on an event $X=x$ defines new probability measures, but does not define new events.
The proof of equation $(3.3)$ is just the application of the law of total probability, to which you add a conditionality on $X=x$ at every probability (it's the law of total probability applied to the probability measure $ P(.|X=x)$).
Then you need independence to say that the law of $Z$ and the law of $Z$ conditionally on $ X=x$ are the same.
Here is an example were $X$ and $Z$ are not independent. $X$ is the choice (with probabilities $1/2$) of a coin between a fair one and a biased one with two tails, $Y$ is the result of a toss of the chosen coin, and $Z=Y$. Then  equation $(3.5)$ does not hold.
$$
P(Y= tail | X= biased) =1
$$ and
\begin{aligned}
&\sum_z P(Y=tail|X=biased , Z=z) P(Z=z) \\
&= P(Y= tail| X=biased, Z= tail) P(Z=tail) \\ &+ P(Y = tail|X= biased, Z= head)P(Z= head) \\
&= 1\times P(Y = tail) + 0 \\
&=3/4
\end{aligned}
using that $Z=Y$.
I hope this helps.
Comment: Yes it should. I struggled with a very similar problem not so long ago, conditional probability may be quite tricky!
Comment: It really is, especially since I had hardly encountered similar exercises before. The probability courses I once took did not seem to offer many (any?) examples of this kind, and the probability section of Pearl's textbook does not consider them either.
Comment: Thank you for your answer! (+1)
Answer: \begin{align}
P(Y=y|X) &=E(1_{Y=y}|X) \\ &\overset{Tower\ property}{=}E\color{green}{\bigg(}E\color{red}{(}1_{Y=y}|X \color{red}{)}|(X,Z)\color{green}{\bigg)}
\\
&\overset{Tower\ property}{=}E\color{green}{\bigg(}E\color{red}{(}1_{Y=y}|(X,Z) \color{red}{)}|X\color{green}{\bigg)}
\\
&= E\color{green}{\bigg(}g(X,Z) |X\color{green}{\bigg)}
\\
&= \sum_{z} g(X,Z=z) P(Z=z|X)
\\
&= \sum_{z} E\color{red}{(}1_{Y=y}|(X,Z=z) \color{red}{)} P(Z=z|X)
\\
&= \sum_{z} P\color{red}{(}Y=y|(X,Z=z) \color{red}{)} P(Z=z|X)
\end{align}
So
\begin{align}
P(Y=y|X)=
 \sum_{z} P\color{red}{(}Y=y|(X,Z=z) \color{red}{)} P(Z=z|X)
\end{align} an hence
\begin{align}
P(Y=y|X=x)=
 \sum_{z} P\color{red}{(}Y=y|(X=x,Z=z) \color{red}{)} P(Z=z|X=x)
\end{align}
Detail:Tower Property Conditional_expectation
For sub-σ-algebras
$$\mathcal H_{1} \subset H_{2} \subset \mathcal F$$
 we have
 $$E(E(Y\mid \mathcal H_{2})\mid \mathcal H_{1})=E(E(Y \mid \mathcal H_{1})\mid \mathcal H_{2})=E(Y\mid \mathcal H_{1})$$.
In this situation $\mathcal H_{1}=\sigma(X) \subset \mathcal H_{2}=\sigma(X,Z) $
so
$$E(E(Y\mid \sigma(X,Z))\mid \sigma(X))=E(E(Y \mid \sigma(X))\mid \mathcal \sigma(X,Z))=E(Y\mid \sigma(X))$$
Comment: Thank you for your answer! I am currently unable to focus on this thread, but I will return to it (hopefully this week) and then will either upvote or ask for further clarification. Feel free to remind me if I do not.
Comment: @Richard Hardy , Feel free. It was a good question and enjoy it. it is enough .
Comment: So the expectation is taken over the distribution of $z$? These expectations get confusing when having to guess what is being averaged over, but you have made it clearer now.
Comment: I wonder how you got $$E\color{green}{\bigg(}g(X,Z) |X\color{green}{\bigg)} = \sum_{z} g(X,Z=z) P(Z=z|X).$$ I also wonder how you got $$E(E(Y\mid \mathcal H_{2})\mid \mathcal H_{1})=E(E(Y \mid \mathcal H_{1})\mid \mathcal H_{2}).$$
Comment: $E(E(Y\mid \mathcal H_{2})\mid \mathcal H_{1})=E(Y \mid \mathcal H_{1})$ By Tower property.

$E(\color{red}{E(Y \mid \mathcal H_{1})}\mid \mathcal H_{2})=\color{red}{E(Y \mid \mathcal H_{1})}$   because $\mathcal H_{1} \subset \mathcal H_{2}$ (Stability property since $E(Y \mid \mathcal H_{1})$ is $\mathcal H_{2} $measurable).
Comment: @Richard Hardy , For first question$E\color{green}{\bigg(}g(X,Z) |X=x\color{green}{\bigg)} = E\color{green}{\bigg(}g(x,Z) |X=x\color{green}{\bigg)} =\sum_{z} g(x,Z=z) P(Z=z|X=x)$
Comment: $\Longrightarrow$ $E\color{green}{\bigg(}g(X,Z) |X\color{green}{\bigg)} = \sum_{z} g(X,Z=z) P(Z=z|X)$
Comment: The expectation is taken over the distribution of $Z|X$. https://math.stackexchange.com/questions/3616279/by-definition-of-mathbb-ex-mid-sigmay-calculate-mathbb-ex-mid-y-y-w


How to check that cache is working on current page?

Question: Some modules silently turn off caching on certain pages. How is the easiest way to check that this is the case and also identify problematic module?
Comment: With Boost cache it's simple, there is a html comment at the bottom of the page. with other caches it's a bit more interesting.
Comment: @Mołot I'm primarily interested in standard Drupal cache, but instructions to other caches are also appreciate.
Answer: The easiest way is probably to inspect the HTTP response headers.
For example, with your browser DOM inspector tool ( e.g Chrome's "Network" tab )
Cache Miss
Here's some sample response headers from drupal.org showing a cache miss. In this case, using Varnish however core Drupal cache also sets similar headers.

Cache Hit
Here's one showing a standard Drupal cache hit:
Comment: But Drupal.org is behind Varnish, isn't it? I can't see X-Cache headers on my Drupal accessed directly. Or I would if the page I'm testing it with was cacheable?
Comment: @Mołot I can see the Varnish headers if I'm logged out.
Comment: For my Drupal 7 site I indeed see header `X-Drupal-Cache: HIT` but on my Drupal 6 site I don't see anything. It could be stripped by reverse proxy?
Comment: @user11153 yes, D6 doesn't appear to set the X-Drupal-Cache HTTP header there. However D7 does so in `_drupal_bootstrap_page_cache`
Comment: @DavidThomas So what check cache status in Drupal 6? Are there any alternatives? And thanks for instructions to D7.
Comment: OK, I think that I found the solution for Drupal 6 also.
Answer: Adding cache headers to Drupal 6 default cache
Sadly, it's involving some core hacking.
In file includes/bootstrap.inc change lines from
      // If there is a cached page, display it.
      if ($cache) {
        drupal_page_cache_header($cache);
        // If the skipping of the bootstrap hooks is not enforced, call hook_exit.
        if ($cache_mode != CACHE_AGGRESSIVE) {
          bootstrap_invoke_all('exit');
        }
        // We are done.
        exit;
      }
      // Prepare for non-cached page workflow.
      drupal_page_header();
      break;

to
      // If there is a cached page, display it.
      if ($cache) {
        header('X-Drupal-Cache: HIT');
        drupal_page_cache_header($cache);
        // If the skipping of the bootstrap hooks is not enforced, call hook_exit.
        if ($cache_mode != CACHE_AGGRESSIVE) {
          bootstrap_invoke_all('exit');
        }
        // We are done.
        exit;
      }
      // Prepare for non-cached page workflow.
      header('X-Drupal-Cache: MISS');
      drupal_page_header();
      break;

and the rest of instructions it's exactly as in David's answer.


python3 argparse: checking combination of boolean arguments

Question: I have a set of boolean argparse options: --foo/--no-foo, --bar/--no-bar, --baz/--no-baz
My script makes sense only if at least one of those options is set to True.
I'd like to issue an Exception correctly processed by argparse, which will be managed as a command line error clear message.
But argparse.ArgumentTypeError is not a good option because it required the option as first argument to the constructor ... and my case is related to multiple options.
[Edit based on @00 comment:] The only solution I've got now is to raise, at the end of the command line processing, a ValueError is none of those options are set. But it is an exception, which is not user friendly.
What is the way to proceed in such cases?
Thanks a lot.
P.S.: Code to generate those options:
    @classmethod
    def addBoolean(
        cls, argumentParser, dest, helpTrue, helpFalse,
        default=None
    ):
        """Adds a boolean option
        - argumentParser: A argparse.ArgumentHelper object
        - dest: The destination argument
        - helpTrue: The documentation of the True option
        - helpFalse: The documentation of the False option
        - default: Value to use if not required and not provided

        When no default (None) is provided, required is True

        The option will be --{dest} and --no-{dest}
        """
        # pylint: disable=too-many-arguments

        required = (default is None)
        group = argumentParser.add_mutually_exclusive_group(
            required=required,
        )
        group.add_argument(
            f'--{dest}',
            dest=dest,
            action='store_true',
            help=helpTrue
        )
        group.add_argument(
            f'--no-{dest}',
            dest=dest,
            action='store_false',
            help=helpFalse
        )
        if not required:
            argumentParser.set_defaults(**{dest: default})

Comment: You could always throw an exception/error message after the initial parsing, that is, code the check yourself outside of argparse. Perhaps less nice, but I'd say that it would work fine.
Comment: @00 Indeed, and that's what I do now. I've edited the question accordingly.
Comment: check out this answer: https://stackoverflow.com/a/6723066/6018688 which uses `parser.error` after a custom check past parsing.
Comment: Thanks @fabianegli. I have not seen this.
Comment: @MichaelHooreman You are most welcome. Hope it helps :-)
Comment: @fabianegli Perfectly ;-)
Comment: An alternative to the good answers above: you can also set one of the arguments to default true if the others are false. This is how we handle some of our arguments and works well for first-time users who don't necessarily know which methods to use. This might not be applicable in your use case though.
Answer: According to Python argparse: Make at least one argument required:
Flexible argparse errors can be created using parser.error("error message")
(see comments of @fabianegli in the question)


What does it mean "WebSockets (test): Failed by timeout"?

Question: I use Chromium on Ubuntu and I see an error "The server encountered an error. Please try to reload the page" in loop when I try to access websites like grammarly.com, slack.com. I have also tried to access it on Chrome, Firefox but results were same.

I have also done numerous self-diagnostic tests which was recommended by Grammarly-Support, but nothing seems worth doing. Here is the test result:

Here is the console result:

It's been a year, and since then I've been facing this problem. Please help me to understand what is wrong. Any suggestion on this would be highly appreciated.
Comment: Turn off WebSockets and try it, chrome.exe --disable-web-sockets http://stackoverflow.com/questions/5612158/how-can-i-temporarily-disable-websocket-in-google-chrome
Comment: Why to disable websockets?
Comment: Because I thought you were saying that was part of the problem.  I was only eliminating that part.
Comment: As far I know, websockets are supposed to be working fine as certain website uses websockets.
Answer: I've just observed a strange behaviour of app.grammarly.com.
In Firefox, when I'd disabled the following in proxy-setting:
FTP Proxy : Null
SOCKS Host : Null
I am able to access the app.grammarly.com successfully.
Answer: I get the same problem with Windows 10 and Chrome. I also contacted Grammerly and they said it was a connection issue at my end, second time they said it was my internet provider.
I find that it happens when I have multiple tabs open in Chrome. Closing most of the tabs and refreshing the page with Grammerly fixes the issue for me.
Hope this helps to find your solution.
-Tina
Comment: This is not the case, no matter what browser I chose I am getting the same error.
I am behind a proxy though it wasn't an issue before.


IP6tables blocks INPUT? can't connect with youtube API

Question: I thought to have a simple ipv6 firewall, but it turned out to be hell.
Somehow I really can't connect with any ipv6 from my machine unless I set INPUT Policy to ACCEPT. Below my current ip6tables
ip6tables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all      anywhere             anywhere           state RELATED,ESTABLISHED
ACCEPT     ipv6-icmp    anywhere             anywhere
ACCEPT     tcp      anywhere             anywhere           tcp dpt:http
ACCEPT     tcp      anywhere             anywhere           tcp dpt:https

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

If I try to connect with any ipv6 adres it doesn't work?
telnet gdata.youtube.com 80
Trying 2a00:1450:4013:c00::76...

OR
telnet gdata.youtube.com 443
Trying 2a00:1450:4013:c00::76...

When I set:
ip6tables -P INPUT ACCEPT

It works.. but then.. well then everything is open? what is going on?
Help?
Answer: You're probably missing the critical "stateful" rule:
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

You are also missing a rule to accept ICMPv6. Without ICMPv6, IPv6 simply does not function.
-A INPUT -p ipv6-icmp -j ACCEPT

For performance reasons, this should be among the earliest rules in your chain.
Comment: Noope that did not work.. i flushed the input rules and first added your rule:
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT
-A INPUT -i eth0 -p tcp --dport 443 -j ACCEPT
Comment: Oops, I forgot something. See the updated answer.
Comment: i updated my post in the top, but no result... i did both the things you mention, you can see the ip6tables -L  in the top


Transferring data from string into a Data View

Question: I am trying to transfer data from a string to a Data View control, could someone demonstrate how this could be done:
<code> private void testing_Click(object sender, EventArgs e)
        {
            // Get a ScheduledTasks object for the computer named "DALLAS"
            string machineName = (@"\\" + System.Environment.MachineName);
            ScheduledTasks st = new ScheduledTasks(machineName);
            // Get an array of all the task names
            string[] taskNames = st.GetTaskNames();
            st.Dispose();
        }
</code>
Comment: What data out of this set would you want to display?
Comment: @Frosty840 string name in taskNames
Answer: <code>for (int i = 0; i < taskNames.Count; i++)
{
    dataGridView1.Rows.Add(taskNames[i]);
}
</code>


WPF TabControl remove header padding?

Question: I am trying to make it so that I can perform a command when the user clicks on a TabItem header in my TabControl.
Here is my code:
      <TabControl TabStripPlacement="Left" BorderThickness="1,0,0,0">
        <TabItem Selector.IsSelected="{Binding IsGeneric, Mode=OneWay}">
            <TabItem.Header>
                <Button Content="Generic" Margin="0" Command="{Binding GenericSelected}"></Button>
            </TabItem.Header>
            <V:WasteEstimationGenericView DataContext="{Binding}"></V:WasteEstimationGenericView>
        </TabItem>
        <TabItem Selector.IsSelected="{Binding IsSTP, Mode=OneWay}">
            <TabItem.Header>
                <Button Content="STP" Margin="0" Command="{Binding STPSelected}"></Button>
            </TabItem.Header>
            <V:WasteEstimationSTPView DataContext="{Binding STPViewModel}"></V:WasteEstimationSTPView>
        </TabItem>
    </TabControl>

However I end up this something that looks like this:

Can someone please tell me how to make my TabControl headers consume all the available space in the TabItem Header? I originally wanted to do this using a label but it had a problem where if the user clicked towards the edge of the header it would not execute the command, I would still prefer this to using buttons, but the buttons allow the users to target where they click.
Answer: You will need to Modify the TabItem ControlTemplate, more specifically the ContentPresenter, setting the VerticalAlignment and HorizontalAlignment to Stretch and setting the Margin to what you are wanting, it is defaulted to 12,2,12,2.
Answer: Try this:
<TabControl TabStripPlacement="Left" BorderThickness="1,0,0,0" HorizontalContentAlignment="Stretch">

Comment: I created a test project based on your code minus the view bindings and the STP button width stretched to meet the Generic button width. Are you able to create a new window and just test with only the TabControl? I suspect a parent container of the TabControl is causing your problem.
Comment: It would take a lot of work to isolate just that control, but I am not after buttons of the same length, I am looking for them to fill the available space etc. Also setting the horizontal content alignment on the tab control did not seem to alter button dimensions.

WPF TabControl remove header padding?


Can a class inherit from both an Interface and a base class in Java?

Question: in .Net you can simply do this with the following code
Public class MyClass:ISomeInterface, SomeBaseClass

Can something similar be done in Java?
The code I have is as follows
public class InputHander extends OnTouchListener implements IControlHandler

However I get the error "no interface expected here" with regards to OnTouchListener
Comment: Yes of course. Have you gone through a basic Java tutorial, covering inheritance and interfaces?
Comment: Classes don't inherit from interfaces, they just implement them. You can extend (inherit from) a single class, but you can implement multiple interfaces.
Comment: `OnTouchListener` in an interface.
Comment: @coolblue2000 an interface cannot implement an interface. But it can extend other interfaces.
Comment: So if an interface implements another interface does that use the extends keyword instead?
Answer: Yes, use the extends keyword for class inheritance and implements for interface implementation:
public class MyClass extends SomeBaseClass implements SomeInterface

From your question edit, you should use extends in class declaration for class inheritance. In other words, a class can only extend from another single class, not from interfaces. Multiple class inheritance is not allowed. In case you want to implement an interface, use implements keyword only. So, your code would be:
public class InputHander implements OnTouchListener, IControlHandler

More info:

Java Tutorials: Inheritance
Comment: I get an error in Android Studio saying "No Interface expected here" with regards to the BaseClass.
Comment: @coolblue2000 it would be better if you edit your question and add your current code below the current content to get better help.
Comment: Well, you actually can extend from interfaces, but only in other interfaces.
Comment: Ah, that makes sense now as I copied the call from an interface not a class.... Java is not entirely clear at times....
Answer: Yes. It takes couple of seconds to try it out:
public class MyClass extends MyAbstractClass implements MyInterface

Answer: In order to prevent the pitfalls and complexities that arise if you have a language that supports multiple inheritance (e.g. C++), Java allows you to inherit from exactly one class (using extends and that class may or may not be abstract) and any number of interfaces (using implements).
So this is valid:
public class MyClass
    extends SomeBaseClass
    implements SomeInterface1, SomeInterface2

Java 8 will allow you to have default methods in interfaces but it's implemented carefully enough so as to avoid multiple inheritance ambiguities.
See Interface with default methods vs Abstract class in Java 8


how to create modal on load of page

Question: The following code is not working for me.
<code>$config = \Drupal::config('popup.settings');
$title = $this->t('Fnord');
$content = [
  '#type' => 'processed_text',
  '#text' => $config->get('content')['value'],
  '#format' => $config->get('content')['format'],
 ];
$options = [
  'dialogClass' => 'popup-dialog-class',
  'width' => '75%',
];

$response = new AjaxResponse();
$response->addCommand(new OpenModalDialogCommand($title, $content, $options));

return $response;
</code>
<code>(function ($, Drupal, drupalSettings) {
  $(document).ready(function () {
    var ajaxSettings = {
     url: '/popup/modal'
    };
    var myAjaxObject = Drupal.ajax(ajaxSettings);
    myAjaxObject.execute();
  });
})(jQuery, Drupal, drupalSettings);
</code>
I wrote the code basing on How do I display a modal dialog on page load, with working title and dialog options, using OpenModalDialogCommand?
It is giving me this JSON response but not opening the modal. Could you please help me with this?
<code>[{"command":"openDialog","selector":"#drupal-modal","settings":null,"data":"","dialogOptions":{"dialogClass":"popup-dialog-class","width":"75%","modal":true,"title":"Fnord"}}]
</code>
Answer: Let's say you have a custom module

In the module you have controller that provides a main page page where you want to show the modal popup (on page load).

You also need to add a custom library (in a <my_module>.libraries.yml) file. That library will point to a jasvascript file where you have javascript code mentioned above:

<code>my_modal:
  js:
    js/script.js: {}
  dependencies:
    - core/drupalSettings
</code>

To load the javascript code on the main page, you need to attach the library in the controller build array:

<code>$build['#attached']['library'][] = 'my_module/my_modal';
</code>

The content of the modal will provided by the ajax callback with the php code snipet showed above.
Here, as I said in my previous comment, you need to attach the core dialog ajax library:

<code>$attachments['library'][] = 'core/drupal.dialog.ajax';
$response->setAttachments($attachments);
</code>
Or, you can add it as a dependency in the custom library.

Last:  you need to provide the routing with the paths to main page and to ajax callback.
Comment: Thanks for responding but still I am getting the below response but not modal.  could you please tell me more on this so, I can check it rom my end "config object with the name popup.settings with correct structure. "
Comment: I added more details to my previous answer.

how to create modal on load of page


How to do a virus scan before post attachments in asp.net application

Question: How to do a virus scan before post attachments in asp.net application,when they find a virus on to give up post attachments,otherwise proceed to upload.
Comment: Did you check this question? http://stackoverflow.com/questions/1264891/server-side-virus-scan-on-a-file-for-windows ? Is server side but I doubt whether it is possible in client side.
Answer: You don't.
You scan it at the server, and delete it if it doesn't pass. There's no way to know if the client side has any AV software installed at all, and any result you got could be faked anyway. Do your checking on the server side instead where you have control.


Writing to Excel File using hash map

Question:
Hi,I'm getting exact values from hash map but my Apache POI Row and
Cell cannot set values properly expected result like that please let me
know.Thanks

I'm getting result hash-map like that:
{1=[ACSS Description1, ACSS Description2, ACSS Description3, SACSS Description4], 2=[11, 1, 4, 12]}

I'm expecting:

I'm getting result based on below code :

And that's my code:
   public void getList(List<ExportReport> listcriteria)
    {
        Map<Integer, List<String>> hashmap = new HashMap<Integer , List<String>>();
        List<String> listpropertyvalue =new ArrayList<String>();
        for(int i=0; i < listcriteria.size(); i++)
        {
            String strValue =listcriteria.get(i).getDescription();
            listpropertyvalue.add(strValue);
            hashmap.put(1, listpropertyname);
        }
           listpropertyvalue =new ArrayList<String>();
            for(int i=0;i<listcriteria.size();i++){

                String strInterValue=listcriteria.get(i).getExportIntervalId().toString();
                listpropertyvalue.add(strInterValue);
                hashmap.put(2, listpropertvalue);
            }
    }
    Set<Integer> keyset = hashmap.keySet();
    int rownum = 1;
  int cellnum = 0

    for(Integer key : keyset){

        Row row = worksheet.createRow(rownum++);

        Cell cell = row.createCell(cellnum);
        List<String> nameList = hashmap.get(key);
        for(Object obj : nameList)
        {
            if(obj instanceof Date)
            {
                cell.setCellValue((Date) obj);
            }
            else if(obj instanceof Boolean)
            {
                cell.setCellValue((Boolean) obj);
            }
            else if(obj instanceof String)
            {
                cell.setCellValue((String) obj);
            }
            else if(obj instanceof Double)
            {
                 cell.setCellValue((Double) obj);
            }
        }
           cellnum++;
            rownum=1;
    }
}

What am I doing wrong?
Comment: could you please show a snippet  of excel file that you expected
Comment: Just now I have updated my post .please let me know is  there any other way .Thanks
Answer: Sorry for this late reply.
Using you code, I created a working program that initialize a Excel file Writesheet.xlsx with 5 rows each row contains 5 Cells. Also, I created a List that contains 5 strings. Then I used  getList(List<ExportReport> listcriteria) method to write the content of this List on Writesheet.xlsx
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    static XSSFWorkbook workbook = new XSSFWorkbook();

    public void getList(List<String> listcriteria){
        Map<Integer, List<String>> hashmap = new HashMap<Integer , List<String>>();
        //create 5 key value pairs
        for(int i=0; i < 5; i++){
            hashmap.put(i, listcriteria);
        }
        System.out.println("hashmap : "+hashmap);
        Set<Integer> keyset = hashmap.keySet();
        int rownum = 0;
        int cellnum = 0;
        XSSFSheet sheet = workbook.getSheetAt(0);
        rownum = 0;
        for(Integer key : keyset){
            List<String> nameList = hashmap.get(key);
            for(String s : nameList){
                XSSFRow row = sheet.getRow(rownum++);
                Cell cell = row.getCell(cellnum);
                if(null!=cell){
                    cell.setCellValue(s);
                }
            }
            cellnum++;
            rownum=0;
        }
    }

    public static void main(String[] args) throws IOException {
        //Creation of List from an Array to test getList Method
        String[] ss = {"a","b","c","d","e"};
        List<String> listcriteria = new ArrayList<String>();
        listcriteria.addAll(Arrays.asList(ss));
        /***********************************************************/

        Test t = new Test();
        // Because I put 5 key values pairs in hashmap (see getList method), I create  Writesheet.xlsx
        // file that contains 5 rows each row contains 5 cell
        FileOutputStream out = new FileOutputStream( new File("Writesheet.xlsx"));
        XSSFSheet sheet = workbook.createSheet();
        for(int i = 0;i<5;i++){
            XSSFRow row = sheet.createRow(i);
            for(int j=0;j<5;j++)
            row.createCell(j);
        }
        workbook.write(out);
        out.close();//end creation of Excel file

        // I open Writesheet.xlsx file and write the data on it
        InputStream inp = new FileInputStream( new File("Writesheet.xlsx"));
        workbook = new XSSFWorkbook(inp);
        // listcriteria contains the data that will be written it on  Writesheet.xlsx
        t.getList(listcriteria);
        out = new FileOutputStream( new File("Writesheet.xlsx"));
        workbook.write(out);
        out.close();
        inp.close();
        System.out.println("Writesheet.xlsx written successfully" );

    }

}

Comment: Thanks for replied me .above code if I have change variable to value 1 it's working fine i don't want to use hardcode ? `hashmap.put(i, listcriteria); `
Comment: Thanks please look at my post now I have updated again as per expect result needed please let me know where I have made mistaken again ?
Answer: I just change the code on void getList(List<String> listcriteria) so the data

{1=[ACSS Description1, ACSS Description2, ACSS Description3, SACSS
  Description4], 2=[11, 1, 4, 12]}

will be put it on hashmap.The rest of code still the same and Voilà you get on Writesheet.xlsx what you want.
Map<Integer, List<String>> hashmap = new HashMap<Integer , List<String>>();
        String[] data1 = {"ACSS Description1", "ACSS Description2", "ACSS Description3", "SACSS Description4"};
        List s1 = Arrays.asList(data1);
        hashmap.put(1,s1);
        String[] data2 = {"11", "1", "4", "12"};
        List s2 = Arrays.asList(data2);
        hashmap.put(2,s2);

        System.out.println("hashmap : "+hashmap);
    //the rest of code it is the same

All the code with Change
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Test {

    static XSSFWorkbook workbook = new XSSFWorkbook();

    public void getList(List<String> listcriteria){
        Map<Integer, List<String>> hashmap = new HashMap<Integer , List<String>>();
        String[] data1 = {"ACSS Description1", "ACSS Description2", "ACSS Description3", "SACSS Description4"};
        List s1 = Arrays.asList(data1);
        hashmap.put(1,s1);
        String[] data2 = {"11", "1", "4", "12"};
        List s2 = Arrays.asList(data2);
        hashmap.put(2,s2);

        System.out.println("hashmap : "+hashmap);
        Set<Integer> keyset = hashmap.keySet();
        int rownum = 1;
        int cellnum = 0;
        XSSFSheet sheet = workbook.getSheetAt(0);
        for(Integer key : keyset){
            List<String> nameList = hashmap.get(key);
            for(String s : nameList){
                XSSFRow row = sheet.getRow(rownum++);
                Cell cell = row.getCell(cellnum);
                if(null!=cell){
                    cell.setCellValue(s);
                }
            }
            cellnum++;
            rownum=1;
        }
    }

    public static void main(String[] args) throws IOException {
        //Creation of List from an Array to test getList Method
        String[] ss = {"a","b","c","d","e"};
        List<String> listcriteria = new ArrayList<String>();
        listcriteria.addAll(Arrays.asList(ss));
        /***********************************************************/

        Test t = new Test();
        // Because I put 5 key values pairs in hashmap (see getList method), I create  Writesheet.xlsx
        // file that contains 5 rows each row contains 5 cell
        FileOutputStream out = new FileOutputStream( new File("Writesheet.xlsx"));
        XSSFSheet sheet = workbook.createSheet();
        for(int i = 0;i<5;i++){
            XSSFRow row = sheet.createRow(i);
            for(int j=0;j<5;j++)
            row.createCell(j);
        }
        workbook.write(out);
        out.close();//end creation of Excel file

        // I open Writesheet.xlsx file and write the data on it
        InputStream inp = new FileInputStream( new File("Writesheet.xlsx"));
        workbook = new XSSFWorkbook(inp);
        // listcriteria contains the data that will be written it on  Writesheet.xlsx
        t.getList(listcriteria);
        out = new FileOutputStream( new File("Writesheet.xlsx"));
        workbook.write(out);
        out.close();
        inp.close();
        System.out.println("Writesheet.xlsx written successfully" );

    }

}

And here the result
Comment: Thanks replied me same way I have done but my write excel file only showing cell[1] values(11,1,4,2)  not cell[0] values are empty .
Comment: Thanks replied , yes exactly same as .
Comment: As per reference[link](http://stackoverflow.com/questions/16186257/how-to-write-data-into-excel-file-in-order)I have tried but still expected result I cannot get it .
Comment: Sorry, I am Little confused. Do you want the result like you ask in your first post or it is a new question. Because if it is a new one please create a new post
Comment: please click new post [link](http://stackoverflow.com/questions/30135152/how-list-has-map-values-write-to-excel-file-using-apache-poi?noredirect=1#comment48380943_30135152)

Writing to Excel File using hash map


Where does the great audio quality of tracks released on YouTube come from?

Question: For example, I produced a track, then exported an mp3 or wav, but it is in no way comparable to the quality of the clips on YouTube.
Do the producers pass the track through some kind of equipment or what? In their clips there is such depth, etc.
I saw music on YouTube written in MilkyTracker and the audio in this video sounds awesome! But if I export audio from MilkyTracker, it will sound in no way comparable to that.
Comment: Superior audio engineering skills and superior musicianship.
Comment: Have to flag this as too broad. The steps to get "great audio quality" on recordings are literally the subject of years of study at universities and colleges of music. It's also heavily opinion-based, because you're asking how to create great art, and that will always depend on the individual artist.
Comment: Do you have examples of good sounding and bad sounding clips? I'd like to have a listen to see if it's really just about skilled use of MilkyTracker, or if I can hear compression or different soundfonts there.
Comment: They may also have better soundfonts than you. I've read that Waterflame has accumulated a huge soundfont collection over his years of composing (often EDM-like) music.
Comment: Are you using any Mastering software?
Comment: @Graham I worked in the industry and don't know any audio engineers who studied at a university or college. A handful of musicians did, but they were generally the less successful ones.
Comment: An interesting watch, about some of the techniques used to make music videos look better (although less about sound unfortunately) https://youtu.be/G025oxyWv0E
Comment: Years of practice and study, and no short cuts.
Comment: Youtube: "They cant call this audio bad quality if the good ones do not really exist" (They compress EVERYTHING, so everything's equally bad)
Answer: Quick answer - try running your output through a compressor.
Long answer - work on your composing, arranging and recording skills.  Get years of experience. Then try running your output through a compressor.
Answer: MilkyTracker is just a tool, and like any tool, the quality of the tool is less important than the skill and knowledge of the person using it. You could give a carpenter terrible, rusty old tools and they would make something far better than I could even with the very best tools available.
These things take a lot of practice to get good at, but everyone starts out not knowing what they're doing, and it's incredibly satisfying to see yourself improve over time!
There's a lot that goes into a good sounding track. It's a chain of things all the way from the input sound source to the output track. And like any chain, it's overall quality is limited by its weakest link.
The quality of the singer/instrument/thing-being-sampled is very important. Then there's the room it's recorded in. Does it add color, or is a neutral recording room that allows color to be added during the mix? What about the equipment used to record the sound? This means the choice of mic, the position of the mic, EQ, compression, and so on.
The mix itself is super important. A talented mix engineer adds so much to the recorded material. They're like the editor of a film. They can work magic, however what they can ultimately accomplish is limited by the quality of the recorded tracks or samples that they're working with.
Mastering is also important, although really only polishes a well crafted track, it's not going to create something great out of something mediocre.
The lovely thing is that everything you need these days can be obtained for far less than used to be the case. The very best equipment is obscenely expensive, but you can get good stuff at a fraction of the price. And in the right hands, you can get professional sounding results with (reasonably) inexpensive equipment.
Comment: +1  This has exactly nothing to do with YouTube or any other hosting/distribution service.  They simply regurgitate what they were given.
Comment: "MilkyTracker is just a tool" but it is not just another DAW. It's a tracker and it's MIDI-only. You say the quality of singer/instrument/thing-being-sampled is important but MT doesn't allow recording of audio or even sampling. You also say the EQ and compression is important, but MT doesn't have this.
Comment: @Dean, i am going to disagree with this some of this. I think in the case of recording the tools do matter a bit. While you may be able to create a good recording with cheap, crappy Mics, in a room that doesn't sound great, recording a crappy musical instrument, it is going to be a challenge. To create a great recording the better tools you use, from the room, the instruments, the mics, preamps, anything else you run the sound through, and ultimately the recording medium is going to make the recording more professional and sound higher quality. you can still have all that and make a bad record
Comment: @b3ko I don't think we disagree here. My point isn't that the quality of tools don't have an effect, it's that the quality is less important than the skill of the craftsman. All things being equal, a recording done using a U87 is going to sound better than a NT-2A. But if the NT-2A is being used by an experienced engineer they're going to be able to get a good enough recording with it. And if the U87 is being used by an amateur, it's probably still going to sound like an amateur recording.
Answer: Besides mastering and other thing related to creating the source audio, you'll also want to make sure that you aren't applying lossy compression to your audio before it gets uploaded - this won't make a big difference in most cases but can't hurt to get in the habit of. Whatever video and audio container format you're using to upload, you should make sure the audio track is stored as PCM data or something lossless - that way, when it's uploaded to YouTube, it'll only ever get compressed lossily once, by YouTube. That way, anyone hearing the audio on YouTube will only hear something that's been lossily compressed one time.
Personally I like to use .mkv containers - there are several programs out there, like MKVMerge, that let you drag and drop files (such as .wav files) straight into an MKV container, so that you know no compression is going on behind the scenes. I typically render my video out with lossy compression, then drop the video into a .mkv, then a .wav, then upload the .mkv. It works perfectly on YouTube.
Comment: Although this isn't bad advice, twice re-encoding with a gentle lossy codec is not going to have nearly as much influence on the way it sounds as mastering does. Never use 128 kb/s .mp3 or something like that, but 196 kb/s or more vorbis/aac/opus is for most purposes as good as lossless, even after 2× generation loss.
Comment: @leftaroundabout thanks for the addition - that's a great point. I tend to err on the side of being super careful, but yeah, I'll edit my answer to include the fact that it won't necessarily make a huge difference.