text:
Q: Splitting a column in a data frame by an nth instance of a character I have a dataframe with several columns, and one of those columns is populated by pipes "|" and information that I am trying to obtain.
For example:
View(Table$Column)
"|1||KK|12|Gold||4K|"
"|1||Rst|E|Silver||13||"
"|1||RST|E|Silver||18||"
"|1||KK|Y|Iron|y|12||"
"|1||||Copper|Cpr|||E"
"|1||||Iron|||12|F"

And so on for about 120K rows.
What I am trying to excavate is everything in between the 5th pipe and the 6th pipe in this series, but in it's own column vector, so the end result looks like this:
View(Extracted)
Gold
Silver
Silver
Iron
Copper
Iron

I don't want to use RegEx. My tools are only limited to R here. Would you guys happen to have any advice how to overcome this?
Thank you.

A: 1) Assuming x as defined reproducibly in the Note at the end use read.table as shown. No regular expressions or packages are used.
read.table(text = Table$Column, sep = "|", header = FALSE,
  as.is = TRUE, fill = TRUE)[6]

giving:
      V6
1   Gold
2 Silver
3 Silver
4   Iron
5 Copper
6   Iron

2) This alternative does use a regular expression (which the question asked not to) but just in case here is a tidyr solution.  Note that it requires tidyr 0.8.2 or later since earlier versions of tidyr did not support NA in the into= argument.
library(dplyr)
library(tidyr)

Table %>%
  separate(Column, into = c(rep(NA, 5), "commodity"), sep = "\\|", extra = "drop")

giving:
  commodity
1      Gold
2    Silver
3    Silver
4      Iron
5    Copper
6      Iron

3) This is another base solution.  It is probably not the one you want given that (1) is so much simpler but I wanted to see if we could come up with a second approach in base that did not use regexes.  Note that if the split= argument of strsplit is "" then it is treated specially and so is not a regex.  It creates a list each of whose components is a vector of single characters.  Each such vector is passed to the anonymous function which labels | and the characters in the field after it with its ordinal number.  We then take the characters corresponding to 5 (except the first as it is |) and collapse them together using paste.
data.frame(commodities = sapply(strsplit(Table$Column, ""), function(chars) {
  wx <- which(cumsum(chars == "|") == 5)
  paste(chars[seq(wx[2], tail(wx, 1))], collapse = "")
}), stringsAsFactors = FALSE)

giving:
  commodities
1        Gold
2      Silver
3      Silver
4        Iron
5      Copper
6        Iron

Note
Table <- data.frame(Column = c("|1||KK|12|Gold||4K|",
  "|1||Rst|E|Silver||13||",
  "|1||RST|E|Silver||18||",
  "|1||KK|Y|Iron|y|12||",
  "|1||||Copper|Cpr|||E",
  "|1||||Iron|||12|F"), stringsAsFactors = FALSE)

A: You can try this:
df <- data.frame(x = c("|1||KK|12|Gold||4K|", "|1||Rst|E|Silver||13||"), stringsAsFactors = FALSE)
library(stringr)
stringr::str_split(df$x, "\\|", simplify = TRUE)[, 6]

A: 1) We can use strsplit from base R on the delimiter | and extract the 6th element from the list of vectors
sapply(strsplit(Table$Column, "|", fixed = TRUE), `[`, 6)
#[1] "Gold"   "Silver" "Silver" "Iron"   "Copper" "Iron"

2) Or using regex (again from base R), use sub to extract the 6th word
sub("^([|][^|]+){4}[|]([^|]*).*", "\\2",
       gsub("(?<=[|])(?=[|])", "and", Table$Column, perl = TRUE))
#[1] "Gold"   "Silver" "Silver" "Iron"   "Copper" "Iron"

data
Table <- structure(list(Column = c("|1||KK|12|Gold||4K|",
 "|1||Rst|E|Silver||13||",
 "|1||RST|E|Silver||18||", "|1||KK|Y|Iron|y|12||", "|1||||Copper|Cpr|||E",
 "|1||||Iron|||12|F")), class = "data.frame", row.names = c(NA,
 -6L))


text:
Q: NSComboBox value getting and assigning it to a label I am new to Mac development. I want to get the value selected from a combo box and assign it to the text of a label in a Mac app using Objective-C. How can I do this?

A: Following  gives the selected value:
[yourComboBox objectValueOfSelectedItem] returns id. Have a try with following, if in case you may require to type cast it to NSString.
[self.yourLabelOutlet setStringValue:[yourComboBox objectValueOfSelectedItem]];

*Not checked, but something similar to this
EDIT:
Find a Sample Project.

A: The accepted answer only works when your NSComboBox does not use its own dataSource
When using your own dataSource for your NSComboBox you should approach it like this:
[yourDataSourceArray objectAtIndex:[yourComboBox indexOfSelectedItem]]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# use SHA1 to hash string into byte array I'm using SHA1 to encrypt some values like password.
This is my code:
String passwd = Membership.GeneratePassword(10, 2);
SHA1 sha = new SHA1CryptoServiceProvider();
byte [] password = sha.ComputeHash(passwd);

But VS returns error, because passwd is a string.
I have to store the password in a byte array, so is there a way to solve this?

A: String passwd = Membership.GeneratePassword(10, 2);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(passwd);
SHA1 sha = new SHA1CryptoServiceProvider();
byte [] password = sha.ComputeHash(bytes);

Note that SHA1 does not encrypt data but hash them instead. Encrypted data can be decrypted. Hash algorithms are one way.

A: Use an Encoding to convert the string to a byte array
var bytes= Encoding.UTF8.GetBytes(passwd);
var password = sha.ComputeHash(bytes);


text:
Q: How to smooth a ragged plot I am using Mathematica 10. I have the following code yielding a ragged plot
    market [r_, a_] = (1 + 2*r + a^2)/(1 - 2*I*(Sqrt[a^2 - r^2])  - a^2);

stock11[l_, x_, r_, a_] = (
   Abs[market[r, a]]^2* Exp[- 5.59 * 10^9 * x])/
   2 (Cosh[(1.1174 * 10^10)/2 x] - Exp[- l* x] Cos[5.302*10^9 x]);

stock22[l_, x_] =
  Exp[- 5.59 * 10^9* x]/
   2 (Cosh[(1.1174 * 10^10)/2 x] + Exp[- l*x] Cos[5.302*10^9 x]);

VarianceS[l_, x_, r_, a_] =
  1 - 4*stock11[l, x, r, a] + 8*stock11[l, x, r, a]*stock22[l, x]  +
   Abs[market[r, a]]^2* Exp[-2*5.59 * 10^9*x] (Exp[-2*l*x] - 1) ;

Λ[l_, x_, r_, a_] =
 1 - 2 stock11[l, x, r,
    a]; (* The two time correlation Subscript[C, 01] = Subscript[c, \
12] = Λ*)

VarianceT[l_, x_, r_, a_] =
 2 Λ[l, x, r, a] - Λ[l, 2*x, r, a];

differenceV[l_, x_, r_, a_] =
  VarianceS[l, x, r, a] - VarianceT[l, x, r, a];

Plot[differenceV[0, 1.7889*10^-10*x, 0.001596, 2.228*10^-3], {x, 0,
  20}]

Is there any way of smoothing this raggedness/peaks?

A: After replacing the inexact numbers by exact numbers, FullSimplify turns the function you plot into 0
a1 = 559/100;
a2 = 11174/10000;
a3 = 5302/1000;

market[r_, a_] = (1 + 2*r + a^2)/(1 - 2*I*(Sqrt[a^2 - r^2]) - a^2);
stock11[l_, x_, r_, a_] = (Abs[market[r, a]]^2*Exp[-a1*10^9*x])/2 (Cosh[(a2*10^10)/2 x] -
                           Exp[-l*x] Cos[a3*10^9 x]);
stock22[l_, x_] = Exp[-a1*10^9*x]/2 (Cosh[(a2*10^10)/2 x] + Exp[-l*x] Cos[a3*10^9 x]);

VarianceS[l_, x_, r_, a_] = 1 - 4*stock11[l, x, r, a] + 8*stock11[l, x, r, a]*
  stock22[l, x] + Abs[market[r, a]]^2*Exp[-2*a1*10^9*x] (Exp[-2*l*x] - 1);
Λ[l_, x_, r_, a_] = 1 - 2 stock11[l, x, r, a];
VarianceT[l_, x_, r_, a_] =  2 Λ[l, x, r, a] - Λ[l, 2*x, r, a];

differenceV[l_, x_, r_, a_] = VarianceS[l, x, r, a] - VarianceT[l, x, r, a];

differenceV[0, 17889/10000*10^-10*x, 1596/1000000, 2228/1000*10^-3] // FullSimplify

0

So to get a non-ragged plot use Plot[0, {x, 0, 20}]


text:
Q: Copying one file to another, while "expanding" some variables. The use case is that I have a template LaTeX file, which I would like to be copied several times while replacing variables in it to some other variables.
Here is an example of how such a template might look like:
   \documentclass[%POINT-SIZE%pt]{book}

    \includeonly{%CURRENT-CHAPTER%}
    \begin{document}
     \chapter{Chapter 1}
        \include{chapter1}
     \chapter{Chapter 2}
        \include{chapter1}

    \end{document}

The desired code should present read the file named "template.tex", and
copy it to four files named:

*

*"10pt-chapter1-only.tex",

*"12pt-chapter1-only.tex",

*"10pt-chapter2-only.tex", and,

*"12pt-chapter2-only.tex",

by replacing in template file:

*

*each occurrence of %POINT-SIZE% by the contents of the TeX macro \pointSize, and,

*each occurrence of %CURRENT-CHAPTER% by the contents of TeX macro \currentChapterFileName
Needless to say, there is nothing sacred in the way I chose to denote the variables in the template file.

A: I would let TeX do the macro expansion.
If your file is
   \documentclass[\pointSize]{book}
    \includeonly{\currentChapterFileName}
    \begin{document}
     \include{c1}
     \include{c2}
    \end{document}

then
 pdflatex '\def\pointSize{12pt}\def\currentChapterFileName{c1}\input' file

will make the 12pt version of chapter 1


text:
Q: nodejs need use 'strict use'?or what is the best practice of node's strict mode? I'm a new to node.js and javascript.I checked code examples of node.js and it used use strict mode.
For example, a server.js:
'use strict';
//some server code

Also, I got to know that use strict is present at head of every js file.
It confused me and so I want to know what is best practice in Nodejs to use strict mode?

Thank you all, My question is focus on the strict mode. In this mode, some code mistake can be reported. In back-end, the strict error reporter also run? And If I need use it, I should add it in every js file header? Or add it in main file(server.js or etc.) head? Or use some node.js self style?

A:
"use strict" is a behavior flag you can add to to first line of any JavaScript file or function. It causes errors when certain bad practices are use in your code, and disallows the use of certain functions, such as with.

References:

*

*Restrictions on Code in Strict Mode by Microsoft MSDN

*Node.js Best Practices

A: Use it always. If nothing else, it ensures that your code is properly written, and cross browser compatible as it can be.  It also will reveal mundane syntax errors that would otherwise go unfound, and lead to hours of unnecessary debugging.

A: Nodejs is server-side javascript, so many coding practices are similar in both. So using strict mode is common.
It ensures that you are not violating certain coding conventions like undeclared variables x=14;, use of specific variable names arguments,eval which are names of few global variables and functions.


text:
Q: Parsing .xml with vbs Trying to pull out all the product names from the tag <NameProduct>, but the problem is that you need to pull out all the names of the products, which lie only in the interval <Product>...<PostAll>.
Below is a sample XML:
<?xml version="1.0" encoding="UTF-8"?>
<Products>
    <Product>
        <NameProduct>PRODUCT NAME 1</NameProduct>
        <CodeProduct>PRODUCT CODE 1</CodeProduct>
        <CodePlant>1111111111111111</CodePlant>
        <NameDesc>DESCRIPTION POS 1</NameDesc>
        <PostAll>
            <Post>
                <NameProduct>M1</NameProduct>
                <CodeProduct>M1</CodeProduct>
                <CodePlant>1</CodePlant>
                <NameDesc>??-1</NameDesc>
            </Post>
            <Post>
                <NameProduct>M2</NameProduct>
                <CodeProduct>M2</CodeProduct>
                <CodePlant>2</CodePlant>
                <NameDesc>??-2</NameDesc>
            </Post>
        </PostAll>
    </Product>
    <Product>
        <NameProduct>PRODUCT NAME 2</NameProduct>
        <CodeProduct>PRODUCT CODE 2</CodeProduct>
        <CodePlant>2222222222222222</CodePlant>
        <NameDesc>DESCRIPTION POS 2</NameDesc>
        <PostAll>
            <Post>
                <NameProduct>M3</NameProduct>
                <CodeProduct>M3</CodeProduct>
                <CodePlant>3</CodePlant>
                <NameDesc>??-3</NameDesc>
            </Post>
            <Post>
                <NameProduct>M4</NameProduct>
                <CodeProduct>M4</CodeProduct>
                <CodePlant>4</CodePlant>
                <NameDesc>??-4</NameDesc>
            </Post>
        </PostAll>
    </Product>
</Products>

Below is a sample code:
Dim node
Dim nodes
Dim query
Dim xml
Dim i
Dim attrs
Dim ConfigFile

Set xml = CreateObject("Msxml2.DOMDocument.3.0")
ConfigFile = "C:\ProgramData\xmlfile.xml" ' Configuration file path
Dim ok
ok = xml.Load(ConfigFile)

If (Not ok) Then
    MsgBox("File configuration failed!")
    Exit Sub
Else
    xml.SetProperty "SelectionLanguage", "XPath"
    query = "NameProduct"
    Set nodes = xml.SelectNodes(query)

The method "XPath" does not work for me, apparently due to the fact that XML is missing attribute names.
Tell me how to return all the matches in a given interval XML?

A: Your XPath expression doesn't work because it doesn't match what you think it matches. A query NameProduct will not find <NameProduct> nodes anywhere in the XML structure, but only under the current node (which in your case is the document root node). Since there are no <NameProduct> nodes directly under <Products> you're getting an empty result set. Missing attributes have nothing to do with it.
What you want is an XPath expression //Product/NameProduct (find <NameProduct> nodes that are immediate child nodes of <Product> nodes anywhere in the document):
query = "//Product/NameProduct"
Set nodes = xml.selectNodes(query)

The double slash essentially means "anywhere below".
Please read up on how XPath works.

As a side note: Msxml2.DOMDocument.3.0 is buggy and should not be used anymore. Use Msxml2.DOMDocument.6.0 instead. Also, you may want to disable asynchronous loading of your XML file to make sure the document is actually loaded completely before you start processing it:
Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.Async = False
ok = xml.Load("C:\ProgramData\xmlfile.xml")


text:
Q: Can`t install datasets in R, not cvs and not xlsx I am new to RStudio. And it was working well, about a week ago my computer update the new version of the system. And from this moment R doesnt work like before. I am trying to load at datasets in .xlsx and .cvs - it doesn`t work. R write like this:
** Installing R Package Dependencies for Excel Import: `'readxl', 'Rcpp'`

[1/5] Installing cellranger...

�������������� � utils::install.packages("cellranger", repos = "https://cran.rstudio.com/") :
  'lib = "C:/Program Files/R/R-4.0.2/library"' is not writable
������ � utils::install.packages("cellranger", repos = "https://cran.rstudio.com/") :
  unable to install packages
������: sourceWithProgress -> eval -> eval -> <Anonymous>
���������� �����������

I trying to install xlsx packages, it writes like this:
`install.packages("xlsx")`
WARNING: Rtools is required to build R packages but is not currently installed. Please download and install the appropriate version of Rtools before proceeding:

https://cran.rstudio.com/bin/windows/Rtools/
Warning in install.packages :
  'lib = "C:/Program Files/R/R-4.0.2/library"' is not writable
Warning in install.packages :
  не могу создать каталог 'C:\Users\Lina\OneDrive\?????????' по причине 'Invalid argument'
Error in install.packages : unable to create 'C:/Users/Lina/OneDrive/?????????/R/win-library/4.0'

if somebody can help me?

A: Since you appear to be a Windows user, I can offer two pieces of advice.
First, make sure your R installation is in a location that you have write permissions to. In some Windows OS, the Program Files locations are by default locked down. If the computer is yours, you should be able to change the permissions to the R folder. How to do so will vary a little by your windows version, so I will not provide more instructions. One other thing you can try is to set R and RStudio to "Run as administrator".
Second, OneDrive is a bad place to put your R installation or your R packages. OneDrive does not support all filenames and file extensions. R and its packages will generate a number of unsupported files, and you will continually be notified that something will not sync and that you should do something about it.
On a Windows machine, I generally install R and set up the library at C:\R where I have appropriate permissions.


text:
Q: Shared memory sync using semaphore I have two codes : PRODUCER (PR) and CONSUMER (CO). There is a block of memory (Mat) (a 3D matrix to be precise) which needs to be shared between both the programs. I am currently using shared memory based IPC functions to share the memory space between the two codes.
Constraints:

*

*PR is the owner of the Mat and performs iterations changing the values of the matrix. CO is the user of the Mat and only reads the values and uses for some further calculation

*PR should write the data first and then should wait for the CO to read and use the values of the Matrix then signalling PR to proceed with further iteration and it should continue like this.

What I am currently using is -
PRODUCER
#include <unistd.h>
#include  <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>
#include  <sys/ipc.h>
#include  <sys/shm.h>

#define  NOT_READY  -1
#define  FILLED     0
#define  TAKEN      1

#define  nx (400)
#define  ny (400)
#define  nz (400)

struct Memory {
     int      status;
     double   u_x[nx+1][ny+2][nz+2];
}

int
main(int  argc, char *argv[])
{
     key_t          ShmKEY;
     int            ShmID;
     struct Memory  *ShmPTR;
     int            i, j, k;
     int            niter = 5;

     int            sumX[niter],sumY[niter],sumZ[niter];

     ShmKEY = ftok(".", 'x'); // getting the unique identifier key from directory location
     ShmID = shmget(ShmKEY, sizeof(struct Memory), IPC_CREAT | 0666);
     if (ShmID < 0) {
          printf("*** shmget error (server) ***\n");
          exit(1);
     }

     ShmPTR = (struct Memory *) shmat(ShmID, NULL, 0);
     if ((int) ShmPTR == -1) {
          printf("*** shmat error (server) ***\n");
          exit(1);
     }
     printf("Server attached the memory to its virtual space...\n");

     ShmPTR->status  = NOT_READY; // setting the status to be not ready before filling it

     for (int m = 0; m < niter; m++){
        for (i=0; i<=nx; i++) for (j=0; j<=ny+1; j++) for (k=0; k<=nz+1; k++)
           ShmPTR->u_x[i][j][k] = m; // filling the array with iteration number (just for depiction purpose)
        ShmPTR->status = FILLED; // change the status to Filled
        //printf("Please start the client in another window...\n");
        while (ShmPTR->status != TAKEN)
             sleep(1);
     }

     printf("Server has detected the completion of its child...\n");
     shmdt((void *) ShmPTR);
     printf("Server has detached its shared memory...\n");
     shmctl(ShmID, IPC_RMID, NULL);
     printf("Server has removed its shared memory...\n");
     printf("Server exits...\n");
     exit(0);
}

CONSUMER
#include  <stdio.h>
#include  <stdlib.h>
#include  <sys/types.h>
#include  <sys/ipc.h>
#include  <sys/shm.h>

#define  NOT_READY  -1
#define  FILLED     0
#define  TAKEN      1

#define  nx (400)
#define  ny (400)
#define  nz (400)

struct Memory {
    int      status;
    double   u_x[nx+1][ny+2][nz+2];
}

int
main(void)
{
    key_t          ShmKEY;
    int            ShmID;
    struct Memory  *ShmPTR;
    int            i, j, k;

    int            niter = 5;
    int            sumX[niter];

    ShmKEY = ftok(".", 'x');
    ShmID = shmget(ShmKEY, sizeof(struct Memory), 0666);
    if (ShmID < 0) {
          printf("*** shmget error (client) ***\n");
        exit(1);
    }
    printf("Client has received a shared memory...\n");

    ShmPTR = (struct Memory *) shmat(ShmID, NULL, 0);
    if ((int) ShmPTR == -1) {
        printf("*** shmat error (client) ***\n");
        exit(1);
    }
    printf("Client has attached the shared memory to it's virtual memory space...\n");

    for (int m =0; m<niter; m++){
        sumX[m] = 0;
        while (ShmPTR->status != FILLED)
            ;
        printf("Client found the data is ready, performing sanity check...\n");
        // read the integers and check for the sum

        for (i=0; i<=nx; i++) for (j=0; j<=ny+1; j++) for (k=0; k<=nz+1; k++)
            sumX[m] +=  ShmPTR->u_x[i][j][k];
        printf("Cycle %d : sumX-> %d\n", m,sumX[m);

        ShmPTR->status = TAKEN;
        printf("Client has informed server data have been taken...\n");
    }
    shmdt((void *) ShmPTR);
    printf("Client has detached its shared memory...\n");
    printf("Client exits...\n");
    exit(0);
}

What I am doing right now is using a member of the struct called status to kind of prevent race conditions. From what I have read till now, semaphores allow a similar thing in IPC.
Question: How to use semaphore in this such that the memory space which needs to be shared is just the array(s) and not wrapping it in a struct with a self defined flag ?
Edit1: Or maybe mutex for that matter if it is better than semaphore for this application.
Edit2: Following @Stargateur answer which works for this code but in the production code where nx, ny and nz are variables, how does one define a shared memory for the struct consisting of a member which is a variable length multidimensional array ? ( ofcourse it would live until the call shmdt and shmctl )

A: I will advice you to implement your feature with two semaphores, one for unlock produser, one for unlock consumer.

How to use semaphore in this such that the memory space which needs to be shared is just the array(s) and not wrapping it in a struct with a self defined flag ?

Yes but why separate the data and the semaphore associate with the data ?
I would do the following:
struct Memory {
     sem_t    prod;
     sem_t    cons;
     double   u_x[nx+1][ny+2][nz+2];
};

// produser
sem_init(&ShmPTR->cons, !0, 0);
sem_init(&ShmPTR->prod, !0, 1);

 for (int m = 0; m < niter; m++) {
     sem_wait(&ShmPTR->prod);
     // ...
     sem_post(&ShmPTR->cons);
 }

// consumer
for (int m =0; m<niter; m++) {
     sem_wait(&ShmPTR->cons);
     // ...
     sem_post(&ShmPTR->prod);
}

Or maybe mutex for that matter if it is better than semaphore for this
  application.

mutex can't be share between process.
By the way, you use an int to iterate on a array, you should use size_t

A: If you are planning to keep PR and CO as separate processes, you can try to fork one of the processes from the other to synchronize them. In this particular case, my suggestion is to fork CO from PR process. Here is briefly my idea:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main(int argc, char* argv[])
{
    const char *name="SHARED";
    const int SIZE = 4096;

    pid_t pidA;
    pidA = fork();

    if (pidA < 0)
    {
        printf("forkA Failed" );
        return 1;
    }
    else if (pidA == 0) // Child process A
    {

        // Read from the shared memory object.

        exit(0);
    }
    else // Parent process
    {

        int shm_fd;
        /* pointer to shared memory obect */
        void* ptr;
        /* create the shared memory object */
        shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
        /* configure the size of the shared memory object */
        ftruncate(shm_fd, SIZE);
        /* memory map the shared memory object */
        ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

        /* write to the shared memory object */

        // Wait for child to read matrix
        wait(NULL);

        printf("Program finished------\n");
    }
}

But we all know that threads are more lightweight, hence preferable. You can use semaphore with two threads as below:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

sem_t can_read,can_write; // declare two global semaphore

void* threadPR(void* arg)
{
  while(true)
  {
    //wait
    sem_wait(&can_write);

    //Write to matrix

    //signal
    sem_post(&can_read);
  }
}

void* threadCO(void* arg)
{
  while(true)
  {
    //wait
    sem_wait(&can_read);

    //Read the matrix

    //signal
    sem_post(&can_write);
  }
}

int main()
{
    // initialize the semaphore
    sem_init(&mutex, 0, 1);
    // declare two threads
    pthread_t t1,t2;
    pthread_create(&t1,NULL,threadPR,NULL); // Run the PR thread

    // do whatever needed before running CO

    pthread_create(&t2,NULL,threadCO,NULL); // Run the CO thread

    // wait for threads to join
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);

    // free the semaphore
    sem_destroy(&mutex);
    return 0;
}

You can add required initializations as globals to this implementation.


text:
Q: using weakref to get exit child windows in PyQt4 I am trying to take advantage of weakref.ref that if the main window object is deleted then the child window should close with it.
Here is the example I have tried, but is not working as expected :
import sys
import weakref
from PyQt4 import QtCore, QtGui

print __file__

class ParentWindow(QtGui.QMainWindow):
    """docstring for ParentWindow"""
    def __init__(self, parent=None):
        super(ParentWindow, self).__init__(parent)
        self.setWindowTitle("Parent Window")
        self.setGeometry(300, 300, 250, 150)
        self._setupUi()
        self._connections()
        self.childObj = ChildWindow()
        self.uiDict = weakref.ref(self, self._closeChild)

    def _closeChild(self):
        self.childObj.close()

    def _setupUi(self):
        self.btn = QtGui.QPushButton("Launch child window in child thread")
        self.setCentralWidget(self.btn)

    def _connections(self):
        self.btn.clicked.connect(self.callChild)

    @QtCore.pyqtSlot()
    def callChild(self):
        self.childObj.show()

class ChildWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ChildWindow, self).__init__(parent)
        self.setWindowTitle("Child Window")
        self.byeBtn = QtGui.QPushButton("Bye", self)
        self.childLayout = QtGui.QVBoxLayout()
        self.childLayout.addWidget(self.byeBtn)
        self.setLayout(self.childLayout)
        self.byeBtn.clicked.connect(self.close)

    def __del__(self):
        print "Exiting"

def main():
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('Parent')
    pWinObj = ParentWindow()
    pWinObj.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

right now when I am closing the main window its not happening.


text:
Q: R function, that given an input uses it for future calculations For my project I would require some help that I cannot find on google. Is there a code where the starting value of a chain of commands (previous output (using a shift function)* value (from another column) = output) is set to be 1, so that the next command has a previous output to reach back on, to start the chain? Whatever I have tried, with setting the first row = 1 etc., has not worked... :(
Thank you very much for the Help,
Ferdinand
For more details: In a dream world Debt$returnp for row 1 would be 1, the output in row 2 would be output row 1 (1) * Debt$return (1.015) and so on for every following row. Would anyone know a string of code that would do that?
https://i.stack.imgur.com/w2vFW.jpg

A: Building on comments above and making some assumptions about what you are trying to achieve, how's this working for you:
library(purrr)
library(dplyr)

values <- c(2,4,6,10)
purrr::reduce(
  .x = values,
  .f = function(state, input){return(c(state, input*dplyr::last(state)))},
  .init=1
)[-1] # the [-1] is just there to remove the initial value from your output

// UPDATE:
this should adapt the above to what you're showing in the screenshot:
library(tibble)
library(purrr)
library(dplyr)

Debt <- tibble(
    # Week, debt, Date, Diff, Perf
    return = c(NA_real_, 1.015, 1.092, 1.005)
  ) %>%
  mutate(
    returnp = purrr::reduce(
      .x = return[-1], # start with the second entry and skip that initial <NA>
      .f = function(state, input){return(c(state, input*dplyr::last(state)))},
      .init = 1
    )
  )


text:
Q: I Cannot Solve This Algebra-Trig Equation If someone can guide me on how to solve this, that'll be great:
$$\frac{4805}{a} = \cos^{-1} \left(\frac{a-4.2}{a}\right)$$
solve for $a$.
Cheers

A: This is not an equation that can be solved algebraically. The best way to solve it is to plug it into a computer and ask for the answer. If you need to calculate it by hand, there are some approximations of $\arccos$ that converge reasonably quickly that can be used, and if you want I can provide them.

A: This is a  transcendental equation and the solution can be obtained only by numerical method (notice that this already the case for the simple $x=\cos(x)$).
Taking into account the fact that $-1\leq\cos(x)\leq 1$, it is clear that the zero of equation $$f(a)=\frac{4805}{a}-\cos ^{-1}\left(\frac{a-\frac{21}{5}}{a}\right)$$ must be very large.
To get a first approximation, let us use Taylor series. This will give $$f(a)=-\sqrt{\frac{42}{5}} {\frac{1}{a^{1/2}}}+\frac{4805}{a}+O\left(\frac{1}{a^{3/2}}\right)$$ which gives as an estimate $$a_0=\frac{115440125}{42}\approx 2.74857\times 10^6$$ Now, we can start Newton method which will provide the following successive iterates
$$\left(
\begin{array}{cc}
 n & a_n \\
 0 & 2.7485744047619047619\times 10^6 \\
 1 & 2.7485737047613966799\times 10^6 \\
 2 & 2.7485737047616195229\times 10^6
 \end{array}
\right)$$ which is the solution for twenty significant figures.
Edit
May be simpler, we could consider the problem to be : find the zero of equation
$$g(x)=\frac{21 }{5}x+\cos (4805 x)-1$$ where $x=\frac 1a$. Its derivative is $$g'(x)=\frac{21}{5}-4805 \sin (4805 x)$$ which cancels for $$x_*=\frac{1}{4805}\sin ^{-1}\left(\frac{21}{24025}\right)$$ This corresponds to a maximum (by the second derivative test). Since $g(0)=0$, the solution is such that $x > x_*$.
Now, using Taylor expansion again around $x=0$
$$g(x)=\frac{21 }{5}x-\frac{23088025}{2} x^2+O\left(x^3\right)$$ which cancels for $$x=\frac{42}{115440125}\implies a=\frac{115440125}{42}$$


text:
Q: Iptables Not Blocking User iptables seems to not want to block a user.
I'm using a remastered 10.04 live and Firestarter as a firewall.  I've made no fundamental changes to the distro, except to update, upgrade and added this iptable line for my admin user dev:
sudo iptables -A OUTPUT -p all -m owner --uid-owner dev -j DROP

I've allowed dev, my admin, to use Firefox as another user:
gksudo -u browserUser /usr/bin/firefox
Note: The purpose of this is stop opening up browser scripts to the admin account, and instead use a clean account with no privs as a proxy.
Now, I test to see if iptables is blocking in case admin accidentally tried to connect without using another user.  So I try Midori browser directly:
/usr/bin/midori

Midori launches, and connects to the internet.  I'm puzzled.  My iptables entry doesn't seem to work.
I added the same line I remastered with:
sudo iptables -A OUTPUT -p all -m owner --uid-owner dev -j DROP

I still am not blocked.  So, I try reseting the tables:
sudo /etc/init.d/networking restart

I get output:
 * Reconfiguring network interfaces...
Ignoring unknown interface wlan0=wlan0.

I try connecting again with Midori browser, and my iptable rule is still ignored.
What's happening?

A: The order of your rules in iptables is critical. If a packet matches an earlier rule, there is no further processing.
You are appending ( -A ) your rules to the end of the OUTPUT chain, so, my guess is the packets are accepted by an earlier rule.
If you put the rule first, with -I OUTPUT 1, it will work.
sudo iptables -I OUTPUT 1 -p all -m owner --uid-owner dev -j DROP

Your user case is more complex as you are using 2 tools, firestarter and iptables, to manage your firewall rules. I suggest you use one or the other, but not both.
If you would like to see your rule set, use
sudo iptables -L -v -n

And if you want to use iptables to manage your firewall see
https://help.ubuntu.com/community/IptablesHowTo


text:
Q: How to extract monthly financial time series given daily fts I understand that we can use the function 'tomonthly' within the financial toolbox but this returns a default monthly data taking the last business day of every month.
What if i want the first business day of every month instead?
I have tried using 'ED' set to 1 in the following manner:
ftsFuture = fints (matlabDate, lnPrice);
monthlyFuture = tomonthly(ftsFuture,'ED',1);

But this was only partially successful in the sense that if the 1st of the month is a working day, it is alright, but if it is not a working day, it becomes the previous working day, which is in the previous month.
I have also tried using 'BusDays' by setting it to 0, in the following manner:
ftsFuture = fints (matlabDate, lnPrice);
monthlyFuture = tomonthly(ftsFuture,'ED',1, 'BusDays',0);

This successfully forces every entry to be the 1st of each month but clearly cannot be correct as some of these dates are clearly not working days!
Any help with this is vastly appreciated!

A: There is a way to extract the data from daily financial time series in monthly periods starting on the first business day of the month. We can get dates in the middle of the series using tomonthly and busdate functions.
Assuming the data starts at the beginning of some month and ends at the end certain month, we add the first date and eliminate the last date we will get after the operations.
ftsFuture = fints (matlabDate, lnPrice);
monthlyFuture = tomonthly(ftsFuture);
eomDates = monthlyFuture.dates ; % getting end of month business days)
fomDates = busdate(eomDates) ;  % getting first month bussines days)
fomDates(end)=[] ; % deleting the last date in the array (out of range otherwise).
firstday = ftsFuture.dates(1); % adding the first date of the series.
fomDates = [firstday ; fomDates];
fomDates = datestr(fomDates);
fomftsFuture = ftsFuture(fomDates);


text:
Q: Appending data to model always empty Swift I am trying to append data on model after based on selections. Data is based on cell index selection but for some reasons its not appending to model. Data values are here may be I am doing something wrong in appending data .
I am using delegate after append data and to pass model to previous viewController.

*

*I need to append data in Item - selection - see model

Data appending declaration var dataItems: [Item]?
Model:
struct SectionList : Codable {

    let title : String?
    var items : [Item]?
}

struct Item : Codable {

    var textField : String?
    var textValue : String?
    var pickList: [SectionList]?
    var selection: [Item]?
    var multiSelect: Bool?
    var masterId: Int?
    var itemValue: String?

}

Main function for appending then delegate:
here dataItems are not appending values here on selectedItem
if let selectedItem = AppData?.pickList?[indexPath.section].items?[indexPath.row] {
  dataItems?.append(selectedItem)
}

@IBAction func bittiBtn(_ sender: Any) {
        print(dataValue)
        pickDelegate?.listPick(listValue: dataValue, selectedItems: dataItems ?? [])
        self.navigationController?.popViewController(animated: true)
    }

Values I am getting which needs to be append at dataItems: [Item]?
▿ Item
  ▿ textField : Optional<String>
    - some : "Tipi ve kesiti uygun olmalı"
  - textValue : nil
  - pickList : nil
  - selection : nil
  - multiSelect : nil
  ▿ masterId : Optional<Int>
    - some : 671
  ▿ itemValue : Optional<String>
    - some : "347"

A: You need to initialise your dataItems array
var dataItems = [Item]()

and if you still want it to be optional you can do
var dataItems:[Item]? = [Item]()


text:
Q: std::reference_wrapper unwrap the wrapper Introduction.
In C++ we cannot create containers of references:
std::vector<int&> vri;

In instantiation of 'class __gnu_cxx::new_allocator<int&>':
required from 'class std::allocator<int&>'
required from 'struct std::_Vector_base<int&, std::allocator<int&> >'
required from 'class std::vector<int&>'
required from here
error: forming pointer to reference type 'int&'
       typedef _Tp*       pointer;
                          ^~~~~~~

The internal implementation requires to create a pointer to the contained type, that leads to the pointer to reference forbidden type.
Luckily, std::reference_wrapper exists:
int x{1}, y{2}, z{3};
std::vector<std::reference_wrapper<int>> vr{x, y, z};
for (auto &v : vr)
    ++v;
std::cout << x << ' ' << y << ' ' << z << '\n';

Code above shows 2 3 4.
Problem.
I'm working on a C++ filter utility, as example the filter where receives a container and returns std::reference_wrapper to the contained objects that meets the criteria:
template <typename container_t> auto range(const container_t &container)
{ return std::tuple{std::begin(container), std::end(container)}; };

template <typename container_t, typename predicate_t>
auto where(const container_t &container, predicate_t predicate)
{
    auto [b, e] = range(container);
    using type = std::remove_reference_t<decltype(*b)>;
    using reference = std::reference_wrapper<type>;

    std::vector<reference> result{};

    std::copy_if(b, e, std::back_inserter(result), predicate);

    return result;
}

Code below shows 2 3 6 7:
int main()
{
    std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (auto &x : where(v, [](auto n){ return n & 0b10; }))
        std::cout << x << ' ';

    return 0;
}

But I have a problem chaining filters:
for (const auto &x :
    where(where(v, [](auto n){ return n & 0b10; }), [](auto n){ return n & 0b1; })) {
    std::cout << x << ' ';
}

no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'const std::reference_wrapper<const std::reference_wrapper<const int> >')
   std::cout << x << ' ';
   ~~~~~~~~~~^~~~

Inner where returns std::vector<std::refernce_wrapper<int>>, so the outer one will use std::vector<std::refernce_wrapper<const std::refernce_wrapper<const int>>>.
What have I tried?.
In order to solve the problem, I've tried to create a template that unwraps std::reference_wrapper<T>:
template <typename type_t>
struct unwrap
{
    using type = type_t;
};

template <typename type_t>
struct unwrap<std::reference_wrapper<type_t>>
{
    using type = type_t;
};

template <typename type_t>
using unwrap_t = typename unwrap<type_t>::type;

So far, it looks like it's working:
int main()
{
    using ri = std::reference_wrapper<int>;
    using rf = std::reference_wrapper<float>;
    using rri = std::reference_wrapper<ri>;
    using rrri = std::reference_wrapper<rri>;

    std::cout
        << typeid(int).name() << '\t' << typeid(unwrap_t<int>).name() << '\n'
        << typeid(float).name() << '\t' << typeid(unwrap_t<float>).name() << '\n'
        << typeid(ri).name() << '\t' << typeid(unwrap_t<ri>).name() << '\n'
        << typeid(rf).name() << '\t' << typeid(unwrap_t<rf>).name() << '\n'
        << typeid(rri).name() << '\t' << typeid(unwrap_t<rri>).name() << '\n'
        << typeid(rrri).name() << '\t' << typeid(unwrap_t<rrri>).name();

    return 0;
}

It yields the propper mangled names:

  i   i
  f   f
  St17reference_wrapperIiE    i
  St17reference_wrapperIfE    f
  St17reference_wrapperIS_IiEE    St17reference_wrapperIiE
  St17reference_wrapperIS_IS_IiEEE    St17reference_wrapperIS_IiEE

Integer and floating point (int, float) remains the same, integer and floating point wrappers get unwrapped and nested wrappers unwrap one level.
But it doesn't work inside where:
template <typename container_t, typename predicate_t>
auto where(const container_t &container, predicate_t predicate)
{
    auto [b, e] = range(container);
    using type = unwrap_t<std::remove_reference_t<decltype(*b)>>;
    //           ^^^^^^^^ <--- Unwraps iterator's inner type
    using reference = std::reference_wrapper<type>;

    std::vector<reference> result{};

    std::copy_if(b, e, std::back_inserter(result), predicate);

    // Debug
    std::cout
        << __PRETTY_FUNCTION__ << "\n"
        << '\t' << "decltype(*b) = " << typeid(decltype(*b)).name() << '\n'
        << '\t' << "unwrap *b = " << typeid(unwrap_t<decltype(*b)>).name() << '\n'
        << '\t' << "type = " << typeid(type).name() << '\n'
        << '\t' << "reference = " << typeid(reference).name() << '\n'
        << '\t' << "unwrap type = " << typeid(unwrap_t<type>).name() << '\n';

    return result;
}

int main()
{
    std::vector v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    for (const auto &x :
        where(where(v, [](auto n){ return n & 0b10; }), [](auto n){ return n & 0b1; })) {
        std::cout << &x << ' ';
    }

    return 0;
}

Debug logs into where shows that the unwrapper worked on the first call (it did nothing to the type), but not on the second call:

  auto where(const container_t&, predicate_t) [with container_t = std::vector<int, std::allocator<int> >; predicate_t = main()::<lambda(auto:1)>]
      decltype(*b) = i
      unwrap *b = i
      type = i
      reference = St17reference_wrapperIKiE
      unwrap type = i
  auto where(const container_t&, predicate_t) [with container_t = std::vector<std::reference_wrapper<const int>, std::allocator<std::reference_wrapper<const int> > >; predicate_t = main()::<lambda(auto:2)>]
      decltype(*b) = St17reference_wrapperIKiE
      unwrap *b = St17reference_wrapperIKiE
      type = St17reference_wrapperIKiE
      reference = St17reference_wrapperIKS_IKiEE
      unwrap type = St17reference_wrapperIKiE

On the inner call, input container is std::vector<int>, so the iterator inner type (decltype(*b)), the unwrapping (unwrap_t<decltype(*b)>), tye type (type) and the unwrapped type (unwrap_t<type>) are int, only reference is std::reference_wrapper.
On the outer call, input container is std::vector<std::reference_wrapper<const int>> and all tye types (except reference) are std::reference_wrapper<const int>, as if the unwrapper ignored the input type.
Question.
What am I doing wrong on my unwrapper? I think the issue might be related to const propagation.
Code available on Try it online!.

A: I think the problem is, that *b returns a const value (since the container is passed by const reference). Your unwrap only works on non-const, non-volatile reference_wrapper. I would go as follows at this problem:
#include <functional>

namespace detail{
template <typename type_t, class  orig_t>
struct unwrap_impl
{
    using type = orig_t;
};

template <typename type_t, class V>
struct unwrap_impl<std::reference_wrapper<type_t>,V>
{
    using type = type_t;
};
}

template<class T>
struct unwrap {
  using type = typename detail::unwrap_impl<std::decay_t<T>, T>::type;
};

template <typename type_t>
using unwrap_t = typename unwrap<type_t>::type;

int main() {
    static_assert(std::is_same_v<const int&, unwrap_t<const int &>>);
        static_assert(std::is_same_v<const int&, unwrap_t<std::reference_wrapper<const int &>>>);
        static_assert(std::is_same_v<const int&, unwrap_t<const std::reference_wrapper<const int &>&>>);
}

This should return the original type for anything not a reference_wrapper and the inner type for cv-qualified reference_wrappers and references thereto.

Explanation: I will call the original unwrap from OP UNWRAP in the following to differentiate with my version. We want to invoke the reference_wrapper specification of UNWRAP whenever std::decay_t<T> is a std::reference_wrapper. Now this could be simply accomplished if we always invoke UNWRAP with std::decay_t<T> instead of T.
The problem with this is, that if T is not a reference_wrapper, this will remove all qualifications, i.e. UNWRAP<std::decay_t<const int>> is int when we would want it to be const int.
To get around this we define us template<class type_t, class orig_t> struct unwrap_impl. We want to always pass this the decayed type for the first argument and the original type (before decaying) as the second argument. Then, we can pass for the general case orig_t as the result type (as done by using type = orig_t).
For the specification, we define template<class type_t, class V> struct unwrap_impl<std::reference_wrapper<type_t>, V>. This will apply whenever type_t is a reference_wrapper, i.e. when the orignal type is some qualification of a reference_wrapper. We don't care about the second argument (which will be the original type), so we just ignore it. Then we take the inner type of the reference_wrapper as type (using type = type_t;).
Then we call unwrap_impl by defining basically template<class type_t> unwrap = detail::unwrap_impl<std::decay_t<type_t>, type_t>; (this is pseudocode but I think this makes it more clear.
Some examples:
unwrap<int> -> unwrap_impl<int, int> -> int
unwrap<const int> -> unwrap_impl<int, const int> -> const int
unwrap<std::reference_wrapper<const int>> -> unwrap_impl<std::reference_wrapper<const int>, std::reference_wrapper<const int>> -> const int
unwrap<const std::reference_wrapper<const int>> -> unwrap_impl<const std::reference_wrapper<const int>, const std::reference_wrapper<const int>> -> const int

(Again more pseudocode, but I hope its clear)
Edit: fixed some bugs.
Edit2: Seems to work: link


text:
Q: How to calculate mean for batch of images in Python in a non vectorized way? In order to calculate the image mean, one can use numpy.mean() if I'm not mistaken.
What mean() does, is simply summing all elements and then dividing by the number of all elements summed. furthermore if I want to calculate mean channelwise,(each channel has its own mean calculated), and I have an input of shape: (num_batch, num_channel, width, height), I'd write :
numpy.mean(a,axis=(0,2,3))

Now, I tried to code its non vectorized version but I'm not sure I'm doing everything correctly.
This is the code that is presumed to be calculating the mean channel-wise, (its output should match that of the command given above:
def calc_mean_classic(a):
    #sum all elements in each channel and divide by the number of elements
    batch = a.shape[0]
    channel = a.shape[1]
    width = a.shape[2]
    height = a.shape[3]

    sum = np.zeros((channel))
    for i in range(batch):
        for c in range(channel):
            for w in range(width):
                for h in range(height):
                    sum[c] += a[i,c,w,h]

    return sum, (sum/(width*height))

When I run my data with numpy.mean(a,axis=(0,2,3)), I get :
[ 125.30691805  122.95039414  113.86538318]

but when I run the function I coded, I get :
sum,m3 = calc_mean_classic(data_train)
print 'sum=',sum
print 'm3=',m3
print m3[0]/(32*32)

Output:
sum= [  6.41571420e+09   6.29506018e+09   5.82990762e+09]
m3= [ 6265345.90234375  6147519.70703125  5693269.15917969]
6118.50185776

There is an irony here, image size is 32*32 that's why I'm doing m3[0]/(32*32) (sum/width*height) to see if I can generate the sum[0] value! As you can see they are completely different values, while they should yield the same value!
I have no idea what's going on here.

A: Use sum along those three axes and divide by the block size, which would be width*height i.e. a.shape[2]*a.shape[3] -
batch_mean = np.sum(a,axis=(0,2,3))/(a.shape[2]*a.shape[3])

With np.mean(a,axis=(0,2,3)) you were also dividing by the number of elems along the first axis, which doesn't seem to be intended operation there, not at least with sum/(width*height) with your func calc_mean_classic.

Otherwise, if you meant to simulate the behavior of np.mean(a,axis=(0,2,3)) with the loopy calc_mean_classic, just edit the return statement to incorporate a.shape[0] -
return sum, (sum/(width*height*a.shape[0]))

A: this worked for me, thanks!
    # YOUR CODE HERE
    a = batch.asnumpy()

    #sum all elements in each channel and divide by the number of elements
    batch = a.shape[0]
    channel = a.shape[1]
    width = a.shape[2]
    height = a.shape[3]

    sum = np.zeros((channel))
    for i in range(batch):
        for c in range(channel):
            for w in range(width):
                for h in range(height):
                    sum[c] += a[i,c,w,h]

    sum = sum/(width*height*a.shape[0])

    return mx.nd.array(sum)


text:
Q: ROM initialization in VHDL for waveform generator I have to create a waveform generator and i used matlab to generate the sine wave. Now my TA told me to store the points from the wave in a ".mem" file then initialize the ROM by i guess importing them.
I don't really know how to initialize it and can't seem to find any references to
.mem files being used in vhdl.
I have the wave but i need help with creating the ROM and initializing it by using the values from matlab.


text:
Q: Filters for Gooddata "Export a large report" API I would like to know if I could filter a report before download it's data inside the csv file, I'm using this url:
https://secure.gooddata.com/gdc/app/projects/project_id/execute/raw/

I couldn't found any information at gooddata api about this, the body of the post request accept this json:
{'report_req': {'reportDefinition': '/gdc/md/{project_id}/obj/{obj_id}'} }

There are other parameters for filtering the data?
If don't, there is another way to download filtered data?
If there is another way, can I change from .csv to .json? Or maybe get the json data inside the response body?

A: Definition of filters is a part of "reportDefinition". The solution is to use or create report definition which contains required filters and perform the mentioned "execute/raw" call. Result of "execute/raw" call is always in csv format.


text:
Q: How can i search TODO lines in javascript files with resharper? I am writing javascript codes and i want to add todo, note, bug etc. to .js or .aspx files. But Resharper 4.5 couln't find them. Is there any way to show these comments inside todo explorer?
any help would be greatly appreciated
Platform: VS.NET 2008

A: ReSharper needs lexer to analyse comments. JavaScript is not yet supported in ReSharper, so there is no lexer and to-do items won't work there.
Updated: ReSharper 6 does support JS files and to-do items are extracted from such files.


text:
Q: How can we skip display:none items in owl carousel? Can anyone please tell how can we skip display:none items in owl carousel?
My html is like this :-

Here is my jquery :-

Now the issue is I do not want to display the "display:none" items. Now the display none items are not coming but at the end there comes a space, that should not come.
Any one can help please?
Thanks.

A: Basicly your way is not correct. This kind of carousels firstly parse html and generate its own data then it start to loop with them. If you define some css property, you just break the carousel. So you should OwlCarousel's method for adding and removing items.
    //Initialize Plugin
    $(".owl-carousel").owlCarousel();

    //get carousel instance data and store it in variable owl
    var owl = $(".owl-carousel").data('owlCarousel');

    //Manipulation methods.
    owl.addItem(htmlString [,targetPosition]);
    owl.removeItem(targetPosition);

I hope it sounds good...

A: Finally I got the solution. Well but not the owl-carousel way. It's not possible to skip the display:none items in owl-carousel. Here is the custom solution.
I took the new div in which I got the collection of lis but I gave them hid class so all will be hidden(hid = css class with display:none)  Then look at the javascript I put in code.
Html is like this :-

<button onclick="reinitcarousel(1)">Tab 1</button><button onclick="reinitcarousel(2)">Tab 2</button>

Script is like this :-

Done :)
Thanks.


text:
Q: In Excel, how I can find working day from hours? I have an input column like this:
Q3 column
34:48:00
34:18:00
10:51:00
48:14:00
9:40:00
15:01:00
5:19:00
18:33:00

"calculations for just first row of this column=34:48/8:30"
I want my output like this:
Days
4.05
and others

How could I do this?
I've tried this using =INT(Q3/"8:30") but this is giving me only integer number!
My working hours in a day is 8:30.

A: Did you try =Q3/"8:30"?  Did you get 97:24:42?  If so, you're 99% of the way home.
That (97:24:42) is your answer, expressed as a number of days
(4 days is 96 hours; and 0.05882 days is 1 hour, 24 minutes, and 42 seconds).
All you need to do now is Format the cell as a Number, as follows:

*

*Click on the cell.

*Either

*

*type Ctrl+1 (not Ctrl+F1, but simply Ctrl+1),
or,

*on the "Home" tab, in the "Cells" panel, click on the "Format" button and select "Format Cells…" from the drop-down menu.

*Then, in the "Number" tab (which will be selected initially by default), click on either "General" or "Number" -- the "Sample" field will show what it will look like.

*And then click on "OK".


text: Q: How to connect and disconnect bluetooth headphones with python? I tried to search good way to automatically connect bluetooth headphones and/or disconnect them with python 3 but couldn't find any good solutions. Is there any good libraries or tutorials how I could accomplish this task?


text:
Q: Import single user from sql file From the Joomla database I exported the entire nligu_users table with the users. Now I would like to copy only some of them to a new database. Can you tell me how to do it?
Thank you for your help
Igor

A: INSERT INTO newtable
SELECT username FROM oldtable
WHERE username in ('name1','name2','name3')

Something like that?


text:
Q: Looping inside block return I have a custom block that allows me to choose a color. This is how the block's return function looks:
                return (
                        el( 'div', { },
                                el( 'div',
                                        { },
                                        el( ColorPalette, {
                                                value: props.attributes.paletteData[0],
                                                onChange: updatePalette,
                                        } )
                                )

                        )
                );

At the moment it shows a single color picker.
However I would like my block to show as many color pickers as there are values inside props.attributes.paletteData.
How can I achieve that? I was hoping I'd be able to loop as you do in React like so:
return (
   {
      props.attributes.paletteData.map(value => {
         return (
            el( ColorPalette, {
               value: etc,
               onChange: etc,
            }
         )
      }
   }

But I haven't been able to get it to work.

A: Well, just change this:
el( ColorPalette, {
    value: props.attributes.paletteData[0],
    onChange: updatePalette,
} )

to this:
el( 'div', {}, props.attributes.paletteData.map(
    function ( value, i ) {
        return el( ColorPalette, {
            'value': value,
            onChange: updatePalette,
            key: 'color-' + i, // required
            //...
        } );
    }
) )

I.e. Pass an array of elements as the third parameter:
el( 'div', {}, <array of elements here> )

Or am I not understanding you?


text:
Q: first order linear recurrence I have been given an introduction to linear first order recurrences. The notes given in class haven't helped much with the assignment, and I have spent some hours trying independently (I haven't studied maths for 8+ years). Your help would be greatly appreciated.
The first part of the question:
U(n+1)= AU(n)+B with the assumption that A>1
where A=6 B=4
The initial starting value is 666.
Determine U5 and U10.

A: HINT
We know that
$U(n+1)=6U(n)+4$ (for $n\ge1$) and $U(1)=666$. Then
$$
\begin{align}
n=1{:}\quad&U(2)=6U(1)+4=6\cdot666+4=4000,\cr
n=2{:}\quad&U(3)=6U(2)+4=6\cdot4000+4=24004,\cr
&\ldots
\end{align}
$$


text:
Q: Blazor, fill 0 value binded property as empty string in input Hi I have a question,
So I am experimenting with blazor and it has been fun but I was wondering when I bind a simple model, with one int property to a text input for example:
<input type="text" class="communication__control--input" id="broadcast-port" autocomplete="off" placeholder=" " @bind="@this.Simple.Number" />

Now property in model is just int (not nullable) so default value would be 0 for that input. So my question is can I make that 0 will show as an empty string in input and still if I write any value (for example 3 will show as 3 but 0 will show empty string) to it it will bind?
Basing @Bennyboy1973 comment, basically I could go with 2 properties one that will be binded string prop and other would be read only int that will try to convert first one, or just use 2 model combination (something like DTO and backend model) with automapper. But is there any simpler way?

A: If you really want to do it this way, then this works:
    <input type="text" @bind-value="model.Value" />

@code {

    public class Model
    {
        public string Email { get; set; }

        public string Value
        {
            get => _value != 0 ? _value.ToString() : string.Empty;
            set
            {
                if (int.TryParse(value, out int pvalue))
                    _value = pvalue;
                else
                    _value = 0;
            }
        }

        private int _value;
    }

I can foresee a problem or two with more advanced situations in validation and edit state management, so I would probably write a custom version of the Blazor InputText.


text:
Q: Ruby: Assign output of a function only if it does not return nil When programming in Ruby I quite often have assignments like the following
test = some_function if some_function

With that assignments I want to assign the output of a function, but if it returns nil I want to keep the content of the variable. I know there are conditional assignments, but neither ||= nor &&= can be used here. The shortest way I found to describe the statement above is
test = (some_function or test)

Is there a better / shorter way to do this?

A: I don't think there's anything better than the last snippet you showed but note that or is used for flow control, use || instead:
test = some_function || test

It's usually better to assign new values to new names, the resulting code is easier to understand and debug since variables/symbols have the same value throughout the scope:
some_different_and_descriptive_name_here = some_function || test

A: I'd just add parentheses

(a = b) unless b.nil?
(a = b) if b

being inferior because if b is false then a remains as before
Keep in mind that this evaluates b twice, so if b is a function with side-effects (such as changing variables outside of its scope or printing) it will do that twice; to avoid this you must use

temp = b; (a = temp) unless temp.nil?

(which can, of course, be split into)

temp = b
(a = temp) unless temp.nil?


text:
Q: How to skip using @JsonCreator for Enums during deserialization of Json to Java Object? An Enum Class, ColorName is generated using jsonschema2pojo from ColorName json file.So by default the Enum class has by default fromValue method annotated with @JsonCreator.
@JsonCreator
public static ColorName fromValue(String value) {
    ColorName constant = constants.get(value);
    if (constant == null) {
        throw new IllegalArgumentException(value);
    } else {
        return constant;
    }
}

If this class is used to deserialize the json string to Java object and if there is a new/wrong Enum value passed in the json, then the deserialization fails with IllegalArgumentException()
When attempted to avoid this error using below, it didn't work

ObjectMapper om = new ObjectMapper();
      om.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);

The issue seems to be because @JsonCreator is honoured always. Is there a way to indicate the deserializer to skip this or ignore unknown enum value ?

A: This has been fixed by a change to the Jackson library itself, as of https://github.com/FasterXML/jackson-databind/pull/1642/files
According to https://github.com/FasterXML/jackson-databind/pull/1642 it has been backported to Jackson 2.8.9, so try upgrading to that.


text:
Q: Checking if my app is using any undocumented parts of the API I just read through this question, but I am still confused.
How can I know if my app is using undocumented API calls before submitting to it to the app store? Are there any tools I can use?

A: Undocumented methods aren't listed in the public headers. If you're using any such methods you will have had to declare them yourself in a category or gone out of your way to call them using a method like performSelector:@selector(...) or through some Objective-C runtime function.
In other words, it's unlikely that you'll call an undocumented method by accident.
The only reason to worry is if you're using code that someone else wrote and which you haven't taken the time to read through, or if you're perhaps using a library created by someone else for which you don't even have the source code. In that case, it's up to you to talk to the developer or otherwise satisfy yourself that the code in question doesn't use undocumented methods.

A: Based on the answers I've found online, I do not believe there is anyway to dynamically be notified if you are using an undocumented API while coding. For the most part, it is assumed programmers would know ahead of time if they are using a third-party API that is not documented/approved by Apple. All the related answers suggest using the Validate step after you make an archive of your app: https://stackoverflow.com/questions/9815498/detecting-private-apis

A: The problem is not only with using an undocumented API, but reportedly with using any method which looks like an undocumented API to Apple (which, not being publicly documented, there's no way for you to know).  Therefore, to reduce risk of rejection, make sure that any of your own methods don't even look like an iOS or UIKit-named method or variant or future extension thereof.
If you are really concerned, you could dump all the method and class names from your compiled executable, and google them all to make sure they either show up nowhere, or on an official Apple public API page.


text:
Q: mySQL - how to code SELECT statement correctly I have a mySQL SELECT statement with a combination of full text search and normal search in the WHERE condition and an additional JOIN like this
SELECT
 customer.*,
 countries.name as country
 FROM customer
 LEFT JOIN countries ON countries.ID = customer.country_id
 WHERE customer.num   = :keyword
    OR customer.city  = :keyword
    OR customer.email = :keyword
    OR MATCH (customer.company) AGAINST (:keyword)
    OR countries.name = :keyword

Queries with a full text search into (customer.company) column returns no result as long as the table.column countries.name is part of the WHERE condition. But queries into countries.name itself are successful.
How to code the SELECT statement correctly to return a successful query using a combination of all WHERE components from above example ?
EDIT :
In a previous version I used this statment
 SELECT
  customer.* ,
  countries.name
  FROM customer, countries
  WHERE customer.country_id=countries.ID
  AND MATCH (customer.company) AGAINST (:keyword)

  UNION

  SELECT
  customer.*,
  countries.name
  FROM customer, countries
  WHERE customer.country_id=countries.ID
  AND countries.name=:keyword

which works well. I just do not know if this is the efficient way to query two tables with different searchs (full text and normal). Also when I search in more than 2 columns the code is getting blown up easily, which I would like to avoid.
Any more ideas and help is welcome

A: You should check for NULLs since you are using a LEFT JOIN :
SELECT
     customer.*,
     countries.name as country
 FROM customer
 LEFT JOIN countries ON countries.ID = customer.country_id
 WHERE customer.num   = :keyword
    OR customer.city  = :keyword
    OR customer.email = :keyword
    OR MATCH (customer.company) AGAINST (:keyword)
    OR (countries.name = :keyword OR countries.name IS NULL)

Just for clarification, conditions on the right table of a LEFT JOIN should be placed only inside the ON clause, not the WHERE clause . This is a bit different, since you want to compare it against all the other conditions, therefore - the NULL comparison.

A: My solution is just set a default value = '' to countries.name if it's null using CASE WHEN
(CASE WHEN countries.name is null then 'default value' else countries.name END)

new query
SELECT
 customer.*,
 countries.name as country
 FROM customer
 LEFT JOIN countries ON countries.ID = customer.country_id
 WHERE customer.num   = :keyword
    OR customer.city  = :keyword
    OR customer.email = :keyword
    OR MATCH (customer.company) AGAINST (:keyword)
    OR (CASE WHEN countries.name is null then '' else countries.name END) = :keyword


text:
Q: Why HTML Table Is So Slow To Render in Explorer and Edge I'm working with a dynamic HTML table that has a max row count of around 7,000.  The code below shows how the current design is populating the table with rows of data.  Performance in Chrome is great but IE and Edge are terribly slow.  As you can see, the code below is basically assigning the table to the string variable "mTable". innerHTML is then called on the resulting object.  The while loop is just to insert empty rows in the event few records are returned.  The table is draggable, sortable and can be opened in a new window.  All three of those functions become incredibly slow in IE once the table grows in size.  In fact, I can actually watch the table get populated in the new window function - it's that slow.  Edge has better performance in those three areas but it still takes too much time to populate.  I've done a lot of reading about this though most of the literature just describes the problem.  There were a few ideas that mentioned setting the table's layout to fixed and having each row occupy an equal amount of space but that didn't seem to help.  I also saw some older solutions that involved running chrome inside IE but that doesn't seem like an option anymore.   I thought by sharing my code that perhaps someone might provide some insight as to a better approach.  Thank you in advance for any helpful responses.
    function makeTable(param1){

            paramJ = JSON.parse(param1);

            mTable="

"+
                "	"+
                "OBJECTID	"+
                "Locomotive ID	"+
                "Signal ID	"+
                "Avg RSSI	"+
                "Signal Strength	"+
                "Count

";
            iterTable=1;
             mTable+="
";
            for(i=0;i<paramJ.features.length;i++){

                mTable+="
	"+iterTable+"	";
                mTable+=""+paramJ.features[i].attributes.VAL1+"	";
                mTable+=""+paramJ.features[i].attributes.VAL2+"	";
                mTable+=""+paramJ.features[i].attributes.VAL3.toFixed(0)+"	";

                mTable+=""+paramJ.features[i].attributes.VAL4+"	";
                mTable+=""+paramJ.features[i].attributes.VAL6+"	";
                mTable+="
";
                iterTable+=1;

                }

                while(iterTable<100){

                    mTable+="
		";
                    mTable+="	";
                    mTable+="	";
                    mTable+="	";
                    mTable+="	";
                    mTable+="	";
                    mTable+="
";
                    iterTable+=1;
                }
             mTable+="

";
             document.getElementById("containerR2").innerHTML=mTable;

             //below is for sorting and opening table in new window
             $("#myTable").tablesorter( { headers: { 0: { sorter: false} }} );
             if(winOpen=="yes"){newTable();}
    }

A: I would suggest taking some type of primary key, such as OBJECTID if I'm guessing correctly, and use that as the key for a dictionary. Then use document.createElement to populate the dictionary with DOM elements. That will be done only once, whenever you get your data (Initial load, AJAX, etc). Now, when you do anything else, just myTable.appendChild(tableDict[key]) over and over again to add the node to the table. That can either be sorted, or not sorted, depending on the for loop that's running over keys.
If you want more speed, or if my suggestion didn't help, use asyncs to separate adding things to tableDict and progressively putting them on myTable. I don't think this will be necessary though.


text:
Q: Why is Infinity-Infinity NaN? I am stuck with this peculiar scenario mentioned below. Could someone please explain to me what's the reason for the following behavior.
Why is Infinity - Infinity results NaN, but NaN === (Infinity-Infinity) results false ?

A: The answer lies in the full form of NaN.
NaN stands for Not a Number.
Hence, if something is not a number, it cannot be compared or checked for equality.
Going mathematically,
Infinity - Infinity = NaN   (1)

NaN == Infinity - Infinity  (2)

Here in (1) NaN holds a value that signifies the result is not quantifiable.
And in (2) you are checking the equality of 2 entities that are not quantifiable.
Hope that makes sense.
P.S. I know string values can be compared, but that is not the case with NaN.


text:
Q: How to find view by tag? I have a Form that contains a few TableLayoutPanel (List Panels) that I create dynamically.
Each TableLayoutPanel has a unique Tag. Actually each panel has Lable and this Lable has Name = "lable_name"
I need to update this exact Label inside a TableLayoutPanel.
public void UpdateLable(string tag, string newText)
        {
            foreach(var tlp in Views)
            {
                if (tlp.Tag.ToString().Equals(tag))
                {
                    var lable = tlp.findViewByName("lable_name") as Label;
                    lable.Text = newText;
                }
            }
        }

But I can't find method like findViewByName()
So, question is - how to find view by name?

A: Create a method as below
public static IEnumerable<Control> GetControlsOfType<T>(Control control)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl)).Concat(controls).Where(c => c is T);
}

Use it like
Var control= GetControlsOfType<Label>(yourView).FirstOrDefault(x => x.Tag == tag);

if(control != null)
   control.Text = newText

A: there is no such method directly in TableLayoutPanel class. But each Control has Controls property - collection of child controls.
that specialized collection has Find method which allows to get child by name:
var label = tlp.Controls.Find("lable_name", true)[0] as Label;


text:
Q: OPA unit-test failing, How to output response variable? Newbie to OPA, I am writing OPA unit test case.
test_valid_type {
  response = evaluate with
             input as valid_type
  response == "approved"
}

it's failing response == "approved". I want to see the output of response variable, how do i output it?

A: Try the trace method provided by OPA for debugging.
https://www.openpolicyagent.org/docs/latest/policy-reference/#debugging
This will let you print the output.
In your example you can add trace(response) which will print the response output.

A: After reading many documention finally found it.
trace(variable)

prints the content of the variable.
[Ref][1]


text:
Q: WPF Binding textbox to listview stops after textbox value is updated I have a listview that when selected, will populate data from the selected lineitem into separate textboxes.
I used databinding to accomplish the task, which seems to work fine:
<TextBox x:Name="SKU_TxtBox" HorizontalAlignment="Left" Height="23" Margin="10,21,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Text="{Binding SelectedItem.SKU, ElementName=Inventory_ListView, Mode=OneWay}" />

The above code works correctly. The problem starts if in the codebehind I have to change the textbox value; afterwards the databinding stops.
SKU_TxtBox.text = ""

After the above line runs, the textbox will remain blank no matter what is selected in the listview.

A: When working with bindings, you should always manipulate only the binding source.
Inventory_ListView.SelectedItem.SKU = ""

Or a better approach is to have a View Model bound to the view. in which you define a Dependency Property (currentSKU). Then bind it to both Inventory_ListView.SelectedItem and SKU_TxtBox.text. Then it will be:
CurrentSKU = ""


text:
Q: Pull Request displays a 'git --diff...' command? I'm facing a strange behavior with Git and BitBucket.
I created a Pull Request in order to merge my branch into the mother branch.
There is no conflict, however at the bottom of some source code files, I can see:
      [code]
    }
  }
  diff --git a/src/..[path]../xxx.component.ts b/src/..[path]../xxx.component.ts

I don't understand why this command is shown here?...
3 files of my Pull Request have similar line at the bottom, and for one of them, the file xxx doesn't correspond to the merged source code.
Could you please explain me this behavior?
Is that an error? An alert? Anything else?
Thank you for your help
Best regards


text:
Q: How to make TypeScript literal types in Angular (narrow from string to specific strings)? I made a set of radio buttons:

<mat-radio-group [(ngModel)]="learningMode" aria-label="Select an learning mode">
    <mat-radio-button value="videos">Videos
            <mat-icon>videocam</mat-icon>
    </mat-radio-button>
    <mat-radio-button value="vocabulary">Vocabulary
            <mat-icon>feed</mat-icon>
    </mat-radio-button>
    <mat-radio-button value="wordSearch">Word Search
            <mat-icon>search</mat-icon>
    </mat-radio-button>
</mat-radio-group>

It works just great if I set learningMode as a string.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
  learningMode: string = 'videos';
}

The TypeScript Handbook says that I can narrow string to a Literal Type, i.e., three strings:
s: string, alignment: "left" | "right" | "center"

But this doesn't work:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
   learningMode: string, learningModes: 'videos' | 'vocabulary' | 'wordSearch' = 'videos';
}

How do I narrow learningMode from any string to any of three strings?

A: If i understand corectly. There is my aproach how to narrow learningMode.
export declare type LearningModes = 'videos' | 'vocabulary' | 'wordSearch';

and after that i would say
 learningMode: LearningModes;

You cannot use = (equal) in declaring type. So there should be some method (function) to handle this logic. For example with if else statement.
 example(test: string){
   if (test === 'videos'){
      return 'wordSearch'
    }
  }

A: The syntax that you're using for declaring is kind off wrong.
learningMode: 'videos' | 'vocabulary' | 'wordSearch' = 'videos';
//where videos will be default value

A: Here's the complete solution.
import { Component, OnInit } from '@angular/core';

export declare type LearningModes = 'videos' | 'vocabulary' | 'wordSearch';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  learningMode: LearningModes;

  constructor() { }

  ngOnInit(): void {
    this.learningMode = 'videos';
  }

}


text:
Q: Jtextfield border I created a formattedfield which takes only integer as input and i set its border to be a red line border if any alphabet is typed.
Now i want to set default border if user corrects the error.
how can i set default border.
Thanks For Your Help
This is my code :
    if(!(Character.isDigit(evt.getKeyChar()))){
        evt.consume();
        Toolkit.getDefaultToolkit().beep();
        flatNoField_addUser.setBorder(BorderFactory.createLineBorder(Color.red));
    }
    else{
        ?????
    }

A: First of all, it would look like you are using a KeyListener to try and filter a text field, this is a bad idea and can lead to many issues and inconsistencies.  Instead you should be using a DocumentFilter, which is designed to do just this.
You could store a reference to the original border before your start...
Border border = flatNoField_addUser.getBorder();

And simply reapply it when you need to.
A more generic solution would be to ask the UIManger...
Border border = UIManager.getBorder("TextField.border");

The problem with this is it does not take into consideration the use case where the field had a non-default border

A: You can get the original border to the JTextField by using by:
flatNoField_addUser.setBorder(UIManager.getBorder("TextField.border"));


text:
Q: Cors issue in HttpResponse Activity I'm running the Elsa-Core - AspnetCore Monolith Dashboard sample.
Workflow:,

This problem happens in the HttpReponse Activity, the HttpEndpoint works fine
I'm getting an error on the client which I can't catch in the server, I think the problem happens in:
Elsa.Activities.Http -> WriteHttpResponse -> OnExecuteAsync(ActivityExecutionContext context)

It seems that response.WriteAsync fires some background thread that fails at some point but the exception is not caught:
        /// <summary>
        /// The headers to send along with the response.
        /// </summary>
        [ActivityProperty(Hint = "Additional headers to write.", UIHint = ActivityPropertyUIHints.Json)]
        public HttpResponseHeaders? ResponseHeaders { get; set; }

        protected override async ValueTask<IActivityExecutionResult> OnExecuteAsync(ActivityExecutionContext context)
        {

            var httpContext = _httpContextAccessor.HttpContext ?? new DefaultHttpContext();
            var response = httpContext.Response;

          ...

            var bodyText = Content;

            if (!string.IsNullOrWhiteSpace(bodyText))
            {
                try
                {

                    await response.WriteAsync(bodyText, context.CancellationToken);

                    await Task.Delay(5000);      <--CLIENT FAILS HERE
                    Console.WriteLine("Delay End");

                }
                catch(Exception ex)
                {
                    var z = ex;
                }
            }

            return Done();
        }

The API function has not returned when the client already fails:

Client only says "Unknown Backend Error, Status = 0"
The workflow instances are created and Finished OK

This doesn't happen if the call is made from the browser, so it has to be CORS related
I'm using Angular 10, tried in a clean empty project, no credentials, no extra headers in the http call

A: Make sure to update your Startup class to:

*

*Add CORS services, and

*Add CORS middleware.

As you already figured out, make sure to add the CORS middleware component before the call to app.UseHttpActivities() (which is the middleware handling HTTP workflow requests).
Sample code in ConfigureServices:
// Allow arbitrary client browser apps to access the API for demo purposes only.
// In a production environment, make sure to allow only origins you trust.
services.AddCors(cors => cors.AddDefaultPolicy(policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders("Content-Disposition")));

Sample code in Configure:
app
    .UseCors()
    .UseHttpActivities()
    .UseRouting()
    .UseEndpoints(endpoints => { endpoints.MapControllers(); });

With that in place, your AJAX calls from your Angular application should now be allowed.


text:
Q: How to send a Secure e-mail using SMTP I am currently using Google Apps to send SMTP e-mails. If my project deploys some of the information that i am going to be sending will be confidential and i would like to make sure the transmission is secure.  Can anyone please let me know what i need to do to ensure that i send a safe e-mail using smtp through the google apps smtp server? smtp.google.com.
Any help greatly appreciated.
From what I have been told i need to force Https and have a SSL cert in order to do this. I don't know if this is true?

A: You Can Use 'smtp.EnableSsl = true' For Enable SSL for security.
MailMessage mail = new MailMessage();
            mail.To.Add("" + to + "");
            mail.From = new MailAddress("" + from + "");
            mail.Subject = "Email using Gmail";
            string Body = "Hi, this mail is to test sending mail" +
                          "";
            mail.Body = Body;
            mail.IsBodyHtml = true;
            Attachment at = new Attachment(Server.MapPath("~/ExcelFile/TestCSV.csv"));
            mail.Attachments.Add(at);
            mail.Priority = MailPriority.High;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential(""+ username +"", ""+ password +"");
            smtp.EnableSsl = true;
            smtp.Port = 587;
            smtp.Send(mail);

A: To enforce Network Security you have to use SSL. to enforce security of the data going from your webserver to mail server you need to send your mail over SSL. and to secure the HTTP request that triggers the mail action you need to enforce SSL over HTTP.
But the question is Security in what context ? If you need network security to ensure a 3rd party cannot eavesdrop or manipulate then SSL is your way to go.


text:
Q: Show image, wait 10 second and load page content i want to stop html loading after an specific img tag, wait 10 seconds.. and continue...
i mean, the lines at below of , must be read/load 10 seconds after the selected img tag(#waitme).
i tried with JQUERY wait(), delay() functions; but couldnt solve.
i will add this img tag at after  tag, and all content of the site must be load 10 seconds after this image shown.
show #waitme, wait 10 second, load page content..
Could someone help me?

A: You can try this:
...

      Here is your content

...

A: Here is a way to achieve what you want,

*

*Display this image in document's ready handler and hide the page's content.

*Start a timeOut function in windows load handler with 10k
milliseconds.

*In the call back of timeout, hide the image and display the page
content.


text:
Q: How does Mashable.com displays/hides an element through Css? I'm wondering how mashable.com hides its menu button - which appears in the top right hand corner - when the page is above a certain width and disappears when the page is below a certain width. A specific CSS rule:
html.no-touch .main-menu li.menu
{
  display: none;
}

takes precedence over the rule that displays the icon:
.navbar .nav > li
{
   display:block;
   float: left;
}

but I can't see how it's doing it since disabling JavaScript appears to cause no ill effects and none of Css classes applied to parent elements seem to change. It seems that:
html.no-touch .main-menu li.menu
{
  display: none;
}

should always take precedence, but clearly doesn't and somehow this appears to have been accomplished solely with CSS and I'm curious to know how.
A graphic illustrating this is here.

A: They are using css @media queries to show and hide different elements at different resolutions.

A: Mashable.com uses Skeleton which is a very good resposive website design framework. It has well defined @media queries to hide or display divs depending on viewport size.


text:
Q: HighCharts missing data points on line chart I'm using highcharts to plot data and on some data series there are no data points like on image bellow and the jsFiddle example. Before I log a issue on github I want to ask you if there are something that I miss or it id really an issue.

Javascript
$(function () {
    $('#container').highcharts({
        chart: {
                type: 'line',
                animation: false
            },
            title: {
                text: "abc"
            },
            xAxis: {
                type: 'datetime',
                dateTimeLabelFormats: { // don't display the dummy year
                    month: '%e. %b',
                    year: '%b'
                }
            },
            yAxis: {
                title: {
                    text: 'Time [ms]'

                },
                labels: {
                    step: 1
                },
                tickInterval: 100,
                minRange: 400
                //range: 200
            },
            plotOptions: {
                line: {
                    dataLabels: {
                        enabled: true,
                        allowOverlap: true,
                        borderWidth: 2,
                        style: {
                            textShadow: false
                        },
                        padding: 2.5
                    },
                    //selected: true,
                    enableMouseTracking: true,
                    animation: false,
                    allowPointSelect: true,
                    /*stacking: 'percent'*/
                },

            },
        series: [{
        "name": "a",
        "data": [[1458604800000, 1800], [1458691200000, 1600], [1458777600000, 1800], [1458864000000, 1800], [1459123200000, 1800], [1459209600000, 1800]],
        "color": "rgba(91,155,213,1)",
        "dataLabels": {"color": "rgba(91,155,213,1)", "y": 0},
        "_symbolIndex": 0
    }, {
        "name": "b",
        "data": [[1458604800000, 1500], [1458691200000, 1500], [1458864000000, 1500], [1459123200000, 1500], [1459209600000, 1500]],
        "color": "rgba(165,165,165,1)",
        "dataLabels": {"color": "rgba(165,165,165,1)", "y": 24},
        "_symbolIndex": 1
    }, {
        "name": "c",
        "data": [[1458604800000, 1400], [1458691200000, 1300], [1458777600000, 1300], [1459123200000, 1100], [1459123200000, 1100], [1459209600000, 1100]],
        "color": "rgba(237,125,49,1)",
        "dataLabels": {"color": "rgba(237,125,49,1)", "y": 0},
        "_symbolIndex": 2
    }]
    });
});

var seriesToReproduce = [{"name":"a","data":[[1458604800000,1800],[1458691200000,1700],[1458777600000,1700],[1458864000000,1700],[1459123200000,1700],[1459209600000,1700]],"color":"rgba(237,125,49,1)","dataLabels":{"color":"rgba(237,125,49,1)","y":0},"_symbolIndex":0},{"name":"b","data":[[1458604800000,2100],[1458691200000,2000],[1458864000000,2100],[1459123200000,2000],[1459123200000,2000],[1459209600000,2000]],"color":"rgba(165,165,165,1)","dataLabels":{"color":"rgba(165,165,165,1)","y":24},"_symbolIndex":1},{"name":"c","data":[[1458604800000,2300],[1458691200000,2200],[1458777600000,2200],[1458864000000,2200],[1459123200000,2200],[1459209600000,2200]],"color":"rgba(91,155,213,1)","dataLabels":{"color":"rgba(91,155,213,1)","y":0},"_symbolIndex":2}]

DEMO
No data points screenshot: http://i.stack.imgur.com/NS8Rl.png
Thanks!

A: You have to dig into the documentation for the marker attribute of series to find that there is an enabled property, and it says :

enabled: Boolean
Enable or disable the point marker. If null, the markers are hidden when the data is > dense, and shown for more widespread data points. Defaults to null.

So I don't know how they determine that the data is dense or not, but if you want the markers to be always displayed, you should set the enabled property to true.

A: updated Plunk
In highcharts APi there is an option for enabling Markers link,
use
plotOptions: {
        series: {
            marker: {
                enabled: true

            }
        }
    },

for enabling markers in your series ,


text:
Q: How can deserialize using Newtonsoft.Json? How to read it using Newtonsoft.Json?
{
  "192.168.0.12":
       {
         "Name":"12",
         "Mode":"STOP"
       },
  "192.168.0.13":
       {
         "Name":"13",
         "Mode":"STOP"
       }
}

I am using this data class as below:
class Device{
    public string Name;
    public string Mode;
}

Dictionary<string, Device> devices;

So, I tried this code to deserialize. But, I can't read value from JToken as dictionary.
JObject JDevices = JObject.Parse(Encoding.ASCII.GetString(buffer));
foreach (JProperty property in JDevices.Properties())
{
    string name = property.Name;
    JToken value = property.Value;
    // to read Device.Name and Device.Mode
}

A: You can use dynamic object var result = JsonConvert.DeserializeObject<dynamic>(json);
Code to convert to Dictionary:
Dictionary<string, Device> devices = new Dictionary<string, Device>();
string json = "{\"192.168.0.12\": {\"Name\":\"12\",\"Mode\":\"STOP\"},\"192.168.0.13\": {\"Name\":\"13\",\"Mode\":\"STOP\"}}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
foreach (var item in result)
{

         var name = item.Name;
         evices.Add(item.Name.ToString(), new Device {Name = item.Value.Name.ToString(), Mode = item.Value.Mode.ToString()});

 }

A: Try this, no need to use dynamic.
var json = "{
  "192.168.0.12":
       {
         "Name":"12",
         "Mode":"STOP"
       },
  "192.168.0.13":
       {
         "Name":"13",
         "Mode":"STOP"
       }
}";
var result = JsonConvert.DeserializeObject<Dictionary<string, Device>>(json);

foreach (var device in result.Values)
{
    var name = device.Name;
    var mode = device.Mode;
}


text:
Q: Why does an uncountable well-ordered set exist? A well-ordered set $(W, <)$ is a set $W$ with a total order $<$ such that every nonempty subset of $W$ has a minimal element.
Let $(W, <)$ be an infinite well-ordered set.
Define a sequence $ w_0 = \min W$, $ w_{i+1} = \min(W \setminus \bigcup_{j=1}^i \{ w_j \})$ (the minimas exist $\forall i$ since $W$ is infinite), then
$$ W = \{ w_i : i \in \mathbb N_0 \}$$
because the $w_i$ just go through $W$ from the "smallest" element to the "second smallest" and so on, hence every element in $W$ is reached.
Hence, $W$ is countable. Of course, there has to be a mistake in this proof since there are uncountable well-ordered sets. But where is the mistake?

A: The assertion that $W=\{w_i\,:\, i\in \Bbb N_0\}$ is false, and it's already false for almost all countable ordinals: for instance, $W=\{\infty\}\cup\{0,1,2,\cdots\}$, with $x\le \infty$ for all $x\in W$, will result in $w_i=i$, and therefore $W\setminus\{w_i\,:\, i\in\Bbb N_0\}=\{\infty\}$.

A: Nope, you cannot ensure every element in $W$ is reached. Just for $W=\mathbb{Z}_+\times \mathbb{Z}_+,$ having lexicographical order. Which means $(a,b)<(c,d)\Leftrightarrow a<c$ or $a=c$ but $b<d.$
So the smallest one is $(1,1)$, then $(1,2),$ $\cdots$ However, by this way you can only count $(1,n).$ Not for whole $W$ acutually.


text:
Q: How do I detect a socket disconnection? / How do I call socket.recv with a timeout? I'm using gevent patched socket to connect to a streaming server and I'm using an adsl connection.
I don't control the server but in my tests, if I stop the server I can detect the disconnection by just checking if the result from recv is an empty string, but if I turn off my adsl modem recv never exits. If I just disconnect my computer's network cable it doesn't return an empty string either, but when I reconnect it, it returns everything the server sent in the meantime, so I'm guessing the router or modem is keeping the connection open for me and buffering the stream while my network cable is disconnected.
I tried setting socket.SO_RCVTIMEO to a few seconds but it didn't detect the disconnection, recv continues to "block" forever. This is gevent, so it only blocks the greenthread, but I need to detect this disconnection as soon as possible so I can try to reconnect.

A: Use the timeouts provided by gevent, for example in a with-statement:
with Timeout(5, False):
    data = sock.recv()

or as a function:
data = gevent.with_timeout(5, sock.recv, timeout_value="")

A: it's not detecting the disconnection because there wasn't any disconnection, the TCP "connection" is still alive and suppose to be reliable. if for example you unplug your LAN cable, and the re-plug it, the connection will still work.
if you really want to detect the disconnection ASAP, then i guess you should just parse every second the os network status (ifconfig/ipconfig)/ or use os events, and do what you want when you detect network disconnection.


text:
Q: Haxe construct to mimic PHP list() = each() in Haxe 2.10 You probably know this construct in some languages, like in PHP and Perl:
var $a = ["Apple", "Banana", "Pear", "Orange"];
list($p1, $p2, $p3, $p4) = each($a);
echo $p1;  // Apple
echo $p2;  // Banana
echo $p3;  // Pear
echo $p4;  // Orange

It is often used in while loops, e.g. while (list($key, $val) = each($fruit)) echo "$key: $val;". But not only in loops.
In one line you could affect two or three variables coming from different columns of a row in a database, or taking scalar values from an array like in above example.
Another usage of it is in conjunction with split, especially in scripts:
list($a, $b, $c) = split("/", "papa/tango/charlie");    // this is PHP code again.

Is it possible to achieve that or something similar with Haxe?
For instance, supposing with had a static function assignTo (probably a macro), we could imagine this usage:
using ArrExt;

class Test {
    public static function main() {
        [13, "Bobby Fisher", "USA"].assignTo(age, name, country);  // macro would *define* those vars, no declaration needed
        trace(age);
        trace(name);
        trace(country);
    }
}

I'm more looking for an Haxe 2.10 solution, but an Haxe 3 solution would be welcome to so it can be useful to everyone.

A: The feature is called destructuring assignment, or sometimes unpacking.
Instead of writing a macro function, there is a simpler way... use pattern matching (in Haxe 3)!
switch ["Apple", "Banana", "Pear", "Orange"] {
    case [p1, p2, p3, p4]:
        trace(p2); //"Banana"
}

It looks different, but functionally it is the same.

A: list() on the left hand of an assignment is a PHP language construct, not a function(!). If the haxe language does not support this feature, it will not work.


text:
Q: PHP and Twilio Real-time? I'm currently working on a real-time SMS System but I'm fairly positive that my current implementation is a terrible practice and I'm looking for guidance to be more efficient with this.
The Attempt
Currently, when you load up the interface it pulls all the text messages for that number you have selected. Then it fires off an ajax call every 5 seconds to the Twilio JSON PHP script I've written asking for messages newer than the last message in the list.
$.getJSON("/includes/twilio.php",{action:"getconvo",cid:customer.customer_number},function(data){
        $('#sms_messages').html("

");
        $(data.messages).each(function(){
            insertSMS(this.msg,this.date,this.from);
            lastMessage = this.date;
        });
        $("#sms_messages").animate({ scrollTop: $('#sms_messages > div').height()},"fast");
        shouldUpdate = true;
        sms_interval = setInterval(function(){updateSMS(customer.customer_number)},5000);
});

Update Function
function updateSMS(cid){
    if(shouldUpdate){
        $.getJSON("/includes/twilio.php",{action:"getconvo",cid:cid,date:lastMessage},function(data){
            if(data.messages.length > 0){
                // Play an embeded sound effect when a new message is found.
                $('#sms_sound')[0].play();
                $(data.messages).each(function(){
                    insertSMS(this.msg,this.date,this.from);
                    lastMessage = this.date;
                });
                $("#sms_messages").animate({ scrollTop: $('#sms_messages > div').height()},"fast");
            }
        });
    }
}

A: Twilio developer evangelist here.
I don't recommend polling the Twilio API to get "real time" SMS messages. Polling is inefficient and will keep both your servers as well as Twilio's servers busy for longer than is necessary.
Rather, I would use Twilio's webhooks to receive messages. Then, while you are on the page to receive messages I would implement either Server Sent Events (see this article for an in depth description of SSE as well as example PHP code to implement) or web sockets (here's an article on web sockets in PHP and the library built as part of it) in order to push new messages that you receive from the webhook to your page.
Let me know if that helps at all.


text:
Q: the sum of all possible values of natural number 30 < Q < 48 I don't understand this problem very well. It says "If...., then it must..." Let's say, P=15, then it can't be divided by Q larger than 15. I assume Q should be 3, 5, 15, 2, 4, 7, 12, 28.

If a natural number> P is divisible by 15 and 28, then it must also be divisible by the natural number Q where 30 < Q < 48. Find the sum of all possible values of Q satisfying this condition.

A: We are told that $P$ must be divisible by both 15 and 28 so one such number is $ 15 \times 28 = 420 $ but this may not be the smallest number that is divisible by both these numbers.  We need to find the lowest common multiple of both 15 and 28.
One way to do this would be to write out the 28 times table checking each one until we find one that is divisible by 15.  A better way however is to find the prime factors of both 15 and 28.
$ 15 = 3 \times 5 $ and $ 28 = 2^2 \times 7 $
The lowest common multiple is thus: $ 2^2 \times 3 \times 5 \times 7 = 420 $
because our initial two numbers are relatively prime but we didn't know this initially.
The next step from here is to find all numbers $Q$ such that $30 < Q < 48$ and $\frac{420}{Q}$ is an integer. You can do this either by trying them all or considering which ones have 2, 3, 5 or 7 as a factor.
Make sure you don't use any number $Q$ more than once and add them all up.
I'll leave the rest as an exercise


text:
Q: Swift - How to Properly Implement Updating/Setting Up of CoreData for use prior to ViewController loading My situation is as follows:
I will be using CoreData to store/fetch entity instances to be displayed in a tableView. At the start of the app, I have the app check the version of the current library, then - if necessary - download an updated version (via JSON).
The problem (I believe) is that the View Controller loads and crashes when it attempts to pull the tableView information from the data source before the  "version check" and "library updates" to CoreData have completed. Since the update has not completed, the library has no instances of the entity saved and returns a nil value for the rows to be displayed - causing the crash.
My question is: What is the proper way to implement the updating feature and ensure that all "version" checks and "library" updates are completed before the initial view controller is loaded and attempts to retrieve the necessary information to display the tableView.
I assume it has something to do with "willFinishLaunchingWithOptions" in App Delegate, but I am stuck in terms of how to set it up. As you might have guessed, I am new to coding; therefore, detailed responses would be greatly appreciated.

A: To perform some lengthy task (such as implementing the updating feature like "version" checks and "library" updates), follow the following approach:-

*

*Create a view controller which is similar to splash view controller, say CustomSplashViewController

*In CustomSplashViewController, perform the version checks and library updates task

*After completion of updates check, navigate to your home view controller.

*If mandatory updates fail at CustomSplashViewController, then show the popup with try again button.