text:
Q: Integer comparison fails I have a linked list of a node structure, and in my function for searching through the list to find a node with a matching id the if statement seems to fail when comparing he passed in id and the node id. The if statement is on line 6 in the function below. Even if both *node_id* and id has the same value it fails.
NODE *node_id_search(int id, NODE *start) {
    NODE *result = NULL, *current = start;

    do {

        if(current->node_id == id) {
            result == current;
        }

        current = current->next;
    } while(current->next != NULL && result == NULL);

    return result;
}

node.h
typedef struct node {
    /*@{*/
    /**
     * The node id used to identify the node. The id is a positive integer.
     */
    int node_id;

    /**
     * The node type.
     */
    char node_type[10];

    /**
     * Pointer to the next node element.
     */
    struct node *next;
    /*@}*/
} NODE;

A: Other than answers mentioned above(which I don't see how they relate to the question), the only problem I see is this piece of code:
    if(current->node_id == id) {
        result == current; //which should be result = current;
    }

Change it to:
if(current->node_id == id){
     result = current;
     return result; // no need to search any further(hence optimized).
}

Other than that,I don't see any problem with your code.

A: Your code is overly complicated. It can be reduced to:
NODE *node_id_search(int id, NODE *ptr) {

    for( ; ptr; ptr = ptr->next) {
        if(ptr->node_id == id) return ptr;
        }

    return NULL;
}

BTW: the above snippet returns the first matching node in the chain, where the original returned the last.
Also: if the pointer-argument ("start" in the original) were NULL, the original would dereference the NULL pointer and crash (or return nonsense). This version with the for(;;) loop would just return NULL.

A: 2 points to be noted in the block
if(current->node_id == id) {
    result == current;
}

*

*You're not checking whether current is NULL or not. If any node with node_id equal to  id does not exist, eventually you'll reach the end of the list (where next is NULL) and try to evaluate NULL->next and crash. Put a printf() before this block to see what happens.

*You've written result == current, which does nothing on result. It's just checking for equality, and result remains the same forever. It should be result = current, which assigns the value of current to result.


text:
Q: Does draggable/resizable not work with jquery 1.11.1 and jquery-ui 1.10.3? The code is simple  -
$("#chat_widget_container_iframe").draggable( {containment: "#rtcdemo-background-layer", scroll: false} );
$("#chat_widget_container_iframe").resizable({
 // maxHeight: 250,
 // maxWidth: 350,
  minHeight: 270,
  minWidth: 300
});

If I change jquery to 1.7.2, then the code works. But I need 1.11.1 for other things in the page. How can I make it work with 1.11.1?
I get the error " Uncaught TypeError: undefined is not a function "

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to cast json value I'm unable to cast values from json object in to variable.
Here is my json which comes in either of two formats and I always wanted to retrieve the format 1 values and whenever I get format 2 values I just have to igonore executing the assignment to my local variable.
1.
<Parameters>
      <Param1>"aa9c1b47dfc946f396038b6462700e8c"</Param1>
 </Parameters>

*

<Parameters>
      <Param1>{"Code":"12345"}</Param1>
 </Parameters>

Here is my code to fetch GUID value
public static void GetCodes(string code, string msg, params object[] usrLogData)
        {
var proposalId = string.Empty;
 proposalId = (string)userLoggingData.FirstOrDefault();
}

However I'm getting a below exception when I get the second format XML value
Unable to cast object of type '<>f__AnonymousType0`1[System.String]' to type 'System.String'.
I tried with Dictionary and Regex still didn't worked.

A: are you trying to parse XML into your variable?
For example 1, the parameter is in XML and not json.
For example 2, you perhaps need to pass "{"Code":"12345"}" as your parameter, as that is the json object you mentioned..
Moreover, you can try newtonsoft library to parse json into your variable..
try
        {
            //your working code
            var tempproposalId = string.Empty;
            tempproposalId = (string)userLoggingData.FirstOrDefault();
            //your working code
            Guid proposalId;
            if(!Guid.TryParse(tempproposalId, out proposalId))
            {
                //failed to parse GUID, wrong format.. IGNORE
            }

        }
        catch(Exception e)
        {
            //here catch the wrong format for second data,.. you can just ignore it if you wish
        }


text:
Q: How to create SQL-Query to update data in tables? I'm trying to update data in my table.
I have two tables, t1 and t2
T1
T2
I'm want to do, that if t1 have id_avito = null and all_usl_name = %usl_name1% and all_tel = %tel1%, and t2 have id != null, usl_name = %usl_name1% and tel = %tel1%
For example, t1 after execute query must to look like that
update people.t1, people.t2
set
    id_avito = people.t2.id,
    lnk_avito = people.t2.link,
    all_price = people.t2.price,
    all_date = people.t2.date,
    all_adr = people.t2.adr,
    all_usl_name = people.t2.usl_name
where id_avito != people.t2.id
and all_tel= people.t2.tel
and all_usl_type = people.t2.usl_type

I try to do like this, but it is not working
UPD
EXAMPLE: tables. Table before update, after update, and second table

A: Try with update join also you need to use like operator where you are searching with string
update people.t1 a
join people.t2 on id_avito != people.t2.id
and all_tel= people.t2.tel
and all_usl_type = people.t2.usl_type
set
    id_avito = people.t2.id,
    lnk_avito = people.t2.link,
    all_price = people.t2.price,
    all_date = people.t2.date,
    all_adr = people.t2.adr,
    all_usl_name = people.t2.usl_name

A: Please try this.
For SQL
 UPDATE A
 SET
    A.id_avito = B.id,
    A.lnk_avito = B.link,
    A.all_price = B.price,
    A.all_date = B.date,
    A.all_adr = B.adr,
    A.all_usl_name = B.usl_name
 FROM
    people.t1  A
    INNER JOIN people.t2 B
    ON A.id_avito != B.id
    AND A.all_tel= B.tel
    AND A.all_usl_type =B.usl_type
where ISNULL(A.id_avito,'') ='' and A.all_usl_name like '%usl_name1%' and A.all_tel like '%tel1%' and B.id is not null and B.usl_name like '%usl_name1%' and B.tel like '%tel1%'

FOR MYSQL
UPDATE people.t1 a
INNER JOIN people.t2 B
    ON A.id_avito != B.id
    AND A.all_tel= B.tel
    AND A.all_usl_type =B.usl_type
   SET
        A.id_avito = B.id,
        A.lnk_avito = B.link,
        A.all_price = B.price,
        A.all_date = B.date,
        A.all_adr = B.adr,
        A.all_usl_name = B.usl_name
where IFNULL(A.id_avito,'') = ''  and A.all_usl_name like '%usl_name1%' and A.all_tel like '%tel1%' and IFNULL(B.id,0) <> 0 and B.usl_name like '%usl_name1%' and B.tel like '%tel1%'


text:
Q: Is my interpretation of Probability Density Function correct? The question I am asking has its reference listed below:

*

*Can a probability distribution value exceeding 1 be OK?

*Would it be accurate to describe a PDF as a probability mass per unit length

*Introduction to Probability for Data Science

*"The total area underneath a probability density function is 1" - relative to what?
Since I am learning probability properly for the first time, there is a lot of confusion that I want to clarify. The journey from discrete to continuous random variables and distributions is not smooth (no pun intended) at all. I felt like even after reading so many posts, I cannot fully grasp it. My main confusion lies in the interpretation of what a Probability Density Function at point $x$ is, here's my own thought process, it may not be rigorous, but I'd appreciate it if someone can tell me that I am going in the right direction or not.

Problem
We begin with an example:

The masses of 200 six-month-old babies are collected. To visualise the distribution of the
mass of a six-month old baby (which is a continuous random variable), let us for a moment
treat this 200 data points as the probability distribution$^1$ of all the babies'
masses. Then, we can say that $X$ is a random variable that represents the mass of a (randomly drawn) baby.

Density Histogram
The dataset has 200 samples.
We can then group the data into 5 classes with a class width of 1 kg each. The frequency table and the histogram corresponding to the data are shown below.

We try to link back how a density histogram can connect to PDF and its integral. Let $X$ be the continuous random variable defined earlier.

*

*The area under a density histogram is 1, this follows because the relative histogram must add to 1.

*The area represents how dense the population is at that particular interval/bin. The larger the area, the denser the population is (think density).

*For each interval/bin, the area inside that rectangle is simply the relative frequency (i.e. $\text{width of interval} \times \text{density}$).

*Therefore, we can think of it this way, the area inside each interval/bin is the probability of $X$ being in that interval.

*Consequently, we can define $\mathbb{P} [a < X \leq b]$ to be the area inside the interval between point a and b, i.e. $\mathbb{P} [a < X \leq b] = (b-a) \times \text{density}$
Note we defined this without the usage of integrals.

Now this definition seems quite coarse because we are only restricted with a fixed interval, i.e. bins 5-10 with only 1 width, and
we can only find cases for these discretized bins.
What if we want to find $\mathbb{P}[5 < X < 5.25]$? Well, we can discretize our bins further to have 0.25 intervals (width)!

Now the problem is that all the bins are discretized, and hence does not fit the definition of continuous, we can keep ask for a smaller interval on the real line
(i.e. what is $\mathbb{P}[5.00000001 < X \leq 5.00000002]$). Then we have to keep shrink the bin width to recover the area of the rectangle in order to
recover the relative frequency (probability).
Define the number of bins to be $k$, and the width of a bin to be $\frac{5}{k}$ where $5$ is $10 - 5$,
then we can solve this problem by letting $k \to \infty$, this will eventually smooth out the whole
histogram into infinitely number of bins and recover a smooth function $f$, which turns out to be our PDF.
We can use seaborn to plot something like this with 20 bins.

PDF at a point $x$
Finally, I try to connect back on what PDF at a point $x$ is, and attempt to explain why PDF is also the probability per unit length, as well as why it is a "density".
We now ask, what exactly does PDF mean at a point $x$ mean, in other words, if $f_X(x)$ is not the probability, then
what is it? We established that the probability at a point $x$ is $0$, because integrating over a point (line) gives 0 (also can prove by contradiction
by summing up infinite number of bins).
But to me it does not make sense if this number has no meaning. The textbook says that $f_X$ at a point
$x$ is the "probability mass per unit length$^2$ around $x$ within a small neighbourhood $\delta$".
This means that if we define an infinitesimally small interva epsilon $\delta$ around $x$ (here we would just use $x^{+}$) to $x$,
we have an interval $(x, x+\delta]$. We then ask ourselves the probability between
this interval, which is $\mathbb{P}[x < X \leq x + \delta]$.
Now recall we have showed earlier that we can approximately interpret integration as sums, and this is now connected to the histograms
we plotted. If the interval/bin width is very small, then we can say that the probability of this interval is
$\mathbb{P}[x < X \leq x + \delta] \approx \delta f_X(x)$. Note carefully that the interval must be small,
if not the "area" won't be close to the probability in that interval.
Rearranging will get me:
$$
\mathbb{P}[x < X \leq x + \delta] \approx \delta f_X(x) \implies f_X(x) \approx \dfrac{\mathbb{P}[x < X \leq x + \delta]}{\delta}
$$
Then we can see that the PDF at a point $x$ is the probability per delta, which translates to the probability mass per unit length around $x$
within the small neighbourhood $\delta$. One can think of it as how densely packed $f_X$ is around the point $x$, if
$f_X(x)$ turns out to be larger than the rest, this means that the probability of occurring at that point (and its neighbourhood)
is larger than the rest. More concretely, for the same interval length $\delta$, a larger $f_X$ means the probability is higher.
Furthermore, the probability density function can be greater than 1, as long as it obeys that the area under the curve is 1.
Note that the above did not mention about the definition of $f_X$ in terms of integrals, we complete the intuiton as follows:
$$
\mathbb{P}(x \le X \le x+\delta) = \int_x^{x+\delta} f_X(x) \, dx \approx \delta f_X(x) \approx dx f_X(x)
$$
Am I in the right direction if I interpret this way?
Appendix
The code to generate the dataset is:
# generated bins of data from 5-10
bin_56 = np.random.uniform(5, 6, 20)
bin_67 = np.random.uniform(6, 7, 48)
bin_78 = np.random.uniform(7, 8, 80)
bin_89 = np.random.uniform(8, 9, 36)
bin_910 = np.random.uniform(9, 10, 16)
population = np.concatenate((bin_56, bin_67, bin_78, bin_89, bin_910))

Footnotes
1: This means per 1 unit.
2: Even though this is the empirical distribution (observed, collected data) from
the true population (PDF), we will assume that these 200 data points is our true population
since I am trying to understand PDF.


text:
Q: Program "returns" and exits using 2d char array pointers in loop? I'm really baffled by my program's behavior. I'm trying to read from a file and represent the entire file as a 2d char array, but for some reason it seems to just "return" or exit whenever I'm trying to assign a char to an element in that array... Any ideas what I'm missing here?
(Oh and I want it to cut off after the first 10 characters)
Thanks kindly.
(Edited: added headers and main)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main() {
    FILE *fpin;

    fpin = fopen("tester.txt", "r");

    char (*strings)[20][10];      //Array of strings contains entire file
    bool continueReading = true; //boolean for end of file: end of file = 0

/* ===THIS WORKS===
    (*strings)[0][0] = 'f';
    printf("\nPutting character: %c", (*strings)[0][0]);
    return 0;
*/
    int whileLoops = 0;
    while (continueReading)
    {
        //grab first char
        char ch = fgetc(fpin);

        //if no charaters exist break
        if (ch == EOF)
        {
            break;
        }
        if (ch != '\n' && ch != EOF)
        {
            printf("\nPutting character: %c", ch);
            printf(" in Strings - %d", whileLoops);
            printf(" - 0");
            (*strings)[whileLoops][0] = ch;
/* === PROGRAM TERMINATES HERE, NO ERRORS ??? === */
        }

        for (int i = 1; i < 10; i++)
        {

            //concat char by passing to array
            ch = fgetc(fpin); //repeat with next char from infile

            if (ch == '\n') // newline char
            {
                break; //break here go back into while loop
            }
            else if (ch == EOF)
            {
                continueReading = false;
                break;
            }

            if (ch != '\n' && ch != EOF)
            {
                printf("\nPutting character: %c", ch);
                printf(" in Strings - %d", whileLoops);
                printf(" - %d", i);
                (*strings)[whileLoops][i] = ch;
            }

            if (i+1 >= 10)
            {
                while (1)
                {
                    ch = fgetc(fpin); //repeat with next char from infile
                    if (ch == '\n' || ch == EOF)   // newline char
                    {
                        break; //break here go back into while loop
                    }
                }
            }
        }
        whileLoops++;
    }

    fclose(fpin);
    return 0;
}

Input File:
Tony Buffet
Kailey Heson
Art Johnson
John Pernanski

Output:
Putting character: T in Strings - 0 - 0

A: The problem with the code is how you define and access the array.
This is hinted at by the compiler if you include the -Wall flag:
$ gcc main.c -o main -Wall
main.c: In function 'main':
main.c:35:39: warning: 'strings' may be used uninitialized in this function [-Wmaybe-uninitialized]
   35 |             (*strings)[whileLoops][0] = ch;
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~

char (*strings)[20][10] defines a pointer to a 2D array, whereas what you want is just the array: char strings[20][10].
Now you can access the array using strings[whileLoops][0] = ch and the code works.


text:
Q: i.landsat.dehaze add-on for Grass 7.x What happened to the landsat add-ons i.landsat.dehaze and i.landsat.trim in grass7?  I keep seeing references to them but cannot find them in the repository.

A: Both the GRASS GIS Addons i.landsat.dehaze and i.landsat.trim still have not been rewritten in Python which is a requirement to become part of the GRASS GIS 7 Addons section.
The original Shell code is here:

*

*https://github.com/OSGeo/grass-addons/tree/master/grass6/imagery/i.landsat.dehaze

*https://github.com/OSGeo/grass-addons/tree/master/grass6/imagery/i.landsat.trim
Volunteers desired to rewrite the code in Python!


text:
Q: Word for "a deep study" In the past few years I've started to do personal studies on different topics ranging all parts of life. They range in length from a week to a few months, on and off, but focus on understanding a particular subject more fully than I did at the start by reading, thinking, and writing about it.
I'm looking for a term (noun) to describe this or a verb to describe the act of doing the deep study on a particular topic. Are there any English words to properly describe this?

A: What first came to mind was:

delve: to carry on intensive and thorough research for data, information, or the like; investigate:
  to delve into the issue of prison reform.

Usually used with into, as in the example above.
Source: dictionary.com

A: As stated in the comments, investigation is the word that you are looking for.

A formal inquiry or systematic study

(OED)

A: This was called a deep dive where I used to work:

an in-depth exploration

It's mostly used in the noun sense in business. "Tsk. We'll have to perform a deep-dive on this" or "let's do a deep dive on this tomorrow."  It can mean exhaustively examining every facet of an issue.
It's a good noun to use in conjunction with the verb delve suggested earlier.  A noun is needed in the business sense because a "deep dive" begins to take on a certain scheduled ominousness in the noun sense like exam, test, audit and review.

A: I might consider dividing out those studies which only took a couple of weeks and those that you spent a few months on and labeling them differently. For the studies that were only a few weeks, maybe something along the lines of "background research," "examination," or "inquiry." For those projects which you spent several months on, you might want something that packs a little more punch, like "comprehensive analysis." Or stick them all together: "During the past several years I engaged in a range of inquires on a variety of subjects, including background research on x, a through examination of y, as well as a comprehensive analysis of z." It's an easy way to denote which projects you have spent more time on and which projects you were less engaged in.

A: OP could describe these intensive, concentrated studies as, focused research.

focused adjective: giving a lot of attention to one particular thing: the need for more focused research (Cambridge Dictionaries online)

research
1. careful or diligent search
2. studious inquiry or examination; especially: investigation or experimentation aimed at the discovery and interpretation of facts, revision of accepted theories or laws in the light of new facts, or practical application of such new or revised theories or laws
3. the collecting of information about a particular subject; (Merriam-Webster online)

A: Originally, a perusal would have been exactly this, from the verb peruse which meant

to examine or read (something) in a very careful way

but has come to mean

to look at or read (something) in an informal or relaxed way

which is the very opposite. (Both definitions from Merriam-Webster.)
To a sufficiently pedantic crowd, however, perusal might remain an option for expressing this. Especially since the noun form perusal does not see the casual use that peruse does, the fact that you are using that form may be a cue to the right audience that you are using the word "correctly."
Unfortunately, the risk of being interpreted as meaning the exact opposite of what you intend probably eliminates this from consideration.

A: A verb for this might be to pore over:

To examine something closely; in great detail. It can also refer to meditating over something, and to be fully absorbed in a subject.

It is, as the answer in the link says, usually associated with "academics who are passionate about their fields, and students who study obsessively before an important exam."

A: Contemplation or meditation, as in "he meditated on the question for many days".
A "brown study" is a moody attitude, whether sad or angry.

A: An in-depth study of something would properly be called a survey:

to view or consider comprehensively
According to a New York Times report, the DOJ is surveying claims that the ticketing company is forcing venues to use its subsidiary, Ticketmaster, as vendor for high-profile events.
— Patrick Shanley, The Hollywood Reporter, "Live Nation's Ruthless Business Practices Reportedly Probed by Justice Department," 1 Apr. 2018

[MW]
Simply typing the phrase "a survey of" into Google Scholar yields many such of such kinds of surveys.

A: Many words come to mind while describing your act.

*

*Thorough insight.

*Recursive study. (Recursive insight).

*Profound research. (abstract research)

A:
I'm looking for a term (noun) to describe this or a verb to describe the act of doing the deep study on a particular topic

How about immersion?
From WordNet 3.0:

n 3. complete attention; intense mental effort

Colloquially, I've also heard deep dive used, in the context of troubleshooting, and especially in  root cause analysis, to refer to an intensive, often protracted investigation or study.
Here's a source defining deep dive as:

an in-depth exploration.

Both terms are analogous to being deeply submerged in water, and possibly alluding to the mammalian diving reflex.

The mammalian diving reflex is a reflex in mammals which optimizes respiration to allow staying underwater for extended periods of time.

Hope this helps.

A: blow-by-blow
By Cambridge : A blow-by-blow description contains every detail and action of an event
E.g.

However, we do not purport to offer in this book a detailed, blow by blow study of how each organisation set about inventing and implementing its system of PIs.
  [ref: https://books.google.com/books?isbn=1134813651]

A: The verb to scrutinize captures the meaning well.
scrutinize : to examine in detail with careful or critical attention.

A: Odyssey
I suggest 'odyssey' as it means a journey through something that is 'epic' - monsters are encountered and beheaded, Sirens beguile and are avoided and dragons are slain.
Studying and learning are a personal journey through which you encounter yourself, confront misunderstandings, judgements and inner conflicts, on your quest for your personal 'truth'.
Odyssey derives from the adventures of Odysseus - his epic spiritual journey.
You can also say 'spiritual odyssey', 'emotional odyssey', 'linguistic odyssey' or 'odyssey of self-discovery', etc.
https://www.merriam-webster.com/dictionary/odyssey

A: The could be termed an exposition, especially if it is written.
From WordNet 3.0:

exposition
n 1: a systematic interpretation or explanation (usually written) of a specific topic ...
3: an account that sets forth the meaning or intent of a writing or discourse ...


text:
Q: Setting publish rights to Azure website I have multiple developers in my team and I'd like to control who has publish rights to my Azure Website.
We're using Visual Studio 2013 and 2015 CTP for developing this ASP.NET MVC site. I want to make sure Developer A and B can publish to the site but NOT Developer C.
I'd appreciate some pointers on how to manage publish rights to Azure Websites.

A: Microsoft just added RBAC functionality for website deployments:
http://azure.microsoft.com/blog/2015/01/05/rbac-and-azure-websites-publishing/


text:
Q: bash 4.4 inside python with os.system I have problems with running a bash script inside a python script script.py:
import os
bashCommand = """
sed "s/) \['/1, color=\"#ffcccc\", label=\"/g" list.txt | sed 's/\[/    GraphicFeature(start=/g' | sed 's/\:/, end=/g' | sed 's/>//g' | sed 's/\](/, strand=/g' | sed "s/'\]/\"),/g" >list2.txt"""

os.system("bash %s" % bashCommand)

When I run this as python script.py, no list2.txt is written, but on the terminal I see that I am inside bash-4.4 instead of the native macOS bash.
Any ideas what could cause this?
The script I posted above is part of a bigger script, where first it reads in some file and outputs list.txt.
edit: here comes some more description
In a first python script, I parsed a file (genbank file, to be specific), to write out a list with items (location, strand, name) into list.txt.
This list.txt has to be transformed to be parsable by a second python script, therefore the sed.
list.txt
[0:2463](+) ['bifunctional aspartokinase/homoserine dehydrogenase I']
[2464:3397](+) ['Homoserine kinase']
[3397:4684](+) ['Threonine synthase']

all the brackets, :, ' have to be replaced to look like desired output list2.txt
    GraphicFeature(start=0, end=2463, strand=+1, color="#ffcccc", label="bifunctional aspartokinase/homoserine dehydrogenase I"),
    GraphicFeature(start=2464, end=3397, strand=+1, color="#ffcccc", label="Homoserine kinase"),
    GraphicFeature(start=3397, end=4684, strand=+1, color="#ffcccc", label="Threonine synthase"),

A: Read the file in Python, parse each line with a single regular expression, and output an appropriate line constructed from the captured pieces.
import re
import sys

#                         1     2                3
#                        ---   ---              --
regex = re.compile(r"^\[(\d+):(\d+)\]\(\+\) \['(.*)'\]$")
# 1 - start value
# 2 - end value
# 3 - text value
with open("list2.txt", "w") as out:
    for line in sys.stdin:
        line = line.strip()
        m = regex.match(line)
        if m is None:
            print(line, file=out)
        else:
            print('GraphicFeature(start={}, end={}, strand=+1, color="#ffcccc", label="{}"),'.format(*m.groups()), file=out)

I output lines that don't match the regular expression unmodified; you may want to ignore them altogether or report an error instead.


text:
Q: Is it possible not to display INSERT FAILED Error in page, when our custom validation error is triggered We have a visualforce page (Manage Packaged) that saves a record. We added a custom validation using trigger (addError method) to prevent it to save when a certain criteria is met. But when this is triggered, two errors are getting displayed (shown below). Is it possible not to display the second error considering that the code at the record is inserted is managed?

You can only match one invoice at a time
Insert failed. First exception on row 0; first error:
  FIELD_CUSTOM_VALIDATION_EXCEPTION, You can only match one invoice at atime: []


text:
Q: How to relax subplot ratio in pyplot? I plot an array of images as subplots as follows:
fig, ax = plt.subplots(nrows=32,ncols=3, sharex=True, sharey=True)
...
for n in range(32*3):
  ax = plt.subplot(32, 3, n)      # select where to plot
  plt.imshow(filt, cmap='gray')   # plot image
  n += 1
...
plt.show()

but the images are too small - seems like the plt.show() holds the horizontal/vertical ratio to 1, so the overall plot is square, but should be 32/3 ratio. As a result, my images look very small and distant within columns:

I tried using tight_layout() as suggested here and tried plt.axes().set_aspect(32/3) but it did not have any good effect. There are many examples that use equal number of subplots horizontally and vertically, so the subplots look normal, but in my case I have 32 rows and 3 columns which is scaled weirdly. What am I missing?


text:
Q: How to delete parent array JSON string and leave an child array JSON string? I have a JSON array like this ( it has an array inside an array like the code below )
{
    "data": [
        {
            "id": "40",
            "memo_kondisi": "OKe lah",
            "id_kondisi": "010118",
            "total_row": "2",
            "nilai_temuan": "10.000.000",
            "nilai_potensi_kerugian": "9.000.000",
            "data_sebab": [
                {
                    "id": "12",
                    "id_sebab": "0202",
                    "total_row_b": "2",
                    "memo_sebab": "sebab 1",
                    "data_rekomendasi": [
                       {
                        "id": "14",
                        "id_rekomendasi": "",
                        "nilai_rekomendasi": "0",
                        "memo_rekomendasi": "",
                        "data_tindak_lanjut": [
                            {
                                "id": "20",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            },
                            {
                                "id": "21",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            }
                           ]
                        },
                        {
                            "id": "14",
                            "id_rekomendasi": "",
                            "nilai_rekomendasi": "0",
                            "memo_rekomendasi": "",
                            "data_tindak_lanjut": [
                                {
                                    "id": "20",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                },
                                {
                                    "id": "21",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

I wanted the JSON array to look like this:
Expected Result
{
    "data": [
        {
            "id": "40",
            "memo_kondisi": "OKe lah",
            "id_kondisi": "010118",
            "total_row": "2",
            "nilai_temuan": "10.000.000",
            "nilai_potensi_kerugian": "9.000.000",
            "data_sebab": [{
                                "id": "20",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            },
                            {
                                "id": "21",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            },
                                {
                                    "id": "20",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                },
                                {
                                    "id": "21",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                }
                            ]
        }
    ]
}

So, the array parent will be removed and will leave a child array, it's like push array but its reverse and it will delete the parent JSON array. Any suggestion ? Since i had no idea how to delete the parent array, i didn't give any minimal code that i made.

A: Here is a solution using jq.  If the sample data is in data.json then the command
$ jq -M '.data[].data_sebab |= map(.data_rekomendasi[].data_tindak_lanjut[])' data.json

produces
{
  "data": [
    {
      "id": "40",
      "memo_kondisi": "OKe lah",
      "id_kondisi": "010118",
      "total_row": "2",
      "nilai_temuan": "10.000.000",
      "nilai_potensi_kerugian": "9.000.000",
      "data_sebab": [
        {
          "id": "20",
          "id_tindak_lanjut": "",
          "nilai_tindak_lanjut": "0",
          "memo_tindak_lanjut": "",
          "tindak_lanjut_no": "1",
          "tgl_tindak_lanjut": "0000-00-00"
        },
        {
          "id": "21",
          "id_tindak_lanjut": "",
          "nilai_tindak_lanjut": "0",
          "memo_tindak_lanjut": "",
          "tindak_lanjut_no": "1",
          "tgl_tindak_lanjut": "0000-00-00"
        }
      ]
    }
  ]
}

A: You can decode the array using json_decode() then re-assign the array:
# Presumably you have this somewhere as an array already or in a string
$json = '{
    "data": [
        {
            "id": "40",
            "memo_kondisi": "OKe lah",
            "id_kondisi": "010118",
            "total_row": "2",
            "nilai_temuan": "10.000.000",
            "nilai_potensi_kerugian": "9.000.000",
            "data_sebab": [
                {
                    "id": "12",
                    "id_sebab": "0202",
                    "total_row_b": "2",
                    "memo_sebab": "sebab 1",
                    "data_rekomendasi": [
                        {
                            "id": "14",
                            "id_rekomendasi": "",
                            "nilai_rekomendasi": "0",
                            "memo_rekomendasi": "",
                            "data_tindak_lanjut": [
                                {
                                    "id": "20",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                },
                                {
                                    "id": "21",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}';
# Decode
$array = json_decode($json,true);
# Reassign
$array['data'][0]['data_sebab'] = $array['data'][0]['data_sebab'][0]['data_rekomendasi'][0]['data_tindak_lanjut'];
# Write back to json
echo json_encode($array);

A: You've got 4 nested arrays, so in order to flatten the middle two tiers, you'll have to execute 4 nested loops.
Demo: https://3v4l.org/XWpZB
$data = json_decode($json, true)['data'];

$result = [];

foreach ($data as $datum) {
    // copy top tier
    $copy = $datum;
    // clear children
    $copy['data_sebab'] = null;

    foreach ($datum['data_sebab'] as $sebab) {
        foreach ($sebab['data_rekomendasi'] as $rekomendasi) {
            foreach ($rekomendasi['data_tindak_lanjut'] as $tindak_lanjut) {
                // copy leaf child
                $copy['data_sebab'] []= $tindak_lanjut;
            }
        }
    }

    // nest last leaf under top tier
    $result['data'] []= $copy;
}

echo json_encode($result, JSON_PRETTY_PRINT);

A: Try this using ES6 for...of statement :
The for-of loop introduced with ES6 allows for iterating over an array (or any iterable) in a succinct fashion similar to how we can iterate over the keys of an object using for-in.
Working Demo :

var jsonObj = {
    "data": [
        {
            "id": "40",
            "memo_kondisi": "OKe lah",
            "id_kondisi": "010118",
            "total_row": "2",
            "nilai_temuan": "10.000.000",
            "nilai_potensi_kerugian": "9.000.000",
            "data_sebab": [
                {
                    "id": "12",
                    "id_sebab": "0202",
                    "total_row_b": "2",
                    "memo_sebab": "sebab 1",
                    "data_rekomendasi": [
                       {
                        "id": "14",
                        "id_rekomendasi": "",
                        "nilai_rekomendasi": "0",
                        "memo_rekomendasi": "",
                        "data_tindak_lanjut": [
                            {
                                "id": "20",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            },
                            {
                                "id": "21",
                                "id_tindak_lanjut": "",
                                "nilai_tindak_lanjut": "0",
                                "memo_tindak_lanjut": "",
                                "tindak_lanjut_no": "1",
                                "tgl_tindak_lanjut": "0000-00-00"
                            }
                           ]
                        },
                        {
                            "id": "14",
                            "id_rekomendasi": "",
                            "nilai_rekomendasi": "0",
                            "memo_rekomendasi": "",
                            "data_tindak_lanjut": [
                                {
                                    "id": "20",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                },
                                {
                                    "id": "21",
                                    "id_tindak_lanjut": "",
                                    "nilai_tindak_lanjut": "0",
                                    "memo_tindak_lanjut": "",
                                    "tindak_lanjut_no": "1",
                                    "tgl_tindak_lanjut": "0000-00-00"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
};

var newArr = [];

for (let i of jsonObj.data) {
  for (let j of i.data_sebab) {
    for (let k of j.data_rekomendasi) {
      for (let l of k.data_tindak_lanjut) {
        newArr.push(l);
      }
    }
  }
}

jsonObj.data[0].data_sebab = newArr;

console.log(jsonObj);


text:
Q: SolrCloud ZooKeeper compatibility We have Solr running in our production environment in a master-slave setup which works great. But we are looking to shore up our Solr infrastructure more as we get Solr involved more involved in our solution.
For this, we are looking to implement SolrCloud. I have gone through the documentation of SolrCloud and it seems straight enough to implement.
One area, where I'm not clear, where I need more information is what version of ZooKeeper goes with a specific version of Solr in SolrCloud. I'm looking to go with Solr 5.5 for SolrCloud, due to supported compatibility with another product we use here. Is there a compatibility chart that I can look at to determine the appropriate version of ZooKeeper?

A: I'm fairly sure the Zookeeper protocol has been kept stable between the versions used by Solr, so that shouldn't really be an issue (the 3.4.x version has been in use for many years now).
The only important part I remember is that Solr itself changed how it expects the layout of the zookeeper store to be - moving from a global clusterstate.json to a state.json for each collection. This helps immensely with scalability and the need to push all updates to all nodes. That scale might not have much relevancy for you at this time, however.
However, to find the exact version used in a version of Solr, CHANGES.txt can be helpful! For the last version of Solr 5.5, this was the bundled versions:
Versions of Major Components
---------------------
Apache Tika 1.7
Carrot2 3.10.4
Velocity 1.7 and Velocity Tools 2.0
Apache UIMA 2.3.1
Apache ZooKeeper 3.4.6
Jetty 9.2.13.v20150730

A: Our kerberized Hadoop cluster has running Solr 5.5 on three nodes. We are using ZooKeeper 3.4.6. This works like a charm. However ZK config changes can be a pain in the ass sometimes and has to be done with caution in a production environment.
Are you using Kerberos? Than ZK setup is a little different.


text:
Q: Akka Stream TCP + Akka Stream Kafka producer not stopping not publishing messages and not error-ing out I have the following stream:
Source(IndexedSeq(ByteString.empty))
.via(
  Tcp().outgoingConnection(bsAddress, bsPort)
    .via(Framing.delimiter(ByteString("\n"), 256, allowTruncation = true))
    .map(_.utf8String)
)
.map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
.runWith(
  Producer.plainSink(
    ProducerSettings(system, new ByteArraySerializer, new StringSerializer)
      .withBootstrapServers(s"${kafkaAddress}:${kafkaPort}")
  )
).onComplete {
    case Success(Done) => printAndByeBye("Stream ends successfully")
    case Failure(ex) => printAndByeBye("Stream ends with an error: " + ex.toString)
  }

It works fine for a while, and I can consume the messages populated on the Kafka topic. But from time to time, apparently at a random interval, there are no more messages published, and this code is not logging any errors (printAndByeBye will print the message passed and terminates the actor system.) After restarting the app, the messages continue to flow.
Any idea on how to know what is going on here?
Edit: I put Kamon on it and I could see the following behavior:

It looks like something stopped without informing the stream should stop, but I don't know how to make it explicit and stop the stream.

A: I´d suggest creating the flow with supervision attributes to handle possible exceptions in your TCP connection like that:
val flow =
    Tcp().outgoingConnection("", 12)
          .via(Framing.delimiter(ByteString("\n"), 256, allowTruncation = true))
          .map(_.utf8String).withAttributes(ActorAttributes.supervisionStrategy {
      case ex: Throwable =>
        println("Error ocurred: " + ex)
        Supervision.Resume
     }

and
Source(IndexedSeq(ByteString.empty))
.via(flow)
.map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
.runWith(
  Producer.plainSink(
    ProducerSettings(system, new ByteArraySerializer, new StringSerializer)
      .withBootstrapServers(s"${kafkaAddress}:${kafkaPort}")
  )
).onComplete {
    case Success(Done) => printAndByeBye("Stream ends successfully")
    case Failure(ex) => printAndByeBye("Stream ends with an error: " + ex.toString)
  }

If there is any error with the flow the stream stops. With this configuration you´ll see if the flow has thrown any exception.

A: If everything goes silent it could be down to backpressure been applied somewhere.
Try and selectively replace your backpressure-aware stages with non-backpressure-aware stages and check if the problem is still there.
In your case there are 2 possible sources of backpressure:
1) the TCP connection
You can try and attach an infinite source of ByteString to Kafka, doing something along the lines of:
Source.cycle(() => List(???).iterator)
.map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
.runWith(
  Producer.plainSink(
    ProducerSettings(system, new ByteArraySerializer, new StringSerializer)
      .withBootstrapServers(s"${kafkaAddress}:${kafkaPort}")
  )
).onComplete {
    case Success(Done) => printAndByeBye("Stream ends successfully")
    case Failure(ex) => printAndByeBye("Stream ends with an error: " + ex.toString)
  }

2) the Kafka sink
replace it with some logging
Source(IndexedSeq(ByteString.empty))
.via(
  Tcp().outgoingConnection(bsAddress, bsPort)
    .via(Framing.delimiter(ByteString("\n"), 256, allowTruncation = true))
    .map(_.utf8String)
)
.map(m => new ProducerRecord[Array[Byte], String](kafkaTopic, m))
.runForeach(println)
.onComplete {
    case Success(Done) => printAndByeBye("Stream ends successfully")
    case Failure(ex) => printAndByeBye("Stream ends with an error: " + ex.toString)
  }

Can you see the problem in only one of the 2 cases? In both? In none?

A: The stream was not failing, but the TCP stream went idle as the device publishing data stop sending data after a while without dropping the connection.
Instead of using the simpler:
TCP().outgoingConnection(bsAddress, bsPort)

I end up using:
def outgoingConnection(
remoteAddress:  InetSocketAddress,
localAddress:   Option[InetSocketAddress]           = None,
options:        immutable.Traversable[SocketOption] = Nil,
halfClose:      Boolean                             = true,
connectTimeout: Duration                            = Duration.Inf,
idleTimeout:    Duration                            = Duration.Inf): Flow[ByteString, ByteString, Future[OutgoingConnection]] = ???

so
Tcp().outgoingConnection(bsAddress, bsPort)

became
val connectTimeout: Duration = 1 second
val idleTimeout: Duration = 2 second
Tcp().outgoingConnection(
    remoteAddress = InetSocketAddress.createUnresolved(bsAddress, bsPort),
    connectTimeout = connectTimeout,
    idleTimeout = idleTimeout
  )

by informing idleTimeout, the follow start failing and another flow could be restarted.


text:
Q: A possible misconception on the weak law of large numbers
Let $\{X_n\}_{n\geq1}$ be a sequence of i.i.d. random variables having
common probability density function   $f(x)=xe^{-x}, x\geq0$
Let $\bar{X_n}=\frac{1}{n}\sum_{i=1}^nX_i$
Then, $\lim_{n\to\infty}P(\bar{X_n}=2)$ equals??

$\because \bar{X_n}\xrightarrow[n\to\infty]{P} 2=E[X_i].$   (hence, $\bar{X_n}$ converges in probabilty to a discrete distribution, that is equal to $2$ with probability $1$)
$\therefore \forall \epsilon>0, \lim_{n\to\infty}P(|\bar{X_n}-2|<\epsilon)=1$
$\therefore  \lim_{n\to\infty}P(\bar{X_n}=2)=1 $
(here I derive intuition from the result in real analysis that says, that if two numbers are arbitrarily close to each other, then those numbers are the same.)
But, the given answer is that   $\lim_{n\to\infty}P(\bar{X_n}=2)=0$.
So, what did i do wrong? and how to prove that  $\lim_{n\to\infty}P(\bar{X_n}=2)=0$
Also, looking at the answer, I get the feeling that even as $n\to\infty, \bar{X_n}$ still remains a continuous random variable. But this is very counterintuitive, because all the probability  of $\bar{X_n}$ is getting concentrated inside smaller and smaller intervals around $2$, but still in the limit, $\bar{X_n}$ does not become a discrete random variable. How is this possible?
Note: I do know that $\lim_{n\to\infty}P(|\bar{X}_n-\mu|\leq\epsilon)=1$ does not imply that, for large $n$, $|\bar{X}_n-\mu|\leq\epsilon$

A: ''here I derive intuition from the result in real analysis that says, that if two numbers are arbitrarily close to each other, then those numbers are the same''. The numbers here are no arbitrarily close to each other as you said in the note, becasue $X_n(\omega)$ is a different number for each $n$.
To prove that the limit is in fact zero, notice that the sum of i.i.d variables with density is a random variable with density (therefore for each fixed $n, \ P(\overline{X}_n = a)=0$ for every $a \in \mathbb{R}$).
To visualize this example, imagine that for each $n$ the density of $\overline{X}_n$ is a curve in $\mathbb{R}$ which as you said is getting closer to the constant $2$. However for each fixed $n$ the random variable has density.

A: As you correctly pointed out $\bar{X}_n \xrightarrow{p} 2$ but this is a slightly different statement than $\lim_{n\to\infty}P(\bar{X}_n =2) =1$.
Let $\bar{X}_n$ be the sequence of random variables representing the sample mean of $n$ iid samples of $X$. Being averages of continuous variables, each of these has a differentiable cumulative distribution function $F_n$ on $(0,\infty)$ (i.e., density function) denoted $f_n$.
Note that $\bar{X}_n \xrightarrow{p} 2 \implies F_n(x) \to \mathbf{1}_{\geq2}(x):=F(x)$, where $\mathbf{1}_A(x)$ is the indicator function.
Using the properties of CDFs, we define
$$P_n(x) := P(\bar{X}_n=x) = \lim_{\delta \to 0^+} \left[F_n(x+\delta)-F_n(x-\delta)\right]$$
Since each $F_n$ is differentiable at $x=2$, it is also continuous at $x=2$, hence
$$P_n(2)= 0 \;\;\forall n>0 \implies \lim_{n\to\infty} P_n(2) = 0 \neq \lim_{\delta \to 0^+} \left[F(2+\delta)-F(2-\delta)\right]$$
Put a different way
$$\lim_{n\to \infty}\lim_{\delta \to 0^+} \left[F_n(2+\delta)-F_n(2-\delta)\right] \neq \lim_{\delta \to 0^+}\lim_{n\to \infty} \left[F_n(2+\delta)-F_n(2-\delta)\right]$$
Your confusion comes from assuming these limits can be interchanged.


text:
Q: How to compute this integral? Dominated convergence theorem doesn't apply I've met a physics problem and I need to evaluate:
$$\int_0^{\infty}y \sum_{n=1}^{\infty}\frac{(-1)^n}{(n^2r^2 + y^2)^{3/2}} dy$$
If we pretend we can interchange the sum and the integral we get the alternate harmonic series. But I'm not sure there is a theorem that garantees we can interchange them in this case.
And I'm not sure if Taylor expansion would help either, both the integral and the sum of the absolute values are not finite.
Can one show that it diverges?

A: Since terms are alternating and decreasing in absolute value with respect to $n$, we have
$$\left|\sum_{n=1}^N \frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\right| \leqslant  \frac{y}{(r^2 + y^2)^{\frac32}} < \frac{1}{y^2},$$
and since $y^{-2}$ is integrable on $[1,\infty)$, by the dominated convergence theorem,
$$\int_1^{\infty} \sum_{n=1}^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy =  \sum_{n=1}^{\infty}\int_1^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy $$
Note also that
$$\frac{y}{(n^2r^2 + y^2)^{\frac32}} =\frac{1}{2nr}\frac{2nry}{n^2r^2 + y^2} \frac{1}{\sqrt{n^2r^2 + y^2}} \leqslant \frac{1}{2nr} \cdot 1 \cdot \frac{1}{nr} = \frac{1}{2n^2r^2},$$
and $\frac{y}{(n^2r^2 + y^2)^{\frac32}}\to 0 $ uniformly and monotonically with respect to $n$. By the Dirichlet test, the series is uniformly convergent for $y \in [0,1]$ and we can switch the sum and the integral over the finite interval $[0,1]$, as
$$\int_0^{1} \sum_{n=1}^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy =  \sum_{n=1}^{\infty}\int_0^{1}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy,$$
Thus,
$$\int_0^{\infty} \sum_{n=1}^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy =  \sum_{n=1}^{\infty}\int_0^{1}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy + \sum_{n=1}^{\infty}\int_1^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy \\ = \sum_{n=1}^{\infty}\int_0^{\infty}\frac{(-1)^ny}{(n^2r^2 + y^2)^{\frac32}}\, dy$$


text:
Q: REST API cache control for shared cache on server? I would like to implement some caching on my REST API server so that clients can get faster responses from cached data that is shared among them.
However, I would still like to give clients the option of getting fresh data if they prefer it.
Most examples of the HTTP cache headers I have seen assume that the data is being cached locally on the client, but I will be storing it on my server in Redis.
What is the preferred method to expose cache control functionality to clients when the cache is server-side and shared?
Thank you.

A: Have you looked at the Cache-Control

Cache-Control: max-age=
  Cache-Control: max-stale[=]
  Cache-Control: min-fresh=
  Cache-Control: no-cache
  Cache-Control: no-store
  Cache-Control: no-transform
  Cache-Control: only-if-cached


text:
Q: Split two divs with diagonal line, scaling to content I've got a mockup for a website which has a hero section consisting of two sections, split diagonally at the same angle. The two sections have content and need to scale to fit the content.
I have tried the method described here: two divs split with diagonal line - CSS
but it doesn't work well with content; adding text to the div just extends the rectangle not the triangle. How do I get the boxes to scale with the content?
I would post a comment but I don't have the reputation :/
EDIT: by scaling to content, I mean that the if I add content to one of the divs, the div should be able to fit all of the content inside of it. Both of the divs would need to be the same height. Apologies for any confusion :)

A: The question is not so clear as to :

scaling to content

I suppose it means that it should keep the same aspect after window resize (??).
// Create a flex container
.hero {
  display: flex;
  height: 500px;
  width: 100%;
  flex-flow: row nowrap; // make the two divs side by side
  font-size: 2em;
  color: white;
  font-family: sans-serif;
  position: relative;
}

// apply basic styles to the divs
.hero div{
  display: flex;
  position: relative;
  background-color: tomato;
  width: 50%;
  padding: 50px;
}

// + 100px for :after and :before to fit
// + 10px for the space we really want to see between diagonal
.hero div:first-child{
  margin-right: 110px;
}

.hero_1:after, .hero_2:before{
  content:'';
  position: absolute;
  top: 0;
  width: 0;
  height: 0;
}

// Add a triangle at the end and starts of both divs to simulate diagonal
.hero_1:after {
    left: 100%;
    border-top: 500px solid tomato;
    border-right: 100px solid transparent;
}
.hero_2:before {
    right: 100%;
    border-bottom: 500px solid tomato;
    border-left: 100px solid transparent;
}

Please have a look to this codepen. The split is made with a diagonal line, and it fits to window resizes.
If it's not the desired effect, please edit the question to be more explicit about "scaling to content" I'll be happy to help.


text:
Q: WordPress: WooCommerce email_order_items_table remove price I'm new to PHP and also new to WooCommerce.
I want to edit the woo-custom-emails plugin.
As a user I have the possibility to set {email_order_items_table} in my text which outputs the product name, followed by its quantity, followed by the price. I want to remove the price!
Here is what it does in code:
    // file: my_plugin/admin/class-wcemails-instance.php

    $this->find[]    = '{email_order_items_table}';
    $this->replace[] = $this->object->email_order_items_table();

here is what the that function does:
    // file: woocommerce/includes/abstracts/abstract-wc-order.php

/**
 * Output items for display in html emails.
 *
 * @param array $args Items args.
 * @param null $deprecated1 Deprecated arg.
 * @param null $deprecated2 Deprecated arg.
 * @param null $deprecated3 Deprecated arg.
 * @param null $deprecated4 Deprecated arg.
 * @param null $deprecated5 Deprecated arg.
 * @return string
 */
public function email_order_items_table( $args = array(), $deprecated1 = null, $deprecated2 = null, $deprecated3 = null, $deprecated4 = null, $deprecated5 = null ) {
    ob_start();

    if ( ! is_null( $deprecated1 ) || ! is_null( $deprecated2 ) || ! is_null( $deprecated3 ) || ! is_null( $deprecated4 ) || ! is_null( $deprecated5 ) ) {
        _deprecated_argument( __FUNCTION__, '2.5.0' );
    }

    $defaults = array(
        'show_sku'      => false,
        'show_image'    => false,
        'image_size'    => array( 32, 32 ),
        'plain_text'    => false,
        'sent_to_admin' => false
    );

    $args     = wp_parse_args( $args, $defaults );
    $template = $args['plain_text'] ? 'emails/plain/email-order-items.php' : 'emails/email-order-items.php';

    wc_get_template( $template, apply_filters( 'woocommerce_email_order_items_args', array(
        'order'               => $this,
        'items'               => $this->get_items(),
        'show_download_links' => $this->is_download_permitted() && ! $args['sent_to_admin'],
        'show_sku'            => $args['show_sku'],
        'show_purchase_note'  => $this->is_paid() && ! $args['sent_to_admin'],
        'show_image'          => $args['show_image'],
        'image_size'          => $args['image_size'],
        'plain_text'          => $args['plain_text'],
        'sent_to_admin'       => $args['sent_to_admin']
    ) ) );

    return apply_filters( 'woocommerce_email_order_items_table', ob_get_clean(), $this );
}

and that is the template:
    // file: woocommerce/templates/emails/email-order-items.php

<?php
/**
 * Email Order Items
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/emails/email-order-items.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you
 * (the theme developer) will need to copy the new files to your theme to
 * maintain compatibility. We try to do this as little as possible, but it does
 * happen. When this occurs the version of the template file will be bumped and
 * the readme will list any important changes.
 *
 * @see         https://docs.woocommerce.com/document/template-structure/
 * @author      WooThemes
 * @package     WooCommerce/Templates/Emails
 * @version     2.1.2
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

foreach ( $items as $item_id => $item ) :
    $_product     = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
    $item_meta    = new WC_Order_Item_Meta( $item, $_product );

    if ( apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
    ?>
    <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_order_item_class', 'order_item', $item, $order ) ); ?>">
        <?php

            // Show title/image etc
            if ( $show_image ) {
                echo apply_filters( 'woocommerce_order_item_thumbnail', '
get_image_id() ? current( wp_get_attachment_image_src( $_product->get_image_id(), 'thumbnail') ) : wc_placeholder_img_src() ) .'" alt="' . esc_attr__( 'Product Image', 'woocommerce' ) . '" height="' . esc_attr( $image_size[1] ) . '" width="' . esc_attr( $image_size[0] ) . '" style="vertical-align:middle; margin-right: 10px;" />
', $item );
            }

            // Product name
            echo apply_filters( 'woocommerce_order_item_name', $item['name'], $item, false );

            // SKU
            if ( $show_sku && is_object( $_product ) && $_product->get_sku() ) {
                echo ' (#' . $_product->get_sku() . ')';
            }

            // allow other plugins to add additional product information here
            do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order, $plain_text );

            // Variation
            if ( ! empty( $item_meta->meta ) ) {
                echo '
' . nl2br( $item_meta->display( true, true, '_', "\n" ) ) . '';
            }

            // File URLs
            if ( $show_download_links ) {
                $order->display_item_downloads( $item );
            }

            // allow other plugins to add additional product information here
            do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order, $plain_text );

        ?>
        <?php echo apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ); ?>
        <?php echo $order->get_formatted_line_subtotal( $item ); ?>

    <?php
}

if ( $show_purchase_note && is_object( $_product ) && ( $purchase_note = get_post_meta( $_product->id, '_purchase_note', true ) ) ) : ?>

        <?php echo wpautop( do_shortcode( wp_kses_post( $purchase_note ) ) ); ?>

<?php endif; ?>

I could replace the template as described in the comments BUT that would overwrite all emails to hide the price and I actually want to keep the price in all other emails that are not send through the plugin. I have no idea on how to make this conditional.
So here is my question: How can I hook that email_order_items_table() function to not output the price?
PS: How can I see what is inside $this->object or how can I output in a human readable form everything inside the $thisobject?

A: You can use either of this to see the object printed as an array in human readable form.
echo '
';print_r($this->object);exit;
echo '
';print_r($this);exit;

Or you may need to log the object into error log file like below
error_log(print_r($this->object, 1), true);

A: In woocommerce all templates can be override if you put it on your theme,
so:
woocommerce/templates/emails/email-order-items.php

can be override if you put it on:
wp-content/themes/{your theme}/woocomerce/{the template}

in this case
content/themes/{your theme}/woocommerce/emails/email-order-items.php

Then you can change the template, so it dont draw the price.
take out this line on the file that is on your themes directory. Be carefull some time you change somthing on the plugin directory and you will lose it on the next update.
<?php echo $order->get_formatted_line_subtotal( $item ); ?>

br


text:
Q: compodoc: command not found I installed the documentation tool "Compodoc" in my Angular application. First, I installed the tool globally and in my project
npm install -g @compodoc/compodoc
npm install --save-dev @compodoc/compodoc

I added the command to my package.json file in the "scripts" area with the following line
"compodoc": "./node_modules/.bin/compodoc -p src/tsconfig.app.json"

And it generated me the entire documentation files with this command :
npm run compodoc

Everything went good until I tried to run the command compodoc -s to see the documentation in my browser.
compodoc: command not found

A: Just run "./node_modules/.bin/compodoc -s"

A: In your package.json, for "compodoc" have the options you require and just run "npm run compodoc".
For Example:
"compodoc": "./node_modules/.bin/compodoc -p tsconfig-compodoc.json -d docs -n \"My Document Name\" --serve --port 3003 --theme postmark --hideGenerator --watch"
It should run. Hope it helped. Thanks:)

A: Adding this for Angular 9 users:
tell it to create the documentation elsewhere so that 'ng serve' doesn't get confused by the changes caused by the documentation folder if you are using the 'w' folder
Add this package. json then you can run 'npm run compodoc'.
Also, In Angular 9, now I see that I have to specify what folder to watch as well - '-w' means watch the source folder.
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"compodoc": "./node_modules/.bin/compodoc -p tsconfig.json -w ./src -s --output ../Path To where you want the documentation/documentation --silent"
},


text:
Q: jQuery target input tag with required attr I have a simple date section in my form. I have 5 select tags:

*

*1 for the Month - id&name attr ="userdobm"

*1 for the Year - id&name attr ="userdoby"

*1 for (29) Days - id&name attr ="userdobd29"

*1 for (30) Days - id&name attr ="userdobd30"

*1 for (31) Days - id&name attr ="userdobd31"

All of the 5 select tags have unique ID's
By default (29)Days and (30)Days are set on display:none without required attr and (31)Days is set on display:block with required attr.
When a user selects a Month e.g. February
(30)Days and (31)Days will be set to display:none without required attr and (29)Days is set on display:block with required attr.
Code for the above:
$("#userdobm").change(function() {
    var userdobmval = $("#userdobm").val();
    if(userdobmval == 4 || userdobmval == 6 || userdobmval == 9 || userdobmval == 11) {
        $("#userdobd30").css('display','block').val('').prop('required', true);
        $("#userdobd29,#userdobd31").css('display','none').val('').removeAttr('required');
    } else if (userdobmval == 2) {
        $("#userdobd29").css('display','block').val('').prop('required', true);
        $("#userdobd30,#userdobd31").css('display','none').val('').removeAttr('required');
    } else {
        $("#userdobd31").css('display','block').val('').prop('required', true);
        $("#userdobd29,#userdobd30").css('display','none').val('').removeAttr('required');
    }
});

My problem is. How do I get the value of the current Days select tag that has a required attr?

A: A better approach would be to conditionally load the number of days based on the year and month currently selected by the user, this would also remove the problem of having multiple required attributes to the select value for days (And should handle leap years).
$('#Month').change(function(){
    updateDays();
});

$('#Year').change(function(){
    updateDays();
});

function updateDays(){
    var year = $('#Year').val();
    var daysInMonth = daysInMonth($('#Month').val(), year);

    for(var i=0;i<=daysInMonth;i++){
        $('#Day').append($("<option></option>")
         .attr("value",i)
         .text(i));
    }

    function daysInMonth(month,year)
    {
       return new Date(year, month, 0).getDate();
    }
}

updateDays();

JS Fiddle

A: To immediately answer your question there are a few approaches you could do that ultimately hinge on determining the visibility. This is most easily done if you apply a class to each of the selects with a day. $('select.userdobd:visible').val() or $('select.visible').val() if you apply a class 'visible' instead of modifying the css directly in your month select's .change() method
Though, as has been suggested in the comments a more efficient method would be to just use one select and hide the options (especially if you're sending POST data to a server side script like php)
$("#userdobm").change(function() {
    var userdobmval = $("#userdobm").val();
    if(userdobmval == 4 || userdobmval == 6 || userdobmval == 9 || userdobmval == 11) {
        $("#userdobd").val('').find('option[value="30"]').show();
        $("#userdobd").val('').find('option[value="31"]').hide();
    } else if (userdobmval == 2) {
        $("#userdobd").val('').find('option[value="30"], option[value="31"]').hide();
    } else {
        $("#userdobd").val('').find('option[value="30"], option[value="31"]').show();
    }
});

Here's a fiddle of it in action
EDIT: Note that this does not account for leap years
EDIT: Also note that there are still more efficient ways of doing this kind of operation. Sparko mentioned a great way using JS's native Date() constructor!
Last but not least
jQuery has another project called ui. In the which they have a particularly useful datepicker widget. I would recommend at least checking it out ;) This would not only take care of handling all of this but allows for a nice display for the user to click to a date with a familiar interface.

A: The selector [attribute] will return any elements that have that attribute (regardless of whether a value is specified). So something like $('select[required]').val(); should return the value of an dropdown like <select required> ... </select>. Here's the jQuery docs for the attribute selector. Let me know if you have any questions :)
Better option
Instead of 3 dobd selects, just have one, and change the number of options in it dynamically.. The method below also adjusts for leap years :)
$("#userdobm, #userdoby").change(function() {
    var max = new Date($('#userdoby').val(), $('#userdobm').val(), 0).getDate();
    $('#userdobd').empty();
    for (var i=1; i<=max; i++)
    {
        $('#userdobd').append("<option>"+i+"</option>");
    }
});

A: DEMO: http://jsfiddle.net/abc123/ksJ8t/4/
This does what you want.
JS:
$('#userdobd').prop('disabled', true);

function SetDays() {
    if ($('#userdobm').val() !== undefined && $('#userdoby').val() !== undefined) {
        $('#userdobd').prop('disabled', false);
        var d = new Date($('#userdoby').val(), $('#userdobm').val(), 0);
        console.log(d.getDate() + "Year " + d.getFullYear() + " Month " + d.getMonth());
        var options = '';
        for (var i = 1; i <= d.getDate(); i++) {
            options = options + "<option value='" + i + "'>" + i + "</option>";
        }
        $('#userdobd').html(options);
    }
}

$("#userdobm, #userdoby").focus(function(){
  SetDays();
}).change(function() {
    SetDays();
});


text:
Q: Regex for text between a set of chars I have been trying to get a string between two other strings.  For example, The full string is;
"main.aspx?etc=2&id=c3331316-1b17-e811-a953-0022480042b3&Key=930349624&Window=true"

And I am trying to get the string between "id=" and "&";
"c3331316-1b17-e811-a953-0022480042b3"

The regex I have landed on is;
id=(.*?)&

My regex attempts are including the "id=" and the "&". So they are coming out like this;
"id=c3331316-1b17-e811-a953-0022480042b3&"

Any pointers would be greatly appreciated as from what I have read this should be working. The regex is being supplied by me and run through a third party software piece so I want to find out if I am wrong or the software is.  I'd imagine I am :-)

A: The * greedily takes the & until it finds the last one in the string.
Try this.
id=([^&]+)
As @revo pointed out this, this will match and return the entire id=... parameter. The ( ) captures the value portion into a separate matches value.  This is usually represented as an array or hash of some sort dependent on your programming language.
(?<=id=)[^&]+

Revo's modification will match and return the value of id without having to use capturing backreferences.
Both have the added benefit of not having to have a & at the end of the parameter. Meaning both of these urls will be matched.
"main.aspx?etc=2&id=c3331316-1b17-e811-a953-0022480042b3&Key=930349624&Window=true"
"main.aspx?etc=2&Key=930349624&Window=true&id=c3331316-1b17-e811-a953-0022480042b3"

A: You are using a matching group. Do not try to get the whole result, but only the grouped result.
Though, you can use lookahead and lookbehind groupings, like this :
(?<=id=)(.*?)(?=&)

Edit, if the id parameter is the last in the URL, the regex won't trigger. You can use this regular expression if you are unsure of its place within the URL :
(?<=(?:\?|&)id=)(.*?)(?=&|$)

A: [?&]id=(.*?)(?:&|$)

See the demo
What all other answers here fail to do is not match something in the form:
main.aspx?otherid=hek83749dbidne3

This regex will make sure that the id either appears directly after the ? or after an ampersand.

A: Try this :
(?<=id=)(.*?)(?=&)

This will match everythink between "id=" and "&"


text:
Q: Why what's wrong with this dict conversion of a lambda expression result object? Was feeling smug thinking that I had the best lambda expression in the universe cooked up to return all the relevant network information ever needed using python and netifaces
>>> list(map(lambda interface: (interface, dict(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses(interface) )))  , netifaces.interfaces()))

but I got this
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: cannot convert dictionary update sequence element #0 to a sequence

scaling it back a bit
>>>dict(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses("eth0")))

is where the problem is:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a  sequence

but so I can convert the filter object to a list
 >>> list(filter(lambda ifaddress: ifaddress in (netifaces.AF_INET, netifaces.AF_LINK), netifaces.ifaddresses("eth0")))
 [17, 2]

but, that's not what I want.  I want what it actually is:
>>> netifaces.ifaddresses("tun2")
{2: [{'addr': '64.73.0.0', 'netmask': '255.255.255.255', 'peer': '192.168.15.4'}]}
>>> type (netifaces.ifaddresses("eth0"))
<class 'dict'>

so what's mucking up my cast back back to dictionary?

A: When given a dictionary as input, filter will only iterate and return the keys from that dictionary.
>>> filter(lambda x: x > 1, {1:2, 3:4, 5:6})
[3, 5]

Thus you are feeding just the sequence of filtered keys into the new dict, not the key-value-pairs. You could fix it like this: Note the call to items() and how the inner lambda is getting a tuple as input.
list(map(lambda interface: (interface, dict(filter(lambda tuple: tuple[0] in (netifaces.AF_INET, netifaces.AF_LINK),
                                                   netifaces.ifaddresses(interface).items()))),
         netifaces.interfaces()))

Now that's not very pretty... I suggest changing your code to a nested list- and dictionary-comprehension:
[(interface, {ifaddress: value
          for (ifaddress, value) in netifaces.ifaddresses(interface).items()
          if ifaddress in (netifaces.AF_INET, netifaces.AF_LINK)})
 for interface in netifaces.interfaces()]


text:
Q: Is there a way to improve chkdsk performance in HDD? I have a system which has 8 GB of RAM. While running chkdsk it takes quite a bit of time to complete. This is for external HDD. I know there are two options -

*

*Have an SSD, that should improve performance but with a weak/strong possibility of lesser read and write cycles at least on the lower end of the SSD range.

*Get more memory. This should improve the performance but I don't know how much as chkdsk appears to be a single threaded app which works serially. The only option might be have a large block size but don't know if it's possible, at least in Windows 10.

*There is also possibility of defragging the filesystem which should help chkdsk as well but dunno how good or bad this will be?
The reason to improve chkdsk is mani-fold. I know if it starts happening too often, its probable that the HDD is prone to failure more .
The performance I am seeking for is more for external HDD's than internal HDD's at this moment in time.
The options I use are chkdsk g: /f /x /r on a Windows 10 box. The external HDD is a Seagate Slim BUP 2 TB HDD with support for only USB 2.0.
Currently, it takes anywhere between 7-10 hours or even more to check the whole HDD. I dunno if it should take that much time.

A: It's about /r. This is what it means:

/r  Locates bad sectors and recovers readable information.

(source)
With this option chkdsk reads (tries to read) the entire space assigned to the filesystem (or the entire partition, I'm not sure, usually there's no difference). It's somewhat similar to badblocks in Linux. This takes time. Yes, it takes about 10 hours to read 2TB via USB 2.0 (which maximum speed is 60 MB/s; 2TB HDD is 2000000 MB, do the math).
This option is useful when you suspect there may be bad sectors on the device. They are a hardware issue. If you run chkdsk only to fix/check filesystem inconsistency (i.e. invalid data on a healthy hardware) then you don't need /r.
However if you're experiencing bad sectors (what does S.M.A.R.T. say?) and you do need /r so often then your HDD is probably dying.
To make chkdsk take less time run it without /r or connect the disk via an interface that provides more bandwidth (if you can).
Switching to SSD connected via the same USB 2.0 bottleneck will speed things up only because the SSD will probably be smaller. More RAM won't help you at all.


text:
Q: $\sum E_{x} |V_k - V_{k-1}|I\{\tau_C \ge k\} = \sum E_x[|E[(V_k - V_{k-1})|\mathscr{F}_{k-1}]I\{\tau_C \ge k\}|]$ for a submartingale Markov chain. Let $V$ be a non-negative function that satisfies
$$E_x V(y) - V(x) \ge 0, \; x\in C^c.$$
Let $\tau_C := \min\{n\ge 1: \Phi_n \in C\}$, where $\Phi_n$ is a Markov chain. Let $V_k = V(\Phi_k)$. In this case, how do we get the following equality?
$$\sum_{k=1}^\infty E_{x} |V_k - V_{k-1}|\mathbb{I}\{\tau_C \ge k\} = \sum_{k=1}^\infty E_x[|E[(V_k - V_{k-1})|\mathscr{F}_{k-1}]\mathbb{I}\{\tau_C \ge k\}|].$$
I can see that on $\{\tau_C \ge k\}$, $E[V_k - V_{k-1}|\mathscr{F}_{k-1}] \ge 0$ and  $\{\tau_C \ge k\}$ is $\mathscr{F}_{k-1}$- measurable, so we can take it out, but then the RHS is equal to $\sum_{k=1}^\infty E_x[E[(V_k - V_{k-1})|\mathscr{F}_{k-1}]\mathbb{I}\{\tau_C \ge k\}]$. I can't see how this is equal to $\sum_{k=1}^\infty E_{x} |V_k - V_{k-1}|\mathbb{I}\{\tau_C \ge k\}$. I would greatly appreciate any help.


text:
Q: Почему не грузятся Яндекс карты на Android, библиотека MapKit 3.0? Использую бесплатную версию библиотеки MapKit (3.0) для Android, в процессе подключения библиотеки возникла проблема отображения самой карты
После успешного подключения библиотеки с ключем:
MapKitFactory.setApiKey("Ключ полученный через личный кабинет разработчика яндекса");

В процессе запуска приложения карты не загружаются

Листинг кода:
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.yandex.mapkit.Animation;
import com.yandex.mapkit.MapKitFactory;
import com.yandex.mapkit.geometry.Point;
import com.yandex.mapkit.map.CameraPosition;
import com.yandex.mapkit.mapview.MapView;

public class MapActivity extends AppCompatActivity {

    private MapView mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MapKitFactory.setApiKey("Здесь мой ключ из кабинета разработчика яндекс");
        MapKitFactory.initialize(this);

        // Укажите имя activity вместо map.
        setContentView(R.layout.map_activity);
        mapView = (MapView)findViewById(R.id.mapview);
        mapView.getMap().move(
                new CameraPosition(new Point(55.751574, 37.573856), 11.0f, 0.0f, 0.0f),
                new Animation(Animation.Type.SMOOTH, 0),
                null);
    }

    @Override
    protected void onStop() {
        mapView.onStop();
        MapKitFactory.getInstance().onStop();
        super.onStop();
    }

    @Override
    protected void onStart() {
        super.onStart();
        MapKitFactory.getInstance().onStart();
        mapView.onStart();
    }
}

В лог при этом пишется следующее сообщение :

E/zygote: Failed sending reply to debugger: Broken pipe E/yandex.maps:
yandex::maps::runtime::network::common::DnsCache::resetLocalResolver:
Invalid argumentfailed to parce address from web.adfox.ru.
E/yandex.maps:
yandex::maps::runtime::network::common::DnsCache::resetLocalResolver:
Invalid argumentfailed to parce address from web.adfox.ru.

A: Обратился в тех поддержку яндекса, прислали письмо с текстом, что активировали мой ApiKey на стороне сервера, проблема ушла.

A: После получения ключа может пройти какое-то время, прежде чем он активируется и карты начнут отображаться. В моем случае все заработало примерно через час


text:
Q: Rice formula on time series I have a time-series which is a mean-reverting spread with a long-run mean (equilibrium) close to zero. I am looking to use the Rice formula to get the level crossings rate, e.g. how many times the spread crosses an arbitrary value, say 2. However, I have never performed integration in Python which means I cannot continue with this problem. Here is a picture of the description of the Rice formula
Does anyone have a way of programming this?
I have this but I think this is very wrong:
import numpy as np
import pandas as pd
from datetime import datetime
import pandas_datareader.data as pdr
import seaborn as sns
import statsmodels.api as sm

from statsmodels.regression.rolling import RollingOLS

sns.set_style("darkgrid")

stocks = ["DHR", "TMO"]
start, end = datetime(2000, 1, 1), datetime.now()
df = pdr.DataReader(stocks, "yahoo", start, end)["Close"]
df.dropna(inplace=True)

window = 40  # 12
exog = sm.add_constant(df.DHR)
rolling_ols = RollingOLS(endog=df.TMO, exog=exog, window=window, min_nobs=12).fit()
beta = - np.array(rolling_ols.params.iloc[:, 1].dropna())  # rolling beta
df = df.iloc[window-1:, :]

df["Spread"] = np.log(df.TMO) + beta * np.log(df.DHR)

from scipy.integrate import quad, simps

integrand = np.abs(np.gradient(df.Spread)) * (2 * np.gradient(df.Spread)[0]) * np.gradient(np.gradient(df.Spread))
df.reset_index(inplace=True)
rice = simps(y=integrand, x=df.index)
print(rice)

rice = lambda x: np.abs(np.gradient(x)) * (2 * np.gradient(x)[0]) * np.gradient(np.gradient(x))


text:
Q: How to call methods on a variable in SQL Server I saw the below syntax in a training video and I was wondering what this is called and which methods can we use on a variable?
 DECLARE @text VARCHAR(max);
 SET @text = REPLICATE(CAST('asdfasdf' as varchar(max)),8000);
 SET @text.write('zzzzzzzz',0,8);
 SELECT @text

the value stored in the variable is
'zzzzzzzzasdfasdf...'

A: The update.write syntax is not really a method. It is a TSQL syntax for updating large data types like nvarchar(max).
The official UPDATE documentation describes how to use .WRITE.
  SET
        { column_name = { expression | DEFAULT | NULL }
          | { udt_column_name.{ { property_name = expression
                                | field_name = expression }
                                | method_name ( argument [ ,...n ] )
                              }
          }
          | column_name { .WRITE ( expression , @Offset , @Length ) }

.WRITE (expression,@Offset,@Length) Specifies that a section of the
value of column_name is to be modified. expression replaces @Length
units starting from @Offset of column_name. Only columns of
varchar(max), nvarchar(max), or varbinary(max) can be specified with
this clause. column_name cannot be NULL and cannot be qualified with a
table name or table alias.
expression is the value that is copied to column_name. expression must
evaluate to or be able to be implicitly cast to the column_name type.
If expression is set to NULL, @Length is ignored, and the value in
column_name is truncated at the specified @Offset.
@Offset is the starting point in the value stored in column_name at
which expression is written. @Offset is a zero-based ordinal byte
position, is bigint, and cannot be a negative number. If @Offset is
NULL, the update operation appends expression at the end of the
existing column_name value and @Length is ignored. If @Offset is
greater than the byte length of the column_name value, the Database
Engine returns an error. If @Offset plus @Length exceeds the end of
the underlying value in the column, the deletion occurs up to the last
character of the value.
@Length is the length of the section in the column, starting from
@Offset, that is replaced by expression. @Length is bigint and cannot
be a negative number. If @Length is NULL, the update operation removes
all data from @Offset to the end of the column_name value.

See also Updating Large Data Types and the examples provided for updating large data types.

A: It's not a method, though it sure looks like it. Unlike for example XML methods, which you can use in a SELECT, this is a mutator. It's available on (n)varchar and varbinary data types with max length  specified, and is used to modify the stored values efficiently.
There's not much information about them out there, I only found this blog post.


text:
Q: Trigger ON BEFORE error I have two tables and would like to create a trigger to delete on ticket_reply when a ticket is deleted:
ticket:
+-------------+-----------------+------+-----+---------+----------------+
| Field       | Type            | Null | Key | Default | Extra          |
+-------------+-----------------+------+-----+---------+----------------+
| id          | int(8) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id     | int(8) unsigned | NO   | MUL | NULL    |                |
| status      | varchar(6)      | NO   |     | opened  |                |
| subject     | varchar(100)    | NO   | MUL | NULL    |                |
| message     | text            | NO   |     | NULL    |                |
+-------------+-----------------+------+-----+---------+----------------+

And ticket_reply:
+-----------+-----------------+------+-----+---------+----------------+
| Field     | Type            | Null | Key | Default | Extra          |
+-----------+-----------------+------+-----+---------+----------------+
| id        | int(8) unsigned | NO   | PRI | NULL    | auto_increment |
| user_id   | int(8) unsigned | NO   |     | NULL    |                |
| ticket_id | int(8) unsigned | NO   | MUL | NULL    |                |
| message   | text            | NO   |     | NULL    |                |
+-----------+-----------------+------+-----+---------+----------------+

My trigger:
CREATE TRIGGER `ticket_delete` BEFORE DELETE ON ticket
FOR EACH ROW
BEGIN
DELETE FROM ticket_reply
    WHERE ticket_reply.ticket_id = ticket.id;
END

I get the error message: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 5
Why?
Thanks.

A: Either use delimiters, or skip BEGIN / END :
DELIMITER $
CREATE TRIGGER `ticket_delete` BEFORE DELETE ON ticket
FOR EACH ROW
BEGIN
DELETE FROM ticket_reply
    WHERE ticket_reply.ticket_id = ticket.id;
END $
DELIMITER ;

or
CREATE TRIGGER `ticket_delete` BEFORE DELETE ON ticket
FOR EACH ROW
DELETE FROM ticket_reply
    WHERE ticket_reply.ticket_id = ticket.id;

It will make the syntax error go away; but your trigger is wrong, in fact it should be
CREATE TRIGGER `ticket_delete` BEFORE DELETE ON ticket
FOR EACH ROW
DELETE FROM ticket_reply
    WHERE ticket_reply.ticket_id = OLD.id;

(notice OLD.id instead of ticket.id).


text:
Q: Vue.js using POST error(Sysntax but not find out) Thank you for reading this question.
I got a syntax error, but I can't find where.
I am using Vue.js & bootstrap, I am working on shopping cart functionality. In order for endpoints to work you need to pass a special authentication header:
Authorization: kazuhisa.noguchi.ghsd75@gmail.com
import Vue from 'vue'
import App from './App.vue'
import BootstrapVue from 'bootstrap-vue'
import VueRouter from 'vue-router'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import MainPage from './components/MainPage.vue'
import HelpPage from './components/HelpPage.vue'
import ProductPage from './components/ProductPage.vue'
import CategoryPage from './components/CategoryPage.vue'

Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [{
      path: '/',
      component: MainPage
    },
    {
      path: '/help',
      component: HelpPage
    },
    {
      path: '/products/:productId',
      component: ProductPage
    },
    {
      path: '/categories/:categoryAlias',
      component: CategoryPage
    }
  ],
  mode: 'history'
})

axios.defaults.headers.common['Authorization'] = 'azuhisa.noguchi.ghsd75@gmail.com';

axios.post("https://euas.person.ee/user/carts/").then(
  response => {
    new Vue({
      render: h => h(App),
      router: router,
      data: {
        cart: response.data,
        saveCard() {
          axios.put("https://euas.person.ee/user/carts/" +
            this.cart.id, this.cart)
        }
      }
    }).$mount('#app')
  }
};

All my best,


text:
Q: Почему не срабатывает break?  public static void game(int random, int number) throws IOException {

            while (number != 0 && number !=random) {

            {
                if (number == 0 ) {break;}
                else {

                    if (number > random) System.out.println("Число меньше");
                    if (number < random) System.out.println("Число больше");

                    game(random, enterNumber());
                }
            }

        }

        }
    }

A: if (number == 0 ) {break;}

не имеет смыла, так как
 while (number != 0)

цикл while допускает number который не равен нулю, то есть number не может содержать ноль


text:
Q: How to access menu bar with pywinauto without using mouse click methods? I need my program to work on RDP session without focus.
All three methods are not working via minimized RPD session started by a Task Scheduler
app['program'].menu_select('Tools -> Settings...')

or
app['program']['Tools'].select()     or   app['program']['Tools'].click_input()
app['program']['Settings...'].select()  or  app['program']['Tools'].click_input()

After I start my program manually and check the checkbox in menu myself the rest of the program works fine via Task Scheduler through app.connect method.
Is there another method to access this said menu without using a mouse?

A: All the recipes are collected here: Remote Execution Guide.


text:
Q: Raphaeljs Click Event on image not working in IE9 In the following piece of code, the first click event fires, but the rest do not - in IE 9.  It works fine in Chrome and Firefox (and evidently IE 8 - although I have not tested it)
$(document).ready(function () {
    var d = paper.image("/Content/images/male.png", 100, 100, 32, 32);
    d.click(function (event) {
        alert(this.node);
    });

    $.each(hierarchy.children, function (index, value) {
        DrawNode(paper, value);
    });
})

function DrawNode(paper, currentPerson) {
     var currentNode = paper.image("/Content/images/male.png", currentPerson.X, currentPerson.Y, 32, 32).attr({ stroke: "none", fill: "none" });
     currentNode.click(function (event) {
         alert(this.node);
      });
    }

In IE9, clicking on the root node shows [object SVGImageElement] - the other nodes the event doesn't fire.  In the other browsers, you get the same (SVGImageElement) for all the nodes

A: This is a temporary work around for anyone who is looking.  You can put a square, circle or any other vector behind your image and bind the events to that.
In IE9 it works by clicking on the shape behind the image - on all other browsers, the image event fires.


text:
Q: TableView and Fragment to edit Details with tornadofx I use kotlinx.serialization for my models.
I'd like the idea of them to not depend on JavaFX, so they do not expose properties.
Given a model, I want a tableview for a quick representation of a list of instances, and additionally a more detailed Fragment as an editor.
consider the following model:
@Serializable
data class Person(
        var name: String,
        var firstname: String,
        var complex: Stuff)

the view containing the tableview contains
private val personlist = mutableListOf<Person>().observable()

with a tableview that opens an instance of PersonEditor for the selected row when Enter is pressed:
tableview(personlist) {
    column("name", Person::name)
    column("first name", Person::firstname)

    setOnKeyPressed { ev ->
        selectedItem?.apply {
            when (ev.code) {
                KeyCode.ENTER -> PersonEditor(this).openModal()
            }
        }
    }
}

I followed this gitbook section (but do not want the modelview to be rebound on selection of another row within the tableview)
The editor looks about like this:
class PersonEditor(person: Person) : ItemFragment<Person>() {
    val model: Model = Model()

    override val root = form {
        fieldset("Personal information") {
            field("Name") {
                textfield(model.name)
            }
            field("Vorname") {
                textfield(model.firstname)
            }
        }
        fieldset("complex stuff") {
            //... more complex stuff here
        }
        fieldset {
            button("Save") {
                enableWhen(model.dirty)
                action { model.commit() }
            }
            button("Reset") { action { model.rollback() } }
        }
    }

    class Model : ItemViewModel<Person>() {
        val name = bind(Person::name)
        val firstname = bind(Person::firstname)
        //... complex stuff
    }

    init {
        itemProperty.value = mieter
        model.bindTo(this)
    }
}

When I save the edited values in the detail view, the tableview is not updated.
Whats the best practize to solve this?
Also I'm unsure, if what I'm doing can be considered good practize, so i'd be happy for some advice on that too.

A: The best practice in a JavaFX application is to use observable properties. Not doing so is an uphill battle. You can keep your lean domain objects, but add a JavaFX/TornadoFX specific version with observable properties. This object can know how to copy data to/from your "lean" domain objects.
With this approach, especially in combination with ItemViewModel wrappers will make sure that your data is always updated.
The setOnKeyPressed code you posted can be changed to:
setOnUserSelect {
    PersonEditor(it).openModal()
}

Notice though, that you are not supposed to instantiate Views and Fragments directly, as doing so skips certain steps in the TornadoFX life cycle. Instead you should pass the person as a parameter, or create a new scope and inject a PersonModel into that scope before opening the editor in that scope:
setOnUserSelect {
    find<PersonEditor>(Scope(PersonEditor(it)))
}


text:
Q: Looking to represent a fraction template in HTML/JS with input field I have an input field (type text) and a button that generates a general fraction template. Right now it looks similar to this (X/Y). I have been trying to make this look nicer by using .sup() and .sub() methods, but unfortunately I have had no success in getting the final form to look as follows:
(X/Y)
any tips to help make this more aesthetically pleasing?

A: You say in your question you want to format the text inside a <input> field. This is not possible, exactly: the contents of an <input> are plain text and can only have a single uniform style. Here are some alternatives:

*

*Simple: Use two <input>s:

(<input>/<input>)

This will always require the user to tab between the two fields rather than typing a slash, unless you add code to adjust it (which is very error-prone).

*Advanced: Use contenteditable to allow the user to edit a region including  and  elements. This requires additional code to extract the results and deal with the user e.g. deleting the subscripted text, because you're basically allowing the user to edit the HTML in this area (and they can do wacky things like pasting in styled text/HTML from elsewhere).

(a/b)

*Wacky: Use superscripted/subscripted characters:

(<input value="ⁿ/ₓ">)

The problem with this method is that there are very few letters available like this, though there are digits; e.g. ¹²/₃₄.

*Probably won't work: Use the fraction slash character, U+2044 "⁄", in the division template.
<input value="1⁄2">

Depending on the OS, browser, font, and characters present in the template, using this character may cause the numbers to the left and right to be arranged diagonally or vertically as a fraction. Here's some samples to see if it works for you: 1⁄2 1⁄3 3⁄4.

A: Maybe something simple like ...
(X/Y)

Then, in CSS ...
.numer {
  position: relative;
  top: -0.5em;
  left: 0.2em;
}
.denom {
  position: relative;
  top: 0.5em;
  left: -0.2em;
}

You might have to make some adjustments for the parens ...
PS. I didn't test these values, might also need some adjustment.
UPDATE 1:
See jsFiddle
UPDATE 2:
Assuming jQuery here ...
function frac_display(ob, x, y) {
  $(ob).html([
    "(",
    x,
    "",
    "/",
    "",
    y,
    ")"
  ].join("");
}

This function will take a unique element identifier (class or id identifier as .fraction1 or #frac_234), an x and y value and places the code inside the element.


text:
Q: Проблемы с вертикальной линией HTML Сегодня сделал на сайте вертикальную линию через
, но не могу изменить высоту. Как мне это сделать?
Код:
CSS:
.decoration {
   border-left:1px solid black;
   padding-left:10px;
    display:inline;
    width:4px;
    height: 100%;
    margin-top: 20px;
    margin-right: 20px
}

HTML

A: У тебя высота задана как % от родителя.
Либо меняй высоту родителя, либо используй px, vh .....