text:
Q: Efficient way to Identify xlsx & csv files in a directory, which contain specific string in the data For GDPR purposes, I am trying to identify all spreadsheets within a directory, containing specific strings in the data.
The following code has worked on small files, but takes too long to be practical with any larger spreadsheets (1000+ rows).
It's worth mentioning that I don't know which columns these strings will appear in, so can't use cell location to improve efficiency.
If there's a better way to do the following could you please share?
    def list_files(dir):
    r = []
    for root, dirs, files in os.walk(dir):
    for name in files:
       r.append(os.path.join(root, name))
    return r

    all_files = list_files("filepath")

    filenames = []

    for f in all_files:
    if not f.endswith((".xls", ".xlsx")): continue
    wb = load_workbook(f)

    for sheet in wb.worksheets:
    for a in range(1, sheet.max_row+1):
    for b in range(sheet.max_column):
    if sheet[a][b].value:
    if str(sheet[a][b].value).upper() in("STRING_1","STRING_2","STRING_3"):
    filenames.append(f)

    set(filenames)

A:
If there's a better way to do the following could you please share?

If you have Linux there is. And if you don't you'll only need a terminal emulator like Cygwin or Baboon in Windows.
I've created two files: example.xlsx (newer format of xls) and example.csv and added data into each file.
Inside those files I put some strings like: dodo, lolo, string1, string2 among others.
mortiz@alberta:~/Documents/test$ ls -ltr
total 20
-rw-r--r-- 1 mortiz mortiz 4822 Apr 20 16:34 example.xlsx
-rw-r--r-- 1 mortiz mortiz   68 Apr 20 16:34 example.csv

There's an utility in almost every linux distro called "grep" which let you search "strings" inside almost anything.
There are two easy ways:

Unziping the xlsx files and using grep

when you unzip the xlsx, you'll find a directory called "lx" inside it an xml file with the data called "sharedStrings.xml"
mortiz@alberta:~/Documents/test$ unzip example.xlsx
Archive:  example.xlsx
  inflating: _rels/.rels
  inflating: docProps/app.xml
  inflating: docProps/core.xml
  inflating: xl/_rels/workbook.xml.rels
  inflating: xl/workbook.xml
  inflating: xl/styles.xml
  inflating: xl/worksheets/sheet1.xml
  **inflating: xl/sharedStrings.xml**
  inflating: [Content_Types].xml

By now we just unzipped the file, we'll see the output of grep below.

Converting xlsx to xls and using grep

The xls format is easier to read, so using this command we will generate a version of the xlsx in xls, then using strings to read its content.
   mortiz@alberta:~/Documents/test$ libreoffice --headless --convert-to xls example.xlsx
    convert /home/mortiz/Documents/test/example.xlsx -> /home/mortiz/Documents/test/example.xls using filter : MS Excel 97

Now using grep to find the files with specific strings

Finding the strings with this utility would be the easier and fastest way I know.
Because you need to know which files have those strings you must use grep, the -R (recursive) and i (insensitive, doesn't matter about camel case).
 mortiz@alberta:~/Documents/test$ grep -Ri lolo *
    example.csv:no data,lolo,foo
    Binary file example.xls matches
    xl/sharedStrings.xml:<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="12" uniqueCount="12"><si><t xml:space="preserve">string1</t></si><si><t xml:space="preserve">string</t></si><si><t xml:space="preserve">string2</t></si><si><t xml:space="preserve">no data</t></si><si><t xml:space="preserve">lolo</t></si><si><t xml:space="preserve">foo</t></si><si><t xml:space="preserve">test</t></si><si><t xml:space="preserve">mia</t></si><si><t xml:space="preserve">ami</t></si><si><t xml:space="preserve">nono</t></si><si><t xml:space="preserve">toto</t></si><si><t xml:space="preserve">dodo</t></si></sst>

To print only the filenames add the parameter "l", this will print each file with the string "lolo" inside:
mortiz@alberta:~/Documents/test$ grep -Ril lolo *
example.csv
example.xls
xl/sharedStrings.xml

Grep will work well with xml, csv, xls or plain text files, that's why we need to unzip or convert the xlsx :)

A: Thanks for the help Miguel, I would like to try your solution but am quite new to this kind of scripting, and don't have the tools on my work machine.
I was shown this Python code, which works on my xlsx files. (the field names i'm searching for are usually pasted in the first row of a spreadsheet & this code returns when a match is found).
The process still has room for improvement. Converting the files to csv (or xls?) and parsing as single string would speed things up.
import xlrd
import glob

def search_excel(path, phrases):
    try:
        wb = xlrd.open_workbook(path)
    except xlrd.biffh.XLRDError:
    # Assumed False if document fails to open (e.g. invalid format/corrupt)
        return False
    for sheet in wb.sheets():
        for row in sheet.get_rows():
            for cell in filter(lambda x: x.ctype==1, row):
                # Only operate on string typed cells
                try:
                    if any(phrase in cell.value for phrase in phrases):
                        # Return as soon as possible if criteria fulfilled
                        return path
                except TypeError:
                    pass

if __name__ == "__main__":
    # Recursively searches all nested directories/files for files
    # Change the path here.
    file_paths = glob.glob("...path...", recursive=True)
    search_phrases = ['string_1','STRING_1','string_2','STRING_2']
    list_comp = [search_excel(path, search_phrases) for path in file_paths]


text:
Q: .Net Core BackgroundService for RabbitMQ.Client.Core.DependencyInjection - not possible to use other services or MediatR command I'm creating an application using RabbitMQ.Client.Core.DependencyInjection as a consumer of messages in the BackgroundService. Receiving and deserializing the message works correctly, but when I'm sending command to the MediatR I got an error:
 ---> System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder Lifetime: Singleton ImplementationType: RabbitMQ.Client.Core.DependencyInjection.Services.MessageHandlerContainerBuilder': Cannot consume scoped service 'Application.Common.Interfaces.IDbContext' from singleton 'RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder'.
 ---> System.InvalidOperationException: Cannot consume scoped service 'Application.Common.Interfaces.IDbContext' from singleton 'RabbitMQ.Client.Core.DependencyInjection.Services.IMessageHandlerContainerBuilder'.

My Command's Handler's constructor is creating dbContext in the constructor, and outside the BackgroundService it works correctly.
I understand that for BackgroundService one needs to create scope and get service from the ServiceProvider:
using var scope = _sp.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<IDbContext>();

But how can I use the rest of the application, where I'm using injected services as singletons?
I believe the same issue would happen if I would call a Service class that constructs injected dbContext in the same way, it does not seem to be a problem with a MediatR.

A: ok, found a problem with RabbitMQ.Client.Core.DependencyInjection NuGet, instead used RabbitMQ.Client and all works as expected

redpajama_set_name: RedPajamaStackExchange


text:
Q: Analog of eigenvalue bound for a general bounded operator It's known that for a matrix, $\max|λ|≤\sqrt{tr(A^*A)}=\sqrt{∑_{i,j=1}^n|A_{i,j}|^2}$ where $\lambda$ denotes its eigenvalue. I'm wondering whether there's an analog of this inequality for a general bounded operator.
For example an integral operator, $T(f(x))=\int k(x,y)f(y)dy$, can we say its spectrum is bounded by something like $\sqrt{\int k(x,y)^2dydx}$, it looks similar to the property that $\rho (T)\leq ||T||=\underset {||f||\leq 1}\sup ||Tf||$ if we use the norm of $L_2 R$ space.

A: Yes there is. If $A$ is an operator in a Hilbert space, $A^*A$ is a trace class operator, and $\lambda$ is an eigenvalue of $A$ with the corresponding unit eigenvector $u$, then $|\lambda|^2=(Au,Au)=(A^*Au,u)\le\operatorname{tr}A^*A$, because $\operatorname{tr}A^*A=\sum (A^*Ae_j,e_j)=\sum||Ae_j||^2$ for any orthonormal basis $\{e_j\}$, and we can always arrange that $e_1=u$. Moreover,
$$
 ||A||^2=\sup_{||u||=1}(Au,Au)\le \operatorname{tr}A^*A.
$$
But note that not all operators in an infinite-dimensional Hilbert space are trace class...


text:
Q: named not serving letsencrypt TXT records Am trying to renew/create letsencrypt certs using DNS auth:
certbot-auto -d xxx.it -d mail.xxx.it --manual --preferred-challenges dns certonly

However, after inserting the requested records:
Please deploy a DNS TXT record under the name
_acme-challenge.mail.xxx.it with the following value:

yB_EQ-wiB0NzNUVwiyfiabeIOqIXx3fWKiia1uHGesE

Before continuing, verify the record is deployed.

The challenge fails.
Indeed, if I try:
$ dig_acme-challenge.mail.xxx.it TXT

The request also fails, though the zone file includes the record:
 # fgrep TXT /var/named/chroot/var/named/master/xxx.it
 acme-challenge.mail.xxx.it IN  TXT     "yB_EQ-wiB0NzNUVwiyfiabeIOqIXx3fWKiia1uHGesE"

I am supposing that BIND (bind-9.8.2-0.62.rc1.el6_9.4.x86_64) is somehow refusing to serve records with leading underscores, but the docs/google aren't helping.
Any ideas?
Edit As pointed in the answer below, host parts in zone records need to have a trailing dot OR have the domain part stripped. Look after you copy and paste.

A: In your zone file you need to end the domain with a . that tells bind not to append the origin you list in the zone
 acme-challenge.mail.xxx.it. IN  TXT     "yB_EQ-wiB0NzNUVwiyfiabeIOqIXx3fWKiia1uHGesE"


text:
Q: MYSQL Query if a column is empty I have the following statement but what I am trying to do is find out a way to say if its returned empty insert N/A.  Would I use an if statement or set the default value in the DB?
Code:
$query = $this->db->query("SELECT f.film_id 'Film ID', f.film_name 'Film Name', u.user_first_name 'First Name', u.user_surname 'Surname', u.user_address_line1 'Address1', u.user_address_line2 'Address2', u.user_towncity 'City', u.user_us_state_id 'US State', u.user_non_us_state_county 'Non US State', u.user_country 'Country' FROM films f
INNER JOIN users u ON u.user_id = f.user_id WHERE f.active = 0");

return $query;

A: This will replace an empty string in a column with N/A when performing the query.
SELECT ..., IF(column = '', 'N/A', column) AS column, ...

A: You can use and update to set change the column to N/A where the column is null.
UPDATE tablename SET column='N/A' WHERE column IS NULL

A: You can easily cover an empty column using a coalesce function like this:
SELECT
    f.film_id 'Film ID',
    f.film_name 'Film Name',
    coalesce(u.user_first_name, 'N/A') 'First Name',
    // ^^ Guessing that this might sometimes be the null column.
    u.user_surname 'Surname',
    u.user_address_line1 'Address1',
    u.user_address_line2 'Address2',
    u.user_towncity 'City',
    u.user_us_state_id 'US State',
    u.user_non_us_state_county 'Non US State',
    u.user_country 'Country'
FROM
    films f
        INNER JOIN users u
            ON u.user_id = f.user_id
WHERE f.active = 0

This will put in "N/A" if the first name field is null.


text:
Q: Convert List of integers to Hex I'm doing some OpenCL computing with Mathematica, I have an SHA256 implementation running on my GPU. It returns a list of uints (64bit, Mathematica mistakenly treats these as signed 64bit ints), how do I convert a list of uints like this:
{-21538778104198244, -4938185804688833306, -5532891535721358017,
1706758832443728646}

Into a hex string something like this:
6b86b273ff34fce19d6b804eff5a3f5747ada4eaa22f1d49c01e52ddb7875b4b

Edit: Here's my current code:
    kern = "#ifndef uint32_t
#define uint32_t unsigned int
#endif

#define H0 0x6a09e667
#define H1 0xbb67ae85
#define H2 0x3c6ef372
#define H3 0xa54ff53a
#define H4 0x510e527f
#define H5 0x9b05688c
#define H6 0x1f83d9ab
#define H7 0x5be0cd19

uint rotr(uint x, int n) {
  if (n < 32) return (x >> n) | (x << (32 - n));
  return x;
}

uint ch(uint x, uint y, uint z) {
  return (x & y) ^ (~x & z);
}

uint maj(uint x, uint y, uint z) {
  return (x & y) ^ (x & z) ^ (y & z);
}

uint sigma0(uint x) {
  return rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22);
}

uint sigma1(uint x) {
  return rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25);
}

uint gamma0(uint x) {
  return rotr(x, 7) ^ rotr(x, 18) ^ (x >> 3);
}

uint gamma1(uint x) {
  return rotr(x, 17) ^ rotr(x, 19) ^ (x >> 10);
}

__kernel void sha256_crypt_kernel(__global uint *data_info,__global \
char *plain_key,  __global uint *digest){
  int t, gid, msg_pad;
  int stop, mmod;
  uint i, ulen, item, total;
  uint W[80], temp, A,B,C,D,E,F,G,H,T1,T2;
  uint num_keys = data_info[1];
  int current_pad;

  uint K[64]={
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, \
0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, \
0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, \
0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, \
0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, \
0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, \
0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, \
0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, \
0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};

  msg_pad=0;

  ulen = data_info[2];
  total = ulen%64>=56?2:1 + ulen/64;

//  printf(\"ulen: %u total:%u\\n\", ulen, total);

  digest[0] = H0;
  digest[1] = H1;
  digest[2] = H2;
  digest[3] = H3;
  digest[4] = H4;
  digest[5] = H5;
  digest[6] = H6;
  digest[7] = H7;
  for(item=0; item<total; item++)
  {

    A = digest[0];
    B = digest[1];
    C = digest[2];
    D = digest[3];
    E = digest[4];
    F = digest[5];
    G = digest[6];
    H = digest[7];

#pragma unroll
    for (t = 0; t < 80; t++){
    W[t] = 0x00000000;
    }
    msg_pad=item*64;
    if(ulen > msg_pad)
    {
      current_pad = (ulen-msg_pad)>64?64:(ulen-msg_pad);
    }
    else
    {
      current_pad =-1;
    }

  //  printf(\"current_pad: %d\\n\",current_pad);
    if(current_pad>0)
    {
      i=current_pad;

      stop =  i/4;
  //    printf(\"i:%d, stop: %d msg_pad:%d\\n\",i,stop, msg_pad);
      for (t = 0 ; t < stop ; t++){
        W[t] = ((uchar)  plain_key[msg_pad + t * 4]) << 24;
        W[t] |= ((uchar) plain_key[msg_pad + t * 4 + 1]) << 16;
        W[t] |= ((uchar) plain_key[msg_pad + t * 4 + 2]) << 8;
        W[t] |= (uchar)  plain_key[msg_pad + t * 4 + 3];
        //printf(\"W[%u]: %u\\n\",t,W[t]);
      }
      mmod = i % 4;
      if ( mmod == 3){
        W[t] = ((uchar)  plain_key[msg_pad + t * 4]) << 24;
        W[t] |= ((uchar) plain_key[msg_pad + t * 4 + 1]) << 16;
        W[t] |= ((uchar) plain_key[msg_pad + t * 4 + 2]) << 8;
        W[t] |=  ((uchar) 0x80) ;
      } else if (mmod == 2) {
        W[t] = ((uchar)  plain_key[msg_pad + t * 4]) << 24;
        W[t] |= ((uchar) plain_key[msg_pad + t * 4 + 1]) << 16;
        W[t] |=  0x8000 ;
      } else if (mmod == 1) {
        W[t] = ((uchar)  plain_key[msg_pad + t * 4]) << 24;
        W[t] |=  0x800000 ;
      } else /*if (mmod == 0)*/ {
        W[t] =  0x80000000 ;
      }

      if (current_pad<56)
      {
        W[15] =  ulen*8 ;
        //printf(\"ulen avlue 2 :w[15] :%u\\n\", W[15]);
      }
    }
    else if(current_pad <0)
    {
      if( ulen%64==0)
        W[0]=0x80000000;
      W[15]=ulen*8;
      //printf(\"ulen avlue 3 :w[15] :%u\\n\", W[15]);
    }

    for (t = 0; t < 64; t++) {
      if (t >= 16)
        W[t] = gamma1(W[t - 2]) + W[t - 7] + gamma0(W[t - 15]) + W[t \
- 16];
      T1 = H + sigma1(E) + ch(E, F, G) + K[t] + W[t];
      T2 = sigma0(A) + maj(A, B, C);
      H = G; G = F; F = E; E = D + T1; D = C; C = B; B = A; A = T1 + \
T2;
    }
    digest[0] += A;
    digest[1] += B;
    digest[2] += C;
    digest[3] += D;
    digest[4] += E;
    digest[5] += F;
    digest[6] += G;
    digest[7] += H;

  //  for (t = 0; t < 80; t++)
  //    {
  //    printf(\"W[%d]: %u\\n\",t,W[t]);
  //    }
  }

}"

And here's my code using the kernel

fun = OpenCLFunctionLoad[kern,
   "sha256_crypt_kernel", {{"UnsignedByte"}, {"UnsignedByte"}, \
{"UnsignedByte[8]", _ , "Output"}}, {16}];
numhashes = 1;
datainfo = Array[0, {numdatainputs}];
datainfo[[1]] = 64; (* plaintext length constant 64 in source *)
datainfo[[2]] = 1; (* Global work size *)
datainfo[[3]] = 448; (* String length *)
datainfo
(* Why 2048? It's called "kpc" in the source. Don't know why*)
plainkey = ConstantArray[0, 64*2048];
hashout =
  ConstantArray[
   0, {32}];(* Output for hash 4 64bit unsigned integers *)
res = fun[datainfo, plainkey, hashout];
res[[3]]
StringJoin @@ IntegerString[res[[3]], 16]

Naturally this results in a hash:
"9cb346e987ab3ffe644a59c2ca78bb3f1d9078763837b36a311851da0af17"

That is different from Hash
Hash["", "SHA256", "HexString"]
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

I realize I'm likely confounding data inout types (opencl vs mathematica) and possibly little/big endian in all this. I don't know how to extract exact types for what Mathematica is handing openCL here.

*

*Original OpenCL source code https://github.com/Fruneng/opencl_sha_al_im/blob/master/sha256/sha256.c

A: Define a function to convert a number to a 64-bit hex string while respecting two's complement representation: (thanks to Michael for simplifying!)
tohex[x_] := IntegerString[Mod[x, 2^64], 16, 16]

Apply to the data and join together:
data = {-21538778104198244, -4938185804688833306,
        -5532891535721358017, 1706758832443728646};

StringJoin[tohex /@ data]
(*    "ffb37a986e340b9cbb780a2c9ca544e6b337387678901d3f17afa01d8511a306"    *)


text:
Q: windows virus on usb will run on ubuntu 16.04? As the title suggest, is it really possible that a virus/malware/spyware or anything bad that will affect my pc, will be transferable and "AUTO-RUN" from a USB with files copied from a Windows OS(maybe infected/maybe not) to Ubuntu 16.04? As I was doing some reading here in the community, many amongst the users had concluded that there is no use for an AV in Ubuntu OS, hence I followed, since I am a new user and still studying/reading almost everything. Or will it require everytime the user password and "NO AUTOMATIC THINGS" will be installed in my Ubuntu PC" ?

A: I use the same USB stick on both my Ubuntu and my Windows PC. Normally, Windows viruses should not be able to affect your Ubuntu OS, because the viruses that affect your Windows PC are written for Windows and don't do their 'work' on a Linux OS such as Ubuntu.
However, Ubuntu is getting more popular and therefore it may become more profitable to write viruses for Ubuntu. A lot of people claim that you should not worry about viruses on Ubuntu, but nevertheless, it doesn't hurt to install anti-virus programs written for Ubuntu. ClamAV is one that is regularly updated. You may find an old version of it in the Ubuntu software repository which you can find on your ribbon, but I would recommend you install the latest version which you can find on the ClamAV site. It does come with instructions and a readme file.


text:
Q: Using native HistoryAPI and History.js together I am a little bit confused newbie of History API. Please help me in understanding this. I wrote this code using Native HistoryAPI:
function addClicker(link) {
    link.removeEventListener('click', null);
    link.addEventListener("click", function (e) {
        if (swapData(link.href)) {
            if (prevlink != link.href) {
                history.pushState(null, null, link.href);
                prevlink = link.href;
            }
            e.preventDefault();
        }
    }, true);
}

function setupHistoryClicks() {
    var links = document.getElementsByClassName('hrlinks');
    for (var i = 0; i < links.length; i++)
        addClicker(links[i]);
}

function initHist() {
    if (!supports_history_api()) { return; }
    setupHistoryClicks();
    window.setTimeout(function () {
        window.addEventListener("popstate", function (e) {
            swapData(location.href); //a function that changes content according to URL
        }, false);
    }, 1);
    swapData(location.href);
}

This code overrides the click event of links with hrlinks as class and enable them to use history API.
But from past 2 days I am researching on History API and came to know that it's not very much reliable. And the other alternative is to use History.js.
What I want to know is that how can I use History.js when History API is not available? And do I need to change my code for that? Or I have to simply import History.js when native History API is not supported?


text:
Q: What is the name of this android view? What is the name of this view and how can I make one just like it?

When a user click on it, it will make him choose between choices (image below)

A: You can use a Recyclerview with a Cardview or a Listview to achieve this design. Also you will need to create a standard layout like this and then call this layout in your Recyclerview adapter class. Google for tutorials on Recyclerview and you will come up with the best solution of code with a few modifications.


text:
Q: Can you have different types of primitive data types in a dynamic array? I am new to data structures in computer science. I am trying to find out about all the types of implementations of lists. I started with dynamic arrays and I wanted to know if it is possible to have different types of primitive data types in a dynamic array data structure.
I though that "dynamic" only means that you can remove, insert and add to your array without caring about its size. But do you have to care for the types of elements that there are in the array too ?

A: The term dynamic data structure only refers to its size/structure in runtime, as in it can change on runtime.
So for example, in C++ an array is a static data structure, whereas a vector or ordered_set is probably what you might call dynamic.
By having multiple data types in a data structure, what you are referring to is a dynamically typed language.
Any data structure will support multiple elements in it if the language is dynamically typed, such as python. The data structure itself need not be strictly dynamic for that to happen.

A: The term you are searching for is heterogeneous repectivelly homogenous. Heterogenous lists can store different kind of elements, while homogenous lists are limited to one type of elements.
Python is a good example for heterogeneous lists. This is implemented by storing references to the different objects in the list. So from a technical point of view, they store homogenous references, but from a user perspective they store different types, such as integer, strings, and other objects.


text:
Q: Library for optimizing / parameter scanning a method I have several java classes which implements a quite complicated (non-linear) business logic. Basically the user provides several (numeric) input parameters, and the application computes a scalar.
I would like to do a parameter scan on the input data, that is I would like to know what parameter values create the maximum output value.
The easiest and most time-consuming method would be to create some simple loops with "small" steps on the input parameters, and constantly check the output one.
But as I said, this takes quite a long time; there are several mathematical solutions for this problem (e.g. Newton-method).
My question is; are there any free/open source JAVA libraries which provide this parameter scanning funcionality?
Thanks,
krisy

A: You might be able to adjust OptaPlanner for this. Call your business logic in a SimpleScoreCalculator and wrap the returned scalar in a Score instance.
Make sure you use at least 6.1.0.Beta2 as that supports IntValueRange and DoubleValueRange.
As for optimization algorithms: if the variables are few, integer and small in range, "Branch And Bound" can work, guaranteeing you the optimal solution (but much faster than Brute Force).
Otherwise, you'll need to go with a limited selection Construction Heuristic followed by Local Search with custom Move implementations.


text:
Q: Does left-cancellativity of an element imply that in a superstructure, it has a left inverse? Let $X$ denote a magma and suppose $x \in X$. Then clearly, if there exists a magma $Y$ and an injective homomorphism $f : X \rightarrow Y$ such that $f(x)$ has a left-inverse, then it follows that $x$ is left-cancellative.
Does the converse hold?
Meaning, is it true that if $x \in X$ is left-cancellative, then there exists a magma $Y$ and an injective homomorphism $f : X \rightarrow Y$ such that $f(x)$ has a left-inverse?
My definitions are as follows.
"$x$ is left-cancellative" =
$$\forall a,b : x*a = x*b \rightarrow a=b$$
"$x$ has a left-inverse" =
$$\exists y \forall a : y*(x*a)=a.$$

A: You can simply pick $Y = X \cup \{x^{-1}\}$ and find a way to extend $*$ to $Y$ :
Define $x^{-1} * (x*a) = a$ forall $a \in X$ (this is possible since $x \mapsto x * a$ is injective).
For $x * x^{-1}$, pick any result in $Y \setminus \{ x * a, a \in X\}$, so you can define next $x^{-1} * (x * x^{-1}) = x^{-1}$. For the remaining operations involving $x^{-1}$, you don't have any constraint so anything you pick works.


text:
Q: Jquery POST fetching data on keyup What I want to do
When writing in the text field, I want the
 to be filled with what PHP is echoing.
But it doesn't work!
Jquery
$(document).ready(function() {
    var search = $("#search");
    if (search.val() !== '') {
        search.keyup(function() {
            $.post("index.php", { search : search.val()}, function(data) {
                $(".result").html(data);
            });
        });
    }
});

php
    if (isset($_POST['search'])) {
        echo 'hello';
    }

html
<input type="text" name="search" id="search"/>

Problem
When filling the input, nothing happens, and it meant to POST the entered data on keyup (When entering a new character/or deleting.
What is stopping it from working? I am new to jQuery .
Thanks.

A: This is wrong.
if (search.val() !== '') {

The above line should be,
if (search.val() != '') {

EDIT:
Then wrap the if condition inside the keyup function.
$(document).ready(function() {
    var search = $("#search");

        search.keyup(function() {
            if (search.val() != '') {
                $.post("getInputs.php", { search : search.val()}, function(data) {
                    $(".result").html(data);
                });
            }
        });
});

A: When I run into situations like this, I just start breaking the problem in half to see where its failing. Here are a couple things I would try.
First, in your jQuery, add some output to the console:
if (search.val() !== '') {
        console.log("I am not empty so I should go to index.php");
        search.keyup(function() {
            $.post("index.php", { search : search.val()}, function(data) {
                $(".result").html(data);
            });
        });
    }
else
{
     console.log("search val was empty");
}

Of course you could always check the browsers network profiler to see if it made a POST to that resource. This will tell you if the problem is in your search.val test.
Then, if you want to debug the PHP side, you could remove the isset test and just always return "hello".  That will tell you if its an issue with your POST variables or checks.
Finally, you could output the data result to be sure something is coming back at all. This will remove any issues with $(".result").html() being the problem:
$.post("index.php", { search : search.val()}, function(data) {
   console.log(data);
   $(".result").html(data);
});

If none of these work, maybe you could just switch around the way you bind to keyup in the first place:
$(document).ready(function() {
    $("#search").keyup(function() {
       if ($(this).val() !== '') {
            $.post("index.php", { search : $(this).val()}, function(data) {
                $(".result").html(data);
            });
        });
    }
});

A: $(document).ready(function() {
    var search = $("#search");

});

This fire only at document ready but not on keyup, means in var $("#search").val() will be blank.
Change your code to capture inpute value on every key-up stroke.
$(document).ready(function() {
         search.keyup(function() {

             var value = $("#search").val();
             if(value!="")
            {
             $.post("index.php", { search : value}, function(data) {
                $(".result").html(data);
            });
           }
        });

});

A: Your logic is incorrect. You are only setting the keyup event handler if your #search has text in it. Unfortunately when that script runs on document ready, there is NO value in #search so your keyup handler never gets set, which is why it never fires.

A: I rewrote some of your logic and was able to get it to work. One being the way your checking to ensure you have a value. Instead of string comparing I am checking the length. Also, instead of binding the event to the field, I bind the event on the document and target the field. Try it:

<input type="text" name="search" id="search"/>

A: // when the html is loaded
$(document).ready(function() {
    // find an element with the id 'search'
    var search = $("#search");

    // if this element's value is NOT an empty string -- oh look, it is!
    if (search.val() !== '') {
        // well, going to skip all this here then
        search.keyup(function() { // don't care
            $.post("index.php", { search : search.val()}, function(data) { // don't care
                $(".result").html(data); // don't care
            });
        });
    }

    // YAAAAY! All done!
});

A: Actually nothing is wrong in your code. I have tried your code itself. Only issue was that you have called keyup function conditionally. Your Javascript code should be like below:
$(document).ready(function() {
    var search = $("#search");
        search.keyup(function() {
            if (search.val() != '') {
            $.post("index.php", { search : search.val()}, function(data) {
                $(".result").html(data);
            });
            }
        });

});

Here, condition should be inside the keyup function.


text:
Q: C2679 binary '-=': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion) I have created a Vector class that holds 3 parameters and overloaded the -= operator
template <class T>
class Static3Vector
    {
    public:
        Static3Vector() : m_coords{ 0, 0, 0 } {}
        Static3Vector(T x, T y, T z) : m_coords{ x, y, z } {}

        T operator [] (const size_t& i) { return m_coords[i]; }
        T operator [] (const size_t& i) const { return m_coords[i]; }

        Static3Vector operator -= (const Static3Vector& rhs)
        {
          for (int i = 0; i < sizeof(m_coords) / sizeof(m_coords[0]); i++)
             this[i] -= rhs[i];
          return *this;
        }
    private:
        T m_coords[3];
    };

but when I try using this operator
Static3Vector<int> vec1(1,2,3);
Static3Vector<int> vec2(1,2,3);
vec1 -= vec2;

I get the error I typed out in the title.

A: this is a pointer and this[i] is not doing what you expect. It takes this and performs pointer arithmetic. The only value of i that is not UB is then 0 and type of this expression is Static3Vector<T>
It is pretty much equivalent to this:
Static3Vector<int> vec1(1,2,3);
Static3Vector<int>* ptr = &vec1;
ptr[0]; //ok, equivalent to *ptr
ptr[1]; //compiles, but invokes UB

You can solve it in a couple of ways:
(*this)[i] -= rhs[i]; //dereference first
this->operator[](i) -= rhs[i]; //call operator explicitly
m_coords[i] -= rhs[i]; //don't use overloaded operator, use data directly

One more thing: First two will not work with your current implementation, because your operator[] returns a copy of the value it stores. It's more typical for operator[] to return a reference to stored object:
    T& operator [] (const size_t& i) { return m_coords[i]; }
    const T& operator [] (const size_t& i) const { return m_coords[i]; }

See also What are the basic rules and idioms for operator overloading?

A: Take a look at your indexing-operators:
T operator [] (const size_t& i) { return m_coords[i]; }
T operator [] (const size_t& i) const { return m_coords[i]; }

The only difference between them is that one is called for constant objects, begging the question why you duplicated them at all.
That is easily answered though:
Both should return references, the latter const-qualified, to avoid copies and allow modification for the first one.
Fix that as a first step to resolving your error.

As a second step, recognize that this was introduced before references existed, and is thus a pointer to the instance, not a reference, thus this[n] is pointer-arithmetic, not calling your custom indexing-operator. Thankfully that results in a different type and thus failed overload-resolution.

A: there is incorrect use of the subscript operator. In the operator definitions as for example in this
    Static3Vector operator -= (const Static3Vector& rhs)
    {
      for (size_t i = 0; i < sizeof(m_coords) / sizeof(m_coords[0]); i++)
         this[i] -= rhs[i];
      return *this;
    }

in this statement
         this[i] -= rhs[i];

there is used the b built-in subscript operator for an object of the pointer type Static3Vector *.
You need to write
         ( * this )[i] -= rhs[i];

or
         this->operator[]( i ) -= rhs[i];

Also the return type shall be a referenced type like
    T &  operator [] (const size_t& i) { return m_coords[i]; }
    const T & operator [] (const size_t& i) const { return m_coords[i]; }

and
    Static3Vector & operator -= (const Static3Vector& rhs)
    {
      for (size_t i = 0; i < sizeof(m_coords) / sizeof(m_coords[0]); i++)
         ( *this )[i] -= rhs[i];
      return *this;
    }


text:
Q: Can't reload CollectionView with new fetched data from Firebase When I select a cell in the CategoryVc it should pop to the MainVc and display the new data in the CollectionView but it doesn't. It only load data when I run the app.
I checked and the chosenCategory var get the right String after selecting the cell and the refresh function gets called. I can't understand what wrong.
Edit: If I push the view controller instead of popping it, it works. But I need to pop it.

It also prints both the right chosenCategroy

The mainVc is a UICollectionViewCell
MainVc
static var chosenCategory = "General"

    func fetchQuotes() {
        CATEGORIES_REF.child(QuoteCell.chosenCategory).observe(.childAdded) { (snapshot) in
            let quoteId = snapshot.key

            CATEGORIES_REF.child(QuoteCell.chosenCategory).child(quoteId).observeSingleEvent(of: .value, with: { (snapshot) in
                guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return }
                let quote = Quote(quoteId: quoteId, dictionary: dictionary)

                self.quotes.append(quote)
                self.collectionView.reloadData()
                print("second: \(QuoteCell.chosenCategory)")
            })
        }
    }

    func refresh() {
        quotes.removeAll()
        fetchQuotes()
        print(QuoteCell.chosenCategory)
    }

CategoryVc
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
            self.navigationController?.popViewController(animated: true)
            QuoteCell.chosenCategory = "\(categories[indexPath.item])"
            quoteCell.refresh()
    }

A: one of the missing parts is not using main thread. When you use reloadData of collectionView use with main thread.
DispatchQueue.main.async { [weak self] in
    self.collectionView.reloadData()
}

Then another thing is if you want to process anything in backward controller, I would recommmend you to use Protocol / Delegates.
Describe a protocol
protocol Handler:class{
    func reloadHandler()
}

Then extend it with your MainController. After extending use your own reload function in protocol's function.
extension MainController: Handler{

    func reloadHandler() {
            self.reload()
    }
}

Then delegate the protocol in target ViewController
class TargetController: UIViewController {
    weak var delegate: Handler?
}

Before the push the targetController, you must assign self to delegate of the TargetController.
var target = TargetController()
target.delegate = self

You set the delegation between two controllers. Now time to trigger your action. In target controller, when you trigger the reload(), use delegate?.reloadHandler().

A: The problem is you're popping the view controller before refreshing you data. Try to change the order like:
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
     QuoteCell.chosenCategory = "\(categories[indexPath.item])"
     quoteCell.refresh()
     self.navigationController?.popViewController(animated: true)
}


text:
Q: AWS - deployment & security for a PHP + ReactJS frontend & backend app Hoping to get some guidance here and I will present the scenario as best as I can given I am relatively new to AWS.
I have an app built in PHP (Yii2) and ReactJS. The PHP app is to run simply as a RESTful service. The app is split into a frontend and a backend, which each sharing common ORM/models, controllers etc with this as the general idea: -
/models
    /frontend
    /backend
    /common

A standard enough pattern, as the same would be done from for the controllers.
My aim is to run the app as www.thewebsite.com and admin.thewebsite.com. The frontend will offer the user the ability to log into their account but this will not allow any access to admin.thewebsite.com. I am looking to use AWS Cognito and DynamoDB sessions for this.
My intention is to have the admin site entirely protected so as to render nothing other than a logon page unless the user has been authenticated. If possible, I do not wish to have the app.js exposed until the user has logged in.
Can I ask if there is a certain strategy that can be used in AWS to achieve this? I would again be looking to use Cognito and DynamoDB sessions but I am wondering if there is a specific paradigm in AWS for this type of scenario? This is not a lazy question and I am not expecting others to do the work for me... it's just that AWS offers so many different services I really don't know where to start.
If someone could give me some advice here/point me in the right direction, that would be great. I've had a look at the AWS forums but they seem to be fairly dead.

A: From what I understand, your main priority is to allow users to log into the www subdomain but not into the admin portal.
AWS' services are mainly around hosting and networking, there are some services that help with security like cognito as you mentioned and aws signature but it would be your code's role to maintain that security and control between the two applications.


text:
Q: Insert a CSS file within a PHP class I have a little problem, which I can't figure out by myself.
I created sort of a "webengine", which I build out of several classes.
The main-class, getting a "theme's" internals is called "Logic".
This logic-class includes all the files, needed for a website. I made it like that, so that every developer, creating such website could use function, that are given inside this class.
I now want to create a function, that allows these developers to include a CSS file. But this turns out to be quite difficult.
So far I tried this:
public function include_css($path_to_css) {
    $path_to_css = $this->project_name . THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;
    if(file_exists($path_to_css)) {
        ?>
        <html>
            <head>
                <link rel="stylesheet" type="text/css" href=" <?php echo $path_to_css; ?>" />
            </head>
        <?php
    } else {
        return false;
    }
}
/* Idea number 2 */
public function include_css($path_to_css) {
    $path_to_css = $this->project_name . THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;
    if(file_exists($path_to_css)) {
        echo "
        <html>
            <head>
                <link rel='stylesheet' type='text/css' href='".$path_to_css."' />
            </head>
        ";
    } else {
        return false;
    }
}

Please note that unclarified attributes are declared in a complex matter, so it would be a very long post, if I would paste these here.
I am just getting this console error: http://127.0.0.1/vpm2/themes/numberOne/css/test.css 404 (Not Found), which means there is no such file. The interesting thing about that, is, that this is the exact path to the right file!
Is there anything I am missing?

A: I found the solution. Apparently the CSS Path seems to be wrong. It needs to look like that:
$path_to_css = THEMES . "/" . ACTIVE_THEME . "/" . $path_to_css;

So the result looks like that:
themes/numberOne/test.css

Before it looked like that:
/vpm2/themes/numberOne/test.css


text:
Q: Having trouble getting IIS bindings with PowerShell I am doing this.
Get-ChildItem -Path IIS:\Sites

Which works, but I want to select specific items and then export into a file. I want to select Name, State, and Bindings. So something like this;
Get-ChildItem -Path IIS:\Sites | select-object name, state, bindings

The problem is, bindings appears to be an array. How can I loop through that and get the bindings? Should I use like a PSCustomObject? How could I loop through the bindings array and get the actual bindings?
Thanks.


text:
Q: Flutter Dart - List' can't be assigned to the parameter type 'Chat' I simply want to add a list to another list.
List<Chat> allChats1;
List<Chat> allChats2;

...

allChats1.add(allChats2);

But I'm getting: The argument type 'List' can't be assigned to the parameter type 'Chat'.

A: You are trying to add a Chat type List to a List that accepts only Chat instances.
If you want to add the Chat instances that are in allChats2 you must use addAll, like this.
allChats1.addAll(allChats2);


text:
Q: How to translate only one html I have a list of services requested by API from a provider. I do not have access to the backend configuration in any way. I can only make some changes to html via twig templates.
So, I would like to know if there is any way to translate these descriptions automatically via ajax with google, or I need an api, etc.
I already check the possibility of using the google API, but I don't have enough technical knowledge to implement it.
Example
<select class="form-control" id="category">
          </select>

Hello World!

Hello World!

Hello World!

looking for internationalization (i18n), finding libraries like react-i18next, but all of them as I understand it, a translation needs to be earlier, which becomes unviable because there are more than 1500 descriptions and 1 million characters.
So, I think, I may be wrong, that this translation would be better if it were somehow dynamic, just for the descriptions that would appear for the user.
Using the systran api for rapidapi, I can do the translation using the code presented there, but I don't know how to use the output to replace the original text.
translate = $('#category_description').text()
var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate",
  data: {
        source: "en",
        target: "pt",
        input: translate,
      },
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "systran-systran-platform-for-language-processing-v1.p.rapidapi.com",
        "x-rapidapi-key": "7f58b5667bmshd95c9dc930cbf6ap1d0268jsnd64f23091817"
    },
}

$.ajax(settings).done(function (response) {
  console.log(response)

});

Output:
Object {
outputs: [Object {
output: "
Olá! mundo!
Olá! mundo!
Olá! mundo!
",
stats: Object {
elapsed_time: 26,
nb_characters: 36,
nb_tokens: 9,
nb_tus: 3,

Thank you for your help

A:

var btnTranslate = document.querySelector("button[name='btnTranslate']");

btnTranslate.addEventListener("click", TextTranslator);

function TextTranslator(){

    var divTranslateContent = document.querySelector("div[id='category_description']");

    var elements = divTranslateContent.querySelectorAll("p");

    var translatedTexts = [];

    for (var i = 0; i < elements.length; i++) {
        translatedTexts.push(elements[i].innerText);
    }

    InvokeAPITranslator(translatedTexts.toString().replace(","," . "), ReplaceText, elements);

}

function ReplaceText(response, elementsP){
    var arrayOfStrings = response.outputs[0].output.split(".");

    for (var i = 0; i < arrayOfStrings.length; i++) {
        elementsP[i].innerText = arrayOfStrings[i].trim();
    }
}

function InvokeAPITranslator(textToTranslate, callback, elementsP){

    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://systran-systran-platform-for-language-processing-v1.p.rapidapi.com/translation/text/translate",
      data: {
            source: "en",
            target: "pt",
            input: textToTranslate,
          },
        "method": "GET",
        "headers": {
            "x-rapidapi-host": "systran-systran-platform-for-language-processing-v1.p.rapidapi.com",
            "x-rapidapi-key": "7f58b5667bmshd95c9dc930cbf6ap1d0268jsnd64f23091817"
        },
    }

    $.ajax(settings).done(function (response) {
      callback(response, elementsP)
    });
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Trad</title>
    <link rel="stylesheet" type="text/css" href="style.css">

    <select class="form-control" id="category">
    </select>
    <button type="button" name="btnTranslate">Click Me!</button>

First text to be modified

Second text to be modified

Text that should not be modified


text:
Q: How to do server side rendering with node reactjs? I have created a sample project in reactjs and using node for backend. I have build react project with webpack. Now I want to render my react app from the server-side but got stuck with an error:
const express = require('express');
const path = require('path');
const logger = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');

const { renderToString } = require("react-dom/server");
const { StaticRouter } =  require("react-router-dom")
const React = require("react");
const App = require('./src/App')

const session = require('express-session');
const routes = require('./server/index');

const port = process.env.PORT || 3000;

const app = express();

app.use(express.static(path.join(__dirname, 'dist')));

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));

//app.use(cookieParser());

app.use(function (req, res, next) {
  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', '*');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST');

  // Request headers you wish to allow
  res.setHeader(
    'Access-Control-Allow-Headers',
    'X-Requested-With,content-type',
  );

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});

// end

app.use('/', routes);

app.use((req, res, next) => {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

if (app.get('env') === 'development') {
  app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.json({
      message: err.message,
      error: err,
    });
  });
}

app.use((err, req, res, next) => {
  res.status(err.status || 500);
  res.json({
    message: err.message,
    error: {},
  });
});

 router.get("*", (req, res) => {
   // Render the component to a string.
   const html = ReactDOMServer.renderToString(
     <StaticRouter location={req.url} context={context}>
       <App />
     </StaticRouter>

   );
   const finalDocument =`

                             <title>Your App Title</title>

${html}

                         `;
     res.send(finalDocument);
 });

app.listen(port, () => {
  console.log('Api Server running on port' + port);
});

module.exports = app;

package.json

{
  "name": "ssrnodereact",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.12.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^11.2.7",
    "@testing-library/user-event": "^12.8.3",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "cryptr": "^6.0.2",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "express-session": "^1.17.2",
    "formik": "^2.2.9",
    "helmet": "^4.6.0",
    "morgan": "^1.10.0",
    "nodemailer": "^6.6.3",
    "path": "^0.12.7",
    "pg": "^8.7.1",
    "prettier": "^2.3.2",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-ga": "^3.3.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.3.5",
    "web-vitals": "^1.1.2",
    "yup": "^0.32.9"
  },
  "scripts": {
    "build": "webpack --mode production",
    "start": "npm run build && nodemon server.js",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "format": "prettier --write ./**/*.{js,jsx,ts,tsx,css,md,json,html} --config ./.prettierrc"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/preset-env": "^7.15.0",
    "@babel/preset-react": "^7.14.5",
    "babel-loader": "^8.2.2",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^3.2.0",
    "react-hot-loader": "^4.13.0",
    "ts-loader": "^8.3.0",
    "webpack": "^4.44.0",
    "webpack-cli": "^4.7.2",
    "webpack-dev-server": "^3.11.2"
  }
}

 Got following error:

error
I have tried the following solutions but have not been able to resolve the error:
React Serverside rendering Unexpected token, JSX and Babel

A: I'm not sure if React is a framework that suits your needs. Server-side rendering can be accomplished much easier and more efficiently using a framework like NextJS.

A: You can check this plugin and it has examples for you to do the SSR easily.


text:
Q: How to know camera preview successful or ready to snapshot using Directshow I develop an application using .Net Directshow.
Is there any way to get notify message when camera preview successful or ready to snapshot

A: For a live video source there might be no immediately available preview frame (by design). At some times you might be able to detect that a frame is being streamed through the pipeline and will eventually reach the renderer and you also don't specify the snapshot method. There is no specific event and in general you are supposed to poll if you are waiting for preview frame to arrive.
If you happen to have a filter in the pipeline, which streams video frames through (which can be basically any custom filter, such as, for example, processing filter as simple as transform-in-place or even sample grabber with a callback) then you might be able to use it as a replacement for event in question: when video frame passes such filter, video renderer is expected to be able to deliver a snapshot soon afterwards.


text:
Q: Asymptotics of the Steenrod algebra / $s$-partitions? Recall that an $s$-partition is a partition of a natural number $n$ such that each part is of the form $2^r-1$. By a fundamental theorem of Milnor, the number $p_s(n)$ of $s$-partitions of $n$ counts the dimension of the mod-2 Steenrod algebra in degree $n$. I'm interested in the asymptotics of the function $p_s(n)$, as well as related functions for the odd-primary Steenrod algebras.
Questions:

*

*Does the number of $s$-partitions $p_s(n)$ grow subexponentially in $n$?

*If so, are there effective constants $p_s(n) \leq C_\epsilon (1+\epsilon)^n$?

*What about the dimension of the odd-primary Steenrod algebras?
The OEIS page (here's the link again) leads to this paper which gives an asymptotic formula for $\ln p_s(n)$, and all the terms are indeed sublinear in $n$, except possibly for the term involving a handicrafted function $W(z)$, whose growth I don't know how to estimate.
As for the odd-primary Steenrod algebras, Milnor showed that for $p$ an odd prime, the dual Steenrod algebra at the prime $p$ is the tensor product $P(\xi_1,\xi_2,\dots) \otimes E(\tau_0,\tau_1,\tau_2,\dots)$ where $deg(\xi_i) = 2p^i - 2$, $deg(\tau_i = 2p^i - 1)$, and $P, E$ denote polynomial and exterior algebras respectively, over $\mathbb F_p$. So counting the dimension reduces to a combinatorial partition problem of a similar flavor.

A: My original answer, below the horizontal rule, was based on a misunderstanding.  I'm preserving it so that the comments make sense.
For a fixed odd prime $p$, the generating function for the corresponding partitions is
$$ \frac{\prod_{i\ge0}(1+x^{2p^i-1})}{\prod_{i\ge1} (1-x^{2p^i-2})}.$$
@Dvitek in the comments explains nicely why we want the $2p^i-1$ parts to appear at most once while the $2p^i-2$ parts can be repeated arbitrarily often.
For instance, for $p = 3$ the first 30 coefficients (from $n=1$) are
$$1, 0, 0, 1, 2, 1, 0, 1, 2, 1, 0, 1, 2, 1, 0, 2, 4, 2, 0, 2, 5, 4, 1, 2, 5, 4, 1, 2, 5, 4.$$
There's a variant of the Frobenius problem here: $x^{19}$ is the highest power with coefficient 0.  In other words, 19 is the largest positive integer that cannot be made with parts 1, 5, 17 appearing at most once and parts 4 and 16 with no restrictions.  For $p=5$, I verified that the last 0 occurs for $n=39{,}047$.  For $p=7$, I believe the corresponding number is $659{,}108{,}891$.  (If that's an interesting value to find in general, I can explain my thinking.)

A near(ish) miss on (3) that's too long for a comment but might still be helpful as more than a cautionary tale.
I put the generating function
$$ \frac{1}{(1-x) \prod_{p,i} (1-x^{2p^i-2})(1-x^{2p^i-1})}$$
into Mathematica, with odd primes $p$ and exponents $i \ge 1$. (The $(1-x)$ factor handles the $i=0$ case of $(1-x^{2p^i-1})$.)  The sequence begins
$$ 1,1,1,2,3,3,3,5,7,8,8,11,15,17,18,23,30,35,37,45$$
which matches OEIS A035362. That sequence has a much simpler description: partitions with parts $4k$ or $4k+1$.  Why should that be the same?
Fortunately, before thinking too much about the connection, I computed more terms and realized that, in fact, the sequences do not match.  The first discrepancy happens at $n=28$.  The parts for the partitions counted here are everything of the form $4k$ or $4k+1$ up to 25, but not 28, which is a part for the OEIS description.  That is, 28 is the smallest positive multiple of 4 that cannot be written as $2p^i-2$ for some prime $p$ and integer $i \ge 0$.
Back to your question, the asymptotics of the partitions you care about are bounded above by the partitions with parts of the form $4k$ and $4k+1$.  The OEIS page includes an asymptotic expression for those given by Vaclav Kotesovec.


text:
Q: TypeError: invalid 'in' operand a in a class
I have some JavaScript code here that uses JQuery to create a class and to use class functions then.
function sample(a, b)
{
    var id = a;
    var img_src = b;

    this.getId = function()
    {
        return id;
    };

    this.move = function(pTop, pLeft)
    {
        var p = $(this).position();
        var mov_top = p.top + pTop;
        var mov_left = p.left + pLeft;
        $(this).animate({
            top: mov_top,
            left: mov_left
        });
    }
}

And I am calling it when clicking a button :
<button onclick="create(3);">Click me :D</button>

<script>
    function create(id)
    {
        var mySample = new sample(id, 'url');
        mySample.move(50, 50);
    }
</script>

And this returns me the error TypeError: invalid 'in' operand a but I don't see where it comes from...
Do anyone has an idea?

A: Try passing this to create() instead of 3 which should be a within sample() , setting button css position to relative

function sample(a, b)
{
    var id = a;
    var img_src = b;

    this.getId = function()
    {
        return id;
    };

    this.move = function(pTop, pLeft)
    {
        var p = $(a).position();
        var mov_top = p.top + pTop;
        var mov_left = p.left + pLeft;
        $(a).animate({
            top: mov_top,
            left: mov_left
        });
    }
}
button {
  position:relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<button onclick="create(this);">Click me :D</button>

<script>
    function create(id)
    {
        var mySample = new sample(id, 'url');
        mySample.move(50, 50);
    }
</script>


text:
Q: Changing LineWidth messes up the marker I am using Matlab 2017b. When I change the default line width, the circular marker becomes choppy, as if Matlab is 'out of ink'. The following code:
figure
subplot(211)
plot([1 2],[1 2],'o-','markersize',12)
xlim([0,3]), ylim([0,3])
subplot(212)
plot([1 2],[1 2],'o-','markersize',12,'linewidth',2)
xlim([0,3]), ylim([0,3])

produces this result:

EDIT Forgot to mention OS, win 10 64 bit

A: Turns out it's one of those 'renderer' voodoo (in the sense that trial-and-error is the easiest approach), see this related question: MATLAB Figure Rendering: OpenGL vs. Painters?
If I do this:
set(gcf, 'Renderer', 'painters');

Then the marker looks as it should.


text:
Q: Protect a multi tenant Azure ad protected api in a microservice architecture My question is regarding a multi tenant, Azure AD authenticated, microservice architecture in which I allow customers to consumer via an api.
Lets say my architecture is made up of service A, service B and service C, each has an api for the microservice. Each api requires authentication, therefore there is an app registration for A,B and C. Each service has user roles, user and admin, for authorization within the api's.
My questions are:

*

*If a customer wants to consume the api's this would mean they need the enterprise app for each service in their tenant. This feels like we would be bloating their app registrations. Even if I wrote an api to wrap all the service api's, the service api's would still need a jwt therefore would still need registering in the client tenant. How can I avoid so may registrations?

*As each service api relies on user roles, admin and user. This would mean a clients sys admin would have to go through each registration apply users to relevant roles, over and over again. This seems like a management nightmare for a client. Is there a way around this.

*There is likely to be some endpoints in the services which are for internal use, not clients. How do I restrict what scopes are mad available to the client tenants to protect them endpoints?


text:
Q: Ignoring a folder from my repo using gitignore Im trying to ignore a wordpress plugin folder form my git repo via .gitignore. Ive tried blocking the folder by using :

/wp-snapshots/*
/wp-snapshots/
wp-snapshots
wp-snapshots/
wp-snapshots/*
/wp-snapshots

But not of the above works any ideas how i can block this file ?

A: if your folder name is wp-snapshots and you want to block it, your .gitignore file should contain the entry wp-snapshots only without slashes. Just make sure that your .gitignore file is located in the  directory which contains the wp-snapshots folder.
Thus if your folder structure is root/plugins/wp-snapshots, then your .gitignore should be at root/ or can be at max in root/plugins/, but if it is located at say, root/src, it won't work.


text:
Q: Finding closest value to a target in BST, but running into variable referenced before assignment, even though I have covered all cases? I am writing code to solve the following problem: we are given a binary search tree, and a target integer value. Our task is to find the closest value in the BST to this target.
Here is my code:
def findClosestValueInBst(tree, target,):
    return findClosestValueInBstHelper(tree, target, float("inf"))

def findClosestValueInBstHelper(tree, target,closest):
    if tree.value == target:
        return target
    if not tree:
        return closest
    closer = min(abs(target - tree.value), closest)
    if abs(target - tree.value)<closest:
        output = tree.value
    if tree.value<target and tree.right:
        return findClosestValueInBstHelper(tree.right,target,closer)
    elif tree.value>target and tree.left:
        return findClosestValueInBstHelper(tree.left, target, closer)

    elif tree.value<target and not tree.right:
        if abs(target-tree.value)<closest:
            return tree.value
    elif tree.value>target and not tree.left:
        if abs(target-tree.value)<closest:
            return tree.value
    return output

Now my code passes half of the tests cases but fails the other half, and I run into the error 'output referenced before assignment' for the final line- I do know what this means; that the code is returning output before it is assigned to anything, however I thought that in my code above this line I have covered all possible scenarios and 'output' will be equal to a value.
Any ideas why I am running into this error?


text:
Q: R - Speed up subsetting data table based on another one? I have a data table dat1 with daily rainfall measurements for multiple sites:
> dat1
              date   ID value
     1: 2000-03-01 1559     0
     2: 2000-03-02 1559     0
     3: 2000-03-03 1559     0
     4: 2000-03-04 1559     0
     5: 2000-03-05 1559     0
    ---
106178: 2019-12-27 1322     2
106179: 2019-12-28 1322     1
106180: 2019-12-29 1322     2
106181: 2019-12-30 1322     2
106182: 2019-12-31 1322     0

and I also have another data table dat2 with each site in dat1 along with some neighbour sites, the distance between them, and the measurement dates they have in common:
> dat2
     ID1  ID2      dist common_date_begin common_date_end diff_days
 1: 1549 1550 490774.05        2010-02-23      2017-06-16      2670
 2: 1549 1551 290832.68        2010-02-23      2017-06-16      2670
 3: 1549 1552  87750.38        2006-02-01      2017-06-16      4153
 4: 1549 1553 138531.18        2006-02-01      2017-06-16      4153
 5: 1549 1554 103870.34        2000-03-01      2017-06-16      6316
 6: 1549 1555 112919.70        2000-03-01      2017-06-16      6316
 7: 1549 1556  19625.65        2000-03-01      2017-06-16      6316
 8: 1549 1557 398693.43        2000-03-01      2017-06-16      6316
 9: 1549 1558  73514.23        2000-03-01      2017-06-16      6316
10: 1549 1559 129691.63        2000-03-01      2017-06-16      6316

For each ID1-ID2 pair in dat2, I want to subset those stations in dat1 and calculate the correlation between the two sites.
The following code achieves what I need:
library(data.table)
dat1 <- fread("https://www.dropbox.com/s/d2s61du255vzu7g/dat1.csv?dl=1") # ~2 MB
dat2 <- fread("https://www.dropbox.com/s/7n0z0gbeoifss4j/dat2.csv?dl=1") # ~5 KB

# fix column classes
dat1$date <- as.Date(dat1$date)
dat1$ID <- as.character(dat1$ID)
dat2[, (c("common_date_begin","common_date_end")) := lapply(.SD, as.Date), .SDcols = c("common_date_begin","common_date_end")]
dat2[, (c("ID1","ID2")) := lapply(.SD, as.character), .SDcols = c("ID1","ID2")]

# get list of unique stations
ids <- unique(dat2$ID1)

# initialize matrix to hold correlations
correlations <- matrix(NA, nrow = nrow(dat2), ncol=1)

# initialize data frame to hold results
results <- as.data.frame(dat2[, -c(4:5)])

# initialize loop counters
x <- 1

# loop over the main ID's
for (i in ids) {

  tmp <- dat2[ID1==i]

  #loop over the ID's of the neighbour stations
  for (id in 1:nrow(tmp)){

    # get ID of the neighbours
    near_id <- as.numeric(tmp[id, 2])

    # get common dates
    beg_date <- tmp[id, 4]
    end_date <- tmp[id, 5]

    # calculate correlations
    correlations[x,1] <- cor(dat1[ID==i & date %between% c(beg_date, end_date)]$value,
                             dat1[ID==near_id & date %between% c(beg_date, end_date)]$value)
    # increment loop counter
    x <- x + 1
  }
}

# assemble final data frame
results <- data.table(ID=results[, 1],
                      ID_nearest=results[, 2],
                      distance=results[, 3],
                      overlapping_days=results[, 4],
                      correl=as.vector(correlations))

It works quite fast for this toy example. However, it takes forever on my real, 4-million-row data table. I waited for ~ 3 hours and have not seen the processing coming to an end.
So my questions are: is there any way to speed-up the above code, excluding translating it to C++? Since I have 32 cores available, would the code qualify for any multicore approach? mclapply or foreach? Any starting hints on either one?

A: Your code could be speeded up by using joins to match id-pairs in dat2 with measurements in dat1 instead of for-loops. By the way: At least in my opinion using joins makes the code also more concise and cleaner. And more robust.
Note further: I found a bug in your code. Setting up the matrix of correlations using correlations[x,1] results in assigning correlations to wrong id-pairs.
Benchmark
To compare with your approach I set up two functions: cor_join which implements a simple tidyverse approach of this idea and cor_loopwhich is a wrapper around your code.
Microbenchmarking both functions shows that using joins speeds-up the compuations by factor ~2.5. I'm not familiar with data.table but I would guess that using data.table or dtplyr (data table backend to dplyr) could increase the performance further especially on your real data set.
library(data.table)
library(dplyr)
library(purrr)
library(ggplot2)
library(microbenchmark)

dat1 <- fread("https://www.dropbox.com/s/d2s61du255vzu7g/dat1.csv?dl=1") # ~2 MB
dat2 <- fread("https://www.dropbox.com/s/7n0z0gbeoifss4j/dat2.csv?dl=1") # ~5 KB

# fix column classes
dat1$date <- as.Date(dat1$date)
dat1$ID <- as.character(dat1$ID)
dat2[, (c("common_date_begin","common_date_end")) := lapply(.SD, as.Date), .SDcols = c("common_date_begin","common_date_end")]
dat2[, (c("ID1","ID2")) := lapply(.SD, as.character), .SDcols = c("ID1","ID2")]

cor_join <- function(dat1, dat2) {
  # We want to get a dataframe with
  #
  # 1. pairs of sites,
  # 2. dates where we have measurements for both
  # 3. the measurements at each site
  #
  # This could be achieved via left_joins
  dat3 <- dat2 %>%
    # Join dates and measurements for ID1
    left_join(dat1, by = c("ID1" = "ID")) %>%
    rename(value1 = value) %>%
    # Join dates and measurements for ID2 on the same date
    left_join(dat1, by = c("ID2" = "ID", "date" = "date")) %>%
    rename(value2 = value, ID = ID1, ID_nearest = ID2)
  dat3

  # Compute correlations
  dat3 %>%
    # Drop missings, i.e. observations with no common dates
    filter(date >= common_date_begin & date <= common_date_end) %>%
    group_by(ID, ID_nearest, dist, common_date_begin, common_date_end, diff_days) %>%
    summarise(correl = cor(value1, value2)) %>%
    ungroup()
}

cor_loop <- function(dat1, dat2) {
  # get list of unique stations
  ids <- unique(dat2$ID1)

  # initialize matrix to hold correlations
  correlations <- matrix(NA, nrow = nrow(dat2), ncol=1)

  # initialize data frame to hold results
  results <- as.data.frame(dat2[, -c(4:5)])

  # initialize loop counters
  x <- 1

  # loop over the main ID's
  for (i in ids) {

    tmp <- dat2[ID1==i]

    #loop over the ID's of the neighbour stations
    for (id in 1:nrow(tmp)){

      # get ID of the neighbours
      near_id <- as.numeric(tmp[id, 2])

      # get common dates
      beg_date <- tmp[id, 4]
      end_date <- tmp[id, 5]

      # calculate correlations
      correlations[x,1] <- cor(dat1[ID==i & date %between% c(beg_date, end_date)]$value,
                               dat1[ID==near_id & date %between% c(beg_date, end_date)]$value)

      # increment loop counter
      x <- x + 1
    }
  }

  # assemble final data frame
  results <- data.table(ID=results[, 1],
                        ID_nearest=results[, 2],
                        distance=results[, 3],
                        overlapping_days=results[, 4],
                        correl=as.vector(correlations))
  results
}

# microbenchmark
microbenchmark::microbenchmark(cor_join(dat1, dat2), cor_loop(dat1, dat2), times = 10)
#> Unit: milliseconds
#>                  expr      min       lq     mean   median       uq      max
#>  cor_join(dat1, dat2) 247.4106 286.1556 301.6367 296.6921 302.2751 400.8654
#>  cor_loop(dat1, dat2) 773.5274 784.9197 807.3767 798.4800 842.3080 854.1716
#>  neval
#>     10
#>     10

Check results
To check that both functions give same results I made a scatterplot
# Check result
results <- list(join = cor_join(dat1, dat2), loop = cor_loop(dat1, dat2))

# Plot
check <- results %>%
  purrr::reduce(left_join, by = c("ID", "ID_nearest"), suffix = c("_join", "_loop"))
check %>%
  ggplot(aes(correl_join, correl_loop, color = ID)) +
  geom_point()

OOPS: Scatterplot shows differing results? To check that I used a simple dataset where I filtered the datasets for sites 1183, 1550 and 1551:
dat1a <- dat1 %>% filter(ID %in% c(1183, 1550, 1551)) %>% as.data.table()
dat2a <- dat2 %>% filter(ID1 %in% c(1183, 1550, 1551), ID2 %in% c(1183, 1550, 1551)) %>% as.data.table()

# For the simple dataset I get the same correlations
cor_join(dat1a, dat2a)
#> # A tibble: 2 x 7
#>   ID    ID_nearest     dist common_date_begin common_date_end diff_days  correl
#>   <chr> <chr>         <dbl> <date>            <date>              <int>   <dbl>
#> 1 1183  1550       1576360. 2010-02-23        2017-06-16           2670  0.0456
#> 2 1183  1551       1513356. 2010-02-23        2017-06-16           2670 -0.0251
cor_loop(dat1a, dat2a)
#>      ID ID_nearest distance overlapping_days      correl
#> 1: 1183       1550  1576360             2670  0.04564506
#> 2: 1183       1551  1513356             2670 -0.02513991

After inspecting your code I guessed that the differences arise from assigning correlations to wrong id-pairs due to correlations[x,1]. To check I adjusted cor_loop. Besides returning the df results it also return a second df correlations2 which is set up in the loop and contains not only the correlation but also the corresponding value of id and near_id:
cor_loop_check <- function(dat1, dat2) {
  # get list of unique stations
  ids <- unique(dat2$ID1)

  # initialize matrix to hold correlations
  correlations <- matrix(NA, nrow = nrow(dat2), ncol=1)
  correlations2 <- data.frame(id1 = rep(NA, nrow(dat2)),
                              id2 = rep(NA, nrow(dat2)),
                              correl = rep(NA, nrow(dat2)))

  # initialize data frame to hold results
  results <- as.data.frame(dat2[, -c(4:5)])

  # initialize loop counters
  x <- 1

  # loop over the main ID's
  for (i in ids) {

    tmp <- dat2[ID1==i]

    #loop over the ID's of the neighbour stations
    for (id in 1:nrow(tmp)){

      # get ID of the neighbours
      near_id <- as.numeric(tmp[id, 2])

      # get common dates
      beg_date <- tmp[id, 4]
      end_date <- tmp[id, 5]

      # calculate correlations
      correlations[x,1] <- cor(dat1[ID==i & date %between% c(beg_date, end_date)]$value,
                               dat1[ID==near_id & date %between% c(beg_date, end_date)]$value)

      # Put correlation in df together with current id and near id
      correlations2[x, "id1"] <- i
      correlations2[x, "id2"] <- near_id
      correlations2[x, "correl"] <- correlations[x,1]

      # increment loop counter
      x <- x + 1
    }
  }

  # assemble final data frame
  results <- data.table(ID=results[, 1],
                        ID_nearest=results[, 2],
                        distance=results[, 3],
                        overlapping_days=results[, 4],
                        correl=as.vector(correlations))

  list(results, correlations2)
}

results_check <- cor_loop_check(dat1, dat2)

# Check results for e.g. row 20: Same value for correlation but differing id-pair ):
results_check[[1]][20,]
#>      ID ID_nearest distance overlapping_days      correl
#> 1: 1315       1551  1193032             2670 -0.06323207
results_check[[2]][20,]
#>     id1  id2      correl
#> 20 1315 1559 -0.06323207

Created on 2020-03-14 by the reprex package (v0.3.0)
As you see. In line 20 both df's contain the same correlation but a different ID pair.


text:
Q: AS3 KeyboardEvents not firing until after I've clicked on an onscreen button So here's my setup:
My document class is Main.as (it extends MovieClip). The following code is in my Main.as.
I've declared all these variables in my class definition:
private var holder:MovieClip;
private var leftButton:SimpleButton;
private var rightButton:SimpleButton;

in constructor...
holder = new MovieClip();
addChild(holder);
holder.addEventListener(KeyboardEvent.KEY_UP, handleKeyboardEvent);

leftButton = new Arrow();
rightButton = new Arrow();

holder.addChild(leftButton);
holder.addChild(rightButton);

leftButton.x = 50;
leftButton.rotation = 180;
rightButton.x = 150;

leftButton.y = rightButton.y = 50;

leftButton.addEventListener(MouseEvent.CLICK, handlePaging);
rightButton.addEventListener(MouseEvent.CLICK, handlePaging);

...outside of constructor...
public function handleKeyboardEvent ( e:KeyboardEvent ) {
            trace("got a keyboard event");

                trace("e.charCode : " + e.charCode);
                trace("e.keyCode : " + e.keyCode);
                switch (e.keyCode) {
                    case 37: //left arrow
                        showPreviousMoment();
                        break;
                    case 39: //right arrow
                        showNextMoment();
                        break;
                }

        }

The two buttons are instances of an Arrow movieclip that I have in the library. The Arrow movie clip just has graphics in it (in the property dialog for it the base class is flash.display.SimpleButton).
I want the user to be able to press the onscreen arrows OR the keyboard arrow keys to page forwards and backwards.
So...when I test the movie or publish it as an app, pressing the left and right keyboard keys doesn't do anything. HOWEVER...AFTER I click on the screen arrows THEN the keyboard events are getting picked up!!!  How come my keyboard events are not getting received initially? Why does clicking on the onscreen buttons make the 'holder' start receiving the events?
UPDATE
I've also just commented out all of my code EXCEPT for the instantiating the 'holder' and adding the listener.
The KeyboardEvents are not being heard by the holder.
UPDATE...ANSWER
So I found out that if I want to globally hear the KeyboardEvent, I should register stage as the listener. So this did the trick:
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyboardEvent);

Info from Colin Moock's book:

Keyboard-input events that trigger
  application-wide commands are
  typically handled globally, by
  listeners registered with Flash
  Player's Stage instance. By contrast,
  keyboard-input events that trigger a
  specific interface-element response
  are typically handled by listeners
  registered with the object that
  currently has keyboard focus.

So I guess that in my initial version, when I clicked on the onscreen arrow button, I somehow gave keyboard focus to the 'holder;.

A: Ususally the object you click on gets the focus. This really affects listeners, that's why it works when you add it to the stage.
When you clicked on any of those, your "holder" object got the focus, therefore the event fired. Now you do it well, that you added it to the stage.

A: A more dynamic solution (say if you dynamically instance a class which contains a movieclip) is to use:
stage.focus = this;

So if you apply the event listener to the class instance that actually needs to listen to key events, this might work better for you.
For me the previous suggestions didn't work as I was adding my main class instance at run-time. In the end I my code looked like this:
Main.singletron.stage.addEventListener(KeyboardEvent.KEY_UP, checkKeyDown);
Main.singletron.stage.focus = this;

...you'll have to set up a singletron for those 2 lines to work.

A: I'm posting the answer to my own question based on @Ascension Systems recommendation. I'm just really copying from my update to my question above.
UPDATE...ANSWER
So I found out that if I want to globally hear the KeyboardEvent, I should register stage as the listener. So this did the trick:
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyboardEvent);

Info from Colin Moock's book:

Keyboard-input events that trigger
  application-wide commands are
  typically handled globally, by
  listeners registered with Flash
  Player's Stage instance. By contrast,
  keyboard-input events that trigger a
  specific interface-element response
  are typically handled by listeners
  registered with the object that
  currently has keyboard focus.

So I guess that in my initial version, when I clicked on the onscreen arrow button, I somehow gave keyboard focus to the 'holder'.


text:
Q: Keep Indexing when Sorting Vector c++ I am very new to c++ and can't find a way to keep track of my vector indexing after sorting an vector.
So far I have:
static bool sortlowtohighinternal(double u, double v) //internal use in sortlowtohigh
{
    return u < v;
}

vector<double> sortlowtohigh(vector<double> v){

sort(v.begin(), v.end(), sortlowtohighinternal);

    return v;
}

which will sort the vector<double> from low to high but it also reindexes the vector. Is it possible to get something like:
Input Vector: {1.0, 3.0, 2.0}
Output Sorted Vector: {1.0, 2.0, 3.0}
Output Of Indexes from Input Vector: {1, 3, 2}


text:
Q: Typescript type transform While working my way through typescript types, I have a question about transformations. I have the following type:
export type DataChampLogLevel = 'debug' | 'verbose' | 'info' | 'warning' | 'error'

No it is the case that some loggers only accept debug while others expect verbose
I have a logging facade which expects DataChampLoglevel
export interface DataChampLogger {

  setLogLevel(level: DataChampLogLevel): void

}

//implementation

  setLogLevel(level: DataChampLogLevel): void {
    SomeLogger.setLogLevel(level) // compiler type error debug is not allowed in type OtherLogLevel..
  }

internally I need to convert the value from e.g. debug to verbose while it is rather simple to write a convert function I was wondering if the same was possible with typesxript types e.g. String Templates or the like. I was playing around a bit but was not able to come up with the proper solution.
This is just my own curiosity to improve my skills ;)
Regards
Mathias

A:
I was wondering if the same was possible with typesxript types

No. What you're describing is a runtime value conversion. TypeScript types don't exist at runtime (other than a small caveat around enums). So there's no TypeScript type solution to this. You'll need a runtime solution to modify a runtime value.
There may or may not be a type aspect to this as well, since SomeLogger.setLogLevel seems to accept a different type from DataChampLogLevel, so you'll need a way to tell TypeScript that the (updated) value is allowed for SomeLogger.setLogLevel. But it can't help with the runtime side of it.
For instance, let's say that SomeLogger.setLogLevel accepts a SomeLoggerLogLevel which is:
type SomeLoggerLogLevel = 'verbose' | 'info' | 'warning' | 'error';

In that case, there's no need to do anything explicit with the type, since TypeScript's flow analysis can see you handling it inline if you do something like:
setLogLevel(level: DataChampLogLevel): void {
    if (level === "debug") {
        level = "verbose";
    }
    SomeLogger.setLogLevel(level);
}

But if you do it another way (like a lookup table), you may need to reassure TypeScript that your runtime conversion is correct. For instance, TypeScript won't be happy with this:
const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        SomeLogger.setLogLevel(level); // Argument of type 'DataChampLogLevel' is not assignable to parameter of type 'SomeLoggerLogLevel'.
    }
};

but if you add a type assertion function, it's happy:
const logLevelMap: Partial<Record<DataChampLogLevel, SomeLoggerLogLevel>> = {
    debug: "verbose",
};

function assertsIsValidSomeLoggerLogLevel(level: DataChampLogLevel): asserts level is SomeLoggerLogLevel {
    if (level in logLevelMap) {
        throw new Error(`Invalid SomeLoggerLogLevel "${level}"`);
    }
}

const obj: DataChampLogger = {
    setLogLevel(level: DataChampLogLevel): void {
        level = logLevelMap[level] ?? level;
        assertsIsValidSomeLoggerLogLevel(level);
        SomeLogger.setLogLevel(level);
    }
};


text:
Q: What's the output of 'd = {0, 1, 2} for x in d: print(d.add(x)) .And why? The Python code is:
d = {0, 1, 2}
for x in d:
    print(d.add(x))

What is the output, and why?

A: The output is just
None
None
None

This is because d.add(x) adds x to the set and returns None.

A: Let's understand this step by step
(1) d is a set of elements{0,1,2}
(2)Set is a data structure which has only unique values
Loop:
(3)for x in d:
print(d.add(x))
this will take each element from the set and add it to self (d.add(x))
AND it returns nothing.
(4)You will get the output three times None because the loop will run three times
As it is a set adding elements to itself will return the original set(It will discard the duplicate entries)


text:
Q: OpenCart 3: system cache cleaning, ocmod and twig. I made changes in controller but its not reflecting I want to change something related to product attributes in the product details page: /index.php?route=product/product&product_id=100
So I changed
\catalog\controller\product\product.php file and saved it.
but it's not reflecting my changes even I removed the cache and refreshed the page but it's not working.
Even I removed the whole code in the PHP file. But it's not reflecting my changes

A: If you are using OpenCart 3 - it might be ocmod cache or twig cache.
To clear twig cache in your admin dashboard click on the gear button on top right corner, and then clear the Theme cache.

To clear ocmod cache in admin panel go to Extensions - Modifications and click reload button in top right corner.


text:
Q: DataGrid row selection not working when padding is added to cells DataGrid control in WPF is behaving weird. When I click on a row it should be selected.
There is a problem when I click on cell border or row border. It simply does nothing. As a user I want to click row and select it without forcing me to re-click cause I accidentally clicked on border between cells.
Is it possible to somehow fix this behavior so no matter where I click it selects row?

[edit]
I discovered its a matter of this style I applied to DataGrid to CellStyle property:
<Style x:Key="CustomDataGridCellStyle" TargetType="DataGridCell">
    <Setter Property="Padding" Value="2" />
    <Setter Property="Margin" Value="0" />
    <Setter Property="Background" Value="White" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DataGridCell">
                <Border x:Name="border"
                              BorderBrush="#CCaaccda"
                              BorderThickness="1"
                              CornerRadius="0"
                              Padding="4"
                            >
                    <ContentPresenter />
                </Border>
                <ControlTemplate.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="true">
                        <Setter TargetName="border" Property="Background" Value="#CC119EDA"/>
                    </DataTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

If I remove it its working. I wander how style can mess with interactions to control.

[edit]
Padding="4"

is preventing the created empty area between cells to not be able to take hit test. Any idea how to add not hittest blocking padding to cells?

[edit]
And the solution is very weird.
<Grid Background="Transparent" IsHitTestVisible="True">
    <ContentPresenter Margin="4"/>
</Grid>

Margin is added to cell content and its not reacting to click. But I surrounded it with Grid that have IsHitTestVisible="True" and is transparent. WPF is crazy weird.

A: Since you hadn't posted any xaml, or a picture of how your datagrid looks.
It's hard to pint point the problem.
However, This might be caused by a Hit Test failing.
The mouse hit test detects an element by the matrix of colored pixels which represent it.
Try coloring all the pixels by setting the background to Transparent. Transparent would not effect how your row looks and would color it for the Hit test :
<DataGrid>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="Background" Value="Transparent" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>


text:
Q: Highlight text in primeng editor I am using primeng editor to allow the user to write some python code in my app. I want to highlight the text where there's any syntax error. I've gone through the following link syntax highlighting in quill.js but am unable to figure out how to use it.
How can I do this?
Currently I have this -
<p-editor [(ngModel)]="text" [style]="{'height':'320px'}"></p-editor>


text:
Q: Calling .js file function from code behind I have been trying to call .js file function from code behind but function is not being called.
I have this following html button which needs to be visible from the code behind.
   <input id="btnShowMap" type="button" value="Results On Map" onclick = "ShowMap();" style="visibility: hidden;"/>

I have tried following three methods so far and none of them is working.
 -ClientScript.RegisterStartupScript(Me.GetType(), "VoteJsFunc", "test();")

 -Page.ClientScript.RegisterStartupScript(Me.[GetType](), "VoteJsFunc", "alert('Sorry.You are not legible to vote')", True)

 -ClientScript.RegisterStartupScript(Me.GetType(), "VoteJsFunc", "test();")

Here is .js file function
function test() {
var hdLat = $('input[id$=hdVendorLat]').val();
    var hdLng = $('input[id$=hdVendorLng]').val();
    if (hdLat != 0 && hdLng != 0) {
        $('#btnShowMap').show();
    }
    else {
        $('#btnShowMap').hide();
    }
 }

Here is the pahe html
 <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
 </asp:Content>

 <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="updSearch" UpdateMode="Conditional" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnSearch" />
    </Triggers>
    <ContentTemplate>
        <asp:HiddenField ID="hdVendorLat" runat="server" Value="0" />
        <asp:HiddenField ID="hdVendorLng" runat="server" Value="0" />
        <asp:HiddenField ID="hdVenID" runat="server" Value="" />
  <asp:Panel ID="pnlExport" runat="server" Enabled="true">
  <asp:Button ID="btnSearch" runat="server" Text="Search" Width="90px" />
  <input id="btnShowMap" type="button" value="Results On Map" onclick   = "ShowMap();" style="visibility: hidden;"  />
</asp:Panel>

<script type="text/javascript" src="/scripts/inspector-search.js"></script>
    </ContentTemplate>
</asp:UpdatePanel>
</asp:Content>

A: try register script, like this:
Page.ClientScript.RegisterStartupScript(GetType(), "VoteJsFunc", "test()", True)

I checked this locally, worked fine.

A: jQuery method show works over display css property. It is equivalent to call .css( "display", "block").
Since you are using visibility property, method show has no effect on changing this so it remains hidden. I see 2 options to fix this:

*

*use .css( "visibility", "visible") instead of .show()

*replace style="visibility: hidden;" by style="display: none" on your input markup

A: You just need to invoce the mentioned .js file in html before you call the script from which you are calling the function. If you need more information, please include your HTML code.


text:
Q: Distance between points in a convex set and outside of a convex set. Let $W$ be a set of points in $\mathbb{R}^n$. Let $C$ be the convex hull of the members of $W$. Is there a simple way of demonstrating that for any $x \in C$ and any $y \in \mathbb{R}^n \backslash C$, there must be some $w \in W$ such that $\|w - x\| < \|w - y\|$?

A: Let $H=\{ z | \langle z,x-y\rangle = \frac{1}{2} (||x||^2-||y||^2)\} $ Then $H$ is a hyperplane perpendicular to $x-y$, that passes through $\frac{1}{2}(x+y)$.
Let $S$ be the half-space containing $x$, ie, $S=\{ z | \langle z,x-y\rangle \geq \frac{1}{2} (||x||^2-||y||^2)\} $. Note that $x \in S^{\circ}$. Also, note that if $z \in S^{\circ}$, then $||z-x|| < ||z-y||$.
Finally, since $x \in C$, we can write $x = \sum_{i=1}^k \lambda_i w_i$, with $w_i \in W$ and $\lambda_i$ are convex multipliers. Then at least one $w_{i'} \in S^{\circ}$, since $\langle x,x-y\rangle = \sum_{i=1}^k \lambda_i \langle w_i,x-y\rangle > \frac{1}{2} (||x||^2-||y||^2)$. Consequently, $||w_{i'}-x|| < ||w_{i'} -y||$, which is what you wanted to show.

A: As a counter example consider two points in $\mathbb{R}^2$, $W=\{(0,0),\,(2,0)\}$. Clearly $(1,0)$ is in the convex hull $C$ of $W$. The distance from this point to any point in $W$ is 1. However, the point $(1,\varepsilon)\in\mathbb{R}^n \setminus C$ is at a distance of $\varepsilon$ from $(1,0)$. then the statement is false for $-1< \varepsilon < 1$.


text:
Q: Comparing logistic regression models b/w non-independent samples I have run a fully adjusted logistic regression model for a sample whose data was collected in the year 2000. The outcome is retirement, and the predictors are individual characteristics, like age, gender, etc, and some health predictors as well.
I have run a second logistic regression model for a sample whose data was collected in the year 2008, with the same outcome and set of predictors.
I now want to compare the model coefficients using various methods, i.e. as an interaction term (predictors x year (2000 or 2008)), and using a Wald test to compare logit coefficients between the two "groups".
My problem is that about 50% of the people sampled in 2000 were sampled again in 2008 (that is if they didn't have the outcome in 2000, i.e. had not yet retired).
So I am wondering what are the limitations this setup causes? What should I be checking (in addition to the degree of overlap) that can estimate the effects of this design? So for example, how can I quantify the "issue" to explain to my readers the degree to which it is a problem? And finally, is there anything I can do to reduce any weaknesses the design causes?


text:
Q: Isn't F# supported in Visual Studio 2013 Update 3 and Azure SDK 2.4 I just installed Visual Studio 2013 Update 3 and Azure SDK 2.4. I also installed "Microsoft Azure Tools for Microsoft Visual Studio 2013 -v2.4". I also tried repairing and reinstalling both the sdk and the Azure tools.
I can see 4 templates under Cloud (Azure Cloud Service,ASP.NET web application,Microsoft Azure WebJob and Azure Mobile Service) when creating a C# project.
There is no Cloud folder and no Azure templates at all when creating a F# project.
Is F# not supported or is it something wrong with my installation? I think it was supported earlier.

A: The F# template for Worker Roles is available as you are creating your Cloud Service project.
Create a Cloud Service project using C# or Visual Basic.

Next, as you are selecting the roles for your cloud service, you can select the F# Worker Role.

Full Disclosure: I've not actually used the F# template.  I just recall seeing it when creating my C# projects.


text:
Q: MySQL Pivot data into Year Months I have two tables student and class fees, i want to get report to view that students paid their fees or not.
i tried this mysql query and this is i exactly wanted but there is an issue with month and years also im getting empty columns.
this is the query i tried

    SELECT
        student.stu_name,
        SUM(IF(MONTH(fees.date) = 1, fees.amt, 0)) AS Jan,
        SUM(IF(MONTH(fees.date) = 2, fees.amt, 0)) AS Feb,
        SUM(IF(MONTH(fees.date) = 3, fees.amt, 0)) AS Mar,
        SUM(IF(MONTH(fees.date) = 4, fees.amt, 0)) AS Apr,
        SUM(IF(MONTH(fees.date) = 5, fees.amt, 0)) AS May,
        SUM(IF(MONTH(fees.date) = 6, fees.amt, 0)) AS Jun,
        SUM(IF(MONTH(fees.date) = 7, fees.amt, 0)) AS Jul,
        SUM(IF(MONTH(fees.date) = 8, fees.amt, 0)) AS Aug,
        SUM(IF(MONTH(fees.date) = 9, fees.amt, 0)) AS Sep,
        SUM(IF(MONTH(fees.date) = 10, fees.amt, 0)) AS Oct,
        SUM(IF(MONTH(fees.date) = 11, fees.amt, 0)) AS Nov,
        SUM(IF(MONTH(fees.date) = 12, fees.amt, 0)) AS Dece,
        SUM(fees.amt) AS Total,
        (28000-(SUM(fees.amt))) AS Balance
    FROM
        `fees`
    INNER JOIN student ON fees.stu_id = student.id
    GROUP BY student.stu_id

This is the result i'm getting
if i add data in two years there will be a problem.
I want to get table like this (orders by month years)
i have been working on it for weeks but i couldnt find any solution. i appreciate if you can help me for this.

A: Is probably too late for this answer, but I would recomend a third table feedsTotals to set the total of feeds for each year. Like this:
create table feesTotals (
  id INT NOT NULL AUTO_INCREMENT,
  year INT,
  total DECIMAL(13,2),
  PRIMARY KEY (id)
);

INSERT INTO feesTotals(year,total)
VALUES (2018, 28000.00) , (2019, 29000.00);

Than you can do the query you want like this:
SELECT
        student.stu_name,
        feesTotals.year,
        SUM(IF(MONTH(fees.date) = 1, fees.amt, 0)) AS Jan,
        SUM(IF(MONTH(fees.date) = 2, fees.amt, 0)) AS Feb,
        SUM(IF(MONTH(fees.date) = 3, fees.amt, 0)) AS Mar,
        SUM(IF(MONTH(fees.date) = 4, fees.amt, 0)) AS Apr,
        SUM(IF(MONTH(fees.date) = 5, fees.amt, 0)) AS May,
        SUM(IF(MONTH(fees.date) = 6, fees.amt, 0)) AS Jun,
        SUM(IF(MONTH(fees.date) = 7, fees.amt, 0)) AS Jul,
        SUM(IF(MONTH(fees.date) = 8, fees.amt, 0)) AS Aug,
        SUM(IF(MONTH(fees.date) = 9, fees.amt, 0)) AS Sep,
        SUM(IF(MONTH(fees.date) = 10, fees.amt, 0)) AS Oct,
        SUM(IF(MONTH(fees.date) = 11, fees.amt, 0)) AS Nov,
        SUM(IF(MONTH(fees.date) = 12, fees.amt, 0)) AS Dece,
        feesTotals.total AS Total,
        (feesTotals.total-(SUM(IFNULL(fees.amt,0)))) AS Balance
FROM student CROSS JOIN feesTotals
LEFT JOIN fees ON fees.stu_id = student.id AND YEAR(fees.date) = feesTotals.year
GROUP BY student.stu_name, feesTotals.year, feesTotals.total

See sample on DB Fiddle here


text:
Q: Error-page not working (with pic) I'm working in Eclipse+tomcat. My custom made static error page is not showing up in tomcat when i click on url for non-existing pages. generated-error.html has a simple img src="404_man.jpg" tag. But I keep getting the error page shown on the pic.

My servlet version is 3.0 if i view it from manifest.mf.

A: Have you tried the error definition for generic errors, not just 404.

    /general-error.html

And are you sure tomcat is running on port 8080?
The error page does not look like Tomcat7's default 'cant find page' page.

A: Some browser like IE needs atleast 512 bytes of data to render. Otherwise it will not render the response. Try adding more content in your error page.
I believe you have very less content in your error page.
Mozilla will work without any problem in this kind of situation.


text:
Q: How to generate Excel/PDF through PHP I have a table and I want to download the table data as excel/pdf using PHP.
FYKI, below shared the UI, Requesting Help

Student Name : Suresh (XII Std)

    Subject
    Mark

    Language
    95

    English
    99

    Maths
    100

    Total
    294/300

Download as
<input type="button" name="export" value="↓ Excel"/>  <input type="button" name="export" value="↓ PDF"/>

While click download button I want excel output like below.
Report Output

A: Use a library.
I suggest you use PHPExcel for Excel and mPDF for PDF.
Both libraries have good documentation and they can be customized based on your requirements.


text:
Q: Proving a vector identity using suffix notation An identity my lecturer used is:
$$\boldsymbol{ \Omega\times x\cdot\sigma\cdot n=\Omega\cdot x\times\sigma\cdot n}$$
$\boldsymbol{\Omega, x, n}$ are 3 dimensional vectors, $\boldsymbol \sigma$ is a second rank tensor. The best way of showing this is probably by suffix notation however I confused on how to order my suffixes, how do I know which are going to be subscript $i$'s, and others $j$'s and so on?