salt-cloud & Rackspace: How to attach Private Networks to new instances?

Question: I'm trying really hard to get salt-cloud to provision new servers with one (or more) private networks attached.
SaltStack's documentation here said that I am supposed to add this "section" to the 'providers' configuration file:
networks:
  - fixed:
    # This is the private network
    - private-network-id
    # This is Rackspace's "PublicNet"
    - 00000000-0000-0000-0000-000000000000
    # This is Rackspace's "ServiceNet"
    - 11111111-1111-1111-1111-111111111111

So I did that (replacing private-network-id with the Private Network's UUID, of course).
Didn't work.
I tried adding the section to the 'profiles' configuration file.
Also didn't work.
I tried removing the -fixed: atom (hence promoting the list underneath).
Still didn't work.
I'm at the end of my wits here. Can someone please tell me how I can provision a server using salt-cloud and at the same time attach private networks (in addition to PublicNet and ServiceNet) to the instance?
Or is that simply not possible?
Answer: I just tested this. Here's my working provider config
cat /etc/salt/cloud.providers.d/rackspace.conf
rs:
  minion:
    master: <master ip or url>

  # Configure Rackspace using the OpenStack plugin
  #
  identity_url: 'https://identity.api.rackspacecloud.com/v2.0/tokens'
  compute_name: cloudServersOpenStack
  protocol: ipv4

  # Set the compute region:
  #
  compute_region: DFW

  # Configure Rackspace authentication credentials
  #
  user: <user name>
  tenant: <tenant>
  apikey: <api key>

  driver: openstack
  networks:
    - fixed:
      # This is the private network
      - < private network UUID >
      # This is Rackspace's "PublicNet"
      - 00000000-0000-0000-0000-000000000000
      # This is Rackspace's "ServiceNet"
      - 11111111-1111-1111-1111-111111111111

Comment: Thanks! It works! I found out that the key difference is **`driver: openstack`** instead of **`driver: rackspace`**. With the latter, Private Networks won't be attached. The fault is mine, I overlooked that one line in [the documentation](https://docs.saltstack.com/en/latest/topics/cloud/rackspace.html): "The settings that follow are for using Rackspace with the openstack driver". Again, thank you for taking the time to answer!!


Devel and XHProf configuration!

Question: I have installed Devel and XHprof to profile (kind of performance analysis) my website . Configured everything but i am confused with this setting

XHProf URL: Path to the publically accessible xhprof_html - required to display profiler reports. You will need to set this up
  outside Drupal, for example at http://xhprof.localhost/xhprof_html

my drupal installation is in inside /www/
please help
Answer: You need to set up a virtual host on your server and put the xhprof front-end HTML files on it (the ones that come with the the xhprof download). Give the host an address (e.g. http://xhprof.localhost/xhprof_html as suggested), then give that path to Devel.
Then you should get the link at the bottom of each page to check the profiling information for that request.
Comment: No a subdomain isn't necessary, the files just need to be located at a host on the same machine
Comment: no need to create a subdomain? sorry i am not much familiar with virtual host thing.. thas why

Devel and XHProf configuration!


access dbcontext inside ExceptionFilter

Question: I've written an ExceptionFilter attribute which in that i need to access dbContext class to do database affairs. but i receive null reference in my filter attribute.
Is there any way that i can get working reference of dbContext?
    public class AppExceptionAttribute : ExceptionFilterAttribute
    {
        AppIdentityDbContext _context;
        public AppExceptionAttribute(AppIdentityDbContext context)
        {
            _context = context;
        }

        public AppExceptionAttribute()
        { }

        public override async Task OnExceptionAsync(ExceptionContext context)
        {

            var exception = context.Exception;
            while (exception != null)
            {
    //here _context is null, that is a dbContext class
                _context.Errors.Add(new Entities.Error {
                    Message = exception.Message,
                    StackTrace = exception.StackTrace,
                    Date = DateTime.Now
                });

                exception = exception.InnerException;
            }
            await _context.SaveChangesAsync();
        }
    }

i need to mention that is an asp.net core application
Answer: You can access the IServiceProvider from the ExceptionContext.
public override async Task OnExceptionAsync(ExceptionContext context)
{
    var db = context.HttpContext.RequestServices.GetService<AppIdentityDbContext>();

    ...

    await db.SaveChangesAsync();
}

Comment: Thank u very much! although method GetService in my case was like that:var db = context.HttpContext.RequestServices.GetService(typeof(AppIdentityDbContext));
Comment: The generic extension methods `GetService()` and `GetRequiredService()` are in the `Microsoft.Extensions.DependencyInjection` namespace.

access dbcontext inside ExceptionFilter


Instagram no Wordpress sem Login (sem utilização de senha)

Question: Preciso colocar o instagram na sidebar de um blog porém o usuário tem seguidor demais e tem medo de perde-los e ser hackeado e por ai.
Tentei explicar, mas de jeito nenhum eles querem colocar a senha para autorizar o plugin.
Tem alguma maneira de eu fazer isso sem logar no instagram do usuário ?
procurei diversos plugins e em todos era obrigatório logar.
Alguém pode me ajudar ?
Comment: Simples, diz para o usuário que se ele quer ter essa funcionalidade, ele vai precisar seguir as regras que os criadores dessa funcionalidade exigiram, se ele não quiser seguir essas regras, ele não poderá fazer uso, que é 8 ou 80, não tem meio termo para ele
Comment: Tem jeito sim, avisa ao usuário que ele tem que ter uma senha segura no Instagram, o computador bem protegido e o WordPress bem configurado. Se o que você quer precisa de senha, não vai ter muito jeito de conseguir nada sem ela...
Comment: Não tem um esquema de OpenId não? Ou de chave de aplicação, tipo as apps do Facebook?
Answer: @Eroder, a API do Instagram requer um CLIENT ID e um CLIENT SECRET que são fornecidos no momento que você criar uma aplicação. Para criar uma aplicação, você precisa preencher o seguinte formulário: http://instagram.com/developer/clients/register/
Ao realizar o cadastro de sua app você terá em mãos o seu CLIENT ID e um CLIENT SECRET, a partir disso basta realizar suas requisições.
Existem vendors como o instafeedjs que te ajudam nisso, exemplo de código:
<code><script type="text/javascript">
    var userFeed = new Instafeed({
        get: 'user',
        userId: YOUR_USER_ID,
        accessToken: 'YOUR_ACCESS_TOKEN'
    });
    userFeed.run();
</script>
</code>
Você conseguirá o acesso as medias recentes como você deseja caso o usuário não tenha um perfil privado, desta forma você não precisa que o usuário passe o ID e SENHA dele para você.
Answer: Eroder,
Tenho utilizado um "concorrente" do Instagram que exibe as imagens e apenas um pequeno link no site. Chama-se Iconosquare.
Deve haver um método que exiba, através da API do Instagram, mas meus conhecimentos em API são bem básicos.


Can someone please tell me what += does in java for example i += 2;

Question: Can someone please tell me what += means in java, for example i +=2;
Any help would be great, thanks!
Comment: Have you even searched anything on that?
Comment: @ChrisGerken did you mean `quality -= 1`?
Comment: the level of quality of the questions decreasing :(
Comment: Might want to try making the title match the question.
Comment: @ivanovic.. Still we got 3 answers already. ;)
Comment: Someone should probably detail the multi-threading implications of +=.
Comment: @pamphlet: What are those implications? Haven't heard about it.
Comment: @Nambari My comment was tongue-in-cheek, but merely that the read and assignment aren't atomic. So for example, if i starts at 0, two threads performing i += 2 won't necessarily result in the value being 4.
Answer: It adds 2 to the value of i. It is a shorthand for
i = i + 2

Answer: Val1 += Val2 means add Val2 to Val1 and assign the result to Val1.
It's a very common need, that's why it's built in to most languages.


Function in Python not producing output?

Question: Whenever I enter the following code:
def in_fridge():
    try:
        count = fridge[wanted_food]
    except KeyError:
        count = 0
    return count

fridge = {"apples": 10, "oranges": 3, "milk": 9}
wanted_food = "apples"
in_fridge()

Into the IDLE, "10" is outputted.
When I enter the same code into the code editor and then press F5, nothing is outputted. As a test, I created a new file in the code editor, entered:
print ("Hello World")

and dutifully got the outputted result, i.e. hello world displayed in a new window from the IDLE shell.
So I am curious as to why I get a value displayed in the IDLE environment but not the code editor, when I have entered precisely the same code.
Comment: You don't have any `print` in your first code snippet.
Comment: This question is actually not about IDLE.  The output displayed is the output generated by the python interpreter that runs the code.  The difference in behavior is the difference one sees running the same code directly in Python in interactive versus batch mode in the console.  IDLE just makes the comparison slightly easier by running code directly from the editor.
Answer: You've called in_fridge but you haven't done anything with the result. You could print it, for example:
result = in_fridge()
print(result)

Answer: You have to print that, because in IDLE the return is shown on console if not stored in a variable. Which doesn't happen when running a script, in script if something is returned by a function you need to capture that. Using = operator like result_of_func = function_name() and then print the value storred in that variable print(result_of_func)
This will work :
def in_fridge():
    try:
        count =fridge [wanted_food]
    except KeyError:
        count =0
    return count

fridge ={"apples":10, "oranges":3, "milk":9}
wanted_food="apples"
print (in_fridge())

Or :
in_fridge_count = in_fridge()
print ('Count in fridge is : ',in_fridge_count)

Comment: Yes what ever be the return in IDLE it's outputted to console if not captured into any variable. Which is not the case in running via script. Read the updated answer.
Comment: So if in IDLE the return is automatically printed, does that mean conversely that in code editor, the return is NOT automatically printed?
Comment: kindly accept the answer if this is clear to you now.
Answer: You are not priting the result of the in_fridge call, you should print it:
def in_fridge():
    try:
        count =fridge [wanted_food]
    except KeyError:
        count =0
    return count

fridge ={"apples":10, "oranges":3, "milk":9}
wanted_food="apples"
print(in_fridge())

Answer: In order to display the output, you need to print it :
print(in_fridge())


Problema com controle customizado

Question: Eu criei uma search bar customizada com um entry. Eu preciso pegar o text desse entry para ser um parametro de pesquisa.
Então, criei uma propriedade customizada que usa a propriedade Text do entry. Porém essa propriedade customizada não pega o texto da search bar customizada.
O que estou fazendo de errado? Abaixo deixo os códigos do controle customizado.
Código do evento click do botão de procura da search bar customizada.
    private async void SbcPesquisar_OnClicked(object sender, EventArgs e)
        {
            string busca = SbcPesquisar.TextSearch;
            List<Promocao> Promocoes = await PromocaoService.GetListaPromocoes(busca);
            LstPromocoes.ItemsSource = Promocoes;
        }

Code Bihind do Controle
    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace MeDeiBem.Controls
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class SearchBarCustom : ContentView
    {
        public event EventHandler ClickScope;
        public SearchBarCustom ()
        {
            InitializeComponent ();
        }
        public static readonly BindableProperty TextSearchProperty =
            BindableProperty.Create(
                propertyName: "TextSearch",
                returnType: typeof(string),
                declaringType: typeof(SearchBarCustom),
                defaultValue: "",
                defaultBindingMode: BindingMode.TwoWay,
                propertyChanged: TextSearchPropertyChanged
            );

        public string TextSearch
        {
            get { return (string)GetValue(TextSearchProperty); }
            set { SetValue(TextSearchProperty, value); }
        }
        private static void TextSearchPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var searchBarCustom = (SearchBarCustom)bindable;
            searchBarCustom.textSearch.Text = (string)newValue;
        }
        private void On_clickScope(object sender, EventArgs e)
        {
            if (ClickScope != null)
            {
                ClickScope(sender, e);
            }
        }
    }
}

Código XAML:
    <?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MeDeiBem.FontsAwesome;assembly=MeDeiBem"
             x:Class="MeDeiBem.Controls.SearchBarCustom">
  <ContentView.Content>
        <Frame Margin="10, 0, 10, 0" Padding="2" BorderColor="#49c1ff" CornerRadius="5" BackgroundColor="Transparent" HeightRequest="60">
            <StackLayout Orientation="Horizontal" BackgroundColor="Transparent">
                <Entry x:Name="textSearch"
                       Placeholder="Digite o que procura"
                       PlaceholderColor="Black"
                       FontSize="Medium"
                       BackgroundColor="Transparent"
                       HorizontalOptions="FillAndExpand"
                       />

                <Button Text="{x:Static local:Fontes.FASearch}"
                        FontSize="30"
                        BorderWidth="0"
                        BackgroundColor="Transparent"
                        WidthRequest="60"
                        HorizontalOptions="End"
                        Clicked="On_clickScope" />
            </StackLayout>
        </Frame>
  </ContentView.Content>
</ContentView>

Código XAML de onde estou usando o componente:
<controls:SearchBarCustom x:Name="SbcPesquisar" ClickScope="SbcPesquisar_OnClicked" />

Comment: Olá, coloquei o código na pergunta. Obrigado.
Answer: O que faltou foi vocÊ usar a BindableProperty TextSearchProperty que você criou no seu componente. Ela já está exposta para Bindings.
Então você deverá ter uma propriedade na sua ViewModel, como SearchText, por exemplo, e usá-la com o binding no componente. Assim:
<controls:SearchBarCustom x:Name="SbcPesquisar"
                          TextSearch="{Binding SearchText}"
                          ClickScope="SbcPesquisar_OnClicked" />

Isso porque no seu delegate propertyChanged definido na BindablePropertyvocê fez refletir a alteração da propriedade TextSearch no componente Entry interno, mas quando a alterção ocorre no Entry a sua propriedade TextSearch não está sendo 'notificada'.
Edit:
Sem usar Bindings (como é o caso do MVVM), expor a propriedade como bindable acaba se tornando desnecessário, pois foi justamente para isso que ela foi projetada.
Mas, com alguns pequenos ajustes é possível resolver o problema que você está enfrentado.
Você vai precisar acrescentar uma propriedade x:Name no seu componente, definir que ele será seu proprio BindingContext e vincular o texto do seu Entry à propriedade que você expôs no codebehind do componente. Assim:
<?xml version="1.0" encoding="UTF-8"?>
<ContentView ...
             x:Class="MeDeiBem.Controls.SearchBarCustom"
             x:Name="searchBarCustom">
    <ContentView.Content>
        <Frame Margin="10, 0, 10, 0"
               BindingContext="{Reference searchBarCustom}"
               ...>
            <StackLayout Orientation="Horizontal"
                         BackgroundColor="Transparent">
                <Entry x:Name="textSearch"
                       Text="{Binding TextSearch}"
                       Placeholder="Digite o que procura"
                       .../>

                <Button ... />
            </StackLayout>
        </Frame>
  </ContentView.Content>
</ContentView>

* Onde tem os "..." é para você manter o seu código do jeito que está atualmente
Esse pequeno ajuste fará com que as alterações no Entry reflitam na propriedade TextSearch e vice-versa. Agora você pode remover a implementação do propertyChanged: TextSearchPropertyChanged que você usou na BindableProperty.
Fazendo assim você será capaz de recuperar o conteúdo da propriedade como estava tentando:
private async void SbcPesquisar_OnClicked(object sender, EventArgs e)
{
    string busca = SbcPesquisar.TextSearch;
    List<Promocao> Promocoes = await PromocaoService.GetListaPromocoes(busca);
    LstPromocoes.ItemsSource = Promocoes;
}

Espero que isso ajude.
Comment: Poderia me explica porque não faz sentido? Pretendo usar MVVM nos meus projetos futuros. Fiquei um pouco afastado do Xamarin e ainda estou meio perdido. Mas quero entender melhor como funciona o MVVM quando estiver com mais tempo.
Comment: Ola  Diego. O problema é que eu não estou usando MVVM, então não tenho uma viewmodel.
Comment: @MarcosAurelio editei a resposta. Assim vai funcionar para você. Desse jeito que propus no final será desnecessário ter a implementação do `TextSearchPropertyChanged`, pode descartá-la.
Comment: Diego, fiz como voce falou, mas no XAML da erro no Reference: A propriedade searchBarCustom não foi econtrada no tipo Reference Extension. O código esta exatamente como voce fez, dei um nome ao meu componente de searchBarCustom, coloquei dentro da tag ContentView.BindingContext.
Comment: Foi falha minha, escrevi de cabeça. O `Referece` não é para ser usado como eu tinha feito. Já corrigi. Tenta agora
Comment: Diego funcionou. Tive que te agradecer. Obrigado.

Problema com controle customizado


Preg replace em links textarea

Question: O que eu posso fazer para jogar estes link no textarea
Ex:
http://link1.com/embed/código/nomepagina
http://link2.com/v/código/nomepagina
http://link3.com/e/código/

E ele me retornar somente
http://link1.com/código/
http://link2.com/código/
http://link3.com/código/

Pegando o código somente e formatando deixando da forma a cima.
Comment: Não duplique suas perguntas. Se a [anterior](https://pt.stackoverflow.com/q/372921/112052) não foi bem recebida, concentre seus esforços lá. Edite-a para que fique dentro do escopo, leia mais na [help/on-topic] e na página [ask]
Comment: Rogério voce quer pular uma linha no textarea é isso ? ou quer mudar o formato ?
Comment: Os links quando é gerado, é formado do jeito do primeiro exemplo, eu queria conseguir formatar esses 3 links e deixar do jeito do segundo, pegar a parte CODIGO de cada link e a parte link1,link2,link3
Answer: Criei esse regex que atende neste caso que você fez:
(http:\/\/\w+\.\w+\/)(\w+)\/(\w+)\/(.+)?

 ^ .... grupo do link        ^.... grupo do código

Depois pega os elementos de cada grupo que será usado e junta.
Ficaria assim o código:
$str = "http://link1.com/embed/codigo/nomepagina
        http://link2.com/v/codigo/nomepagina
        http://link3.com/e/codigo/";

$str = preg_replace('/(http:\/\/\w+\.\w+\/)(\w+)\/(\w+)\/(.+)?/', '$1$3 ', $str);
                  //                                              ^ aqui haverá a junção

Saída:
http://link1.com/codigo http://link2.com/codigo http://link3.com/codigo

Como é uma url eu retirei do código o acento no ó
Edição
Para subdomínios e outros tipos de domínios fiz o código assim:
$str = preg_replace('/(http:\/\/|https:\/\/)?([\w\.]+\/)([\w-_]+\/)?([\w-_]+)\/?(.+)?/', '$2$4 ', $str);

Comment: sim obrigado!!!
Comment: funcionou até ai, mas e se uns links tiver subdominio e outros não? como funcionaria? tipo os dois primeiros for subdominio.link1.com/embed/codigo/... e os outros sem ?
Comment: @RogérioSilva vou fazer para subdominions
Comment: @RogérioSilva está lá
Comment: @RogérioSilva deu certo?
Comment: Andrei, sabe pq quando o link tem - (traço) não pega? ex: site.com/embed/hB8l23wOU-E/ ele retorna somente hB8l23wOU
Comment: @RogérioSilva vou fazer uma edição
Comment: @RogérioSilva está lá!

Preg replace em links textarea


how to set up electronic drums in ableton

Question: sorry about the repost, I couldn't write a comment on the previous one, because I wasn't registered
So, I have Alesis DM Lite electronic drum kit and I also have Ableton Live 9 software. I want to record the drums thorugh Ableton, but I don't know how to set up the drums in the software. The drum kit has a usb port with one end which is like the one for printers (not the regular usb end) and with that I can connect the kit to my computer. When I open ableton it detects that the drum-kit is connected, but I can't make any sounds with it whatsoever. Can someone please explain how to set up the drums in ableton so that it reacts to the signals when I hit the pads? Thanks! I hope you got the idea.
I don't have any kind of instructions for this and I have no experience working with MIDI.
I tried all the steps in this topic but still i can not get my e-drums to work.
What i've done so far:
-Set my td-3 local control off. The manual says this is nescesairy for sending midi to my pc.
-Installed a midi to usb converter
-changed the preferences. https://ibb.co/cjwU6R . The mackiecontrol is the usb converter.
-made a midi track and hit the pad.
I still do not receive any signal.
What can i do to fix this?
THanks!
Comment: Tom's answer is excellent. Can you edit your question to tell us where you're having trouble with the steps Tom outlined? Are you able to create a midi track? Can you record arm it? When you do that, and play the pads, does the incoming MIDI meter (the column of yellow circles) jump? Are you able to put a drum rack on the midi track?
Answer: Ableton Certified Trainer here. There's a few things you need to have a look at in order to get your drums working properly.
If your drum kit is showing up in your Preferences > MIDI area, you need to ensure that the "Track" option is enabled for the kit. This means that Ableton Live will receive note data from the drum kit.
The other two options are "Remote" (Which is reserved for CC data, thing knobs turning, faders moving etc...) and "Clock" (Syncs Ableton to or from an external time source).
With the Track option enabled, you need to create a new MIDI track from the Create menu.
When this track is created, there should be a little round circle with a musical note at the very bottom of the track. If you aren't seeing it, hit the TAB key to make sure you are in Session view, which sort of looks like a spread sheet. The other view is Arrangement view, which is used for laying down a track over a timeline.
If you click that little button, it should turn red. That indicates that this track is now MIDI armed... and hopefully when you play your drums, you should see some levels moving on that track. They will be circles instead of a steady volume looking level meter, because you currently haven't set any machine or sampler to play any sounds yet.
If you are running Ableton Live 9 Suite, go into your instruments via the browser area on the right hand side, and choose "Drum Rack".
This will load up a sampler with 128 different slots, each slot a sample can be dragged into. If you hit your drums, you will see which MIDI note each drum sends in the drum rack, as it will highlight it yellow each time you hit it (you may need to scroll up and down in the drum rack as it can only display 16 pads at a time).
Once you know which drums trigger which slots, you can then go ahead and load in some drum samples to those slots. If you do not currently own any samples, grab the Session Drums kit for free from Ableton here https://www.ableton.com/en/packs/session-drums/
This kit is a standard drum kit sampled into a Drum Rack for you.
If you do not own Live 9 Suite, you can use the Impulse instrument instead, which is restricted to 8 sample slots.
Let me know if you run into any problems or have any more question.
Answer: just wanted to add a few points to the (comprehensive) post made before - If you want to use Impulse: Abletons Impulse sample slots are mapped to C3 to C4 (in Cmaj scale) - your Alesis is probably sending out the midi notes in the General Midi (GM) Standard - (e.g. Kickdrum is C1, Snare D1 etc.) - you need to 'tune'/ pitch the incoming midi notes.
I patched a Max for Live device exactly for this purpose, which you can get here:
https://gumroad.com/l/wVkbs
There is a device which is doing the same for the Drumrack as well here:
https://gumroad.com/l/uPvaf


Can't restore LVM Logical volume configuration - missing PV

Question: I had a VG with 3 pvs. The VG had one LV using all three PVs. Then one PV (hdd) died. I wanted to try to recover whatever I could. So the first thing I needed to do was to remove the missing PV from the LV/VG. Following instructions I found via googling, I used vgreduce to remove that PV. But, as I learned, that removed the LV as well. I am now trying to restore the original configuration, the one before the vgreduce, to use vgchange instead. I am using vgcfgrestore -f , where the archive file is the one created before the vgreduce. But I keep getting "Cannot restore Volume Group VGR with 1 PVs marked as missing".
Is the LV recoverable? If so how?
Any help greatly appreciated.
TIA
ken
Answer: Linux LVM does not remove PVs with LVs on them by default. It needs all the extents for the LVs to have good integrity.  vgreduce --force  might remove LVs though, it disables several safety checks. Be very specific and careful in what options you use. Log your terminal sessions.
Plan your recovery. Find any backups that exist of this data. Estimate how valuable it is to the organization, and how long it would take to recreate. If there are no backups, consider getting an estimate from a professional data recovery service.
Attempt to image the failed drive to a good one of the same size. If doing it yourself, with an error tolerant tool like dd_rescue.  Beware that in some cases further use can damage the media further, if not already dead. Data recovery services might be able to do surgery on it in an attempt to get data back.
If you manage to image it, the new disk will have the old PV's identification.  Add the new device back in.  vgextend --restoremissing $PV  As you reduced LVs away,  this would be the time to try vgcfgrestore --file again, to get back to before you did that.
Should all attempts fail and you accept data loss, consider replacing the failed PV with a new empty drive. Almost certainly this will corrupt your data. How exactly the corruption manifests depends on file system and such. But its something to try. man vgcfgrestore describes the procedure:

To replace PVs, vgdisplay --partial --verbose will show the UUIDs
and sizes of any PVs that  are  no  longer present.  If  a PV in the
VG is lost and you wish to substitute another of the same size, use
pvcreate --restorefile filename --uuid uuid (plus additional
arguments as appropriate) to initialise  it  with  the  same UUID  as
the missing PV. Repeat for all other missing PVs in the VG.  Then use
vgcfgrestore --file filename to restore the VG's metadata.

In a less degraded scenario without missing PVs, pvmove will move extents between PVs, and can be used in storage migrations.
Going forward, to have volume groups survive hard drive loss, consider adding redundancy. Either below LVM with PVs from LUNs of an array, or at the LVM layer.  See man pages mdadm and lvmraid respectively, for software solutions.
Answer: I think this link is the answer to your question
https://unix.stackexchange.com/questions/47380/where-does-lvm-store-data


Espaços entre Inputs no Twiter Bootstrap

Question: Nos formulários de cadastros o espaçamento tanto horizontal como vertical ficam muito grandes, resolvi o problema acrescentando o style="margin-bottom:10px;margin-right:-10px" em cada input, porém, no tamanho sm e xm das colunas ele perde a marge direta com essa solução.

                CNPJ*
                <input id="in_cpf_cnpj" name="cpf_cnpj" type="text" class="form-control" readonly>

                Inscrição estadual*
                <input id="in_rg_insc_estadual" name="rg_insc_estadual" type="text" class="form-control">

Também achei isso com cara de gambiarra. Tem como deixar padrão para todos os inputs?
Answer: Adiciona o seguinte em uma folha de css personalizada:
.form-group {
    margin-bottom:10px;
    margin-right:-10px;
}

Aconselho usar em uma folha css personalizada e não na padrão do bootstrap. Pq caso vc atualize a versão do bootstrap, vc n vai perder as atualizações.
Comment: valeu@Eduardo, funcionou  blz.


Navigation bar overlays music player in IOS development using Swift

Question: I am creating an app that has a music player. The view that is used to select the file to be played contains a navigation bar. The problem is that the navigation bar overlaps the music player interface, preventing me to be able to scroll to the currently playing media. I am using the latest swift, xcode and ios version. Here is a screenshot of the problem and the relevant storyboard region.

What I want is to have the navigation bar in the player appear above the playback navigation controls. Could anybody tell me a way to do that please?
Answer: You need to set navigationController.navigationBar.translucent = NO; in your viewcontroller.


Is there some quick magic trick to remove digital signature form field from pdf file just by editing PDF in text editor?

Question: What I want is to edit PDF file, and remove digital signature form field. I would like to do that without buying Adobre Pro liscence. I remember some time ago I opened PDF file in text editor and saw some scripting language, so I am wondering if I can edit PDF file directly in text editor, remove the proper lines from PDF, save and that's it!
My question:
  - Is that possible?
  - Are there any document checksums, or some existing number of objects per page in PDF file?
  - If yes, so what should I look for, and what should I change?
Comment: You might be able to in a Hex editor, like HxD, but you would want to zero bytes. You can't safely "move" anything, since PDF files use actual bye offsets to find objects. As for what to zero out, to remove just the signature, and not prevent viewing of the file, is difficult. Objects can be compressed, so they would not show up in the binary stream, but I don't imagine this would be the case for a digital signature. You can find the PDF standard online, and from there you can find the keys you want, and from that what entries to zero out.
Comment: Yeah, I was exploring that document, not so thoroughly, and tried to remove some objects with something like /Ft Sig, but every time, I do that, it was corrupted when I was opening. Ok, so it seems, I will need to go deeper for that
Answer:
Disclaimer If you choose to edit or remove signatures from a PDF, be aware that you're doing so at your own risk. This action can have legal implications. It's advisable to seek professional guidance before proceeding.

How to remove digital signature from PDF

Open the PDF in Google Chrome
Click "Print" icon in the top right corner
For "Destination" select "Save as PDF"

How to verify digital signatures have been removed
You can use the command line tool pdfsig:
pdfsig my-document.pdf
The output should include this sentence:
File 'my-document.pdf' does not contain any signatures


Question about interior of a set

Question: I'm given two normed vector spaces $X$ and $Y$ and a linear map $T:X \rightarrow Y$. Also given is that $0$ lies in the interior of $T(B(0,r))$ for some $r>0$.
I now have to show that $0$ lies in the interior of $T(B(0,\epsilon))$ for any $\epsilon > 0$.
I know that $B(0,\epsilon) = \frac{\epsilon}{r}B(0,r)$, where I use the notation
$\frac{\epsilon}{r}B(0,r)=\{\frac{\epsilon}{r}x |x\in B(0,r)\}$. But how do I continue from here?
I'm very confused about the interior of a set of the from $\lambda V$. Is it true that $int(\lambda V) = \lambda(int(V))$? Or is one of them included in the other?
And what about sets of the form $\lambda + V$?
My apologies for the probably dumb questions but the thing is that I'm quite dumb myself.
Answer: Yes, it is true that $\text{int}\,(\lambda V)=\lambda\,\text{int}\,V$.
Suppose that $x\in \text{int}\,V$. Then there exists $c>0$ with $B(x,c)\subset V$. Note that $B(x,c)=x+B(0,c)$. Then
$$
\lambda V\supset \lambda B(x,c)=\lambda x+\lambda B(0,c)=\lambda x+B(0,\lambda c)=B(\lambda x,\lambda c).
$$
So $\text{int}\,(\lambda V)\supset\lambda\,\text{int}\,V$. Now
$$
\frac1\lambda\,\text{int}\,(\lambda V)\subset \text{int}\,(\frac1\lambda\,\lambda V)=\text{int}\,V,
$$
so $\text{int}\,(\lambda V)\subset\lambda\,\text{int}\,V$
Comment: Ok, thank you so much!

Question about interior of a set


toggleClass in jQuery skips css rule

Question: I have a div of id="header" with initial css rule: padding: 25px 0;. When scrolling down the page, I want to decrease this div's padding:
$(document).ready(function() {
  var headerID = $("#header");
  $(this).scroll(function() {
    if (!$(this).scrollTop())
      headerID.toggleClass("headerScrolled");
    else if (!headerID.is(".headerScrolled"))
      headerID.toggleClass("headerScrolled");
  });
});

.headerScrolled {
  padding: 15px 0;
}

However when I scroll down the page, padding does not change. What is wrong with my code?
Comment: you're running same code on both if-else conditions? What the purpose of this?
Answer: Your two conditions are cancelling each other out. It makes more sense to make a single call to toggleClass() and provide the boolean argument to specify if the class should be added or removed based on the current scrollTop value. Also note that you should listen for the scroll on the window instead of the document. Try this:

$(document).ready(function() {
  var $header = $("#header");

  $(window).scroll(function() {
    $header.toggleClass('headerScrolled', $(this).scrollTop() !== 0);
  });
});
html,
body {
  height: 1000px;
  margin: 0;
}

#header {
  padding: 25px 0;
  background-color: #CCC;
  width: 100%;
  position: fixed;
}
#header.headerScrolled {
  padding: 15px 0;
}

  Header

Comment: Awesome as usual, never knew you could pass a bool into toggleClass, this will make a lot of things much easier from now on!
Comment: You need to make the `.headerScrolled` selector more specific in order to override any existing styling on the element. That's why I included `#header` on that selector.
Comment: This solution will keep toggling the `headerScrolled` class on header as the content is scrolled
Comment: That's not the case. I added a snippet to demonstrate
Comment: Same. Please edit this to include instructions on using `window` instead of `this` for the scroll method and I'll upvote and remove my answer.
Comment: @sean thank you, but there's no need for you to remove your answer.
Comment: @RoryMcCrossan Why this solution won't work as you emit the "#header" from the #header.headerScrolled css selector?
Answer: Use the .scroll() method on window, not this or the document. Additionally, it may be easier to use .addClass() and .removeClass() in this case.
$(document).ready(function() {

  var $header = $("#header");

  $(window).scroll(function() {
    if (!$(window).scrollTop()) {
      $header.addClass("headerScrolled");
    } else {
      $header.removeClass("headerScrolled");
    }
  });

});

Comment: This solution will keep toggling the class on #header

toggleClass in jQuery skips css rule


Picasso image mask transform with border

Question: I am trying to draw a border on an image with a squircle mask using a Picasso Transformation. The squircle mask is a VectorDrawable.
I think the easiest and most flexible way to do this is to first draw a larger squircle of a desired border color using canvas.drawPaint. Then draw a smaller squircle using the photo bitmap using canvas.drawBitmap. I can draw them both separately, I can scale the bitmap and draw it with the mask successfully, but any time I try to combine the two it loses the mask on the canvas.drawBitmap call. Any ideas on what I could be doing wrong?
I have tried loads of blend mode options but I don't think that is the issue.
override fun transform(source: Bitmap): Bitmap {
    val width = source.width
    val height = source.height
    val borderWidth = 100

    val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(output)

    //Draw a full size, red squircle
    val paint = Paint()
    paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    paint.color = Color.RED
    val mask = context.getDrawable(maskID)
    mask.setBounds(0, 0, width, height)
    mask.draw(canvas)
    canvas.drawPaint(paint)

    //Draw a masked, scaled down bitmap of the photo on top
    val bitmapPaint = Paint()
    bitmapPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    val bitmapMask = context.getDrawable(maskID)
    bitmapMask.setBounds(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2)
    bitmapMask.draw(canvas)

    val sourceDrawable = source.toDrawable(context.resources)
    sourceDrawable.setBounds(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2)
    canvas.drawBitmap(sourceDrawable.bitmap, null,
           Rect(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2),
           bitmapPaint)

    source.recycle()

    return output
}

Result:

If I comment out the call to drawBitmap I get this result (which is nearly there!):
Comment: i think you will end up drawing 3 times. First outer region, then image with mask.
Answer: UPDATED 27/11/2018
I've solved the problem by drawing the picture on a temp canvas with desired mask, then drawing the result bitmap over the main canvas. The source code and visual result are included here:
MaskTransformation.kt
import android.content.Context
import android.graphics.*
import android.graphics.drawable.BitmapDrawable
import android.support.annotation.DrawableRes
import android.support.v4.content.ContextCompat
import com.squareup.picasso.Transformation

class MaskTransformation(
    private val context: Context,
    @DrawableRes private val maskID: Int
) : Transformation {

    override fun key(): String {
        return "mask"
    }

    override fun transform(source: Bitmap): Bitmap {
        val width = source.width
        val height = source.height
        val borderWidth = 400

        val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)

        //Draw a full size, red squircle
        val paint = Paint()
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        paint.color = Color.RED
        val mask = ContextCompat.getDrawable(context, maskID)!!
        mask.setBounds(0, 0, width, height)
        mask.draw(canvas)
        canvas.drawPaint(paint)

        //Draw a masked, scaled down bitmap of the photo on top
        val maskingPaint = Paint()
        maskingPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        val maskDrawable = ContextCompat.getDrawable(context, maskID)!!
        maskDrawable.setBounds(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2)

        val overlayBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val overlayCanvas = Canvas(overlayBitmap)
        maskDrawable.draw(overlayCanvas)

        val pictureBitmap = Bitmap.createBitmap(width - borderWidth, height - borderWidth, Bitmap.Config.ARGB_8888)
        val pictureCanvas = Canvas(pictureBitmap)

        val sourceDrawable = BitmapDrawable(context.resources, source)
        sourceDrawable.setBounds(borderWidth / 2, borderWidth / 2, width - borderWidth / 2, height - borderWidth / 2)
        pictureCanvas.drawBitmap(
            sourceDrawable.bitmap,
            null,
            Rect(0, 0, width - borderWidth, height - borderWidth),
            Paint()
        )

        overlayCanvas.drawBitmap(pictureBitmap, (borderWidth / 2).toFloat(), (borderWidth / 2).toFloat(), maskingPaint)

        canvas.drawBitmap(overlayBitmap, 0f, 0f, Paint())

        source.recycle()

        return output
    }

}

MainActivity.kt
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Picasso.get()
            .load(R.drawable.img_aminography)
            .transform(MaskTransformation(this, R.drawable.ic_squircle))
            .into(imageView)

    }
}

ic_squircle.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="32"
        android:viewportHeight="32">

    <path android:fillColor="#000000"
          android:pathData="M31.2,14.3v3.5c0,9.8,-5.9,13.5,-13.4,13.5h-3.5c-7.7,0,-13.5,-3.4,-13.5,-13.5v-3.5c0,-10.8,6,-13.5,13.5,-13.5h3.5C25.2,0.8,31.2,4.1,31.2,14.3"/>

</vector>

.
Visual Result
Comment: Thanks dude :) The behavior of masking was strange and I spent about 3 hours to overcome it as you said :D
Comment: Great job! I was getting close but already spent probably 3 hours trying to figure it out :D


Set defined for proving existence of $ r > 0 $ s.t. $ r^2 = 2 $ is problematic

Question: Theorem: There exists a positive real number $ r $ s.t. $ r^2 = 2 $
The proof in my book begins with defining a set $ L = \{ x \in \mathbb{R} | x \geq 0 , x^2 \leq 2 \} $  and then proceeds to show that $ r^2 = 2 $ is the maximum of this set. However, I don't understand the following:
Since the set L contains real numbers $ x $ such that $x \geq 0, x^2 \leq 2 $, then specifically, it contains a number $ x>0 $ s.t. $ x^2 = 2 $ . How am I supposed to show the existence of such a number ( $ r^2 = 2 $ ) if it already exists  in the set I've defined? ( In which case, the set $ L $ is problematic since it already contains the number which I need to prove exists )
Comment: yup, you got it now
Comment: How do you know that it exists in the set?
Comment: The set is defined as such. Are you saying that I am defining the set to show that indeed such a number exists ( from the set's properties )?
Comment: You are assuming you what you are trying to prove.  How do you know that there exists a number that when squared is equal to $2$.  If such a number *does* exist and is in your set, that's fine.  But why would you think so number does exist?  Every number I pick at random doesn't equal to $2$ when squared so why should I assume such a number exists.
Comment: Suppose I asked you to prove there exists a least positive (strictly larger than $0$) and gave you the set $L = \{x \in \mathbb R|x\ge 0; x > 0\}$ and you pointed out that as it contains *all* positive numbers it specifically contains the number you've been tasked to find.
Comment: Yes you are right, I over-thinked about this. As stated by @Rob_Arthan below, there exists a set such as $ L = \{x \in \Bbb{R} \mid x \ge 0, x^2 \le 2\} $ , regardless if there is or isn't a number in it such that $ r^2 =2 $  ( because the set is not empty ), so there is no problem with defining such a set.
Answer: The point is that you know there exists some $x$ such that $x \ge 0$ and $x^2 \le 2$, (e.g., $1$) and you know that for all large enough $x$, $x^2 > 2$ (e.g., that is true for $x \ge 2$). Hence (without knowing whether there is an $x$ with $x^2=2$), you can define $L = \{x \in \Bbb{R} \mid x \ge 0, x^2 \le 2\}$ and you know that it is non-empty ($1 \in L$) and bounded above (if $x \in L$, then $x < 2$). But you also know that every non-empty bounded-above set of real numbers has a supremum $s$, say. And then you can prove that $s^2 = 2$. There is no circularity here, even though $s \in L$.
In this case (as pointed out by fleablood in a comment), if you were to change $\le$ in the definition of $L$ to $<$, you would get the same result, but the supremum $s$ would not be a member of $L$. However, there are proofs where you need to reason about a set that must contain a particular number of interest in order to establish what that number is. For example, to prove that any family $F$ of open intervals that covers the closed interval $I = [0, 1]$ has a finite subfamily that covers $I$, you look at the set $M$ of $x \in [0, 1]$ such that a finite subfamily of $F$ covers $[0, x]$ and then prove that $1 \in M$. It would be hard to recast that without allowing $1 \in M$.
Comment: Two things to point out.  Although we find out in the end that $s \in L$ we didn't *know* that at the start of the proof.  And had we written the proof with the set $L' = \{x\in \mathbb R| x\ge 0, x^2<2, x^2 \ne 2\}$ the exact same result occurs as $s'=\sup L'$ will have $s'\not\in L'$ and the whole issue needn't arise.... well, it needn't have arisen anyway but....
Comment: Yes. I did think about mentioning that point and have now updated my answer.
Answer: We don't know much about real numbers at this stage.  We know that every rational number is a real.  And we know that every set of real numbers that is bounded above will have a least upper bound.  But that's about all. (Okay, we know it's an ordered fields and... more stuff)
We do not know that there actually is any number $r$ so that $r^2 = 2$?  Why should there be?  Sure,  if there were such a number than $r\in L$ but we don't know any number exists.
(Here's an analogy.  Suppose I asked you to prove that something that doesn't exist does exist.  Suppose I asked you to prove that there is a smallest positive number $s$.  That is a number $s$ so that $s > 0$ and for any $t>0$ then $s \le t$.  There is no such number.  But I'm asking you to prove it.  So you say let $R= \{x| x > 0\}$.  But then you declare that because $s> 0$ then $s \in R$ so what's left to be done.....)
(Or maybe if we defined $S = \{x| 5< x \le \infty\}$ and we argue well if $w = \infty$ then $w \in S$......  Just because the set is defined to allow $w = \infty$ doesn't mean that it does have it.)
So we don't know that there is an $r$ so that $r^2=2$.
But we do know that $s=\sup L$ exists. (That because $L$ is not empty [$1\in L$] and $L$ is bounded above [If $s\ge 2$ then $s^2 \ge 4>2$ so $s\not \in L$ so $2$ is an upper bound] and the reals have the least upper bound property.)
So how does $s^2$ compare to $2$?  Either $s^2 < 2$ or $s^2 > 2$ or $s^2 = 2$.  If we can prove $s^2 < 2$ and $s^2 > 2$ are both impossible than we'd have to conclude $s^2 \ge 2$ and $s^2 \le 2$ and we must conclude $s^2 = 2$
=======

 if $s^2 < 2$ then if we let $\epsilon = \frac {2-s^2}3$.  As $1$ and $1\in L$ we know that $\epsilon \le \frac 13$ so $\epsilon^2 < \epsilon$.  And so $(s+ \epsilon)^2 = s^2 + 2\epsilon + \epsilon^2< s^2 + 3\epsilon =s^2-(2-s^2) = 2$.  So $s < s+\epsilon \in L$ contradicting that $s$ is an upper bound of $L$.

 So $s^2 \ge 2$.

 Do something similar if we assume $s^2 > 2$.  Then let $\delta = \frac{s^2 -2}2$.  As $y \ge 1.5\implies y^2 \ge 2.25$ we know $\delta < 1$ so $\delta^2 < \delta$ and .... same stuff.   $(s-\delta)^2 = s^2 - 2\delta + \delta^2> s^2 -2\delta = s^2 -(s^2-2) = 2$.  (And if $t\ge  (s-\delta)$ then $t^2 \ge (s-\delta)^2 > 2$.) So $s-\delta$ is an upper bound contradicting that $s$ is the least upper bound of $L$.

So $s^2 \le 2$.
Well if $s$ exists, and $s^2 \ge 2$ and $s^2 \le 2$ then we must have $s^2 = 2$.
And that's that.
And, yes, $s \in L$.
(Actually the proof would have worked just as well if we had defined $L$ as $L = \{x| x\ge 0; x^2 < 2\}$.  ANd just as an aside there was no need to specify $x \ge 0$--- it doesn't matter that negative values are in $L$ because the $\sup$ would still be positive.)
Comment: "there is no problem defining sets that have elements that I want to show which exist/not exist?"  Sure consider the set $K=\{n \in \mathbb N|n$ is prime$; n \le 10000\}$ that doesn't mean $10000\in K$.  Or consider the set $P= \{x\in R| x^2 \le-42\}$.  That doesn't mean $\sqrt{-42}\in P$.
Comment: So essentially, there is no problem defining sets that have elements that I want to show which exist/not exist? ( As long as the set is not empty and there are no paradoxes ).
Comment: And also, as long as the set  is defined with properties already established in my working-environment ( for example If I already learned about natural numbers and there is no restriction to using them in whatever problem I'm working on then I have no problem defining sets composed of natural numbers ).


Using an RMSE with derived confidence interval, to generate a prediction interval for an estimate

Question: Previous questions have asked about creating prediction intervals for estimates derived from random forests or boosted regression trees, in a similar way to is easily achieved with linear regression models.
A comment on this question described the RMSE as an estimate of the standard deviation of the residual error, supporting use of the RMSE in construction of an interval around a prediction (or estimate) from a BRT or RF.
Am I right in thinking that CART methods relax the requirement for homoscedasticity?  If so, it would seem that using the RMSE calculated across the full range of residuals would lead to inappropriately wide intervals in some regions, and too narrow intervals in others.  It would then seem the only way to estimate an interval would be through bootstrapping (BRT) or accessing trees' individual predictions (RF).
[That same question] (Confidence interval of RMSE) attracted advice on the construction of a confidence interval for the standard deviation of residuals, assuming mean residual is zero, with normal distribution, based on a chi squared statistic around the RMSE.
How would such an interval on the SD be used?  Would using the high end of the CI for SD as the value in a CI such as $\hat{x} \pm z\hat{SD}_u$ be a valid, if conservative, interval?  Could you still attribute a specific 'confidence' value (e.g. 95%) to such an interval, given that it has 'nested' confidences?
Comment: I'm interested to know if you found a resolution to this question.
Comment: Another good question left unanswered on CV....
Comment: Wish I could help, but I'm curious about the answer myself!
Comment: I asked a question that is related to this: https://stats.stackexchange.com/questions/524863/simple-constant-width-prediction-interval-for-a-regression-model. Your point that "using the RMSE calculated across the full range of residuals would lead to inappropriately wide intervals in some regions, and too narrow intervals in others" reminds me of the note at the end of my question, where I wrote "this is true [the intervals have the desired coverage] only on average: if we condition on X, we can find subsets of the predictor space where the intervals have lower coverage."
Answer: The CART, as I understand it, does not have homoscedasticity assumptions.  If anything it presumes that the variance of each component is independent from the variance of all other components.  It doesn't account for correlations in variables either.
The normality assumption is problematic.  It is convenient but not necessarily true.  There is often hand-waving about "law of large numbers" but the real world, impo, likes to frustrate such things.
Have you considered using quantile regression forests for your estimate, or is that part of the problem?


Como capturar atributo class com Cheerio?

Question: Estou estudando Web Scrapping com Cheerio e Request. Estou tendo dificuldade ao tentar capturar o atributo class no site da Amazon que contém uma lista de div e não está retornando nada.
var Crawler = {
    request : null,
    cheerio : null,
    init : function(){
        Crawler.request = require('request');
        Crawler.cheerio = require('cheerio');
        Crawler.getProducts();
    },
    getProducts: function(){
        Crawler.request('https://www.amazon.com.br/s?k=notebook&__mk_pt_BR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=13P0U6JH9AMHS&sprefix=%2Caps%2C416&ref=nb_sb_ss_i_1_1', function(err, res, body){
            if(err) console.log('Error: ' + err);

            var $ = Crawler.cheerio.load(body);

            $('div.s-result-list.s-search-results.sg-row div').each(function(){
                console.log("capturou");
            });
        });
    }
};
Crawler.init();

O que estou fazendo de errado ?
Answer: Falta informar o atributo gzip no seu request:
Crawler.request({
  gzip: true,
  method: 'GET',
  url: 'https://www.amazon.com.br/s?k=notebook&__mk_pt_BR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=13P0U6JH9AMHS&sprefix=%2Caps%2C416&ref=nb_sb_ss_i_1_1',
}, function (err, res, body) {
  // Execucação ...
});

gzip
if true, add an Accept-Encoding header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response.

Em tradução livre:

Se true, adiciona um cabeçalho Accept-Encoding para requisitar o conteúdo comprimido do servidor (se ainda não estiver presente) e decodifica conteúdos de codificação suportadas na resposta.

Fora isso seu código não está seguindo as boas práticas para o Node.js, mas sem saber a versão que você está utilizando (e considerando que não faz parte da resposta) é inviável sugerir mudanças.


Não aparecem erros no VSCode (ex: erros referenciando algo digitado de forma errada)

Question: Já olhei em tudo que tinha e não consegui ainda...
Estou estudando ASP.NET Core, com C#, e não aparecem os erros no Visual Studio Code.
Exemplo: se eu referenciar uma classe com o nome errado, não dá alerta nenhum.
Onde posso arrumar isso?
(Os erros de estrutura aparecem)

O erro:
Some projects have trouble loading. Please review the output for more details.
Source: C# (Extension)
<code>   [info]: OmniSharp.MSBuild.ProjectManager
        Loading project: c:\Users\Vanessa\Desktop\Engenharia de Computação\Estágio\SSTecnologia\2-DotNETCore\ProAgil.Domain\ProAgil.Domain.csproj
[warn]: OmniSharp.MSBuild.ProjectManager
        Failed to load project file 'c:\Users\Vanessa\Desktop\Engenharia de Computação\Estágio\SSTecnologia\2-DotNETCore\ProAgil.Domain\ProAgil.Domain.csproj'.
c:\Users\Vanessa\Desktop\Engenharia de Computação\Estágio\SSTecnologia\2-DotNETCore\ProAgil.Domain\ProAgil.Domain.csproj(1,1)
Microsoft.Build.Exceptions.InvalidProjectFileException: o SDK 'Microsoft.NET.Sdk' especificado não pôde ser encontrado.  c:\Users\Vanessa\Desktop\Engenharia de Computação\Estágio\SSTecnologia\2-DotNETCore\ProAgil.Domain\ProAgil.Domain.csproj
   em Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(String errorSubCategoryResourceName, IElementLocation elementLocation, String resourceName, Object[] args)
   em Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(String directoryOfImportingFile, ProjectImportElement importElement, List`1& projects, SdkResult& sdkResult, Boolean throwOnFileNotExistsError)
   em Microsoft.Build.Evaluation.Evaluator`4.ExpandAndLoadImports(String directoryOfImportingFile, ProjectImportElement importElement, SdkResult& sdkResult)
   em Microsoft.Build.Evaluation.Evaluator`4.EvaluateImportElement(String directoryOfImportingFile, ProjectImportElement importElement)
   em Microsoft.Build.Evaluation.Evaluator`4.PerformDepthFirstPass(ProjectRootElement currentProjectOrImport)
   em Microsoft.Build.Evaluation.Evaluator`4.Evaluate(ILoggingService loggingService, BuildEventContext buildEventContext)
   em Microsoft.Build.Evaluation.Project.Reevaluate(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   em Microsoft.Build.Evaluation.Project.ReevaluateIfNecessary(ILoggingService loggingServiceForEvaluation, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   em Microsoft.Build.Evaluation.Project.Initialize(IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   em Microsoft.Build.Evaluation.Project..ctor(String projectFile, IDictionary`2 globalProperties, String toolsVersion, String subToolsetVersion, ProjectCollection projectCollection, ProjectLoadSettings loadSettings, EvaluationContext evaluationContext)
   em Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)
   em OmniSharp.MSBuild.ProjectLoader.EvaluateProjectFileCore(String filePath) na D:\a\1\s\src\OmniSharp.MSBuild\ProjectLoader.cs:linha 129
   em OmniSharp.MSBuild.ProjectLoader.BuildProject(String filePath) na D:\a\1\s\src\OmniSharp.MSBuild\ProjectLoader.cs:linha 72
   em OmniSharp.MSBuild.ProjectFile.ProjectFileInfo.Load(String filePath, ProjectIdInfo projectIdInfo, ProjectLoader loader) na D:\a\1\s\src\OmniSharp.MSBuild\ProjectFile\ProjectFileInfo.cs:linha 98
   em OmniSharp.MSBuild.ProjectManager.LoadOrReloadProject(String projectFilePath, Func`1 loader) na D:\a\1\s\src\OmniSharp.MSBuild\ProjectManager.cs:linha 308

[fail]: OmniSharp.MSBuild.ProjectManager
        Attempted to update project that is not loaded: c:\Users\Vanessa\Desktop\Engenharia de Computação\Estágio\SSTecnologia\2-DotNETCore\ProAgil.API\ProAgil.API.csproj
</code>
Comment: Por padrão, o VSCode não detecta os erros mesmo. Quem detecta os erros é a IDE do Visual Studio. Mas você pode ter a detecção de erros no Code, tem uma extensão que faz isso, mas não sei ao certo o nome dela.
Comment: @Vanessa Alves, verifica se você tem a extensão *C# for Visual Studio Code (OmniSharp)* instalada no VSCode: [https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp](https://marketplace.visualstudio.com/items?itemName=ms-vscode.csharp)
Comment: Ainda não consegui, alguma ideia?
Comment: instalou a extensão?
Comment: Não consegui achar nenhuma extensão sobre isso... já tenho algumas instaladas, mas como estou aprendendo a usar o VSCode agora não sei muito bem qual seria
Comment: Tenho instado a extensão sim. Já procurei em todo lugar pra resolver isso e não consigo
Answer: Seus pacotes instalados provavelmente estão dando conflito nas versões, procure instalar todos da mesma versão e verifique se a versão do sistema bate com o sdk instalado no seu pc.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: caso tenha instalado as versões erradas, tente dar um update para a versão mais atual, exemplo: dotnet tool update --global dotnet-ef --version 6.0.0
Answer: Galera eu também estava com este problema, porém eu estava acostumado a apenas abrir a pasta e clicar em abrir com visual studio. Depois de muita luta descobri que se abre o projeto executando o arquivo .sln a partir disso funcionou normalmente, espero ter ajudado.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


drupal_match_path() for multiple wildcard patterns?

Question: I want to add some CSS and JS to multiple matched wildcard URL patterns. According to Add javascript to multiple specific urls, I can use a wildcard using drupal_match_path() and that works well for one pattern. However, I am trying to use a few patterns to add the same JS and CSS. So far I've tried these:
  // By path matching wildcard patterns.
  $path = drupal_get_path_alias();
  $pattern = 'portfolio/* || photo-blog';

and
  $path = drupal_get_path_alias();
  $pattern = 'portfolio/*, photo-blog';

and
  $pattern = 'portfolio/*' 'photo-blog';
  $path = drupal_get_path_alias();

... but none of these work. I am guessing it may not be possible in the context of:
if (drupal_match_path($path, $pattern)) {
// add JS and CSS based on above
  }

Answer: The API page you've linked describes the format of the $patterns argument:

$patterns: String containing a set of patterns separated by \n, \r or
  \r\n.

These are types of carriage returns, in different Operating Systems.
Sooo .... did you try:
 $pattern = "portfolio/*\nphoto-blog";
 // or
 $pattern = "portfolio/*\rphoto-blog";
 // or
 $pattern = "portfolio/*\r\nphoto-blog";

EDIT:
 // for platform portability heh
 $pattern = "portfolio/*" . PHP_EOL . "photo-blog";

Answer: This one got me so many times - drupal_match_path() is expecting a newline character to separate the paths. Add this function to your project and never look back:
function _get_path_pattern_string(array $items) {
  return implode(PHP_EOL, $items);
}

Example usage (overly verbose):
$patterns = array('portfolio/*', 'photo-blog', 'something-else');
$pattern_string = _get_path_pattern_string($patterns);
if (drupal_match_path($path, $pattern_string)) {
  // Do something...
}

Comment: hmmm ... `return implode(PHP_EOL, $items)'` ?
Comment: @tenken Yep stupid mistake, thanks for pointing that out


Execute Code Between If and Else-if Statement in Java

Question: I got this code:
if (conditionX) {

                    doX();
                }

else if (conditionY) {
                    boolean isSomethingTrue = findOutIfSomethingIsTrue();
                    if (anotherConditionIsTrue) {
                        doY();
                    }
                }

XYZPojo xyzPOJO = getXYZPOJO();

else if (xyzPOJO.getValueX().contains("xyz")) {  // <- eclipse wants me to delete this 'else' statement

                    doXYZ();

                }

When I run this code eclipse complains that "Syntax error on token "else", delete this token". I understand this is because I have the code:
boolean conditionXYZ = checkIfXYZIsTrue();

between both else if statements. But I cannot check the value of conditionXYZ unless I set the value of conditionXYZ in between both else if statements.
The only other similar question I found on SO is this one and it suggests to use two if statements. The problem is I don't want conditionXYZ to be evaluated if conditionY is true.
My other option is to use two if statements and add a return statement for each if statement. But I do not find this solution to be elegant in terms of code design.
My third option is to  checkIfXYZIsTrue() before executing any of the if statements but this is not efficient because if conditionY is true we don't need to check conditionXYZ.
Any ideas?
Thanks in advance
Comment: And what exactly is conditionXYZ ?
Comment: think about additional `{ }` in the middle. Sorry, i cant understand algoritjhm
Answer: Java syntax doesn't allow you to have statements between chains of if/else (that's not in their respective blocks).
You can execute your third condition in the else if condition:
if (conditionX) {
    doX();
} else if (conditionY) {
    boolean isSomethingTrue = findOutIfSomethingIsTrue();
    if (anotherConditionIsTrue) {
        doY();
    }
} else {
    XYZPojo xyzPOJO = getXYZPOJO();
    if (xyzPOJO.getValueX().contains("xyz")) {
        doXYZ();
    }
    //reuse xyzPOJO
}

Alternatively, the last else can still look like:
} else if (getXYZPOJO().getValueX().contains("xyz")){
    doXYZ();
}

Comment: I had done this initially however  checkIfXYZIsTrue() actually returns and object and I'm evaluating one of the fields of the object as in objectX.getField() and I'm checkinf if the field contains a certain value (I edited the code in my OP for simplicity) . I also need to use this field in the final else if statement -- this means I would need to get this value twice if I put it in the else if condition.. one in the condition and once in the actual block
Comment: Then you can call put the call to `checkIfXYZIsTrue()` inside the final `else` and have a nested `if/else` in the final `else`.  If you update the question with that info, I can update my answer.
Comment: Updated the answer
Answer: I know this is pretty old, but seeing as no one gave the answer I would have, I figured I would post my answer incase anyone else finds their way here looking for options.

The problem is I don't want conditionXYZ to be evaluated if conditionY is true.

You could use a ternary operator to check that conditionX and conditionY are false before evaluating conditionXYZ above the if/else statements.
//Evaluates xyzPOJO only if conditionX and conditionY aren't true, otherwise set xyzPOJO to null
XYZPojo xyzPOJO = conditionX==false && conditionY==false ? getXYZPOJO() : null;

if (conditionX) {
    doX();
}
else if (conditionY) {
    boolean isSomethingTrue = findOutIfSomethingIsTrue();
    if (anotherConditionIsTrue) {
        doY();
    }
}
else if (xyzPOJO.getValueX().contains("xyz")) {
    doXYZ();
}


In Drupal 8 how can I print the page title within a paragraph.html.twig

Question: Is there a way to print the page title within a paragraph.html.twig?
In Drupal 7 your could just do a drupal_get_title(); in an tpl.php and use it as a variable.
That function is depreciated and from what I read about TWIG not in the spirit of themeing in Drupal 8 now.
What is the Drupal 8 way to do this?
Answer: An alternative strategy to setting cache context is to use a placeholder. This is a more complex approach but you will never have issues with the database cache table filling up - as 4k4 points out this can be a real problem.
All of this code goes in themename.theme.
First we must define a callback function that returns the page title to the placeholder:
function _MyTheme_paragraphs_title_placeholder($page_title) {
  // Must go here, if you attempt to pass in $page_title from preprocess it will
  // be cached!
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $title_array = array(
    '#theme' => 'page_title',
    '#title' => $page_title,
  );

  return $title_array;
}

Next we create the placeholder in preprocess, we will print a variable in the template, so we must populate it with the placeholder:
function MyTheme_preprocess_paragraph(&$variables) {
  // Note: the first item in the #lazy_builder array is our callback.
  $placeholder_title = array(
    '#lazy_builder' => ['_MyTheme_paragraphs_title_placeholder', ['page_title']],
    '#create_placeholder' => TRUE,
  );

  $variables['title'] = $placeholder_title;
}

Finally create copy the paragraphs template and use the title variable:

  {{ title }}
  {{ content }}

This is how I have implemented the breadcrumb title feature in Adaptivetheme (D8 version), to avoid cache context url as I noticed the database entries, I think it's a great method and I'd love more feedback if I have done something wrong - I'm a themer of course, not a hardcore dev :)
Answer: You can borrow the code from preprocess breadcrumb:
function mytheme_preprocess_paragraph(&$variables)
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $variables['title'] = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $variables['#cache']['contexts'][] = 'url';
}

Twig:
{{ title }}

You need to set a cache context. Normally a paragraph is cached until the cache tag is invalidated by a change in the database. It will appear with the title it was first generated with on all following pages. If you use a context on the url, you get a new cached version of the paragraph for every new path. This will fill up your cache table. So you should try to target only that paragraphs where you need the title.
Or think about another solution, because if you have a big site with many pages this may not be a good idea at all.


Using javascript to display user input with table and deleting a  with button

Question: I am struggling to get this working and would like to know if i'm headed in the right direction with what i have.
Whats supposed to be happening is two input fields that get added to a  on a click event. This part is done and its working fine.
Whats supposed to happen after the input fields get added to the table is you can then delete a tr with a button that gets added when the tr is created. Which is not working. I also cant figure out why the page refreshes when you click the delete button to delete a tr, preventDefault() is being used.

let data             = [];
let speciesInput     = document.querySelector('#speciesInput')
let breedInput       = document.querySelector('#breedInput')
let messageBox       = document.getElementById("display");
const addProductBtn  = document.querySelector('#addValue')
let deleteProductBtn = document.getElementsByClassName('deleteProduct')
const deleteBtnArray = Array.from(deleteProductBtn)

addProductBtn.addEventListener('click', function (e) {
    e.preventDefault();

    let species, breed;
    species = speciesInput.value;
    breed   = breedInput.value;

    data.push({
        species: species,
        breed: breed,
    });
    clearAndShow();
})

function clearAndShow() {
    // Clear our fields
    speciesInput.value   = "";
    breedInput.value     = "";
    messageBox.innerHTML = computeHTML();
}

function computeHTML() {
    let html = "
";
    data.forEach(function (item) {
        html += "
";
        html += "" + item.species + '&nbsp' + "	"
        html += "" + item.breed + "	"
        html += "" + "<button class='deleteProduct' onclick='deleteProduct()'> − </button>" + "	"
        html += "
"
        console.log(deleteBtnArray)
    });
    html += "
"
    return html;
}

function deleteProduct() {
    console.log(deleteBtnArray)
    deleteBtnArray.forEach((btn) => {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            console.log('Delete item')
            deleteItem() // Not made yet
        })
    })
}
deleteProduct()

document.querySelector('#productForm').addEventListener('submit', function (e) {
    e.preventDefault();
})

Welcome

      Set up your profile to begin interacting with the community.

    Add Your Product For Display
    <form id="productForm" class="form d-flex flex-column align-items-center mt-2" action="">

            <input id="speciesInput" class="sign-up-inputs addProductInputs" type="text" placeholder="Species">

            <input id="breedInput" class="sign-up-inputs addProductInputs" type="text" placeholder="Breed">

          <button id="addValue" class="add-product-btn btn-active mt-4 ms-2">+</button>

      <button class="primary-btn continue-btn btn-active mt-4">Continue</button>
    </form>
    <button class="back-btn btn-active me-auto mt-4">Back</button>

Welcome

            Set up your profile to begin interacting with the community.

        Add Your Product For Display
        <form class="form d-flex flex-column align-items-center mt-2" action="">

                        <input id="speciesInput" class="sign-up-inputs addProductInputs" type="text" placeholder="Species">

                        <input id="breedInput" class="sign-up-inputs addProductInputs" type="text" placeholder="Breed">

                    <button id="addValue" class="add-product-btn btn-active mt-4 ms-2">+</button>

            <button class="primary-btn continue-btn btn-active mt-4">Continue</button>
        </form>
        <button class="back-btn btn-active me-auto mt-4">Back</button>

Javascript
let data = [];
let speciesInput = document.querySelector('#speciesInput')
let breedInput = document.querySelector('#breedInput')

let messageBox = document.getElementById("display");
const addProductBtn = document.querySelector('#addValue')
let deleteProductBtn = document.getElementsByClassName('deleteProduct')
const deleteBtnArray = Array.from(deleteProductBtn)

addProductBtn.addEventListener('click', function (e) {
    e.preventDefault();

    let species, breed;
    species = speciesInput.value;
    breed = breedInput.value;

    data.push({
        species: species,
        breed: breed,
    });
    clearAndShow();
})

function clearAndShow() {
    // Clear our fields
    speciesInput.value = "";
    breedInput.value = "";
    messageBox.innerHTML = computeHTML();
}

function computeHTML() {
    let html = "
";
    data.forEach(function (item) {
        html += "
";
        html += "" + item.species + '&nbsp' + "	"
        html += "" + item.breed + "	"
        html += "" + "<button class='deleteProduct' onclick='deleteProduct()'> − </button>" + "	"
        html += "
"
        console.log(deleteBtnArray)
    });
    html += "
"
    return html;
}

function deleteProduct() {
    console.log(deleteBtnArray)
    deleteBtnArray.forEach((btn) => {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            console.log('Delete item')
            deleteItem() // Not made yet
        })
    })
}
deleteProduct()

Comment: _"I also cant figure out why the page refreshes when you click the delete button"_ — A [``'s](//developer.mozilla.org/docs/Web/HTML/Element/button) default `type` in a submittable `` is `submit` and you're _not_ preventing the default action of the `submit` event dispatched by the ``.
Comment: Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead.
Comment: Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it's more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)'s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212).
Comment: Thank you for these suggestions! i will probably refactor this a bit after i get it working... I'm also still really new to javascript
Answer: There is more than one thing happening

The variables on top of your JS code are recovering elements from the document object only when the page loads. You are not updating them (I.E. the deleteBtnArray) after appending the html on clearAndShow() function. That's why the deleteBtnArray is always empty when you click the - buttons.
One way to avoid this is collectiong the elements inside the deleteProduct function. Also, you don't need to convert into array using Array.from because document.getElementsByClassName(...) already returns an iterable collection. Also, using "for of" is a little better readable than forEach with callbacks.

You are adding the deleteProduct(...) function more than once using this method, because you are calling using the onclick='deleteProduct()' and also btn.addEventListener('click'...). And after that you also call the deleteProduct function right after its declaration. No need for that.

If you want to remove the whole
, there is a easy way of doing that referencing each
 with an id and using it as argument for the deleteProduct function, just like in the example below

Replace your whole javascript by this, and use the same HTML
let data = [];
var speciesInput = document.querySelector('#speciesInput')
var breedInput = document.querySelector('#breedInput')
var messageBox = document.getElementById("display");
var addProductBtn = document.querySelector('#addValue')

addProductBtn.addEventListener('click', function (e) {
  e.preventDefault();

  let species, breed;
  species = speciesInput.value;
  breed = breedInput.value;

  data.push({
    species: species,
    breed: breed,
  });
  clearAndShow();
})

function clearAndShow() {
  // Clear our fields
  speciesInput.value = "";
  breedInput.value = "";
  messageBox.innerHTML = computeHTML();
}

function computeHTML() {
  let html = "
";
  data.forEach(function (item, index) {
    html += "
";
    html += "" + item.species + '&nbsp' + "	"
    html += "" + item.breed + "	"
    html += "" + "<button onclick='deleteProduct(" + index + ")'> − </button>" + "	"
    html += "
"
  });
  html += "
"
  return html;
}

function deleteProduct(removedIndex) {
  document.getElementById("line-" + removedIndex).remove()
  data = data.filter(function (item, index) { return index != removedIndex })
}

document.querySelector('#productForm').addEventListener('submit', function (e) {
  e.preventDefault();
})

Bonus:
I recommend you to use ` instead of " or ' when writing html inside strings, because

You can insert variables using ${variableName}
You can break lines
You can use ' and " freely inside strings delimited by `
You don't need to use a lot of +=

I also recommend you to use .map( instead of .forEach(. Things get cleaner this way.
Replace the computeHTML() I've shown before with this piece of code:
function itemHtml(item, index) {
  return `

    ${item.species}
    ${item.breed}
    <button onclick="deleteProduct(${index})"> − </button>

`
}

function computeHTML() {
  return `<table>${data.map(itemHtml)}</table>`
}

Comment: Thank you for doing this, ive been stuck on this for a while. I really appreciate you taking the time to explain things as-well it really helps me out. If u do have time there are a couple lines i done really understand how its working...
<tr id="line-${index}" - how is this keeping track of the index?                                               onclick="deleteProduct(${index})" - what is ${index} doing?
Comment: When you use ` instead of " or ' on beginning and ending of strings, you can put variables inside the string and their values will be inserted there. You just need to wrap the variable inside ${ and }
Example:
var name = "Caio"
var phrase = `My name is ${name}, you khow?`

Also, the index will be a counter with the "position" of every element inside the original array (in this case, the array is the variable "data"). So, the first  will have an id="line-0", the second one will have "line-1"


In a Dirichlet process, can the base distribution be discrete?

Question: Must it be continuous? Note we are talking about the base distribution. The sampled distribution is discrete.
1) If the base distribution is continuous, drawing from it will get a new value (a new cluster mean, for example) every time.
2) But, you can nest Dirichlet processes. Which implies the base distribution can be discrete. (You can place a prior over your base distribution which is just another Dirichlet process).
Consider the Blackwell-Macqueen urn scheme.
H is a distribution over colors.
Start with an empty urn.
With probability alpha sample a color from H. Note, if H is continuous, you'll get a different color every time. If the H is discrete, you may draw colors already present in the urn.
With probability proportional to n-1, pick a ball from the urn. Put the ball back and another one of the same color.
Reference: http://www.columbia.edu/~jwp2128/Papers/PaisleyWangetal2015.pdf
edit: The paper above demonstrates this is possible. Any distribution drawn for the a DP with a discrete base distribution will have the same atoms as the base distribution, but with different weights.
Still, I wonder how the CRP would work under this scheme since there's a chance you'd select a non-empty table (analogously to the above urn scheme).
Comment: Apparently, after reading a few excerpts from some papers, I think they can be. Not sure then how this fits in with sampling schemes.
Answer: The base measure can be discrete. An example of the case where it is discrete is the Hierarchichal Dirichlet Process, wherein $F_j \sim \mathcal D(\alpha F_0)$ where $F_0 \sim \mathcal D(\gamma H)$. The base measure of the second level of the hierarchy ($F_0$) is discrete with probability $1$.


How do I change position of a "fixed" element/header to go below Admin toolbar when in Admin view?

Question: New to JS / CSS
How do I change / control the position of a sticky navigation bar to go below Admin toolbar when in Admin mode?
Site uses:

Subtheme of Omega / Commerce Kickstart
Through subtheming, I have two sticky "zones": (1) user (contains login/checkout); (2) menu-super (main menu)
User zone is sticky and came as part of the Commerce Kickstart theme and works in both regular user and admin mode.
My new "Menu-Super" works in regular user mode, but disappears behind the admin toolbar when viewing as an admin. (less than ideal.)

In the js file, I found the following:
// Handle user toolbar when user is admin and have admin toolbar enabled.
  Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
        });
      }
    }
  }
I tried repurposing this code to handle my new zone, but no dice. When I clear cache, I can see the zone built and then pop up under the admin bar. What am I missing here?
Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
    attach: function(context, settings) {
      if ($('body').hasClass('toolbar')) {
        $(window, context).resize(function() {
          var toolbarHeight = $('div#toolbar').height();
          var zoneuserHeight = $('div#toolbar').height()+ $('div#zone-user').height();
          $('.zone-menu-super-wrapper').css('top', zoneuserHeight + 'px');
        });
      }
    }
  }
where the css file specifies
User Zone (Working)
.zone-user-wrapper {
  background-color: #666666;
  height: 32px;
  width: 100%; }
Super Menu Zone (Not working)
.zone-menu-super-wrapper {
  background-color: #9E4934; /*Monkey brown*/
  height: 36px;
  width: 100%;
  position: fixed;
  top: 32px;
  z-index: 99;}
Comment: Are you using the contrib admin_menu or the normal admin toolbar from Drupal 7? This can be fixed with CSS but the answer depends on which one you are actually using
Comment: @burnsjeremy: I am using the admin menu that comes with Commerce Kickstart. It is a customized menu that comes as part of that distribution.
Answer: In drupal you need to use jquery like this
(function ($) {
 $( document ).ready(function() {

      // custom code here

     });
  });
}(jQuery));

So try:
(function ($) {
  $( document ).ready(function() {
      Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
        attach: function(context, settings) {
          if ($('body').hasClass('toolbar')) {
            $(window, context).resize(function() {
              var toolbarHeight = $('div#toolbar').height();
              $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
            });
          }
        }
      }
    });
  });
}(jQuery));

If that doesn't work, all you have to do is check if the toolbar div class or id exists.
if ($('#toolbar').length > 0) {
    // dostuff
}

So if there is a wrapper that wraps everything on your site except the admin toolbar. that would be more ideal to use. So all you do is move everything down by 10 or so pixels
Using CSS with jQuery
(function ($) {
 $( document ).ready(function() {
          if ($('#toolbar').length > 0) {
           $('.zone-user-wrapper').css({"position": "relative", "top": "10px"})
           }
     });
  });
}(jQuery));

Comment: Thanks for trying to point me in the right direction. Please let me clarify.
Comment: The new js I added is within the function callout with the other code that came with Kickstart. The js code that I provided for 'zone-user-wrapper' works. I created a second zone / region ("menu-super") that sits below the "user" zone and want it to be handled in the same way. When I try to add identical code for the second zone, nothing happens.
Comment: highlight the second zone / region and right mouse click and select inspect element. double check that the div wrapper is indeed `.zone-menu-super-wrapper` perhaps you have the wrong name?
Answer:
The new js I added is within the function callout with the other code
  that came with Kickstart. The js code that I provided for
  'zone-user-wrapper' works. I created a second zone / region
  ("menu-super") that sits below the "user" zone and want it to be
  handled in the same way. When I try to add identical code for the
  second zone, nothing happens.

highlight the second zone / region and right mouse click and select inspect element. double check that the div wrapper is indeed .zone-menu-super-wrapper perhaps you have the wrong name?
you don't need 2 separate codes just add the
var zoneuserHeight = $('div#toolbar').height()+ $('div#zone-user').height();

and
 $('.zone-menu-super-wrapper').css('top', zoneuserHeight + 'px');

lines to your first code
   Drupal.behaviors.commerce_kickstart_theme_custom_toolbar = {
        attach: function(context, settings) {
          if ($('body').hasClass('toolbar')) {
            $(window, context).resize(function() {
              var toolbarHeight = $('div#toolbar').height();
              var zoneuserHeight = $('div#toolbar').height() + $('div#zone-user').height();
              $('.zone-user-wrapper').css('top', toolbarHeight + 'px');
              $('.zone-menu-super-wrapper').css('top', zoneuserHeight + 'px');
            });
          }
        }
      }

Also, make sure that your .zone-menu-super-wrapper has position: relative; or position: absolute; otherwise the top: zoneuserHeight won't work.
Example: Does Not Work
Example: Works
PS:
perhaps this line
var zoneuserHeight = $('div#toolbar').height() + $('div#zone-user').height();

needs to be
var zoneuserHeight = $('div#toolbar').height() + $('div#zone-user-wrapper').height();

Comment: Nearly there - I added in the code you recommended. It does not work without changing the zone-menu-super `{position: relative}`, as you stated. However, that negates my ability to keep this zone as sticky. I need both "zone-user" and "zone-menu-super" to be sticky. Out of the box from Commerce Kickstart, "zone-user" is sticky, but I don't see the position call out in the global.css for that zone. In order to make my new zone sticky, I added in `position: fixed;`, but ran into this issue with the admin menu. What am I missing here?  PS `absolute` does not work :)
Comment: "I added in position: fixed; but ran into this issue with the admin menu". so you made `.zone-menu-super { position: fixed; }` so whats the issue with admin menu?
Comment: When in the admin view, the new "zone-menu-super" disappears. As the page loads, I see it build, but then it disappears behind the admin menu. However, the Commerce-created "zone-user" does not behave this way.


How teams are ranked if they are equal in points in UCL groups

Question: Quoting from from the UEFA rules:

If two or more teams are equal on points on completion of the group matches, the following criteria are applied in the order given to determine their rankings:
a. higher number of points obtained in the group matches played among the teams in question;
  b. superior goal difference from the group matches played among the teams in question;
  c. higher number of goals scored in the group matches played among the teams in question;
  d. higher number of goals scored away from home in the group matches played among the teams in question;
  e. if, after having applied criteria a) to d), teams still have an equal ranking, criteria a) to d) are reapplied exclusively to the matches between the teams in question to determine their final rankings. If this procedure does not lead to a decision, criteria f) to l) apply;
  f. superior goal difference in all group matches;
  g. higher number of goals scored in all group matches;
  h. higher number of away goals scored in all group matches;
  i. higher number of wins in all group matches;
  j. higher number of away wins in all group matches;
  k. lower disciplinary points total based only on yellow and red cards received in all group matches (red card = 3 points, yellow card = 1 point, expulsion for    two yellow cards in one match = 3 points);
  l. higher club coefficient (see Annex D).

I don't see the point of rule "e". For me

group matches played among the teams in question

is exactly the same as

exclusively to the matches between the teams in question

I'm not the only one confused by this:

But then Uefa throws us a curveball:
5) if, after having applied criteria a) to d), teams still have an
  equal ranking, criteria a) to d) are reapplied exclusively to the
  matches between the teams in question to determine their final
  rankings. If this procedure does not lead to a decision, criteria f)
  to h) apply;
Say what now? Is that not what we just did? Applied those rules to the
  "teams in question"? I thought, perhaps, I'd read something wrong and
  Uefa meant all members of the specified group, rather than the three
  even on points. But that doesn't make sense either:

Could someone give an example of when rule "e" applies?
Answer: It's used when you started with three teams equal on points, but one (and only one) of the teams was ruled out via criteria (a) to (d). For simplicity, I'll go with a scenario where each team plays each other once only rather than twice. Imagine the results are:
A beats B 2 - 0
A loses to C 1 - 2
A beats D 1 - 0
B beats C 3 - 0
B beats D 1 - 0
C beats D 1 - 0
After this, A, B and C all have six points and D has zero points so we need to separate A, B and C:

(a): We consider the matches played between A, B and C. Each team has three points.
(b): We consider the matches played between A, B and C. A and B have a goal difference of +1, C has a goal difference of -2. C is ranked lower than the other teams.
(c): Note that we still consider the matches played between A, B and C. Nothing says to eliminate the matches involving team C (yet). A and B have both scored 3 goals.
(d): (Skipping for this example because I don't have home and away matches)

We now apply criterion (e), which says to repeat steps (a) to (d) only on the matches involving teams A and B. A is declared the winner as they beat team B.
Note that if the A - C result had instead been 0 - 1, team B would have been the winner as they would have scored more goals in the matches involving teams A, B and C.


Limit, in distribution, of random variable defined for each n

Question: For each $n \in N $, let $X_n$ a random variable with probability distribution:
$$P(X_n = j) = \frac{2j}{n(n+1)}$$
With $j = 1,\dots,n$
I need to find:
a) Cumulative distribution Function of the random variable $Yn = X_n/n$
b) Limit, in distribution, of the sequence $(Y_n)_{n \ge 1}$
For a) I was trying just integrating it:
$P(Y_n \le j) = P(X \le nj) = \int_{1}^{nj}\frac{2j}{n(n+1)} dj = \frac{n}{n+1} (j^2 - 1)$
For the distribution, just derive a):
$\frac{d P(Y_n \le j)}{dj} = 2j \frac{n}{n+1}$
Now, how should I proceed to work b)? When $n \to \infty$ it should look like a known distribution? Have I made a mistake in a)?
Comment: When $j \ge 2$, your probabilities in your solution to $(a)$ are obviously greater than $1$.  In $(b)$, pick any $j$: what happens to $\Pr(Y_n=j)$ as $n$ increases?
Comment: Now your probabilities are negative!
Comment: This transformation is making me very confused. I'm trying $P(X \le nj) = \int_{n}^{nj}\frac{2j}{n(n+1)}$, but this evaluates to $\frac{n(j^2 - 1)}{n-1}$, which still doesnt make sense. The boundaries of j before the transformation were 1 and n, so they should be n and n^2 after it. For example, if I was just doing without a transformation it would be: $P(X \le j) = \int_{1}^{j}\frac{2j}{n(n+1)} = \frac{j^2 - 1}{n(n-1)}$
Answer: The cumulative distribution function for $X_n$:
$$F_{X_n}(j) = \sum_{i=1}^{j}\frac{2i}{n(n+1)} = \frac{j(j+1)}{n(n+1)}$$
The cum. distr. funct. for $Y_n$:
$$F_{Y_n}(k = \frac{j}{n}) = \frac{j(j+1)}{n(n+1)} = \frac{n^2\frac{j}{n}(\frac{j}{n}+\frac{1}{n})}{n(n+1)} = \frac{nk(k+\frac{1}{n})}{n+1}$$
keeping in mind $k \in [0,1]$ and taking the limit $n \to \infty$
$$\lim_{n \to \infty}F_{Y_n}(k) = \lim_{n\to \infty} \frac{nk^2+k}{n+1}= k^2$$
Comment: @gung I'm new, so I didn't know [self-study] only requires hints no answers
Comment: Is this an answer to the OP's question? It it a hint? (Please only provide hints for `[self-study]` questions.) Can you elaborate this?
Comment: Damn, just noticed I was trying to integrate a discrete random variable, that's why no result made any sense. I feel so dumb for that. Thanks for the help!
Comment: No problem, @user118591, now you know. You can read more about our `[self-study]` policies (which are special & unique to SS) [here](http://stats.stackexchange.com/tags/self-study/info). Welcome to CV.
Comment: Just a question, is $k \in [0,1]$? Shouldn't it be $k \in [1/n,1]$?
Comment: indeed you are correct but in the limit it goes to $k\in[0,1]$
Comment: @user118591 I don't get why it's possible to set `k = j /n` and then not take it into account when making `n` go infinity.
Comment: You can think of $X_6$ as a unfair (it follows given probability density) 6 sided dice. $Y_6$ is the same 6 sided dice but the sides are 1/6, 2/6, ...,1. Here it is obvious that the probability of getting a 1 with dice $X_6$ is the same as getting 1/6 with the $Y_6$ dice. Taking the limit like using dice with more sides.
Comment: @cd98 ignore my previous comment.
Comment: @cd98 when taking the limit I only need the distribution function of $Y_n$ so its relation to the distribution of $X_n$ is no longer of any meaning
Comment: @user118591 I think my question doesn't have to do with $X_n$ at all. Just considering $Y_n$, the expression has $k$ defined as $\frac{j}{n}$. Later you take the limit as $n \rightarrow \infty$, but take $k$ as fixed, as it didn't depend on $n$. I'm wondering what allows you to do that. If it's something you deem basic, please feel free to ignore it. Otherwise, please incorporate it to the question as other readers might have my same question, thanks :)


asymptotic distribution of a statistic

Question: Say we have iid sample of size $n$ with $X_i \sim Exp(\lambda)$ and the task is to find asymptotic distribution of the statistic $$T_n := \frac{\bar{X}}{s}$$, where $s^2$ is the unbiased sample variance.
Now, it is easy to show that $E(\bar{X}) = E(X) =: \mu$, so (skipping some details) if we let $Y_i := X_i - \mu$, then $\frac{1}{\sqrt{n}} \sum_{k=1}^n Y_k \overset{D}{\to} N(0, \sigma^2_Y)$, where $\sigma^2_Y$ is the variance of $Y$
Now I know how to also show, that $s \overset{p}{\to} \sigma_X$, so that (?) $Var(T_n) \overset{p}{\to} 1$.
So if I'm correct up until here, it feels that well, we have an estimator $T_n$ with variance 1 so its asymptotic distribution should be standard normal. But then I haven't used the fact that the sample has exponential distribution.
Basically, I would be very grateful for tips/scheme on who I should approach/think/solve this problem as it would be the most beneficial in terms of learning.
Note: I know Slutsky theorem, Continuous Mapping Theorem and (classical) CLT.
Comment: I think it does not matter what distribution the sample has as long as the observations are i.i.d. The CLT which kicks in in the asymptotics does not assume a particular distribution of the underlying observations; i.i.d. is enough.
Comment: The only aspects of the exponential that matter are those that come into applying the CLT in some way.
Comment: Are you allowed to use delta method?
Comment: yes, forgot to mention that
Comment: I've added a hint. Note also in your question that $\mathrm{Var}T_n$ is a sequence of numbers, so they converge as numbers, not in probability.
Answer: Here is a hint. Let me know if you need more and I'll expand.
Show that (in particular, make sure to check the assumptions; I didn't):
$$
\sqrt{n}\left( (\bar{X}_n,S_n^2)' - (\mu, \nu)'\right)\overset{d}{\to}N(0,\Sigma),
$$
for some constants $\mu,\nu$ and covariance matrix $\Sigma$. Consider then the function $g(x,y)=x/\sqrt{y}$. What can you say about $g(\bar{X}_n,S_n^2)$, and why?
Comment: I got it, thank you :) I think we can use multivariate CLT too, so that works. just noticed the professor has it in his notes.
Comment: @Sarunas yes you would need multivariate CLT for this. If you don't have that, this may not be the way to go. I'll see if I can update with something based on univariate results when I have time.
Comment: would I be correct in saying that I need some kind of 'multivariate' CLT to show that $ \sqrt{n}\left( (\bar{X}_n,S_n^2)' - (\mu, \nu)'\right)\overset{d}{\to}N(0,\Sigma), $ ?  I realize that the rest is just trivial Delta method application. but I'm not sure on how to show this multivariate convergence in distribution
Answer: As you note yourself, $\mathrm{Var}[T_n]$ becomes 1 in the limit, so $T_n$ becomes deterministically equal to $\mu/\sigma$ in the limit. For the exponential distribution, we have that $\mu=\sigma=1/\lambda$, so $T_n\to 1$.
But that is "the limit value" of $T_n$, i.e. for $n=\infty$. When you ask for "the asymptotic distribution", you probably want to know how $T_n$ is distributed for extremely large $n$ but still $n<\infty$. In that case, the CLT is of limited use and you will have to work out the distribution of $\bar{X}/s$ for general $n$ from scratch. The main difficulty here will most likely be the fact that $\bar{X}$ and $s$ are not independent random variables. Sample mean and sample variance are independent if and only if $X$ is normally distributed.
Comment: What does it mean to "become deterministically equal to in the limit"? If it means almost surely (or something even stronger), then what you say is generally not true. Moreover, CLT is perhaps the most common tool used to find asymptotic distributions.
Comment: The reason that the limit is degenerate is that the scaling $\sqrt{n}$ is missing. Under appropriate scaling, the limit is a random variable.
Comment: @StijnDeVuyst, variance approaching 0 does not imply almost sure convergence, that's what I'm getting at.
Comment: I'm sorry if you feel attacked, that's not anyone's intention I dare to say.
Comment: Yes, I mean almost sure convergence to the deterministic value 1.  That is because the variance of $T_n$ approaches 0.
Yes, CLT is the most common tool for asymptotic distributions but here it gives a strange answer, $T_n \overset{a.s.}{\to} 1$, that may not be very useful. If it is for you, so much the better.
Comment: Yes, ok, probably not.
Comment: That's it, I've had it. I wish you all a very fond farewell.

asymptotic distribution of a statistic