Q: Ist possible to convert my own HTML to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks? I have already searched for many questions at Stackoverflow, but I really didn't consider the questions and the answers for my needs. DocRaptor is really not a good app because it breaks the pages and it doesn't recognise the extended Latin letters, as à, é, ã,, etc.
I used many HTML to PDF converter web-based apps, it didn't work for me, because they didn't preserve the formatting and the hyperlinks.
I used capture apps for Mac, as W3Capture and Layouts.1) Layouts capture one whole HTML and CSS page as a PDF without breaking the pages and also preserving the formatting. But, it didn't support the hyperlinks, because it captures the page as PDF, behaving as PNG-like.
2) W3captures supports the hyperlinks, converting the HTML/CSS pages, but it breaks the pages and really doesn't preserve the formatting.
I also tested TextEdit, which can exports as PDF, but when it exports as PDF, it breaks the pages. Pages from iWork and Word also do it.
I'm really frustrated.
Is it possible to convert the own HTML page to PDF, without breaking the pages, preserving the formatting and supporting the hyperlinks?

A: I think you can open you html file in Chrome. Then print it to pdf format. Then it will works.
That is when you print it, you choose "save as pdf" rather than your printer.


Q: is there a way to allow a phone "-" in phone format using numeric in vuelidate? I'm using vuelidate to validate a form in VUE build. I have a phone number input that needs to be formatted as 222-222-2222 which I have setup using a phone mask. My issue is now the input will not validate when the phone is filled in. My error message is still displayed. Is there a way to allow for numbers only along with a dash "-"???

          Phone Number

        <input type="text" class="form-input text-input" name="phone" id="phone" @input="phoneNumberMask()"
               v-model.trim="$v.formData.phone.$model">

          Please enter a valid phone number.

    validations: {
      formData: {
        phone: {
          required,
          numeric,
          minLength: minLength(12),
          maxLength: maxLength(12)
         }
        }
       }

methods: {
  phoneNumberMask(){
        const x = this.formData.phone.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
        this.formData.phone = !x[2] ? x[1] : x[1] + '-' + x[2] + (x[3] ? '-' + x[3] : '');
    },
   }

A: As pointed out in the comments, you can create a regular expression that validates you phone number format, in this case /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/ could be a starting point.
Here a complete example.
<template>

      <input
        class=""
        v-model="number"
        @change="$v.number.$touch()"
        placeholder="Phone number"
      />

NOT VALID

    <button
      class="
        "
      :disabled="$v.$invalid"
      @click="saveClick()"
    >
      Save
    </button>

</template>

Script part
import { required, helpers } from "vuelidate/lib/validators"

const number = helpers.regex(
  "serial",
  /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/
)

export default {
  data() {
    return {
      number: null
    }
  },

  computed: {
    serial: {
      get() {
        return this.number
      },
      set(value) {
        this.number = value
      }
    }
  },
  methods: {
    saveClick() {
      //TODO
    }
  },
  validations: {
    number: {
      required,
      number
    }
  }
}

Note
This is for Vue 2.x and vuelidate ^0.7.6


Q: How to implement a Master Detail Form as part of a MultiPageEditor in Eclipse? I have created a sample multi page editor via the Eclipse wizard. Now, I want to extend this editor with a Master Detail Form, so basically, there should be two pages, one standard text editor and the beforesaid Master Detail Form.
Please note: I am using this a demo code for my MasterDetailsPage.java.
Here is my code so far:
MultiPageEditor:
package multipageeditortest.editors;

import java.io.StringWriter;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FontDialog;
import org.eclipse.ui.*;
import org.eclipse.ui.editors.text.TextEditor;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.part.MultiPageEditorPart;
import org.eclipse.ui.ide.IDE;

/**
 * An example showing how to create a multi-page editor.
 * This example has 3 pages:
 *

 *
page 0 contains a nested text editor.
 *
page 1 allows you to change the font used in page 2
 *
page 2 shows the words in page 0 in sorted order
 *

 */
public class MultiPageEditor extends MultiPageEditorPart implements IResourceChangeListener{

    /** The text editor used in page 0. */
    private TextEditor editor;

    /** The font chosen in page 1. */
    private Font font;

    /** The text widget used in page 2. */
    private StyledText text;
    /**
     * Creates a multi-page editor example.
     */
    public MultiPageEditor() {
        super();
        ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
    }
    /**
     * Creates page 0 of the multi-page editor,
     * which contains a text editor.
     */
    void createPage0() {
        try {
            editor = new TextEditor();
            int index = addPage(editor, getEditorInput());
            setPageText(index, editor.getTitle());
        } catch (PartInitException e) {
            ErrorDialog.openError(
                getSite().getShell(),
                "Error creating nested text editor",
                null,
                e.getStatus());
        }
    }
    /**
     * Creates page 1 of the multi-page editor,
     * which allows you to change the font used in page 2.
     */
    void createPage1() {

        Composite composite = new Composite(getContainer(), SWT.NONE);
        GridLayout layout = new GridLayout();
        composite.setLayout(layout);
        layout.numColumns = 2;

        Button fontButton = new Button(composite, SWT.NONE);
        GridData gd = new GridData(GridData.BEGINNING);
        gd.horizontalSpan = 2;
        fontButton.setLayoutData(gd);
        fontButton.setText("Change Font...");

        fontButton.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent event) {
                setFont();
            }
        });

        int index = addPage(composite);
        setPageText(index, "Properties");
    }
    /**
     * Creates page 2 of the multi-page editor,
     * which shows the sorted text.
     */
    void createPage2() {
        Composite composite = new Composite(getContainer(), SWT.NONE);
        FillLayout layout = new FillLayout();
        composite.setLayout(layout);
        text = new StyledText(composite, SWT.H_SCROLL | SWT.V_SCROLL);
        text.setEditable(false);

        int index = addPage(composite);
        setPageText(index, "Preview");
    }

    void createMasterDetailPage() {
        int index = addPage(new MasterDetailsPage(this)); // ERROR
        setPageText(index, "Master Detail Page");
    }

    /**
     * Creates the pages of the multi-page editor.
     */
    protected void createPages() {
        createPage0();
        createPage1();
        createPage2();
        createMasterDetailPage();
    }
    /**
     * The MultiPageEditorPart implementation of this
     * IWorkbenchPart method disposes all nested editors.
     * Subclasses may extend.
     */
    public void dispose() {
        ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
        super.dispose();
    }
    /**
     * Saves the multi-page editor's document.
     */
    public void doSave(IProgressMonitor monitor) {
        getEditor(0).doSave(monitor);
    }
    /**
     * Saves the multi-page editor's document as another file.
     * Also updates the text for page 0's tab, and updates this multi-page editor's input
     * to correspond to the nested editor's.
     */
    public void doSaveAs() {
        IEditorPart editor = getEditor(0);
        editor.doSaveAs();
        setPageText(0, editor.getTitle());
        setInput(editor.getEditorInput());
    }
    /* (non-Javadoc)
     * Method declared on IEditorPart
     */
    public void gotoMarker(IMarker marker) {
        setActivePage(0);
        IDE.gotoMarker(getEditor(0), marker);
    }
    /**
     * The MultiPageEditorExample implementation of this method
     * checks that the input is an instance of IFileEditorInput.
     */
    public void init(IEditorSite site, IEditorInput editorInput)
        throws PartInitException {
        if (!(editorInput instanceof IFileEditorInput))
            throw new PartInitException("Invalid Input: Must be IFileEditorInput");
        super.init(site, editorInput);
    }
    /* (non-Javadoc)
     * Method declared on IEditorPart.
     */
    public boolean isSaveAsAllowed() {
        return true;
    }
    /**
     * Calculates the contents of page 2 when the it is activated.
     */
    protected void pageChange(int newPageIndex) {
        super.pageChange(newPageIndex);
        if (newPageIndex == 2) {
            sortWords();
        }
    }
    /**
     * Closes all project files on project close.
     */
    public void resourceChanged(final IResourceChangeEvent event){
        if(event.getType() == IResourceChangeEvent.PRE_CLOSE){
            Display.getDefault().asyncExec(new Runnable(){
                public void run(){
                    IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
                    for (int i = 0; i<pages.length; i++){
                        if(((FileEditorInput)editor.getEditorInput()).getFile().getProject().equals(event.getResource())){
                            IEditorPart editorPart = pages[i].findEditor(editor.getEditorInput());
                            pages[i].closeEditor(editorPart,true);
                        }
                    }
                }
            });
        }
    }
    /**
     * Sets the font related data to be applied to the text in page 2.
     */
    void setFont() {
        FontDialog fontDialog = new FontDialog(getSite().getShell());
        fontDialog.setFontList(text.getFont().getFontData());
        FontData fontData = fontDialog.open();
        if (fontData != null) {
            if (font != null)
                font.dispose();
            font = new Font(text.getDisplay(), fontData);
            text.setFont(font);
        }
    }
    /**
     * Sorts the words in page 0, and shows them in page 2.
     */
    void sortWords() {

        String editorText =
            editor.getDocumentProvider().getDocument(editor.getEditorInput()).get();

        StringTokenizer tokenizer =
            new StringTokenizer(editorText, " \t\n\r\f!@#\u0024%^&*()-_=+`~[]{};:'\",.<>/?|\\");
        ArrayList editorWords = new ArrayList();
        while (tokenizer.hasMoreTokens()) {
            editorWords.add(tokenizer.nextToken());
        }

        Collections.sort(editorWords, Collator.getInstance());
        StringWriter displayText = new StringWriter();
        for (int i = 0; i < editorWords.size(); i++) {
            displayText.write(((String) editorWords.get(i)));
            displayText.write(System.getProperty("line.separator"));
        }
        text.setText(displayText.toString());
    }
}

MasterDetailsPage:
public class MasterDetailsPage extends FormPage {
    private ScrolledPropertiesBlock block;
    public MasterDetailsPage(FormEditor editor) {
        super(editor, "fourth", "test"); //$NON-NLS-1$ //$NON-NLS-2$
        block = new ScrolledPropertiesBlock(this);
    }
    protected void createFormContent(final IManagedForm managedForm) {
        final ScrolledForm form = managedForm.getForm();
        //FormToolkit toolkit = managedForm.getToolkit();
        form.setText("Test"); //$NON-NLS-1$
        block.createContent(managedForm);
    }
}

The problem is in this method:
void createMasterDetailPage() {
    int index = addPage(new MasterDetailsPage(this)); // ERROR
    setPageText(index, "Master Detail Page");
}

How can I add the MasterDetailsPage to my MultiPageEditor?

A: You normally use FormEditor rather than MultiPageEditorPart when using FormPage (FormEditor extends MultiPageEditorPart).
FormEditor has an addPage that accepts a FormPage.


Q: Upload,read and display the image with Tkinter and Opencv-Python I want to upload this file using tkinter method and read it using cv2.imread and display .But i have a problem,this is the code i am using:
wid=Tk()
def myown():
file = tkFileDialog.askopenfile(parent=wid,mode='rb',title='Choose a file')
if file != None:
   data = file.read()
   b=cv2.imread(data)
   cv2.imshow('img',b)
   cv2.waitKey(0)

   file.close()

after this,
  wid3=Button(None,text="upload it",command=myown)
  wid.mainloop

but i am getting an opencv error,the image is not being displayed by the imshow,it says size.width>0 && size.height>0


Q: Not getting the right result in base64 string when I try to convert base64 encoded string EC Public Key generated on iOS to Java PublicKey As the title suggests I am trying to convert base64 encoded string (EC Public Key) generated on IOS device(Swift) to Java PublicKey which will be used to calculate a Shared Secret Key between two parties. There is neither runtime nor compile time exception/error in the code, it compiles and runs successfully and generates a PublicKey but when I encode the PublicKey (Base64.encodeToString(PublicKey.encoded), Base64.NO_WRAP) back to Base64 string to confirm whether I have gotten the same public key I have passed as an argument, they are not the same.
import android.util.Base64
import org.bouncycastle.asn1.sec.SECNamedCurves
import org.bouncycastle.math.ec.ECCurve
import java.math.BigInteger
import java.nio.charset.StandardCharsets
import java.security.*
import java.security.spec.*
import javax.crypto.*
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

fun iosB64EncodedStrPKToPK(iOSB64EncodedPK: String): PublicKey {
    val decodedPK = Base64.decode(iOSB64EncodedPK, Base64.NO_WRAP)
    val x9ECParamSpec = SECNamedCurves.getByName("secp256r1")
    val curve = x9ECParamSpec.curve
    val point = curve.decodePoint(decodedPK)
    val xBcEC = point.affineXCoord.toBigInteger()
    val yBcEC = point.affineYCoord.toBigInteger()
    val gBcEC = x9ECParamSpec.g
    val xGBcEC = gBcEC.affineXCoord.toBigInteger()
    val yGBcEC = gBcEC.affineYCoord.toBigInteger()
    val hBcEC = x9ECParamSpec.h.toInt()
    val nBcEC = x9ECParamSpec.n
    val jPEC = ECPoint(xBcEC, yBcEC)
    val gJpEC = ECPoint(xGBcEC, yGBcEC)
    val jEllipticCurve = convertECCurveToEllipticCurve(curve, gJpEC, nBcEC, hBcEC)
    val eCParameterSpec = ECParameterSpec(jEllipticCurve, gJpEC, nBcEC, hBcEC)
    val ecPubLicKeySpec = ECPublicKeySpec(jPEC, eCParameterSpec)
    val keyFactorySpec = KeyFactory.getInstance("EC")
    return keyFactorySpec.generatePublic(ecPubLicKeySpec)
}

private fun convertECCurveToEllipticCurve(
    curve: ECCurve,
    ecPoint: ECPoint,
    n: BigInteger,
    h: Int
): EllipticCurve {
    val ecField = ECFieldFp(curve.field.characteristic)
    val firstCoefficient = curve.a.toBigInteger()
    val secondCoefficient = curve.b.toBigInteger()
    val ecParams = ECParameterSpec(
        EllipticCurve(ecField, firstCoefficient, secondCoefficient),
            ecPoint,
            n,
            h
        )
    return ecParams.curve
}

The public key I am passing to the iosB64EncodedStrPKToPK() function: BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94=
The output I get: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAECVZa7jqKX+XLoDF3+pyWaERWEa2H3dA3n6HckEkQoSaEp3Ut+qSkKpfVxPVxAOz2c+r0urT8W1mK2SOvtGp33g==
val pkIOS = "BAlWWu46il/ly6Axd/qclmhEVhGth93QN5+h3JBJEKEmhKd1LfqkpCqX1cT1cQDs9nPq9Lq0/FtZitkjr7Rqd94="

Log.i("SOME_TAG","PUBLIC_KEY_IOS:${Base64.encodeToString(iosB64EncodedStrPKToPK(pkIOS).encoded,Base64.NO_WRAP)}")

I am not an expert on the matter, maybe someone may guide me in the right direction and can see the mistake I am making. Cryptography is out of my field expertise.
I have tried Googling, ChatGPT and other insightful resources, if you know a source around the issue I would gladly accept it too.
I am running the code in an Android Environment
The version of BouncyCastle I am using:
def bouncy_castle_version = '1.70'
implementation "org.bouncycastle:bcpkix-jdk15on:$bouncy_castle_version"
implementation "org.bouncycastle:bcprov-jdk15on:$bouncy_castle_version"

A: The keys are identical, only their formats differ:

*

*The input BAlW... is an uncompressed public EC key (Base64 encoded).

*The output MFkw... is an ASN.1/DER encoded key in X.509/SPKI format (Base64) encoded.

This can be easily verified by encoding both keys not in Base64 but in hex:
input :                                                     0409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de
output: 3059301306072a8648ce3d020106082a8648ce3d0301070342000409565aee3a8a5fe5cba03177fa9c9668445611ad87ddd0379fa1dc904910a12684a7752dfaa4a42a97d5c4f57100ecf673eaf4bab4fc5b598ad923afb46a77de

As can be seen, the ASN.1/DER encoded X.509/SPKI key contains the uncompressed public key at the end (the last 65 bytes).

Background:
Keep in mind that a public EC key is a point (x, y) on an EC curve (obtained by multiplying the private key by the generator point) and that there are different formats for its representation, e.g. the following two:

*

*The uncompressed format, which corresponds to the concatenation of a 0x04 byte, and the x and y coordinates of the point: 04|x|y.
For the secp256r1 curve (aka prime256v1 aka NIST P-256), x and y are both 32 bytes, so the uncompressed key is 65 bytes.

*The X.509/SPKI format as defined in RFC 5280. This format is described with ASN.1 and serialized/encoded with DER (s. here).
PublicKey#getEncoded() returns the ASN.1/DER encoded X.509/SPKI key. With an ASN.1/DER parser the ASN.1/DER can be decoded, e.g. https://lapo.it/asn1js/.


Q: How can display text only when mouse over I have this sample:
link
CODE HTML:

                SED PERSPICIATIS

                    Sed ut perspiciatis unde omnis iste natus error sit
                    voluptatem accusantium doloremque laudantium,
                    totam rem aperiam, eaque ipsa quae ab illo inventore
                    veritatis et quasi architecto beatae vitae dicta sunt
                    explicabo.

SED PERSPICIATIS

                Sed ut perspiciatis unde omnis iste natus error sit

                voluptatem accusantium doloremque laudantium,

                totam rem aperiam, eaque ipsa quae ab illo inventore

                veritatis et quasi architecto beatae vitae dicta sunt

                explicabo.

SED PERSPICIATIS

                Sed ut perspiciatis unde omnis iste natus error sit

                voluptatem accusantium doloremque laudantium,

                totam rem aperiam, eaque ipsa quae ab illo inventore

                veritatis et quasi architecto beatae vitae dicta sunt

                explicabo.

CODE CSS:
.col-md-4 {
    width: 33.33333333%;
}
.tab-bottom {
    position: relative;
    height: 400px;
    float:left;
}
.tab-bottom-img {
    width: 100%;
    position: absolute;
    top: 50%;
    height: 100%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.tab-bottom-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

CODE JS:
$(".tab-bottom").bind('mouseover',function(event){
    $(this).find("tab-bottom-content").css("display", "block");
});
$('.tab-bottom-img').bind('mouseleave', function(e) {

});

I want the text in the div tab-bottom-content to be displayed only when the mouse is over.
I tried to use the script above but unfortunately does not work
Can you help me to solve this problem?
Thanks in advance!

A: I would solve this using CSS instead.
like this fiddle
Example html:

     Test

CSS:
.tab-bottom{
  border: 1px SOLID #F00; /* For display purpose */
  width: 200px;
  height: 200px;
}

.tab-bottom.tab-bottom-content{
  display: none;
}
.tab-bottom:hover .tab-bottom-content{
  display: block;
}

There is no need for JavaScript or jQuery here :)

A: You should initially hide .tab-bottom-content using display: none like following.
.tab-bottom-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none
}

And the use following jQuery. You missed the . before tab-bottom-content
$(".tab-bottom").mouseover(function(event){
    $(this).find(".tab-bottom-content").show(300);
}).mouseleave(function(e) {
    $(this).find(".tab-bottom-content").hide(300);
});

A: You need '.' in this .find("tab-bottom-content")
$(".tab-bottom").on('mouseover',function(event){
    $(this).find(".tab-bottom-content").show(300);
});
$('.tab-bottom').on('mouseleave', function(e) {
    $(this).find(".tab-bottom-content").hide(300);
});

Here is the pen
You must also add CSS
.tab-bottom-content {
    display:none;
 }

or inline style to hide the 'tab-bottom-content' content first

A: You can set the opacity of the tab-bottom-content to 0 and then change it to 1 in its :hover pseudo-selector class so that the text appears when you hover over the tab-bottom-content div. You may even want to add a transition so that the opacity changes smoothly. Do this,
.tab-bottom-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid black;
  opacity: 0;
  transition: opacity .4s ease-in;
}

.tab-bottom-content:hover {
  opacity: 1
}

Check it out https://jsfiddle.net/5s1fv2a9/


Q: C++: Storing user inputs I just want the user to enter some numbers. If the number is -1 the program stops and then outputs those same numbers. Why is that so difficult? I don't understand why the logic is not working here.
For example when the user types:
1 2 3 -1

The program should then print out:
    1
    2
    3
    -1
#include <iostream>

using namespace std;

int main()
{
    int input, index=0;
    int array[200];

    do
    {
        cin >> input;
        array[index++]=input;
    } while(input>0);

    for(int i=0; i < index; i++)
    {
        cout << array[index] << endl;
    }
}

A: Change this
for(int i=0; i < index; i++)
{
    cout << array[index] << endl;
}

To
for(int i=0; i < index; i++)
{
    cout << array[i] << endl;
}

You used index at the seconde loop causing your program to print all the array cell's after the user input.
Also, if -1 is your condition you should change it to
} while(input>=0);
             ^^

Otherwise, also 0 will stop the loop, which is not what you asking for.


Q: Sending email in Asp.net / C# with attachments - Issues with Gmail In an ASP/C# application I'm sending an email with 3 file attached. The 3 files are the same type, same extension and more or less same size ( but none are empty ).
The email is sent correctly. If I open it using outlook, I have no problems. I can see the body, and the 3 files attached.
But here is my issue: If I send that mail to a Gmail Adress, then on Gmail I can see only 2 attachments.

And if I click on the download all attachment icon ( on the right ), it will download the 2 visible attachment + the third one but empty.
It's a really weird issue.
Also there is a 4th attachment which is an embedded image. And this image is display correctly in the mail body.
Here is the code I'm using to send the mail:
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("SMTP_IP_ADRESS", SMTP_IP_PORT);

            mail.From = new MailAddress("MYEMAIL@DOMAIN.COM");

            mail.To.Add("GMAIL_EMAIL");
            mail.To.Add("OUTLOOK_EMAIL");

            mail.Subject = "MSN "+Request.Params["nameMsn"];

            Attachment imageAttachment = new
            Attachment(Server.MapPath(Url.Content("~/Content/images/image.png")));
            string contentID = "logoCare";
            imageAttachment.ContentId = contentID;
            mail.IsBodyHtml = true;
            mail.Body = "Have a good day.
Best regards.

";

            for (int i = 0; i < Request.Files.Count; i++)
            {
                HttpPostedFileBase file = Request.Files[i];
                var attachment = new Attachment(file.InputStream, file.FileName,
                MediaTypeNames.Application.Octet);
                mail.Attachments.Add(attachment);
            }

            mail.Attachments.Add(imageAttachment);

            SmtpServer.Send(mail);

A: The third attachment you see empty can possibly be the CID embedded image that web based email clients (like Gmail) can't manage, meanwhile it works with desktop email clients like Outlook. Can you verify this?
Please take a look at here


Q: Out of memory errors in Java API that uses finalizers in order to free memory allocated by C calls We have a Java API that is a wrapper around a C API.
As such, we end up with several Java classes that are wrappers around C++ classes.
These classes implement the finalize method in order to free the memory that has been allocated for them.
Generally, this works fine. However, in high-load scenarios we get out of memory exceptions.
Memory dumps indicate that virtually all the memory (around 6Gb in this case) is filled with the finalizer queue and the objects waiting to be finalized.
For comparison, the C API on its own never goes over around 150 Mb of memory usage.
Under low load, the Java implementation can run indefinitely. So this doesn't seem to be a memory leak as such. It just seem to be that under high load, new objects that require finalizing are generated faster than finalizers get executed.
Obviously, the 'correct' fix is to reduce the number of objects being created. However, that's a significant undertaking and will take a while. In the meantime, is there a mechanism that might help alleviate this issue? For example, by giving the GC more resources.

A: Java was designed around the idea that finalizers could be used as the primary cleanup mechanism for objects that go out of scope.  Such an approach may have been almost workable when the total number of objects was small enough that the overhead of an "always scan everything" garbage collector would have been acceptable, but there are relatively few cases where finalization would be appropriate cleanup measure in a system with a generational garbage collector (which nearly all JVM implementations are going to have, because it offers a huge speed boost compared to always scanning everything).
Using Closable along with a try-with-resources constructs is a vastly superior approach whenever it's workable.  There is no guarantee that finalize methods will get called with any degree of timeliness, and there are many situations where patterns of interrelated objects may prevent them from getting called at all.  While finalize can be useful for some purposes, such as identifying objects which got improperly abandoned while holding resources, there are relatively few purposes for which it would be the proper tool.
If you do need to use finalizers, you should understand an important principle: contrary to popular belief, finalizers do not trigger when an object is actually garbage collected"--they fire when an object would have been garbage collected but for the existence of a finalizer somewhere [including, but not limited to, the object's own finalizer].  No object can actually be garbage collected while any reference to it exists in any local variable, in any other object to which any reference exists, or any object with a finalizer that hasn't run to completion.  Further, to avoid having to examine all objects on every garbage-collection cycle, objects which have been alive for awhile will be given a "free pass" on most GC cycles.  Thus, if an object with a finalizer is alive for awhile before it is abandoned, it may take quite awhile for its finalizer to run, and it will keep objects to which it holds references around long enough that they're likely to also earn a "free pass".
I would thus suggest that to the extent possible, even when it's necessary to use finalizer, you should limit their use to privately-held objects which in turn avoid holding strong references to anything which isn't explicitly needed for their cleanup task.

A: Phantom references is an alternative to finalizers available in Java.
Phantom references allow you to better control resource reclamation process.

*

*you can combine explicit resource disposal (e.g. try with resources construct) with GC base disposal

*you can employ multiple threads for postmortem housekeeping

Using phantom references is complicated tough. In this article you can find a minimal example of phantom reference base resource housekeeping.
In modern Java there are also Cleaner class which is based on phantom reference too, but provides infrastructure (reference queue, worker threads etc) for ease of use.


Q: Hibernate Search Error Can someone help, i'm trying a simple example with hibernate search but getting the following error:
Exception in thread "main" org.hibernate.HibernateException: could not init listeners
    at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:205)
    at org.hibernate.cfg.Configuration.getInitializedEventListeners(Configuration.java:1396)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
    at FirstExample.main(FirstExample.java:32)
Caused by: java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:61)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
    at org.hibernate.search.util.HibernateSearchResourceLoader.getLines(HibernateSearchResourceLoader.java:52)
    at org.apache.solr.analysis.StopFilterFactory.inform(StopFilterFactory.java:53)
    at org.hibernate.search.impl.SolrAnalyzerBuilder.buildAnalyzer(SolrAnalyzerBuilder.java:79)
    at org.hibernate.search.impl.InitContext.buildAnalyzer(InitContext.java:185)
    at org.hibernate.search.impl.InitContext.initLazyAnalyzers(InitContext.java:155)
    at org.hibernate.search.impl.SearchFactoryImpl.initDocumentBuilders(SearchFactoryImpl.java:541)
    at org.hibernate.search.impl.SearchFactoryImpl.<init>(SearchFactoryImpl.java:171)
    at org.hibernate.search.event.ContextHolder.getOrBuildSearchFactory(ContextHolder.java:60)
    at org.hibernate.search.event.FullTextIndexEventListener.initialize(FullTextIndexEventListener.java:122)
    at org.hibernate.event.EventListeners$1.processListener(EventListeners.java:198)
    at org.hibernate.event.EventListeners.processListeners(EventListeners.java:181)
    at org.hibernate.event.EventListeners.initializeListeners(EventListeners.java:194)
    ... 3 more

My Item Class:
@Indexed
@AnalyzerDef(name="customanalyzer",
        tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
        filters = {
                @TokenFilterDef(factory = ISOLatin1AccentFilterFactory.class),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(factory = StopFilterFactory.class, params = {
                    @Parameter(name="words", value= "org/hibernate/search/test/analyzer/solr/stoplist.properties" ),
                    @Parameter(name="ignoreCase", value="true")
                })
})

public class Item
{
    @DocumentId
      private Integer id;

      @Field @Analyzer(definition = "customanalyzer")
      private String title;

      @Field @Analyzer(definition = "customanalyzer")
      private String description;

      @Field(index=Index.UN_TOKENIZED, store=Store.YES)
      private String ean;

      private String imageURL;
      //public getters and setters
}

Program code:
Session session = null;
        Transaction tx = null;

            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            session =sessionFactory.openSession();
            FullTextSession ftem = org.hibernate.search.Search.getFullTextSession(session);

            ftem.beginTransaction();
            List <Item> AllItem=session.createQuery("From Item").list();

            for (Item item : AllItem) {
                  ftem.index(item);
            }
            ftem.getTransaction().commit();

            String searchQuery = "title:Batman";

            QueryParser parser = new QueryParser(
                    "title",
                    ftem.getSearchFactory().getAnalyzer("customanalyzer")
        );
            org.apache.lucene.search.Query luceneQuery;
            try {
                 luceneQuery = parser.parse(searchQuery);
            }
            catch (ParseException e) {
                  throw new RuntimeException("Unable to parse query: " + searchQuery, e);
            }

            org.hibernate.Query query = ftem.createFullTextQuery(
                    luceneQuery,
                    Item.class);
            query.setFirstResult(20).setMaxResults(20);
            List results = query.list();

A: It looks like Hibernate Search can't find org/hibernate/search/test/analyzer/solr/stoplist.properties in the classpath. Make sure it's there.


Q: Efficient way to calculate average MAPE and MSE in R I have a real data and predicted data and I want to calculate overall MAPE and MSE. The data are time series, with each column representing data for different weeks. I predict value for each of the 52 weeks for each of the items as shown below. What would be the best possible calculate overall Error in R.
real = matrix(
    c("item1", "item2", "item3", "item4", .5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37),
     nrow=4,
     ncol=4)
colnames(real) <- c("item", "week1", "week2", "week3")

predicted = matrix(
  c("item1", "item2", "item3", "item4", .55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37),
  nrow=4,
  ncol=4)
colnames(predicted) <- c("item", "week1", "week2", "week3")

A: How do you get the predicted values in the first place? The model you use to get the predicted values is probably based on minimising some function of prediction errors (usually MSE). Therefore, if you calculate your predicted values, the residuals and some metrics on MSE and MAPE have been calculated somewhere along the line in fitting the model. You can probably retrieve them directly.
If the predicted values happened to be thrown into your lap and you have nothing to do with fitting the model, then you calculate MSE and MAPE as per below:
You have only one record per week for every item. So for every item, you can only calculate one prediction error per week. Depending on your application, you can choose to calculate the MSE and MAPE per item or per week.
This is what your data looks like:
real <- matrix(
  c(.5, .7, 0.40, 0.6, 0.3, 0.29, 0.7, 0.09, 0.42, 0.032, 0.3, 0.37),
  nrow = 4, ncol = 3)
colnames(real) <- c("week1", "week2", "week3")

predicted <- matrix(
  c(.55, .67, 0.40, 0.69, 0.13, 0.9, 0.47, 0.19, 0.22, 0.033, 0.4, 0.37),
  nrow = 4, ncol = 3)
colnames(predicted) <- c("week1", "week2", "week3")

Calculate the (percentage/squared) errors for every entry:
pred_error    <- real - predicted
pct_error     <- pred_error/real
squared_error <- pred_error^2

Calculate MSE, MAPE:
# For per-item prediction errors
apply(squared_error,  MARGIN = 1, mean)    # MSE
apply(abs(pct_error), MARGIN = 1, mean)    # MAPE

# For per-week prediction errors
apply(squared_error,  MARGIN = 0, mean)    # MSE
apply(abs(pct_error), MARGIN = 0, mean)    # MAPE


Q: Copy nodes with changed element values XSLT I have input xml

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1981</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>USA</country>
    <company>RCA</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
</catalog>

How do the follow?
For each "catalog/cd"
1) if "year" = '1985', then copy all elemets of "catalog/cd" without changed values
2) else copy all elements "catalog/cd" without changed values, exclude elements "company" (need to set value 'MyCompany') and "country" (need to set value 'MyCountry')

Result XML

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <country>MyCountry</country>
    <company>MyCompany</company>
    <price>10.90</price>
    <year>1981</year>
  </cd>
  <cd>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <country>UK</country>
    <company>CBS Records</company>
    <price>9.90</price>
    <year>1985</year>
  </cd>
  <cd>
    <title>Greatest Hits</title>
    <artist>Dolly Parton</artist>
    <country>MyCountry</country>
    <company>MyCompany</company>
    <price>9.90</price>
    <year>1982</year>
  </cd>
</catalog>

A: There are different options to achieve what you need. You need to start with an identity template that would copy the input XML as is to output.
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>

Next you can declare separate templates for modifying country and company where the year != 1985.
<xsl:template match="cd[year != '1985']/country">
    <country>MyCountry</country>
</xsl:template>
<xsl:template match="cd[year != '1985']/company">
    <company>MyCompany</company>
</xsl:template>

Another option is to change the values of both elements in a single template cd whose child element year != 1985.
<xsl:template match="cd[year != '1985']">
    <xsl:copy>
        <xsl:apply-templates select="title | artist" />
        <country>MyCountry</country>
        <company>MyCompany</company>
        <xsl:apply-templates select="price | year" />
    </xsl:copy>
</xsl:template>

Hope this helps. However you need to go online and do some reading / hands on tutorials related to XSLT.

A:  <xsl:template match="catalog">
        <catalog>
        <xsl:for-each select="cd">
            <cd>
            <title>
                <xsl:value-of select="title"/>
            </title>
            <artist>
                <xsl:value-of select="artist"/>
            </artist>
            <xsl:choose>
                <xsl:when test="not(year = 1985)">
                    <country>MY Country</country>
                    <company>My Company</company>
                </xsl:when>
                <xsl:otherwise>
                    <country><xsl:value-of select="country"/></country>
                    <company><xsl:value-of select="company"/></company>
                </xsl:otherwise>
            </xsl:choose>
            <price><xsl:value-of select="price"/></price>
            <year><xsl:value-of select="year"/></year>
            </cd>
        </xsl:for-each>
        </catalog>
    </xsl:template>
Check it, I may be helful for you


Q: mongodb query about listing one field as an array with all collections in detailed Assume I have db structure as;
[
    {name: "alex" , age: 21, school: "x university" },
    {name: "felix" , age: 24, school: "y university" },
    {name: "tom" , age: 43, school: "z university" }
]

I want to write a query to get the details of the collection plus the array of the names. I mean as a result of the query I expect to get;
details:[
    {name: "alex" , age: 21, school: "x university" },
    {name: "felix" , age: 24, school: "y university" },
    {name: "tom" , age: 43, school: "z university" }
],

names: ["alex", "felix", "tom"]

To able to get the names as an array I wrote,
db.colletion.aggregate([
    {$group: {_id: "", names: {$addToSet : "$name"}}}
])

But this just prints the names as;
{ "_id" : "", "names" : [ "alex", "felix", "tom"] }

In grouping I can project fields something like,
db.colletion.aggregate([
    {$group: {age: {$first: "$age"}, _id: "", names: {$addToSet : "$name"}}}
])

But this db is just an example, I have dynamic fields that I don't know in advanced. So how can I build this query?


Q: What is the difference between margin and padding in html? I have made a educational website and I am facing problem to set the paragraph block in the on the background page. So kindly help me.
I was trying to manage the text on the background image but it was coming on the top-left of the image.


Q: How to calculate cubes and functions inside AnyLogic? I have a AnyLogic simulation which is set up to use system dynamic to calculate the power of a cyclist.
For part of this I need to calculate the cube of a function and then "sin(tan^-1) of a function". Within a dynamic variable calculation I have tried this code:
cube(double Velocity)
and
sin(atan(double Gradient))
However  this is not working, any assistance would be appreciated.

A: Quick glance at the help reveals the code you need. In your case:
pow(velocity, 3)
and
sin(pow(tan(myValue), -1))
Please learn to use the help first. And also add what errors/problems you hit when you tried something already :)


Q: angular 2 *ngfor custom orderby causing chrome inspector to refresh constantly I have tried to make a custom orderBy pipe in angular 2 (ionic app) and for some reason, it's making the chrome inspector (maybe even the entire app) refresh constantly.
<ion-card class="event" *ngFor="let position of positions | OrderBy : 'event.startDateTime'">
    ...
</ion-card>

The event.startDateTime is format as such: "2017-05-26 00:00".
I followed this answer: Angular 2 OrderBy Pipe to make this pipe. The only thing I've changed is using moment.js to turn a dateTime stamp into a unix timestamp
static _orderByComparator(a: any, b: any): number {
    a = moment(a).unix();
    b = moment(b).unix();

So, I'm not sure why it's doing this to chrome, and I'm wondering if anyone else has experienced this?
full code below
    import { Pipe, PipeTransform } from "@angular/core";
    import * as moment from 'moment';
    //Angular 2 OrderBy Pipe
@Pipe({
  name: "OrderBy",
  pure: false
})

export class OrderBy implements PipeTransform {

  value: string[] = [];

  static _orderByComparator(a: any, b: any): number {

    a = moment(a).unix();
    b = moment(b).unix();

    if (a === null || typeof a === "undefined") { a = 0; }
    if (b === null || typeof b === "undefined") { b = 0; }

    if (
  (isNaN(parseFloat(a)) ||
  !isFinite(a)) ||
  (isNaN(parseFloat(b)) || !isFinite(b))
) {
  // Isn"t a number so lowercase the string to properly compare
  a = a.toString();
  b = b.toString();
  if (a.toLowerCase() < b.toLowerCase()) { return -1; }
  if (a.toLowerCase() > b.toLowerCase()) { return 1; }
} else {
  // Parse strings as numbers to compare properly
  if (parseFloat(a) < parseFloat(b)) { return -1; }
  if (parseFloat(a) > parseFloat(b)) { return 1; }
}

return 0; // equal each other

}
public transform(input: any, config = "+"): any {
    if (!input) { return input; }
// make a copy of the input"s reference
this.value = [...input];
let value = this.value;
if (!Array.isArray(value)) { return value; }

if (!Array.isArray(config) || (Array.isArray(config) && config.length === 1)) {
  let propertyToCheck: string = !Array.isArray(config) ? config : config[0];
  let desc = propertyToCheck.substr(0, 1) === "-";

  // Basic array
  if (!propertyToCheck || propertyToCheck === "-" || propertyToCheck === "+") {
    return !desc ? value.sort() : value.sort().reverse();
  } else {
    let property: string = propertyToCheck.substr(0, 1) === "+" || propertyToCheck.substr(0, 1) === "-"
      ? propertyToCheck.substr(1)
      : propertyToCheck;

    return value.sort(function(a: any, b: any) {
      let aValue = a[property];
      let bValue = b[property];

      let propertySplit = property.split(".");

      if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
        aValue = a;
        bValue = b;
        for (let j = 0; j < propertySplit.length; j++) {
          aValue = aValue[propertySplit[j]];
          bValue = bValue[propertySplit[j]];
        }
      }

      return !desc
        ? OrderBy._orderByComparator(aValue, bValue)
        : -OrderBy._orderByComparator(aValue, bValue);
    });
  }
} else {
  // Loop over property of the array in order and sort
  return value.sort(function(a: any, b: any) {
    for (let i = 0; i < config.length; i++) {
      let desc = config[i].substr(0, 1) === "-";
      let property = config[i].substr(0, 1) === "+" || config[i].substr(0, 1) === "-"
        ? config[i].substr(1)
        : config[i];

      let aValue = a[property];
      let bValue = b[property];

      let propertySplit = property.split(".");

      if (typeof aValue === "undefined" && typeof bValue === "undefined" && propertySplit.length > 1) {
        aValue = a;
        bValue = b;
        for (let j = 0; j < propertySplit.length; j++) {
          aValue = aValue[propertySplit[j]];
          bValue = bValue[propertySplit[j]];
        }
      }

      let comparison = !desc
        ? OrderBy._orderByComparator(aValue, bValue)
        : -OrderBy._orderByComparator(aValue, bValue);

      // Don"t return 0 yet in case of needing to sort by next property
      if (comparison !== 0) { return comparison; }
    }

    return 0; // equal each other
  });
    }
  }
}


Q: PHP/MYSQL Query as a Function for Multi-Use I am trying to clean a ton of select queries inside about 15 pages of a website and I thought using a function that then I can use to call all the different queries and tables, would reduce the clutter a bunch.
I am running into a problem and can't seem to figure out a way to get it right.
Here is the function:
function dbGet($conn, $table, $select, $where, $cond) {
   require($conn);
   if ( $stmt = $db->prepare(" SELECT $select FROM `" . $table . "` WHERE $where=? ")) {
      $stmt->bind_param("i", $cond);
      $stmt->execute();
      $result = $stmt->get_result();
      $rowNum = $result->num_rows;

      if ( $rowNum > 0 ) {
         while( $data = $result->fetch_assoc() ){
            return $data;
         }
      }
      $stmt->close();
   } else {
      die($db->error);
   }
   $db->close();
}

And here is how I call the function in the various different pages:
$settings = dbGet('php/connect.php', 'settings', '*', 'userId', $sessionId);
echo $settings->toName;

The problem I am running into, is that it is only displaying the first record from the settings table. I thought using the while loop in the function would return all the records. As a matter of fact, if I do a print_r for $data instead of return, I get all the records. How can I pass along all the records into the return $data to be access in any other page?
OR
If you guys happen to have any suggestions of an existing function that is highly regarded and true-and-tested that I can implement instead of writing my own, please let me know.
Thanks.

A: When return is triggered, the function ends and every other line of code after it is not executed. If you want to delay the return of your data until later in the function, then create a variable, assign value(s), and return the variable when you're ready.
For example, you can adapt your code to create an array for $data, like so:
function dbGet($conn, $table, $select, $where, $cond) {
    $data = array();
    ...
    while ( $row = $result->fetch_assoc() ) {
        $data[] = $row;
    }
    $stmt->close();
    ...

    $db->close();

    return $data;
}


Q: R create multiple variables with one condition Is there a simpler way to write it,create multiple variables for one condition? like this
  if am == 1 then do;
    a="";
    b="";
    c=;
  end;
  else if am == 0 then do;
    ...
  end;

The following is the R code I wrote
library(dplyr)
dt1 <- mtcars
dt2 <- dt1 %>%
mutate(a = case_when(am == 1 ~ "a1",
                     am == 0 ~ "a2",
                     am == 2 ~ "a3"),

       b = case_when(am == 1 ~ "a2",
                     am == 0 ~ "a2",
                     am == 2 ~ "a2"),

       c = case_when(am == 1 ~ 0,
                     am == 0 ~ 1,
                     am == 2 ~ 2))

A: lookup <- data.frame(
  am = c(1, 0, 2), a = c('a1', 'a2', 'a3'), b = 'a2', c = c(0, 1, 2)
)
left_join(dt1, lookup, 'am')


Q: How can I get rid of this error: error: unreported exception FileNotFoundException; Here's my code. I have to write it without using the FileNotFoundException class. The code reads from a file which contains array info. I get the this error:
F:\FanClub.java:59: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
    Scanner inputFile = new Scanner(file);

Thanks
import java.util.Scanner;
import java.util.ArrayList;

import java.io.*;

public class FanClub
{
    private static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) throws IOException
    {
        final int NUM_FANS = 100;
        int numFans = 0;
        int[] ages = new int[NUM_FANS];

        String[] names = new String[NUM_FANS];

        numFans = fillArrays(names, ages, NUM_FANS);
    }

    public static int fillArrays(String[] names, int[] ages, int NUM_FANS)
    {
        int counter = 0;
        System.out.print("Enter the file name: ");
        String fileName = keyboard.nextLine();

        File file = new File(fileName);
        Scanner inputFile = new Scanner(file);

        if (!file.exists())
        {
            System.out.println("File " + fileName + " not found.");
            System.exit(0);
        }

        int[] numFans = new int[NUM_FANS];

        while (inputFile.hasNext() && counter < numFans.length)
        {
            numFans[counter] = inputFile.nextInt();
            counter++;
        }
        inputFile.close();
        return counter;
    }
}

A: Try to do this instead:
File file = null;

try
{
    file = new File(fileName);
    Scanner inputFile = new Scanner(file);
}
catch(IOException ioe) // should actually catch FileNotFoundException instead
{
    System.out.println("File " + fileName + " not found.");
    System.exit(0);
}

A: As I tried to explain in the comments, you're reading the file in the wrong order. You say your file looks like this:
Chris P. Cream 5 Scott Free 9 Lou Tenant 3 Trish Fish 12 Ella Mentry 4 Holly Day 3 Robyn DeCradle 12 Annette Funicello 4 Elmo 7 Grover 3 Big Bird 9 Bert 7 Ernie 3

You're just calling inputFile.nextInt(), which attempts to read an int, but "Chris P. Cream" is not an int, which is why you're getting that input mismatch exception. So first you need to read the name, then you can read that number.
Now, since it isn't clear how your text file is delimited (it's all on one line), this presents a problem because the names can be one, two, or even three words, and are followed by a number. You can still do this, but you'll need a regular expression that tells it to read up to that number.
while (inputFile.hasNext() && counter < numFans.length)
{
    names[counter] = inputFile.findInLine("[^\\d]*").trim();
    numFans[counter] = inputFile.nextInt();
    System.out.println(names[counter] + ": " + numFans[counter]);
    counter++;
}

However, if your file is actually formatted like this (separate lines):
Chris P. Cream
5
Scott Free
9
Lou Tenant
3
Trish Fish
12
Ella Mentry
4
Holly Day
3
Robyn DeCradle
12
Annette Funicello
4
Elmo
7
Grover
3
Big Bird
9
Bert
7
Ernie
3

Then you're in luck, because you can do this instead (doesn't require a regular expression):
while (inputFile.hasNext() && counter < numFans.length)
{
    names[counter] = inputFile.nextLine();
    numFans[counter] = inputFile.nextInt();
    if (inputFile.hasNext())
        inputFile.nextLine(); // nextInt() will read a number, but not the newline after it
    System.out.println(names[counter] + ": " + numFans[counter]);
    counter++;
}

What did Ernie say when Bert asked if he wanted icecream?
Sure Bert.


Q: Read and write into a txt file using VB.NET with words in between I want to open a txt file and write into it numbers from 1 to 100 and put between every number enter.

A: One way you could try is to write the numbers into a StringBuilder and then use it's ToString() method to get the resulting text:
Imports System.IO
Imports System.Text

Public Class NumberWriter
   Private ReadOnly OutputPath as String = _
          Path.Combine(Application.StartupPath, "out.txt")

   Public Sub WriteOut()
       Dim outbuffer as New StringBuilder()

       For i as integer = 1 to 100
          outbuffer.AppendLine(System.Convert.ToString(i))
       Next i

       File.WriteAllText(OutputPath, outbuffer.ToString(), true)
   End Sub

   Public Shared Sub Main()
      Dim writer as New NumberWriter()
      Try
        writer.WriteOut()
      Catch ex as Exception
        Console.WriteLine(ex.Message)
      End Try
   End Sub
End Class

A: There's a good example over at Home and Learn
 Dim FILE_NAME As String = "C:\test2.txt"

If System.IO.File.Exists(FILE_NAME) = True Then
    Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
    objWriter.Write(TextBox1.Text)
    objWriter.Close()
    MsgBox("Text written to file")
Else
    MsgBox("File Does Not Exist")
End If

A: You could also use the "My.Computer.FileSystem" namespace, like:
Dim str As String = ""
For num As Int16 = 1 To 100
  str += num.ToString & vbCrLf
Next
My.Computer.FileSystem.WriteAllText("C:\Working\Output.txt", str, False)

A: See System.IO namespace, especially the System.IO.File class.


Q: Why would one want to predefine a template parameter type in C++? I was writing some code for a project, and I was using a library named APA102. In this library, there is a class titled APA102 defined as follows,
template<uint8_t dataPin, uint8_t clockPin>
class APA102 : public APA102Base {
...

I am confused why anyone would use a template class to define a value that could have easily been passed as a class constructor parameter.
And to extend on my original question, I was attempting to create a class method that used this APA102 class as a parameter, but I was not able to define a parameter as this type if I tried to do as follows:
void someMethod(APA102<uint8_t, uint8_t> &param)

As I kept getting the error

error: type/value mismatch at argument 1 in template parameter list for 'template<unsigned char dataPin, unsigned char clockPin> class Pololu::APA102'
     virtual void someMethod(APA102<const uint8_t, const uint8_t> &ledStrip) = 0;

The only way I could have an APA102 object as a parameter was to define two uint8_t values, and use those as the template parameters first. For example, this worked:
const uint8_t clockPin = 11;
const uint8_t dataPin = 12;
virtual void someMethod(APA102<clockPin, dataPin> &ledStrip) = 0;

Can anyone help me understand these template classes with predefined template parameters? Why did I get the error I did?


Q: throw MissingPluginException('No implementation found for method $method on channel $name'); i have a flutter app and i use google sign in with Firebase, but i run app and click in sign in button there is an error while debug
 if (result == null) {
  if (missingOk) {
    return null;
  }
  throw MissingPluginException('No implementation found for method $method on channel  $name');
}
return codec.decodeEnvelope(result) as T?;
}

any help please?

A: It's Solve is so easy just stop your app and run it again
i hope this is useful


Q: What's the difference between minmax() and clamp() in CSS? Both CSS functions clamp the value between an upper and lower bound.
The only difference that I know is that minmax() can only be used in CSS grid.

A: From developer.mozilla.org:

clamp() enables selecting a middle value within a range of values between a defined minimum and maximum. It takes three parameters: a minimum value, a preferred value, and a maximum allowed value.

minmax() only accepts the two extreme values, plus the difference that you already mentioned.

A: minmax() may only be used in Grid and picks between two (2) parameters.
clamp() can be used anywhere in CSS and picks between three (3) parameters: minimum, preferred, and maximum, selecting the middle (preferred) parameter when possible.


Q: How does dup work on jagged arrays? I would expect it to duplicate only nested arrays slices instead of the whole deep copy of array, but suddenly I've got a doubt.

A: ratchet freak is right, it is a shallow copy. You can see the source to the dup function in dmd2/src/druntime/src/rt/lifetime.d. The function is called _adDupT.
It is a pretty short function where the main work is a call to memcpy(). Above the function, you can see a representation of an array: struct { size_t length; void* ptr; }
A jagged array would be an array of arrays, so the memory would look like [length0, ptr0, length1, ptr1, length2, ptr2....]
Since memcpy over those pointers doesn't follow them, that means slice.dup is a shallow copy.
This is generally true with anything that copies slices, it is always shallow copies unless you do something yourself. So struct A {char[] str; } A a, b; a = b; would also shallow copy, so assert(a.str is b.str).
If you want to do a deep copy, the simplest way is to just loop over it:
T[][] newArray;
foreach(item; oldArray)
      newArray ~= item.dup;

(you can also preallocat newArray.length = oldArray.length and assign with indexes if you want to speed it up a bit)
A deep copy of a struct could be done with compile time reflection, though I prefer to write a clone method or something in there since it is a bit more clear.
I'm not aware of a phobos function with this premade.


Q: How to correctly use PLAY_VIDEO in Mirror API I've been playing around with the Google Glass Mirror API and want to be able to stream a video.
This is the Python code snippet I tried:
def _insert_item_video_stream(self):
    """Insert a timeline item with streaming video."""
    logging.info('Inserting timeline item with streaming video')
    body = {
        'notification': {'level': 'DEFAULT'},
        'menuItems' : [{'action' : 'PLAY_VIDEO'},
                       {'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}],
    }
    self.mirror_service.timeline().insert(body=body).execute()
    return 'A timeline item with streaming video has been inserted.'

However, the video was just blank.  Any ideas would be super helpful!

A: Was able to fix this after removing two brackets! Oh, Python. :/
This is the fixed line:
   'menuItems' : [{'action' : 'PLAY_VIDEO', 'payload' : 'https://eye-of-the-hawk.appspot.com/static/videos/waterfall.mp4'}],


Q: Light UIAlertView/UIActionView customization Would this type of customization be considered App Store safe ?
UIColor *veBlueColor = [UIColor colorWithRed:3.0/255.0 green:147.0/255.0 blue:215.0/255.0 alpha:1];
UIColor *veRedColor = [UIColor colorWithRed:242.0/255.0 green:93.0/255.0 blue:69.0/255.0 alpha:1];

for (UIView *subview in actionSheet.subviews) {

    if ([subview isKindOfClass:[UIButton class]]) {

        UIButton *button                    = (UIButton*)subview;
        UIColor *buttonColor                = [button titleColorForState:UIControlStateNormal];
        NSString *buttonColorString         = [buttonColor description];

        UIColor *destructiveColor           = [UIColor colorWithRed:0.992157 green:0.278431 blue:0.168627 alpha:1];
        NSString *destructiveColorString    = [destructiveColor description];

        bool isDestructiveButton            = ([buttonColorString isEqual:destructiveColorString]?YES:NO);

        if (!isDestructiveButton) {

            [button setTitleColor:veBlueColor forState:UIControlStateNormal];
        }
        else {

            [button setTitleColor:veRedColor forState:UIControlStateNormal];
        }
    }
}

I have read the Human Interface Guidelines but there are always "gray areas" and a google search returns quite a few people claiming they got there App approved with customizations that are clearly not allowed by Apple.
So my question is, what are your experiences are with "light" customization ?

A: No in my opinion it's not safe. The Apple documentation clearly states: "UIActionSheet is not designed to be subclassed, nor should you add views to its hierarchy. If you need to present a sheet with more customization than provided by the UIActionSheet API, you can create your own and present it modally with presentViewController:animated:completion:."
In this case you're not adding subviews but you're actually retrieving the ones that are already there and customising them - which from an Apple perspective I assume is quite similar.
I would suggest creating your own ActionSheet if the UIActionSheet API is too restrictive for what you need. (I recommend having a look on Git Hub as there are different solutions that might be a good fit for you).


Q: How to keep folder structure while share common code across projects in git? I have the following directory structure that I'd like to keep it while share some of the directories across different projects. I'd like to achieve something like this:
root
  |_dir1  (git repo1)
  |_dir2  (git repo1)
  |_dir3  (git repo1)
  |_project<n> (git repo2 contains project specific code in different branches, e.g. project1's code in branch1 and project2's code in branch2, etc.)

dir1...3 are common code shared across different projects and I'd like to keep the folder structure unchanged.
I'm thinking about using git submodules but not sure how to do it. Is it possible to put dir1...3 in git repo1, as a submodule, then all project codes in project folder in git repo2, which is the main git repo that hosts git repo1 as the submodule?

A:
Is it possible to put dir1...3 in git repo1, as a submodule, then all
project codes in project folder in git repo2, which is the main git
repo that hosts git repo1 as the submodule?

That's totally feasible. But the .git of the master project have to be in the root directory (it's up to you to say if it's good for you or not), since submodules have to be located inside the repo's path (which is defined by the location of the .git folder).
From root :
git init
git submodule add <remote_url> dir1
git submodule add <remote_url> dir2
git submodule add <remote_url> dir3
mkdir project<n>
git submodule update --init --recursive
git commit -m "Added the submodule to the project."


Q: ProgrammingError - sqlalchemy - on_conflict_do_update Following this question:
As Ilja Everilä mentioned in his answer, I created a table object:
from sqlalchemy import *
metadata = MetaData()
idTagTable = Table('id_tag', metadata,
                 Column('id', String(255), primary_key = True),
                 Column('category', String(20), nullable = False),
                 Column('createddate', Date, nullable = False),
                 Column('updatedon', Date, nullable = False)
                 )

After creating a table object, I changed insert and update statements:
insert_statement = sqlalchemy.dialects.postgresql.insert(idTagTable)
upsert_statement = insert_statement.on_conflict_do_update(
        constraint=PrimaryKeyConstraint('id'),
        set_={"updatedon": insert_statement.excluded.updateon,
              "category":insert_statement.excluded.category}
)
insert_values = df.to_dict(orient='records')
conn.execute(upsert_statement, insert_values)

Now I am getting Programming Error:
Traceback (most recent call last):

File "<ipython-input-66-0fc6a1bf9c6b>", line 7, in <module>
conn.execute(upsert_statement, insert_values)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
exc_info

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1159, in _execute_context
context)

File "/home/ubuntu/anaconda2/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 467, in do_executemany
cursor.executemany(statement, parameters)

ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near
")"
LINE 1: ...category) VALUES ('sports') ON CONFLICT () DO UPDAT...
                                                    ^

Not Able to understand why I am getting this error.

A: The PrimaryKeyConstraint object you're using as constraint= argument is not bound to any table and would seem to produce nothing when rendered, as seen in ON CONFLICT (). Instead pass the primary key(s) of your table as the conflict_target and Postgresql will perform unique index inference:
upsert_statement = insert_statement.on_conflict_do_update(
        constraint=idTagTable.primary_key,
        set_={"updatedon": insert_statement.excluded.updateon,
              "category":insert_statement.excluded.category}
)


Q: Receive formatted 'multipart/form-data' response in Angular 7.x I am developing an Angular application that shows some images to the user.
I would like to obtain those images from a single REST call to a web service: given the fact i am already uploading the images via a FormData object, i would like to  receive those images in the same way (so, basically, via content-type: multipart/form-data).
At the moment, using the following code:
this.http.post('api/load', {}, {headers: {'Accept': 'multipart/form-data'},
  responseType:'text', observe: 'response'});

i am actually receiving the full body of the response in a text format, like this:
--974b5730-ab25-4554-8a69-444664cab379
Content-Disposition: form-data; name=result

{"bar":[1,2,3,4], "foo": true}
--974b5730-ab25-4554-8a69-444664cab379
Content-Disposition: form-data; name=image; filename=image1.jpg; filename*=utf-8''image1.jpg
--- binarycontent...

But it's in a raw, text format.
How can i receive a multipart/form-data response formatted by its boundaries, or a in clean way in Angular 7.x?

A: One of the solution is to implement an interceptor service where you can format multipart/form-data response.
For example, your inteceptor will be  - multipart.interceptor.ts :
@Injectable()
export class MultipartInterceptService implements HttpInterceptor {

    private parseResponse(response: HttpResponse<any>): HttpResponse<any> {
        const headerValue = response.headers.get('Content-Type');
        const body = response.body;
        const contentTypeArray = headerValue ? headerValue.split(';') : [];
        const contentType = contentTypeArray[0];

        switch (contentType) {
            case 'multipart/form-data':
                if (!body) {
                    return response.clone({ body: {} });
                }

                const boundary = body?.split('--')[1].split('\r')[0];
                const parsed = this.parseData(body, boundary); // function which parse your data depends on its content (image, svg, pdf, json)

                if (parsed === false) {
                    throw Error('Unable to parse multipart response');
                }

                return response.clone({ body: parsed });
            default:
                return response;
        }
    }

    // intercept request and add parse custom response
    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(customRequest).pipe(
            map((response: HttpResponse<any>) => {
                if (response instanceof HttpResponse) {
                    return this.parseResponse(response);
                }
            })
        );
    }
}


Q: How do I use variables in a select query? I have this following select query that uses a scalar function to get full name. I want to eliminate the redundancy by using variable but so far there is no success. My query is
select
 a.Id,
 a.UserName,
 getFullName(a.UserName),
 a.CreateTime
from DataTable;

I don't want to retrieve 'a.User' two times. I would prefer if I can save a.User in a variable and then pass it to the function hence improving the efficiency.
Currently the work around I came up with is as following
select
 Id,
 UserName,
 getFullName(UserName),
 CreateTime
from (select a.Id, a.UserName, a.CreateTime from DataTable) temp

This solves the performance issue but adds the overhead to write same select two time. Any other suggestions would be great.
DataTable looks like this
+----+----------+------------+
| Id | UserName | CreateTime |
+----+----------+------------+
|  1 | ab       | 10:00      |
|  2 | cd       | 11:00      |
|  3 | ef       | 12:00      |
+----+----------+------------+

Here is the NamesTable used to get the full names
+----------+----------+
| UserName | FullName |
+----------+----------+
| ab       | Aa BB    |
| cd       | Cc Dd    |
| ef       | Ee Ff    |
+----------+----------+

Here is the function that gets the full name
Create function [dbo].[getFullName](@user varchar(150)) returns varchar(500)
as
begin
    declare @Result varchar(500);

  select @Result = FullName from dbo.NamesTable where UserName =  @user;
  return @Result;
end;

A: You're solving a problem that doesn't exist. You seem to think that
select
 a.Id,
 a.UserName,
 getFullName(a.UserName),
 a.CreateTime
from DataTable;

Has some relatively expensive process behind it to get UserName that is happening twice.  In reality, once the record is located, getting the UserName value is an virtually instant process since it will probably be stored in a "variable" by the SQL engine behind the scenes.  You should have little to no performance difference between that query and
select
 a.Id,
 getFullName(a.UserName),
 a.CreateTime
from DataTable;

The scalar function itself may have a performance issue, but it's not because you are "pulling" the UserName value "twice".
A better method would be to join to the other table:
select
 a.Id,
 a.UserName,
 b.FullName,
 a.CreateTime
from DataTable a
LEFT JOIN dbo.NamesTable b
  ON a.UserName = b.UserName

A: As D Stanley says, you're trying to solve some problem that doesn't exist. I would further add that you shouldn't be using the function at all. SQL is meant to perform set-based operations. When you use a function like that you're now making it perform the same function over and over again for every row - a horrible practice. Instead, just JOIN in the other table (a set-based operation) and let SQL do what it does best:
SELECT
    DT.Id,
    DT.UserName,
    NT.fullname,
    DT.CreateTime
FROM
    DataTable DT
INNER JOIN NamesTable NT ON NT.username = DT.username;

Also, DataTable and NamesTable are terrible names for tables. Of course they're tables, so there's no need to put "table" on the end of the name. Further, of course the first one holds "data", it's a database. Your table names should be descriptive. What exactly does DataTable hold?
If you're going to be doing SQL development in the future then I strongly suggest that you read several introductory books on the subject and watch as many tutorial videos as you can find.

A: Scalar UDF will execute for every row,but not defintely the way you think.below is sample demo and execution plan which proves the same..
create table testid
(
id int,
name varchar(20)
)

insert into testid
select n,'abc'
from numbers
where n<=1000000

create index nci_get on dbo.testid(id,name)

select id,name,dbo.getusername(id) from dbo.testid where id>4

below is the execution plan for above query

Decoding above plan:
Index seek outputs id,name
Then compute scalar tries to calculate new rows from existing row values.in this case expr1003 which is our function
Index seek cost is 97%,compute scalar cost is 3% and as you might be aware index seek is not an operator which goes to table to get data.so hopefully this clears your question


Q: C# RazorPg - Check if form field is empty and mark as unchanged I have a form field that allows users to change their email address.
If the user doesn't enter anything in the field I want to send "unchanged" to the API. Not blank "" or null.
I've came up with this code:
if (!String.IsNullOrEmpty(Request.Form["Email"].ToString()))  // Null or blank check
{
 if (Request.Form["Email"].ToString() != user.Email)  // Don't update email if it's the same as the existing one
  {
    user.Email = Request.Form["Email"];
  }
  else
  {
    user.Email = "unchanged";      // I don't want to pass null or blank to the API.
  }
}
else
{
 user.Email = "unchanged";
}

It just looks very messy to me. I have 10 fields on the page so I'd be listing that 10 times in my controller.
Is there a nicer way of doing this?

A: I think you can initialize the Email property in your User model :
public string Email { get; set; } = "unchanged";

you can do it also in the default constructor .


Q: Execute SQL Task in TSQL I have multiple SQL tasks that execute stored procedures. I intend to call these SQL tasks in some other stored procedure. How do I do this ?
In these SQL tasks, all I have is exec sp statement.All these SQL tasks need to start in a stored procedure only.

A: You can't call individual SSIS tasks, but you can call an SSIS package from a stored procedure. The procedure so is not totally straight-forwards and I won't put instructions here, as there are many sites which do so.
However, if all these tasks do is call an SP, why not just call the sp?


Q: ARCore plugin for UE4 - repository doesn't exist? I wanted to download arcore plugin for unreal engine 4 but link provided in main page (link) of project settings for unreal doesn't exist. Who knows why? Or this is because of preview version of ARCore? Thanks :)

A: Did you tried to clone it ?
git clone -b 4.17-arcore-sdk-preview https://github.com/google-ar-unreal/UnrealEngine.git

A: That repository is actually private. So you cannot access/clone it. What you can do is fork the repository on the link you provided and then clone your fork.
Edit
So the guide here at time of writing is incorrect.
You have to follow the steps to become part of the Epic Organisation on github. When you follow these steps you'll see a private repos which you need to fork.
TL;DR: The clone command in the guide doesn't work now because the repository is private. Forking it works after become part of Epic organisation @ Github!


Q: Return newly allocated pointer or update the object through parameters? I'm actually working on pointers to user-defined objects but for simplicity, I'll demonstrate the situation with integers.
int* f(){
    return new int(5);
}

void f2(int* i){
    *i = 10;
}

int main(){

    int* a;
    int* b = new int();

    a = f();
    f2(b);

    std::cout << *a << std::endl;    // 5
    std::cout << *b << std::endl;    // 10

    delete b;
    delete a;
    return 0;
}

Consider that in functions f() and f2() there are some more complex calculations that determine the value of the pointer to be returned(f()) or updated through paramteres(f2()).
Since both of them work, I wonder if there is a reason to choose one over the other?

A: From looking at the toy code, my first thought is just to put the f/f2 code into the actual object's constructor and do away with the free functions entirely. But assuming that isn't an option, it's mostly a matter of style/preference. Here are a few considerations:
The first is easier to read (in my opinion) because it's obvious that the pointer is an output value. When you pass a (nonconst) pointer as a parameter, it's hard to tell at a glance whether it's input, output or both.
Another reason to prefer the first is if you subscribe to the school of thought that says objects should be made immutable whenever possible in order to simplify reasoning about the code and to preclude thread safety problems. If you're attempting that, then the only real choice is for f() to create the object, configure it, and return const Foo* (again, assuming you can't just move the code to the constructor).
A reason to prefer the second is that it allows you to configure objects that were created elsewhere, and the objects can be either dynamic or automatic. Though this can actually be a point against this approach depending on context--sometimes it's best to know that objects of a certain type will always be created and initialized in one spot.

A: If the allocation function f() does the same thing as new, then just call new.  You can do whatever initialisation in the object's construction.
As a general rule, try to avoid passing around raw pointers, if possible.  However that may not be possible if the object must outlive the function that creates it.
For a simple case, like you have shown, you might do something like this.
void DoStuff(MyObj &obj)
{
    // whatever
}

int Func()
{
    MyObj o(someVal);
    DoStuff(o);
    // etc
}

A: f2 is better only because the ownership of the int is crystal clear, and because you can allocate it however you want. That's reason enough to pick it.


Q: AVSampleBufferDisplayLayer not rendering frames anymore in iOS10 The following setup has been working on all recent iOS versions until iOS10:
I am using AVSampleBufferDisplayLayer to render raw frames from a custom source.
I have a pixel buffer pool set up using CVPixelBufferPoolCreate, and have the kCVPixelBufferIOSurfacePropertiesKey set to @{} as instructed by Apple.
I use CVPixelBufferPoolCreatePixelBuffer to obtain a pixel buffer from the pool and then copy my data to the buffer by using CVPixelBufferLockBaseAddress and CVPixelBufferUnlockBaseAddress.
My raw frames use the NV12 format kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange.
Here is a code snippet showing how I convert the pixel buffer to a CMSampleBufferRef and enqueue it to the display layer:
  CMSampleTimingInfo sampleTimeinfo{
      CMTimeMake(duration.count(), kOneSecond.count()),
      kCMTimeInvalid,
      kCMTimeInvalid};

  CMFormatDescriptionRef formatDescription = nullptr;
  CMVideoFormatDescriptionCreateForImageBuffer(nullptr, pixelBuffer, &formatDescription);

  CMSampleBufferRef sampleBuffer = nullptr;
  CMSampleBufferCreateForImageBuffer(
          nullptr, pixelBuffer, true, nullptr, nullptr, formatDescription, &sampleTimeinfo, &sampleBuffer));

  CFArrayRef attachmentsArray = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, YES);
  const CFIndex numElementsInArray = CFArrayGetCount(attachmentsArray);

  for (CFIndex i = 0; i < numElementsInArray; ++i) {
    CFMutableDictionaryRef attachments = (CFMutableDictionaryRef)CFArrayGetValueAtIndex(attachmentsArray, i);
    CFDictionarySetValue(attachments, kCMSampleAttachmentKey_DisplayImmediately, kCFBooleanTrue);
  }

  if ([avfDisplayLayer_ isReadyForMoreMediaData]) {
    [avfDisplayLayer_ enqueueSampleBuffer:sampleBuffer];
  }

  CFRelease(sampleBuffer);
  CFRelease(formatDescription);

pixelBuffer is of type CVPixelBufferRef, and avfDisplayLayer_ AVSampleBufferDisplayLayer.
This next snippet shows how I construct the display layer:
  avfDisplayLayer_ = [[AVSampleBufferDisplayLayer alloc] init];
  avfDisplayLayer_.videoGravity = AVLayerVideoGravityResizeAspectFill;

I am not getting any warning or error messages, the display layer status does not indicate a failure and isReadyForMoreMediaData is returning true.
The problem is that my frames do not show on the screen. I have also set a background color on the display layer, just to make sure the layer is composited correctly (which it is).
Something must have changed in iOS10 with regards to the AVSampleBufferDisplayLayer, but I am unable to figure out what it is.

A: It turns out that with iOS10, the values for CMSampleTimingInfo are apparently parsed more stringently.
The above code was changed to the following to make rendering work correctly once more:
  CMSampleTimingInfo sampleTimeinfo{
      CMTimeMake(duration.count(), kOneSecond.count()),
      kCMTimeZero,
      kCMTimeInvalid};

Please note the kCMTimeZero for the presentationTimeStamp field.
@Sterling Archer: You may want to give this a try to see if it addresses your problem as well.


Q: Project Euler N2 - Fibonacci algorithm isnt working properly
Each new term in the Fibonacci
  sequence is generated by adding the
  previous two terms. By starting with 1
  and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued
  terms in the sequence which do not
  exceed four million.

        Int64[] Numeros = new Int64[4000005];
        Numeros[0] = 1;
        Numeros[1] = 2;

        Int64 Indice = 2;
        Int64 Acumulador = 2;

        for (int i = 0; i < 4000000; i++)
        {
            Numeros[Indice] = Numeros[Indice - 2] + Numeros[Indice - 1];

            if (Numeros[Indice] % 2 == 0)
            {
                if ((Numeros[Indice] + Acumulador) > 4000000)
                {
                    break;
                }
                else
                {
                    Acumulador += Numeros[Indice];
                }
            }

            Indice++;
        }

        Console.WriteLine(Acumulador);
        Console.ReadLine();

My program isn't functioning as it should be I guess because on Project Euler they say my answer is incorrect. Maybe I'm overlooking something. Any help?

A: This line
if ((Numeros[Indice] + Acumulador) > 4000000)

is checking for the sum being greater than 4MM.  You need to check that the term (Numeros[Indice]) is greater than 4MM.  So changing that to this...
if (Numeros[Indice] > 4000000)

is probably a good place to start.

A: And also man your test condition in for loop is useless.. i wil never reach the value of 4000000.
simply a
while(1){
//code
}

will also do, no need of i as u never use it


Q: Nuxt SSR on plesk have to restart every ≈5minutes I have a server.js file who start my nuxt SSR website. First load of the website is a bit slow but it's ok. The time to start and finish the 'npm run start' command take around 8secs then the app is ready for every other users.
Around 5 minutes laters, if nobody come on the website, it's seems to go in standby...
New users will have to wait around 8 seconds, the time the 'npm run start' need to be ready again.
So my question, how can i keep my nuxt.js website awake so it nobody have to wait for the restart?
The server.js file is below.
I use plesk (windows).

const express = require("express");
const {
  loadNuxt
} = require("nuxt");
const config = require("./nuxt.config.js");

const app = express();

config.dev = false;
async function start() {
  const nuxt = await loadNuxt("start");
  app.use(nuxt.render);
  app.listen(process.env.PORT || 3000);
}
start();

A: Well, i solved my problem...
It was not a nuxt problem but a plesk/ IIS problem ( idle timeout iisnode exactly).
If you have similar issue, have a look at this page : iisnode making the node process always working


Q: Mobile Safari. Sudden movement in form inside of iframe I have a form inside of iframe.
I see the sudden movement of the viewport after I turn on the fields of this form by clicking on the arrows on the virtual keyboard IOS
I noticed this problem in mobile Safari(ios8), and only when the form in the frame.
The "Run code" button not visible if open stack-overflow in iOS, therefore link to working example in here.
Code snippets here:

.a { background-color: #f00 }
.b { background-color: #0f0 }
.c { background-color: #00f }
.d { background-color: #ff0 }
.e { background-color: #0ff }
.f { background-color: #f0f }
.g { background-color: #0a0 }
.h { background-color: #a00 }
.z { background-color: #00a }
<input class="a" placeholder="A" type="text">

<input class="b" placeholder="B" type="text">

<input class="c" placeholder="C" type="text">

<input class="d" placeholder="D" type="text">

<input class="e" placeholder="E" type="text">

<input class="f" placeholder="F" type="text">

<input class="g" placeholder="G" type="text">

<input class="h" placeholder="H" type="text">

<input class="z" placeholder="Z" type="text">

IT REPRODUCE ONLY IF THIS CODE OPEN IN IFRAME
To check this:

*

*open the website,

*click on the first field

*go through the fields by pressing on ">" button(on the virtual keyboard of ios).

After some pressing start twitching movement, and positioning of the screen in the wrong places.
Who faced? How to fix this bug with JS/CSS ?

A: This problem haven't solves for long time
discussions.apple.com/message/23671694

A: It is due to the scrollbar that appears on the iframe due to the length of the form in the viewport. If you do not have anything else on the page other than the iframe, turn the body's scroll bar off by using body { overflow: hidden }


Q: Difference between "Missing Reference Exception" and "Null Reference Exception" in Unity C# In the Unity manual there's an explanation for Null Reference Exceptions but not for Missing Reference Exceptions. Are there any differences?

A: NullReferenceException is thrown when you try to access member of a variable set to null.
MissingReferenceException is thrown when you try to access a GameObject that has been destroyed by some logic in your code.


Q: R Clusplot: How to represent clusters as numbers rather than shapes I want to plot my k means cluster on a 2d plot using clusplot(). However, the points are represented as different shapes on my plot (triangle, square, circle, etc) and it's not easy to see what each shape represents. Is there a way to either generate a legend or change the plot such that it's plotting the cluster assignment rather than a shape?
clusplot(data, myclus$cluster, color=TRUE, shade=TRUE, labels=2, lines=0)

A: get help from ?clusplot.default(), you can get more information,
you just need add a synatx in your command like this :
clusplot(data, myclus$cluster, color=TRUE, shade=TRUE, labels=2, lines=0, plotchar=FALSE),

the points will be  represented as same shapes on your plot !


Q: How to loop through a text file with lines consisting of multiple numbers, while counting the numbers The file looks something like:
John Smith
100 90 80 90
50 60 80 99 40 20

But there can be any number of people/grades in the file. I know how to loop through and get the first and last name of the person, but how can I loop through the first line of numbers, add them to their own total, then loop through the second line and add them to another total?
I've not found a way to check for the end of a line in Go, so I don't know how to distinguish the first line of numbers from the second line.
This is what I've tried:
package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
    //"unicode"
    //"container/list"
)

type Student struct {
    FirstName string
    LastName string
}

func main(){
    fmt.Println("What is the name of your file?\n")
    var filename string
    fmt.Scan(&filename)

    file, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanWords)
    //var scanCount int = 0
    //var studentCount = 1
    //var gradeSum = 0
    //var gradeAvg = 0

    var students [100]Student

    for scanner.Scan() {
        students[0].FirstName = scanner.Text()
        students[0].LastName = scanner.Text()
        fmt.Println(students[0].FirstName)

        //count ++

    }

}

This is what I have so far. Everything I've tried involving the numbers has not worked so I've removed it.

A: The easiest approach is to loop through the file by lines. Something like this:
package main

import (
    "bufio"
    "fmt"
    "log"
    "strconv"
    "strings"
)

type Student struct {
    FirstName string
    LastName  string
}

func main() {
    fmt.Println("What is the name of your file?\n") var filename string
    fmt.Scan(&filename)

    file, err := os.Open(filename)
    if err != nil {
     log.Fatal(err)
    }
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()
        if len(line) == 0 {
            // skip blank lines
            continue
        }
        if '0' <= line[0] && line[0] <= '9' {
            sum := 0
            for _, field := range strings.Fields(line) {
                n, err := strconv.Atoi(field)
                if err != nil {
                    log.Fatal(err)
                }
                sum += n
            }
            fmt.Println(sum)
        } else {
            fields := strings.Fields(line)
            if len(fields) != 2 {
                log.Fatal("don't know how to get first name last name")
            }
            fmt.Println("First:", fields[0], "Last:", fields[1])
        }
    }
    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

See it on the playgrOund.


Q: need group by data in mysql in mysql:
Have data in data:
ColA | ColB | Rank
1      2      0
1      3      1
2      1      0
3      1      0
3      2      1

Keeping Col A as key field, need to get data on base of highest rank i.e.,
output:
ColA | ColB | Rank
1      3      1
2      1      0
3      2      1

any ideas..

A: You can do it this way:
SELECT T1.ColA, T2.ColB, T1.Rank
FROM TableName T2 JOIN
(SELECT ColA,MAX(Rank) as Rank
FROM TableName
GROUP BY ColA) T1 ON T1.ColA=T2.ColA AND T1.Rank=T2.Rank

Explanation:

*

*Inner query (T1) selects records with highest rank for each values of ColA.

*Outer query (T2) is used to select ColB with respect to the values of ColA and Rank from T2.

Result:
ColA    ColB    Rank
--------------------
1       3       1
2       1       0
3       2       1

See result in SQL Fiddle


Q: server side includes: can I compute something inside a variable I'm trying to calculate the current index of my slides depending on the page that is shown.
So far I got this:
<!--#set var="page" value="0" -->
<!--#set var="slidesPerPage" value="4" -->

<!--#if expr="$QUERY_STRING = /p=1/" -->
  <!--#set var="page" value="1" -->
<!--#elif expr="$QUERY_STRING = /p=2/"  -->
  <!--#set var="page" value="2" -->
<!--#endif -->

Now I want to "calculate" the current index like this:
<!--#set var="currentIndex" value="${$page * $slidesPerPage + 1}" -->

But this doesn't work.
Is this even possible?

A: after poking around some more and trying things on my own, I found a "solution" that kind of works:
<!--#exec cmd="printf $(($page * $slidesPerPage + 1))" -->

This just prints the output to page and doesn't store it in a variable, but it's enough for me right now.
If someone has a better/nicer solution, please let me know.


Q: IOS UIWebview alternative - Does it have a webkit browser we can use as a webview different than Safari? I'm looking for an alternative for safari webview I could use like a UIWebview and to communicate with javascript of his webview.
Is it possible? Is Apple tolerant of this?

A: Your question touches on something deeply fundamental in Apple's entire iOS strategy:
At least not yet. Even Google had to rely on embedding the standard (albeit tweaked) UIWebView to implement Chrome for iOS. We can expect Apple to be very reluctant to allow this since allowing other web renderers (possibly even with alternative JS implementations, e.g. V8) kind of breaks Apple's monopoly on control of the development environment for iOS. Allowing an alternative would essentially mean allowing an alternative runtime getting a foothold on the platform.
Although me personally, I think they will have a hard time in the long run to keep this level of purity.

A: Although still inspired by Safari, starting from iOS8 there is WKWebView, a WebKit-based component that provides more powerful, higher-performance APIs than the older UIWebView.


Q: Verifiy if an xls file contains VBA macros without opening it in MS Excel I have a big set of .xls (Excel 97-2003 Workbook) files. A few of them contain VBA macros inside, I would like to find a way to filter them out automatically without opening them one by one in MS Excel.
There is an old post which is similar to my question, I have downloaded the OLE Doc viewer, but cannot open the .zip file, it seems that it is out of date...
Does anyone know if there is any API or tool to check if an .xls file contains VBA macros without opening it in MS Excel? In the first place, I don't bother to know the content of the macros.
PS: for a .xlsx or .xlsm file, we can change their file extension to .zip which contain some .xml files and eventually vbaProject.bin for VBA macros. However, this approach does not work for .xls file, renaming it does not make a valid .zipfile.

A: Here is a simple Python 2.7 solution I've cooked for you:
It depends only on the OleFileIO_PL module which is availble from the project page
The good thing with OleFile parser is that it is not aware of the "excel-specific" contents of the file ; it only knows the higher level "OLE storage". So it is quick in analyzing the file, and there is no risk that a potentially harmful macro would execute.
import OleFileIO_PL
import argparse

if __name__=='__main__':
    parser = argparse.ArgumentParser(description='Determine if an Excel 97-2007 file contains macros.', epilog='Will exit successfully (0) only if provided file is a valid excel file containing macros.')
    parser.add_argument('filename', help="file name to analyse")
    args=parser.parse_args()

    # Test if a file is an OLE container:
    if (not OleFileIO_PL.isOleFile(args.filename)):
        exit("This document is not a valid OLE document.")

    # Open an OLE file:
    ole = OleFileIO_PL.OleFileIO(args.filename)

    # Test if known streams/storages exist:
    if (not ole.exists('workbook')):
        exit("This document is not a valid Excel 97-2007 document.")

    # Test if VBA specific streams exist:
    if (not ole.exists('_VBA_PROJECT_CUR')):
        exit("This document does not contain VBA macros.")

    print("Valid Excel 97-2007 workbook WITH macros")

I tested it on a couple of files with success. Let me know if it's suitable for you


Q: How do I prevent Ace Editor from auto-completing as I type? I want the suggestion to show up only when I use Cntrl-Spacebar. Their documentation is a bit lacking.

A: You need to set these following variables :
enableBasicAutocompletion:true
enableLiveAutocompletion:false

for achieving auto-completion only on pressing Cntrl - Spacebar.
Check this snippet for live demo :

  var langTools = ace.require("ace/ext/language_tools");
  var editor = ace.edit("editor");
  editor.setOptions({
    enableBasicAutocompletion: true,
    enableLiveAutocompletion: false
  });

Type in a word like "will" below and press ctrl+space to get "auto completion"