text:
Q: Android Studio functions of alert dialog in another java class In my MainActivity.Java, I have an onClickListener in a button that will show an Alert Dialog when it's clicked
scanbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            View scanPopup = getLayoutInflater().inflate(R.layout.scan_tab, null);

            forScan.setView(scanPopup);
            dialog = forScan.create();
            dialog.show();

        }
    });

This is is the ScanTab.Java wherein the AlertDialog will have its functions
package com.example.AppDraft1.activity;

import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.AppDraft1.MainActivity;
import com.example.AppDraft1.R;
import com.example.AppDraft1.parser.NdefMessageParser;
import com.example.AppDraft1.record.ParsedNdefRecord;

import java.util.List;

public class ScanTab extends AppCompatActivity {

    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private TextView text;
    private String first, surname, id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scan_tab);
        text = (TextView) findViewById(R.id.text);
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);

        if (nfcAdapter == null) {
            Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        pendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, this.getClass())
                        .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null) {
            if (!nfcAdapter.isEnabled())
                showWirelessSettings();

            nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null){
            nfcAdapter.disableForegroundDispatch(this);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        resolveIntent(intent);
    }

    private void resolveIntent(Intent intent) {
        String action = intent.getAction();

        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs;

            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];

                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }

            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }

            displayMsgs(msgs);
        }
    }

    private void displayMsgs(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0)
            return;

        StringBuilder builder = new StringBuilder();
        List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
        final int size = records.size();

        for (int i = 0; i < size; i++) {
            ParsedNdefRecord record = records.get(i);
            String str = record.str();
            builder.append(str).append("\n");
        }

        text.setText(builder.toString());
        Toast.makeText(this, "NFC Tag Detected", Toast.LENGTH_SHORT).show();

        sndData();
    }
    public void sndData(){

        String theText = text.getText().toString();

        //split data
        String[] split = theText.split("/",3);
        first = split[0];     //first name
        surname = split[1];   //surname
        id = split[2];        //id number

        Intent intent = new Intent(ScanTab.this, MainActivity.class);
        intent.putExtra("FName", first);
        intent.putExtra("SName", surname);
        intent.putExtra("ID", id);
        startActivity(intent);
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
        startActivity(intent);
    }

    private String dumpTagData(Tag tag) {
        StringBuilder sb = new StringBuilder();
        byte[] id = tag.getId();
        sb.append("ID (hex): ").append(toHex(id)).append('\n');
        sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('\n');
        sb.append("ID (dec): ").append(toDec(id)).append('\n');
        sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('\n');

        String prefix = "android.nfc.tech.";
        sb.append("Technologies: ");
        for (String tech : tag.getTechList()) {
            sb.append(tech.substring(prefix.length()));
            sb.append(", ");
        }

        sb.delete(sb.length() - 2, sb.length());

        for (String tech : tag.getTechList()) {
            if (tech.equals(MifareClassic.class.getName())) {
                sb.append('\n');
                String type = "Unknown";

                try {
                    MifareClassic mifareTag = MifareClassic.get(tag);

                    switch (mifareTag.getType()) {
                        case MifareClassic.TYPE_CLASSIC:
                            type = "Classic";
                            break;
                        case MifareClassic.TYPE_PLUS:
                            type = "Plus";
                            break;
                        case MifareClassic.TYPE_PRO:
                            type = "Pro";
                            break;
                    }
                    sb.append("Mifare Classic type: ");
                    sb.append(type);
                    sb.append('\n');

                    sb.append("Mifare size: ");
                    sb.append(mifareTag.getSize() + " bytes");
                    sb.append('\n');

                    sb.append("Mifare sectors: ");
                    sb.append(mifareTag.getSectorCount());
                    sb.append('\n');

                    sb.append("Mifare blocks: ");
                    sb.append(mifareTag.getBlockCount());
                } catch (Exception e) {
                    sb.append("Mifare classic error: " + e.getMessage());
                }
            }

            if (tech.equals(MifareUltralight.class.getName())) {
                sb.append('\n');
                MifareUltralight mifareUlTag = MifareUltralight.get(tag);
                String type = "Unknown";
                switch (mifareUlTag.getType()) {
                    case MifareUltralight.TYPE_ULTRALIGHT:
                        type = "Ultralight";
                        break;
                    case MifareUltralight.TYPE_ULTRALIGHT_C:
                        type = "Ultralight C";
                        break;
                }
                sb.append("Mifare Ultralight type: ");
                sb.append(type);
            }
        }

        return sb.toString();
    }

    private String toHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = bytes.length - 1; i >= 0; --i) {
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    private String toReversedHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; ++i) {
            if (i > 0) {
                sb.append(" ");
            }
            int b = bytes[i] & 0xff;
            if (b < 0x10)
                sb.append('0');
            sb.append(Integer.toHexString(b));
        }
        return sb.toString();
    }

    private long toDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private long toReversedDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = bytes.length - 1; i >= 0; --i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;

    }
}

When I tested it, the view is working but the functions are absent. How do I embed or make the functions work in the AlertDialog?

A: Alert Dialogs are meant to 'alert' the user of something, or run code based on input from user in case of input dialog.
If you want to run code in the alert dialog, you can run it before setView of dialog.
Additionally it is not recommended to block user from interacting with app using an Alert Dialog.
If you want to run code from one activity in another, in your case run code in ScanActivity from MainActivity the best way I can think of is Activity RESULTS API which replaced StartActivityForResult [read here]
But I would just recommended you start ScanActivity and show the dialog from there, then you can easily call all methods of ScanActivity.


text:
Q: Use the principle of mathematical induction to prove [(1/2)+(1/2)+(1/3)+. . . (1/n)] ≤ (n/2)+1 for all n ϵ z+ Use the principle of mathematical induction to prove $$\left[\frac{1}{1}+ \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{n}\right] \leq \frac{n}{2} + 1~\text{for all}~n \in \mathbb{Z}^+$$
I have been trying to solve this however find myself getting stuck when I substitute $p_k$ back into the equation. This is my approach so far:
(1) If $n= 1$, LHS $= (1/1) = 1$ and RHS $= \frac{1}{2}+1 = \frac{3}{2}$
LHS $\leq$ RHS
$p_1$ is true
Assuming $p_k$ is true, $n = k$
$$\frac{1}{1} + \frac{1}{2} + \frac{1}{3} + \ldots + \frac{1}{k} \leq \frac{k}{2}+1$$
If $p_{k+1}$ is true, $n = k+1$
$$\frac{1}{1} + \frac{1}{2}+ \frac{1}{3} + \ldots + \frac{1}{k} + \frac{1}{k+1}  \leq \frac{k+1}{2} +1$$
Now LHS $\leq  \frac{k}{2}+1+ \frac{1}{k+1}$ [using $p_k$]
I don't really know what to do after this in terms of proving the sequence is less than or equal to $\frac{n}{2} + 1$?

A: You have to prove that if it is true for k, it is true fro k+1.
for k>1 let's assume that p[k] is true, then
(1/1)+(1/2)(1/3)...(1/k) ≤ (k/2)+1
we want to prove that p[k+1] is true in other words :
(1/1)+(1/2)+(1/3)...+(1/k)+(1/(k+1))≤(k+1)/2 +1
we have (k+1)/2 + 1 = k/2 + 1/2 + 1 = k/2 + 1 + 1/2
with p[k] we can write :
(1/1)+(1/2)(1/3)... + (1/k) + 1/(k+1) ≤ k/2 + 1 + 1/(k+1)
we also know that k>1 so 1/(k+1) < 1/2
so we have :
(1/1)+(1/2)(1/3)... + (1/k) + 1/(k+1) ≤ k/2 + 1 + 1/2
so we have proved p[k+1]

A: Since $\frac{1}{n+1}\leq \frac{1}{2}$,
$
\begin{align*}
\frac{1}{1} + \frac{1}{2} + \dots + \frac{1}{k} + \frac{1}{k+1} &\leq \frac{1}{1} + \frac{1}{2} + \dots + \frac{1}{k} + \frac{1}{2} \\
&=(\frac{k}{2}+1 )+\frac{1}{2}\\
&=\frac{k+1}{2}+1
\end{align*}$
The second to last line comes from the hypothesis which we assumed is valid for $n=k$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Refreshing a echoed PHP variable after jQuery AJAX success? I have a shopping cart in Codeigniter in which products are added to the cart using (jQuery) Ajax.  In the header of each page it displays the number of contents in the cart using
<?php echo $this->cart->total_items(); ?>

How can I update/refresh this variable when a product is added to the cart, as I am using AJAX to add products to the cart and thus the page isn't being reloaded when products are added.  It seems pointless to use AJAX to do asyncronous stuff if I have to reload the page to get the new number of total items from the server.
Many thanks.

A: You should be able to do this by making the element containing the Shopping Card Item Count easily addressable by JavaScript, so:
<?php echo $this->cart->total_items(); ?>

Then, as part of the AJAX Function you perform, have the response contain the revised value for the total items, and then have your function replace the content of this span with that value.

A: As I understood you, you need something to dynamically update your number of articles ?
You can use jQuery PeriodicalUpdater to update that number "every once in a while" ( point it to a script that returns the current number only, ofc ).

A: Don't think about PHP in this case — it's totally irrelevant. What you need to do is modify content of that element client-side. So if you have:

<?php /* ... */ ?>

Then in your AJAX success handler you should do something like:
$('#total_items').html('new item count');

A: First, you can update as many parts of the page as you want when you make a jQuery call. What is the format of the data that is being returned from the call? Lets say you are returning JSON, then the JSON string should include the total. Then in the callback of the AJAX call you can simply update the total count.


text:
Q: How to reduce the size of image in header of the pdf using itextsharp  public class itsEventsHandler : PdfPageEventHelper
         {
             PdfTemplate total;
             BaseFont helv;

             public override void OnEndPage(PdfWriter writer, Document document)
             {

iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg");
             JPG.ScalePercent(35f);
             JPG.SetAbsolutePosition(130f, 240f);

             iTextSharp.text.Image imgfoot = JPG;
                 //Header Image
                 iTextSharp.text.Image imghead = iTextSharp.text.Image.GetInstance("C:/Users/Public/Pictures/Sample Pictures/Penguins.jpg");

                 imgfoot.SetAbsolutePosition(0, 0);
                 imghead.SetAbsolutePosition(0, 0);
                 imgfoot.ScaleAbsolute(826, 1100);
                 PdfContentByte cbhead = writer.DirectContent;
                 PdfTemplate tp = cbhead.CreateTemplate(2480, 370); // units are in pixels but I'm not sure if thats the correct units
                 tp.AddImage(imghead);

                 PdfContentByte cbfoot = writer.DirectContent;
                 PdfTemplate tpl = cbfoot.CreateTemplate(2480, 664);
                 tpl.AddImage(imgfoot);
                 cbhead.AddTemplate(tp, 0, 715);

                 helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

                 /*PdfContentByte cb = writer.DirectContent;
                 cbfoot.SaveState();
                 document.SetMargins(35, 35, 100, 82);
                 cb.RestoreState();*/

                 //document.NewPage();
                 base.OnStartPage(writer, document);
             }

             public override void OnOpenDocument(PdfWriter writer, Document document)
             {
                 total = writer.DirectContent.CreateTemplate(100, 100);
                 total.BoundingBox = new iTextSharp.text.Rectangle(-20, -20, 100, 100);
                 helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
             }
         }

Code for creating header images; but images looks too big.tried to use a imgfoot.ScaleAbsolute(826, 1100); but dosent worked it result to image shows half.Please anyone help me to resolve.
...............................................................................................

A: Assuming that you are talking about imgHead, then you are creating an image with a width of 826 user units and a height of 1100 user units. You are then adding this image at position (0, 0) of a form XObject with a width of 2480 user units (that's sufficient) and a height of 370 user units (that's not sufficient for the height of the image which is 1100 user units).
You say that the image shows only half. To be correct: you have clipped the image to 33.6% of its height (370 / 1100). Change the height value of the Form XObject tp so that the image fits and you've solved your problem.
Also: user units aren't pixels! By default 1 user unit corresponds with 1 point.


text:
Q: If $\varphi$ is a linear functional, show that $\{\varphi\ge0\}^\circ=\{\varphi>0\}$ Let $E$ be a normed $\mathbb R$-vector space, $\varphi\in E'\setminus\{0\}$ and $H:=\{\varphi\ge0\}$.
I would like to show that $H^\circ=\{\varphi>0\}$ and $\partial H=\{\varphi=0\}$.
Should be trivial enough. It's clear that $H$ is closed and hence $\partial H=H\setminus H^\circ$. So, we only need to determine $H^\circ$.
Now, $\{\varphi>0\}=\varphi^{-1}((0,\infty))$ is open and contained in $H$. So, we only need to show that if $x\in\{\varphi=0\}$, it cannot be an interior point of $H$. I think the correct approach is to take an arbitrary $\varepsilon>0$ and show that $B_\varepsilon(x)$ contains a point not in $H$. But how do we do that?

A: If $\phi(x)$ is $0$ then $\phi[B(x, \delta)]$ is open and contains $0$ and so $B(x, \delta)$ contains points with $\phi(x) < 0$ for all $\delta>0$.


text:
Q: how we can prove that argument $P_1,P_2,...,P_n $? I ran into a one claims on LOGIC. how can add more direction or hint to me?

if we have an argument $P_1,P_2,...,P_n  $ such that $  n>3$ ($p_i$ is
  premise) why $P_1,P_2,....,P_n,P_1$ is necessarily be an argument?

A: Assuming I understood your question correctly:
Let $p,q$ be two propositions, then according to the simplification rule the proposition $(p\wedge q) \to p$ is a tautology. Therefore, $(p\wedge q) \Rightarrow p$ is a valid argument.
You can prove this rule using truth-tables, and then extend it to any finite number of propositions $p_i$ (induction).


text:
Q: ActiveRecord: Accessing owner association after building record Using Rails 2.3.14, I'm looking for way to access the owner of an ActiveRecord object after it was build (but before save) to get some values from the owner. Seems to be simple, but my approach always fires an unnecessary database query.
Example:
class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent

  def after_initialize
    self.some_value = parent.some_value
    # This fires an additional database query to get the parent
  end
end

parent = Parent.find(1)
# SELECT * FROM `parents` WHERE (`parents`.`id` = 1)

child = parent.children.build
# Same SELECT query is fired again, but of course not needed

I'm looking for a way to access the association object (here: parent) without doing an additional database access. How can this be done?

A: In Rails 3, there's a new option, :inverse_of, for belongs_to/has_many to do this, but not in Rails 2. Maybe you have to implement similar function by yourself.


text:
Q: conda install fails even i found the package by conda info package I am on windows using Anaconda with python 3.5, I want to install opencv3.1, so I found a channel called conda-forge has the opencv3.2 for my python version, but when I try to install it by:

conda install -c conda-forge opencv

I got error message:
Fetching package metadata .............
Solving package specifications: ....
UnsatisfiableError: The following specifications were found to be in conflict:
  - opencv -> jpeg 9*
  - opencv -> numpy 1.9*
  - opencv -> python 2.7*|3.4*
Use "conda info <package>" to see the dependencies for each package.

but when I do:

conda info opencv

there is an opencv for python3.5, why conda cannot find it?
opencv 3.1.0 np111py35_1
------------------------
file name   : conda-forge::opencv-3.1.0-np111py35_1.tar.bz2
name        : opencv
version     : 3.1.0
build number: 1
build string: np111py35_1
channel     : conda-forge
size        : 84.4 MB
arch        : x86_64
binstar     : {'owner_id': '5528f42ce1dad12974506e8d', 'package_id': '56feac4e676dfa6a0572551e', 'channel': 'main'}
fn          : opencv-3.1.0-np111py35_1.tar.bz2
has_prefix  : True
license     : BSD 3-clause
machine     : x86_64
md5         : 9ff21915905c36894059eaf8d6d554cc
operatingsystem: win32
platform    : win
priority    : 1
schannel    : conda-forge
subdir      : win-64
target-triplet: x86_64-any-win32
url         : https://conda.anaconda.org/conda-forge/win-64/opencv-3.1.0-np111py35_1.tar.bz2
dependencies:
    jpeg 9*
    libpng >=1.6.21,<1.7
    libtiff 4.0.*
    numpy 1.11*
    python 3.5*
    zlib 1.2.*

so I checked the env by conda list and I have:
λ conda list
# packages in environment at C:\Users\MPNV38\AppData\Local\Continuum\Anaconda3:
#
_license                  1.1                      py35_1
_nb_ext_conf              0.3.0                    py35_0
alabaster                 0.7.9                    py35_0
anaconda                  4.2.0               np111py35_0
anaconda-clean            1.0.0                    py35_0
anaconda-client           1.5.1                    py35_0
anaconda-navigator        1.3.1                    py35_0
argcomplete               1.0.0                    py35_1
astroid                   1.4.7                    py35_0
astropy                   1.2.1               np111py35_0
babel                     2.3.4                    py35_0
backports                 1.0                      py35_0
beautifulsoup4            4.5.1                    py35_0
bitarray                  0.8.1                    py35_1
blaze                     0.10.1                   py35_0
bokeh                     0.12.2                   py35_0
boto                      2.42.0                   py35_0
bottleneck                1.1.0               np111py35_0
bzip2                     1.0.6                    vc14_3  [vc14]
cffi                      1.7.0                    py35_0
chest                     0.2.3                    py35_0
click                     6.6                      py35_0
cloudpickle               0.2.1                    py35_0
clyent                    1.2.2                    py35_0
colorama                  0.3.7                    py35_0
comtypes                  1.1.2                    py35_0
conda                     4.2.9                    py35_0
conda-build               2.0.3                    py35_0
conda-env                 2.6.0                         0
configobj                 5.0.6                    py35_0
console_shortcut          0.1.1                    py35_1
contextlib2               0.5.3                    py35_0
cryptography              1.5                      py35_0
curl                      7.49.0                   vc14_0  [vc14]
cycler                    0.10.0                   py35_0
cython                    0.24.1                   py35_0
cytoolz                   0.8.0                    py35_0
dask                      0.11.0                   py35_0
datashape                 0.5.2                    py35_0
decorator                 4.0.10                   py35_0
dill                      0.2.5                    py35_0
docutils                  0.12                     py35_2
dynd-python               0.7.2                    py35_0
entrypoints               0.2.2                    py35_0
et_xmlfile                1.0.1                    py35_0
fastcache                 1.0.2                    py35_1
filelock                  2.0.6                    py35_0
flask                     0.11.1                   py35_0
flask-cors                2.1.2                    py35_0
freetype                  2.5.5                    vc14_1  [vc14]
get_terminal_size         1.0.0                    py35_0
gevent                    1.1.2                    py35_0
greenlet                  0.4.10                   py35_0
h5py                      2.6.0               np111py35_2
hdf5                      1.8.15.1                 vc14_4  [vc14]
heapdict                  1.0.0                    py35_1
icu                       57.1                     vc14_0  [vc14]
idna                      2.1                      py35_0
imagesize                 0.7.1                    py35_0
ipykernel                 4.5.0                    py35_0
ipython                   5.1.0                    py35_0
ipython_genutils          0.1.0                    py35_0
ipywidgets                5.2.2                    py35_0
itsdangerous              0.24                     py35_0
jdcal                     1.2                      py35_1
jedi                      0.9.0                    py35_1
jinja2                    2.8                      py35_1
jpeg                      8d                       vc14_2  [vc14]
jsonschema                2.5.1                    py35_0
jupyter                   1.0.0                    py35_3
jupyter_client            4.4.0                    py35_0
jupyter_console           5.0.0                    py35_0
jupyter_core              4.2.0                    py35_0
lazy-object-proxy         1.2.1                    py35_0
libdynd                   0.7.2                         0
libpng                    1.6.22                   vc14_0  [vc14]
libtiff                   4.0.6                    vc14_2  [vc14]
llvmlite                  0.13.0                   py35_0
locket                    0.2.0                    py35_1
lxml                      3.6.4                    py35_0
markupsafe                0.23                     py35_2
matplotlib                1.5.3               np111py35_0
menuinst                  1.4.1                    py35_0
mistune                   0.7.3                    py35_0
mkl                       11.3.3                        1
mkl-service               1.1.2                    py35_2
mpmath                    0.19                     py35_1
multipledispatch          0.4.8                    py35_0
nb_anacondacloud          1.2.0                    py35_0
nb_conda                  2.0.0                    py35_0
nb_conda_kernels          2.0.0                    py35_0
nbconvert                 4.2.0                    py35_0
nbformat                  4.1.0                    py35_0
nbpresent                 3.0.2                    py35_0
networkx                  1.11                     py35_0
nltk                      3.2.1                    py35_0
nose                      1.3.7                    py35_1
notebook                  4.2.3                    py35_0
numba                     0.28.1              np111py35_0
numexpr                   2.6.1               np111py35_0
numpy                     1.11.1                   py35_1
odo                       0.5.0                    py35_1
openpyxl                  2.3.2                    py35_0
openssl                   1.0.2j                   vc14_0  [vc14]
pandas                    0.18.1              np111py35_0
partd                     0.3.6                    py35_0
path.py                   8.2.1                    py35_0
pathlib2                  2.1.0                    py35_0
patsy                     0.4.1                    py35_0
pep8                      1.7.0                    py35_0
pickleshare               0.7.4                    py35_0
pillow                    3.3.1                    py35_0
pip                       8.1.2                    py35_0
pkginfo                   1.3.2                    py35_0
ply                       3.9                      py35_0
prompt_toolkit            1.0.3                    py35_0
psutil                    4.3.1                    py35_0
py                        1.4.31                   py35_0
pyasn1                    0.1.9                    py35_0
pycosat                   0.6.1                    py35_1
pycparser                 2.14                     py35_1
pycrypto                  2.6.1                    py35_4
pycurl                    7.43.0                   py35_0
pyflakes                  1.3.0                    py35_0
pygments                  2.1.3                    py35_0
pylint                    1.5.4                    py35_1
pyopenssl                 16.0.0                   py35_0
pyparsing                 2.1.4                    py35_0
pyqt                      5.6.0                    py35_0
pytables                  3.2.2               np111py35_4
pytest                    2.9.2                    py35_0
python                    3.5.2                         0
python-dateutil           2.5.3                    py35_0
pytz                      2016.6.1                 py35_0
pywin32                   220                      py35_1
pyyaml                    3.12                     py35_0
pyzmq                     15.4.0                   py35_0
qt                        5.6.0                    vc14_0  [vc14]
qtawesome                 0.3.3                    py35_0
qtconsole                 4.2.1                    py35_2
qtpy                      1.1.2                    py35_0
requests                  2.11.1                   py35_0
rope                      0.9.4                    py35_1
ruamel_yaml               0.11.14                  py35_0
scikit-image              0.12.3              np111py35_1
scikit-learn              0.17.1              np111py35_1
scipy                     0.18.1              np111py35_0
setuptools                27.2.0                   py35_1
simplegeneric             0.8.1                    py35_1
singledispatch            3.4.0.3                  py35_0
sip                       4.18                     py35_0
six                       1.10.0                   py35_0
snowballstemmer           1.2.1                    py35_0
sockjs-tornado            1.0.3                    py35_0
sphinx                    1.4.6                    py35_0
spyder                    3.0.0                    py35_0
sqlalchemy                1.0.13                   py35_0
statsmodels               0.6.1               np111py35_1
sympy                     1.0                      py35_0
tk                        8.5.18                   vc14_0  [vc14]
toolz                     0.8.0                    py35_0
tornado                   4.4.1                    py35_0
traitlets                 4.3.0                    py35_0
unicodecsv                0.14.1                   py35_0
vs2015_runtime            14.0.25123                    0
wcwidth                   0.1.7                    py35_0
werkzeug                  0.11.11                  py35_0
wheel                     0.29.0                   py35_0
widgetsnbextension        1.2.6                    py35_0
win_unicode_console       0.5                      py35_0
wrapt                     1.10.6                   py35_0
xlrd                      1.0.0                    py35_0
xlsxwriter                0.9.3                    py35_0
xlwings                   0.10.0                   py35_0
xlwt                      1.1.2                    py35_0
zlib                      1.2.8                    vc14_3  [vc14]

A: Please check the link here. As far as I understand, it is an issue related to the new version of anaconda. If you need to find a fast solution, you can simply create a virtual environment, activate the environment, and install opencv there.
The other solution is to simply use this command:
conda install -c menpo opencv3=3.1.0


text:
Q: onclick does not work reliably I have the following html. It is a pager which triggers actions on the server side using buttons with icons. The icons have an onclick event attached which is supposed to trigger a server URL (in the jsfiddle I am simply triggering an alert), like this:
<button class="btn bootstrap-button-margin-style force-height" type="button">

</button>

If you click around, you will notice that the alerts are not always shown (I would say they are just shown 60% of the times - I am using Chrome).

*

*Why is that?

*Is there a way to make the onclick event reliable?

*Is there a better alternative to onclick, so that the icons are triggering the corresponding server action in a reliable way?

A: You're adding onclick even to i tag which is only a part of button
You should add event to button object like
<button class="btn bootstrap-button-margin-style force-height" type="button" onclick="alert('step-forward');">

</button>

Fiddle Example http://jsfiddle.net/utku/wmcME/3/
For alternative i suggest using jQuery for better javascript experience

A: You have attached the onclick event to the icon, not the buttons. The alert appears 100% of the time when you click on the actual icon. The alert will not appear if you click on the button outside of the icon element.
Move the onclick event to the button element:
<button class="btn bootstrap-button-margin-style force-height" type="button" onclick="alert('step-forward');">

</button>

A better approach would be to decouple the JavaScript logic from your HTML markup. You can use a JavaScript selector to handle the click event in a separate JavaScript block.
<button id="btn-step-forward" class="btn">

</button>

Using jQuery:
$('#btn-step-foward').click(function(e) { alert('step-forward'); });


text:
Q: Reverse Engineer Code First after a database change all...
Is there a way of reverse engineering in code first if there has been a minor change by someone within SQL management studio.
The equivalent in the EDMX file would be when you double click on the edmx file and right click and update from the database and it updates your model.
the reason i ask is there is alot of sql changes through SQL management studios and I dont know how I would consistently update my model.
thanks

A: You can reverse engineer selected objects and then add them back to your models and context. https://msdn.microsoft.com/en-us/library/jj200620.aspx


text:
Q: Uwp Screen capture _framePool.FrameArrived not fired for Outlook I am trying to capture application screen shot, I made a test with Screen capture.
For this document, it works for webbrowser application like Edge, but, if I choose to capture the Outlook Application, it will fail with System.NullReferenceException.
The full test code is in Putting it all together
It seems it did not fire for "_framePool.FrameArrived"


text:
Q: How can I find the data which written with for loop in Flask I'm trying to make a database project using with MYSQL and I'm new in Flask. In this project, the user should be able to increase and decrease the number of the products in the database. I print the items in my product table with for loop. The problem is I couldn't select the item which the user selected.
Html:
{% for mydata in data %}

         {{ mydata[3] }}

        Number: <input class="numb" min="1" name="number" type="number">

        <input class="addbutton" type="submit" name="submit_button" value="Add">
        <input class="removebutton" type="submit" name="removebutton" value="Remove">

{% endfor %}

Flask:
@app.route('/mainpage', methods=['POST','GET'])
def mainpage():
    cursor.execute("SELECT * FROM product")
    fetchdata = cursor.fetchall()
    if request.method == 'POST':
        if request.form['submit_button'] == 'Add':
            number = request.form.get("number")
            print(number)
            return render_template('main.html', data=fetchdata)
    else:
        return render_template('main.html', data = fetchdata)

First, I wanted to see the number that the user has selected. So tried to print it but it prints null. As I said im new in flask, open for your suggestions.

A: Actually, the template contains a for loop for data.
In other words, the number field is not unique. So you need to modify the code. For example
{% for i in range(len(data)) %}

         {{ data[i][3] }}

        Number: <input class="numb" min="1" name="number{{i}}" type="number">

        <input class="addbutton" type="submit" name="submit_button" value="Add">
        <input class="removebutton" type="submit" name="removebutton" value="Remove">

{% endfor %}

Flask:
@app.route('/mainpage', methods=['POST','GET'])
def mainpage():
    cursor.execute("SELECT * FROM product")
    fetchdata = cursor.fetchall()
    if request.method == 'POST':
        if request.form['submit_button'] == 'Add':
            number = request.form.get("number1")
            print(number1)
            return render_template('main.html', data=fetchdata)
    else:
        return render_template('main.html', data = fetchdata)


text:
Q: How to layout exact number of elements in a row with a ConstraintLayout's Flow I need to layout a few pairs of title-value widgets, each pair being in a single row with title aligned to the start and value to the end of parent.
Items are hosted in a ConstraintLayout and I'd like to use Flow to align them in a desired way.
I tried to use Flow's app:flow_wrapMode="aligned", but it is not enough as I need to have each title in a new row.

A: What I needed was a flow_maxElementsWrap attribute:
<androidx.constraintlayout.helper.widget.Flow
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:constraint_referenced_ids="amountTitle,amount,deliveryTitle,delivery"
  app:flow_horizontalStyle="spread_inside"
  app:flow_maxElementsWrap="2"
  app:flow_wrapMode="aligned" />

<TextView
  android:id="@+id/amountTitle"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:text="@string/amount_title" />

<TextView
  android:id="@+id/amount"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="$3.00" />

<TextView
  android:id="@+id/deliveryTitle"
  android:layout_width="0dp"
  android:layout_height="wrap_content"
  android:text="@string/delivery_title" />

<TextView
  android:id="@+id/delivery"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="$1.00" />


text:
Q: How to save python file in jupyter note if path contains spaces %20 When I try to save a file in a jupyter notebook I get an error saying there is no file or directory.
Error Message ___________________________________________________________
Unexpected error while saving file: OneDrive%%20-%%20Files/Desktop/PythonProjects/bhp.ipynb [Errno 2] No such file or directory: 'C:\Users\username\OneDrive%%20-%%20Files\Desktop\PythonProjects\bhp.ipynb'
I began having this problem after a software update where now I can only save things to "OneDrive - Files".  Unfortunately, the path to OneDrive contains several spaces - causing this error every time I try to save a new file.  I would use a different directory if I could.  I was hoping for an easy fix like wrapping the path in quotes - but so far this didn't work.

A: Replacing the %20 characters with a literal space resolved the issue.  I suppose the Jupyter Notebook treats the path the same way as a url and inserts %20 characters for spaces.  But when saving to a directory on a pc - the %20 characters can be replaced with a space - without the need to wrap the path in quotations or to place backslashes before the spaces.


text:
Q: How to add two arrays in Java in parallel manner? For example, there are two huge (length 2-3 million) of the array float [] or double []. Need them very quickly add up. How to do it? Are there any libraries for this?

A: Employ a fixed thread-pool with the number of threads equaling the number of processor cores. Submit as many tasks as there are threads. Each task receives its index range it needs to sum. In the main thread collect the results from all Futures returned to you from ExecutorService.submit and sum them up to the final result.

A: One approach can be to decide a splitting of the array, and let N threads read specified parts of array and find individual sums. A final thread can then add up all these individual sums for final output.

A: I've not had to do much truly high-performance coding but there isn't really a lot of room for optimization here (unless I'm being naive) except to divide the list into n segments (1 for each core) and have each core come up with a subtotal and add the subtotals up.  Now if you were being asked to multiply the values, as soon as a worker encounters a 0, you have your answer.
public class ArrayAdder {
    public double getTotal(double[] array) {
        Worker workers[] = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length - 1;i++) {
            workers[i] = new Worker(array,
                    i * array.length / workers.length,
                    (i + 1) * array.length / workers.length);
        }
        workers[workers.length - 1] = new Worker(array,
                (workers.length - 1) * array.length / workers.length,array.length);
        double total = 0;
        for (int i = 0;i < workers.length;i++) {
            try {
                workers[i].join();
                total += workers[i].getSum();
            } catch (InterruptedException e) {
                i--; //retry the wait for worker[i]
            }

        }
        return total;

    }
    static class Worker extends Thread {
        public Worker(double[] array, int start, int end) {
            super();
            this.array = array;
            this.start = start;
            this.end = end;
            start();
        }
        private double[] array;
        private int start;
        private int end;
        private double sum;
        @Override
        public void run() {
            for (int i=start;i < end;i++) {
                sum += array[i];
            }

        }
        public double getSum() { return sum; }
    }
}

You might want to store the subtotals and total as a BigDecimal depending on how large you expect the values to be.  Of course, unless you need an exact answer, adding them up as ints/longs would be much faster - obviously you'd want to round and not just cast or just cast (which may be faster) and assume you answer will be low by ~ array.length / 2 as half the time, the cast will "round" it in the incorrect direction.

A: Use the Fork/Join framework in Java7.

A: Another possible optimisation might be to try to use the superscalar abilities of your CPU by partially unrolling your loop.
For instance, on an architecture (and if the JVM is intelligent) with a pipeline size of four ints, you could write :
for(int i = 0; i < array.size(); i += 4)
{
    c[i] = a[i] + b[i];
    c[i+1] = a[i+1] + b[i+1];
    c[i+2] = a[i+2] + b[i+2];
    c[i+3] = a[i+3] + b[i+3];
}

But you have to write different code for every different architecture pipeline size.


text:
Q: Why is my html getting mal-formed? I have the following table in a form that's embedded in a formtastic form (semantic_form_for).  Everything I ask to be generated by ruby shows up, but the table gets badly mangled (essentially, the  tags NEVER get formed.
The table headers get drawn correctly
There are 14 available_date objects that get passed, and they alternate between having a time value of 1 or 2, so this is just terribly boggling, but probably simple to fix...

        Date
        Early
        Late

    <% f.fields_for :available_dates do |ad| %>
        <% if ad.object.time == 1  #if this is an early shift, then start the new row %>

<%= ad.object.date.strftime('%a, %b %d, %Y') %>
                <%= ad.collection_select(:availability , LookupAvailability.all.collect, :id, :name) %>
        <% else #otherwise end the row with just a box%>
            <%= ad.collection_select(:availability , LookupAvailability.all.collect, :id, :name) %>

        <% end %>
    <% end %>

So like I said, the form functions properly, and the objects all get updated and displayed correctly and all that, it's just that the HTML isn't getting echo'd out properly so my table is all mangled.  Help!

A: Try this:
<% f.fields_for :available_dates do |ad| %>

    <% if ad.object.time == 1  #if this is an early shift, then start the new row %>
      <%= ad.object.date.strftime('%a, %b %d, %Y') %>
      <%= ad.collection_select(:availability , LookupAvailability.all.collect, :id, :name) %>
    <% else #otherwise end the row with just a box%>
      <%= ad.collection_select(:availability , LookupAvailability.all.collect, :id, :name) %>

    <% end %>

<% end %>

I changed
 and
 positions and added 	 to add empty table cell.

A: You close your tr tag only in the else branch. Would make sense to close it after the if-else.

A: Are you using ruby 1.8.7?
If so, try to remove the comments next to the if and else lines. On erb, the only valid syntax  for comments is <%# this is a comment %>. That is, the "#" should be at the beginning, right after the "<%", not after an instruction. On ruby 1.8.7, it crashes randomly, mangling the rendered html.


text:
Q: CSS gradient to create two different color design I am trying to create a specific shape with specific color to keep it as a background. I successfully created gradient color that I want but I am struggling with getting shape right.
Here is what I have done and what is am trying to achieve,
My Work :

Expectation :

Code :

.grad {
  height: 400px;
  width: 900px;
  background: linear-gradient(110deg, #62e6a5 50%, #9ae7ba 50%, #9ae7ba 52%, #d1f5de 52%, #d1f5de 0);
}

I am open to use any other method as long as it is only one 'div'. I don't want to use two different div which are causing many issues in responsive design. I tried using clip-path but that too did not help because of the nature of the design.
Any help would be appreciated.

A: Use multiple gradient then adjust dimension and position to obtain what you want:

.grad {
  height: 100px;
  width: 300px;
  background:
  linear-gradient(110deg, #62e6a5 50%, #9ae7ba 50%, #9ae7ba 52%, #d1f5de 52%, #d1f5de 0) 0 0/100% calc(100% - 10px) no-repeat,
  linear-gradient(110deg, #62e6a5 52%, transparent 0) 0 100%/100% 100% no-repeat;
}

A: Use pseudo-elements like :before and :after

.grad{
  position: relative;
  height:200px;
  width:450px;
  margin-bottom: 10px;
  background: linear-gradient(110deg, #62e6a5 50%, #9ae7ba 50%, #9ae7ba 52%, #d1f5de 52%, #d1f5de 0);
}

.grad-new{
  position: relative;
  height:200px;
  width:450px;
  margin-bottom: 10px;
  overflow: hidden;
  background: linear-gradient(110deg, #62e6a5 50%, #9ae7ba 50%, #9ae7ba 52%, #d1f5de 52%, #d1f5de 0);
}

.grad-new:before{
  content: '';
  position: absolute;
  width: 3%;
  height: 10px;
  bottom: 0;
  right: 55.6%;
  background: #62e6a5;
  transform: skew(-20deg);
}
.grad-new:after{
  content: '';
  position: absolute;
  width: 100%;
  height: 10px;
  bottom: 0;
  left: 44.4%;
  background: #fff;
  transform: skew(-20deg);
}


text:
Q: saving data points when picking from a plot I want to select some points from a plot. I am using event picking and I want to store the data points that I select to numpy array. There is no problem about selecting points. I will select them and I can see those points in output (by printing command in function). The problem is that I don't know how to save these selected points, so that I can use them later. I am using global variable, but noting is saved to them after selecting data points when I print them independently. These data points are added to an array for each click (I know this from print command in each function calling), but it seems that when I print the array myself, they are empty. Any help appreciated!
import numpy as np
import matplotlib.pyplot as plt

    x= np.random.rand(10, 100)
    y = np.random.rand(10, 100)
    # the selected data
    diy_pick_x = np.zeros(0)
    diy_pick_y = np.zeros(0)

    a= np.zeros(0)
    b = np.zeros(0)

    fig, ax = plt.subplots()
    col = ax.scatter(x, y, 0.3, picker=True)

    plt.xlabel('Wavelength '+r'[${\rm \AA}$]')
    plt.ylabel('Flux '+r'[${\rm 10^{-17} erg  s^{-1}  \AA^{-1}}$]')

    def onpick(event):
        global diy_pick_x,  diy_pick_y
        global a, b
        ind = event.ind
        print("onpick scatter:", ind, np.take(x, ind), np.take(y, ind))
        diy_pick_x = np.append(diy_pick_x, np.take(x, ind))
        diy_pick_y = np.append(diy_pick_y, np.take(y, ind))
        a=diy_pick_x
        print(diy_pick_x)
        print(diy_pick_y)

    fig.canvas.mpl_connect('pick_event', onpick)

When I print the array, this is the result:
    print(diy_pick_x)

    Out[6]: array([], dtype=float64)

A: As mentioned in the comments, updating Python addressed the issue.
Another method which may work is use list mutability instead of global numpy arrays. This method works because the original lists still exist, and we can change their content without changing the "id" of the original list. If we were to reassign the list like with "diy_pick_x = [new items]" then we are making a new list that happens to have the same name, but does not exist outside of the onpick function.
Reviewing objects in python that are mutable may help with understanding.
import matplotlib.pyplot as plt
import numpy as np

x = np.random.rand(10, 100)
y = np.random.rand(10, 100)
# the selected data
diy_pick_x = [0] # <----- Changed
diy_pick_y = [0] # <----- Changed

a = np.zeros(0)
b = np.zeros(0)

fig, ax = plt.subplots()
col = ax.scatter(x, y, 0.3, picker=True)

plt.xlabel("Wavelength " + r"[${\rm \AA}$]")
plt.ylabel("Flux " + r"[${\rm 10^{-17} erg  s^{-1}  \AA^{-1}}$]")

def onpick(event):
    global a, b
    ind = event.ind
    print("onpick scatter:", ind, np.take(x, ind), np.take(y, ind))

    # ----------- Changed -----------
    # Loop through each point index found by the event
    for i in ind:
        # Append each point to the lists
        # Note that this changes the lists, but does not reassign them
        diy_pick_x.append(np.take(x, i))
        diy_pick_y.append(np.take(y, i))

    a = diy_pick_x
    print(diy_pick_x)
    print(diy_pick_y)

fig.canvas.mpl_connect("pick_event", onpick)
plt.show() # <----- Changed

diy_pick_x = np.array(diy_pick_x) # <----- Changed
diy_pick_y = np.array(diy_pick_y) # <----- Changed

print(diy_pick_x) # <----- Changed


text:
Q: React router dom not redirect correctly That's my code, when i try to go in / or /home the components are rendered, but when i want to go in /login or /contacts it doesn't render, i don't know where is the problem, can someone help me?
 import React, { Component } from "react"
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import ContentInfo from './components/Card/Card';
import LoginCard from './components/LoginCard/LoginCard';
import ContactsCard from './components/ContactsCard/ContactsCard';
import RegisterCard from './components/RegisterCard/RegisterCard';
import {Root} from './components/Root';
import {HomeRoot} from './components/HomeRoot';
import Panel from './components/Panel/Panel';
import './components/particles.css';

class App extends Component {

  render(){
    return (
      <Router>
            <Switch>
              <Route path={"/"} exact>
                <Root>
                  <Route component={ContentInfo} />
                  <Route path={"/login"} exact component={LoginCard} />
                  <Route path={"/contacts"} component={ContactsCard} />
                  <Route path={"/register"} component={RegisterCard} />
                </Root>
              </Route>
              <Route path={"/home"}>
                <Switch>
                  <HomeRoot>
                    <Route component={Panel} />
                  </HomeRoot>
                </Switch>
              </Route>
            </Switch>
      </Router>
    );
  }
}

export default App;

A: From our comment conversation if I understand correctly you are looking to do the following:
import { useLocation } from 'react-router-dom'

.
.
.

const location = useLocation()

return (
<Router>
        <Switch>
           {location.pathname === '/home' ? <HomeRoot /> : <Root />}
           <Route exact path={"/"} component={ContentInfo} />
           <Route path={"/login"}  component={LoginCard} />
           <Route path={"/contacts"} component={ContactsCard} />
           <Route path={"/register"} component={RegisterCard} />
           <Route path={"/home"} component={Panel}>
          </Route>
        </Switch>
  </Router>
)


text:
Q: Call jQuery Ajax Request Each X Minutes How can I call an Ajax Request in a specific time Period?
Should I use Timer Plugin or does jQuery have a plugin for this?

A: you can use setInterval() in javascript
<script>
//Call the yourAjaxCall() function every 1000 millisecond
setInterval("yourAjaxCall()",1000);
function yourAjaxCall(){...}
</script>

A: No plugin required. You can use only jquery.
If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );

A: You have a couple options, you could setTimeout() or setInterval().  Here's a great article that elaborates on how to use them.
The magic is that they're built in to JavaScript, you can use them with any library.

A: use jquery Every time Plugin  .using this you can do ajax call for "X" time period
$("#select").everyTime(1000,function(i) {
//ajax call
}

you can also use setInterval

A: You can use the built-in javascript setInterval.
var ajax_call = function() {
  //your jQuery ajax code
};

var interval = 1000 * 60 * X; // where X is your every X minutes

setInterval(ajax_call, interval);

or if you are the more terse type ...
setInterval(function() {
  //your jQuery ajax code
}, 1000 * 60 * X); // where X is your every X minutes

A: A bit late but I used jQuery ajax method. But I did not want to send a request every second if I haven't got the response back from the last request, so I did this.
function request(){
            if(response == true){
                // This makes it unable to send a new request
                // unless you get response from last request
                response = false;
                var req = $.ajax({
                    type:"post",
                    url:"request-handler.php",
                    data:{data:"Hello World"}
                });

                req.done(function(){
                    console.log("Request successful!");

                    // This makes it able to send new request on the next interval
                    response = true;
                });
            }

            setTimeout(request(),1000);
        }

        request();

A: I found a very good jquery plugin that can ease your life with this type of operation. You can checkout https://github.com/ocombe/jQuery-keepAlive.
$.fn.keepAlive({url: 'your-route/filename', timer: 'time'},       function(response) {
        console.log(response);
      });//

A: Instead of having an absolute repeating timer, you should call the function after completing the initial request (like a recursive function).
This ensures that requests will be sent only after completing the previous one. This avoids the issues like queuing up of requests and thereby Denial of Service.
(function ajaxRequest() {
  $.ajax('url_of_your_application.php', {
    type: 'post',
    data: {
      phone: '1234567890',
    },
  })
    .done(function (data) {
      // Do whatever you want with the data.
    })
    .always(function (data) {
      // We are starting a new timer only AFTER COMPLETING the previous request.
      setTimeout(ajaxRequest, 5000);
    });
})();


text:
Q: What is the correct way to destroy the CMFCMenuBar and CMFCToolBar and recreate them? I wanted to change a MFC app to be per-monitor aware. Most things work fine but the menu and tool bars don't.  I'd like to simple recreate them presumably picking up the current DPI. I basically tried:
  if (m_wndToolBar.GetSafeHwnd()) {
    m_wndToolBar.DestroyWindow();
  }

  if (m_wndMenuBar.GetSafeHwnd()) {
    m_wndMenuBar.DestroyWindow();
  }

followed by the normal create process but on m_wndMenuBar.Create() it asserts.
This is where it fails inside the m_wndMenuBar.Create(this)
if (!CMFCBaseToolBar::Create(
        GetGlobalData()->RegisterWindowClass(_T("Afx:ToolBar")), dwStyle, rect, pParentWnd, nID, 0))
    {
        return FALSE;
    }

A: Assuming your main window is derived from CFrameWnd, you can reload the menu-bar from the application's resources, which should reset it (where resource is the ID for the main menu and accelerator table):
    CMyFrameWnd *pFrame = dynamic_cast<CMyFrameWnd*>(AfxGetApp()->AfxGetMainWnd());
    if (pFrame && pFrame->IsWindowEnabled())) {
        HMENU defMenu = LoadMenu(AfxGetInstanceHandle(), MAKEINTRESOURCE(resource));
        pFrame->m_wndMenuBar.CreateFromMenu(defMenu, TRUE, TRUE);
        pFrame->LoadAccelTable(MAKEINTRESOURCE(resource));
    }

You can probably do a similar operation on the toolbar(s), using the CMFCToolBar::LoadToolBar(), member, but I haven't used or tested that function.

A: To handle DPI Scaling in per-monitor mode.  This seems to work for the default menubar and toolbar.
  class CCustomMFCToolBar : public CMFCToolBar
  {
    public:
    BOOL FullRestoreOriginalState()
    {
      // ensure restore original
        if (m_uiOriginalResID == 0)
        {
            return FALSE;
        }

      // remove existing images
      ResetAllImages();

      // reset id so bitmaps are loaded again
      UINT resid=m_uiOriginalResID;
      m_uiOriginalResID=0;

      // handle loading toolbar and bitmaps
        BOOL bRes = LoadToolBar(resid);

        AdjustLayout();

        if (IsFloating())
        {
            RecalcLayout();
        }
        else if (m_pParentDockBar != NULL)
        {
            CSize sizeCurr = CalcFixedLayout(FALSE, IsHorizontal());
            CRect rect;
            GetWindowRect(rect);

            if (rect.Size() != sizeCurr)
            {
                SetWindowPos(NULL, 0, 0, sizeCurr.cx, sizeCurr.cy, SWP_NOMOVE  | SWP_NOACTIVATE | SWP_NOZORDER);
                UpdateVirtualRect();
            }
            m_pDockBarRow->ArrangePanes(this);
            AFXGetParentFrame(this)->RecalcLayout();
        }

        RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);

        return bRes;
    }

  };

Catch the DPI Change here or all items set back to restart since WM_SETTINGCHANGED is called after WM_DPICHANGED
void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
  CFrameWndEx::OnSettingChange(uFlags, lpszSection);
  g_DPIHelper.SetChangedScaleForWindow(m_hWnd);

  struct GlobalDataUnprotect : AFX_GLOBAL_DATA
  {
    #define AFX_FONT_NAME_OFFICE       _T("Tahoma")
    #define AFX_FONT_NAME_OFFICE_2007  _T("Segoe UI")
    #define AFX_FONT_NAME_DEFAULT      _T("MS Sans Serif")
    #define AFX_FONT_NAME_VERT         _T("Arial")
    #define AFX_FONT_NAME_MARLETT      _T("Marlett")

     // This is a copy of UpdateFonts() modified a couple places to
     // set the correct / changed scaling.

    static int CALLBACK FontFamilyProcFonts(const LOGFONT FAR* lplf, const TEXTMETRIC FAR* lptm, ULONG ulFontType, LPARAM lParam)
    {
        ENSURE(lplf != NULL);
        ENSURE(lParam != NULL);

        CString strFont = lplf->lfFaceName;
        return strFont.CollateNoCase((LPCTSTR) lParam) == 0 ? 0 : 1;
    }

    void UpdateScaledFonts()
    {
        CWindowDC dc(NULL);

        m_dblRibbonImageScale = static_cast<double>(g_DPIHelper.GetScale())/100.0;

        if (m_dblRibbonImageScale > 1. && m_dblRibbonImageScale < 1.1)
        {
            m_dblRibbonImageScale = 1.;
        }

        if (fontRegular.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontRegular.Detach());
        }

        if (fontTooltip.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontTooltip.Detach());
        }

        if (fontBold.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontBold.Detach());
        }

        if (fontDefaultGUIBold.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontDefaultGUIBold.Detach());
        }

        if (fontUnderline.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontUnderline.Detach());
        }

        if (fontDefaultGUIUnderline.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontDefaultGUIUnderline.Detach());
        }

        if (fontVert.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontVert.Detach());
        }

        if (fontVertCaption.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontVertCaption.Detach());
        }

        if (fontMarlett.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontMarlett.Detach());
        }

        if (fontSmall.GetSafeHandle() != NULL)
        {
            ::DeleteObject(fontSmall.Detach());
        }

        // Initialize fonts:

        NONCLIENTMETRICS info;
        info.cbSize = sizeof(info);
        GetNonClientMetrics (info);

        LOGFONT lf;
        memset(&lf, 0, sizeof(LOGFONT));

        lf.lfCharSet = (BYTE) GetTextCharsetInfo(dc.GetSafeHdc(), NULL, 0);

        lf.lfHeight = info.lfMenuFont.lfHeight;
        lf.lfWeight = info.lfMenuFont.lfWeight;
        lf.lfItalic = info.lfMenuFont.lfItalic;

        //------------------
        // Adjust font size:
        //------------------
        int nFontHeight = lf.lfHeight < 0 ? -lf.lfHeight : lf.lfHeight;
        if (nFontHeight <= 12)
        {
            nFontHeight = 11;
        }
        else if (!m_bDontReduceFontHeight)
        {
            nFontHeight--;
        }

        lf.lfHeight = (lf.lfHeight < 0) ? -nFontHeight : nFontHeight;

      lf.lfHeight=g_DPIHelper.ScaleNonClientMetricsFont(lf.lfHeight);

        // Check if we should use system font
        lstrcpy(lf.lfFaceName, info.lfMenuFont.lfFaceName);

        BOOL fUseSystemFont = m_bUseSystemFont || (info.lfMenuFont.lfCharSet > SYMBOL_CHARSET);
        if (!fUseSystemFont)
        {
            // Check for "Segoe UI" or "Tahoma" font existance:
            if (::EnumFontFamilies(dc.GetSafeHdc(), NULL, FontFamilyProcFonts, (LPARAM)(LPCTSTR) AFX_FONT_NAME_OFFICE_2007) == 0)
            {
                // Found! Use MS Office 2007 font!
                lstrcpy(lf.lfFaceName, AFX_FONT_NAME_OFFICE_2007);
          lf.lfQuality=5; // CLEARTYPE_QUALITY;
            }
            else if (::EnumFontFamilies(dc.GetSafeHdc(), NULL, FontFamilyProcFonts, (LPARAM)(LPCTSTR) AFX_FONT_NAME_OFFICE) == 0)
            {
                // Found! Use MS Office font!
                lstrcpy(lf.lfFaceName, AFX_FONT_NAME_OFFICE);
            }
            else
            {
                // Not found. Use default font:
                lstrcpy(lf.lfFaceName, AFX_FONT_NAME_DEFAULT);
            }
        }

        fontRegular.CreateFontIndirect(&lf);

        // Create small font:
        LONG lfHeightSaved = lf.lfHeight;

        lf.lfHeight = (long)((1. + abs(lf.lfHeight)) * 2 / 3);
        if (lfHeightSaved < 0)
        {
            lf.lfHeight = -lf.lfHeight;
        }

        fontSmall.CreateFontIndirect(&lf);
        lf.lfHeight = lfHeightSaved;

        // Create tooltip font:
        NONCLIENTMETRICS ncm;
        ncm.cbSize = sizeof(ncm);
        GetNonClientMetrics (ncm);

        lf.lfItalic = ncm.lfStatusFont.lfItalic;
        lf.lfWeight = ncm.lfStatusFont.lfWeight;
        fontTooltip.CreateFontIndirect(&lf);

        lf.lfItalic = info.lfMenuFont.lfItalic;
        lf.lfWeight = info.lfMenuFont.lfWeight;

        // Create "underline" font:
        lf.lfUnderline = TRUE;
        fontUnderline.CreateFontIndirect(&lf);
        lf.lfUnderline = FALSE;

        // Create bold font:
        lf.lfWeight = FW_BOLD;
        fontBold.CreateFontIndirect(&lf);

        // Create Marlett font:
        BYTE bCharSet = lf.lfCharSet;
        lf.lfWeight = info.lfMenuFont.lfWeight;
        lf.lfCharSet = SYMBOL_CHARSET;
        lf.lfWeight = 0;
      lf.lfHeight=g_DPIHelper.ScaleNonClientMetricsFont(::GetSystemMetrics(SM_CYMENUCHECK) - 1);
        lstrcpy(lf.lfFaceName, AFX_FONT_NAME_MARLETT);

        fontMarlett.CreateFontIndirect(&lf);
        lf.lfCharSet = bCharSet; // Restore charset

        // Create vertical font:
        CFont font;
        if (font.CreateStockObject(DEFAULT_GUI_FONT))
        {
            if (font.GetLogFont(&lf) != 0)
            {
                lf.lfOrientation = 900;
                lf.lfEscapement = 2700;

          lf.lfHeight = g_DPIHelper.ScaleNonClientMetricsFont(info.lfMenuFont.lfHeight);
                lf.lfWeight = info.lfMenuFont.lfWeight;
                lf.lfItalic = info.lfMenuFont.lfItalic;

                {
                    lstrcpy(lf.lfFaceName, AFX_FONT_NAME_VERT);
                }

                fontVert.CreateFontIndirect(&lf);

                lf.lfEscapement = 900;
                fontVertCaption.CreateFontIndirect(&lf);
            }
        }

        // Create dialog underline and bold fonts:
        CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
        ASSERT_VALID(pDefaultGUIFont);
        pDefaultGUIFont->GetLogFont(&lf);

        lf.lfUnderline = TRUE;
        fontDefaultGUIUnderline.CreateFontIndirect(&lf);
        lf.lfUnderline = FALSE;

        lf.lfWeight = FW_BOLD;
        fontDefaultGUIBold.CreateFontIndirect(&lf);

        UpdateTextMetrics();

      extern CObList afxAllToolBars;

        // Notify toolbars about font changing:
        for (POSITION posTlb = afxAllToolBars.GetHeadPosition(); posTlb != NULL;)
        {
            CMFCToolBar* pToolBar = (CMFCToolBar*) afxAllToolBars.GetNext(posTlb);
            ENSURE(pToolBar != NULL);

            if (CWnd::FromHandlePermanent(pToolBar->m_hWnd) != NULL)
            {
                ASSERT_VALID(pToolBar);
                pToolBar->OnGlobalFontsChanged();
            }
        }
    }

  };

  GlobalDataUnprotect *globaldata=reinterpret_cast<GlobalDataUnprotect*>(GetGlobalData());
  globaldata->UpdateScaledFonts();

  m_wndToolBar.CleanUpLockedImages();
  m_wndToolBar.FullRestoreOriginalState();

}


text:
Q: Why is there such a large difference in efficiency in these two boost converter configurations?

Here is the datasheet
I realize that the converter has to "work harder" to boost a voltage from 2.8V-6V to 48V than it does from 8V-38V to 48V, but I'm curious why there's such a significant drop in the efficiency in the first configuration below 10mA when there isn't a similar drop in the lower configuration. Do boost converters have a certain attribute that doesn't allow high efficiency at low currents? Are some boost converters designed to maximize the efficiency at high boost voltages and low currents?

A: I'm going to call the lower input voltage range but less efficiency circuit, circuit A.
I'm going to call the more efficient configuration, circuit B.
Note that both circuits are actually the same, only some component values are different:

*

*The inductor L1: 0.33 uH (circuit A) vs 6.8 uH (circuit B)

*The RC network connected to the Vc pin

These two changes are relates, the RC network on the Vc pin influences the voltage regulation feedback loop. The inductor is also part in this loop so if its value is changed then the RC network could require a change as well.
But the main difference is in the inductor L1.
This type of DCDC converter works by charging an inductor (magnetic flux is stored), by connecting a voltage across it (the input voltage). During charging the current will ramp up (linearly). This ramp will be more steep (faster current increase) when the inductor has a smaller value (circuit A).
Inside the IC there's a switching transistor (NMOS M1, page 8 of the datasheet) and this NMOS will have a certain on resistance (\$R_{DS,on}\$). As the current through this switch is higher, more voltage is dropped and more power is lost. So high value charging currents cause inefficiency. There's also the current sense resistor making things worse.
So from this we can conclude that a large charging current will decrease the efficiency. So which circuit will have the higher charging current? Then we have to look at the value of the inductor which is the smallest in circuit A. At the same input voltage circuit A should be the least efficient then.
So why not simply increase the value of the inductor and enjoy a better efficiency?
Yes, that is an option however, as always that has other consequences. Suppose that the input voltage is low but at the same time the demanded load current at the output is significant. Then enough power must be transferred from input to output.
To be able to draw enough power from the input a small value inductor is needed. If a larger value inductor was used the current will ramp up more slowly and less energy is stored in a given amount of time.
So yes you can use a larger value inductor and get better efficiency but then the maximum output current will be smaller. Note how the Efficiency plot for circuit A has an X-axis from 0 to 30 mA while the one for circuit B is from 1 mA to 1 A.
The load current for circuit A needs to be quite small, up to 25 mA only. That is a result of the large \$\frac{V_{out}}{V_{in}}\$ ratio. That is always a challenge (resulting in lower effciency) with this type of converter.
To get better efficiency you can check out the Flyback converter which uses a transformer to aid with large \$\frac{V_{out}}{V_{in}}\$ ratios. Mains adapters mainly use flyback converters to efficiently convert a high \$V_{in}\$ to a low \$V_{out}\$ (and provide mains isolation on the go) but the same principle can be used to convert a low \$V_{in}\$ to a high \$V_{out}\$.

A: Lower input voltage results in larger current switching to generate same output power. This simply means more loss in the inductor and transistor.
Also note the output power is much larger for the higher voltage input, thus offsetting the IC static and dynamic current.

A: A larger step up ratio is less efficient because the power stage has to handle much more current through the inductor and mosfet.  This results in higher switching losses in the mosfet and higher conduction losses in the mosfet and inductor.
At light loads, the quiescent current of the regulator becomes significant.  So efficiency suffers.  This does not mean that regulation is poor.  Similar to a car with a big engine requiring more fuel even when it is idling or moving slow.
The design with the larger inductor allows the regulator to switch less often at light loads.  Between switching events the regulator got into low power standby.  It monitors the output, and after a small droop the regulator wakes up briefly and boosts the output back up. This is called burst mode.  Similar to a car with automatic start stop to prevent idling.
The LT836x family is known for its low quiescent current, and for its ability to switch fast.  This helps light loads efficiency, let's you use small inductors and more easily pass an EMI test.


text:
Q: Text parsing via python I have 100+ files with the extension *.log. Each file contains the results from an ansible-playbook run. I would like to parse the data using python, so that I can import it into an excel spreadsheet. I need some help to automate the process.
File content are:
ok: [wrt02.test1] => {
    "msg": "nxos"
}
TASK [checklist : OUTPUT IOS_XR] *******************************************************************************************************************************************************************************************************
skipping: [leaf1J0101.test2]
skipping: [leaf1J0102.test2]
ok: [spine01.test1] => {
    "msg": [
        "Bundle-Ether1.100              192.168.245.65    Up              Up       default ",
        "Bundle-Ether10.151             192.168.203.3   Up              Up       default ",
        "Loopback0                      192.168.255.7     Up              Up       default ",
        "MgmtEth0/RSP0/CPU0/0           192.168.224.15    Up              Up       MANAGEMENT",
        "TenGigE0/0/0/2                 192.168.114.114    Up              Up       default ",
        "TenGigE0/0/0/3                 192.168.82.170    Up              Up       default"
    ]
}

RESULTS:

spine01.test1,Bundle-Ether1.100,192.168.245.65,
spine01.test1,Bundle-Ether10.151,192.168.203.3,
spine01.test1,Loopback0,192.168.255.7,
spine01.test1,MgmtEth0/RSP0/CPU0/0,192.168.224.15,
spine01.test1,TenGigE0/0/0/2,192.168.114.114,
spine01.test1,TenGigE0/0/0/3,192.168.82.170

CODE:
def findIOS(output):
# String we're looking for
OUTIOS_string = "TASK [checklist : OUTPUTIOS] ***************************************************************************************************************************************************************************************************************"
end_string = "TASK"
# Find the start of our string
start_index = output.find(OUTIOS_string) + len(OUTIOS_string) + 2
# Find the end of our string
end_index = output.find(end_string, start_index + 1)
lines = output[start_index:end_index].split('\n')
# Create a list to store our resulting dictionaries
#print lines
d = []
for line in lines:
    #print line
    if line != "":
        # If line is not empty, find our starting and closing brackets
        # Find the host:
        hstart = line.find('[')
        hend = line.rfind(']') + 1
        start = line.find('{')
        end = line.rfind('}') + 1
        hostname = line[hstart:hend]
        # Store content between brackets
        obj = line[start:end]
        hostname = hostname.replace("[", "").replace("]","")
        print hostname
        print obj
        # Convert string to dictionary, and store the results
        d.append(eval(obj))
        print d
return d

def main():
output = None
with open("../showint.log", "rb") as f:
    output = f.read()

if __name__ == '__main__':
    main()

How to fetch the into above format? Thanks for the help

A: I let you the pleasure of creating the code around that.
import re

# This matches the msg pattern
find_start = r"^\s+\"msg\":\s\["
# This matches the line with the information you want that you can access with match.groups()
find_line = r"^\s+\"([^\s]+)\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"


text:
Q: How to use Hashicorp Vault like login to web site I need advice about how can I use Vault login for web. I have set up Debian 8 server. On that server run web page (hashi-ui) for manage Nomad and Consul. Web page work and I can access it. But there is no login so everyone can access to this web page. So I need set up login and authenticate of users. I want use Vault that run on server too. I need result like if I access web page via web browser so after enter URL, web browser pop up login form (Like if you want call some REST and service need authenticate user, so web browser pop up default login form). I enable user-pass method in Vault. I set username and password, but now I do not know how to set up for this web page.
How can I set this user-pass method to authenticate user and then give access to web?
Thank you for any advice.

A: It's an unusual use case, I don't believe you can use Vault directly for it.
Perhaps with PGP, you could use a web interface to keep exchanging encrypted messages with an agent that can proxy your authentication, read, write requests somehow to Vault and transmit them back for you, preferably encrypted. Doing sealing, unsealing like this might be tricky, you might risk getting yourself locked out from sealing if the proxy agent is unreachable or refuses your requests.


text:
Q: Dynamic casting using a generic interface Is there any way to cast to a dynamic generic interface..
Site s = new Site();
IRepository<Site> obj = (IRepository<s.GetType()>)ServiceLocator.Current.GetInstance(t)

obviously the above won't compile with this cast. Is there anyway to do a dynamic cast of a generic interface. I have tried adding a non generic interface but the system is looses objects in the Loc container.
Thanks
Phil

A: Dynamic casting is not easily achievable in C#. You can use 'cast-by-example' - but I would not recommend this - it tends to be confusing.
In you case it's unclear why a 'dynamic' cast is even necessary - if you don't know the type at compile time you can't access any of it's methods or properties. What would such a cast gain you? You may as well just write:
IRespository<Site> obj =
      (IRepository<ISite>)ServiceLocator.Current.GetInstance(t);

If you're inside a generic method, you can always cast to the generic parameter type:
public void SomeMethod<T>( )
    where T : new()
{
    T s = new T();
    IRepository<T> obj = (IRepository<T>)ServiceLocator.Current.GetInstance(t)
    // ...
}


text:
Q: Are all node modules supposed to work out of the box with react native? I have tried using a couple of node modules with react native using npm install (specifically https://github.com/Thuzi/facebook-node-sdk/) and I continually get errors about dependencies not being resolved when I run the app.  Are node modules generally supposed to be supported by react native or only modules that are specifically written for it (such as this one https://github.com/brentvatne/react-native-login).

A: Many Node modules will not work with React Native. Some of the reasons are architectural and can be fixed (ex: currently React Native supports only asynchronous native methods while Node supports synchronous ones as well), while others are inherent to the fact that Node runs on V8 and React Native iOS runs on JSC.
As a heuristic, you should find success with Node modules that are utilities and depend only on JavaScript's core library (the APIs defined here: https://people.mozilla.org/~jorendorff/es6-draft.html). This includes things like sorting algorithms, string formatting, etc.


text:
Q: Create a key:value pair in the first loop and append more values in subsequent loops How can I create a key:value pair in a first loop and then just append values in subsequent loops?
For example:
a = [1,2,3]
b = [8,9,10]
c = [4,6,5]

myList= [a,b,c]
positions= ['first_position', 'second_position', 'third_position']

I would like to create a dictionary which records the position values for each letter so:
mydict = {'first_position':[1,8,4], 'second_position':[2,9,6], 'third_position':[3,10,5]}

Imagine that instead of 3 letters with 3 values each, I had millions. How could I loop through each letter and:

*

*In the first loop create the key:value pair 'first_position':[1]

*In subsequent loops append values to the corresponding key: 'first_position':[1,8,4]

Thanks!

A: Try this code:
mydict = {}
for i in range(len(positions)):
    mydict[positions[i]] = [each[i] for each in myList]

Output:
{'first_position': [1, 8, 4],
 'second_position': [2, 9, 6],
 'third_position': [3, 10, 5]}

A: dictionary.get('key') will return None if the key doesn't exist. So, you can check if the value is None and then append it if it isn't.
dict = {}
for list in myList:
  for position, val in enumerate(list):
    this_position = positions[position]
    if dict.get(this_position) is not None:
      dict[this_position].append(val)
    else:
      dict[this_position] = [val]

A: The zip function will iterate the i'th values of positions, a, b and c in order. So,
a = [1,2,3]
b = [8,9,10]
c = [4,6,5]

positions= ['first_position', 'second_position', 'third_position']
sources = [positions, a, b, c]

mydict = {vals[0]:vals[1:] for vals in zip(*sources)}
print(mydict)

This created tuples which is usually fine if the lists are read only. Otherwise do
mydict = {vals[0]:list(vals[1:]) for vals in zip(*sources)}


text:
Q: Whats happening in Mootools with for (var x in data) loops This situation came about when I was trying to squeeze a google analytics plugin that uses jQuery into my site which uses mootools throughout.
The jQuery code uses a loop similar to the one in the code with no issues.
http://jsfiddle.net/RzBh5/2/
var myData = [[20130105,0,0],[20130106,0,0],[20130107,0,0],[20130108,3,44],[20130109,2,6],[20130110,0,0]]
for (var r in myData) {
$('results').set('html',$('results').get('html') + '
' + myData[r][0] + ' - ' + r);
}

The same loop in Mootools adds all the new methods it adds to the array class to the array I've built. Can someone explain whats happening and how I can rewrite this loop in normal javascript or jQuery so that it doesnt happen.
The 'mootools' way to do this loop which works fine is;
Array.each(myData, function(stuff, index){
$('resultsMoo').set('html',$('resultsMoo').get('html') + '
' + stuff[0]);
});

The fiddle justs spits out the contents of the array object.
Thanks

A: A plain for ... in loop lists all methods and properties of an object including those inherited via the prototypes.
To limit the loop to those properties and methods, that are unique to the respective object, you can use hasOwnProperty().
In this case, however, it is just an array to loop through, which you should use a plain for loop like this:
for( var i=0; i<myData.length; i++ ) {
   $('results').set('html',$('results').get('html') + '
' + myData[i][0] + ' - ' + i );
}

EDIT
An array is at its core an object like any other. In JavaScript there is a native object called Array, which all arrays inherit their functions from.
So when you use a for ... in loop all the methods of the parent object Array are listed as well as the new properties of the array itself like the values.
Hope this explanation helps a little.


text:
Q: Laravel Content-Length header can't be sent with file response I'm actually trying to send the Content-Length header with my file response (for downloading status bar purproses on client side) using this method :
return response()->header('Content-Length', $fileSize)->file($this->filesPath.$fileName);

But i'm getting an error :
BadMethodCallException: Method Illuminate\Routing\ResponseFactory::header does not exist. in file /www/vendor/laravel/framework/src/Illuminate/Macroable/Traits/Macroable.php on line 113

It seems that the method is not recognized when there is "file()" in the response.
Here are my response headers :

Note : Apache webserver based on Linux machine running Laravel 8 with PHP 8.1
Aditional informations :
After testing on different environements and with multiples files, i've found out that the Content-Length header is working only with images. I've tested it in Laravel 9 & 8 and still can't send Content-Length header manually. Any other header is working.

A: Use the pre-built download() method to send headers
$filesPath = 'path/to/file'; // change this
$fileName = 'file-name'; // change this
$fileSize = 'size'; // change this

$headers = [
    'Content-Length' => $fileSize
];

return response()->download($filesPath, $fileName, $headers);


text:
Q: How to pass Dynamic C++ 2D arrays as arguments to LAPACKE functions The LAPACKE documentation states that for C and C++ code, arrays should be passed as pointers, not double pointers as 2D arrays are usually created.
Is there a way to create a C++ dynamic 2D array from a single pointer?


text:
Q: Interpretation of the radius of convergence What interpretation should one give to the radius of convergence of a series $\sum a_nz^n$ ?
I do know how it is mathematically defined and what it implies for convergence/divergence, but I'm having a hard time understanding what its meaning is behind the formulas.
Is there, for instance, a graphical interpretation, or something of that kind ?

A: First the radius of convergence is defined for a power series but not for whatever series. Then the power series converge inside the disk of convergence, the one centered in zero and having for radius the radius of convergence. And it diverges outside this disk.


text:
Q: Why is synchronous sleep function not made async by being inside promise? I'm trying to wrap my head around promises, and how JavaScript works with it's queue and event loop etc.
I thought that if I put a slow synchronous function inside a promise, that slow sync function would be delegated to the background and I could use .then to deal with it when it was done.
function syncSleep(ms){
    var end = new Date().getTime() + ms;
    var start = new Date().getTime();

    while (start < end) {
      start = new Date().getTime();
    }
}

function p() {
  return new Promise(function(resolve) {
     syncSleep(5000);
     resolve("syncSleep done!");
  });
}

p().then( function(s) {
  var div = document.getElementById('async');
  div.innerHTML = s;
} );

var div = document.getElementById('sync');
div.innerHTML = "This should appear right away! (but it doesn't)";

https://jsfiddle.net/7mw6m2x5/
The UI is unresponsive while this code runs though.
So I was wondering, can someone explain what is going on here? Are Promises only a way to handle code that is already "made to be" async?
(If so, how is that done?)
How do I deal with slow sync code when I don't want it to freeze the UI? Do I have to use a web worker for that?
Grateful for any clarification. Thanks.

A: The code works as expected.
Since Javascript is single threaded, the UI will block while your loop is executing.
Promises are just a nice way to handle async code. See an introduction here:
http://www.html5rocks.com/en/tutorials/es6/promises/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
To be able to maintain the UI reponsive while other code is executing in the background, you would need to use WebWorkers:
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
Quoting from the page listed above:
"Web Workers provide a simple means for web content to run scripts in background threads. The worker thread can perform tasks without interfering with the user interface."
Update:
following your comments, I crafted this little script to demonstrate the difference between blocking and no-blocking approaches.
There is some repetition in the code, but I think it is simple enough to understand.

function setVal(s) {
  var divAsync = document.getElementById('async');
  var innerDiv = document.createElement('div');
  innerDiv.innerHTML = s + '
';
  divAsync.appendChild(innerDiv);
}

function syncSleep(ms) {
  var end = new Date().getTime() + ms;
  var now = new Date().getTime();
  var stepBegin = new Date().getTime();
  var step = 0;

  // This loop is blocking
  // The UI will only refresh after the loop completion
  while (now < end) {
    now = new Date().getTime();
    step = now - stepBegin;
    if (step >= 1000) {
      setVal(now);
      step = 0;
      stepBegin = now;
    }
  }

}

function pBlock() {
  return new Promise(function(resolve) {
    syncSleep(3200);
    resolve("pBlock syncSleep done!");
  });
}

function noBlockUpdate(ms, resolve) {
  var end = new Date().getTime() + ms;
  var now = new Date().getTime();
  var stepBegin = new Date().getTime();
  var step = 0;

  function noBlock() {
    now = new Date().getTime();

    // paint every 1000ms;
    step = now - stepBegin;
    if (step >= 1000) {
      setVal(now);
      step = 0;
      stepBegin = now;
    }

    if (now < end) {
      // NB: this is going to be called thousands of times
      // But the UI will still update every 1000 ms
      setTimeout(noBlock);
    } else {
      resolve("pNoBlock done!");
    }
  };
  noBlock();
}

function pNoBlock() {
  return new Promise(function(resolve) {
    noBlockUpdate(3200, resolve);
    setVal("pNoBlock launched!");
  });
}

pNoBlock().then(setVal);

var divSync = document.getElementById('sync');
divSync.innerHTML = "This appears right away!";

// Just wait 4 seconds so the non-blocking code completes
setTimeout(function() {
  // Clear all div's
  document.getElementById('sync').innerHTML = '';
  document.getElementById('async').innerHTML = '';

  var divSync = document.getElementById('sync');
  divSync.innerHTML = "This does not appear right away, only after the blocking operation is complete!";

  pBlock().then(setVal);
}, 4000);
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

A:
Are Promises only a way to handle code that is already 'made to be' async?

Yes. Promises don't truly create asynchronous operations. Their intention is just to make working with asynchronous operations easier, by defining a consistent API. But, they don't avoid blocking on their own beyond one small delay between when resolve() and .then() callbacks are invoked.
The function provided to the Promise constructor is invoked immediately and synchronously. And, once a .then() callback begins executing, it will have to run to completion before the engine does anything else.

How do I deal with slow sync code when I don't want it to freeze the UI?

Try to avoid long-running synchronous operations as much as possible. An asynchronous alternative to syncSleep() would be setTimeout().
function p() {
  return new Promise(function(resolve) {
    setTimeout(function () {
      resolve("syncSleep done!");
    }, 5000);
  });
}

If a long-running synchronous operation can't be avoided, then you'll want to try to move it to a separate process / instance of the engine – and, in browsers, that can be done with Web Workers.
A possible middle ground may be, if you can break up the operation into multiple steps, to separate each step by a brief setTimeout(). Those breaks will give the engine time periodically to work on other events, including updating the page for the user. You'll want each step to be small to have as many breaks as often as possible, since each step will still block everything else once it starts.

A: Promises are not threads. They're just a sugar for handling success and failure events (callbacks) in single-threaded code.
Callback to new Promise(cb) constructor is executed immediately and synchronously. Callbacks given to .then(cb)/.catch(cb) are executed on next tick after the promise is resolved/rejected, but they also run on the same—and only—thread.