Reliably getting favicons in Chrome extensions, chrome://favicon?

Question: I'm using the chrome://favicon/ in my Google Chrome extension to get the favicon for RSS feeds. What I do is get the base path of linked page, and append it to chrome://favicon/http://<domainpath>.
It's working really unreliably. A lot of the time it's reporting the standard "no-favicon"-icon, even when the page really has a favicon. There is almost 0 documentation regarding the chrome://favicon mechanism, so it's difficult to understand how it actually works. Is it just a cache of links that have been visited? Is it possible to detect if there was an icon or not?
From some simple testing it's just a cache of favicons for pages you have visited. So if I subscribe to dribbble.com's RSS feed, it won't show a favicon in my extension. Then if I visit chrome://favicon/http://dribbble.com/ it won't return right icon. Then I open dribbble.com in another tab, it shows its icon in the tab, then when I reload the chrome://favicon/http://dribbble.com/-tab, it will return the correct favicon. Then I open my extensions popup and it still shows the standard icon. But if I then restart Chrome it will get the correct icon everywhere.
Now that's just from some basic research, and doesn't get me any closer to a solution. So my question is: Is the chrome://favicon/ a correct use-case for what I'm doing. Is there any documentation for it? And what is this its intended behavior?
Comment: I know that it's been a while since you asked it. Can you share how you were able to get the favicon for a page?
Answer: I've seen this problem as well and it's really obnoxious.
From what I can tell, Chrome populates the chrome://favicon/ cache after you visit a URL (omitting the #hash part of the URL if any). It appears to usually populate this cache sometime after a page is completely loaded. If you try to access chrome://favicon/http://yoururl.com before the associated page is completely loaded you will often get back the default 'globe icon'. Subsequently refreshing the page you're displaying the icon(s) on will then fix them.
So, if you can, possibly just refreshing the page you're displaying the icons on just prior to displaying it to the user may serve as a fix.
In my use case, I am actually opening tabs which I want to obtain the favicons from. So far the most reliable approach I have found to obtain them looks roughly like this:
chrome.webNavigation.onCompleted.addListener(onCompleted);

function onCompleted(details)
{
    if (details.frameId > 0)
    {
        // we don't care about activity occurring within a subframe of a tab
        return;
    }

    chrome.tabs.get(details.tabId, function(tab) {
        var url = tab.url ? tab.url.replace(/#.*$/, '') : ''; // drop #hash
        var favicon;
        var delay;

        if (tab.favIconUrl && tab.favIconUrl != ''
            && tab.favIconUrl.indexOf('chrome://favicon/') == -1) {
            // favicon appears to be a normal url
            favicon = tab.favIconUrl;
            delay = 0;
        }
        else {
            // couldn't obtain favicon as a normal url, try chrome://favicon/url
            favicon = 'chrome://favicon/' + url;
            delay = 100; // larger values will probably be more reliable
        }

        setTimeout(function() {
            /// set favicon wherever it needs to be set here
            console.log('delay', delay, 'tabId', tab.id, 'favicon', favicon);
        }, delay);
    });
}

This approach returns the correct favicon about 95% of the time for new URLs, using delay=100. Increasing the delay if you can accept it will increase the reliability (I'm using 1500ms for my use case and it misses <1% of the time on new URLs; this reliability worsens when many tabs are being opened simultaneously). Obviously this is a pretty imprecise way of making it work but it is the best method I've figured out so far.
Another possible approach is to instead pull favicons from http://www.google.com/s2/favicons?domain=somedomain.com. I don't like this approach very much as it requires accessing the external network, relies on a service that has no guarantee of being up, and is itself somewhat unreliable; I have seen it inconsistently return the "globe" icon for a www.domain.com URL yet return the proper icon for just domain.com.
Hope this helps in some way.
Comment: I've submitted a Chrome defect report in hopes of getting this problem addressed: https://code.google.com/p/chromium/issues/detail?id=131018
Comment: I did not know about the faviconURL property of tab! Unfortunately, I want something that works retroactively, without opening the page in tab. But this was helpful, and I do believe I can add this now, for future users. I just wish that it wasn't so complicated.
Comment: I tried this code and can't get it to work. When I call chrome.webNavigation.onCompleted.addListener(onCompleted); I get the error Uncaught TypeError: Cannot read property 'onCompleted' of undefined. I do have the permission "webNavigation" set in the manifest. Any idea why chrome.webNavigation seems to be undefined?
Comment: Not really sure why that would be happening... are you using manifest.json v2? Not using the v2 style was breaking my extension for a while recently. http://developer.chrome.com/extensions/manifest.html
Answer: As of Oct 2020, it appears chrome extensions using manifest version 3 are no longer able to access chrome://favicon/* urls. I haven't found the 'dedicated API' the message refers to.

Manifest v3 and higher extensions will not have access to the
chrome://favicon host; instead, we'll provide a dedicated API
permission and different URL. This results in being able to
tighten our permissions around the chrome:-scheme.
Comment: Some insight on the Chromium bug tracker: [Issue 104102: Create a new API permission for access to favicons](https://bugs.chromium.org/p/chromium/issues/detail?id=104102)
Comment: It seems like the best solution currently(for MV3) is to use the Google Favicon Snatcher: https://www.google.com/s2/favicons?domain=www.google.com
Comment: The problem with these is that, you cant implement this unless you want to lose your user base
Comment: New API example: https://stackoverflow.com/a/73415941/766850
Answer: In order to use chrome://favicon/some-site in extension. manifest.json  need to be updated:
"permissions": ["chrome://favicon/"],
"content_security_policy": "img-src chrome://favicon;"

Test on Version 63.0.3239.132 (Official Build) (64-bit)
Comment: Thanks for this. Here's relevant Chromium changes to allow extensions to access favicons: https://bugs.chromium.org/p/chromium/issues/detail?id=37802
Answer: chrome://favicon url is deprecated in favor of new favicon API with manifest v3.
// manifest.json
{
  "permissions": ["favicon"]
}

// utils.js
function getFaviconUrl(url) {
  return `chrome-extension://${chrome.runtime.id}/_favicon/?pageUrl=${encodeURIComponent(url)}&size=32`;
}

Source: https://groups.google.com/a/chromium.org/g/chromium-extensions/c/qS1rVpQVl8o/m/qmg1M13wBAAJ
Answer: I inspected the website-icon in Chrome history page and found this simpler method.
You can get the favicon url by  --
favIconURL = "chrome://favicon/size/16@1x/" + tab.url;

Don't forget to add "permissions" and "content_security_policy" to Chrome. (https://stackoverflow.com/a/48304708/9586876)
Answer: In the latest version of Chrome, Version 78.0.3904.87 (Official Build) (64-bit)) when tested, adding just img-src chrome://favicon; as content_security_policy will still show 2 warnings:

'content_security_policy': CSP directive 'script-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.

And:

'content_security_policy': CSP directive 'object-src' must be specified (either explicitly, or implicitly via 'default-src') and must whitelist only secure resources.

To get rid of them use:
"permissions": ["chrome://favicon/"],
"content_security_policy": "script-src 'self'; object-src 'self'; img-src chrome://favicon;"

Now you can use chrome://favicon/http://example.com without getting any errors or warnings.
Comment: I tried this solution but with no luck. When my content script tries to show some a tab's favicon it gets  `Not allowed to load local resource: chrome://favicon/https://www.google.com`. Tested on Chrome 88.0.4324.146
Answer: There is now the official documentation for Favicon Permission - Fetching favicons.
Add favicon to your permission
{
  "name": "Favicon API in a popup",
  "manifest_version": 3,
  ...
  "permissions": ["favicon"],
  ...
}

Access the favicon URL
For my simple case:
const favIconUrl = `chrome-extension://${chrome.runtime.id}/_favicon/?pageUrl=${encodeURIComponent(url)}&size=32`;

From their example:
function faviconURL(u) {
  const url = new URL(chrome.runtime.getURL("/_favicon/"));
  url.searchParams.set("pageUrl", u);
  url.searchParams.set("size", "32");
  return url.toString();
}

const img = document.createElement('img');
img.src = faviconURL("https://www.google.com")
document.body.appendChild(img);

This also works on Chromium Edge, it automatically transform chrome-extension://
into extension://
Note: when fetching favicons in content scripts, the "_favicon/*" folder must be declared as a web accessible resource. For example:
  "web_accessible_resources": [
    {
      "resources": ["_favicon/*"],
      "matches": ["<all_urls>"],
      "extension_ids": ["*"]
    }
  ]


How to get async await / promise based response

Question: So I have a code as below. There is a function that calls 2 axios requests to fetch some sample API data.
function fetch_records(){
  var api_url1 = "https://api.github.com/users/mojombo"
  var api_url2 = "https://api.github.com/users/defunkt"

  axios.get(api_url1)
    .then(function (response) {
      console.log('Data1 received: ',response);
    })
    .catch(function (error) {
      console.log(error);
    })

  axios.get(api_url2)
    .then(function (response) {
      console.log('Data2 received: ',response);
    })
    .catch(function (error) {
      console.log(error);
    })
}

And then I want to run this function fetch_records() as below
console.log('Script started');
fetch_records();
console.log('Script ended');

So that the output should be
Script started
... api response data ...
Script ended

But because Javascript is asynchronous, it always gives output as below
Script started
Script ended
... api response data ...

I belive async/await or promise is used to achieve the response I want but I am not sure how to use that exactly.
Comment: Since you already mentioned `async`/`await`, did you actually try using it? Yes, it is the right tool, learn about it! Please show us your approach and ask a specific question about what is not working.
Comment: this how JS async call works. If you want data then use promise.all a below
Comment: `Javascript is asynchronous` no it isn't ... but AJAX calls are
Answer: Just use async/await keywords, but remember JS always is JS.
async function fetch_records() { // a async function
  var api_url1 = "https://api.github.com/users/mojombo"
  var api_url2 = "https://api.github.com/users/defunkt"

  // waterfall way
  const data1 = await axios.get(api_url1); // await
  console.log('Data1 received: ', data1);

  const data2 = await axios.get(api_url2); // await
  console.log('Data2 received: ', data2);

  // parallel way
  // const [data1, data2] = await Promise.all([
  //   axios.get(api_url1),
  //   axios.get(api_url2)
  // ]);
  // console.log(data1, data2);
}

(async () => {
  try {
    console.log('Script started');
    await fetch_records(); // await a async function (Thenable object)
    console.log('Script ended');
  } catch(err) {
    console.error(err);
  }
})();

Answer: change your function to return promises:
function fetch_records() {
 var api_url1 = "https://api.github.com/users/mojombo"
 var api_url2 = "https://api.github.com/users/defunkt"

const promise1 = axios.get(api_url1)
.then(function (response) {
  console.log('Data1 received: ',response);
})
.catch(function (error) {
  console.log(error);
})

const promise2 = axios.get(api_url2)
.then(function (response) {
  console.log('Data2 received: ',response);
})
.catch(function (error) {
  console.log(error);
});

 return [promise1, promise2];

}

now use promise.all :
Promise.all(fetch_records()).then(function(response) {
  console.log(response[0], response[1]);
});

Answer:

function fetch_records() {
  var api_url1 = "https://api.github.com/users/mojombo"
  var api_url2 = "https://api.github.com/users/defunkt"

  return [
    axios.get(api_url1),
    axios.get(api_url2)
  ]
}

console.log('Script started');
Promise.all(fetch_records()).then(res => {
  console.log(res);
  console.log('Script ended');
})

Promise.all will wait till all promises are resolved, more about it
Answer: function fetch_records() {
  var api_url1 = "https://api.github.com/users/mojombo";
  return new Promise((resolve, reject) => {
    axios
      .get(api_url1)
      .then(function(response) {
        console.log("Data1 received: ", response);
        resolve(response);
      })
      .catch(function(error) {
        console.log(error);
        reject(error);
      });
  });
}

Use with Async/Await :
async function getData() {
   let data = await fetch_records();
   console.log("Fetch Records :: ", data);
}


Etale after base change

Question: If a morphism of schemes $f: X\rightarrow Y$ is etale after base change via an etale cover $Z\rightarrow Y$, is $f$ etale?
Comment: Yes. This follows from flat and unramified base change, which are both pretty simple.
Comment: Hi, could you point me to a reference for the theorems you are citing?
Comment: By locality of the condition of being etale, we can reduce to affine neighborhoods. Then it follows from [this](http://stacks.math.columbia.edu/tag/00U2)
Comment: Which of the many properties are you using?
Comment: I'm worried that people are going to read this too quickly and assume you mean to ask about whether being étale is preserved under base change.
Answer: If $Z\rightarrow Y$ is etale and surjective, then your desired result follows from the fact that being etale is etale-local on the base. More generally, a morphism $f : X\rightarrow Y$ is etale if and only if there exists an fpqc morphism $Z\rightarrow Y$ such that the pullback of $f$ by $Z\rightarrow Y$ is etale.
Here, fpqc means faithfully flat and quasi-compact. In particular, fppf morphisms (faithfully flat and locally of finite presentation) are fpqc, and surjective etale morphisms are fppf.
In short, the property of a morphism being "etale" is fpqc-local on the base, hence a fortiori fppf-local on the base, and hence a fortiori etale-local on the base.
In fact, a whole slew of properties of morphisms are fpqc, fppf, or etale local on the base.
The chapter on descent:
http://stacks.math.columbia.edu/tag/0238
gives a long list of examples of such properties.
Comment: Surjective etale morphisms are not necessarily fppf. However, surjective etale morphisms which are of finite presentation are fppf.
Comment: @AriyanJavanpeykar So it seems that according to http://stacks.math.columbia.edu/tag/021L , the "pf" in fppf stands for "locally of finite presentation", which makes sense to me, since if you have a family of fppf morphisms which are jointly surjective and hence form an fppf covering, then you'd want the map from the disjoint union of the family to also be an fppf covering. If your family is the family of all inclusions of all affine opens, then each inclusion is of finite presentation, but the induced map from the disjoint union is not quasi-compact, hence only locally of finite presentation.
Comment: @AriyanJavanpeykar does that make sense? Are there other sources where fppf actually means "flat of finite presentation"?
Comment: you're right. I was misremembering.

Etale after base change


Value of the input is not preserved when it is an HTML array

Question: Suppose, we have a form, containing 3 elements:

Checkbox with special name 'name[attached]', indicating that it is a part of an array of checkboxes.
Text input
Submit button

Code
<code>function bundles_test_form($form, &$form_state)
{
    $form['name[attached]'] = array(
        '#type' => 'checkbox',
        '#required' => false,
        '#attributes' => array('name' => 'name[attached]'),
        );

    $form['date'] = array(
        '#type' => 'textfield',
        '#required' => false,
        );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        );

    return $form;
}

function bundles_test_form_validate($form, &$form_state)
{
    if (isset($form_state['input']['name']['attached']))
    {
        if ($form_state['input']['date'] === '')
        {
            form_set_error("date", 'date is required');
        }
    }
}
</code>
Question
When the form throws an error, the checkbox must be checked, but it is not. When I change the name to "name" or anything that it not the array, it works correctly. So the error is caused by the non-standard name of the input.
Comment: why you are using name[attached] instead of name_attached?
Comment: @drupality Because in the real code there is an array of courses and a checkbox must be created to attach them. I don't know how many courses there are and is using an array of inputs.
Comment: Does `$form['name[attached]']` actually produce the markup you'd expect? I would have thought you'd have to explicitly set a `'#name' => 'name[attached]'` on the element itself
Comment: @Clive I explicitly set `'#attributes' => array('name' => 'name[attached]')`
Comment: @Clive Seems, that Drupal core doesn't support such array inputs
Answer: IMO this should work
<code>    function mm_definition_of_the_form($form, &$form_state) {
      //other code
      $form_state['rebuild'] = TRUE;

      if (isset($form_state['check_field'])) {
        //set default value of the field
      }
    }

    function mm_definition_of_the_form_validate(&$form, &$form_state) {
      //if is error
      $form_state['check_field'] = TRUE;
    }
</code>
Comment: So, no way to fix it without manually setting the value?
Comment: @user4035 AFAIC no.


Button Alignment with textbox

Question:
Hello I am unable to align the button with the above text box on right side. There is no effect to set the margin of the fieldset.
Below is my code.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <title>Document</title>

            <form role="form" action method="post" class="registration-form"
                style="width:482px;height:175px;background-color:aqua;margin-left:5px;margin-right:5px;"
            >

                    <fieldset>

                                <input type="text" name="form-email" placeholder="Enter Your email" class="form-email form-control" id="form-email">

                            <button type="button" class="btn btn-primary btn-next" style="margin-top:20px;margin-bottom:20px;margin-left:10px;padding-right:15px;width:100%">Get Started</button>

                    </fieldset>
                </form>

Please fix the problem and tell me when we set the margin of fieldset 10px from right side then it will br the boundary of fieldset of 110px for element? Is it ok or there is any other concept?
Comment: I would suggest you go through float once. And see the magic :)
Answer: try this

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

  <title>Document</title>

        <form role="form" action method="post" class="registration-form" style="width:482px;height:175px;background-color:aqua;margin-left:5px;margin-right:5px;padding-left: 20px;padding-right: 20px;">

          <fieldset>

                <input type="text" name="form-email" placeholder="Enter Your email" class="form-email form-control" id="form-email">

              <button type="button" class="btn btn-primary btn-next" style="margin-top:20px;margin-bottom:20px;padding-right:15px;width:100%">Get Started</button>

          </fieldset>

        </form>

Button Alignment with textbox


Como registra todas classes de validação com DryIoc?

Question: Como posso registra todas as minhas classes de validação usando DryIoc de forma dinâmica ?
Estou tentando da seguinte forma a baixo;
using DryIoc;
using FluentValidation;
using System;
using System.Linq;
using System.Reflection;

namespace TesteDryIoC.IU
{
    class Program
    {
        private static Type[] GetTypesInNamespace()
        {
            return Assembly.GetExecutingAssembly().GetTypes().Where(t => String.Equals(t.Namespace, "TesteDryIoC.IU.Validator", StringComparison.Ordinal)).ToArray();
        }
        static void Main(string[] args)
        {

            var container = new Container();

            var implementingClasses =
                Assembly.GetExecutingAssembly()
                .GetTypes().Where(type => String.Equals(type.Namespace, "TesteDryIoC.IU.Validator", StringComparison.Ordinal) &&
                     type.Name.EndsWith("Validator"));

            foreach (var implementingClass in implementingClasses)
            {
                    container.Register(implementingClass, Reuse.Singleton);
            }

            Cliente cliente = new Cliente();
            var validador = new ProvaderValidator<Cliente>().GetValidator(container);

            cliente.Nome = "";
            cliente.SobreNome = "Souza";
            cliente.Observacao = "teste";
            cliente.Email = "firstname.lastname@example.com";
            cliente.Idade = 32;
            cliente.DtInclusao = DateTime.Now;
            cliente.Ativo = true;
            cliente.Senha = "";

            var resultad0 = validador.Validate(cliente);

            foreach (var item in resultad0.Errors)
            {
                Console.WriteLine(item.ErrorMessage);
            }
            Console.WriteLine("--------------------------------------");

            Console.ReadKey();
        }
    }
}

Minhas classes de validação sempre terminam com Validator como mostrado a baixo.
using FluentValidation;

namespace TesteDryIoC.IU.Validator
{
    class ProdutoValidator : AbstractValidator<Produto>
    {
        public ProdutoValidator()
        {
            RuleFor(x => x.Nome)
               // Garante que a propriedade especificada não seja nula
               .NotNull().WithMessage("{PropertyName} deve ser preenchido");
        }
    }
}

Classe produto;
namespace TesteDryIoC.IU
{
    public class Produto
    {
        public string Nome { get; set; }
    }
}

Classe genérica para fazer o registro.
using DryIoc;
using FluentValidation;

namespace TesteDryIoC.IU
{
    public class ProvaderValidator<T> where T : class
    {
        public IValidator GetValidator(Container container)
        {

            var validador = container.Resolve<IValidator<T>>();
            return validador;
        }
    }
}

O Problema aqui é que quando entra na linha var validador = container.Resolve<IValidator<T>>(); ele retorna o seguinte erro;

DryIoc.ContainerException: 'Unable to resolve IValidator
  Where no service registrations found  and no dynamic registrations
  found in 0 Rules.DynamicServiceProviders and nothing in 0
  Rules.UnknownServiceResolvers'

O erro com mais detalhes;

DryIoc.ContainerException occurred   HResult=0x80131509
  Message=Unable to resolve IValidator Where no service
  registrations found   and no dynamic registrations found in 0
  Rules.DynamicServiceProviders   and nothing in 0
  Rules.UnknownServiceResolvers   Source=TesteDryIoC.IU   StackTrace:
  at DryIoc.Throw.It(Int32 error, Object arg0, Object arg1, Object arg2,
  Object arg3) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  11242    at DryIoc.Container.ThrowUnableToResolve(Request request) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  893    at DryIoc.Container.DryIoc.IContainer.ResolveFactory(Request
  request) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  851    at DryIoc.Container.ResolveAndCacheDefaultDelegate(Type
  serviceType, Boolean ifUnresolvedReturnDefault) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  557    at DryIoc.Container.DryIoc.IResolver.Resolve(Type serviceType,
  Boolean ifUnresolvedReturnDefault) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  475    at DryIoc.Resolver.Resolve[TService](IResolver resolver,
  IfUnresolved ifUnresolved) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\DryIoc\Container.cs:line
  5665    at TesteDryIoC.IU.ProvaderValidator`1.GetValidator(Container
  container) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\IProvaderValidator.cs:line
  11    at TesteDryIoC.IU.Program.Main(String[] args) in
  C:\Work\SolutionTest\TesteDryIoC\TesteDryIoC.IU\Program.cs:line 31
Answer: Foi meio complicado resolver esse problema, demorei bastante, mas aí está a solução que encontrei. Primeiro, criamos um método assim:
public static void RegisterGeneric<T>(Container container, IValidator<T> validator, IReuse reuse)
{
    container.RegisterDelegate(typeof(IValidator<T>), r => validator, reuse);
}

Depois de descobrir todos os seus Validators, dentro do foreach você usa reflection para instanciar a classe em questão e chame esse novo método:
foreach (var implementingClass in implementingClasses)
{
    dynamic validator = Activator.CreateInstance(implementingClass);
    RegisterGeneric(container, validator, Reuse.Singleton);
}

Observações
Como precisamos passar um objeto do tipo IValidator<T> que é genérico, não podemos fazer isso:
var validator = (IValidator<T>)Activator.CreateInstance(implementingClass);

e nem isso:
IValidator<T> validator = Activator.CreateInstance(implementingClass);

e se usarmos object, o código não compila porque não dá para passar um object como argumento em um método que espera um tipo genérico (nesse caso, IValidator<>). Por isso foi necessário "abusar" do dynamic.
Eu não costumo utilizar muito o dynamic, achei aceitável nesse caso pois você já garantiu que todos os tipos encontrados serão implementações da interface IValidator<>.
Comment: @MarconcilioSouza obrigado! Eu mesmo não conhecia, instalei aqui para fazer os testes, mas essa questão de registrar várias classes de uma determinada interface dinamicamente é algo que sempre acabamos precisando usar em frameworks de injeção de dependência. Vou continuar pensando aqui e qualquer coisa eu edito minha resposta com uma segunda alternativa.
Comment: Vlw, legal que conseguiu acha uma solução, se tratando de dryioc é uma coisa pouco inexplorada ainda, eu achei uma forma de fazer isso um pouco um pouco diferente. Caso não apareça algo melhor sinalizo sua resposta no final da recompensa.
Comment: postei a forma como fiz.
Answer: Eu encontrei uma forma diferente de fazer a injeção de dependência, estava pecando no meu foreach.
foreach (var implementingClass in implementingClasses)
{
        container.Register(implementingClass, Reuse.Singleton);
}

Foi necessário recuperar a interface (interfaceValidator) no loop e fazer a injeção usando ela.
public static class ContainerRegister
{
    public static Container getContainer()
    {
        Container container = new Container();

        var implementingClasses =
           Assembly.GetExecutingAssembly()
           .GetTypes().Where(type =>
           type.ImplementsServiceType(typeof(IValidator))
           );

        foreach (var implementingClass in implementingClasses)
        {
            var interfaceValidator = implementingClass.GetImplementedInterfaces()[0];
            container.Register(interfaceValidator, implementingClass);
        }

        return container;
    }
}

Como eu podia ter mais de uma classe com validação precisei alterar a forma como recuperar a classe correta.
public static class ProvadersValidator<T1> where T1 : class
{
    public static IValidator GetValidators(Container container, Func<IEnumerable<IValidator<T1>>, IValidator<T1>> criterio = null)
    {
        var validador = container.Resolve<Lazy<IEnumerable<IValidator<T1>>>>();
        var validadores = validador.Value;
        // TODO: função para selecionar qual usar
        if (criterio != null)
            return criterio(validadores);

        return validadores.First();
    }
}

Minha chamada ficou assim.
var container = ContainerRegister.getContainer();
//
var validadorDefout = ProvadersValidator<Produto>.GetValidators(container);

// buscar a validador especifico por propriedade
var validadorPropriedade = ProvadersValidator<Cliente>.GetValidators(container, (validadores) =>
{
    var validadorEncontrado = validadores.FirstOrDefault(x => x.CreateDescriptor().GetRulesForMember("Observacao").Any());
    return validadorEncontrado ?? validadores.First();
});


Creating a new variable for an outlier tag

Question: So, i am doing an outlier detection for a given data set. This is done in R by the way.
With the function boxplot.stats(x)$out i get information for the variable that i am detecting outliers for. Right? I get the observation's value that is considered an outlier.
What i want to do is create a new column in the data set which could be binary and put a 1 for the observations that are outliers and 0 for the ones that are not outliers.
Example:
Var1   Var2
asd    111
dsa    15
ssa    10
aas    9
dad    10
dda    95

Lets say observation 1 and 6 is detected as an outlier:
Var1   Var2
asd    111
dda    95

When i use:
outlier <- boxplot.stats(Var2)$out

I only receive the value of the outliers - i get 111 and 95 in the console.
So.. After i have detected this outliers i want to do the following:
Var1   Var2   Outlier
asd    111    1
dsa    15     0
ssa    10     0
aas    9      0
dad    10     0
dda    95     1

It is probably really easy to do, but i don't know how. Any ideas?
Answer: say your data.frame name is "data" and you have the values of outliers in "outlier"
then do this:
data$outlier = 0

data[which(data$Var2 %in% outlier),"outlier"] <- 1

Answer: If you have an outlier in your vector like
outlier <- c(111,90)

You can use within function to subset the binary variable by using ifelse function
within(df,outlier <- ifelse(df$var1%in%outlier,1,0))

var1 var2 outlier
1  111  asd       1
2   10  csd       0
3   11  pud       0
4   12  dud       0
5   90  kud       1

Answer: You could try the following:
require(data.table)

data <- fread('Var1   Var2
asd    111
dsa    15
ssa    10
aas    9
dad    10
dda    95 ')

outliers <- fread('Var1   Var2
asd    111
dda    95 ')

data[, Outlier:= ifelse(paste(Var1, Var2) %in% paste(outliers$Var1, outliers$Var2), 1, 0)]

Answer: You can use min() of the values in boxplot.stats(Var2)$out to compute the new variable via ifelse().
Assume data is your dataframe:
data$outliers <- ifelse(data$Var2 < min(boxplot.stats(data$Var2)$out), 0, 1)

This way you don't have to save the values of the outliers in another redundant object first.


Bash - Insert variables into string (command not found)

Question: I try to write a script for get some software's version from many servers.
But I get this error message, when i try.

bash: Postfix verzio:  MariaDB verzio:  OS verzio:  Java verzio: :
  command not found
bash: postfixverzio: command not found
Null message body; hope that's ok

#!/usr/bin/env bash

parancsok=$(<verziok_lekerdezese.sh)

while read line
do
    array=($line)
    echo "IP Addresses : ${array[0]} "
    ssh -t -t root@${array[0]} ${parancsok}
done < ipcimek_test.txt

Verziok_lekerdezese.sh:
postfixvr = $(postconf -d | grep -m 1 mail_version | cut -d= -f2)
mariadbvr = $(mysql -v)
osvr = $(cat /etc/redhat-release)
javavr = $(java -version)
hostname = $(cat /etc/hostname)

body = "Postfix verzio: $postfixvr MariaDB verzio: $mariadbvr OS verzio: $osvr Java verzio: $javavr"

echo $body | mail -s "Verziok - Szervernev: $hostname" firstname.lastname@example.com

exit

I apologize for my bad english.
Answer: You need to remove the spaces on both sides of equal char = (in the assignment statements) in your bash script. So, the lines:
postfixvr = $(postconf -d | grep -m 1 mail_version | cut -d= -f2)
mariadbvr = $(mysql -v)
osvr = $(cat /etc/redhat-release)
javavr = $(java -version)
hostname = $(cat /etc/hostname)

should be written as:
postfixvr=$(postconf -d | grep -m 1 mail_version | cut -d= -f2)
mariadbvr=$(mysql -v)
osvr=$(cat /etc/redhat-release)
javavr=$(java -version)
hostname=$(cat /etc/hostname)

This applies to all assignments including body = also.
Comment: OMG, not every hero wears a cape.
I am very grateful, thank you.
Comment: BTW, while you cannot put spaces around the `=` in an assignment, you *must* use them in a comparison (e.g. `if [ $a=$b ]` does not do what you think it does). Also, there are a number of other problems with your script, such as variable references that aren't wrapped in double-quotes. [shellcheck.net](http://www.shellcheck.net) will point out many of them.


How can I programmatically reset a user's password

Question: I have a native mobile application communicate with my drupal 7 site via services module.  I'd like to give users the ability to reset their password from the app.  Is there a way to initiate this process programmatically, so a an email is generated with a one time use token that expires in 24 hours?
Thanks
Answer: You can use the <code>_user_mail_notify()</code> function, along with a user object, to invoke the password reset email:
<code>// Load a user (admin in this case).
$account = user_load(1);

// Invoke the email. It will be queued along with other system mail to be sent during cron
_user_mail_notify('password_reset', $account);
</code>
A one time login URL with a 24 hour expiry is included by default with that particular email.
Comment: Sorry.  I haven't tested this yet.  The feature I was going to use it for was pushed back one release, so I'll be doing this sometime this month.  I imagine it'll work since it seems very straightforward.  Thanks.


How to flag pointless edits

Question: Is it possible to flag or report useless edits made by users who obviously take advantage of +2pts per edit? I saw this user 'exhibit' this behavior and checked the edits. They don't provide any useful information to the questions that were asked. I watched the user for a few hours over several question edits but he still continues doing it :)
Is there a way to stop him?
Answer: flag the post with i need of moderator intervention
write your detail summary then @amitbera and @marius can take proper action for that user
Comment: @daina it will not affect as its manual process and moderator has to do action manually so its just way to contact them
Comment: but wouldn't that affect the original author of the post?
Comment: understood! thank you!

How to flag pointless edits


Coil Kotlin Uri to Bitmap throws null pointer exception

Question: Trying to convert a Uri image file to Bitmap in Kotlin fails with a Null Pointer exception. How can I fix this?
var bitmap = remember {  mutableStateOf<Bitmap?>(null)}

LaunchedEffect(key1 = "tobitmap") {
    CoroutineScope(Dispatchers.IO).launch {
        bitmap.value = uriToBitmap(
            context,
            shoppingListScreenViewModel.state.value.imageUri
        )
    }
}

Image(
    bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
    contentDescription = ""
)

private suspend fun uriToBitmap(context: Context, uri: Uri?): Bitmap {

    val loader = ImageLoader(context)
    val request = ImageRequest.Builder(context)
        .data(uri)
        .allowHardware(false) // Disable hardware bitmaps.
        .build()

    val result = (loader.execute(request) as SuccessResult).drawable
    val bitmap = (result as BitmapDrawable).bitmap

    val resizedBitmap = Bitmap.createScaledBitmap(
        bitmap, 80, 80, true);

    return resizedBitmap
}

Answer: bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here

not-null assertion is not a good way to handle this.
Your possible options are either display Image with
bitmap?.value?.asImageBitmap()?.let{ imageBitmap->
   Image(...)
}

and wait for bitmap to be created while you display nothing
or display preferably a Composable for loading or Image with placeholder.
if(bitmap.value!= null) {
  Image(...)
} else {
 // Your loading Composable
}

Another option is to use SubcomposeAsyncImage which has slots for Loading, Error and Success Composable slots so you can pass your Composables inside these slots.
Answer: var bitmap = remember {  mutableStateOf<Bitmap?>(null)}

Here, bitmap.value will be null.
Image(
    bitmap = bitmap.value?.asImageBitmap()!!, //Throws exception here
    contentDescription = ""
)

Here, bitmap.value?.asImageBitmap() will be null, since bitmap.value is null. As a result, you will crash with a NullPointerException as soon as you execute this code.
Eventually, bitmap.value will not be null, courtesy of your LaunchedEffect, but that will take some time. You need to rework your composable to be able to work prior to that point in time.


Reverse Proxy To Cloudfront CDN

Question: We want to forward all requests to domain.com/foo to a S3 Bucket fronted by Cloudfront.  The idea being that our domain is used while the content is loaded from S3/Cloudfront.  I have Apache setup to reverse proxy requests to /foo thusly:
<Location /foo>
    RequestHeader set X-Forwarded-Proto "https"

    ProxyPassReverseCookiePath / /foo

    ProxyPass http://bar.cloudfront.net/
    ProxyPassReverse http://bar.cloudfront.net/
</Location>

However when I hit domain.com/foo I get a 403 Forbidden from Cloudfront.
I tried adding the header RequestHeader set Host "bar.cloudfront.net", the page loads and I see the content in the s3 bucket, but then the domain is obviously the CDN domain.
Update:
I swapped out the cloudfront URL in the Apache config for the s3 bucket's public URL and it worked, while preserving the hostname.  So I believe this confirms its an issue with Cloudfront.
I added our domain name as a CNAME on CloudFront.  Then set the RequestHeader set Host to our domain name with the /foo.  This preserves the host name but causes a 400 error from CloudFront.
Comment: Have you considered setting up CloudFront with multiple origins, one path pointing at S3, the other pointing at your origin server? The documentation is a bit light in this area, but try setting up a distribution then adding additional behaviours once it's working. Someone else may be able to give you more details.
Comment: @Tim The content that Cloudfront is providing is only in the S3 bucket.  I was under the impression the origins serve up content won't Cloudfront attempt to load files from my host if I se the origin to my EC2 instance?
Comment: Multiple origins means CloudFront will load content from different places based on a path match. I've never set it up, and something I read suggested it may in the past have been API only, but maybe there's a UI for it now. Interesting problem though, I do think you should follow up CF.
Comment: @Tim I setup the host as an origin and it didn't change the results. Still seeing the 403 error.
Comment: You have solved the question?
Comment: Don't you lose the CDN benefits of cloudfront if you proxy through Apache?
Answer: Cloudfront needs to be aware of all Host headers it is going to receive. You can add domain.com as a CNAME entry in Cloudfront. This does not cause traffic to come to cloudfront, but it does identify that host header as related to your specific config.
Comment: I set our domain as a CNAME, and that allowed the content to load, but wihtout the `RequestHeader set Host` I ended up on the cloudfront domain.  I set the `RequestHeader set Host` to our domain, and ended up on our homepage (domain.com).  So I set the header to `domain.com/foo` and then I get the CloudFlare error page, though this time it is a `400` instead fo a `403`.  I cannot set a CNAME as `domain.com/foo` in the CF console.  So I guess I'm stuck then?
Comment: The CNAME would be just domain.com. Perhaps I am misunderstanding what you mean by 'end up on'.

Reverse Proxy To Cloudfront CDN


Regression on fractional data

Question: I'm writing a piece of research into the death rate of minorities on tv shows, as there's been a lot of outcry over the deaths of queer women in media but very little actual analysis on the topic. I've done multivariate data analysis in the past but nothing needing regression; I'm a second-year undergraduate statistics student.
In order to control for the correlation between total number of characters and number of deaths, I'm intending to express the deaths per year as a fractional value. Aside from a simple linear regression, are there any regression models that would be appropriate? I've looked into binomial regression (which might works, but I'm unsure) and Poisson regression already, which certainly wouldn't work as it's not integer data.
Comment: Do you have the number of characters and the number of deaths, or just the fraction?
Comment: You do in fact have integers - the number of deaths. Depending on what data you have exactly either logistic or Poisson regression might be appropriate so can you show us some more detail?
Comment: If you're directly comparing sets of proportions by category of person there's already tests for that -- I wouldn't use linear regression. If you have other covariates (besides the exposure variable, i.e. the number of characters) then I'd look at say logistic regression, but otherwise I'd probably look at something like a chi-squared test.
Comment: I'm examining the rate of deaths, as a proportion of the total population, over time; the goal is to find out if 2016 is a significant outlier in terms of death and thus check the validity of all the claims that it is.

My data is currently sorted by character, year they were introduced, year they left, and whether they died, so there's transformations to be done regardless. The issue is that there's likely an underlying relationship between the number of characters present in a year and the number that die, and that could skew the result of an analysis that just uses the number of deaths.
Comment: https://stats.stackexchange.com/questions/142338/goodness-of-fit-and-which-model-to-choose-linear-regression-or-poisson/142353#142353
Answer: You say you cannot use a poisson regression on the count variable deaths directly, because there might be some influence of exposure (number of characters that year) with the number of deaths, presumably because with too many characters the film company's need to get rid of more of them ... (?).
But I think that we can take care of that within the glm framework, I will first discuss a poisson regression (with log link). Let $Y_t$ be the number of deaths year $t$, the exposure $E_t$ the total number of characters, and possibly $x_t$ other covariates (in intensive form, see Goodness of fit and which model to choose linear regression or Poisson). Then $Y_t \sim \cal{P}(\lambda_t)$, $\lambda_t = \exp(\beta_0+1\cdot \log E_t + \beta^T x_t)$ where the log exposure $\log E_t$ is used as an offset (see Difference between offset and exposure in Poisson Regression). This is a baseline model which is not modelling any interaction between exposure and number of deaths.  Then to see if there is any such interaction, extend the model as
$\lambda_t = \exp(\beta_0+1\cdot \log E_t + s(\log E_t) + \beta^T x_t)$ where $s(\cdot)$ represents a smooth term, maybe a spline, or more simply a linear term. Then the estimate of the new term indicates if there is such an interaction.  If there is overdispersion all this can be done within a negative binomial model.
One could argue (since the number of deaths $Y_t$ is bounded above by the exposure) that a binomial likelihood is more natural. That would have to be used with a log link, see for instance Log binomial regression with a case-control sample

Regression on fractional data


LilyPond - opacity of objects (slurs specifically)

Question: I am transcribing a manuscript of BWV 1011 (prelude) and there are a few slurs that appear to be a little faint:

Is there a way in which the slur opacity can be controlled in LilyPond?
Comment: I wonder *why* they are? Maybe it's a later addition? (Also: If you want to indicate this distinction in your own typeset version, it might be worth using a more noticeable method like bracketing them.)
Answer: Lilypond currently uses a PS backend by default. PS does not support opacity, so there is no way to do so. The SVG backend will handle alpha as fourth color channel, so doing
{
  \override NoteHead.color = #"#000000A0"
  b'
}

will work with the SVG backend. Alternatively you may fake it by setting the color gray. Still, it is questionable if you really want to do so. It is quite uncommon to see transparency being used in music engraving, usually you'd go for smaller font sizes, different fonts or dashed/dotted lines for distinction.
Answer: I'm not sure how to interpreting that measure; is that one large dashed slur, it three short slurs?

If you want a dashed slur, use \slurDashed:

\slurDashed
c''16( b' a' g' a' b') |

If you need more control of the dashes you can use \slurDashPattern (with a numbers for the dash ratio, and a number for the dash period):

\slurDashPattern #0.5 #5
c''16( b' a' g' a' b') |

For more options and details about dashed and dotted slurs, see:
https://lilypond.org/doc/v2.24/Documentation/notation/expressive-marks-as-curves

To simply change to colour of slurs use \override Slur.color (and specify the colour in hexadecimal):

\override Slur.color = "#888888"
c''16( b') a'( g') a'( b') |


Creating is_sold MySQL field based on index existence in another table

Question: I have a simple set of products with serial numbers. If a product is sold, its serial number gets placed in sold_items while all items that ever existed remain in all_items.
Some sample data:
all_items
id | serial_number | product_name | product_price
1  | XXXXXXXXXXX01 | Laptop       | 199
2  | XXXXXXXXXXX02 | Tablet       | 99

sold_items
id | serial_number | sold_time
1  | XXXXXXXXXXX02 | [TIMESTAMP]

I'm trying to do something like this with my query:
SELECT
  all_items.* ,
  (JOIN sold_items ON sold_items.serial_number = all_items.serial_number) AS is_sold
FROM all_items

In this case, the expected output would be
[
  0=>[
    'id'=>1,
    'serial_number'=>XXXXXXXXXXX01,
    'product_name'=>Laptop,
    'product_price'=>199,
    'is_sold'=>0
  ],
  1=>[
    'id'=>1,
    'serial_number'=>XXXXXXXXXXX02,
    'product_name'=>Tablet,
    'product_price'=>99,
    'is_sold'=>1
  ]
]

Is this easily achievable with a single query?
Answer: Use a LEFT JOIN and test whether the ID in the other table is not null.
SELECT a.*, s.id IS NOT NULL AS is_sold
FROM all_items AS a
LEFT JOIN sold_items AS s ON a.serial_number = s.serial_number


Retornar registros do banco de dados utilizando jquery ajax, php e mysql

Question: Sou iniciante em jquery e gostaria de uma ajuda para a seguinte situação:
Neste campo:
<input type="text" name="colaborador" id="colaborador">

Como faria onde, para cada letra digitada seja executada uma consulta no banco de dados e retorne as linhas de uma tabela?
$(document).ready(function() {
    $("#colaborador").keyup(function(){
       //muitas dúvidas aqui
    });
});

No meu arquivo.php deveria retornar um JSON??? Como faria isso??
Answer: Aqui tem um exemplo que fiz, dá pra entender se olhar:
JAVASCRIPT:


Test logistic regression model using residual deviance and degrees of freedom

Question: I was reading this page on Princeton.edu. They are performing a logistic regression (with R). At some point they calculate the probability of getting a residual deviance higher than the one they got on a $\chi^2$ distribution with degrees of freedom equal to the degrees of freedom of the model. Copying-pasting from their website...

> glm( cbind(using,notUsing) ~ age + hiEduc + noMore, family=binomial)

Call:  glm(formula = cbind(using, notUsing) ~ age + hiEduc + noMore,
     family = binomial)

Coefficients:
(Intercept)     age25-29     age30-39     age40-49       hiEduc       noMore
    -1.9662       0.3894       0.9086       1.1892       0.3250       0.8330

Degrees of Freedom: 15 Total (i.e. Null);  10 Residual
Null Deviance:      165.8
Residual Deviance: 29.92        AIC: 113.4

The residual deviance of 29.92 on 10 d.f. is highly significant:
> 1-pchisq(29.92,10)
[1] 0.0008828339

so we need a better model

Why does it make sense to compute 1-pchisq(29.92,10) and why does a low probability indicate that something is going wrong with their model?
Answer: They are using a deviance test shown below:
$$
D(y) = -2\ell(\hat\beta;y) + 2\ell(\hat\theta^{(s)};y)
$$
Here the $\hat β$ represents the fitted model of interest and $\hatθ(s)$ represents the saturated model. The log-likelihood for the saturated model is (more often than not) $0$, hence you are left with the residual deviance of the model they fitted ($29.92$). This deviance test is approximately chi-squared with degrees of freedom $n-p$ ($n$ being the observations and $p$ being the number of variables fitted). You have $n=16$ and $p=6$ so the test will be approximately $\chi^2_{10}$. The null of the test is that your fitted model fits the data well and there is no misfit—you haven't missed any sources of variation. In the above test you reject the null and, as a result, you have missed something in the model you fitted. The reason for using this test is that the saturated model will fit the data perfectly so if you were in the case where you are not rejecting the null between your fitted model and the saturated model, it indicates you haven't missed big sources of data variation in your model.
Answer: Your question, as stated, has been answered by @francium87d.  Comparing the residual deviance against the appropriate chi-squared distribution constitutes testing the fitted model against the saturated model and shows, in this case, a significant lack of fit.

Still, it might help to look more thoroughly at the data and the model to understand better what it means that the model has a lack of fit:
d = read.table(text=" age education wantsMore notUsing using
   <25       low       yes       53     6
   <25       low        no       10     4
   <25      high       yes      212    52
   <25      high        no       50    10
 25-29       low       yes       60    14
 25-29       low        no       19    10
 25-29      high       yes      155    54
 25-29      high        no       65    27
 30-39       low       yes      112    33
 30-39       low        no       77    80
 30-39      high       yes      118    46
 30-39      high        no       68    78
 40-49       low       yes       35     6
 40-49       low        no       46    48
 40-49      high       yes        8     8
 40-49      high        no       12    31", header=TRUE, stringsAsFactors=FALSE)
d = d[order(d[,3],d[,2]), c(3,2,1,5,4)]

library(binom)
d$proportion = with(d, using/(using+notUsing))
d$sum        = with(d, using+notUsing)
bCI          = binom.confint(x=d$using, n=d$sum, methods="exact")

m     = glm(cbind(using,notUsing)~age+education+wantsMore, d, family=binomial)
preds = predict(m, new.data=d[,1:3], type="response")

windows()
  par(mar=c(5, 8, 4, 2))
  bp = barplot(d$proportion, horiz=T, xlim=c(0,1), xlab="proportion",
               main="Birth control usage")
  box()
  axis(side=2, at=bp, labels=paste(d[,1], d[,2], d[,3]), las=1)
  arrows(y0=bp, x0=bCI[,5], x1=bCI[,6], code=3, angle=90, length=.05)
  points(x=preds, y=bp, pch=15, col="red")

The figure plots the observed proportion of women in each set of categories that are using birth control, along with the exact 95% confidence interval.  The model's predicted proportions are overlaid in red.  We can see that two predicted proportions are outside of the 95% CIs, and anther five are at or very near the limits of the respective CIs.  That's seven out of sixteen ($44\%$) that are off target.  So the model's predictions don't match the observed data very well.
How could the model fit better?  Perhaps there are interactions amongst the variables that are relevant.  Let's add all the two-way interactions and assess the fit:
m2 = glm(cbind(using,notUsing)~(age+education+wantsMore)^2, d, family=binomial)
summary(m2)
# ...
#     Null deviance: 165.7724  on 15  degrees of freedom
# Residual deviance:   2.4415  on  3  degrees of freedom
# AIC: 99.949
#
# Number of Fisher Scoring iterations: 4
1-pchisq(2.4415, df=3)  # [1] 0.4859562
drop1(m2, test="LRT")
# Single term deletions
#
# Model:
# cbind(using, notUsing) ~ (age + education + wantsMore)^2
#                     Df Deviance     AIC     LRT Pr(>Chi)
# <none>                   2.4415  99.949
# age:education        3  10.8240 102.332  8.3826  0.03873 *
# age:wantsMore        3  13.7639 105.272 11.3224  0.01010 *
# education:wantsMore  1   5.7983 101.306  3.3568  0.06693 .

The p-value for the lack of fit test for this model is now $0.486$.  But do we really need all those extra interaction terms?  The drop1() command shows the results of the nested model tests without them.  The interaction between education and wantsMore is not quite significant, but I would be fine with it in the model anyway.  So let's see how the predictions from this model compare to the data:

These aren't perfect, but we shouldn't assume that the observed proportions are a perfect reflection of the true data generating process.  These look to me like they are bouncing around the appropriate amount (more correctly that the data are bouncing around the predictions, I suppose).
Answer: I do not believe that the residual deviance statistic has a $\chi^2$ distribution.  I think it is a degenerate distribution because asymptotic theory does not apply when the degrees of freedom increases at the same speed as the sample size.  At any rate I doubt that the test has sufficient power, and encourage directed tests such as tests of linearity using regression splines and tests of interaction.
Comment: I think because in this case all the predictors are categorical, the no. degrees of freedom of the saturated model wouldn't increase with sample size, so the asymptotic approach makes sense. The sample size is still rather small though.
Comment: I agree this terminology's unfortunate: `glm` gives a different "residual deviance" when the data are grouped up from when they aren't - & a different "null deviance" for that matter.
Comment: Not sure that's it.  The d.f. of the model parameters is fixed but the d.f. of the residual "$\chi^2$" is $n$ minus that.
Comment: In this case the data consist of 1607 individuals in a contingency table & the test is comparing a 6-parameter model with the 16-parameter saturated model (rather than a 1607-parameter model).
Comment: Then it should not be labeled as residual $\chi^2$.


Fluent NHibernate - Mapeamento Chave Composta

Question: Saudações,
Estou com uma dificuldade e não consigo resolver.
Tenho uma aplicação onde criei o mapeamento e estava tudo funcionando perfeitamente, porém agora preciso alterá-lo e é aí que surge o problema:
Utilizei o Fluente NHibernate para o ORM.
Preciso criar o mapeamento utilizando uma chave composta, ou seja, em linguagem SQL ficaria algo assim:
select
    *
from
    t1
inner join
    t2
        on  t1.codigo = t2.codigo
        and t1.versao = t2.versao;

E não consigo mapear o "and" do join.
Meu mapeamento está assim:
public class T1Map : ClassMap<T1>{
    public T2Map() {
        Table("TB_WF_T1");
        Id(x => x.Codigo, "CD_T1").GeneratedBy.Sequence("SEQ_TB_WF_T1");
        Map(x => x.Versao, "CD_VERSAO");
        HasMany(x => x.T2).KeyColumn("FK_CODIGO_T1").LazyLoad().Inverse().Cascade.SaveUpdate();
    }
}

public class T2Map : ClassMap<T2>{
    public T2Map() {
        Table("TB_WF_T2");
        Id(x => x.Codigo, "CD_T2").GeneratedBy.Sequence("SEQ_TB_WF_T2");
        Map(x => x.Versao, "CD_VERSAO");
        References(x => x.T1).Column("FK_CODIGO_T1").LazyLoad().Cascade.None();
    }
}

Minha dúvida é como faço o mapeamento tanto do campo "CODIGO" quanto do campo "VERSAO".
Existe alguma maneira de realizar esse mapeamento?
Qualquer dica que alguem puder me ajudar, ficarei muito agradecido.
Comment: Você conseguiu resolver o problema com a minha resposta abaixo? caso sim selecione a minha resposta como resolvido. Senão eu ainda posso te ajudar em algo.
Comment: Vou tentar agora... Já já eu posto o resultado.
Comment: Danilo, eu vou precisar fazer algumas modificações na estrutura da minha aplicação para realizar os testes. Assim que eu terminar, eu aviso se deu certo.
Answer: Eu utilizo o CompositeId() do FluentNHibernate, e utilizo o reference. o HasMany é se é alguma coleção que quero carregar junto. Pelo seu código você já deve saber a diferença.
CompositeId()
            .KeyReference(x => x.Id, "idB")//se for uma referencia(entidade)
            .KeyProperty(x => x.Id2, "idB2");//se for uma propriedade(int/long)

Segue um exemplo se for uma classe com KeyProperty e KeyReference:
(Esse Link)
    public class TestChildMap : ClassMap<TestChild>
    {
        public TestChildMap()
        {
            Table("TestChild");
            CompositeId()
                .KeyProperty(x => x.ChildName, "ChildName")
                .KeyReference(x => x.Parent, "TestParentId");
    Map(x => x.Age);
            References(x => x.Parent, "TestParentId")
     .Not.Insert();  //  will avoid "Index was out of range" error on insert
    }

Segue um exemplo se for uma classe apenas com KeyReference:
public class MapEmpresaProduto : MapBase<EmpresaProduto>
    {
        public MapEmpresaProduto()
        {
            Table("EmpresaProduto");
            CompositeId()
                .KeyReference(x => x.Empresa, "IdEmpresa")
                .KeyReference(x => x.Produto, "IdProduto");

            References(x => x.Empresa)
                .Not.Nullable()
                .Fetch.Join()
                .Cascade.SaveUpdate()
                .Column("IdEmpresa")//linko o KeyReference(x => x.Empresa, "IdEmpresa") atraves do column name.
                .ReadOnly();

            References(x => x.Produto)
                .Not.Nullable(

)
                .Fetch.Join()
                .Cascade.SaveUpdate()
                .Column("IdProduto")
                .ReadOnly();
        }
    }

Minha entidade EmpresaProduto:
public class EmpresaProduto : EntidadeAuditavelSemId
    {
        public virtual Produto Produto { get; set; }

        public virtual Empresa Empresa { get; set; }

        protected EmpresaProduto()
        {
        }
        public EmpresaProduto(Empresa empresa, Produto produto) : this()
        {
            Produto = produto;
            Empresa = empresa;
        }

        public override bool Equals(object entity)
        {
            if (entity == null || !(entity is EmpresaProduto))
            {
                return false;
            }

            // Mesmas instâncias devem ser consideradas iguais
            if (ReferenceEquals(this, entity))
            {
                return true;
            }

            // Objetos transientes não são considerados iguais
            var other = (EmpresaProduto)entity;
            var typeOfThis = GetType();
            var typeOfOther = other.GetType();
            if (!typeOfThis.IsAssignableFrom(typeOfOther) && !typeOfOther.IsAssignableFrom(typeOfThis))
            {
                return false;
            }

            return Produto.Id.Equals(other.Produto.Id) && Empresa.Id.Equals(other.Empresa.Id);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hash = GetType().GetHashCode();
                hash = (hash * 31) ^ Produto.GetHashCode();
                hash = (hash * 31) ^ Empresa.GetHashCode();

                return hash;
            }
        }
    }

OBS: Já fiz inumeros testes e o SQLServer até agora se destacou, sendo index criados com nomes estranhos e errados no MYSQL e postgress. Então caso o seu banco não for sqlserver tenha cuidado. (O problema esta realmente no conector e não no fluent em si).
Comment: é eu realmente não entendi oque voce quer... no codigo postado vc esta utilizando em 'public class ExclusaoMap' tanto CompositeId() como Id(), isso esta me deixando confuso, qual é a chave da tabela Exclusao? Se for uma chave composta deve se utilizar CompositeId(), senão Id(). Esse mapeamento tambem estou percebendo que não é necessario, voce pode fazer 2 queries no LINQ com um where(x => x.Codigo == codigo && x.versao == versao)... Entao esta bem confuso mesmo. De uma pesquisada em alguns exemplos em ingles, que talvez melhore sua ideia de como fazer isso.
Comment: http://stackoverflow.com/questions/8855135/fluent-nhibernate-mapping-one-to-many-using-2-columns esse link talvez te ajude.
Comment: Danilo, não deu certo. Nesse trecho que você me deu como exemplo, onde que eu especifico qual é a segunda cláusula (chave composta) para o join?
Comment: Eu acho que compliquei quando postei as classes. Amanhã eu posto como estava e o que preciso, ficará mais fácil para você conseguir me ajudar.
Comment: Danilo, eu descrevi em baixo o que eu preciso e como está. Veja se entende e se consegue me ajudar.
Comment: Para resolver seu problema, o campo Versao Deve ser Um ForegnKey/PrimaryKey Pois não é usual voce fazer um join por propriedades basicas... Nao conseguirei resolver seu problema, talvez alguem possa me ajudar para solucionar esse misterio kkk


Add/enable language to Language Module from code

Question: I'd like to add/enable a language, just like one would from the admin ui at /admin/config/regional/language/add
but, from code. I've found old options such as locale_add_language which no longer exists, since Drupal 5 or 6. Everything else I can find is in Tests, which seems like a bad route to take and I'm still a little new to Drupal development to understand how to make it happen, or if I should.
I'm building an app that checks the server for content in the device's language and, if it doesn't have it, the server hits Google Translate and stores the translation, and sends it on to the app. The problem is that if that language hasn't been enabled in Drupal, it doesn't store properly and effectively doesn't exist. If I pre-add the language, no problem.
Therefore, unless there's a code solution to adding a language when a new language is encountered, I'd have to enable all languages on the server. I'm not against that, but I'm also wondering if there is overhead on that, or other problems it could cause.
Thank you for any help or suggestions you might have!
Comment: This doesn't sound like a language issue to be honest. I would post your end goal in the Drupal.org forums, and ask for how Drupal users would approach such a problem. You can explain how you did it in Drupal 7 for context, though the Drupal 8 solution is almost definitely very different. Unfortunately, such questions are not allowed on Drupal Answers, but they are welcome on the Drupal forums.
Comment: Do what LanguageAddForm does.
Comment: Drupal Answers has a specific format, one part of which is that open-ended, or opinion-based questions are not allowed. Such questions get closed by admins. I try to point people at the forums in such a case.
Comment: Small (but kind of important) correction: posts get closed by the community, not admins. Stack Exchange sites are collaboratively edited Q+A. Jaypan is right that this post is probably a bit too broad for that format at the moment, as there are several steps, not all straightforward (downloading and installing the various translations in a batch job, for example). I think cilefen's suggestion to look at the existing form code is a good one
Comment: @Jaypan Obviously being very new here, aside from lurking, may I ask why this question isn't allowed on Drupal Answers? Also, I'm new to Drupal as of 8, so I only found the locale_add_language from digging in the API.
Comment: The end of the question did go open-ended, true. Thanks @Jaypan
Comment: I wasn't saying this question is open-ended, it's fairly specific. However, I don't think it sounds like the solution you are aiming  for with your question would be the best way to go about it in Drupal 8+. I had suggested opening a thread on the topic of 'how would you solve this problem in D8+, that I used to solve this way in D7-?', but such a question would be closed on Drupal Answers, while allowed on Drupal forums. Sorry for the confusion.
Answer: Languages can be added the same way as any other entity. The entity type is configurable_language and you can use the LanguageManager to get the proper settings (name, LTR/RTL) from the stock languages in admin.
So, where $lang is the language code sent by the device:
<code>$standard_languages = LanguageManager::getStandardLanguageList();
$label = $standard_languages[$lang][0];
$direction = $standard_languages[$lang][2] ?? ConfigurableLanguage::DIRECTION_LTR;

$entity = \Drupal::entityTypeManager()->getStorage('configurable_language')->create();
$entity->set('id', $lang);
$entity->set('label', $label);
$entity->set('direction', $direction);
$languages = \Drupal::languageManager()->getLanguages(ConfigurableLanguage::STATE_CONFIGURABLE);
$last_language = end($languages);
$entity->setWeight($last_language->getWeight() + 1);
$entity->save();
</code>
What threw me off was that you do not enable a pre-defined language. The languages shown in the admin UI come from a variable in json format in Core, and they're added as entities when you enable them.


Convergence of sequence of exponential matrices.

Question: If $\{A_k\}$ is a sequence of $n \times n \hspace{1mm}$  matrices so that $\sum_{i,j=1}^n|a_{k_{ij}}|^2 < \infty$  for every $k$, i.e sum of squares of all the entries is finite for each matrix of the sequence. How do we ensure or what will be the criterion for convergence of $\exp(A_k)$ to say $\exp(A)$?
We may assume the norm as $$||B||=\sum_{i,j=1}^n|b_{ij}|^2$$ where $B=(b_{ij})_{1\leq i,j \leq n}$. The definition I am using for $\exp(A)$ is
$$\exp(A)=I+A+\frac{A^2}{2!}+\cdots+\frac{A^n}{n!} +\cdots $$
The above definition of $\exp(A)$ may complicate the proof of convergence hence feel free to share any other definition of $\exp(A)$.
Comment: If $n$ is finite then all norms on the space of $n\times n$ matrices are equivalent.  Since the exponential function is continuous, one has that $\exp(A_k)\to\exp(A)$ (in any norm) as long as $A_k\to A$ (in any norm).
Comment: If $A_n$ is a sequence of negative definite matrices with eigenvalues tending to $-\infty$ then $\|A_n\|\rightarrow \infty$ as $n\rightarrow\infty$ but $\big\|e^{A_n}\big\| \leq 1$.
Comment: Thank you so much for that. Can you give any reference for the stated result?
Answer: If $A_k\to A$ then $e^{A_k}\to e^A$.
Proof: (In what follows, any norm that satisfies $\|AB\|\le\|A\|\|B\|$ can be used.) $$B^n-A^n=B^{n-1}(B-A)+B^{n-2}(B-A)A+\cdots+B(B-A)A^{n-1}+(B-A)A^{n-1}$$
\begin{align}\therefore\ \|B^n-A^n\|&\le(\|B\|^{n-1}+\|B\|^{n-2}\|A\|+\cdots+\|A\|^{n-1})\|B-A\|\\
&\le {nc}^{n-1}\|B-A\|\end{align} where $c=\max(\|A\|,\|B\|)$.
Turning to the exponential,$$e^B-e^A=(B-A)+\tfrac{1}{2!}(B^2-A^2)+\cdots$$
$$\therefore\ \|e^B-e^A\|\le\|B-A\|(1+\tfrac{2c}{2!}+\tfrac{3c^2}{3!}+\cdots+\tfrac{c^k}{k!}+\cdots)=e^c\|B-A\|$$ So, given any $0<\epsilon<1$, let $k$ be large enough that $\|A_k-A\|<\epsilon$, so $\|A_k\|<\|A\|+\epsilon\le\|A\|+1$; then the above shows $\|e^{A_k}-e^A\|\le e^{\|A\|+1}\epsilon$, which can be made arbitrarily small.


Lines perpendicular to vectors- are they similar triangles?

Question: Please excuse my horrible vector drawing skills.

Let us first assume that we have a third vector, called $\Delta V = V_2 - V_1$  Now, these three vectors make a triangle, $V_1, V_2, \Delta V$.  Let us call this triangle 1.  Please note that the angle between these two vectors ($V_1, V_2$ can be any value from 0 to 90 degrees)
If we have a vector perpendicular to $V_1$, let us call it $A_1$ and a vector perpendicular to $V_2$, let us call it $A_2$, and we have a third vector called $\Delta A = A_2 - A_1$.  Now, these three vectors make a triangle, called triangle 2,  $A_1, A_2, \Delta A$
My question is, will triangle 2 be a similar triangle to triangle 1?
EDIT: Sorry for drawing improper vectors.  The arrow tip of each vector will be the highest value possible for the x-axis.  That is, the tip for both vectors is at the end of the far right of the vector.  IN other words, vectors $V_1, V_2$ are joined together TAIL TO TAIL.
Answer: Not necessarily, it depends on the lengths of $\mathbf{A}_1$ and $\mathbf{A}_2$ The ratio of the side lengths of similar triangles are equal. If you do have the correct ratio then by perpendicularity the angles between the two pairs of sides are the same and the triangles will be similar.
Comment: Sorry, I forgot to mention this in the question.  The vectors $V_1, V_2$ are both equal.  Also, their perpendicular lines are also equal.


Python: Como obter uma chave de um dicionário com base no valor?

Question: Eu tenho um dicionário no formato tabela={"t":148}
Eu consigo retornar 148 fazendo tabela["t"], certo?
Como eu posso fazer para retornar "t" com base no 148?
Quando eu tento printar tabela[148] acaba retornando "None", por que?
Answer: A estrutura de dicionários foi criada com o intuito de rapidamente recuperar um valor a partir de uma chave
Sendo assim, veja o exemplo abaixo:
>>> tabela = {"t":148}

>>> tabela["t"]
148

>>> tabela[148]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 148

A exceção KeyError significa que a chave buscada não existe. Para que este erro não aconteça e você tenha mais controle em seu programa, você pode usar um try/except ou o método get() retornando um valor default. Veja abaixo
try/except
try:
    valor = tabela[148]
except KeyError:
    print("Esta chave não existe")

get
valor = tabela.get(148, "Esta chave não existe")
print(valor)

O resultado para ambos os casos será Esta chave não existe
Respondendo sua pergunta
Para achar a chave usando o valor (considerando que os valores são únicos:
for chave, valor in tabela.items():
    if valor == 148:
       break
print(chave)

O resultado será t
Imaginando que a estrutura fosse algo como:
tabela = {"t": 148,
          "u": 200,
          "v": 148
         }

Perceba que as chaves "t" e "v" possuem valor 148.
Então, para recuperar múltiplas chaves a partir de um valor, poderia ser algo como:
resultado = []
for chave, valor in tabela.items():
    if valor == 148:
        resultado.append(chave)

print(resultado)

O resultado seria: ['t', 'v']
EM TEMPO
Recuperar a chave a partir de um valor NÃO DEVE ser frequente em seu programa. Caso seja, a estrutura adotada está errada.
Espero ter ajudado.


what is the role of the backslash in this command why it is used and the dollar sign?

Question: PRICE_PER_APPLE=5
echo "The price of an Apple today is: \$HK $PRICE_PER_APPLE"

Why the dollar sign and backslash is used in the argument?
What is the meaning of sha-bang !#?
And what does it do the bash script can you me the best example to easy get understanding of it?
Comment: Please review the [help] and in particular [How to ask](/help/how-to-ask) as well as the guidance for [what's on-topic.](/help/on-topic) In general, ask one specific question per post, and please search before asking.
Comment: The author of the program wanted - for reason we don't know - the string `... is $HK` to be printed on stdout. Without the backslash, `$HK` would be replaced by the value of the bash variable named `HK`.
Answer: $HK in double quotes would be expanded to the value of the variable $HK. By preceding it with a backslash, you escape the expansion, so the literal string $HK is echoed (probably meaning Hong Kong Dollars).
There's no "sha-bang" in your example. It's usually spelt "shebang" and it contains the characters you mentioned in the reversed order. It tells the system what interpreter to use to run the script. For example,
#! /bin/bash

will be interpreted by /bin/bash, while
#! /usr/bin/sed

will be interpreted by /usr/bin/sed.


Is extending a singleton class wrong?

Question: I am creating a logger for an application. I am using a third party logger library. In which logger is implemented as singleton.
I extended that logger class because I want to add some more static functions. In these static functions I internally use the instance (which is single) of Logger(which i inherited).
I neither creates instance of MyLogger nor re-implemented the getInstance() method of super class.
But I am still getting warnings like destructor of MyLogger can not be created as parent class (Loggger) destructor is not accessible.
I want to know,
I am I doing something wrong?
Inheriting the singleton is wrong or should be avoided??
Answer: Leaving the merits of singleton pattern aside (there is a school of thought that describes it as an anti-pattern) it should not be necessary to subclass it to simply add static functionality. Here are language-specific approaches that I would prefer to subclassing a singleton:

Use a free-standing function enclosed in a C++ namespace
Use an extension class in C#
Use a helper class in Java
Use a Category in Objective-C
Comment: I am using c++ language i am thinking of creating a wrapper class of only static methods which won't inherit from the singleton Logger class. How is it??

And will you please elaborate on method you described above for c++.

Thanks..
Comment: @AnwarShaikh That works too - this is what I would do in Java, because free-standing functions are not available there. I'd go that route in C++ as well, but only if I needed to share state or other implementation details among the functions that I'm adding.
Comment: Thank You!! I will try by writing a wrapper over it.
Answer: I would use a non-singleton and delegate calls to the singleton where needed.  Whenever you have the opportunity to get rid of a Singleton, go for it.
Comment: Yes sure singletons need to be avoided, but it is turns out to be good when used for something like Logger.

what if I need some additional methods along with those are in singleton should I inherit it or write wrapper(of class with only static methods) over singleton which internally uses the singleton.
Comment: Go for a Wrapper.  That's what I meant by 'delegate calls'.
Answer: I do agree with Garret Hall, you should avoid Singleton's if possbile. That said, I don't see it as wrong for one reason. The person that implemented the Singleton let you extend it. If the api developer didn't want the singleton class Logger to be extended, they would have made the constructor private, in C++ for instance, or whatever method is appropriate for the language you are using.
Answer: I think writing a wrapper over the class is not the proper solution, because you need to write wrapper for every method you need from singleton. And you end up in writing dozens of functions.
Also you are restricting yourself from using  all the functions available in singleton.
NOT A GOOD IDEA!!!

Is extending a singleton class wrong?


$y=3^{\cos(x)}$ how to graph this trigonometric function

Question: Please help me with graphing this function $y=3^{\cos(x)}$
without graphing software.
Thanks in advance for all your procedures.
Comment: Consider looking at $x=\frac{n\pi}{2}$ where n is a positive integer.
Comment: Well, how would you graph $\cos x$ without a grapher? What about $3^x$?
Comment: the graph of $y = 3^{\cos x}$ is going to bounce back and forth between the lines $y = \frac13$ and $y = 3$; but not periodic.
Answer: Some observations:

$u \mapsto 3^u$ is order-preserving, so $3^{\cos x}$ is increasing (resp. decreasing, stationary) precisely when $\cos x$ is increasing (resp. decreasing, stationary).
$\cos x$ is periodic with period $2\pi$, hence so is $3^{\cos x}$.
$\cos x$ takes values between $-1$ and $1$, so $3^{\cos x}$ takes values between $\frac{1}{3}$ and $3$.

With this information, and by plugging in some known values of $x$ (say, multiples of $\frac{\pi}{4}$ or $\frac{\pi}{6}$ or something), you should be able to make a reasonably accurate plot.


Duplicates are being imported into Exchange Mailboxes

Question: I am using the New-MailboxImportRequest to import .PST files into existing mailboxes. These mailboxes have emails in them that are also included in the .PST file being imported.
The import request completes successfully, some needing the BadItemLimit to be set. After importing the .PST file, I am noticing that duplicates have been created for emails and contacts.
From this site,  I understand that duplicates are not imported.
This was due to a corrupt Exchange database.
A new empty database was created to allow email access and flow. Some users had cached Exchange mode enabled before the database corruption.
These locally cached emails were exported to .pst using Outlook and then imported into the empty Exchange database and respective mailbox. Most users did not have "All" cached. Data was later recovered from a backup before the corruption exporting each mailbox to a .pst file, these recovered .pst files were then imported into each user new mailbox.
This is an example of the PowerShell command used:
New-MailboxImportRequest -FilePath "\\ServerName\FolderLocation\UserName.pst" -BadItemLimit 10 -Mailbox "UserName"

This is an on premise Exchange 2016 server.
So, to my questions,

How do I stop the duplicates from being imported?
How do I remove the duplicates for those already imported?
Comment: Hi, is there any update?
Answer: I found a similar thread: Duplicates are being imported, please check if the answers in it are helpful to you.
Comment: I am testing today using the -ConflictResolutionOption parameter

The Conversation Clean Up process has been used in the past and did not remove the duplicates.
Comment: If there is any update, please let us know.


How should I go upon solving this problem?

Question: The question goes like: Describe a basis for the vector subspace of polynomials of $degree$ at most $4$  having
$3$  and $-2$  as its roots.
So, what I've done until now is, I took a vector space $P_4$ consisting of all polynomials of degree 4 or less.
Now I formed a basis $S$ of this as:
$S={\{1,x,x^2,x^3,x^4}\}$
Now how do I describe the basis for $P_4$ having $3$ and $-2$ as its roots? I don't have any idea what to do after this.
Comment: Can you find one polynomial inside your subspace? Can you characterize all?
Comment: The title of the question should have something to do with the specific question itself. Imagine what would happen if everyone who wanted help for solving a problem would use the title "How should I go upon solving this problem?".
Comment: I actually didn't know how to title my question properly, that's my bad, I'll try to put a proper title from next time. @JoséCarlosSantos
Answer: As the polynomial has $3$ and $-2$ as it's roots....so $(x-3)(x+2)$ must divide the polynomial.
Which means any such polynomial in $P_{4}$ should be of the form
$(x-3)(x+2)(ax^{2}+bx+c)=ax^{4}+(b-a)x^{3}+(c-b+6a)x^{2}+(-c-6b)x-6c$
Where $a,b,c$ are members of the underlying field.
So the above expression can be written as $$a(x^{4}-x^{3}-6x^{2})+b(x^{3}-x^{2}-6x)+c(x^{2}-x-6)$$.
So the polynomials $\left\{(x^{4}-x^{3}-6x^{2}),(x^{3}-x^{2}-6x),(x^{2}-x-6)\right\}$ Form a basis for the subspace.
Comment: You blew my cover!
Answer: The polynomial must have $(x-3)(x+2)$ as a factor, so it will have the form $(x-3)(x+2)Q(x)$ where $Q(x)$ is another polynomial. To get the product with degree at most $4$, $Q(x)$ must then have degree at most $2$. Therefore ... oops, phone is ringing. Can you finish?
Comment: $(x-3)(x+2)Q(x)$ is what I was looking for. The answer by Arghyadeep Chatterjee even completed the problem, so I didn't have to think much. Thank you for this.
@Oscar Lanzi
Comment: Actually I wanted you to think it through. Then you learn. (The "phone call" was a ruse.)
Comment: Yes, that's what I thought, but before I could go on thinking myself, it was already answered. Thank you for the concern though :)
Answer: Following your initial idea (which might not turn out to be the easiest), you could ask what condition a general polynomial $P=c_0+c_1X+c_2X^2+c_3X^3+c_4X^4$ should satisfy such that both $P[X:=3]=0$ and $P[X:=-2]=0$ (i.e., both $3$ and $-2$ are roots of $P$). The second part gives the condition $c_1-2c_1+4c_2-8c_3+16c_4=0$, and the first part is similar. These are linear (homogeneous) equations in $5$ unknown, for which the general solution describes the subspace you are looking for.
Now solving the system describes the solution in terms of free parameters (typically three of the unknowns can be chosen freely, so they will be parameters, and the remaining ones are then determined by the equations). Making one of the free parameters nonzero and the others zero will give you a particular solution; three distinct particular solutions can so be found (one for each choice of the free parameter to make nonzero). The solutions so found will be a basis for the subspace of solutions (this is a general property of linear homogeneous systems, if the set of parameters is correctly found, and therefore both compete and independent).
Comment: Thank you for explaining, I tried to solve by this way and it certainly is not the easiest and will also consume more time compared to other ways described in the answers by Arghyadeep Chatterjee and Oscar Lanzi. But I will still remember this approach just in case. @Marc van Leeuwen


Mapping by $f(z)=\frac{1+z}{1-z}$

Question: Let $f(z)=\frac{1+z}{1-z}$. Which of the following is/are true?
(A) $f$ maps $\{|z|<1\}$ onto $\{Re(z)<0, Im(z)>0\}$
(B) $f$ maps $\{|z|<1, Im(z)>0\}$ onto $\{Re(z)<0, Im(z)>0\}$
(C) $f$ maps $\{|z|<1, Im(z)<0\}$ onto $\{Re(z)<0, Im(z)<0\}$
(D) $f$ maps $\{|z|>0\}$ onto $\{Im(z)>0\}$
Based on some of the ideas I picked up from Mobius transforms and a whole lot of imagination I am convinced that only A and B are true.
Is this correct?
Comment: Are you sure there are no typos in your options? On the face of it, none of the available options seem correct.
Comment: This question appears to be off-topic because it is too localized as it comprises multiple questions in one.
Answer: Put $z=x+iy$ in right hand side and put $f(z)=u+iv$ in left hand side.Then simplyfy the right hand side and divide in real and imaginary part and compare with left hand side's real and imaginary part.
Answer: This is a bilinear (or Moebius) transformation:
$$
w = f(z) = \frac{az+b}{cz+d}
$$
whose inverse is given by:
$$
z = f^{-1}(w) = \frac{-dw+b}{cw-a}
$$
I've just studied the same transformation. Here is my suggestion.
With your data ($a=b=-c=d=1$), the condition $|z|<1$ is equivalent to:
$$
(w-1)^2 < (1+w)^2
$$
Substituting $w=u+iv$ gives finally the inegality:
$$
u>0
$$
Hence, $f$ maps $|z|<1$ (disk) onto Re(w)>0 (half-plane) which is not what you have proposed but may be are you considering the inverse transformation (the text is not really clear).

Mapping by $f(z)=\frac{1+z}{1-z}$


nested select statement subquery returns more than one row

Question: i am having two tables students and other is marks
students contain all students info like first name, last name and unique idnumber
and marks contain marks obtain by students
for each student marks are stored for each year i.e student from third year will have 3 entries in marks table
now i want to design a query which contain students info and all three years marks in single record
output should be like this :
First Name | Last Name | 1st Year Marks | 2nd Year Marks | 3rd Year Marks
Comment: It'll be easier to help if you post your SQL statement, too.
Comment: Or at the very least the tables full definition
Answer: I don't know what your nested statement looks like, but you want something along the lines of this:
select
    s.firstname,
    s.lastname,
    sum(case when m.year = m2.minyear then m.mark else 0 end) as `1st Year Marks`,
    sum(case when m.year = m2.minyear+1 then m.mark else 0 end) as `2nd Year Marks`,
    sum(case when m.year = m2.minyear+2 then m.mark else 0 end) as `3rd Year Marks`
from
    students s
    inner join marks m on
        s.student_id = m.student_id
    inner join (select student_id, min(year) as minyear from marks group by student_id) m2 on
        s.student_id = m2.student_id
group by
    s.firstname,
    s.lastname

I did conditional sums here, as well as dynamic years, since students could arrive at different times. This would be easier if you had a Year table with like "Freshman", "Sophomore", etc in it, and then kept track of when the Student completed that Year, but this will work, I suppose.
Answer: try below query.. i am considering students and marks have sstudent id in column
select stu.firstname + '|' +stu.lastname+ '|' +marks.1styr+ '|' +marks.2nd yr+ '|'+marks.3rdyr from students as stu,marks where stu.uniqueid=marks.uniqueid


continuity of monotone increasing function which is defined on all of R

Question: I'm aware that a monotone increasing function from an interval to R at most is discontinuous at countable set of points. I'd like to know whether it is true when the function is defined on all of R? and if it's not true, can you give me a counterexample?
Comment: Well, $\Bbb R$ is a countable union of intervals  (each of finite length) ...
Answer: The same proof for an interval will work over the case $\mathbb{R}$ ...when ever $a$ is a point of discontinuity then $\lim_{x\to a+}f(x)- \lim_{x\to a-}f(x) >0$ then you will find a rational number $q_a$ in  between $\lim_{x\to a-}f(x)$ & $\lim_{x\to a+}f(x)$ and since f is increasing $q_x > q_y$ iff $x>y$...so you will get a proper injection from the set of discontinuity of $f$ and rationals...that'll force it a countable set.
Answer: We know that the result is true for any interval, so it is true for the interval $[-n,n]$ for any given $n\in \mathbb{N}$.  We also know that the countable union of countable sets is countable, so if $D_n$ is the set of (at most countable) discontinuities of your function from $[-n,n]$ to $\mathbb{R}$; then $D=\cup_{n\in\mathbb{N}} D_n$ is countable and $D$ is the set of discontinuities for your function from $\cup_{n\in\mathbb{N}} [-n,n]=\mathbb{R}$ to $\mathbb{R}$.


Dado aparecendo duplicado

Question: Queria saber por que quando eu executo esse código ele mostra duas vezes o nome do cliente e funcionário, e como resolver pra aparecer só uma vez
package modelo;

import java.util.Date;

public class Pessoa {

    public int codigo;
    public String nome;
    public Date dataNascimento;
    public String endereco;

    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public Date getDataNascimento() {
        return dataNascimento;
    }
    public void setDataNascimento(Date dataNascimento) {
        this.dataNascimento = dataNascimento;
    }
    public String getEndereco() {
        return endereco;
    }
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

}

--------------------------------------------------------------------------------package modelo;

public class Funcionario extends Pessoa {

}
-------------------------------------------------------------------------------
package modelo;

public class Cliente extends Pessoa {

}
--------------------------------------------------------------------------------
package modelo;

public class Produto {
    public int codigo;
    public String nome;
    public double preco;
    public int quantidadeEstoque;

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public double getPreco() {
        return preco;
    }
    public void setPreco(double preco) {
        this.preco = preco;
    }
    public int getQuantidadeEstoque() {
        return quantidadeEstoque;
    }
    public void setQuantidadeEstoque(int quantidadeEstoque) {
        this.quantidadeEstoque = quantidadeEstoque;
    }
    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

}
--------------------------------------------------------------------------------package movimento;

import java.util.ArrayList;

import modelo.Produto;

public class ItensVenda {

    public ArrayList<Produto> listaDeProduto = new ArrayList<Produto>();
    public double valorTotal = 0;

    public ArrayList<Produto> getListaDeProduto() {
        return listaDeProduto;
    }
    public void setListaDeProduto(ArrayList<Produto> listaDeProduto) {
        this.listaDeProduto = listaDeProduto;
    }
    public double getValorTotal() {
        return valorTotal;
    }
    public void setValorTotal(double valorTotal) {
        this.valorTotal = valorTotal;
    }

}
--------------------------------------------------------------------------------
package movimento;

import modelo.Cliente;
import modelo.Funcionario;

public class Venda {
    private ItensVenda itensVenda;
    private Funcionario funcionario;
    private Cliente cliente;

    public ItensVenda getItensVenda() {
        return itensVenda;
    }

    public void setItensVenda(ItensVenda itensVenda) {
        this.itensVenda = itensVenda;
    }

    public Funcionario getFuncionario() {
        return funcionario;
    }

    public void setFuncionario(Funcionario funcionario) {
        this.funcionario = funcionario;
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

}
--------------------------------------------------------------------------------
package main;

import java.util.Date;

import modelo.Cliente;
import modelo.Funcionario;
import modelo.Produto;
import movimento.ItensVenda;
import movimento.Venda;

public class Principal {

    public static void main(String[] args) {

        Produto banana = new Produto();
        banana.setCodigo(1);
        banana.setNome("Banana");
        banana.setPreco(8.00);
        banana.setQuantidadeEstoque(100);

        Produto maca = new Produto();
        maca.setCodigo(2);
        maca.setNome("Maca");
        maca.setPreco(8.00);
        maca.setQuantidadeEstoque(100);

        Cliente cliente = new Cliente();
        cliente.setCodigo(1);
        cliente.setDataNascimento(new Date());
        cliente.setEndereco("Rua rocha pombo");
        cliente.setNome("Valdecir");

        Funcionario funcionario = new Funcionario();
        funcionario.setCodigo(1);
        funcionario.setDataNascimento(new Date());
        funcionario.setEndereco("Vila Operaria");
        funcionario.setNome("Ricardo");

        ItensVenda itensVenda = new ItensVenda();
        itensVenda.listaDeProduto.add(banana);
        itensVenda.listaDeProduto.add(maca);

        Venda venda = new Venda();
        venda.setItensVenda(itensVenda);
        venda.setCliente(cliente);
        venda.setFuncionario(funcionario);

        for (int i = 0; i < venda.getItensVenda().getListaDeProduto().size(); i++) {
            System.out.println("Nome do Cliente: " + venda.getCliente().getNome());
            System.out.println("Nome do Funcionario: " + venda.getFuncionario().getNome());
            System.out.println("Nome do Produto: " + venda.getItensVenda().getListaDeProduto().get(i).nome);
        }

    }

}

Comment: Poste as outras classes para podermos testar.
Answer: Pelo que entendi o problema todo está na modelagem. Está cadastrando o cliente e o funcionário como informação relevante para o item de venda, quando na verdade deveria ser só informação da venda como um todo e não cada item. Como você tem 2 itens, o dado aparece duas vezes, um para cada item. Então remodela sua venda para ter esses dados lá e retire eles do item de venda.
A resposta do AP resolve o sintoma, mas não o problema. Agora tem algo assim:

Fazendo assim resolve o problema pontual, mas o modelo continuar errado se sempre precisará de gambiarras para resolver. É melhor dar a solução correta.
Answer: Consegui resolver, é so fazer assim:
System.out.println("Nome do Cliente: " + venda.getCliente().getNome());
    System.out.println("Nome do Funcionario: " + venda.getFuncionario().getNome());
    for (int i = 0; i < venda.listaDeItensVenda.size(); i++) {

        System.out.println(
                "Nome do Produto: " + venda.getListaDeItensVenda().get(i).getListaDeProduto().get(i).getNome());

    }

eu estava printando o nome do cliente e funcionario dentro do for e o correto é fora
Comment: Resolveu o sintoma não o problema.

Dado aparecendo duplicado


How can I maintain linear independence through a commutator?

Question: Consider a Lie algebra $\mathcal{L}$, a linearly independent generating set $\mathcal{G}$, and an element $X \in \mathcal{L}$.
Edit: Note that $\mathcal{G}$ is not necessarily a basis; the generation is via the Lie bracket.

What are the conditions on $X$ such that $\{[X,g_i]\; \big| \; g_i \in \mathcal{G}\}$ is also linearly independent?

Or is the question too general and the answer must depend on $\mathcal{G}$? In my specific case I am looking at the Lie algebra $\mathfrak{sp}(2n,\mathbb{R})$ if that helps. Also maybe there is a more general answer for any given set of matrices but this is my specific problem.
Answer: Since $\mathcal{G}$ is a basis, we can write $X\neq 0$ as a non-trivial linear combination of elements of $\mathcal{G}$. Then $ad(X)(\mathcal{G})=\{[X,g_i] \mid g_i\in \mathcal{G}\}$ represents $0=[X,X]$ also non-trivially. Hence this set cannot be linearly independent. In formulas: if $X=a_1g_1+\cdots +a_ng_n$, where not all $a_i=0$, then
\begin{align*}
a_1[X,g_1]+\cdots a_n[X,g_n] & = [X,a_1g_1+\cdots +a_ng_n]\\
 & = [X,X]\\
 & = 0.
\end{align*}
Comment: If "generating" in the question means generating as a vector space, then this answer completely settles the matter.  It's possible, though, that Matta intended "generating" to mean generating as a Lie algebra, i.e., that the elements of $\mathcal G$ and their iterated commutators span $\mathcal L$ as a vector space.  In that case, the answer will depend on the details of $\mathcal L$ and $\mathcal G$ and $X$.
Comment: I did intend $\mathcal{G}$ to be a generating set for the Lie algebra, but thank you very much for the work Dietrich Burde. I can remove the $\mathcal{L}$ ambiguity by saying that it is $\mathfrak{sp}(2n,\mathbb{R})$ but cannot remove any ambiguity in $\mathcal{G}$. I felt like there might be some magical $X$s lying around that had no effect on linear independence but my hope was fairly tentative.