In Blackberry Cascades 10 (C++, Qt, QML), how do I invoke an email client with the fields populated?

Question: In Blackberry Cascades 10 (C++, Qt, QML), how do I invoke an email client with the fields populated?
I have looked into this - and here is what I have tried to do:
<code>InvokeManager invokeManager;
InvokeRequest request;

request.setTarget("sys.pim.uib.email.hybridcomposer");
request.setAction("bb.action.OPEN, bb.action.COMPOSE");
request.setMimeType("message/rfc822");

QString data = QString("{ \"to\" : [\"" + btnEmailTo_->text() + "\"], \"subject\" : \"---This is the Subject---\", \"body\" : \"---This is the Body---\" }");

request.setData(data.toUtf8());

if (reply_ = invokeManager.invoke(request)) QObject::connect(reply_, SIGNAL(finished()), this, SLOT(onInvokeResult()));
</code>
But it seems like this brings up an email client - but none of the fields are populated.
(In case you are wondering - the blackberry device I am testing this on as a main email account setup for - that when you press send in the email client - it does send from the email account set up in the blackberry.)
Answer: The information about invoking emails can be found here: http://developer.blackberry.com/cascades/documentation/device_platform/invocation/email.html#ufa1355425510139.
The only thing I can guess from reading there is that you've screwed up the action -- it should be only bb.action.COMPOSE according to the documentation when invoking an email with pre-populated fields using data in JSON.


Unknown bytes while reading an image from ImageIO after sending it with ImageIO

Question: While transfering images over the network using sockets, I had a -for me- strange issue:
When I wrote images to the OutputStream of one socket with ImageIO.write() and read the same images from the InputStream of the other socket with ImageIO.read() I noticed, that 16 bytes per image were sent more than read.
To be able to send multiple images in a row I had to read these bytes after every call of ImageIO.read() to not receive null because the input could not be parsed.
Does anybody know, why this is so and what these bytes are?
In this piece of code I have extracted the issue:
public class Test implements Runnable
{
    public static final int COUNT = 5;

    public void run()
    {
        try(ServerSocket server = new ServerSocket(3040))
        {
            Socket client = server.accept();
            for(int i = 0; i < COUNT; i++)
            {
                final BufferedImage image = readImage(client.getInputStream());
                System.out.println(image);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    private BufferedImage readImage(InputStream stream) throws IOException
    {
        BufferedImage image = ImageIO.read(stream);

        dontKnowWhy(stream);

        return image;
    }

    private void dontKnowWhy(InputStream stream) throws IOException
    {
        stream.read(new byte[16]);
    }

    public static void main(String... args)
    {
        new Thread(new Test()).start();

        try(Socket server = new Socket("localhost", 3040))
        {
            for(int i = 0; i < COUNT; i++)
            {
                BufferedImage image = new BufferedImage(300, 300, BufferedImage.TYPE_INT_ARGB); //
                int[] vals = new int[image.getWidth() * image.getHeight()];                     //
                Arrays.fill(vals, new Random().nextInt());                                      // Create random image
                image.setRGB(0, 0, image.getWidth(), image.getHeight(), vals, 0, 1);            //

                ImageIO.write(image, "png", server.getOutputStream());  //send image to server

                long time = System.currentTimeMillis();             //
                while(time + 1000 > System.currentTimeMillis());    //wait a second
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }

    }
}

I am glad about any answers, already thank you!
Answer: The "extra" bytes you see, is not read, simply because they are not needed to correctly decode the image (they are, however, most likely needed to form a fully compliant file in the chosen file format, so they are not just random "garbage" bytes).
For any given ImageIO plugin, the number of bytes left in the stream after a read may be 0, 16or any other number. It might depend on the format, the writer that wrote it, the reader, the number of images in the input, the metadata in the file, etc. In other words, relying on this behavior would be an error.
The easies way to fix this, is to prepend each image with a byte count, containing the length of the output image. This typically means you need to buffer the response on the client, to either a ByteArrayOutputStream (in-memory) or a FileOutputStream (disk).
The client then needs to read the byte count for the image, and make sure you skip any remaining bytes after the read. This can be accomplished by wrapping the input (see FilterInputStream) and keep track of the byte count internally.
(You can also read all the bytes up front, and wrapping them in a ByteArrayInputStream, before passing the data to ImageIO.read(), which is simpler but does more in-memory buffering).
After this, the client is ready do start over, by reading a new byte count, and a new image.
Another approach if you'd like less buffering on the server, could be to implement something like HTTP chunked transfer encoding, where you have multiple smaller blocks (chunks) sent to the client for each image, each prepended with its own byte count. You would need to handle the last chunk of each image especially, or insert special delimiter chunks to mark end of stream or start of a new stream.
Code below implements the buffering approach on the server, while using direct reading on the client.
Server:
DataOutputStream stream = new DataOutputStream(server.getOutputStream());

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
for (...) {
    buffer.reset();
    ImageIO.write(image, "png", buffer);

    stream.writeInt(buffer.size());
    buffer.writeTo(stream); // Send image to server
}

Client:
DataInputStream stream = new DataInputStream(client.getInputStream());

for (...) {
    int size = stream.readInt();

    try (InputStream imageData = new SubStream(stream, size)) {
        return ImageIO.read(imageData);
    }
    // Note: imageData implicitly closed using try-with-resources
}

...
// Util class
private static final class SubStream extends FilterInputStream {
    private final long length;
    private long pos;

    public SubStream(final InputStream stream, final long length) {
        super(stream);

        this.length = length;
    }

    @Override
    public boolean markSupported() {
        return false;
    }

    @Override
    public int available() throws IOException {
        return (int) Math.min(super.available(), length - pos);
    }

    @Override
    public int read() throws IOException {
        if (pos++ >= length) {
            return -1;
        }

        return super.read();
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        if (pos >= length) {
            return -1;
        }

        int count = super.read(b, off, (int) Math.min(len, length - pos));

        if (count < 0) {
            return -1;
        }

        pos += count;

        return count;
    }

    @Override
    public long skip(long n) throws IOException {
        if (pos >= length) {
            return -1;
        }

        long skipped = super.skip(Math.min(n, length - pos));

        if (skipped < 0) {
            return -1;
        }

        pos += skipped;

        return skipped;
    }

    @Override
    public void close() throws IOException {
        // Don't close wrapped stream, just consume any bytes left
        while (pos < length) {
            skip(length - pos);
        }
    }
}

Comment: and how can I know exacly how many bytes are remaining? When I send another image right after the first, there is no difference between the "extra bytes" and the bytes of the next image. Trying to read the second after every extra byte to see if it now starts would be very inefficient
Comment: You count how many bytes the `ImageReader` did consume. This can be accomplished either by wrapping the input (`FilterInputStream`) and keep track of the byte count. Another approach is reading all the bytes up front, and wrapping in a `ByteArrayInputStream`. The whole point of the byte count is to know exactly how many bytes to read, there's no need to guess or try.
Comment: I am sorry, but I don't understand it yet. Lets say I am on a client which receives exactly 1 000 000 bytes and I know that there are 3 images to read. How can I know where the second and the third begins? There must be anything in the image format, which the images are send in, that tells me: Image read finished
Comment: I think with your solution I had to buffer the image on the server and the client. Then I could send the total number of bytes, which one image has before the actual image. On the client side I could read all bytes into a buffer with the size of the bytes of this image and let the `ImageIO.read()` read from there. But this means a lot more lag than just letting `ImageIO` handling all the buffer things, am I right? Is it possible without this?
Comment: With 3 images, you will have three byte counts, each telling the length of the next image stream (I edited the answer to make this clearer). Some image formats contain stream size, most don't. If you'd like less buffering on the server, you could implement something like HTTP chunked transfer encoding. And finally yes, it's possible to not buffer on the client, as I wrote in my answer, you just wrap the input stream, and then count bytes until you have read up to the byte count (or if read is done and you haven't, you just skip the remaining bytes).
Comment: ok, it is clearer now. I`d have never thought that something like this would be necessary to transfer images! But thanks a lot for your answers, it has really helped understanding this!
Comment: Good stuff! Actually, the problem isn't strictly related to images, it's about reliably transferring dynamically generated data (with unknown length). :-)


How cmake judging target_link_libraries item is a library name or a target?

Question: I have some troubles in cmake target_link_libraries function.
In my case,there are three projects like this,which means A depends on B,B depends on C
A(exec) --> B(static library) --> C(static library alias C::C)

I write a CMakeLists.txt for B like this:
find_package(C REUQIRED)
add_library(B ...)
target_link_libraries(B PRIVATE C::C)

And it works well ,complie successfully.
A's cmake file like this:
find_package(B REQUIRED)
add_exectuable(A ...)
target_link_libraries(A B)

It reports error when linking A,cmake set a linker flags "-lC::C",and then ld said C::C not exist.
How it happend?I think C::C is a target and A should know it,but cmake think it is a library name.And I think A should not know B depends on C,it's a private library.
I don't want to write find_packge(C) in A's cmake,because C is a static library,I think B should handle all dependcies of C,that's right?
So anyone knows how to fix it ?
Comment: I believe CMake should never treat aliased target (with :: in name) as library. You may have encountered an CMake's error. Do you use the newest one?
Comment: @R2RT Yes,you are right,B treat C::C as a target,but A does not.Maybe this information was lost when A reference B
Comment: By any chance, can you make small reproduction project? How do you use `find_package` here? Do you install `B` and `C`?
Answer: I solved this problem finally.
In my case,B using C's funtion in template code,and B does not instantiate this template,so C::C would not link into B's static library.But A would instantiate B's template,so A need C::C,that's why B's PRIVATE flag was useless.
In order to help A found the C::C,I should use find_depecncy(C) in B's config.cmake to let A knows B's depency when use find_package(B).


The tutorial's problem about addHero (where the new id comes from)

Question: When I want to add a new hero, I will use
add(string) function from heroes/heroes.component.ts
  add(name: string): void {
    name = name.trim();
    if (!name) { return; }
    this.heroService.addHero({ name } as Hero)
      .subscribe(hero => {
        this.heroes.push(hero);
      });
  }

and
addHero(Hero) function from heroes.service.ts

  addHero (hero: Hero): Observable<Hero> {
    return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
      tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
      catchError(this.handleError<Hero>('addHero'))
    );
  }

I want to know where the new ID is coming from.
This is the live example: https://stackblitz.com/angular/ombxjmbjedp
Answer: Angular uses in in-memory-web-api module to emulate CRUD operations over a RESTy API.
This module adds custom HttpInterceptor to interceptors chain. Under the hood that interceptor is also responsible for generating id for entity.
// Create entity
// Can update an existing entity too if post409 is false.
protected post({ collection, collectionName, headers, id, req, resourceUrl, url }: RequestInfo)
   : ResponseOptions {
  const item = this.clone(this.getJsonBody(req));

  // tslint:disable-next-line:triple-equals
  if (item.id == undefined) {
    try {
      item.id = id || this.genId(collection, collectionName);

You can also write your own function for generating id in your InMemoryDataService. That's exactly that we can see in that example:
export class InMemoryDataService implements InMemoryDbService {
 ...

// Overrides the genId method to ensure that a hero always has an id.
// If the heroes array is empty,
// the method below returns the initial number (11).
// if the heroes array is not empty, the method below returns the highest
// hero id + 1.
genId(heroes: Hero[]): number {
  return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
}

Comment: so ID are generating from in-memory-web-api .

No wonder even I deleted genID can  not stop ID
Answer:
    addHero (hero: Hero): Observable<Hero> {
        return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
          tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
          catchError(this.handleError<Hero>('addHero'))
        );
      }

In this you can see, While calling this service function we are sending data object from heroes.component.ts ,
 hero: Hero  at this point we are using Hero as defined variable
addHero (hero: Hero): Observable<Hero> {
 // which is further allocated another instance
 tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`));

All the data is in newHero, From it we can acess the id.
Thanks


Prove $A\rightarrow 0$ iff $A^2\rightarrow 0$

Question: The implication from left to right is pretty easy. But the implication from right to left does not work. I tried to proof by contradiction by supposing $A^2$ converges to some number not 0 for the sake of contradiction. But it turns out we do not even know if it converges or not! Can anyone help me on this please?
Comment: *Hint* If $A\not\to 0$, then $A^2\not\to 0$.
Answer: I think you might be confused about what you're trying to prove; assuming that $A^2$ converges to anything but zero is not going to help you prove the implication from the right to the left. What you should do to show the implication right to left, if you want to do a proof by contradiction, would be to assume that $A$ does not converge to zero and prove that $A^2$ may not converge to zero either. I would expect this to be of similar difficulty to what you've already done.
Comment: But you do not even know if A converges or not. So it is not helpful
Comment: You don't really *need* to do this, but you can split into cases from "A does not converge to zero" - you could have "A converges to something other than zero" and "A does not converge" as subcases, and handle them separately. But "A does not converge to zero" is enough, since you can from that say that infinitely many values of $A$ are not in some interval $(-\varepsilon,\varepsilon)$ and hence $A^2$ has infinitely many values not in $[0,\varepsilon^2)$, contradicting that it might converge to $0$.


Change DataTable Search Label

Question: Been trying to change the Search: to Filter: in my datatable that I created.
I tried this that i found:
$(document).ready(function() {
oTable = $('#datatable-example_filter').dataTable({
  "aaSorting": [[ 10, "desc" ]],
  "bJQueryUI": true,
  "aLengthMenu": [[25, 50, 100, 250, 500, -1], [25, 50, 100, 250, 500, "All"]],
  "sPaginationType": "full_numbers",
  "oLanguage": {
    "sSearch": "Filter: "
  }
});
} );

but it is not working, #datatable-example_filter is the name of the id, inside the div that is generated by dataTable
Comment: @TheGuest, it is exactly what he is doing, and it should work -> POC -> (OP's code) http://jsfiddle.net/c846e6mo/ Guess it is cache ...1.10.x too -> http://jsfiddle.net/5cvj0t18/
Comment: See [this](http://datatables.net/forums/discussion/3900/changing-search-label-in-tab0le-header) if it can help you
Comment: @TheGuest & david, thanks, i was targeting it erroneously. not sure how to up voate, as i think it's just a comment?
Comment: Dude, the same thing is working for me.
Answer: The other answer that uses "oLanguage" is using legacy DataTables api.  According to DataTables v 1.10+ documentation, the syntax is:
$('#example').dataTable( {
  "language": {
    "search": "Filter records:"
  }
} );

Comment: You can also use the key `"searchPlaceholder"` alongside `"search"` to place some placeholder text in the search input.
Comment: is it possible to shift the placement of the `search` label? Shift to the right side of the `search input field` for example.
Comment: I couldn't figure out how to add some space between the default label and search box, so I used this method to change it to "Search:  " and it worked!
Answer: very easy, just put this parameter when you call data table function:
"oLanguage": {
  "sSearch": "YOUR SEARCH TITLE HERE: _INPUT_" //search
}

Comment: Cool! For other using angular-datatables, replace keywords with 'language' and 'search' respectively.
Answer: Inside the Datatable Javascript (table = $dataTable.DataTable) add the following code:
language: {
  'search' : '' /*Empty to remove the label*/
}

I left the search empty because I wanted the info to be in the Placeholder
Ps: If you want to add a placeholder put the following code outside the Datatable initialization
$('.dataTables_filter input').attr("placeholder", "Zoeken...");

Answer: I have found this code will change the Search Label ( in my case to "Filter results:" before the DataTable get populated with data.
var dataTable_leSrch = $('#dataTable_leSrch').dataTable({
    "oLanguage": {
        "sSearch": "Filter results:"
    }
});

but when I later populate the DataTable with data the label reverted back to "Search:", so I had to add this code to my DataTable configuration to keep the label changed:
function fillDataTable(res) {
if ($('#dataTable_leSrch').length !== 0) {
    $('#dataTable_leSrch').DataTable({
        fixedHeader: {
            header: true,
            headerOffset: $('#header').height()
        },
        oLanguage: {
            "sSearch": "Filter results:"
        },
        responsive: false,
        scrollX: true,
        scrollY: 400,
        scrollCollapse: true,
        select: true,
        destroy: true,
        aaData: res.data.Results,
        ...

Answer: // Input text box will be appended at the end automatically
$(document).ready( function() {
  $('#example').dataTable( {
    "oLanguage": {
      "sSearch": "Filter records:"
    }
  } );
} );

// Specify where the filter should appear
$(document).ready( function() {
  $('#example').dataTable( {
    "oLanguage": {
      "sSearch": "Apply filter _INPUT_ to table"
    }
  } );
} );

for more detail check this link  http://legacy.datatables.net/usage/i18n
Answer: try this for change label search panel
$('#table_id').DataTable({
 "oLanguage": {
                "sSearch": "type somthing.. ",
            },

});

Change DataTable Search Label


Display each section (h1, h2, h3) in a new page in Sphinx

Question: When I build HTML output using sphinx, it is possible to display h1 and h2 on separate pages, however, h3 is always displayed on the same page as h2. Does anyone know how to make sphinx display the content of h3 on a separate page? The same way traditional online help systems do this.
For example:

Section

Sub-section
Sub-section

Sub-sub-section
Sub-sub-section

Sub-section

So, I want when I click on sub-sub-section see the content only under that sub-sub-section and not from Sub-section above or sub-sub-section below.
Thanks in advance!
Comment: There is no way to "chunk" an input file into multiple output files. Each input file (\*.rst) always corresponds to one output file (\*.html).
Answer: Unfortunately, based on this note from the readthedocs.org irc channel one of the main devs said no, that's not possible.
Source: https://stackoverflow.com/a/32788289/3750804
If you want this support the only thing I can suggest is checking out MkDocs at http://mkdocs.org, however, you lose PDF building capability and some other LaTex support that's included in Sphinx.
Good luck!
Comment: This answer seems to be about whether readthedocs supports download of multiple HTML pages. But the question (which is not tagged with "readthedocs") is about whether Sphinx supports "chunking" one RST file into multiple HTML files. These are two different things.
Answer: So, we were able to make it work by adjusting the HTML template and the globaltoc setting.
Comment: I'm sorry to say this, but without much more details this answer is useless. It does not help anyone.
Comment: Exactly how did you adjust the HTML template and the globaltoc setting?
Comment: I cannot share the details about the Jinja template settings that have been changed as it is confidential, but for the globaltoc., we set the value to 4.
Comment: Well, can't you at least provide an outline of how adjusting the template and the globaltoc solved the problem?
Comment: What is the globaltoc setting? The only reference to globaltoc in the Sphinx documentation is the `globaltoc.html` template for the sidebar...


Multihomed email

Question: Our primary MX record points to an external server which handles spam filtering, thereafter the mail is pushed to our internal mail server. The mail is never stored on the external server for longer than it takes to process the mail and deliver it to our internal server.
The current setup requires that we connect to our internal server to retrieve mail. The problem with this setup is that roaming users are unable to access their email if our internet connectivity at the office goes down. An alternative is to host all our mail externally, but this means that users in the office must be connected to the internet for the duration it takes to download and send all their mail, which will be significantly slower than if we had a mail server on the LAN handling the mail. Additionally, this setup would mean that even internal mail has to leave the network, which is terribly inefficient.
Are there any methods whereby we can have both our internal server and our external server hosting the mail, and depending on the DNS record (from within the office the DNS record will resolve to our internal server, and externally the record will resolve to our offsite mail server) our users will always be able to send and retrieve their mail? ie. users should be able to use either of the two mail servers to retrieve their mail. I've given some thought to using IMAP in this situation, but would this not cause mail duplication when switching between servers?
The architecture is irrelevant. I'm looking for any solution, regardless of whether it's based on Exim, Exchange, or anything else that we can setup ourselves.
Answer: There is no solution to your problem, as you already refused any option. Only three options are available:

Server is internal. Contras: You can't access it from extern when your Internet connection is down.
Server is external. Contras: as above, plus all mails have to be transferred from internal to external and for reading even back.
Server is internal and external. Contras: all from 1) AND 2), plus that synchronizing stuff is not easy.

So why not go with the option with least impact? I would choose 1) because how big is the risk of a failure in Internet connection?
Comment: Sorry, I don't follow - why does your option 3 include the cons from both option 1 and 2? The idea is that users should be able to access their mail from either of the two servers - whether it's possible to keep the two servers perfectly synchronized (and how) is what I'm trying to find out.
To answer your last point, the risk of failure of the internet connection is fairly high - ADSL in South Africa isn't too reliable. Offsite would be more reliable since the server would reside in a hosting centre on the internet backbone.
Comment: @Richard - Option 3 introduces The Synchronization Problem. The Synchronization Problem is to be avoided - that way lies only pain and madness.  If your ADSL is unreliable an external server is the way to go.
Comment: @Richard how will you synchronize when there is no connection between both points? You get out-of-sync and then need to synchronize everything. Not only the mails but also the flags of each mail. And during handling the backlog there are changes on both systems.
Answer: Why not just have your mail servers in your DMZ, or at least the Exchange server with the Client Access role? Then they'll traverse your internal network when they're in the office (assuming your routing and DNS are configured properly) and external clients will have access based on whatever firewall rules you have in place.
AFAIK, Microsoft's recommendation is to put Edge Transport and Client Access on the outside/DMZ, Hub Transport wherever you need it based on your infrastructure, and the Mailboxes on the trusted side of your firewall. This allows you to open whatever services you see fit to the outside while keeping your mail secure on the inside.
Comment: If your office network link is reliable the DMZ solution is a great way to go.
Answer: I'm not sure I understand.  You say that the internal server is a requirement because it is faster (because it's on the LAN), but then you say that you want people to be able to access their email when the internal server is unreachable.  You've kind of boxed yourself into a hole.  You might want to look into off-site exchange hosting.  They might have a solution for the sort of thing you're looking for with some sort of replicating module you can run on an 'internal' server.
Comment: Well the idea is that people should be able to retrieve their mail from either one of the two servers, depending on their current location. Whether or not this is actually possible is what I'm trying to find out. If there was some way of synchronizing the two servers...

Multihomed email


@PreUpdate com @Transient - EclipseLink

Question: Preciso que um método @PreUpdate seja chamado quando um atributo @Transient for modificado. Esse @Transient sempre será modificado, então, sim, o @PreUpdate teria que ser chamado sempre.
Já que ele terá que ser chamado sempre, procurei uma opção semelhante ao @PreUpdate, mas que fosse chamada independentemente de ter atributos modificados ou não, pois é esse método que irá definir o valor de uma coluna a ser persistida, de acordo com o valor no @Transient.
A alternativa que encontrei foi definir os seguintes atributos:
<code>@Column(name="valor")
private Double valor;

@Column(name="valor", insertable=false, updatable=false)
private Double valorTransientDisfarcado;
</code>
Desse forma, o "transient" sempre será carregado com o valor da coluna que  ele irá, possivelmente, alterar.
Caso esse "transient" seja alterado , ele irá cair no @PreUpdate e realizar algumas operações que irão definir se o valor que ele possui será   transmitido para o atributo "original" a ser persistido.

A pergunta é: Quais os problemas que essa abordagem pode trazer?

E existe alguma alternativa para esse valor "transient"?
Melhor ainda, existe alguma alternativa para o @PreUpdate, para que o método seja chamado no último momento possível, independente se houver alterações, até o momento, a serem persistidas, para que ele só realize a verificação dos atributos modificados após esse método?
Comment: Como esse atributo seria @Transient você não poderia colocar essa lógica de @PreUpdate no setter desse atributo?
Assim, quando o valor do transient for alterado (através do `setTransient()`) ele pode ser validado e modificar o outro atributo `valorTransientDisfarcado`
Answer: Seguindo bons princípios de separation of concerns (SoC) não seria legal delegar essa regra para sua camada de persitência de dados. Perceba que olhando apenas seu trecho de código já existe uma redundância no nome da coluna, que dificulta a legibildiade.
Prefira usar as ferramentas de Orientação à objetos (OO) já que esse campo não é persistido e usar, por exemplo, um decorator na sua classe com os devidos getters/setters.
Vide o Zen do Python, preceitos de boas práticas de programação, que

explícito é melhor que implícito.

Por tanto eu recomendo fortemente que você coloque suas regras em uma DAO e escreve casos de teste automatizado. É um caminho bem menos tortuoso que observar o ciclo de vida das entidades.

@PreUpdate com @Transient - EclipseLink


Trouble with a simple GetElementById thing real simple

Question: Real simple but I'm starting with javascript so it should be quickly soved
I have this html:

and i want to select the div with an id of "logo" with javascript to then overwrite the  with the apropriate file ( a simple browser test to see if you can support SVG )
this innerHTML look like this:
document.getElementById('logo').innerHTML='<content to be added>';

Firebug send me this error: TypeError: document.getElementById("logo") is null
but its right there!
Thanks
okay so here is the full HTML:

    <META CHARSET="UTF-8">
    <title>Bienvenu au Fin Palais</title>

and here's the full svg_support.js I've made;
function getSvgSupport(file)
            {

                var ua = navigator.userAgent;
        if( ua.indexOf("Android") >= 0 )
            {
          var androidversion = parseFloat(ua.slice(ua.indexOf("Android")+8));
          if (androidversion <= 2.3)
                {
                document.getElementById('logo').innerHTML='';

                }

            } else {
                document.getElementById('logo').innerHTML='<embed src="',file,'.svg" type="image/svg+xml" />';
            }
        }

Comment: Is your JavaScript code inside window.onload?
Answer: yes that is the only reason, and since you seem new to javascript I guess this would make more sense to you
window.onload=function(){
document.getElementById('logo').innerHTML='<content to be added>';
}

You see when your script runs you page has not loaded. so you must use window.onload.
Or you can use this too, if your code is in file.js:

this makes sure your code doesn't run unless document is parsed.
Comment: Oh wow, I didn't know about that `defer` trick. I wasn't expecting to learn something from this question! Thanks.
Answer: You may be trying to run the javascript before the DOM has finished loading. Try this:
$(document).ready(function(){document.getElementById('logo').innerHTML='<content to be added>';});

This assumes you've included jQuery.
As @Thristhart said, you can also use window.onload. This is a built-in javascript event which happens AFTER $(document).ready() does, so you should be safe with that as well.
Comment: alternatively, if you're not using jQuery, you can simply use
`window.onload = function() { ... }`
Answer: If using JQuery:
$(document).ready(function(){
    $('div#logo').html('<content to be added>');
});

Or
$(function(){
    $('div#logo').html('<content to be added>');
});

Answer: You don't have to load jQuery if you don't want to it seems like something is off with the chaining of the javascript.  When I broke it apart it worked fine.
Fiddle:  http://jsfiddle.net/DamianHall/GxghG/
var ele = document.getElementById('logo');

ele.innerHTML = 'content to be added';

Looking at other posts it is an onload issue.  The JS fiddle did the onload for me so I didn't notice.


function stuck in readlines

Question: My python script keeps getting stuck at this point when there is no input:
else:
lines = sys.stdin.readlines()

My program has to support no input, so is there a way to figure it if there is no input, so that I just return out of the function. I tried seeing if lines was empty, but the control seems to be lost inside the readlines function (never exits it)
Here is the complete if statement
if len(args) != 0 and args[0] != '-':
           # print('B')
            input_file = args[0]
            try:
                f = open(input_file, 'r')
                lines = sys.stdin.readlines()
                lines = f.close()
            except:
                return
        else:
            #print('c')
            lines = sys.stdin.readlines()

is there a way to get around this?
Comment: If you give us a [mcve], including how you're running this, how you're feeding it input, etc., we can probably help. But without that, it's impossible to guess.
Comment: Maybe related? https://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python#1454400
Comment: I don't see anything particularly wrong with your code. It's fine for the user to be responsible for providing empty input with something like `python yourscript.py < /dev/null`. `readlines` is simply blocking until it reaches the end of the input "file", which you can simulate by using the correct control character for your terminal (typically Control-D in Unix or Control-Z in Windows, I believe.)
Answer: From my comment original goes to u0b34a0f6ae:
import fileinput

for line in fileinput.input():
    pass

How do you read from stdin in Python?
Comment: answers should be self-contained. you should include the link in your answer so people don't have to search through comments to know what you are talking about
Answer: You can't use readlines, because that enforces a new line to be read, and depending on your input you can't predict when that comes.
Instead, uses the select module to check (with a timeout) for new data. If there is some, read it's with read() and stitch together the data yourself, then split lines & feed them to the rest of your program.

function stuck in readlines


Use Git hooks to auto format code after pull requests or commits or pushes/pulls?

Question: Lets say you have a Git repository, like on GitHub, and you have a lot of people contributing to the repository. Everyone uses their own standards for coding, so the code ends up being a mess without any standards applied.
I've read a bit about git hooks but I don't fully understand their concept or primary uses.
Is it possible to use hooks, when a pull request is sent to your repository, to send the code to some remote service, that then formats the code into whatever XYZ standard you want to use, and then returns the formatted code back in to the repo or into the pull request? Or does it not work like that?
Answer: Sure, you could do something like that. However, I don't like the idea of a third-party service or daemon making changes to code that are committed by my engineers.
So instead of fixing this retroactively, Just check the code via the pre-receive hook and then reject the push if it fails to meet your code style standards. Your engineers really ought to be able to get over their own personal ideas of how code should be formatted and adhere to the organization's desires.
Comment: They aren't "my engineers". Just a group of random people collaborating on a project. If I sit there and reject people's code over and over cause of poor formatting then they are going to just stop contributing.
Comment: More than that, suppose it automatically changed the pull request to have formatted code before pulling. You just generated a future merge conflict for that collaborator. Do it enough times and your collaborators will revolt.


Is jQuery UI missing a state?

Question: The jQuery UI widgets seem to have inactive, active, and hover states, but lack a depressed (clicked-and-held) state. Is this an oversight? Just about every modern UI I can think of have a depressed state. Has anyone added such a state? If so, what pieces of code did you have to touch?

Edit: What I should have said is that hovering and clicked states look the same. There should be another state so you can see that you've clicked after hovering.
Answer: In HTML/CSS, the active state applies "while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it." (CSS 2.1 Section 5.11.3)  In the case of buttons, that would be the depressed state.
I just assume that applies to jQuery UI as well.
Comment: Well, I don't think that's strictly true. HTML buttons (at least in FF and Chrome) have a depressed (clicked and held) state. Some other UI libraries have the extra state (like ExtJS).

As it is now, there are not enough states in jQuery UI to fully skin BUTTON.
Comment: What I SHOULD have said is that hover looks the same as clicked-and-held, so I'm still missing a state. You get a change when you hover, but not when you click.
Comment: There's a problem if hover and active look the same, as they *should* be different.
Answer: Don't forget that in your CSS, you can combine the pseudo-selectors:
a:link {
    color: blue;
}
a:hover {
    color: green;
}
a:visited {
    color: purple;
}
a:active {
    /* link is active */
    color: red;
}
a:visited:hover {
    /* hovering on a visited link */
    color: pink;
}
a:active:hover {
    /* hovering on an active link */
    color: black;
}
a:visited:active:hover {
    color: fuchsia;
}

There's a definite difference between a:active and a:active:hover : a link can become active by tabbing to it using the keyboard. Though it's not 100% foolproof, the state of being active and hovered would suggest that the user has the link depressed. Altering the border style would give you the desired effect. The only bug in this is if the link becomes active and then the user hovers over it without clicking, it'll still go depressed.
Try this CSS to see what I mean:
a {
    padding: 5px 10px;
    background-color: gray;
    border-color: gray;
    border-style: outset;
}
a:active:hover {
    border-style: inset;
}

Comment: Thanks. I know all that. I'm wondering why the jQuery UI interface doesn't show a difference between when you hover and when you depress a button.
Comment: This is a particular annoyance that I have with the jQuery UI right now. It does not appear to have a way to insure that anchors maintain their theme-ability and within the jQuery UI framework. The code above does not help if you want a themeable interface, you'd have to maintain a separate .css file for each theme.
Answer: It looks to be on purpose.  Notice in Themeroller there is a clickable: active state settings area, but it does not behave as the css active state.  A quick grep of a jQuery UI 1.7 package shows no styling for :active.  It kinda seems like they designed the ui state for visual cues to their widgets, leaving the :active to the developer to use.

Is jQuery UI missing a state?


How to send multiple emails after creating a node

Question: I'm using SMTP module to send e-mail messages after creating nodes. It takes about 3-4 seconds to send each such message using hook_node_insert. So if I want to send 10 messages, then I have to wait for 30-40 seconds for the iteration to complete and then only I get redirected to create new node. It's very slow.
I tried use event KernelEvents::TERMINATE per this article, but it did not speed up the whole process.
Is there a way just to complete creating a node without waiting and immediately proceed to creating a new node, while sending e-mail messages at the same time?
Note: I don't want to create queue and wait for the next cron run to send e-mails. Because e-mails need to be sent instantly after creating respective node
Comment: Rules is an extra performance it. It is using event_dispatcher to react to events, which Kernel::TERMINATE is an event being dispatched by HttpKernel.
Comment: Use [Rule](https://www.drupal.org/project/rules)'s `After saving new content` action.
Comment: Did you try it? I'm checking [code](http://cgit.drupalcode.org/rules/tree/rules.module?h=8.x-3.x#n118), It's the same. Because they using hook_entity_save to dispatch action.
Comment: It's really your call to try. But I know the `event_dispatcher` works seamlessly, so things should go smoother for you.
Answer: As noted on the Reddit thread, this event will not work as described in this blog unless you are using PHP FPM. For most hosting providers this is the default setup. So, if you are using Apache with mod_php you are out of luck, it seems.
Are you hosting with Apache and mod_php? You'll need Apache and use PHP FPM with some settings changed. Or use nginx.
Sounds like the problem is due to your server not streaming the output. Per the Symfony docs

Internally, the HttpKernel makes use of the fastcgi_finish_request PHP function. This means that at the moment, only the PHP FPM server API is able to send a response to the client while the server's PHP process still performs some tasks. With all other server APIs, listeners to kernel.terminate are still executed, but the response is not sent to the client until they are all completed.

https://symfony.com/doc/current/components/http_kernel.html#the-kernel-terminate-event
Comment: I don't see referenced link has anything to do with the question asked. Anyway, please note that answers should be relevant and not mislead other problem seekers for the same issue.
Comment: Based on *Is there a way just to complete creating a node without waiting and immediately proceed to creating a new node, while sending e-mail messages at the same time?* it sounds like the OP's server is just not buffering as expected.


How can I customize a table so that it stacks vertically on media/mobile screens?

Question: This page: https://eldergod.ca/necronomicodex/ looks great on desktop, but I dislike the horizontal scroll that occurs on some of the longer entries on mobile (I've tried both safari and chrome on my mobile to check).
I've added this CSS to stack all the table columns.  Can I force the table(s) to display at full width of the media device without any horizontal scrolling?
/* XL */
@media (min-width: 1200px) {
    table {width:100%;}
  thead {display: none;}
  tr:nth-of-type(2n) {background-color: inherit;}
  tr td:first-child {background: #070707; font-weight:bold;font-size:1.5em;}
  tbody td {display: block;  text-align:center;}
  tbody td:before {
      content: attr(data-th);
      display: block;
      text-align:center;}
}

/* Large */
@media (min-width: 768px) and (max-width: 979px) {
   table {width:100%;}
  thead {display: none;}
  tr:nth-of-type(2n) {background-color: inherit;}
  tr td:first-child {background: #070707; font-weight:bold;font-size:1.5em;}
  tbody td {display: block;  text-align:center;}
  tbody td:before {
      content: attr(data-th);
      display: block;
      text-align:center;}
}

/* Medium */
@media (max-width: 767px) {
     table {width:100%;}
  thead {display: none;}
  tr:nth-of-type(2n) {background-color: inherit;}
  tr td:first-child {background: #070707; font-weight:bold;font-size:1.5em;}
  tbody td {display: block;  text-align:center;}
  tbody td:before {
      content: attr(data-th);
      display: block;
      text-align:center;}
}

/* Small */
@media (max-width: 480px) {
     table {width:100%;}
  thead {display: none;}
  tr:nth-of-type(2n) {background-color: inherit;}
  tr td:first-child {background: #070707; font-weight:bold;font-size:1.5em;}
  tbody td {display: block;  text-align:center;}
  tbody td:before {
      content: attr(data-th);
      display: block;
      text-align:center;}
}

Answer: from what I can understand you are trying to stack tables vertically for smaller screen sizes. I have achieved this using media-queries in CSS.
Here is an example

table {
  margin: 0;
  padding: 0;
  width: 100%;
  table-layout: fixed;
}

table caption {
  font-size: 1.5em;
  margin: .5em 0 .75em;
}

table tr {
  background-color: #f8f8f8;
  border: 1px solid #ddd;
  padding: .35em;
}

table th,
table td {
  padding: .625em;
  text-align: center;
}

table th {
  font-size: .85em;
  letter-spacing: .1em;
  text-transform: uppercase;
}

@media screen and (max-width: 600px) {
  table {
    border: 0;
  }
  table caption {
    font-size: 1.3em;
  }
  table thead {
    border: none;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
  }
  table tr {
    border-bottom: 3px solid #ddd;
    display: block;
    margin-bottom: .625em;
  }
  table td {
    border-bottom: 1px solid #ddd;
    display: block;
    font-size: .8em;
    text-align: right;
  }
  table td::before {
    content: attr(data-label);
    float: left;
    font-weight: bold;
    text-transform: uppercase;
  }
  table td:last-child {
    border-bottom: 0;
  }
}

Table

      Name
      Age
      ID

      XYZ
      24
      1

      John
      28
      2

      Alex
      24
      3

      Dave
      20
      4

Hope this helps :)


erro de execução do MySQL - XAMPP

Question: Estou tentando criar um localhost com o xampp, mas o MySQL não inicia. Dá este log
mysql_error.log:

<code>2015-11-10 15:26:56 10fc InnoDB: Warning: Using innodb_additional_mem_pool_size is DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
2015-11-10 15:26:56 4348 [Note] InnoDB: Using mutexes to ref count buffer pool pages

2015-11-10 15:26:56 4348 [Note] InnoDB: The InnoDB memory heap is disabled

2015-11-10 15:26:56 4348 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions

2015-11-10 15:26:56 4348 [Note] InnoDB: Memory barrier is not used

2015-11-10 15:26:56 4348 [Note] InnoDB: Compressed tables use zlib 1.2.3

2015-11-10 15:26:56 4348 [Note] InnoDB: Not using CPU crc32 instructions

2015-11-10 15:26:56 4348 [Note] InnoDB: Initializing buffer pool, size = 16.0M

2015-11-10 15:26:56 4348 [Note] InnoDB: Completed initialization of buffer pool

2015-11-10 15:26:56 4348 [Note] InnoDB: Highest supported file format is Barracuda.

2015-11-10 15:26:57 4348 [Note] InnoDB: 128 rollback segment(s) are active.

2015-11-10 15:26:57 4348 [Note] InnoDB: Waiting for purge to start

2015-11-10 15:26:57 4348 [Note] InnoDB:  Percona XtraDB (http://www.percona.com) 5.6.26-74.0 started; log sequence number 1835027

2015-11-10 15:26:57 6140 [Note] InnoDB: Dumping buffer pool(s) not yet started

2015-11-10 15:26:57 4348 [Note] Plugin 'FEEDBACK' is disabled.

2015-11-10 15:26:57 4348 [Note] Server socket created on IP: '::'.

2015-11-10 15:26:57 4348 [Note] Event Scheduler: Loaded 0 events

2015-11-10 15:26:57 4348 [Note] C:\xampp\mysql\bin\mysqld.exe: ready for connections.
Version: '10.1.8-MariaDB'  socket: ''  port: 3306  mariadb.org binary distribution

2015-11-10 15:27:11 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Normal shutdown

2015-11-10 15:27:11 5152 [Note] Event Scheduler: Purging the queue. 0 events

2015-11-10 15:27:11 5732 [Note] InnoDB: FTS optimize thread exiting.

2015-11-10 15:27:11 5152 [Note] InnoDB: Starting shutdown...

2015-11-10 15:27:13 5152 [Note] InnoDB: Shutdown completed; log sequence number 1835037

2015-11-10 15:27:13 5152 [Note] C:\xampp\mysql\bin\mysqld.exe: Shutdown complete
</code>
Answer: O log que você colou não é referente à sua tentativa de iniciar o XAMPP. Essa parte aí é de 2015, e provavelmente é da primeira inicialização do XAMPP, enquanto ele estava sendo preparado pra ser distribuído (pelo que pesquisei, tem esse log exatamente em vários outros sites, ex: https://jira.mariadb.org/secure/attachment/43238/mysql_error.log).
Você precisa procurar no final do log as linhas mais recentes e corrigir a sua postagem. Se possível inclua também a tela do XAMPP.

erro de execução do MySQL - XAMPP


Let $x(t)$ be the position of an object moving along a number line. Suppose that the velocity of the object is $\frac{dx}{dt}$ = $7 + 5$cos$($t/4$)$

Question: Let $x(t)$ be the position of an object moving along a number line. Suppose that the
velocity of the object is $\frac{dx}{dt} = 7 + 5\cos(t/4)$
What is the displacement of the object between $0\leq t\leq 2\pi$?
What is the distance travelled between $0\leq t\leq 2\pi$?
I first found the function of the position (by taking the anti-derivative since we aren't allowed to integrate yet in class).
I got to $x(t) = 7t + 20\sin(t/4)$ + $c$, and then I did $x(2\pi) - x(0) = 14\pi + 20$ as the displacement.
I am unsure how to get the distance. Since the object is moving on a number line, wouldn't the distance and displacement be the same?
(Please let me know if my displacement is wrong )
Comment: Distance can differ from absolute value of displacement on straight line if there are returning points. As in your case $dx/dt > 0$ for all $t$, there are no returning points. That's why distance is equal to displacement.
Answer: In general, the movement can be back and forth, so displacement is not the same as the distance traveled. However, in this case  $x'(t)=7+5\sin (t/4)$ is always positive which means the movement is only in the positive direction Hence, distance is same as displacement.
Answer: Mind that the object is not moving straight. If you go with your car outside and you drive 100m in north direction, then go back in south direction 50m, then turn again and go north for 100m the total distance you have done is 250m but you are 200m away from your starting point. So displacement can be different of travel distance.
However in that case, as the derivative is positive you don't change direction so the distance travelled is the displacement.
Answer: The object moving on a number line does not necessarily mean that the displacement equals the distance travelled, since it might have gone through the same section multiple times. However, in this case, the velocity is always positive (always $\cos{(t/4)} > -\frac{7}{5}$), so this does not happen. Therefore, the distance travelled does equal to the displacement.


Posting drupal content to tumblr

Question: I am trying to post article content type to my tumblr account (want to post all articles created by different user roles) . I have tried tumblr_connect but its not working i have also installed tumblr api module and registered a application and added the keys.
But i am stuck there i dont how to configure to post only the article content type and link it to my tumblr blog.
Answer: You will have to do this in code. Use hook_node_insert() in a custom module and filter by content type. You can then invoke the tumblr API and send the node data across. See tumblr.lib.php for API usage.

Posting drupal content to tumblr


What is the best way to mimic the findstr functionality in c#?

Question: I am searching for several thousand strings in a large directory tree which contains several thousand files. Each string can appear in many different files. What is the most performant way to perform this search in c#? I tried proccessinfo start with findstr (but it is painfully slow, because it opens every single file several thousand times). Any suggestions?
Comment: Is there a reason you have to do this with C#? Why not just use findstr? You can tell it to execute against entire directory trees, after all.
Comment: Which OS? Maybe use the Indexing Service or Windows Search?
Comment: How are the files stored in the tree?  Are they actual File objects or are they stored in plain text?  (...or secret option number 3?) :-)
Comment: I'm searching through a very large code base for resource keys. So the file types are all varied but can be read using a StreamReader. Right now im using the Directory.GetFiles to gather the files. Right now im using the regex library to match the key to a string which contains the contents of each file. Im running on Window Server 2008.
Comment: I was using findstr. But because im interested in where each string occurs, i have to execute find str several thousand times per file which takes roughly 30 seconds per string (this adds up quickly). I wanted to reduce the time to execute by only opening each file once. Right now its at about 1 second per file.
Answer: I suggest creating a widget that indexes your file tree using Lucene.NET.  Once the documents are indexed you can then use all of Lucene's power to search through the content in a very powerful way...without having to open each file 1000's of time!  :P
Not sure about the life of the program...this may not be a good idea for a one time use scenario.  And for a multi-use scenario you will need to make sure that you have a windows service that updates your index as the files change over time (if that is important).
This will be very performant once the indexes are created!
Answer: Do you need to perform a one-time search or continually on demand?  I would suggest either tying into the Indexing service or implement your own Lucene indexing.  There are a quite a few open-source implementations of the Lucene indexing, where basically you scan your files once and build a comprehensive index of the contents and then future searches are made against the premade index.  The index generation takes a while, but the searches are very fast.  This works well for 'web' type content and simply phrases and words.
If you're trying to find non-word/arbitrary random strings, then you've got a different task.
-Jeff


Find the area of a "petal" of a polar curve using Green's Theorem

Question: Find the area of a "petal" of the curve $r^2 = 3\sin{3\theta}$ using the parametrization $\alpha (t)$ of the equation and the formula $$\frac{1}{2}\int^b_a\begin{vmatrix}
\alpha_1 & \alpha_2  \\
\alpha_1' & \alpha_2'
\end{vmatrix} dt$$
So I got the parametrization of $\theta = t$ and $r = \sqrt{3\sin{3t}}$, and it's obvious that $0 \leq t \leq \frac{\pi}{3}$ because the petals intersect at the origin and this is the smallest interval that gives you a petal. Is there a better way to get the parametrization? If I plugged in this parametrization it would give a very ugly integral.
Answer: You should use the area formula $$Area=\int_a^b\frac{1}{2}r(\theta)^2d\theta$$
Comment: Was that derived from the area equation? I can't exactly see how.
Comment: $Area=\int\int rdrd\theta$ by substitution from the Cartesian formula, and then evaluating the inside integral gives my formula
Comment: I already know how to use double integrals to calculate area. I wanted to use the formula for the area of a region enclosed by a simple closed curve. In this case that is one petal of the curve.
Comment: @Panphobia then you'll just have to evaluate that messy integral
Comment: I figured out a better way, if you let $x= r\cos \theta$ and $y=r\sin \theta$ you can parametrize it nice and you get an easy integral.


Unit vectors out of the axes

Question: I'm having a difficulty to understand unit vectors other than those of the axes ($i, j, k$).
Say I have two vectors $U$ and $V$, somewhere in $\Bbb R^3$ in terms of $i, j, k$, and I want to know the projection of vector $U$ over vector $V$, if their coordinates are all non-zero.
As I see it, I should make:
$$\operatorname{proj}_vu = |u| \cos(\alpha)\;,$$ where $v$ is a unit vector. But how can I find an unit vector $V$ if its coordinates are non-zero? Its length won't ever be $1$.
I apologize for my lack of TEX knowledge, I'm sure it would have made this clearer. Tried to code it somewhere else and paste an url here, but it didn't work.
Comment: Please check that I added $\LaTeX$ correctly. (You can get some help using $\LaTeX$ [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).)
Comment: If $v$ is any non-zero vector, then the scalar multiple $\frac1{\|v\|}v$ is a unit vector in the same direction as $v$.
Answer: If you have a vector with non-zero coordinates, then it has non-zero length. Hence, you may always divide out by the length, to obtain a vector of length 1, that points in the direction of your original vector. We call this the unit vector
$$ \hat{u} = \frac {\vec{v} } { \left\| u \right \| }$$
For example, the vector $ ( 1, 2, 2) $ has length $\sqrt{ 1^2 + 2^2 + 2^2} = \sqrt{9} = 3$, thus the unit vector will be $ ( \frac {1}{3}, \frac {2}{3}, \frac {2}{3} ) $.

Unit vectors out of the axes


how to create a view that shows blogs count for a user?

Question: I want to create a view that list out the following fields

User name
User email
Discussion count
Blog count

I created the view and add the User: Name and User: Email in the fields but it shows me the duplicate users and Also I have no idea about how to add the discussion count and blog count to the view.
I have created the view of node type.
Any help?
Comment: Can you explain in a bit more detail what that "blog count" should exist of? Is that the number of blog-posts a user made? And if, so, what is considered a "blog-post"?
Comment: Yes it is the the number of the blog posts a user made.
Comment: And "Blog posts" are that nodes of type "blog"?
Comment: yes thay are of type "blog".
Answer: I'm going to take a stab at answering this. Create a view where:
Under Fields you select the User name, email and User:Uid. Then add a custom field.
Under the custom field write a query in Value:
<code><?php $result = db_result(db_query("SELECT COUNT(nid) FROM node where uid='%s' and type='blog'",$data->users_uid));
echo $result;
?>
</code>
This query find the number of posts written by each user.
Under filters choose Node:type = 'content type used to store profiles'
(as you want to count the number of blogs of every user who has a profile).


How do I download an image/file to a specified location on the disk?

Question: I want to provide the functionality to the users to download the images/files to their system but not with direct download but with a dialog where they tell the location where they want to download the image.
I have tried the download_file and file_force modules. Both modules provide the field formatter to download the image. but when the user click on the download link the the image directly downloads, it does not provide the option to the user to specify a location for the image to be downloaded in.
Is there any other module or any other method?
Answer: This behavior is largely up to browser itself, and this can't be controlled over how the browser has been configured.

Above settings are from Google Chrome browser. If user has checked "Ask where to save each file before downloading" checkbox, then browser will prompt to choose location else download to default location set in "Download Location".
Instead try educating the user before they download. That's the best way.
Ref : Prompt user to save file to a specific location


how to configure drupal settings to be available to visualize the available variables?

Question: how must drupal local settings be configured to display available variables using IDEs or other tools ?
I guess this is xdebug and phpstorm but i don't know how to configure it if i don't have full admin access to the server.
Comment: You normally use this only locally.
Comment: You don't need to change any Drupal settings. Xdebug is a PHP extension which might be already installed on your server or you are allowed to enable and configure PHP extensions yourself. But this is off-topic here.
Comment: @4k4 Could it be imagined as a feature of devel module? an in-place x-debug like tool ?
Answer: You can use kint which will print you all the variables
https://www.webwash.net/how-to-print-variables-using-kint-in-drupal-8/
or dpm (in devel module)
https://www.drupal.org/docs/contributed-modules/devel/dpm-and-other-devel-functions
Comment: normally, you will use xdebug on local machine, it might be a bit tricky to setup remote debugging
Comment: i am trying to find more efficient alternatives to dpm or kint


How to Convert NSDateComponents to String?

Question: UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
     for request in requests {

         let givenDate = request.trigger?.value(forKey: "dateComponents")
         print(givenDate ?? "")
     }
 }

<NSDateComponents: 0x282884930> {
Calendar Year: 2022
Month: 7
Day: 12
Hour: 12
Minute: 23

How can I convert this to a more readable format: "12 Jul 2022, 12:23 AM"?
Comment: Convert it with `Calendar` to `Date` and then with `DateFormatter` to `String`
Answer: NSDateComponents is not a Date.As the name suggests, NSDateComponents has pieces of a date.
    let dateComponents = NSDateComponents()
    dateComponents.day = 4
    dateComponents.month = 5
    dateComponents.year = 2017

if you want to convert it to a Date(), you need to depend on a calendar.
And then use a date formatted to format it as you want.
    //Use any calender
     if let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian),
        let date = gregorianCalendar.date(from: dateComponents as DateComponents) {

        let dateFormatter = DateFormatter()
       //Use any formatted
        dateFormatter.dateFormat = "dd MMM yyyy, HH:mm:ss"

        let formattedDate = dateFormatter.string(from: date)
        print(formattedDate)
    }


Erro ao iniciar Rails Server

Question: Estou tentando iniciar o Rails Server porém está sempre me retornando muitos erros, um deles era a respeito do SQLite que já corrigi baixando a gem e modificando o require_paths no gemspec, mas atualmente está dando erro com nokogiri e muitos outros.
C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-188.8.131.52-x64-mingw32/lib/nokogiri
.rb:29:in `require': cannot load such file -- nokogiri/nokogiri (LoadError)
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-126.96.36.199-x64-mingw32
/lib/nokogiri.rb:29:in `rescue in <top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/nokogiri-188.8.131.52-x64-mingw32
/lib/nokogiri.rb:25:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.1/lib/loofah.rb:3
:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/loofah-2.0.1/lib/loofah.rb:3
:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l
ib/rails-html-sanitizer.rb:2:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rails-html-sanitizer-1.0.2/l
ib/rails-html-sanitizer.rb:2:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/sanitize_helper.rb:3:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/sanitize_helper.rb:3:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/text_helper.rb:32:in `<module:TextHelper>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/text_helper.rb:29:in `<module:Helpers>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/text_helper.rb:6:in `<module:ActionView>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/text_helper.rb:4:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_tag_helper.rb:18:in `<module:FormTagHelper>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_tag_helper.rb:14:in `<module:Helpers>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_tag_helper.rb:8:in `<module:ActionView>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_tag_helper.rb:6:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_helper.rb:4:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers/form_helper.rb:4:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers.rb:50:in `<module:Helpers>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers.rb:4:in `<module:ActionView>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/actionview-4.2.0/lib/action_
view/helpers.rb:3:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:7:in `<module:LegacyAssetTagHelper>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:6:in `<module:Rails>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:4:in `<module:Sprockets>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/legacy_asset_tag_helper.rb:3:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/helper.rb:45:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/helper.rb:45:in `<module:Helper>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/helper.rb:7:in `<module:Rails>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/helper.rb:6:in `<module:Sprockets>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/rails/helper.rb:5:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/railtie.rb:6:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sprockets-rails-2.2.4/lib/sp
rockets/railtie.rb:6:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass/ra
ils/railtie.rb:2:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass/ra
ils/railtie.rb:2:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass/ra
ils.rb:11:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass/ra
ils.rb:11:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass-ra
ils.rb:1:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/sass-rails-5.0.1/lib/sass-ra
ils.rb:1:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:76:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:76:in `block (2 levels) in require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:72:in `each'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:72:in `block in require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:61:in `each'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler/ru
ntime.rb:61:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/bundler-1.8.5/lib/bundler.rb
:134:in `require'
        from C:/Program Files (x86)/Zend/Apache2/htdocs/Rails/ViasUrbanas/config
/application.rb:7:in `<top (required)>'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands/commands_tasks.rb:78:in `require'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands/commands_tasks.rb:78:in `block in server'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands/commands_tasks.rb:75:in `tap'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands/commands_tasks.rb:75:in `server'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands/commands_tasks.rb:39:in `run_command!'
        from C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/railties-4.2.0/lib/rails/com
mands.rb:17:in `<top (required)>'
        from bin/rails:4:in `require'
        from bin/rails:4:in `'

O SO é Windows 7 e já instalei o DevKit.
Poderiam me informar uma solução?
Comment: O que acontece se você rodar `bundle install`? O Ruby no Windows é um sofrimento, recomendo Ubuntu numa VM ou via dual-boot mesmo. Use apt-get e [rbenv](http://rbenv.org/) para instalar o que precisa. Se está só aprendendo também pode usar o [Nitrous](https://www.nitrous.io/).
Comment: O bundle install funciona corretamente, o problema é apenas ao rodar o Rails Server.
Comment: Aqui também está com esse erro! Não tem jeito. Tem que esperar sair atualização da gem "sprockets". Por enquanto só funciona no Ruby 2.1.5.
Answer: Eu resolvi o problema do nokogiri assim:

Indo na pasta specificions C:\Ruby22-x64\lib\ruby\gems\2.2.0\specifications
Abrindo o arquivo nokogiri-126.96.36.199-x64-mingw32.gemspec com o editor
Alterando
  s.require_paths = ["lib"]

para
  s.require_paths = ["lib/nokogiri_native"]

Espero ter ajudado
Answer: Do jeito que está tá difícil de descobrir o que é, talvez você tenha esquecido de gem 'nokogiri' no Gemfile.
Também pode tentar ajuda aqui: https://groups.google.com/forum/#!forum/rails-br
Answer: Cara para windows, eu normalmente uso o vagrant.
Tenta usar ele pois já existe várias box prontas só para ruby on rails no ponto de codar.
Esse repositório deve te ajudar.
Qualquer dúvida... avisa por aqui que podemos te ajudar.
Answer: Eu espero que você já tenha achado o problema. Mas como não vi uma resposta que efetivamente resolvesse o problema decidi postar a solução que arrumei.
Tive o mesmo problema e resolvi reinstalando o ruby numa versão anterior a 2.1.7, reinstalei o DevKit e o rails. Depois disso constatei que o nokokiri foi instalado corretamente.
Espero ter ajudado.

Erro ao iniciar Rails Server


Pytorch Lightning: How to save a checkpoint for every validation epoch?

Question: It is not clear from the docs how to save a checkpoint for every epoch, and have it actually saved and not instantly deleted, with no followed metric.
How to do it?
Answer: <code>max_epochs = 100
val_every_n_epochs = 1

checkpoint_callback = ModelCheckpoint(
        # dirpath=checkpoints_path, # <--- specify this on the trainer itself for version control
        filename="fa_classifier_{epoch:02d}",
        every_n_epochs=val_every_n_epochs,
        save_top_k=-1,  # <--- this is important!
    )
 trainer = Trainer(
        callbacks=[checkpoint_callback],
        default_root_dir=checkpoints_path,
        check_val_every_n_epoch=val_every_n_epochs,
        max_epochs=max_epochs,
        gpus=1
    )
</code>
this will not delete saved checkpoints.
Comment: Here is the reference of the [documentation for ModelCheckpoint](https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.callbacks.ModelCheckpoint.html#lightning.pytorch.callbacks.ModelCheckpoint)


Update com inner query selecionando a mesma tabela

Question: Tenho a seguinte query:
UPDATE cp_feedback_trabalho as a SET
    a.visivel = 1
WHERE a.dhEnvio IS NOT NULL AND EXISTS (
    SELECT
        b.id
    FROM cp_feedback_trabalho as b
        WHERE
            b.id_pessoa_que_enviou = a.id_pessoa_que_recebeu AND
            b.id_pessoa_que_recebeu = a.id_pessoa_que_enviou AND
            b.id_projeto = a.id_projeto AND
            b.dhEnvio IS NOT NULL
)

Eu obtenho o seguinte erro ao executar:

#1093 - You can't specify target table 'a' for update in FROM clause

O que pode estar errado?
Comment: O que você quer fazer? Pode escrever também o SQL(em português e não em SQL, só para entender), tipo o que você quer fazer, pois não estou entendo qual as relações.
Comment: Olá Fernando, eu quero apenas atualizar um campo (visivel) com base em outro registro que por acaso está na mesma tabela que será atualizada (cp_feedback_trabalho). O problema está nas variáveis (a e b)
Comment: Que eu saiba, no MySQL, não é possível fazer update numa tabela e usar a mesma como critério na cláusula `WHERE`. Uma sugestão seria usar uma tabela temporária com o resultado de um `SELECT` dessa mesma tabela com a cláusula `WHERE` do update (se possível é claro).
Answer: Está um pouco desorganizado o seu SQL.
E o erro ali já está dando uma dica, "você não está especificando a tabela de target, onde você vai efetuar o update".
Pelo que entendi você quer atualizar os registros da tabela cp_feedback_trabalho que dhEnvio dela for diferente de nulo e onde o id_pessoa_que_enviou da tabela b for igual ao id_pessoa_que_recebeu da tabela a e o id_pessoa_que_recebeu da tabela b for igual ao id_pessoa_que_enviou da tabela a e o id_projeto da tabela b for igual id_projeto da tabela a e a dhEnvio da tabela b for diferente de nulo.
Meu Deus que rolo.
Em SQL é mais simples (Hehe):
UPDATE a
SET a.visivel = 1
FROM cp_feedback_trabalho AS a
INNER JOIN cp_feedback_trabalho AS b ON a.id = b.id
WHERE a.dhEnvio IS NOT NULL
  AND b.id_pessoa_que_enviou = a.id_pessoa_que_recebeu
  AND b.id_pessoa_que_recebeu = a.id_pessoa_que_enviou
  AND b.id_projeto = a.id_projeto
  AND b.dhEnvio IS NOT NULL

Olhe ai e vê se funciona.


Why did Force India get docked all constructors points?

Question: Prior to the Hungarian Grand Prix, Sahara Force India entered administration and was bought out by the consortium Racing Point UK, renaming themselves Racing Point Force India in the Belgian Grand Prix but with zero points in the constructors championship.
Besides the new ownership, the entire team was basically the same as it was at the start of the season. Same chassis, same drivers and the same crew.
Is a change of ownership midway through the season regarded as a separate team entry that results in a team not retaining all the points they've currently earned in the season?
Answer: Racing Point Force India count as a new team, that's why they start with no points. The points from old Sahara Force India went away with their exclusion.

When Sahara Force India's entry was excluded from the championship,
  the team's 59 points from the first 12 races of the season went with
  it. As a new entry, Racing Point Force India starts the Belgian Grand
  Prix on zero points and its final championship position for 2018 will
  be determined by the points it accrues relative to its rivals from
  this weekend onwards. The drivers keep their points in the drivers'
  championship in the same way that a driver who switched teams mid
  season would keep theirs.

(ESPN)
Wikipedia also states:

A consortium led by Lawrence Stroll purchased the racing assets and
  operations of Force India through a company named Racing Point UK Ltd.
  Force India was then excluded from the Championship on grounds of
  their inability to participate in events. This allowed a new team
  known as "Racing Point Force India" to apply for a late entry and
  begin the championship from the Belgian Grand Prix.

Force India's (FI) assets were sold to Racing Point (RP), but the FI company itself wasn't
The assets no longer belonged to FI.
FIA excluded FI due to their inability to continue (no assets left to race).
RP applied for the vacant spot as late entry.
RP now finishes the season with a new team using FI's assets.
It must keep the name Force India, because that's the chassis name, which cannot be changed during a season.
Comment: @NoirAntares no.. there are still rules to follow. "*Following a disciplinary investigation and prosecution by the FIA under Article 4 of the FIA's Judicial and Disciplinary Rules, the Sahara Force India F1 Team has accepted its exclusion from the 2018 FIA Formula One World Championship with immediate effect, due to its incapacity to comply with Article 8.2 of the Sporting Regulations moving forward, and forfeits all Constructors Championship points under Article 6.2.*" Administration is one thing, selling all assets is something completely different.
Comment: Had the new owner purchased the shares rather than just the assets, they would have remained the same entrant as before. But because it was an asset sale, i.e. the company itself has not changed hands, that was not possible.
Comment: Is a team going into administration automatically considered as them opting out of the championship?
Comment: Entering administration itself does nothing directly. There is nothing about this in the rules.
Comment: So basically everything was in the FIA's discretion once Sahara FI's assets were bought out by technically, a new team?


How can I implement a multi-language switch in Nuxt?

Question: In my current project, I'm developing a multi-language site using nuxt.js. While the i18n solution is available, my approach doesn't focus on translating English terms into Spanish or other languages. My goal is to build separate pages for each language within dedicated directories. The default language will be English, and I plan to create a directory named es to host all the Spanish pages. This directory might have the following structure:
pages
├── index.vue
├── somepage.vue
└── es
    ├── index.vue
    └── somepage.vue

The default English pages are accessible through example.com and example.com/somepage, while the equivalent Spanish homepag and pages are accessed via example.com/es and example.com/es/somepage.
My main query is: How can I integrate a language-switching dropdown for users? Your assistance in resolving this matter would be highly appreciated. Despite conducting thorough online research, most of the solutions I came across were related to i18n. Can i18n handle this specific scenario, or is there an alternative approach? Thank you in advance for your help.
Answer: Providing Different Routes for Language Switching
So your main question is not about how to switch languages, but rather about how to load different components when the language parameter in the route changes.
If you insist on showing the language in the URL, you need to clarify this in Vue Router as well. Your main route will only be /:lang, which allows you to include the language in every sub-route. Your actual pages will be sub-routes of this. You will need to import the components dynamically, using the :lang variable and the appropriate file path that corresponds to your own file structure.
Here's an example of how to implement this approach:
/**
 ** Get Component
 */
const getComponentByLang = (resolve, route, componentPath) => {
  const lang = route.params.lang;
  return import(`./pages/${lang}/${componentPath}.vue`).then((component) => {
    resolve(component);
  });
};

/**
 ** Routes
 */
const routes: [
  // Main Route (/es or /en ...)
  {
    path: '/:lang',
    children: [
      // Sub Route (/es/articles/title or /en/articles/title ...)
      // Load /langFolder/Articles/Show.vue
      {
        path: '/articles/:name',
        component: (resolve, route) => getComponentByLang(resolve, route, 'Articles/Show')
      },
      // Sub Route (/es/topics/title or /en/topics/title ...)
      // Load /langFolder/Topics/Index.vue
      {
        path: '/topics/:name',
        component: (resolve, route) => getComponentByLang(resolve, route, 'Topics/Index')
      }
    ],
  },
];

More informations:
Nested Routes on Vue-Router
Lazy Component Loading on Vue-Router

It is necessary to place every component in its own language folder, including the English one.
# normal directory tree
server
├── your-project
│   ├── pages
│   │   ├── en
│   │   │   ├── index.vue
│   │   │   └── somepage.vue
│   │   └── es
│   │       ├── index.vue
│   │       └── somepage.vue
│   ├── ...

const getComponentByLang = (resolve, route, componentPath) => {
  const lang = route.params.lang;
  return import(`./pages/${lang}/${componentPath}.vue`).then((component) => {
    resolve(component);
  });
};

Alternatively, you can declare the English language as an exception when defining the component's path.
# normal directory tree
server
├── your-project
│   ├── pages
│   │   ├── index.vue
│   │   ├── somepage.vue
│   │   └── es
│   │       ├── index.vue
│   │       └── somepage.vue
│   ├── ...

const getComponentByLang = (resolve, route) => {
  const lang = route.params.lang;
  const path = lang === 'en' ? `./pages/${componentPath}.vue` : `./pages/${lang}/${componentPath}.vue`
  return import(path).then((component) => {
    resolve(component);
  });
};

Language selection in both cases
In broad strokes... You need an array listing the selectable languages. Then, you create a dropdown menu where you populate the options from that array. Upon value change in the dropdown, you invoke a language selection function. Assuming you have translations for ALL your pages, within this function, you'll replace the "language" part of the current URL with the selected language. So, for instance, if the current URL is example.com/en/articles/mycurrenttitle, after selecting a new language, the URL will become example.com/es/articles/mycurrenttitle.
<template>

    Select Language:
    <select id="language" v-model="selectedLanguage" @change="changeLanguage">
      <option v-for="language in languages" :value="language.value" :key="language.value">{{ language.label }}</option>
    </select>

Current URL: {{ currentUrl }}

Selected Language: {{ selectedLanguage }}

</template>

Answer: use vue-multilanguage plugin
for reference check here
https://www.npmjs.com/package/vue-multilanguage


What is the power of the test if the null hypothesis is true?

Question: E.g. the null hypothesis is $\beta = 0$, while the true value of $\beta$ is 0. What would be the power of the hypothesis test?
My way of thinking is: Since the power of the test is 1- Prob(Type II error) (Type II error is the error to accept the null hypothesis when it is false). However, since the null hypothesis is true here, Prob(Type II error)=0. So the power of the test is 1. Am I correct?
Comment: Power given the null hypothesis is true = Prob(Type I error) =$\alpha$.
Comment: @a_statistician brief though that is why not post it as an answer?
Comment: @mdewey Yes. Because it is simple and common knowledge in statistics.
Answer: If the null hypothesis is true, the concept of power doesn't make sense. Power is the probability of drawing a sample that causes you to reject the null hypothesis when the null hypothesis is false. It has no meaning when the null hypothesis is true.
Comment: Well, power is usually seen as a function of parameter value. Then the power at the null is simply $\alpha$, the significance level.


Can these two situations be efficiently distinguished?

Question: We have N+1 dice, one two-sided and N 6-sided ones. The marginal probability density functions are such that each die is fair, i.e. each face shows up with probability $1/6$.
We want to distinguish two different situations:
H1) The dice are correlated in the following sense. It is possible to write 0s and 1s (at least one!) on the faces of the dice, and that for each throw the sum modulo two is 0.
H2) For any labelling of the dice, the sum modulo two is random, i.e. not constant.
The question is: How many times do we have to throw the dice to distinguish H1 from H2 (with some confidence)? What is the best scaling with respect to N which we could get with methods from statistics?
Now my first approach was to repeat the experiment and try to find the labelling, but that's a hard combinatorical problem. Then I thought that some test of indepence should also do the trick. I know little about statistics, but I found that a Pearson's Chi-squared test could help. Or since we want to do as few experiments as possible maybe I should look into Fisher exact test. I didn't find information on the minimum required sample size, though. And then there are other tests, like kernel statistical tests which look involved, so I would appreciate your take on this before I try to understand the details.
An example of H1:
$$
\begin{array}{cccc}
\text{die}_1 &\text{die}_2& \text{die}_3 & \text{probability}\\
 1 & 1 & 4 & \frac{1}{18} \\
 1 & 2 & 4 & \frac{1}{18} \\
 1 & 3 & 3 & \frac{1}{18} \\
 1 & 4 & 1 & \frac{1}{18} \\
 1 & 4 & 2 & \frac{1}{18} \\
 1 & 5 & 5 & \frac{1}{18} \\
 1 & 5 & 6 & \frac{1}{18} \\
 1 & 6 & 5 & \frac{1}{18} \\
 1 & 6 & 6 & \frac{1}{18} \\
 2 & 1 & 1 & \frac{1}{18} \\
 2 & 1 & 2 & \frac{1}{18} \\
 2 & 2 & 1 & \frac{1}{18} \\
 2 & 2 & 2 & \frac{1}{18} \\
 2 & 3 & 5 & \frac{1}{18} \\
 2 & 3 & 6 & \frac{1}{18} \\
 2 & 4 & 4 & \frac{1}{18} \\
 2 & 5 & 3 & \frac{1}{18} \\
 2 & 6 & 3 & \frac{1}{18} \\
\end{array}$$
Here the labelling $(1,0)$, $(1, 1, 1, 0, 0, 0)$ and $(0, 0, 1, 1, 0, 0)$ for the sides of the first, second and third die, respectively, gives the constant parity of the outcome.
An example of H2:
$$
\begin{array}{cccc}
\text{die}_1 &\text{die}_2& \text{die}_3 & \text{probability}\\
 1 & 4 & 4 & \frac{1}{18} \\
 1 & 4 & 5 & \frac{1}{18} \\
 1 & 4 & 6 & \frac{1}{18} \\
 1 & 5 & 4 & \frac{1}{18} \\
 1 & 5 & 5 & \frac{1}{18} \\
 1 & 5 & 6 & \frac{1}{18} \\
 1 & 6 & 4 & \frac{1}{18} \\
 1 & 6 & 5 & \frac{1}{18} \\
 1 & 6 & 6 & \frac{1}{18} \\
 2 & 1 & 1 & \frac{1}{18} \\
 2 & 1 & 2 & \frac{1}{18} \\
 2 & 1 & 3 & \frac{1}{18} \\
 2 & 2 & 1 & \frac{1}{18} \\
 2 & 2 & 2 & \frac{1}{18} \\
 2 & 2 & 3 & \frac{1}{18} \\
 2 & 3 & 1 & \frac{1}{18} \\
 2 & 3 & 2 & \frac{1}{18} \\
 2 & 3 & 3 & \frac{1}{18} \\
\end{array}
$$
Here no labelling can be found that gives a constant parity.
Comment: So the models are H0: always get 0. H1: obtain 0 with probability 1/2 or 1 with probability 1/2? It's the same as, can we test whether a coin has heads on each side by tossing it many times? It's pretty clear that we have pretty good power to reject H0 when it's false with only 5 or so flips.
Comment: Each individual die is fair: once you decided which faces to label 0 and which 1 the probability to see 0 will be 1/2. However, the dies are correlated, such that for H1 the last die you throw will show exactly the side that makes the sum modulo two become zero - if you labelled correctly.
Comment: What are you assuming about the individual dice?  Are they fair, for instance?  How does "not possible" translate to "uniformly random"?  (Those two statements do not appear to be equivalent.)
Comment: According to the present answer, you appear to describe a simple problem.  Is that interpretation correct, or are we overlooking some subtle difference?  The effort you make to describe such a complex setting suggests there must be a difference, but what is it?
Comment: @whuber maybe the subtle difference is, that we need to assign 0 and 1 to the faces, while it would be simple if we knew how to label them. But I'm still trying to understand the answer better.
Comment: That doesn't appear to make any difference at all: the assignment of zeros and ones appears irrelevant to the solution.
Comment: One problem with your question is that H2 is not a statistical hypothesis, because it doesn't concern any particular experiment: it concerns some combinatorial (mathematical) possibility rather than something you can observe.  This seems to be a case of trying to ask a question through an analogy that doesn't work.  Could you please just describe your actual problem?
Comment: @whuber The "dice" are actually quantum measurements in my application, but I thought it's easier to ask it without the quantum stuff that produces the distribution.
Comment: I think H2 is the lack of the kind of correlation we see in H1, and my guess was that some kind of independence measure can distinguish the two.
Comment: What information can I add to clarify the question?
Answer: So the models are

$H_0$: always get 0, and
$H_1$: obtain 0 with probability 1/2 or 1 with probability 1/2.

your question is equivalent to can we test whether a coin has heads on each side by tossing it many times. It's pretty clear that we have pretty good power to reject $H_0$ when it's false with only 5 or so flips.
Comment: I don't think this is equivalent to my question, or I do not see how.
Comment: @M.Stern It is. H0 is straightforward, as it's defined so that you always get modulo 0. For H1, every die you roll has a 50% chance of flipping the parity of the modulo from 0 to 1 or 1 to 0, and a 50% chance of keeping it the same. You pointed out in the question itself that you get 0 or 1 with 50% probability under the second scenario, and 0 100% of the time under the first scenario. It doesn't matter if you produce those probabilities by flipping coins or rolling dice.
Comment: oh ok, "always get 0" refers to the parity of all outcomes. Maybe I need just more explanation on how to perform the test, then. Note that it is not obvious whether a face should be labelled 0 or 1. For H1 we only know that such a labelling exists.
Comment: I found that I should not assume uniform randomness in H2, and the probabilities could be different from one half. I hope this edit to the question does not affect your answer (I don't think so, but I also do not understand, yet).


Python erro com orientação a objetos

Question: class DBAction(object):
    __conn = None
    __cursor = None
    __id = None

    def __init__(self, arg):
        self.__id = arg
        self.__conn = sqlite3.connect('clientes.db')
        self.__cursor = conn.cursor()

    def insert(self):
        sql = ''' INSERT INTO history(id,conversation)
              VALUES(?,?) '''
        self.__cursor.execute(sql, self.__id, "user : "+srt(self.__id))
        self.__conn.commit()

    def verify(self):
        self.__cursor.execute("SELECT * FROM history WHERE id = '"+self.__id+"'")
        rows = cur.fetchall()
        for row in rows:
            print(row)

A classe acima esta retornando o erro:
self.__cursor.execute(sql, self.__id, "user : "+srt(self.__id))
NameError: name 'self' is not defined

E não estou entendendo o porque, alguém sabe me dizer o motivo? Sou novato em POO em python
Comment: eviye usar nomes com prefixo de dois underscores `__`  - esse uso não é para "atributos privados" - qualquer texto que você tenha dizendo isso está datado, e foi escrito por uma impressão errônea da linguagem na década passada. Na pratica, só vai te dar dor de cabeça.
Comment: Eu falo mais detalhadamente sobre esse uso do `__` numa parte desta resposta: https://pt.stackoverflow.com/questions/351309/sobrescrever-property-na-classe-filha/352209#352209
Answer: Não seria porque você está iniciando self.__cursor com um valor não definido?
De onde vem esse conn? Não seria self.__conn?
def __init__(self, arg):
    self.__id = arg
    self.__conn = sqlite3.connect('clientes.db')
    self.__cursor = self.__conn.cursor()

Comment: Valeu, foi falta de atenção da minha parte ;-;

Python erro com orientação a objetos


Let $X_1$ and $X_2$ be ind, normal random variables with $\mu=0$ and $\sigma^2=1$. Let $Y_1=X_1-X_2$, $Y_2=X_1+X_2$. Find $F_{Y_1,Y_2}$

Question:
Let $X_1$ and $X_2$ be ind, normal random variables with $\mu=0$ and $\sigma^2=1$. Let $Y_1=X_1-X_2$, $Y_2=X_1+X_2$. Find joint density of $Y_1,Y_2$.

I tried to solve this using $$f_{Y_1,Y_2}=\frac{d^2}{dy_1dy_2}F_{Y_1,Y_2}(y_1,y_2)$$
$$=\frac{d^2}{dy_1dy_2}P(Y_1\leq y_1, Y_2\leq y_2)$$
$$=\frac{d^2}{dy_1dy_2}P(X_1-X_2\leq y_1, X_1+X_2\leq y_2)$$
But from here I'm not sure how to do this because differentiating with $y_1$ and then $y_2$ doesn't seem to make sense. So I'm not sure if this method just doesn't work, I don't think I can use moment generating functions to solve either.
Comment: Hint: use linearity of expectation and the variance of sum rule to compute these parameters... Use, say, an MGF, and you'll see something nice!
Comment: Are you familiar with the general method for calculating how the density transforms under coordinate transformations? It's just like how an integrand transforms, you calculate a Jacobian and all that...
Comment: (Alternatively, there's a theorem that linear combinations of normals are multivariate normal distributed, so it's just a matter of calculating means and a covariance matrix.)
Answer: One simple way of answering this is to us characteristic functions.
$Ee^{itY_1+isY_2}=Ee^{i(t+s) X_1} Ee^{i(s-t) X_2}$. This becomes $e^{-(t+s)^{2} /2} e^{-(s-t)^{2} /2}=e^{-t^{2}} e^{-s^{2}}$. From this you can conclude that $Y_1$ and $Y_2$ are independent  normal variables  with mean $0$ and variance $2$. Hence $F_{Y_1Y_2} (x,y)=\int_{-\infty} ^{x}\int_{-\infty} ^{y} \frac 1 {2\pi} e^{-u^{2}/4}e^{-v^{2}/4} dudv$.


How do I determine whether traits in a subgroup of a big group are significantly different than the traits in the whole group in R

Question: I have a big group of 1052 people. Out of 18 people with trait A 11 people also have trait B.
Out of the whole group of 1052 people 569 have trait B.
How do I determine in R whether the trait B is significantly different distributed in people with trait A compared to the overall population?
Answer: There are at least two ways: Chi-square and logistic regression.
Chi square would be used if you don't think either A or B is a dependent or independent variable. In R
traitA <- c(rep('Yes', 18), rep('No', 1052-18))
traitB <- c(rep("Yes", 11), rep("No", 7), rep('Yes', 569), rep("No", 1052-569-18))

chisq.test(traitA, traitB)

Logistic regression would be if you think that (say) B is a dependent variable:
m1 <- glm(traitB=='Yes'~as.factor(traitA), family = 'binomial')
summary(m1)


force close if mediaplayer is not used and back button pushed

Question: In an activity I'm using two media players for different sounds, if both sounds are played and the back button is pushed there is no problem, it works fine. the media players stop and release.(mp is set to loop, mps just plays a short sound)
<code>@Override
protected void onPause() {
    // TODO Auto-generated method stub
    mp.stop();
    super.onPause();
}
@Override
protected void onStop() {
    // TODO Auto-generated method stub
    mp.release();
    mps.release();
    super.onStop();
}
</code>
But, if one and/or both sounds are not played I get a forced close when the back button is pushed and a null pointer exception. How would you write code to check if the mediaplayers were ever used and therefore need to stop and release them?
Comment: could you use a count and add one to it if there has been a play then check if it equals 0 or not.
Answer: could you use a count and add one to it if there has been a play then check if it equals 0 or not.
Answer: If you are getting a null pointer in your onPause and onStop you need to check if mp is null.
<code>@Override
protected void onPause() {
    if (mp != null)
      mp.stop();
    super.onPause();
}
@Override
protected void onStop() {
   if (mp != null)
    mp.release();
   if (mps != null)
    mps.release();

    super.onStop();
}
</code>
You can keep a count if you would like to but that means keeping track of another variable when you already have access to the variables you need
Comment: I got it to work!!  I release the media player directly after the short sound is played and use the if (mp != null) stop and release at onPause.  Thank you everyone for your suggestions.


Converting number to binary, can't fix 0/0 error

Question: Hello I have a program that successfully converts decimal to binary. However, at the end the code divides 0 by 0 resulting in an error message at the end. Here's the code.
import java.lang.*;
import java.util.*;
public class BinaryConverter {
public static void main (String[] argv) {

    Scanner input = new Scanner (System.in);

    int number = 0;
    int factorOfTwo = 0;

    do {
        System.out.println("Enter the number to convert (0-255): ");
        number = input.nextInt();
    }  while (number< 0 || number > 255);

    System.out.println("The number " + number + " converted to binary is : ");

    for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo*=2) {
        if (number / factorOfTwo >= 1){
            System.out.print("1");
            number -= factorOfTwo;
        }
        else System.out.print ("0");
    }

} // end of main
}// end of class

Comment: The only division is by `factorOfTwo`, and I don't see how `factorOfTwo` can be zero.
Comment: Doesn't solve your problem, but you should start with dividing by 128.
Comment: I'm not seeing an error... your code would be cleaner if you declared variables in as small a scope as possible, but it's not giving me an error... what value is failing?
Comment: You could just use the [`toBinaryString()`](http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString%28int%29) instead.
Comment: Sorry everyone, here is the error message, note that this is in Eclipse:

Exception in thread "main" java.lang.ArithmeticException: / by zero
 at Test2.main(Test2.java:28)

So obviously it is an arthmetic error, but yes the program does stop at 8 digits, so it does work, and nobody would see that error code in reality I guess. Sorry for the confusion... and i didint expect this many responses so fast.
Comment: There's a long way from _doesn't crash_ to _working_. You have to at least iterate the division (or subtraction suggested by alestanis) from highest bit to lowest. Or change the x/y>=1 operation to x%y>0 operation. (and even in that way you would be processing the bits right to left, which isn't the typical representation of binary numbers)
Answer: What is the error message you are receiving? because your factorofTwo can never be 0.
for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo*=2)..here it is only being incremented
Comment: yes. I agree with @AkiSuihkonen. The value of `factorofTwo` should start with `128` and be then decremented. 128-->64-->32-->and so on.
Answer: There is no division by zero in the posted code. There is only one division and factorOfTwo can never be 0 in that loop.
If you still get division by zero error, make sure that you are running on this code:

Check that the compiled class file is newer the source file.
Check that the compiled class file is first in the classpath.

Also, note Aki's comment. You are creating the binary number backwards.