How can I get a link to a file to open said file?

Question: I generate a PDF file within a Sharepoint page; as I have so far been unable to let the user choose a landing spot for the pdf file (as asked about here), I have decided to create a link to the file on the page, hoping that clicking the link will open the file. Here's the code:
        String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
        String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf",
    pdfFileID);
        String fileFullpath

Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), pdfFileName);
        String fileLinkBase = "Generated PDF: {1}";
        String filelink = String.Format(fileLinkBase, fileFullpath, pdfFileName);
        File.WriteAllBytes(fileFullpath, bytes);
        AddVerticalSpace();
        var pdflink = new Label // would this be preferable: "LiteralControl pdflink = new LiteralControl();" ?
        {
            CssClass = "dplatypus-webform-field-label",
            Text = filelink
        };
        this.Controls.Add(pdflink);

This creates the link just fine:

...but clicking the link doesn't open the file. Or give an err msg; it just sits there like a lump in a bog.
To verify that it wasn't something to do with the PDF file, I tried creating a text file in the path and accessing it:
String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
pdfFileName = "czechitout.txt"; // Remove after testing

...but alas, also clicking on "czechitout.txt" does nothing - Notepad does not open or give any indication at all as to the reason for its recalcitrance to do so.
So: how can I get a link on a Sharepoint page to invoke the associated software to run the file referenced?
UPDATE
NOTE: I would settle for opening Explorer, displaying the file (usually the user will be copying it from one place to another anyway).
UPDATE 2
By simply saving the file without any path info, like so:
String pdfFileID = GetYYYYMMDDAndUserNameAndAmount();
String pdfFileName = String.Format("DirectPayDynamic_{0}.pdf", pdfFileID);
String fileLinkBase = "Generated PDF: {1}";
String filelink = String.Format(fileLinkBase, pdfFileName, pdfFileName);
File.WriteAllBytes(fileFullpath, bytes);
AddVerticalSpace();
var pdflink = new Label // would this be preferable: "LiteralControl pdflink = new LiteralControl();" ?
{
    CssClass = "finaff-webform-field-label",
    Text = filelink
};
this.Controls.Add(pdflink);

When I mash the link, I get, "Error on Page"
F12ing gives me the low-down/skinny/buttlescut:
Not allowed to load local resource: file:///DirectPayDynamic_20150717_clayshan_0.pdf
UPDATE 3
I then tried the suggestion of saving to a specific directory (without using the fancy-pants "SpecialFolder" jazz, like so:
String pdfFileName = String.Format(@"C:\Projects\DirectPaymentWebForm\DirectPayDynamic_{0}.pdf", pdfFileID);

...but I fared no better that way (the file is plopped there, but trying to invoke it via the link is an exercise in futility).
UPDATE 4
I even tried it with a lowly text file, de modo que:
String pdfFileName = @"C:\Projects\DirectPaymentWebForm\tryopeningthis.txt";

...but my catch block is reached:
catch (Exception ex)
{
    String exMsg = ex.Message;
}

...wherein the msg is, "Access to the path 'C:\Projects\DirectPaymentWebForm\tryopeningthis.txt' is denied."
The path/file does exist; why would I not get that same err msg with the pdf file?!?
Comment: As I understand, it is not related to sharepoint. It is the issue that a tag with href="file://.../a.pdf" cannot be opened. If so, I have this issue also.  :P
Comment: I would settle for opening Explorer, displaying the file (usually the user will be copying it from one place to another anyway).
Answer: This is not the problem with the file. It is because of the security concepts.
Any file that we are referring inside our web pages, need to be under the same directory structure.
If you could open the developer tools using F12 option inside the browser, you can see some console errors saying

Not allowed to load local resource: "your file path"

you can achieve that in two ways:

try generating your file to the application folder structure
create a link button and on click of that button, send the document as a stream to output

Hope this solves your problem.
EDIT
with the approach mentioned in point 1, you can use below code.

   <a href="<your file path>">link

In the file path, it is not required to mention file:/// text.
This works
EDIT
The above process makes the file to load in the current page itself.
To load file in another window or as a popup, use

<a href="javascript:window.Open("<file name>");">link

Comment: 1) I meant "application folder structure" to the directory of your sharepoint site. If your site directory path is "C:\\Sites\", then your PDF should be under the above said directory or its child directories. 2) one more way is to have another page with an IFrame in it and load the PDF into that frame, so that the user can have option to save
Comment: in your code, you are creating **fileFullPath** by mentioning desktop path. Instead, you can just mention the file name alone or any subdirectory w.r.t your sharepoint page. by doing like that, you can make your link opening the PDF file.
Comment: please check my edit. your Update 2 will work. Only thing is you have to remove the file:/// text. The href should be just relative path of your file.
Comment: I don't know what you mean by #1, as users will access this via an URL - what would be the "application folder structure" for them? In #2, do you mean output the pdf on a new page within the browser? If so, that won't work - we need it to be a standalone .pdf file residing on disk.
Comment: Not really; I need to create a "regular" PDF that the user can easily open, or at least its location in Explorer, so they can copy the file and paste it elsewhere.
Comment: Thanks, but see Update 2.
Comment: It would be nice if that were true, but removing the "file:///" still fails, tells me "Error on Page", and F12ing shows me, "Not allowed to load local resource: file:///C:/Users/TEMP.SP.016/Desktop/DirectPayDynamic_20150720_clayshan_0.pdf"


Apply blue frame and icon inside of input box

Question: Based on this code I would like it to add it inside of a input box that contain text. Is it possible to do it?
Thanks!

$(".delete-tag").click(function() {

  $(this).parent().remove();

});
.delete-tag {
  width: 14px;
  height: 14px;
  vertical-align: middle;
  display: inline-block;
  cursor: pointer;
  margin-left: 3px;
  margin-top: 1px;
  margin-bottom: -1px;
}
.delete-tag:hover,
.delete-tag-active {
  background-image: url("https://cdn0.iconfinder.com/data/icons/gcons-2/24/silhouette5-16.png"), none;
  background-size: initial;
}
.delete-tag {
  background-image: url('https://cdn0.iconfinder.com/data/icons/gcons-2/22/airplane1-16.png');
  margin-top: 0;
  margin-bottom: 0;
}
.post-tag {
  text-decoration: none;
  text-align: center;
  line-height: 1;
  color: #3e6d8e;
  font-size: 12px;
  white-space: nowrap;
  background: #e4edf4;
  border: 1px solid #e4edf4;
  display: inline-block;
  border-radius: 0;
  -webkit-transition: color .15s ease, background .15s ease, border .15s ease;
  -moz-transition: color .15s ease, background .15s ease, border .15s ease;
  -ms-transition: color .15s ease, background .15s ease, border .15s ease;
  -o-transition: color .15s ease, background .15s ease, border .15s ease;
  margin: 2px 2px 2px 0;
  padding: .4em .5em;
}
.post-tag:hover {
  text-decoration: none;
  color: #3e6d8e;
  background-color: #dae6ef;
  border: 1px solid #dae6ef;
  background-color: #DAE6EF;
}

   aasdfas

   basdfasdf

   basdfasdf

Comment: you can use a `` instead of an input text box manipulations would be easier
Comment: Can you show me by using code snippet? it is easier to understand.
Answer: Check out the snippet I have used the tags inside a div.tags and added a p[contenteditable=true] in a div block, Now obviously you will have multiple tags so I have kept one of your tag in one and other two in another one

$(".delete-tag").click(function() {

  $(this).parent().remove();

});
.delete-tag {
  width: 14px;
  height: 14px;
  vertical-align: middle;
  display: inline-block;
  cursor: pointer;
  margin-left: 3px;
  margin-top: 1px;
  margin-bottom: -1px;
}
.delete-tag:hover,
.delete-tag-active {
  background-image: url("https://cdn0.iconfinder.com/data/icons/gcons-2/24/silhouette5-16.png"), none;
  background-size: initial;
}
.delete-tag {
  background-image: url('https://cdn0.iconfinder.com/data/icons/gcons-2/22/airplane1-16.png');
  margin-top: 0;
  margin-bottom: 0;
}
.post-tag {
  text-decoration: none;
  text-align: center;
  line-height: 1;
  color: #3e6d8e;
  font-size: 12px;
  white-space: nowrap;
  background: #e4edf4;
  border: 1px solid #e4edf4;
  display: inline-block;
  border-radius: 0;
  -webkit-transition: color .15s ease, background .15s ease, border .15s ease;
  -moz-transition: color .15s ease, background .15s ease, border .15s ease;
  -ms-transition: color .15s ease, background .15s ease, border .15s ease;
  -o-transition: color .15s ease, background .15s ease, border .15s ease;
  margin: 2px 2px 2px 0;
  padding: .4em .5em;
  float:right;
}
.post-tag:hover {
  text-decoration: none;
  color: #3e6d8e;
  background-color: #dae6ef;
  border: 1px solid #dae6ef;
  background-color: #DAE6EF;
}

.inputtext{
  float:left;
  border:1px inset #ccc;
  margin:10px;
  width:100%;
  min-height:30px;
}

.inputtext > p.editable{
  float:left;
  height:100%;
  margin:3px;
  width:70%;
  display:inline;
  padding:2px;
}

.tags{float:left;}

   aasdfas

Editable Text

      basdfasdf

   basdfasdf

Editable Text

This is how it looks to me. I am using safari on a Mac. I checked with Firefox looks ok. Is it something else that you are looking for
Comment: is it possible to have the button to be on the left side, not right side?
Comment: Sure why not edited the snippet the buttons should be on the left now
Comment: But the data is not inside of input like in the picture. I have updated the content page.
Comment: I have now uploaded the picture. Please inform me if you can't see it.
Comment: @HelloWorld Updated Answer: This is how it looks to me. I am using safari on a Mac. I checked with Firefox looks ok. Is it something else that you are looking for
Comment: I have not expected the result but this time I will take it as a yes. I have uploaded with improved pedagogical ability."http://stackoverflow.com/questions/32127963/add-data-with-class-in-input"


Calculating SD for Change in time

Question: I'm conducting a meta-analysis on weight change (T2 - T0) between Group 1 and Group 2. The data I have typically looks like this:
Weight (kg)
Group 1 (n=15)  |  Group 2 (n=14)
T0 65.31±16.49  |  59.06±18.40
T2 63.63±15.20  |  61.49±17.84
I can easily calculate mean weight change, but I'm struggling to calculate the standard deviation (SD) for this change. Considering the potential correlation between T0 and T2 measurements, how can I accurately calculate SD for weight change?
Thank you for any help you can provide.
Comment: You need to know the correlation.
Comment: What do you mean by that?
I need the r?
How would be possible to obtain that?
Is there any other way to approach that?
Comment: You would obtain the correlation by tracking individuals within the groups.
Answer: The answer (with examples) is found here:
https://handbook-5-1.cochrane.org/chapter_16/16_1_3_2_imputing_standard_deviations_for_changes_from_baseline.htm
For the correlation, we typically assume a rho of 0.5.
In the above link, you see that the correlation can be calculated from studies that report mean (SD) for the baseline, follow-up and mean change from baseline.
Comment: I would simply assume 0.5 for the correlation. The assumed value should be informed by substantive knowledge about the rank-order stability of the measurements over a given time frame.

Calculating SD for Change in time


What does a circle under the head of a note in flute mean?

Question: Upon reading the Modern Method for the Boehm Flute, I came upon this notation:

What does the circle under the head of the note mean?
Comment: This looks too asymmetric and smudged to be a proper symbol. It's probably a bit of dirt introduced during the printing process.
Comment: To test the currently popular "smudge theory," I wonder if it's possible to find a different copy of the same book and see if it also has a "smudge."
Comment: I haven't found another one online (other than IMSLP's), so it might be up to someone at a library to find out.
Comment: It looks familiar. I might have an orchestration book that uses that symbol.
Answer: Take a look at page 19 of this PDF from the University of Florida:

It definitely seems to be an indication for a natural harmonic. I know @Richard said a harmonic was notated differently, but perhaps he was thinking of an artificial harmonic? As for the lack of centering, I can see that as a typesetting issue.
Comment: The low D can't possibly be a harmonic on the flute.
Answer: Believe it or not, I'm pretty certain this is just the worst-placed and worse-shaped piece of fuzz to ever find its way onto a scanner, because:

The symbol is not actually centered with the note head.
The symbol doesn't appear to actually be a circle.
The symbol doesn't appear anywhere else in the book (as far as I can tell).

The nearest notation I can think of would be harmonics, but they are notated differently on a flute.


Alterar itens do sidemenu em Ionic 5

Question: Estou migrando um projeto do ionic 3.2 para o 5.14, e estou com dificuldades para usar observables em vez de events.
No código original, após o usuário logar, eu alterava o nome e a imagem do sidemenu através de events:
login.pages.ts
this.events.publish('user:login', this.nomePrimeiro, Date.now());
this.events.publish('image:login', this.imagem, Date.now());

e no app.component.ts eu coloquei isto:
events.subscribe('user:login', (user, time) => {
  Global.nomePrimeiro = user;
});

events.subscribe('image:login', (image, time) => {
  Global.imagem = image;
});

Como fazer o mesmo com Observables?
Answer: Aparentemente você está lidando com evento de login. Nesse caso, o aconselhável é utilizar o guard. Mais detalhes aqui.
De toda forma, para fazer a comunicação entre dois components você pode criar um serviço intermediário. Por exemplo, crie o login.service.ts:
import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs';

@Injectable()
export class LoginService {

  // Observable string sources
  private userSource = new Subject<string>();
  private imageSource = new Subject<string>();

  // Observable string streams
  user$ = this.userSource.asObservable();
  image$ = this.imageSource.asObservable();

  // Service message commands
  anunciarUsuario(user) {
    this.userSource.next(user);
  }

  anunciarImagem(image) {
    this.imageSource.next(image);
  }
}

Aí na login.pages.ts:
constructor(private userService: UserService) {}

anunciarUsuario() {
    let usuario = { user: this.nomePrimeiro, time: Date.now() };
    this.userService.anunciarUsuario(usuario);
  }

anunciarImagem() {
    let image = { image: this.imagem, time: Date.now() };
    this.userService.anunciarImagem(imagem);
  }

E por fim, no app.component.ts:
  userSubscription: Subscription;
  imageSubscription: Subscription;

  constructor(private loginService: LoginService) {
    this.userSubscription = loginService.user$.subscribe(
      user => {
        Global.nomePrimeiro = user.user;
    });
    this.imageSubscription = loginService.image$.subscribe(
      image => {
        Global.imagem = image.image;
    });
  }

Eu criei 2 serviços porque seu código estava assim, mas acredito que apenas 1 serviço poderia mandar os dados de usuário e de imagem, deixando tudo bem mais simples. De toda forma, isso deve funcionar, mas fica ainda a sugestão de utilizar os guards para proteger as rotas da sua aplicação.
E também pode consultar aqui para mais detalhes sobre a comunicação entre componenetes.
Comment: Obrigado, resolvi o problema com um único service, mas dentro do que você colocou.

Alterar itens do sidemenu em Ionic 5


Drush migrate-upgrade error

Question: I have run drush migrate-upgrade successfully previously, but not when I run it, I am getting

"An option named "Configure-only" already exists."

I get this error regardless of if I have --configure-only in the command.
The command is:
drush migrate-upgrade --legacy-db-url=mysql://user:password@localhost/db --legacy-root=http://example.com --configure-only

Has anyone seen this error?  I am not seeing anything on any forums about it.
Answer: I ended up resolving this by uninstalling and reinstalling all of the migrate-related modules.  Not an ideal solution, but it worked.

Drush migrate-upgrade error


Writing to memory mapped file is slower than non-memory mapped file

Question: I am trying to use a memory mapped file to write an application that has high IO demands. In this application, I have burst of data that is received at a rate faster than what the disk is able to support. In order to avoid buffering logic in my application, I thought about using memory mapped file. With this kind of file, I would simply write in memory that is mapped to a file (faster than what the disks can support) and the OS would eventually flush this data to disk. The OS is therefore doing the buffering for me.
After experiment, I see that memory mapped files makes it faster to write in memory but the flushing to disk is slower than with a normal file. Here is what leads me to that conclusion. Here is a piece of code that simply writes as fast as it can to a non-memory mapped file:
<code>    private static void WriteNonMemoryMappedFile(long fileSize, byte[] bufferToWrite)
    {
        Console.WriteLine(" ==> Non memory mapped file");

        string normalFileName = Path.Combine(Path.GetTempPath(), "MemoryMappedFileWriteTest-NonMmf.bin");
        if (File.Exists(normalFileName))
        {
            File.Delete(normalFileName);
        }

        var stopWatch = Stopwatch.StartNew();
        using (var file = File.OpenWrite(normalFileName))
        {
            var numberOfPages = fileSize/bufferToWrite.Length;

            for (int page = 0; page < numberOfPages; page++)
            {
                file.Write(bufferToWrite, 0, bufferToWrite.Length);
            }
        }

        Console.WriteLine("Non-memory mapped file is now closed after {0} seconds ({1} MB/s)", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
    }
</code>
This code results in this:
<code>==> Non memory mapped file
Non-memory mapped file is now closed after 10.5918587 seconds (966.687541390441 MB/s)
</code>
As you can see, my disks are quite fast. This will be my benchmark for memory mapped files.
Now I tried to write the same data to a memory mapped file using unsafe code (because this is what I intend to do in my application):
<code>    [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
    public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);

    private static unsafe void WriteMemoryMappedFileWithUnsafeCode(long fileSize, byte[] bufferToWrite)
    {
        Console.WriteLine(" ==> Memory mapped file with unsafe code");

        string fileName = Path.Combine(Path.GetTempPath(), "MemoryMappedFileWriteTest-MmfUnsafeCode.bin");
        if (File.Exists(fileName))
        {
            File.Delete(fileName);
        }

        string mapName = Guid.NewGuid().ToString();

        var stopWatch = Stopwatch.StartNew();
        using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(fileName, FileMode.Create, mapName, fileSize, MemoryMappedFileAccess.ReadWrite))
        using (var view = memoryMappedFile.CreateViewAccessor(0, fileSize, MemoryMappedFileAccess.Write))
        {
            unsafe
            {
                fixed (byte* pageToWritePointer = bufferToWrite)
                {
                    byte* pointer = null;
                    try
                    {
                        view.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);

                        var writePointer = pointer;

                        var numberOfPages = fileSize/bufferToWrite.Length;

                        for (int page = 0; page < numberOfPages; page++)
                        {
                            memcpy((IntPtr) writePointer, (IntPtr) pageToWritePointer, (UIntPtr) bufferToWrite.Length);
                            writePointer += bufferToWrite.Length;
                        }
                    }
                    finally
                    {
                        if (pointer != null)
                            view.SafeMemoryMappedViewHandle.ReleasePointer();
                    }
                }
            }

            Console.WriteLine("All bytes written in MMF after {0} seconds ({1} MB/s). Will now close MMF. This may be long since some content may not have been flushed to disk yet.", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
        }

        Console.WriteLine("File is now closed after {0} seconds ({1} MB/s)", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
    }
</code>
I then get this:
<code>==> Memory mapped file with unsafe code
All bytes written in MMF after 6.5442406 seconds (1564.73302033172 MB/s). Will now close MMF. This may be long since some content may not have been flushed to disk yet.
File is now closed after 18.8873186 seconds (542.162704287661 MB/s)
</code>
As you can see, this is much slower. It writes at about 56% of a non memory mapped file.
I then tried another thing. I tried to use a ViewStreamAccessor instead of unsafe code:
<code>    private static unsafe void WriteMemoryMappedFileWithViewStream(long fileSize, byte[] bufferToWrite)
    {
        Console.WriteLine(" ==> Memory mapped file with view stream");
        string fileName = Path.Combine(Path.GetTempPath(), "MemoryMappedFileWriteTest-MmfViewStream.bin");
        if (File.Exists(fileName))
        {
            File.Delete(fileName);
        }

        string mapName = Guid.NewGuid().ToString();

        var stopWatch = Stopwatch.StartNew();
        using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(fileName, FileMode.Create, mapName, fileSize, MemoryMappedFileAccess.ReadWrite))
        using (var viewStream = memoryMappedFile.CreateViewStream(0, fileSize, MemoryMappedFileAccess.Write))
        {
            var numberOfPages = fileSize / bufferToWrite.Length;

            for (int page = 0; page < numberOfPages; page++)
            {
                viewStream.Write(bufferToWrite, 0, bufferToWrite.Length);
            }

            Console.WriteLine("All bytes written in MMF after {0} seconds ({1} MB/s). Will now close MMF. This may be long since some content may not have been flushed to disk yet.", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
        }

        Console.WriteLine("File is now closed after {0} seconds ({1} MB/s)", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
    }
</code>
I then get this:
<code>==> Memory mapped file with view stream
All bytes written in MMF after 4.6713875 seconds (2192.06548076352 MB/s). Will now close MMF. This may be long since some content may not have been flushed to disk yet.
File is now closed after 16.8921666 seconds (606.198141569359 MB/s)
</code>
Once again, this is significantly slower than with a non memory mapped file.
So, does anyone knows how to make memory mapped files as fast as non memory mapped files when writing?
By the way, here is the remainder of my test program:
<code>    static void Main(string[] args)
    {
        var bufferToWrite = Enumerable.Range(0, Environment.SystemPageSize * 256).Select(i => (byte)i).ToArray();
        long fileSize = 10 * 1024 * 1024 * 1024L; // 2 GB

        WriteNonMemoryMappedFile(fileSize, bufferToWrite);
        WriteMemoryMappedFileWithUnsafeCode(fileSize, bufferToWrite);
        WriteMemoryMappedFileWithViewStream(fileSize, bufferToWrite);
    }

    private static double GetSpeed(long fileSize, Stopwatch stopwatch)
    {
        var mb = fileSize / 1024.0 / 1024.0;
        var mbPerSec = mb / stopwatch.Elapsed.TotalSeconds;
        return mbPerSec;
    }
</code>
EDIT 1:
As suggested by usr, I tried to use the SequenctialScan option. Unfortunately, it didn't have any impact. Here is the change that I did:
<code>        using (var file = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.SequentialScan))
        using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(file, mapName, fileSize, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, leaveOpen: false))
</code>
Answer: From the SDK documentation:

Modified pages in the unmapped view are not written to disk until their share count reaches zero, or in other words, until they are unmapped or trimmed from the working sets of all processes that share the pages. Even then, the modified pages are written "lazily" to disk; that is, modifications may be cached in memory and written to disk at a later time. To minimize the risk of data loss in the event of a power failure or a system crash, applications should explicitly flush modified pages using the FlushViewOfFile function.

The .NET programmers took the last sentence seriously, the MemoryMappedViewStream.Dispose() method you are calling does in fact call FlushViewOfFile().  That takes time, you are seeing that back in your profile results.  It is technically possible to bypass this call, don't call Dispose() and let the finalizer close the view handle.
FileStream does not do the equivalent for a file (FlushFileBuffers) so you get the full benefit of the lazy write from the file system cache to the disk.  Happens long after the Dispose() call, unobservable to your program.
Comment: Alternatively, call Dispose in a separate thread?
Answer: I encountered a similar performance issue. As an extension to Hans' answer, I believe the following approach will allow the OS to asynchronously flush the modified data to the filesystem, by disposing the SafeMemoryMappedViewHandle instead of the Stream.
<code>private static unsafe void WriteMemoryMappedFileWithViewStream(long fileSize, byte[] bufferToWrite)
{
    Console.WriteLine(" ==> Memory mapped file with view stream");
    string fileName = Path.Combine(Path.GetTempPath(), "MemoryMappedFileWriteTest-MmfViewStream.bin");
    if (File.Exists(fileName))
    {
        File.Delete(fileName);
    }

    string mapName = Guid.NewGuid().ToString();

    var stopWatch = Stopwatch.StartNew();
    using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(fileName, FileMode.Create, mapName, fileSize, MemoryMappedFileAccess.ReadWrite))
    {
        var viewStream = memoryMappedFile.CreateViewStream(0, fileSize, MemoryMappedFileAccess.Write);
        using (viewStream.SafeMemoryMappedViewHandle)
        {
            var numberOfPages = fileSize / bufferToWrite.Length;

            for (int page = 0; page < numberOfPages; page++)
            {
                viewStream.Write(bufferToWrite, 0, bufferToWrite.Length);
            }

            Console.WriteLine("All bytes written in MMF after {0} seconds ({1} MB/s). Will now close MMF. This may be long since some content may not have been flushed to disk yet.", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
        }
    }

    Console.WriteLine("File is now closed after {0} seconds ({1} MB/s)", stopWatch.Elapsed.TotalSeconds, GetSpeed(fileSize, stopWatch));
}
</code>
Comment: Suppressing the finalizer is a bad idea.  You're skipping a lot more code than just the `FlushViewOfFile`.
Comment: After looking closer, it's actually irrelevant here so I removed it. I was thinking Stream had a finalizer that called Flush, but it doesn't.


Vuetify data-table, how to apply external filters?

Question: How, if at all possible, to apply a filter to a Vuetify v-data-table, in conjunction with the 'regular' search property?
Following the Vuetify example (https://vuetifyjs.com/en/components/data-tables)
, consider a Vuetify data-table with two columns:

Dessert
Category

I want to control the table with a search box, linked to the "Dessert" column:
        <v-data-table
          :headers="headers"
          :items="desserts"
          :search="search"
        ></v-data-table>

and:
    headers: [
      { text: 'Dessert (100g serving)', value: 'name' },
      { text: 'Category', value: 'category' },
    ],

But I want to control a filter on the Category column with a group of checkboxes (exact match). There is such a thing as a "custom-filter", but the documentation is not very detailed on that.
This looks to be the same question (unanswered): How to add individual filters for data-table in vuetify?
Answer: Turns out it's actually quite simple! The filters are defined in the headers property.
No changes required to the html element:
<v-data-table
  :headers="headers"
  :items="desserts"
  :search="search"
></v-data-table>

The headers are moved to the computed-section and defined like this:
computed: {
  headers() {
    return [ { text: 'Dessert (100g serving)', value:'name' }
           , { text: 'Category', value: 'category', filter: value => {
                  return this.array_of_matches.indexOf(value) !== -1
                },
             }
           ]
  }

Where array_of_matches is a variable containing a list of search items. You may optionally want to add case conversion stuff like this: value.toString().toLocaleUpperCase()
The 'regular' search won't match anything on a header that has such a filter defined.


How do I play this part in 'Peacherine rag'?

Question: I'm trying to learn Peacherine rag, but I can't understand how to read this part:

To be more precise, I want to understand:

Why the first note on the bottom part has two legs?
Why is it specified again that the high g (top part) is a sixteenth note?
How do I play the top part, I mean, should I keep my fingers fixed on the first chord and only play the f and g (followed by g ab a) or I have to play the notes on the chord again even if are part of a legato?
Comment: To answer your first question, the G has two legs,(one up one down) because it is a unison. This means that two different voices (or instruments) play the same note.
Answer: As noted in the comments, all of this is because there are multiple voicings.  Multiple stems mean that multiple voices play/sing those notes, which should address your first two questions.
I believe that another voice would be doing the short E-F-G run while the other notes are tied.  If you are trying to do this on a single instrument, you would re-articulate the E (and play the F and G) since it is more important to include as much melody as you can.
Comment: You're right about multiple voices, but where's the one beat rest after the crotchet in the 'tenor' part?
Comment: @Tim I'm sure the notation could be better, but it looks like either there are more than 4 voices or at least one instrument is polytonal.
Answer: It's not particularly written well for piano (I guess that's the instrument you are trying to play it on), but look on the top line (all notes on treble clef) as the melody, with up stems, and part accompaniment, with down stems.
This then puts the first chord as a 'backing', followed by the tune of another Eb, then F and G. The other notes under will make the next 'backing', the Bb and second Eb being held - you have to play the second Eb for the melody, and then it can be held over to the second beat, and then joined by the G. Cut off short, to allow the G Ab and A to end the bar.
You are right to be confused. It's a transcription from something, which doesn't translate too well to piano, so compromises need to happen.If you emphasise the notes with up tails, this will bring out the tune over the accompaniment. Having said that, it appears to be the original piano transcript.
Comment: Good point about holding the note after rearticulating it, that would indeed be the most accurate method.
Answer:
why the first note on the bottom part has two legs?

You're supposed to imagine that there are two parts in the left hand that happen to land on the same G on the first beat.  If this piece was sung, for example, one voice might be singing G, Eb, Eb, and the other G, Bb, Bb.
On the piano you'll probably end up playing it exactly as you would if that G didn't have the extra "leg".

why is it specified again that the high g (top part) is a sixteenth note?

There's a separate melodic line here that goes Eb, F, G while three other voices sustain Bb, Eb, and a higher Bb.  And again they probably could have left off that extra "leg" without changing how you'd play this.

how do i play the top part, i mean, should i keep my fingers fixed on the first chord and only play the f and g (followed by g ab a) or i have to play the notes on the chord again even if are part of a legato?

You don't play the notes of the chord (the Bb, Eb, Bb) again on the second beat, you just sustain those.  You do play the Eb in that inner Eb-F-G melody.  And you'll have to hold that Eb even after you play the F.
What you're trying to do is give the illusion that you are simultaneously (1) sustaining that Bb-Eb-Bb chord, and (2) playing the Eb-F-G line.  Clearly that's impossible since your piano only has one Eb key, but you do the best you can.
This isn't necessarily a bad transcription or anything, piano music is often written like this to show how a sequence of notes is made up of separate melodies layered on top of each other.  That can help you figure out the logic of the music, even when it doesn't literally change the note durations.  In this case I think the notation in the bottom part is a little pedantic, but the way they bring out the inner melody in the top part is helpful.


how can I remove registered .tpl.php file?

Question: When I remove html.tpl.php file, I get this error:
Warning: include(/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php) [function.include]: failed to open stream: No such file or directory in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).
Warning: include() [function.include]: Failed opening '/home/xxxx/public_html/sites/all/themes/cgame/html.tpl.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in theme_render_template() (line 1413 of /home/xxxx/public_html/includes/theme.inc).

How can I remove this file to force drupal use core html.tpl.php file?
Comment: Clear the caches, that should do it
Comment: When I remove html.tpl.php file I get WSOD and I even can not access to clear cache page
Comment: Which *core* `html.tpl.php` file are you actually talking about?
Comment: I need remove sites/all/themes/cgame/html.tpl.php and use modules/system/html.tpl.php instead
Answer: Simply clear the caches either on /admin/config/development/performance or via drush cc all if you've configured drush.
Answer: considering White Screen of Death problem you should clear cache from DB or change default theme to another theme so can clear cache from drupal admin interface, if you have access to DB first solution is easier and fast but in case you don't, use second one :
1.truncate cache table:
TRUNCATE cache;

2.set another default theme so you can clear cache from admin/config/development/performance page.
you can simply edit settings.php and add $conf['theme_default']= "new_theme_name" variable to change default theme or edit variables table in DB and set theme_default name to another name, sample SQL:
UPDATE variable SET value='s:7:"garland"' WHERE name = 'theme_default';

then while this new theme is set you can clear cache as usual and then fallback to old theme without problem.
Comment: ;) I was looking for something like `theme registry editor` to simply remove `html.tpl.php` from default theme, but there isn't


Sun-Ra's harmonies and intervals for the layperson

Question: I heard an interview the saxophonist John Gilmore gave about Sun-Ra:
"His intervals, his knowledge of intervals and harmony are very highly advanced."
I'm a layperson without a background in music theory. I've listened to some Sun-Ra, but to my uneducated ear, it doesn't sound much different from any other type of jazz.
However, since I've heard that interview, I've wondered if there were a way to explain to a lay-person what was so advanced about his intervals and harmony, assuming that that is the case.
Is there something advanced and complex about Sun-Ra's music, beyond it being uniquely his? What I mean is, is it more complex objectively than, say, Bach is from a children's ditty. Can someone explain to me, as a lay-person, what makes his intervals so advanced?
Comment: That whole quoted section is pretty confusing.  He seems to be referring to both the selection of intervals (i.e., creating harmony -- which certainly can be advanced) and the actual distance between notes (which doesn't really make sense to have "advanced" knowledge of).
Comment: @MatthewRead Something along the lines of "It's just a subjective appreciation of Sun-Ra's music" would be an acceptable answer : )
Answer: The jazz musician's interest in harmony took a sharp turn with 'be-bop'.  Early development of this music is poorly-understood because it occurred during a lengthy musician's strike, so documentation (recording) is sparse.  But listening to early '40s recordings, with Monk in particular, helps us appreciate the changes not only to rhythm and structures, but to harmony.
Chords got extended (9ths, 11ths, flatted-13ths, &c.), incorporating notes that appear to the traditional ear as dissonances.  Voicings and inversions exacerbated the 'clashing' nature of these intervals (eg: reducing a 9th one octave makes it a 2nd).  The 'natural' overtones (octaves and fifths) were inconsistent in the new forms, and - with the asymetric rhythms and staccato style - made every note stand out.
By the early 1950s, the harmonies of bop had become integrated with more widely-played musics ('cool-jazz', pop, R&B). Herman Blount, who had come up as an R&B musician (with Wynonie Harris, &c.) got a job as arranger/director with the Fletcher Henderson Orchestra; his job was to 'modernize' the sound.  Naturally, he went with bop harmonies.  He also did a sideline combo, which added John Gilmore on sax in 1953.  Gilmore remained with Blount (Sun Ra), eventually leading the Solar Arkestra when illness forced Blount to retire in the late 80s.
So context for the Gilmore quote includes the historical context (a significant development in jazz/popular harmony) and his close ties with the person.
Sun Ra's dramatic but well-contructed political and philosphic world-view often confuses the casual observer/listener.  Again - look at context!  Contemporaries include Elijah Muhammed, L.Ron Hubbard, Harry Partch, and John Cage - and Blount was aware of ALL their work.
Finally - absent the mystical works of Pythagoras - harmony is a cultural artifact.  Listen to Javanese or Karnatic or Shona traditional music (listen to Charley Patton or Elmore James!) and you hear a different set of intervals in use.  Nobody uses just intonation, just like nobody agrees whether A is 442 or 440.  Charles Ives says "My God - what has sound to do with music?"
Music is something done by a person or persons which results in an aural-based image in the mind of another person or persons.  One listens and deduces the rules...
Answer: He was  referring to the song "Saturn". Specifically the introduction section. A song with very simple intervals is Mary had a little lamb. They are all right next to each other on the keyboard. Now, compare to the introduction of "Saturn" and see if you get an idea


Taxonomy import via csv?

Question: Is there a way to quickly create taxonomy categories by importing a csv file?
If so would it preserve any hierarchical relationships?
I've explored the taxonomy_csv project just not totally sure if it does what i wanted.
Answer: this is a Module Drupal 6 to import nodes from CSV, but acording their description, you can import taxonomy with its hierarchy: http://drupal.org/project/node_import
to Drupal 7 exist an alternative: Feeds http://drupal.org/project/feeds
Comment: Ah. Forgot feeds imports taxonomies. Does it preserve their hierarchical relationships?
Comment: Hello, exist a patch to made this in Feeds to Drupal 7 (I have not tried it) http://drupal.org/node/1152940
Answer: You can use Taxonomy CSV import/export
Also it work well with hierarchical relationships.
Answer: I had to import hundreds for terms, which contained custom fields, for a recent project. Here is a method for Drupal 7 using custom drush command...
 /**
 * Implements hook_drush_command
 */
function glossary_import_drush_command() {
  $items['glossary-import'] = array(
    'description' => "Import glossary terms to Glossary taxonomy from CSV",
    'aliases' => array('gloss-imp'),
    'options' => array(
      'csv' => 'Path to CSV file to use',
    ),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL,
  );
  return $items;
}
/**
 * Run command logic.
 */
function drush_glossary_import($csv) {

  // Read csv contents into PHP
  $file = file_get_contents($csv);

  // Create array from file
  $array = array_map("str_getcsv", explode("\n", $file));

  // Make sure it's converted to utf8
  $array_utf8 = utf8_converter($array);

  // Get the vocab id from the vocabulary name
  $vocab = taxonomy_vocabulary_machine_name_load('VOCABULARY_NAME');

  // Create taxonomy terms for each item in array
  foreach ($array_utf8 as $item) {
    // If we have no term name, skip
    if (!empty($item[0])) {
      // Create some friendly variables from $item
      $term_name = !empty($item[0]) ? $item[0] : '';
      $term_sort_name = !empty($item[1]) ? $item[1] : '';
      $term_search_term = !empty($item[2]) ? $item[2] : '';
      $term_description = !empty($item[3]) ? $item[3] : '';

      // Check if term exists so we do not overwrite or create duplicate term
      $query = new EntityFieldQuery;
      $result = $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->propertyCondition('name', $term_name)
      ->propertyCondition('vid', $vocab->vid)
      ->execute();

      // If we don't find a term with the above query, create term
      if (empty($result['taxonomy_term'])) {
        // Setup term
        $term = new stdClass();
        $term->vid = $vocab->vid;
        $term->name = $term_name;
        $term->field_glossary_sortable_name[LANGUAGE_NONE][0]['value'] = $term_sort_name;
        $term->field_glossary_search_term[LANGUAGE_NONE][0]['value'] = $term_search_term;
        $term->description = $term_description;

        // Save term
        taxonomy_term_save($term);

        // Report message term was saved
        drupal_set_message($term_name . ' added');
      }
      else {
        // Warning message, term exists, skip
        drupal_set_message($term_name . ' exists! Skipping', 'warning');
      }
    }
  }
}

function utf8_converter($array) {
  array_walk_recursive($array, function(&$item, $key) {
    if(!mb_detect_encoding($item, 'utf-8', true)){
      $item = utf8_encode($item);
    }
  });

  return $array;
}

Answer: This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.
https://www.drupal.org/project/taxonomy_csv

Taxonomy import via csv?


Count ID's by using field values in python

Question: I have a table such that
Id  Brand1  Brand2  Brand3  Brand4
0     1       0       0       1
1     1       0       1       0
2     1       0       1       0
3     1       1       0       0
4     1       1       0       1

and I am trying to create a table for the number of Ids using brand in combinations.
         Brand1  Brand2  Brand3  Brand4
  Brand1      -       2       2       2
  Brand2      2       -       0       1
  Brand3      2       0       -       0
  Brand4      2       1       0       -

since they have the same values this would work, too.
         Brand1  Brand2  Brand3  Brand4
  Brand1      -       2       2       2
  Brand2      -       -       0       1
  Brand3      -       -       -       0
  Brand4      -       -       -       -

Comment: Hi, what exactly did you try ? Do you have any code to provide ?
Please check [How to ask a good question](https://stackoverflow.com/help/how-to-ask).
Comment: the logic is not clear at all. I mean what are you counting or adding up?
Comment: The below table is the number of IDs having "1" for both brands. such as for Brand1 and Brand2, there are two IDs who has value of 1 (ID=[3, 4])
Answer: You can do that with a simple matrix product:
import pandas as pd

df = pd.DataFrame({
    'Brand1': [1, 1, 1, 1, 1],
    'Brand2': [0, 0, 0, 1, 1],
    'Brand3': [0, 1, 1, 0, 0],
    'Brand4': [1, 0, 0, 0, 1],
})
cross = df.T @ df
print(cross)
#         Brand1  Brand2  Brand3  Brand4
# Brand1       5       2       2       2
# Brand2       2       2       0       1
# Brand3       2       0       2       0
# Brand4       2       1       0       2


What kind of distribution is $f_X(x) = 2 \lambda \pi x e^{-\lambda \pi x ^2}$?

Question: What kind of function is:
$f_X(x) = 2 \lambda \pi x e^{-\lambda \pi x ^2}$
Is this a common distribution? I am trying to find a confidence interval of $\lambda$ using the estimator $\hat{\lambda}=\frac{n}{\pi \sum^n_{i=1} X^2_i}$ and I am struggling to prove if this estimator has Asymptotic Normality.
Thanks
Comment: Maybe helps: if Y is distributed exponentially, then X=Y^2 is distributed with f_X. You can have a look [here](http://en.wikipedia.org/wiki/Exponential_distribution) for the MLE of Y...
Comment: always, always indicate that the question is related to homework. The homework is for you to learn, just getting the correct answer will not help you, and may even hurt you in the long run. I am surmising that this is a homework from the question of another user.
Comment: @mpiktas  Yes, I know your characterization is correct and teucer's is not (even though it got three upvotes despite the fact that the link to Wikipedia provided therein does not support that claim). I am used to seeing random variables with densities of the form $\frac{r}{\sigma^2}\exp(-r^2/2\sigma^2)$ referred to as _Rayleigh_ random variables: they describe the distance from the origin of the point $(X,Y)$ where $X$ and $Y$ are independent $N(0,\sigma^2)$ random variables.
Comment: @teucer, sorry did not see your comment, so I posted practically the same answer.
Comment: @mpiktas, this question was related to a small part of a homework problem, but I didn't phrase the question in a way someone could simply tell me the answer. It was my every intention to understand the concepts and then solve my homework myself.
Comment: your wording of the question was exemplary, this is how the homework questions should be asked. But knowing the problem context usually helps a lot in providing good answer.
Comment: @mpiktas But your answer says that if $Y$ is an exponential random variable with parameter $\pi\lambda$, then the **square root** of $Y$ has the distribution asked about by OP Mitch whereas teucer's answer says the **square** of $Y$  has the distribution asked about. So, how is your answer practically the same as teucer's (and which one should we believe)?
Comment: @DilipSarwate mine :). If $Y$ is exponential then $P(\sqrt{Y}<x)=P(Y<x^2)=F_\lambda(x^2)$, where $F_\lambda$ is the cdf of exponential distribution with parameter $\lambda$. Practically the same means that you have either root or square. Not the best use of expression practically the same.
Answer: Why do you care about asymptotics when the exact answer is just as simple (and exact)?  I am assuming that you want asymptotic normality so that you can use the $\mathrm{Est}\pm z_{\alpha}\mathrm{StdErr}$ type of confidence interval
If you make the probability transformation $Y_{i}=X_{i}^{2}$ then you have an exponential sampling distribution (as @mpiktas has mentioned):
$$\newcommand{\Gamma}{\mathrm{Gamma}}
\newcommand{\MLE}{\mathrm{MLE}}
\newcommand{\Pr}{\mathrm{Pr}}
f_{Y_{i}}(y_{i})=f_{X_{i}}(\sqrt{y_{i}})|\frac{\partial\sqrt{y_{i}}}{\partial y_{i}}|=2 \lambda \pi \sqrt{y_{i}} \exp(-\lambda \pi \sqrt{y_{i}} ^2)\frac{1}{2\sqrt{y_{i}}}=\lambda\pi\exp(-\lambda\pi y_{i})$$
So the joint log-likelihood in terms of $D\equiv\{y_{1},\dots,y_{N}\}$ becomes:
$$\log[f(D|\lambda)]=N\log(\pi)+N\log(\lambda)-\lambda\pi\sum_{i=1}^{N}y_{i}$$
Now the only way the data enters the analysis is through the total $T_{N}=\sum_{i=1}^{N}y_{i}$ (and the sample size $N$).  Now it is an elementary sampling theory calculation to show that $T_{N}\sim \Gamma(N,\pi\lambda)$, and further that $\pi N^{-1}T_{N}\sim \Gamma(N,N\lambda)$.  We can further make this a "pivotal" quantity by taking $\lambda$ out of the equations (via the same way that I just put $N$ into them).  And we have:
$$\lambda\pi N^{-1}T_{N}=\frac{\lambda}{\hat{\lambda}_{\MLE}}\sim \Gamma(N,N)$$
Note that thus we now have a distribution which involves the MLE and whose sampling distribution is independent of the parameter $\lambda$.  Now your MLE is equal to $\frac{1}{\pi N^{-1}T_{N}}$ And so writing quantities $L_{\alpha}$ and $U_{\alpha}$ such that the following holds:
$$\Pr(L_{\alpha} < G < U_{\alpha})=1-\alpha\;\;\;\;\;\;\;G\sim \Gamma(N,N)$$
And we then have:
$$\Pr(L_{\alpha} < \frac{\lambda}{\hat{\lambda}_{\MLE}} < U_{\alpha})=\Pr(L_{\alpha}\hat{\lambda}_{\MLE} > \lambda > U_{\alpha}\hat{\lambda}_{\MLE})=1-\alpha$$
And you have an exact $1-\alpha$ confidence interval for $\lambda$.
NOTE: The Gamma distribution I am using is the "precision" style, so that a $\Gamma(N,N)$ density looks like:
$$f_{\Gamma(N,N)}(g)=\frac{N^{N}}{\Gamma(N)}g^{N-1}\exp(-Ng)$$
Comment: Thanks! Really great answer, however I needed to use a normal approximation. I completely understand and agree with your solution though.
Answer: It is a square root of exponential distribution with rate $\pi\lambda$. This means that if $Y\sim\exp(\pi\lambda)$, then $\sqrt{Y}\sim f_X$.
Since your estimate is maximum likelihood estimate it should be asymptotically normal. This follows immediately from the properties of maximum likelihood estimates. In this particular case:
$$\sqrt{n}(\hat\lambda-\lambda)\to N(0,\lambda^2)$$
since
$$E\frac{\partial^2}{\partial \lambda^2}\log f_X(X)=-\frac{1}{\lambda^2}.$$


Invalid use of Property

Question: TESTING MODULE
Private Sub fooTest()

   Dim foo As cSegment
   Set foo = New cSegment

   foo.ParseSegment

   Debug.Print foo.Segment

End Sub

CLASS
Option Explicit

Private pElements As Collection
Private pSegmentData As String

Public Property Let ParseSegment(value As String)
   pSegmentData = value
   ParseElements pSegmentData
End Property

I keep getting an error on foo.ParseSegment saying "Invalid Use of property"
I'm not sure whats wrong here, as to my understanding my Let property is setup correctly. Does anyone know why I might be getting this error message?
Comment: Its a property let so expects to be assigned a value: `foo.ParseSegment = something` where `something` is set to `value` within the routine.
Answer: It's a property, not a method(Sub).  You are trying to call it like a method.  Property assignments must be assigned to.
foo.ParseSegment = ""

Comment: Oops, sorry, got my `Let` and `Get` mixed up, ... fixed now.
Comment: Perfect it works great now! Appreciate the hasty response :)

Invalid use of Property


Erro PrestaShop "Cannot select any valid SQL engine. at line 302 in file classes/db/Db.php"

Question: Bom dia,
Tive um problema com os ficheiros do servidor em que foram todos apagados, contudo tinha backup do site todo, posto isto foi efectuado uma reposição de dados, que decorreu na normalidade, mas o que ocorre agora é o seguinte:
Cannot select any valid SQL engine.
at line 302 in file classes/db/Db.php

297.         } elseif (extension_loaded('mysqli')) {
298.             $class = 'DbMySQLi';
299.         }
300.
301.         if (empty($class)) {
302.             throw new PrestaShopException('Cannot select any valid SQL engine.');
303.         }
304.
305.         return $class;
306.     }
307.
DbCore::getClass - [line 236 - classes/db/Db.php]
DbCore::getInstance - [line 48 - config/alias.php]
pSQL - [line 340 - classes/shop/Shop.php] - [1 Arguments]
ShopCore::initialize - [line 119 - config/config.inc.php]
require - [line 27 - index.php] - [1 Arguments]

Já fiz de tudo, já verifiquei e activei as extensões e nada.
Terei que solicitar ao meu host para fazer um reset e depois fazer o restauro?
É que eu mesmo tentando instalar uma nova loja PrestaShop dá este erro.
Obrigado.
Comment: O erro é o acima citado, mais nenhum.
Answer: Está faltando a extensão php mysqlnd.
com o gerenciador de pacotes dnf:
sudo dnf install php-mysqlnd (+ reiniciar php) deve resolver o problema.


In what sense does interim monitoring of clinical trials "cost" a Bayesian?

Question: I have read (and will seek a specific reference on the subject) that unlike Frequentist trials, Bayesians can continually monitor data as it accrues.
A Frequentist tries to control, and thus minimize, the probability of adopting ineffective drugs. A Bayesian tries to maximize the probability that adopted drugs work. Frequentists control for multiple testing by "spending" their alpha. If one performs two or more comparisons, to preserve the overall 0.05 level of the trial, the alpha level is spent by Bonferonni, Pocock, or O'Brien Flemming formulas to control for multiple tests.
It seems, though, that when the Bayesian performs too many "interim looks" there must be some Bayes analogue to multiple testing that you are more likely to make the decision to adopt the drug on the basis of favorable interim results.
So what is the real cost to the analysis? How is it correctly reflected in a properly conducted Bayesian trial? Does the Bayesian enforce more stringent decision rules for future analyses based on the result of an interim look should we decide to keep going? Alternately, do we introduce some uncertainty in the posterior that attenuates effect somewhat to account for the fact that we might be observing a stochastic trend for an ineffective drug that may randomly show "favorable" results?
Comment: My understanding is that the Bayesian is subject to the same penalties as the frequentist as far as conditional error rates and so on are concerned. No escaping that. It's just that Bayesian theory doesn't care about or make any guarantees about those quantities in the first place! The things that Bayes _does_ make guarantees about -- which is something like the proper _calibration_ of one's beliefs -- are not hindered (and perhaps even helped) by peeking. So the Bayesian doesn't "solve" the error rate problem so much as declare it not to be a relevant problem in the first place.
Answer: I want to be careful in answering this question, in part, because I do not ordinarily do work that requires multiple trials.  There are a couple of perceptions in your post I felt should be addressed as well.
Your statement "A Frequentist tries to control, and thus minimize, the probability of adopting ineffective drugs. A Bayesian tries to maximize the probability that adopted drugs work," may not be the best phrasing.
Consider the simple case where the null hypothesis is $\theta\le{0}$ with an alternative of $\theta>0$.  There is nothing that prevents the Bayesian statistician from having two hypotheses where the first is $\theta\le{0}$, and the second is $\theta>0$.  They do not have the same meaning, however.
I was reminded of this one day when my wife came home from assisting in a childbirth.  The hospital she was at was one of two hospitals.  It delivered high-risk births, and so the weights of the babies were barbelled.  They either tended to be very low or very high.  The other hospital tended to have the center of the bell curve.
A baby that was over thirteen pounds was delivered that day, with the other babies being tiny.  I asked her the weights, and I realized through quick mental calculation, that I could not falsify the null hypothesis that the babies' mass was less than or equal to zero using a Frequentist method, but I had a roughly ninety-five percent chance that the parameter was greater than zero using a Bayesian method.  Ignoring the preposterousness and the lack of random selection, it illustrates the difference in meaning.  So you are correct, Frequentist and Bayesian hypothesis tests may not mean the same thing, but it may not be safe to assume that one is performing a minimization while the other is performing its dual optimization.
As to interim looks, there are two potential answers to the question.  I do want to note, though, that it is possible to perform "looks" with a Frequentist method if one simply chooses to be careful.  It is true that stopping problems were noted as a problem for Frequentist methods, but that just lead to a revision of Frequentist methods.
Meta-analysis, for example, allows the combining of multiple studies.  Control methods, such as those for family-wise errors, have been developed.  It is true, nonetheless, that such a tool is far easier to construct in the Bayesian sphere than the Frequentist.
There are two cases to consider.  The first case is related to the replication crisis in the sciences, the second to manufacturing.  The solutions would not naturally be the same.
One of the causes of the replication crisis is that only statistically significant studies tend to be published.  The implication is that published parameters tend to be biased away from no effect, though the set of all observed parameters may have no systematic bias at all.  In the case of "peeking," it will be true that the posterior will never forget a long random run that happened early in the process.  Furthermore, because Bayesian methods do not forget, the parameter estimate will be biased systematically, in the bad sense of bias, if and only if studies are stopped due to non-significance and chosen due to significance.  Remember that Bayesian methods are generally biased methods regardless.
I would point out that statistical significance is not a Bayesian concept.  However, there is an analog of something having a high posterior probability.  Still, as mentioned above in the baby example, it may not mean the same thing as the Frequentist inference.
Frequentist decisions minimize the risk of the worst outcome; Bayesian decisions minimize the average loss.  Risk is a function; loss is a scalar.  They are not always doing the same thing even when the calculations are the same.  As a consequence of that fact, plus the fact that the Bayesian model is looking at the probability of the model given the data, runs can be a bit more consequential for the Bayesian making a decision in the extreme cases.
Nonetheless, it is informative to know that parameters may be biased significantly away from zero because only those studies selected based on the posterior will be continued.  So let us consider study one with posterior $\pi(\mu|\sigma;X)$ where $\mu$ is the center of location, $\sigma$ is the scale parameter, and $X$ is the data.  Let us imagine that the posterior is normal with the posterior mean of twenty-five, and the variance is one.
The posterior would not be altered until we came to a decision node.  At a decision node, if the study were continued, then the posterior would be calculated, but it would not be used as a prior in the follow-on elements of the study because it may be upwardly biased.
While the posterior to the right of twenty-five should be untouched, the posterior to the left may contain more mass than is warranted by the posterior as you know you are ignoring some research paths.  One could place a flat mass over the region to the left of twenty-five where a Frequentist would just barely reject the observed value.  One could then continue the left side of the normal distribution at that point.
In effect, you forget information in the data, but you are substituting the information in your professional judgment for the information in the data before you start your next research leg.
You could also perform a large scale validation process to determine if you have a stable false positive rate.  In that case, you could use that data to influence the next prior.
The danger in this, the case of the run, is that you will bias your parameters downward by imposing a flat prior on the region to the left of the observed posterior mean (or right had the test results been on the other side of the axis).  That is a conservative choice that may cause you to reject valid treatments in the following way.
Imagine that in the first study, you saw a truly representative sample of data and the drug's effect was strong and very helpful to the participants.  Based on conservativeness, the posterior is flattened to be the prior of the next study, which, unfortunately, resulted in no effects due to an unfortunate choice of sample.  While the drug would have been approved had the prior not been tampered with, the drug is rejected due to the second peek having been bad.
That is the danger in altering decision rules in a Bayesian space based on peeking.  The assumption is that the second peek is good, and the first is bad.  It may be the other way around.
Note that, depending a bit on the assumptions, that the Frequentist meta-analysis may have accepted the treatment because it wouldn't flatten the prior to protect from bias as it is already using an unbiased estimator.
There is a conservatism in Frequentist decisions that are lost in Bayesian methods unless they are specifically built into the process.  In addition to the use of a flat prior in the region approaching zero, a minimax decision rule may be available even in Bayesian methodologies.  That would also rebuild the conservatism in a Bayesian space.
However, there is a second case that needs to be considered, one where posterior does not influence continuing the research.  In that case, the posterior should not be touched in any way because it is not biasing which research projects are continued forward.  Parallel assembly lines often have this property. Peeking doesn't alter the measurements because peeking doesn't cause the process to stop forever, though it may cause a temporary stop.  In the case of quality assurance, it is desirable to know the population parameters and peeking is valuable.  Indeed, if the posterior probability will not influence the stopping of a research project, then peeking does not cause harm, and no adjustments should be made.  The Bayesian posterior probability automatically adjusts itself for the multiple look problem.  There is no Bayesian analog to the Holm-Bonferroni test as it is unnecessary.
One last parting thought.  The idea of type 1 and type 2 error is not a Bayesian construction and can fall apart when the number of hypotheses is higher than two.  There is no null hypothesis.  Still, in the binary case, you could discuss rejecting useful versus useless treatments.  The difficulty is that Bayesian methods do not have long-run Frequentist properties.  There is no way to assure power and no way to guarantee a level of protection against false positives.  That is because Bayesian methods work in the parameter space.
While there is no concept of power in Bayesian experiments, one could ask what sample size would be required "to change my mind," to a certain level of certainty.  Likewise, there is no guarantee against false positives, but simulations can be constructed under a "null" on the performance of a Bayesian method over a simulated sample space.  It will not give you a guarantee, but it will give you a feel for performance issues under Frequentist ideals.


Jungle Disk vs DiskAgent

Question: I'm looking at implementing a secure off-site data backup of about 100 GB (and growing), more than likely on Amazon S3.  I haven't found many reviews of DiskAgent, has anybody had a good experience with it?  Seems to be significantly more expensive than Jungle Disk, so I'm curious to know why and if it's worth it.
Can either of these run syncing processes as a service?  Or are both GUI based?
Answer: Once you've set up the Jungle Disk server client, you can manage it remotely as far as scheduling, one-offs, etc, so you don't have to use a local GUI on the server.
I don't have any experience with DiskAgent, but JungleDisk has encryption, scheduling, etc, and you can back it up to Rackspace Cloud Files which is a bit cheaper than using S3 (no transfer charges).
Disclaimer: I work for Rackspace, which owns JungleDisk, but I don't have anything to do with that part of the company.  I use JungleDisk to backup all my Linux and Windows machines at home.
Comment: Thanks for the answer.  I've been trying out Jungle Disk today and there's a lot I like about it.  I still haven't decided which way to go though.  I don't like the dependency on the Jungle Disk service to restore files, but DiskAgent is not any different in that regard.
Answer: DiskAgent works very well and seems to be used by the professional community. There have been a number of positive reviews by numerous people in the healthcare and financial services space. We chose it because of the flexibility, excellent support, and high regard for security. We found them because they are a strategic partner/resource from Scottrade Advisor community. There are a lot of backup providers but not very many that work really well. Jungle Disk and DropBox seem fine too but their support is not very good. I also don't think that the other providers are willing to execute confidentiality agreements the people at DiskAgent gladly signed a confidentiality agreement with our group - a requirement for our relationships. One other thing I liked about DiskAgent is that you can backup content selectively to your own networked resource for no charge.
Comment: Thanks for the answer.  I haven't found much discussion of it other than the AWS case study, though that speaks well for it.  The biggest problem I have with DiskAgent is a hard requierment on the service to access the backups, since they don't use your own S3 buckets.  Jungle Disk will use your own S3 bucket, but it's in a native format, so you'll still need to login to Jungle Disk to download your backups, which doesn't offer much improvement over the DiskAgent approach, but it is nice to see something in your S3 buckets.

Jungle Disk vs DiskAgent


How to get a static IP for an EC instance? Or, how to use

Question: I am just setting our Rails app on Amazon AWS. We have 2 EC2 instances, one for the Rails app, the second one for Redis. And then Amazon RDS for MySQL.
When I connect our Rails app with Redis, I need to set the Redis URL, which contains IP address. However, if I restart the Redis instance, its IP address will change and the Redis URL IP I entered to the Rails app for Redis will not work (because after restarting the Redis instance was generated a new IP).
How to handle this behavior? How to avoid "loosing" EC2 instance when restarting it?
The same probably goes for Amazon RDS - this is how I set the host in database.yml:
  host: myapp-production.cg4mxcg62ca0.us-west-2.rds.amazonaws.com

Thank you in advance.
Comment: Their intent is for you to use an ELB infront of your server so the apps point to it (via DNS) not an IP address. For RDS you should be ok since you're using DNS and it will update dynamically, same is true for Redis, use the DNS name, not the IP.
Comment: Thank you for the answer, @TheFiddlerWins. Speaking about the Redis instance - I see in the EC2 dashboard "Private DNS", "Private IPs", "Public DNS" and "Public IP" - but all of these address contain an IP address (and all of these address will be re-created once the instance is restarted, right).
Comment: Are you using a VPC?
Comment: In my console if I go to ElasticCache Dashboard > Cache Clusters >  Nodes there is an "endpoint" listed that's a DNS name. These should be valid DNS entries
Comment: @TheFiddlerWins the OP is not using ElastiCache. He is using Redis on his own EC2 instance.
Answer: Issue 1:
Elastic IP addresses should not be used to preserve the address of a "back-end" server. There are 2 reasons:

Usually, you do not want back-end servers to be exposed to the internet and Elastic IP addresses only work from the internet into your EC2 instance.
If you connect from one EC2 instance to another EC2 instance by it's Elastic IP address, then the connection leaves your VPC and re-enters the VPC. This makes security harder and will incur data traffic charges.

Instead, you should reference your back-end server by it's private IP address. Stopping and restarting an EC2 instance will not change the private IP address. Only when an EC2 instance is terminated will the internal IP address be released. And when you launch an EC2 instance, you can optionally choose it's private IP address.
You can create a DNS entry (Route 53 private hosted zones) for your back-end server.
Another thing you can do, but it's not required, is to create a network interface with your private IP address. Then attach that network interface to the EC2 instance. If you need a new back-end server, then just move the network interface to the new instance and the private IP address will move with it.
Issue 2:
RDS instance endpoints do not change over time.
Also, RDS instances cannot be stopped. They can only be deleted. But, even if you delete an RDS instance and re-create it, if it has the same RDS instance ID, then it's endpoint will remain consistent.
So it's safe, and best-practice, to reference your RDS instance by it's hostname myapp-production.cg4mxcg62ca0.us-west-2.rds.amazonaws.com.
Final Thoughts:
Put your Redis server and your RDS instance in private subnets in your VPC. There is no reason why the public needs access to them. Your Rails app instance should be in a public subnet because the public will access your app through that instance.


Check the content after the "/" on a URL with jQuery

Question: Lets say my URL is:

http://example.com/12434/example-post

I want to check if the current URL contains something after the "/", in other words, I wan't to check whether or not I'm at the homepage http://example.com
Is this possible with jQuery?
Comment: @amnotiam: Excellent example, a lot easier than `location.pathname` or `window.location.pathname`, and everything is a lot faster in jQuery than in JavaScript. I am not sure why JavaScript is still being used when you have jQuery ;)
Comment: @Tadeck: Exactyl. All teh best codez are Jquery!!!!! :D
Comment: Not 'with jQuery' as such, but definitely with plain JavaScript (jQuery, so far as I know doesn't make it any easier or offer methods to achieve this).
Comment: You do not need jQuery for this, raw Javascript will do.
Comment: @Tadeck: You mean you don't do this? `$($(window).prop('location')).prop('pathname')` :D
Answer: Check location global object. It has pathname property:
alert( location.pathname );

Comment: But for homepage, location.pathname = "what?"
Comment: @Belohlavek: Can't you test it? Just use the code @@dfsq gave you in his answer.
Comment: If you on the page `http://example.com/` then location.pathname will be `"/"`. If say you are on the page `http://example.com/user/edit/2` then location.pathname `"/user/edit/2"`, etc. Just open console and check it on different pages.
Answer: window.location.href gives the url of page. Test the code
alert(window.location.href);

Does the URL contains anything afer abc.com/xyz i.e. xyz here can be tested with below code;
var url= window.location.href;
if(url.split("/").length>3){
  // It is not the home page. It is not xyz.com. It has something after /
}
else{
  // you are on the home page.
}


Two-way ANOVA robustness against normality violations

Question: I recently read the article "Is It Really Robust?" (Schmider, E., Ziegler M., Danay, E., Beyer, L. & Bühner M., 2010)
The authors of the article come to the conclusion that an ANOVA is quite robust against violations of the normality assumption.
However the study focusses on one-way ANOVAs. I would like to know if these findings can be generalized on a two-way repeated measures ANOVA?
References to peer-reviewed articles are highly appreciated!

References
Schmider, E., Ziegler M., Danay, E., Beyer, L. & Bühner M. (2010). Is It Really Robust?.Methodology, 6 (4), 147 - 151.
Answer: Unfortunately, the methodology used by the Schmidler et al paper is seriously flawed*, so their results are questionable even for the one-way, fixed-effect design they studied.
*Specifically, to simulate Type I or Type II error using a Monte Carlo simulation, one needs to use all samples that were generated by the Monte Carlo process. Just using the 10% selected by some nonrandom selection method does not give a simulation of the sampling distribution for the test statistic; however, it is this sampling distribution that needs to be simulated.
Comment: The 10% of samples they've picked are the ones that most resemble the population distribution, meaning that the samples were definitely non-normal (in the non-normal conditions, of course)--which is what they're trying to get to (and which is why they've done this). I see your point, but I think saying their methodology is "seriously flawed" might be something of an overstatement.
Comment: @Patrick I guess "seriously flawed" is a judgment call which may vary from individual to individual. Possibly my brief explanation was too brief, so here's a little more: In the process of their selection of the 10% of samples, they used 24 X 50,000 hypothesis tests. That presents a huge multiple testing problem that they did not even mention. I see that in itself as casting serious doubt on the credibility of the results.


Disabled Input Field on Responsive Mode in Chrome

Question: I have a form with Seven fields designed with Yii2. They validation and the input works well on all browsers but the moment i switch to responsive mode using the Developer Tools, Four of those fields stops working (it becomes disabled). It happens majorly on Google Chrome and Internet Explorer. I have tried all i can to resolve this but not hitting a head way. Please guide me on how to resolve this.
An image showing the list of fields is attached
Answer: After i tried all possible ways, i first commented out the whole css that was attached and immediately it started working. So i started adding the css one after the other and boom!!! the judas showed up and that was how i discovered that it was just a line of that css that was the cause.
Found float:left as one of the properties of the input['type=text']. I removed it and works fine now.


How to get the contents of a Third Party lazy loading page?

Question: Via a Chrome extension, I'm trying to get and modify the contents of a third-party page. Everything works for the part of the content that's immediately visible on initial page load.
The problem is that this page has a lazy-load/ajax pagination. To get all of the content I have to click "view all" (ajax link) (and I believe this works essentially the same way as lazy-loading that's why I put that keyword in the title).
Upon clicking that link (on that third-party website) all content gets loaded and becomes visible to the user but when I view source there's still only the originally loaded content present in the source code. i.e. none of the freshly loaded content can be found anywhere when I view page source after the new content has been loaded. The content is visible to the end user but not visible to me when I check the source code.
Initially, I tried to overcome the problem by using setInteval and checking the page content every second but as that wasn't working I checked the source code and sure enough, none of the newly loaded content is visible in the source code. No wonder my Chrome extension can't get that content.
Another confusing thing I just realized when typing here:
When I view source code, even the initial HTML content that my Chrome extension is detecting/loading is NOT actually present in the source code! It actually sits in a JavaScript array. So, somehow, my Chrome extension is correctly getting the initial HTML content that's constructed from that JS array. But it's NOT getting the content that gets loaded after clicking the "view all" ajax link on that page (even though I'm using setInteval and checking for new content every second).
What are possible solutions for this?
I can't post the link to the page because it's the "my certificates" page on Lynda.com and I don't know of a publicly accessible website/page with the same behavior.
Answer: you should find the actual service running in network-panel, when lazy loading happens, and then follow following code
<code>   //recursively make calls and gatther responses. cb is callback to run on response, end is end page-no (end of recursion condition) , pageId is the attribute changing in every subsequent lazy-loading call.
var callIfRequiredConfigured = ({cb,end,step=1,pageURL,pageId})=>callIfRequired = ()=>{
    currentCounter = currentCounter + step;
    if (currentCounter > end) {
        return;
    }
    (async(currentCounter)=>{

        queueCounter++;
        //modify this as needed
        const r = await fetch(pageURL+currentCounter,{credentials:"same-origin"});
          //queueCounter to not make more than 6 calls at once
        if (queueCounter > 6) {
            return;
        }
        var response = await r.text();
        cb(response);
        queueCounter--;
        callIfRequired();
    }
    )(currentCounter);

};

var call = (config)=>{
    const callIfRequired = callIfRequiredConfigured(config);
    callIfRequired();
}

call({
    cb: (response)=>{
        //do somrthing with response
    }
    ,
    end: 50,
    step: 1,
    pageId: 'PageNumber=',
    pageURL: `https://www.lynda.com/home/CertificateOfCompletion/GetCertificatesByFilter?Start=0&Limit=99999&SortBy=CompletionDate&SortByOrder=1&_=[my_personal_id]&PageNumber=`
});
</code>
So main effort will be to deduce the service endpoint here and how it changes in subsequest requests. I have updated the url given in comments, but see if the fetch call is successful. Also this url should also have <code>[my_personal_id]</code> as given in url.
Comment: I checked the network panel and see that when I click the "view all" ajax link the following URL gets called:
https://www.lynda.com/home/CertificateOfCompletion/GetCertificatesByFilter?PageNumber=1&Start=0&Limit=99999&SortBy=CompletionDate&SortByOrder=1&_=[my_personal_id]  Can you give me any pointers as to what could I do with that?
Comment: @WebDevBooster try now. I have made changes with this url. when you run above code, do check that fetch call is successful in network-panel, else make changes to make it successful.


Windows Server 2019 Windows Backup Issue with Hyper-V

Question: I am running Windows Server 2019 and have configured Windows Server Backup.
The backup is to a dedicated backup disk and consists of the following options:

Bare Metal Recovery
C:
System Reserved
System state
Hyper-V (several VMs selected)

The Hyper-V backups routinely fail with the following error:
Error in backup of C:\VHDs\Alderaan\Virtual Machines\A118C476-9DB8-499E-AE63-85B2F8DE0563.VMRS during enumerate: Error [0x80070020] The process cannot access the file because it is being used by another process.

Application backup
Writer Id: {66841CD4-6DED-4F4B-8F17-FD23F8DDC3DE}
   Component: A118C476-9DB8-499E-AE63-85B2F8DE0563
   Caption     : Online\alderaan
   Logical Path:
   Error           : 8078010D
   Error Message   : Enumeration of the files failed.

   Detailed Error  : 80070020
   Detailed Error Message : (null)

The error example above is for one VM, but all of them fail with the same error. At the time of backup, all the VMs are running.
The other Windows backup options complete without issue (as seen below).
Backup of volume C: succeeded.

Backup of volume \\?\Volume{08035f94-0000-0000-0000-100000000000}\ succeeded.

Application backup
Writer Id: {66841CD4-6DED-4F4B-8F17-FD23F8DDC3DE}
   Component: Host Component
   Caption     : Host Component
   Logical Path:

I have tried to do just a one-time backup of only the Hyper-V component VMs and have received the same error as identified above.
Comment: Have you considered using Veeam Agent and B&R to backup physical host and Hyper-v VM? They are industry-standard tools for the job.
Comment: @A.Newgate I just checked out the Veeam Community Edition and it works great. I was concerned about cost for my lab setup, but at the price of Community (free) you really can't beat it. Does everything I need it to do.
Comment: I'm glad I could help
Answer: Can it be that it does copy the drives twice? The VM folders should not be backed up as part of C: (i.e. file backup) but ONLY as part of the VM backups. If you backup C as DRIVE - well, the path where it faily is there.
Comment: Not arguing here - even IF it works.... it does do one thing, that is put in some basic functionality for others to use, but generally it is not exactly a stellar piece of advanced software. It should do a basic job, though.
Comment: @djdomi I actually gave up trying to make this work and tried out the Community Edition of Veeam. It's a great piece of software and works without a hitch. It is a crime in my opinion that Windows Backup in its current state ships with the OS .
Comment: Tom i agree to you but sometimes third parties do or give a better choice...
Comment: I have tried just backing up the Hyper-V component VMs and I get the same error.
Comment: just a suggestion but ehy not using veeam?
Comment: For a small isolated setup - there should not be a NEED to have another software. In fact, unless confirmed as a bug, I would say the error indicates something wrong with the setup, and I at least would be VERY reluctant to avoid the symptoms without treating the problem.
Comment: @djdomi this is a lab setup; trying to stick with out of the box tools.
Comment: Well, then you did not heared in the past about the windows server backup bug? i dont trust in that anymore. Moreover, Veeam is free to use
Comment: Nope actually not heard of it in 2019.


Should I be using node_load() rather than building my own queries with db_select()?

Question: I'm fairly comfortable with using Drupal 7 functions like db_select(). While node_load() is obviously very easy to use, I often find that it returns fields I don't need and doesn't provide fields that I do need (field that would require some joins to obtain).
Therefore, will building my own queries provide better performance than using node_load() in conjunction with other queries? Or is there some kind of performance boost that results from using node_load(), perhaps from cacheing, etc.?
I'm far from an expert on MySQL performance issues, but it seems to me that constructing a single, specific query is better than using multiple queries that individually only retrieve part of what I ultimately need (and a lot of what I don't).
Answer: Technically, yes, writing your own db_query() statements will return the data faster and with less overhead. However, it is not really the "Drupal way" to do things.
node_load() provides a 'static' cache; in other words, if you load the same node twice in one page request, it will only hit the DB once.
What you are really missing out on by not using node_load() is all the API hooks and third-party module integration. If you need a CCK field, node_load() gets all that data for you, where as a manual query would require a lot of joins.
As you note, there is a lot of extra processing/loading going on that you may not need at the given moment. If you don't need the data, it won't technically hurt you not to have it. It is really up to you if you want to go this route.
The biggest reason IMO for using node_load() even though you might not need the extra data is just for the purpose of standardization. You won't have to worry about what pieces of data you have at a certain point. You will have a fully loaded node and will have more options for adjusting the data as necessary through hook_nodeapi(). Other developers looking at your code will have an easier time understanding what they are working with. Also, 6 months down the road when you go to add a new feature/display field you wont have to adjust your queries.
node_load is definitely a resource hog, but i have found it better to use in my experience.  Drupal 7 greatly improves the situation by providing node_load_multiple() which, as its name implies, reduces the number of queries when loading multiple nodes.
Comment: The main reasons for using `node_load()` are compatibility with future versions of Drupal, and integration with other modules, which can alter the result returned from the function. As for the first point, that is evident with Drupal 7: The query to get a complete node object is quite different, compared with the one used on Drupal 6; it also changes the database tables involved in the query.
Comment: I'll also add that in the case of spitting out 1000s of nodes, if you don't *need* other modules' hooks to help build your node object, a single, gigantic sql statement is definitely much faster. 1 trip to fast-joining, fast-querying db is fast, as opposed to an efq to turn around and iteratively load nodes, php to ask other modules for hooks, each nid with its built-in trip to the db (for cache or build), and php to process each on the way out.  Youch.
Answer: As explained in jakarska's answer, node_load(), node_load_mutliple() do more than just DB querying. They take care of calling all the node building hooks implemented by the enabled modules of your site.
In addition, in Drupal 7, with the introduction of pluggable field storages, when working on re-usable code, you can't known whether or not your field data will be available in your (main) database. As a general rule, I would use node_load(), node_load_mutliple() and EntityFieldQuery to query for nodes. If you only need a specific field for multiple node you can also use field_attach_load() with an $options['field_id'] on the results of an EntityFieldQuery.
So, I wouldn't go for a custom SQL query unless the code is sure to be used in cases where everything that node_load(), node_load_mutliple() and EntityFieldQuery provide are not, and will never be, needed and on data that are, and will always, be stored in the SQL database.
Answer: node_load() is the "Drupal way"; it means that, by calling this function, the API sends message to modules when node loading has started, so these can add/change/remove their own information. Yes, even node_load() uses caching, as it uses a lot of queries.
You can use db_select() for selecting concrete data, but be sure that you collect/change/delete correct data.
Answer: You can carefully build a view to filter and relate what you want and then use views_get_view_result() function to get the result.
And by carefully I mean that you only use the fields you need. For example, including a field of node title with a link to it's node will make your query considerably longer in views instead of only using node id without a link.
Views is a powerful query builder and using it programmatically could be a good answer to your problem. You can get the best of both worlds: easy queries that are friendly with Drupal and faster results compared to loading all data from a particular entity.
You must configure your views module to see the generated queries when building it. Also you could find useful to name or tag your views as "system" or something like that, to avoid undesirable overrides.


Are there any special key symbols/words that cannot be used in the Oracle Queue (or just save as a char value in the Oracle)?

Question: I'm a newbie to use Oracle Queue, I wanna know whether there are some symbols/words that cannot be directly used in the Oracle Queue(or just save as a char value in the Oracle)?
If I insist using them, how to convert them as valid ones?
I was told that English dot (.) cannot be used?
Answer: Sure, you can use double quotes to quote oracle keywords.
For example you can create a table like this:
<code>CREATE TABLE timeframe (
    "DATE" DATE,
    "FROM" DATE,
    "TO"   DATE
);
</code>
Be aware that quoted names are case sensitive!
Comment: Are there any special symbols like English dot?


How to change font family of entire shiny app?

Question: I am trying to change the font family of my entire shiny app. I found this solution
* { font-family: Arial, sans-serif !important; }
from this url
This is changing every font but also removing my icons.
dashboardSidebar(sidebarMenu(
                        menuItem("Data", tabName = "dataimport", icon = icon("folder-open"))))

This is how it looks now. It's not working without !important as mentioned in the solution above.
What can I do to fix this?
Answer: Can you share the HTML code of the icon? It probably is a span or i tag.
Instead of adding the font-family to every single html element with *, you can add it to the body tag (see the approved answer in your link). Please don't use !important when adding the font-family when it isn't absolutely needed (information about !important in css: What are the implications of using "!important" in CSS?).
If the icon still gets overwritten by you font, you can select the span or i tag in the css and set the font-family to the default font-family with icons.
CSS:
body {
  font-family: Arial;
}

Comment:  Html code for icon. I have tried    body{
  font-family: Arial;
} and   *{
  font-family: Arial;}.    I have some shiny dashboard boxes and I was hoping to change all their titles too with this.
Comment: So what happened when you changed the css, what font-family is the title?

Can you please create a code snippet with the html code and css? Because then I could check what code overwrites the title in devtools, and find the selector specificity, so you don't have to use !important.
See this for selector specificity in CSS: [link css specificity explained](https://www.freecodecamp.org/news/what-is-css-specificity/)


Se B é um subtipo de A, por que uma coleção de B não é um subtipo de uma coleção de A?

Question: Dados:
public interface A { ... }

public interface B extends A { ... }

private Set bs = new HashSet<>();

RecebeA qualquerCoisa = new RecebeA(bs);

Por que a última linha compila se o construtor RecebeA for declarado como:
public RecebeA(Collection<? extends A> as) { ... }

e não compila se for declarado como
public RecebeA(Collection as) { ... }

?
Se quiser fazer do segundo jeito serei obrigado a fazer a gambiarra new RecebeA(new HashSet<>(bs)); ?
Tem solução melhor?
Comment: Editei o título, mas não sei se é exatamente a "essência" do que vc quis saber...
Comment: O título está bom, também é uma dúvida, apesar que a dúvida essencial era por que Collection funciona e Collection não. Mas essa dúvida eu tirei nos comentários da resposta, obrigado.
Answer: Isso acontece porque herança em coleções não funciona da mesma maneira que funciona com classes. No próprio tutorial da Oracle é mencionado que:

In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.

Ou seja, se B é um subtipo de A (sejam eles classes ou interfaces), não é verdade que um Set é um subtipo de Set. E isso não vale apenas para Set, mas para qualquer tipo genérico. É contra-intuitivo porque imaginamos que o "lógico" seria que uma coleção de B deveria ser um subtipo de uma coleção de A, se B for um subtipo de A. Mas não é.
O próprio tutorial já citado dá um exemplo parecido com o seu:
List<String> ls = new ArrayList<String>();
List<Object> lo = ls; // erro, não compila

Afinal, se String é um Object, então por que uma lista de String não é uma lista de Object? Porque se o código acima compilasse, então seria possível fazer isso:
lo.add(new Object()); // adicionando um Object que não é uma String
String s = ls.get(0); // ops, não vai retornar uma String

Provavelmente para evitar este tipo de situação, decidiram que o melhor é nem deixar atribuir uma lista de String em uma lista de Object.

No seu caso, o mesmo poderia acontecer. Suponha que eu tenho outra sub-interface de A:
public interface C extends A { ... }

public class ImplementoC implements C { ... }

public class RecebeA {
    public RecebeA(Collection as) {
        as.add(new ImplementoC()); // isso compila
    }
}

...
Set bs = new HashSet<>();
RecebeA qualquerCoisa = new RecebeA(bs); // isso não compila, mas vamos supor que compilasse
B b = bs.iterator().next(); // aqui seria retornado uma instância de ImplementoC (que é um C, não um B)

Ou seja, se fosse possível passar um Set para o construtor que só recebe Collection, dentro dele eu poderia adicionar qualquer implementação de A (mesmo que não tenha relação de subtipo com B), e ao tentar obter os valores do Set eles não seriam instâncias de B. No caso acima, seria possível adicionar instâncias de C em um Set, mesmo que B e C não sejam subtipo um do outro.

Curiosamente, isso aqui também não funciona:
public RecebeA(Collection<? extends A> as) {
    as.add(new ImplementoC()); // agora essa linha não compila
}

Set bs = new HashSet<>();
RecebeA qualquerCoisa = new RecebeA(bs); // mas essa compila

Pois é, mesmo que o parâmetro seja declarado como Collection<? extends A>, eu não posso adicionar um C nela. Isso porque o valor recebido pode ser uma coleção de qualquer subclasse/sub-interface de A (como por exemplo B, que não tem relação de subtipo com C, ou seja, se a linha acima compilasse seria possível adicionar um C em um Set).

Pegando emprestado o exemplo do Jon Skeet, para ficar um pouco mais claro:
List<Dog> dogs = new ArrayList<Dog>();
// uma lista de cachorros é uma lista de animais, certo? (não, a linha abaixo não compila)
List<Animal> animals = dogs;
// se a linha acima compilasse, seria possível fazer isso:
animals.add(new Cat()); // adicionando um gato na lista de cachorros
Dog dog = dogs.get(0); // ops, não é um cachorro

No caso, Animal seria a interface A, Dog seria a interface B e Cat seria C.
E se eu tiver uma classe que recebe uma lista de animais:
public class RecebeAnimal {
    public RecebeAnimal(Collection<Animal> c) {
        c.add(new Cat());
    }
}

...
List<Dog> dogs = new ArrayList<>();
RecebeAnimal r = new RecebeAnimal(dogs); // não compila

Se a linha acima compilasse, eu conseguiria adicionar um gato na lista de cachorros.
Agora se eu trocar o construtor:
public RecebeAnimal(Collection<? extends Animal> c) {
    c.add(new Cat()); // não compila
}

...
List<Dog> dogs = new ArrayList<>();
RecebeAnimal r = new RecebeAnimal(dogs); // compila

A última linha compila porque agora a Collection pode ser de qualquer subclasse de Animal. Mas a linha com c.add(new Cat()) não compila, porque se compilasse ainda seria possível adicionar um gato na lista de cachorros.
A única coisa que dá pra fazer no construtor é acessar os elementos da coleção como animais: for (Animal a : c) { etc } (assim como no seu exemplo você poderia fazer um for na Collection<? extends A>). Claro que aí você pode usar instanceof e cast para obter tipos específicos, mas aí já depende do que você precisa fazer.

E como resolve? Depende. O que exatamente RecebeA deve receber? Uma coleção de A, de qualquer subtipo de A, de somente B?
Na verdade, acho que só tendo o caso concreto para saber a melhor solução. Com nomes genéricos assim, só dá para especular, mas de qualquer forma, sabendo as limitações e o funcionamento dos wildcards, você pode avaliar os requisitos e ver o que é melhor para o seu caso.
Comment: O caso concreto é assim: a classe `Server` instancia `SocketHandler`s. A interface `ServerListener` estende `SocketHandlerListener`. Quero passar no construtor de `SocketHandler` uma coleção de `ServerListener`s. Será que violei o princípio de substituição de Liskov?
Comment: @Piovezan Não entendi nada, que classes são essas? :-)  Quem são o `A`, `B` e `RecebeA` nessa história?
Comment: "Interface A extends B" = "Interface ServerListener extends SocketHandlerListener". "RecebeA" = "SocketHandler". Um Server possui uma lista de ServerListeners e instancia SocketHandlers, que por sua vez possui SocketHandlerListeners. Quero passar ServerListeners para o SocketHandler como se fossem SocketHandlerListeners.
Comment: A orientação a objetos disso aí deve estar toda errada :D
Comment: `ServerListener` observa o Server, portanto tem métodos onStarted(), onPortBusy(int port), onStopped(), onNewHandler(SocketHandler handler). Já `SocketHandlerListener` observa o SocketHandler, portanto tem métodos onAuthenticated(Collection tokens), onDisconnect(Collection tokens, String causa). Eu assumi que quem está interessado nos eventos de Server também está interessado nos eventos de SocketHandler.
Comment: @Piovezan Bom, acho que ou você muda o `SocketHandler` para ter uma lista `List` (e receber isso no construtor, aí vc consegue passar um `List` para ele), ou vc faz a gambiarra mesmo: `new SocketHandler(new ArrayList(listeners))` - supondo que `listeners` é a lista do `Server` (um `List`).
Comment: ...que são as duas opções que eu propus na pergunta. Não tem jeito melhor de fazer não então, né? Só remodelando, imagino.
Comment: @Piovezan Da forma que está, acho que essas são as opções. Mas se puder rever o modelo, acho que é uma boa. Será que `ServerListener` deveria mesmo ser um subtipo de `SocketHandlerListener`?
Comment: É, essa herança de tipo não está cheirando muito bem. Beleza, resposta aceita. :)
Comment: Só me tire uma última dúvida, se já não estiver na resposta (aí me fale que eu releio), por que `Collection` dá certo e `Collection` não?
Comment: @Piovezan Porque `Collection` indica que vai receber uma coleção somente de `Tipo`, e `Collection` indica que a coleção pode ser de qualquer subtipo de `Tipo`. Veja a seção "Bounded Wildcards": https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html - como eu disse, herança em coleções funciona meio diferente e muitas vezes é contraintuitivo, mas acho que fizeram assim por causa das consequências mencionadas na resposta (evitar ser possível adicionar um gato na lista de cachorros, etc)