Multiple text search in Qradar AQL

Question: how can i search multiple text in Qradar AQL? the IN function works only for IP address. I want to search like below, any alternate options?

WHERE URL NOT ILIKE IN ('%.com%', '%.net%')
Answer: You can use follow syntax:
<code>select URL FROM events WHERE URL IS NOT NULL and  URL NOT ILIKE ENUMERATION('%.com%')
</code>
For more information please refer following guide:
https://www.ibm.com/support/knowledgecenter/SS42VS_7.3.2/com.ibm.qradar.doc/b_qradar_aql.pdf

Multiple text search in Qradar AQL


CASE expressions using values from different rows

Question: I have below table
WITH TMP AS (
SELECT 'XX' AS AGG, 50 AS VALUE, 0 AS MONTH
UNION ALL
SELECT 'XX' AS AGG, 150 AS VALUE, 1 AS MONTH
UNION ALL
SELECT 'XX' AS AGG, 300 AS VALUE, 2 AS MONTH
UNION ALL
SELECT 'YY' AS AGG, 25 AS VALUE, 0 AS MONTH
UNION ALL
SELECT 'YY' AS AGG, 50 AS VALUE, 1 AS MONTH
UNION ALL
SELECT 'YY' AS AGG, 75 AS VALUE, 2 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG, 500 AS VALUE, 0 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG, 600 AS VALUE, 1 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG, 700 AS VALUE, 2 AS MONTH
)
-- CASE WHEN VALUE OF 'XX' > 0 THEN VALUE OF 'ZZ' ELSE 0 END
SELECT
*
FROM TMP
WHERE 1 = 1

I need to apply following business logic to it always considering the month.

CASE WHEN VALUE OF 'XX' > 0 THEN VALUE OF 'ZZ' ELSE 0 END

This logic should be mapped into a new table. The result should look like the table below.
I would like to avoid joins to the same table. Is this somehow possible using window functions or something similar? The idea is to build several case when statement as the one above within the same sql statement.

IE1
MONTH

500
00

600
01

700
02
Answer: Pivot (conditionally aggregate) your data, and then return the value you need based on your expression:
WITH TMP AS
    (SELECT 'XX' AS AGG,
            50 AS VALUE,
            0 AS MONTH
     UNION ALL
     SELECT 'XX' AS AGG,
            150 AS VALUE,
            1 AS MONTH
     UNION ALL
     SELECT 'XX' AS AGG,
            300 AS VALUE,
            2 AS MONTH
     UNION ALL
     SELECT 'YY' AS AGG,
            25 AS VALUE,
            0 AS MONTH
     UNION ALL
     SELECT 'YY' AS AGG,
            50 AS VALUE,
            1 AS MONTH
     UNION ALL
     SELECT 'YY' AS AGG,
            75 AS VALUE,
            2 AS MONTH
     UNION ALL
     SELECT 'ZZ' AS AGG,
            500 AS VALUE,
            0 AS MONTH
     UNION ALL
     SELECT 'ZZ' AS AGG,
            600 AS VALUE,
            1 AS MONTH
     UNION ALL
     SELECT 'ZZ' AS AGG,
            700 AS VALUE,
            2 AS MONTH),
--Solution
/*WITH */Pvt AS(
    SELECT Month,
           MAX(CASE Agg WHEN 'XX' THEN VALUE END) AS XX,
           --MAX(CASE Agg WHEN 'YY' THEN VALUE END) AS YY,--Not needed hence commented out
           MAX(CASE Agg WHEN 'ZZ' THEN VALUE END) AS ZZ
    FROM TMP
    GROUP BY MONTH)
SELECT CASE WHEN XX > 0 THEN ZZ ELSE 0 END AS IE1,
       MONTH
FROM Pvt;

Comment: Many thanks for you answer. Since we need to make this thing configurable and generic we need to avoid hard coded columns as you did with the pivot. Is there any other way to make this work...
Comment: You can parametrise the above if you need to, if that's what you're asking. Though sounds like you're moving the goal posts, which means you should be asking a *new* question.


WCF serialization gotcha - Different behaviour Azure Web Role VS IIS

Question: I've run into an interesting situation in my WCF webservice where I am experiencing different behaviour between my locally deployed application running in IIS and my deployed Web Role running on Azure.
I have a class defined as such
[DataContract]
public class DefaultClassView : BaseView
{
    [DataMember]
    public Guid ClassID { get; set; }

    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public Guid SchoolID { get; set; }

    [DataMember]
    public string SchoolName { get; set; }

    [DataMember]
    public IEnumerable<Guid> YearLevelIDs { get; set; }

    [DataMember]
    public IEnumerable<string> YearLevelNameList { get; set; }

    [DataMember]
    public IEnumerable<Guid> SubjectIDs { get; set; }

    [DataMember]
    public IEnumerable<string> SubjectNameList { get; set; }
}

The class is then populated using the following code
public static DefaultClassView ConvertToView(this Class entity)
{
    return new DefaultClassView()
    {
        ClassID = entity.ClassID,
        Name = entity.Name,
        YearLevelIDs = entity.Students.Select(o => o.YearLevelID).Distinct(),
        YearLevelNameList = entity.Students.Select(o => o.YearLevel.Name).Distinct(),
        SchoolID = entity.SchoolID,
        SchoolName = entity.School.Name,
        SubjectIDs = entity.Subjects.Select(o => o.SubjectID),
        SubjectNameList = entity.Subjects.Select(o => o.Name)
    };
}

This code has worked perfectly (while deployed in my local IIS instance) until I deployed it on Azure, at which point I began receiving the following error when the service was activated.
Type System.Linq.Enumerable+WhereSelectEnumerableIterator`2[Model.Subject,System.Guid]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.

Upon removal of the LINQ queries I was able to successfully fix this issue but what I would like to understand is why this behaviour is so different between the two platforms and if infact this behaviour is by design, I'd also like to know if there are any other similar "Gotchas" that I need to be aware of related to deploying WCF services on Azure?
Answer: After every LINQ query, call ToList(), First(), or FirstOrDefault() so you are not serializing LINQ types, but the types intended.
Comment: Sorry I guess I wasn't clear, I understand that and in-fact that is exactly how I resolved the problem. What I don't understand is why this behaviour is different between the two platforms.
Comment: It is due to accessing the service locally vs a remote server.


Loss and CER increases when training a fine-tuned TrOCR on custom dataset

Question: I want to train the TrOCR on my custom dataset of receipts. Since we are to use the OCR for receipts we chose the "printed" fine-tuned model. We use a dataset of 5000 bounding boxes where each contains a word. However we experience that all metrics (cer, precision) and loss worsens for each epoch we run. We can't figure out why the model performs more poorly for each epoch.
Processor, model and optimizer is shown below:
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-printed")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-printed")
optimizer = optim.AdamW(model.parameters(), lr=5e-5)

Training method:
for epoch in range(self.epochs):
    self.model.train()
    train_loss = 0.0
    for batch in tqdm(self.train_dataloader):
        for k, v in batch.items():
            batch[k] = v.to(self.device)
        outputs = self.model(**batch)
        loss = outputs.loss
        loss.backward()
        self.optimizer.step()
        self.optimizer.zero_grad()
        train_loss += loss.item()

Does anyone know what we might be doing wrong?
When evaluating the model out-of-the-box, it performs well but we wish to continue training on our receipts to hopefully improve the model.
Comment: @greybeard will do, first time asking question here :)
Answer: you have chosen the already fine tuned model. "microsoft/trocr-base-printed" is already fine tuned on SROIE dataset. So there is no point of fine tuning already fine tuned model. Instead choose only pre trained model like trocr-base-stage1 or trocr-small-stage1.


Behavior of a pointer to an element of `slice` after the `slice` had been appended to

Question: I am wondering what is the behavior of a pointer to an element of slice after the slice had been appended to, for example:
package main

import "fmt"

func main() {
    my_slice := []int {3}

    silly_ptr := &my_slice[0]
    // Do we know that silly_ptr points to value equal 3
    // all the time? (If we don't explicitly change it).

    fmt.Printf("%p\n", silly_ptr)
    fmt.Println(*silly_ptr)

    for i := 0; i < 10; i++ {
        my_slice = append(my_slice, i)
    }

    silly_ptr_2 := &my_slice[0]

    fmt.Printf("%p\n", silly_ptr_2)
    fmt.Println(*silly_ptr_2)
}

Produces: (no surprises)
0xc20800a200
3
0xc20805a000
3

I know that when appending to dynamic array, at certain points we have repopulate the entire array, and therefore memory address of the original array elements is not reliable. To the best of my knowledge similar code is valid in c++, but silly_ptr could be pointing to anything. rust does not allow mutating a vector if it is being borrowed, so the above logic would not compile.
But what about Go? I know that by escape analysis it is valid to return a pointer to a local variable, the variable would be just created on the heap for you. My intuition tells me that the same logic applies in the above case. The memory location where silly_ptr is pointing to will not be repopulated, and hence will always store 3 (if we don't explictly change it). Is this right?
Answer: No, it will not always store 3.
Go has memory management. As long as there is an active pointer to an underlying array for a slice, the underlying array is pinned, it will not be garbage collected. If you have a pointer to an element of an underlying array, you can change the value of the element. For example,
package main

import (
    "fmt"
)

func pin() *int {
    s := []int{3}
    fmt.Println(&s[0])
    a := &s[0]
    s = append(s, 7)
    fmt.Println(&s[0])
    return a
}

func main() {
    a := pin()
    fmt.Println(a, *a)
    *a = 42
    fmt.Println(a, *a)
}

Output:
0xc82000a340
0xc82000a360
0xc82000a340 3
0xc82000a340 42

A slice descriptor contains a pointer to an underlying array so you can see something similar with a slice. For example,
package main

import (
    "fmt"
)

func pin() []int {
    s := []int{3}
    fmt.Println(&s[0])
    d := s
    s = append(s, 7)
    fmt.Println(&s[0])
    return d
}

func main() {
    d := pin()
    fmt.Println(&d[0], d)
    d[0] = 42
    fmt.Println(&d[0], d)
}

Output:
0xc82000a340
0xc82000a360
0xc82000a340 [3]
0xc82000a340 [42]

Comment: I should've been more clear, I don't want to consider a case where we explicitly change the value where the pointer points to. But you say: "As long as there is an active pointer to an underlying array for a slice, the underlying array is pinned, it will not be garbage collected." This seems to answer my question: `silly_ptr` will always point to value equal 3, unless we explicitly change that value, right? Do you know of any good resources on the topic?
Comment: @Akavall: My answer showed that you can safely use the pointer to both read and write the element value. The text for the Go garbage collection project is: The Garbage Collection Handbook: The Art of Automatic Memory Management (Chapman & Hall/CRC Applied Algorithms and Data Structures series) R. Jones, A. Hosking, E. Moss.


Joint distribution by independent distributions

Question: We have $N$ independent discrete finite random variables (RVs) $X_1,\dots,X_i,\dots,X_N$ where RV $X_i$ has $M_i$ finite number of elements. We are free to choose any distribution $f_i$ for RV $X_i$ $\forall i=\{1,\dots,N\}$. Then consider the product set $Y = X_1\times\dots\times X_i\times\dots\times X_N$ and say we are interested in a particular distribution $f_Y$, which is in the set of all possible distributions on $Y$. Note $f_Y$ is not the product of $f_i$s.
How close can we come to $f_Y$ by manipulating the independent distributions $f_i$ $\forall i=\{1,\dots,N\}$ ? Which I believe (not sure) is same as asking how close is $\prod_i^Nf_i$ to $f_Y$?
There is a set of real numbers $\boldsymbol{a}=\{a(y)\}_{y\in Y}$. The objective is to make the expectation of the set $\boldsymbol{a}$ over $f_i$s as close as possible to the expectation of  $\boldsymbol{a}$ over $f_Y$.
I tried writing an optimization problem to minimize $\mid \sum_{y\in Y}[\prod_i^Nf_i(y)-f_Y(y)]a(y)\mid$, but it is non convex. And I am not sure if this is the optimization problem I should solve.
What does it mean to be "close" when we have two distributions?
Note that just expectations being close is not sufficient, the probability $\prod_i^Nf_i(y)$ has to be close to the true probability $f_Y(y)$ $\forall y \in Y$.
The question Distance between the product of marginal distributions and the joint distribution is bit similar but in there marginals come from the joint but in my question no marginals are compared.
Would be very grateful for any clue. Thanks.
PS. Not homework. Part of research work.
Answer: (This is discussion rather than answer)
Measures of distribution distance do exist - Kullback-Leibler divergence (or "relative entropy") and Hellinger distance are just two that come immediately to mind.
But from what you write, you seek to minimize the distance between two expected values - the "true" expected value, that is taken with respect to the true joint probability mass function $p(Y)$ of non-independent random variables, and some approximation of it, which uses a joint probability mass function $q(Y)$ which assumes independence, something like
$$d = \left|E_p\left[a(Y)\right] - E_q\left[a(Y)\right]\right| = \left|\sum_{S_Y}a(y)p(y) - \sum_{S_Y}a(y)q(y) \right|$$
or square or ..., where the $y$ is an $N$-dimensional vector and sums are to be understood as appropriately multiple.
It may seem that your problem falls into the field of "density estimation", but it doesn't: density estimation methods start with a sample and try to estimate from this sample the density that best describes it. Your problem on the other hand does not include a sample of realizations of the random variables involved. It's an abstract theoretical problem. Perhaps this is why you phrase it in mathematical rather than in statistical terms.
For example you write about "manipulation of the individual densities". This could mean anything, not just the use of a joint distribution of independent variables (=product of individual densities) -it could mean any  combination of the individual densities (a weighted sum, whatever), viewed as a mathematical approximation of the true joint distribution -and not as a stochastic estimation (this answer of mine deals to some degree with the differences between the two although in another context).
So it appears that there are two important aspects that perhaps need distinguishing and deciding upon: First, are you after "minimizing distance from true distribution" or "minimizing estimation error of true expected value"? Two, are you going to attempt it in a mathematical approximation framework (where anything goes), or in a statistical framework, where your approximation function should be a proper density?
I hope these comments are useful to you.
ADDENDUM (following discussion with the OP in comments).
it would be interesting to apply a measure of "distribution distance" to the expected value. Assume you are using the Hellinger distance. So, you choose $q(y)$ so that
$$q(y): H(a(y)p(y),a(y)q(y)) = \frac {1}{\sqrt 2} \left(\sum_i\left[\sqrt {a(y_i)p(y_i)}-\sqrt {a(y_i)q(y_i)}\right]^2\right)^\frac 12 =\min$$
$$\Rightarrow  \frac {1}{\sqrt 2} \left(\sum_ia(y_i)\left[\sqrt {p(y_i)}-\sqrt {q(y_i)}\right]^2\right)^\frac 12 =\min $$
One should explore the properties of such a measure.
Comment: I added an idea.
Comment: First of all, thanks a lot. Very helpful. One of these questions are very clear. I am after minimizing estimation error of the true expected value. The answer to second question is not clear because mathematical approximation framework was not in my mind when I formulated this problem. But for now I think I have to go down the path of statistical framework where the approximation function is a proper density. Because in the end I will need each $f_i$ to be a proper densities over each $X_i$.
Comment: It is not just the expectation that matters. Of course the expectation has to be close to the true expectation but the probability distribution of the product of $f_i$s should also be close to the true distribution $f_Y$. I mean the expectation is close as a result of the distributions being close. When I mean distributions close I mean the probability $\prod_if_i(y)$ has to be close to $f_Y(y)$ $\forall i$, i.e, $\prod_if_i(y)$ is in some ball $\epsilon$ around $f_Y(y)$.
Comment: I asked for a metric of distance between distributions because I can't minimize distance of each mass point $\mid f_Y(y)- \prod_if_i(y) \mid $ $y\in Y$ simultaneously. And if I minimize sum difference $\mid \sum_y [f_Y(y)- \prod_if_i(y)] \mid$, that won't be good I think as some points may be very far and others very close.
Comment: From my discussion on comments do you think I should just try to minimize the distance between the two distributions and disregard the expectation? Since if the two distributions are close as it can be then the expectation is too by linearity. Thanks
Comment: Many thank Alecos, good idea.
Comment: You' re welcome, but heed the last sentence - one should first explore the properties of such a measure theoretically, before using it.


Is there a benefit to clearing snow in rimworld?

Question: Is there a benefit to clearing snow during winter in RimWorld?
Answer: Moving over snow is slower. Clearing it will allow your colonists to travel more quickly.
Whether it's worth actually clearing it during winter if the path's just going to get snowed on again depends on your climate and how often that path needs to be used.
Personally, I try to keep a clear path between all my buildings unless the weather reaches coldsnap levels and colonists remain indoors anyway.


Should I replace my roof or just fix it?

Question: Has anyone done their roof by themselves?
I have a long term plan of building upwards (a second floor on top of my 1939 Cape Cod).  Problem is I may not be able to do this right now but my old roof already leaks.  It has two layers of shingles and I was told by roofers that it needs to be replaced soon.  I don't want to spend a bunch of money for a new roof if I'm going to be destroying it relatively soon (in a few years?).  So my options are to replace the roof myself or to just fix the leaks.  There are missing shingles and some soft planks and some leaks around the chimney but that's about it.
What should I do?
Answer: Everyone has given good advice, but the ultimate decision is probably going to depend on the total cost and real time before you plan to add a full second story. I have done dozens of roofs in my time and can give you the following considerations.
A new roof is probably going to cost you around $300 to $350 per square (10ftX10ft or each 100 square feet) for a complete strip, 6 feet of ice/water shield and new 30 yr shingles. Not knowing the size of your roof and pitch, I can't give you a real good guess, but a simple 24X30 cape with a chimney, no crickets or tricky valleys usually runs around 3 to 4 grand. Any good roofer is going to insist that any damaged or rotting roof shiething be replaced while it is stripped, adding more cost. Don't count on using the old roof structure when you remodel. Raising a roof under a new wall system can be very expensive and I suspect you have an original rafter system and board sheithing. Your new roof will want to be of the newest materials and techniques such as trusses, tounge and grove sheathing, soffit and ridge vents etc. A second story is a huge investment and in my humble opinion, very wise to do it all new.
As far as possible repairs to your old existing roof, you may be able to replace some shingles in the field easily, and repair the leaks around the chinmey with a good coat of blind nailing cement or even remove a couple of feet of shingles and treat the area with Grace ice and water shield then reshingle that small area. Obviously, we can't see or judge the general condition or continued life expectancy of the existing roof. I would strongly suggest you stop the water ASAP as Tester is right on saying a couple years of water can cause you a lot of other problems. Good Luck
Answer: Hire a pro to replace the roof.
Last spring a raccoon tried to make a nest in our roof. She didn't get through the sheathing, but she did tear out a lot of rotten shingles.
The owner wanted to save money, so they did it themselves. 4 adults (landlord, landlady, their daughter, her boyfriend), a little scaffolding, a nail gun, a chop saw, and many stacks of cedar shingles.
They would strip the shingles off a section, and fix sheathing, add tar paper or whatever, then reshingle. At night they covered exposed areas with tarps.
It took them much longer than they planned. Soon the weather turned stormy. The wind tore off the tarps and the rain came in the attic. One morning we woke up to a drooping ceiling, dripping steadily. It missed my wife's wedding dress by a few inches.
Now they had a new set of problems: standing water to remove from the attic, ruined roof insulation, water damage to the ceiling.
Learning a lesson, they got diligent about securing the tarps at the end of the day. That meant more of their time and energy going to tarping that could have gone to roofing. Since they were much slower than pros, they spent more days on the job, so they did a lot of retarping. There were a few windstorms during that period, and in the evening they'd drive by to check on the tarps. (More time & energy.)
They trimmed the cedar shingles on a chop saw. They seemed to spend a lot of time passing shingles up, measuring them, passing them down, cutting them, and passing them up again. I think pros use a roofing hatchet to do this quickly, but they didn't have that skill.
The roof on this house is complex, due to two additions over the years. They spent a lot of time on the valleys.
At one point the young couple had an argument and he fell off the roof. He was OK, but scared. That slowed the work down even more.
It took a total of 6 weeks. I would guess that a team of pros could have done it in 4 days. That would have meant a lot less time applying tarps and cleaning up water.
There was also a big mess, including hundreds of nails in the grassy yard. We still don't walk around barefoot.
If you have never replaced a roof, hire a pro. (If you had more time, I'd say get on a crew and do a few roofs under the eye of an expert, before doing your own.)
Comment: sound like u better get out the rolling magnet and metal detector so the kids don't step on rogue nails.
Comment: They already did that (http://diy.stackexchange.com/q/3185/80) and picked up a lot of nails, but we still find some occasionally. We don't walk around barefoot in the grass any more, and miss it. :-(
Comment: Seriously, find someone that has a metal detector and do a sweep of the yard.  It works great.
Answer: It all depends on why those leaks appeared. If that happened because some shingles were defective, got broken by some falling objects or just blown away because they were not hold in place firmly you could consider replacing just those shingles. But if they are so old that their lifetime is ending you risk having to replace more shingles as they continue to age and in that case it could be more efficient to replace them all at once.
Also don't forget that the zone around the chimney is very prone to leaks because of house deformation so the leak aroud the chimney doesn't mean world comes to an end, it just needs prompt repairing.
Answer: Ultimately the decision is going to be based on cost and how long the work has to last.
You need to get three quotes for both the repair and the replacement options. With the repairs you also need to know how long they'd be expected to last. Take this information and factor in your long term plan of building upwards to make the final decision.
If the repair will last until your plan of extending upwards comes to fruition then the repair is the way to go. If however, you'd need to repair again before then you might have to look more seriously at replacing the roof.
Answer: If you aren't going to do your long term second story plan within the next 5 years, then there's no question - simply replace the roof.  Patch jobs, especially when there's already signs of damage, and the roof has already been reshingled once, will not last more than a year or two.
If you are going to expand in the next year or two, then you might consider simple repairs, but it's a lot of work finding and fixing every leak.
Also, check with your local codes.  While it's almost never advised, some places do allow a third layer of shingles, and that may be enough to hold you off until you do the expansion.
Answer: Replace the roof.
If you can handle it yourself you could save some money, if not make sure you find a good contractor to do it don't just select the cheapest.
If you just fix the leaks, you'll probably spend more time in the future fixing more leaks.  The best way to truly fix the leaks is to replace the roof.  You'll find that water can do a lot of damage in two years, so it might actually save you money (and some headaches) to fix the roof properly now.
You might actually be able to use the roof when you expand upwards, I have seen people simply raise the existing roof and use it in the expansion.  This may depend on the size of the roof, the shape of the roof, and the scope of the expansion, but it can be done in some cases.
Answer: First you need to find out if that second story or floor is going to be permitted. That could reduce your problem to one that is non-problematical.
That said, sometimes a decision such as you are facing boils down, simply, to which is the more readily accomplished and which cannot be done without least consequences. In most cases, keeping water out sooner takes preference over (hopefully) keeping water out at some future, as yet undetermined date.
Comment: The OP lives **in** a Cape Cod (a style of house), not **on** Cape Cod.
Comment: @Lex: if you register your account, you'll be able to edit your old answers from any browser without worrying about losing your login cookie.


Is $\overline{A}$ path-connected?

Question: True/False
If $A\subset X$ is path-connected, then $\overline{A}$ is path-connected.
Any hints would be much appreciated; I'm not looking for a full solution.
Answer: Hint: Take the graph of $\sin\frac1x, \ x>0$.
Answer: It's false, the famous closed topologist's sine curve shows why.
https://en.wikipedia.org/wiki/Topologist%27s_sine_curve#Variants .

Is $\overline{A}$ path-connected?


How can I use a multimeter to replace electrical testers, etc.?

Question: I have a multimeter and I don't want to spend more money on other electrical test devices.
How do I use a multimeter to perform the same functions as a:

circuit tester
GFCI outlet tester
Answer:
I have a multimeter and I don't want to spend more money on other electrical test devices.

While, I understand your thought process, keep in mind that multi-meters, when combined with house wiring are not nearly as safe to operate as devices designed to perform these tests.  You are paying not only for utility but also for safety (which is far more important).

circuit tester

I guess you mean outlet tester specifically.

Set your Cat II or better rated multimeter to a high voltage AC range. If your meter has a Low-Z range intended for 120 V AC (or 230 V AC), use that.
Double check that you have the leads in the right sockets for voltage testing.
Measure the voltage

between ground and neutral
between ground and hot
between hot and neutral

Check that the results match what you expect (e.g. 0, 120, 120).

GFCI outlet tester

You can't test this with just a multimeter. You need a load that will pass about 8mA at 120V (or >30mA at 230V for UK/EU readers) between hot and ground.
(Note, according to NEMA, a GFCI "test" button uses a 15kΩ resistor with a suitable voltage rating. This means the test current is nominally 8mA at 120V (or up to 9mA for a 10% tolerance resistor)
A typical multimeter has a 10MΩ impedance on its AC voltage ranges, so it passes less than 12 micro-Amps at 120V - too small to trip a GFCI. A "low-Z" range might use a 3kΩ impedance and pass 40mA at 120V - this is more than is needed for safely testing a GFCI. Note that around 10mA is the let-go threshold for humans and so currents above that can be problematic.
Fabricating something that is safe for use with 120 V AC is going be difficult to do for less than the cost of a purpose built tool.
Comment: As the owner of several multimeters including at least one fairly expensive one - a GFCI outlet tester (which was all of $5, IIRC) is in my kit. It's quick, it's safe, it works - it would cost me more than that to replicate its GFCI-test function alone. The idiot lights are therefore cheaper than free, and faster than poking the probes in 3 ways.
Comment: I prefer using a multimeter over simple testers for measuring voltage because I like to see the actual reading and have confidence in its accuracy.  I'd recommend a Cat4 meter though so you can go on to use it in other areas.  But don't be a cheapskate on the gfci tester.  buy one thats made for the job.
Comment: It would have to draw over 6maA to trip the GFCI that sounds a bit high. The built in testers provide a specific load to trip the GFCI. I have a very expensive unit that starts at 0 and goes to 150MA so I can certify the ones used in chemical systems. I understand wanting to know the trip value but think the plug in testers are better and safer for the average DIY person. + rgb
Comment: Actually, I wonder if a H-G measurement with a low-Z meter range/mode could be used for GFCI testing?
Comment: @ThreePhaseEel, I haven't tested this but I think Flukes Low-Z impedance is 3kΩ. That would pass 40mA at 120V. So it should trip a GFCI.
Comment: @Ed: Answer updated accordingly (based on 8mA test current suggested by NEMA document)


How to moving top line to the bottom of the text in css

Question: I have a problem with css or html, which to move the line as show below the picture from first circle to the second circle. I have posted my version of JSfiddle as show below:

JSFiddle code:
https://jsfiddle.net/odzuwsdt/
HTML:

Werk

        Zo trots als een hond met zeven staarten.
 Ben ik op mijn werk. Denk jij nu: 'Dat wil ik ook!'?
 mail mij!

CSS:
.content_section.with_border:before {
    content: "";
    width: 10%;
    display: block;
    height: 2px;
    left: 0;
    top: 24px;
    position: absolute;
    background: #1d1b22;
    clear: both;
}

.content_section.with_border .label {
    position: relative;
    clear: both;
}

h1, h2 {
    font-weight: 800;
    font-size: 1.60714em;
    line-height: 1.24444em;
    margin: 0 0 .64286em;
}

.content_section.with_border .content {
    padding: 0 11%;
    clear: both;
}

.content_section .label {
    font-size: .5em;
    text-transform: uppercase;
    font-weight: 800;
}

Anybody knows how to solve it?
Comment: What is the wrong with my answer why down voted?
Comment: For better design , we should avoid use of position style. And i have avoided it and did as you wanted
Answer: add position:relative for parent div and add bottom instead of top
.content_section.with_border{
  position: relative;
}
.content_section.with_border:before {
  content: "";
  width: 10%;
  display: block;
  height: 2px;
  left: 0;
  bottom: 8px;
  position: absolute;
  background: #1d1b22;
}

demo: https://jsfiddle.net/odzuwsdt/2/
Answer: Here is a working snippet with comments:

/* Added */
.content_section.with_border {
  position: relative;
}

.content_section.with_border:before {
  content: "";
  width: 10%;
  display: block;
  height: 2px;
  left: 0;
  bottom: -4px; /* modified top -> bottom, value can be modified to adjust position */
  position: absolute;
  background: #1d1b22;
  clear: both;
}

.content_section.with_border .label {
  position: relative;
  clear: both;
}

h1,
h2 {
  font-weight: 800;
  font-size: 1.60714em;
  line-height: 1.24444em;
  margin: 0 0 .64286em;
}

.content_section.with_border .content {
  padding: 0 11%;
  clear: both;
}

.content_section .label {
  font-size: .5em;
  text-transform: uppercase;
  font-weight: 800;
}

Werk

        Zo trots als een hond met zeven staarten.
 Ben ik op mijn werk. Denk jij nu: 'Dat wil ik ook!'?
 mail mij!

Hope it helps!
Comment: That's Literally what the other answer is.
Comment: @ZohirSalakCeNa Well, we were surely answering at the same time. I have the working snippet as a plus. ;)
Comment: @Takit Isy your answer is correct, I want it to be under the text. For the first answer, if i stretch the line, it will overlap the text which is quite a ugly thing. The reason why I wanted to be under it as I wanted to animated including the line when user first loaded the page.
Answer: Try changing your css code to something like this.
.content_section {
  position: relative;
}

.content_section.with_border:before {
  content: "";
  width: 10%;
  display: block;
  height: 2px;
  left: 0;
  bottom: 0;
  position: absolute;
  background: #1d1b22;
}

.content_section.with_border .label {
  position: relative;
}

h1,
h2 {
  font-weight: 800;
  font-size: 1.60714em;
  line-height: 1.24444em;
  margin: 0 0 .64286em;
}

.content_section.with_border .content {
  padding: 0 11%;
}

.content_section .label {
  font-size: .5em;
  text-transform: uppercase;
  font-weight: 800;
}

Comment: let's don't repeat the same answer again and again ... it's already provided twice


React Native Charts for android

Question: Hi can someone suggest me the best way to implement charts in react native , I have already implemented the chart for iOS using https://github.com/onefold/react-native-chart and it works fine , but for android i am struggling a little bit , if somebody can , that will be a great help
Thanks
Answer: There are at least 2 nice libraries for creating charts in react-native for both platforms iOS and android, take a look:

react-native-svg-charts at: https://github.com/JesperLekland/
react-native-chart-kit at: github.com/indiespirit/react-native-chart-kit –

You also could look at Animated Charts in React Native using D3 and ART. With these 2 libraries you will able make customisation graphs and even animate them.
Link for tutorial
Answer: You should try using this library https://github.com/hongyin163/react-native-chart-android.
It does the job for Android.
Answer: You can also check https://github.com/wuxudong/react-native-charts-wrapper.
Support both android and ios. Use latest MpAndroidChart and Charts
Answer: I would recommend you to use react-native-chart-kit & react-native-svg. Just install it, import & you can draw several type of charts, such us: line, bezier line, progress, bar, pie chart & contribution graph (heat map). You can try my basic project: click here. Enjoy

React Native Charts for android


Do $http request from Angular Interceptor?

Question: I'm trying to implement Angular Interceptor for Exceptions. For one at least. I have a token and when it old enogh backend throws TokenAlmostExpired exception. This exception contains errorCode = 101. In the interceptor I'm checking that code is 101 and then I need to send POST request to backend's /refresh endpoint so I could refresh token.
.factory('errorInjector',['$injector', function ($q, $injector) {

    var vm = this;

    var errorInjector = {
        'response': function (response) {
            console.log(response);
            return response;
        },
        'responseError': function (rejection) {
            if (JSON.stringify(rejection.data.errorCode) === JSON.stringify(101)) {
                vm.getRefreshToken();
            }
            return $q.reject(rejection);
        }
    };
    return errorInjector;
}]);

and
.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.interceptors.push('errorInjector');
    }]);

$http
But there's a problem at interceptor level, that I can't just give it dependency on $http, because there's Circular dependency found: $http <- errorInjector <- $http <- $templateFactory <- $view <- $state
$scope
And I can't put getRefreshToken() function to $scope, because $scope dependency also gives 'Circular dependency'.
$Injector
var http = $injector.get('$http');

doesn't work as well, and gives me erorr.
So how can I catch exception in interceptor and then do a $http request from there?
Comment: @ottercoder if you do not understand @CallumLinington code it seems that you do not understant DI in angular, thats why you have `'$injector', function ($q, $injector)` which should be `'$q', '$injector', function ($q, $injector)` and thats probably your problem here
Comment: You may want to consider firing off an event, and picking it up in a service and doing the execution from there
Comment: Don't use rootscope, create your own event aggregator...
Comment: Can you show full errorInjector code? It seems that it is not full implementation.
Comment: We don't need full errorInjector code, there is enough there
Comment: I do not think so. It has $injector injected that should be used to avoid circural dependency .
Comment: Using `$injector` is a code smell to me
Comment: Here is an [event aggregator pattern implementation](https://plnkr.co/edit/hsQ1HjZUK9yWlp7htvEc?p=preview) if you want a full on example with your code just ask
Comment: @CallumLinington I've never done anything with event, so I'd really like to get some help on that, thanks. As long as I understand it supposed to be easy  .broadcast("something), .subscribe('something), right?
Comment: Yeah, if you look at my plnker it should be fairly obvious to what is going on
Comment: @CallumLinington, not really there's a lot of letters that I don't get. What is "t" and "ev", for instance?
Comment: Yeah, would agree with @pawlakppp on this
Comment: If I'd understand Angular completely,  I would'nt need a help at all. But I've found a solution. I'm putting function from service to $rootScope and calling it as a promise.
`$q.get('$rootScope').vmRT.getRefreshToken(); `
Answer: Interceptor
(function (angular) {
    'use strict';

    angular.module('services').factory("httpInterceptor", [
        'errorLauncher',
        '$q',
        function (errorLauncher, $q) {
            return {
                'requestError': function (rejection) {
                    if (rejection.status === 101) {
                        errorLauncher.pushInErrorMessage(rejection);
                    }
                    return $q.reject(rejection);
                },
                'responseError': function (rejection) {
                    if (rejection.status === 101) {
                        errorLauncher.pushInErrorMessage(rejection);
                    }
                    return $q.reject(rejection);
                }
            };
        }]);
})(angular);

and error handler service
(function (angular) {
    'use strict';

    angular.module('services').factory("errorLauncher", [
        '$rootScope',
        function ($rootScope) {
            return {
                'pushInErrorMessage': function (rejection) {
                    $rootScope.$emit('theTokenWillDieSoon');
                }
            };
        }]);
})(angular);

and now main app controller
(function (angular) {
    'use strict';

    angular.module('controllers').controller("globalCtrl", [
        '$rootScope',
        '$http',
        function ($rootScope, $http) {
            $rootScope.$on('theTokenWillDieSoon', function () {
                // http from here
            });
        }]);
})(angular);

Comment: `Circular dependency found: $http <- errorLauncher <- httpInterseptor <- $http <- $templateFactory <- $view <- $state` :/
Comment: try the $emit from error handler then ) hope it will help
Answer:
.factory('errorInjector',['$injector', function ($q, $injector) { .... }]);

Change To:

.factory('errorInjector',['$q', function ($q) { .... }]);
Answer: So I've done it with service. Thanks everyone!
interceptor:
.factory('errorInjector',['$injector', function ($q, $injector) {

    var errorInjector = {
        'response': function (response) {
            ....
        },
        'responseError': function (rejection) {
            if (JSON.stringify(rejection.data.errorCode) === JSON.stringify(101)) {
                var refreshTokenService = $q.get('refreshTokenService');
                refreshTokenService.refreshTokenService();
                $.notify({message: data.data.detailMessage}, {type: 'warning'});
            }
            return $q.reject(rejection);
        }
    };

    return errorInjector;
}]);

refreshTokenService:
.service('refreshTokenService', ['$http', function ($http) {

    this.refreshTokenService = function () {
        $http.post('/refresh').then(
            function success(response) {
               .....
            },
            function error(data) {
                .....
            }
        );
    };

}])
;


Static date in the last column

Question: I am looking to do an IF THEN statement that will help me put a date into the U Column. However, I am not sure how to go about it.
Sub()
   Dim rng1 As Range
   Set rng1 = Selection.SpecialCells("U").xlBlanks
   If Not rng1 Is Nothing Then rng1.Value = Format(Now(), "mm-dd-yyyy")
End Sub

When I run this code I receive a run-time error '1004'. Can someone help me with this?
Comment: which row(s) in column U do you want to test? Also, it's better to post *actual* code you have (even if it doesn't work) as opposed to psuedo-code. Actual code shows us the specific problem more clearly ;)
Comment: I am trying to test all the rows that don't have a current date attached to them already. So, when new data is inserted the system will see that it will need todays date and put it in column U.
Answer: First you want to find the range of cells that actually has data, because you don't want to check rows of column U where the entire row itself is empty. So assuming the last possible row of data can be found in column A, you can use this to set the search range.
With Worksheets("Sheet1") 'qualify sheet, change name as needed

    Dim lRow as Long
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

Then, you can set the search range to be from Row 1 to lRow, assuming the data is in a contiguous range left-to-right, top-to-bottom starting in A1. (The On Error statements are necessary, since Excel will throw an error if blank cells do not exist in the range).
    Dim rngSearch as Range
    On Error Resume Next
    Set rngSearch = .Range("U1:U" & lRow).SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

If the range is set then you can enter values into the entire range at once (which you had in your code above).
    If Not rngSearch is Nothing Then rngSearch.Value = Format(Now(), "mm-dd-yyyy")

End With

Comment: Great @zach123. Please mark as answered so others know going forward.

Static date in the last column


Pandas: Is there a way to count how many times a certain valued row occurs after another set of valued rows

Question: I'm sorry for the horrible phrasing but that's about the best I could do.
What I have is a DataFrame this is filled with serveral rows that represent chains of events. A user can perform two kinds of actions, See and Hold. They have certain areas where they do things: River, Beach, and Item.
Here I have my DataFrame:
df = pd.DataFrame({
    'area': ['river', 'item', 'item', 'beach', 'item', 'item', 'item', 'item', 'river', 'item'],
    'action': ['see', 'hold', 'hold', 'see', 'hold', 'see', 'see', 'hold', 'see', 'hold'],
})

And it looks like this
  action   area
0    see  river
1   hold   item
2   hold   item
3    see  beach
4   hold   item
5    see   item
6    see   item
7   hold   item
8    see  river
9   hold   item

Whats happening is the user sees the river and then holds one item, then holds another.  Then the user sees a beach, and holds one item.  Next the user sees an item, then sees another item, and holds it.  I want get the output to be something like
area  Count
river     3
beach     1
item      1

Basically, I want to know how many items have been held in certain areas.
I know I can do this somewhat simply by looping through the rows, but does pandas provide a way to do this automatically?
Comment: Are you saying that each `see` creates a new "block", and you want to know how many holds occurred within each block?  If so, what about the block containing just line 5.  Why don't you want a line in your output saying `item   0` because the user saw something but held no items in that block?
Comment: a DataFrame seems like an inappropriate data structure for this...
Comment: @BrenBarn Kind of, the only think is, is that I want an overall count. Later the user may see the river again and hold an item... That would make river have a count of 3.. I'll update my question with that difference
Comment: @juanpa.arrivillaga This is a bit of a watered down version of what I'm needing, but represents the core of the issue I am having. What would be a better data structure I could use?
Comment: @KeiNagase: If seeing the river again would update the count, why do you say "seeing another item"?  If the user see "see item, hold item, see item, hold item", would that be seeing the same item twice or two different ones?
Answer: Let's try this for the original version before you changed river to three:
df.groupby((df['action']=='see').cumsum()).agg({'area':'first','action':lambda x: x.count()-1}).replace(0,np.nan).dropna()

Output:
         area  action
action
1       river     2.0
2       beach     1.0
4        item     1.0

How it works?
First create a grouping based on the action column.
df['group'] = (df['action'] == 'see').cumsum()
print(df)

  action   area  group
0    see  river      1
1   hold   item      1
2   hold   item      1
3    see  beach      2
4   hold   item      2
5    see   item      3
6    see   item      4
7   hold   item      4

Now, lets group by "group" column and count subtracting one for the 'see'action.
df1 = df.groupby('group').agg({'area':'first','action':lambda x. x.count()-1})

print(df1)

         area  action
action
1       river       2
2       beach       1
3        item       0
4        item       1

Lastly do some cleanup dropping zero value.
df1.replace(0,np.nan).dropna()

Output:
         area  action
action
1       river     2.0
2       beach     1.0
4        item     1.0

After EDITS:
df['group'] = (df.action == 'see').cumsum()
df['group'] = df.groupby('group')['area'].transform(lambda x: x.iloc[0])
df.groupby('group').agg({'area':'first','action':lambda x: (x == 'hold').sum()}).reset_index(drop=True)

Output:
    area  action
0  beach       1
1   item       1
2  river       3

Comment: Worked like a charm. Thanks
Answer: This type of block-based counting can often be done using the type of .cumsum() trick shown in Scott Boston's answer.  To address your update, we can do it in a couple steps.  First, create a block column showing which seen area we are "in":
df['block'] = (df.action == 'see').cumsum()

>>> df
  action   area  block
0    see  river      1
1   hold   item      1
2   hold   item      1
3    see  beach      2
4   hold   item      2
5    see   item      3
6    see   item      4
7   hold   item      4
8    see  river      5
9   hold   item      5

Then, create a "target" column that tags each block with the seen area:
df.groupby('block').area.transform(lambda g: g.iloc[0])

>>> df
  action   area  block target
0    see  river      1  river
1   hold   item      1  river
2   hold   item      1  river
3    see  beach      2  beach
4   hold   item      2  beach
5    see   item      3   item
6    see   item      4   item
7   hold   item      4   item
8    see  river      5  river
9   hold   item      5  river

Now we can group by target and add up all the holds:
>>> df.groupby('target').action.apply(lambda g: (g=='hold').sum())
target
beach    1
item     1
river    3
Name: action, dtype: int64


Same output repeating in loop

Question: Why does my program only show the line of code U=float(input( "Enter the value of the letter 'U' : " )) in the terminal?
<code>    B=0
    A=0
    U=0

    while(U == 0):

         U=float(input( "Enter the value of the letter 'U' :" ))

         ent=[200,101,255,11]

         for i in ent:

             A = A + (i * ( 1 -(1/10**2)  ) / 255)  -1/(10**2)

             B = B + i

    print(B)
</code>
The output of the program in the terminal is this:
<code>Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  0
Enter the value of the letter 'U' :  9
4536

Process finished with exit code 0
</code>
Comment: Because you keep entering `0` as an input? So `U` is always `0`, and the `while` loop continues - what happens if you enter something other than `0`? (by the way, your question appears to be a Python 3 question, not a Python 2 one, please remove the tag or update your code if it *is* a Python 2 question)
Comment: Since you aren't using `U` in that loop, what's the point of entering it?
Comment: Hii @Grismar, how are you ?,  I updated the premium or that I triggered something other than zero :) ,and removed the paython 2 tag
Comment: hii @TimRoberts, All very well?, it's just so the program doesn't keep repeating without my permission, so I can write down the data calmly
Comment: Hi @Priscilla I see you use the letter U only to end the loop. If you enter 0, the loop ends. If you have a certain number of loops, I recommend using a for loop.
Answer: it seems like you need to fix indentation on the "print(B)" line
By giving one more TAB you will be printing each time the user inputs something, and with one more TAB you will be printing for each value inside your array!
For example, by having print() inside the for loop, the variable B will be shown 4 times (due to the ent variable) each time the user inserts a number:
<code>    B=0
    A=0
    U=0

    while(U == 0):

         U=float(input( "Enter the value of the letter 'U' :" ))

         ent=[200,101,255,11]

         for i in ent:

             A = A + (i * ( 1 -(1/10**2)  ) / 255)  -1/(10**2)

             B = B + i

             print(B)
</code>

Same output repeating in loop


Moving more than one divider at a time in HDividedBox

Question: I'm trying to have a minimap display with a draggable viewport below a chart. I essentially have this to control the viewport of the chart:
<mx:annotationElements>
 <mx:HDividedBox id="dividedBox" horizontalScrollPolicy="off" width="100%" height="100%" liveDragging="true" borderSides="bottom top">
     <mx:Canvas id="leftBox" backgroundColor="#FFFFFF" backgroundAlpha="0.5" width="50%" height="100%" borderColor="#333333" borderThickness="1" borderStyle="solid" borderSides="top right bottom" />
     <mx:Canvas id="centerBox" backgroundColor="#FFFFFF" backgroundAlpha="0" width="50%" height="100%" buttonMode="true" minWidth="100" mouseDown="rangeWindowMouseHandler(event);" mouseUp="rangeWindowMouseHandler(event);" mouseMove="rangeWindowMouseHandler(event);" />
     <mx:Canvas id="rightBox" backgroundColor="#FFFFFF" backgroundAlpha="0.5" width="0%" height="100%" borderColor="#333333" borderThickness="1" borderStyle="solid" borderSides="top left bottom" />
  </mx:HDividedBox>
</mx:annotationElements>

With the following script:
private function rangeWindowMouseHandler(event:MouseEvent):void {
    if(event.target === centerBox) {
     var coords:Object = rangeDragCoordinates;

     switch(event.type.toLowerCase()) {
      case 'mousedown':
       rangeDrag = true;
       break;
      case 'mouseup':
       rangeDrag = false;
       break;
      case 'mousemove':
       if(rangeDrag) {
        var xDiff:Number = -(coords.x - event.stageX) * 4.0;

        for(var i:Number = 0; i < dividedBox.numDividers; i++) {
         dividedBox.moveDivider(i, xDiff);
        }

       }
       break;
     }

     coords.x = event.stageX;
     coords.y = event.stageY;
    }
   }

Problem is, only one divider actually moves at a time. I found that if I set a timeout of about 50ms before moving the next divider that both dividers move. However, this seems like a rather awkward way to approach this and is error prone.
Anyone know if it's possible to move two dividers in a HDividedBox simultaneously or should I be taking another approach?
Comment: When you say "only one divider actually moves at a time" do you mean that the other one "catches up" after you let the first divider go?
Answer: Ended up needing to call the updates on the other divider(s) using callLater rather than calling it immediately.


Can purify find out access violation on stack variables?

Question: Currently I am using Valgrind to check memory leak and take Purify as an alternative. Valgrind can find out the access violation on an array created in heap but not in stack.
char* a = static_cast<char*>(malloc(sizeof(char) * 5));
a[7] = 'c';
printf("%c\n", a[7]);
free(a);

Valgrind points of invalid write and read in the above code, but not the following code.
char a[5] = {0};
a[7] = 'c';
printf("%c\n", a[7]);

Can Purify identify the access violation of the both blocks of code?
Answer: According to the user's guide (ftp://ftp.software.ibm.com/software/rational/docs/v2003/purify/html/ht_m_sbr.htm) and (ftp://ftp.software.ibm.com/software/rational/docs/v2003/purify/html/ht_m_sbw.htm), Purify can detect both stack boundary read and write.
However, trying your actual examples only the violation on heap data was detected also by Purify.  I have only tested the latest version from IBM (7.0.1), both for Linux and Solaris.
You may want to look at -fsanitize=address for gcc 4.8 and later.


New Mythbuntu Installation not working on restart

Question: I've just installed and configured Mythbuntu 16.04.3 LTS on an Intel NUC. It worked fine (I watched some TV through a separate Kodi front-end) until I restarted the NUC, at which point I can access http://localhost:6544/ from the NUC just fine, but cannot access it from another machine on my network. My understanding is that this is due to the service starting too soon (when networks are not yet up) and therefore not binding to make itself available on the network.
My problem now becomes: how do I fix this?
I have been trying to figure out whether the system is using systemd or upstart. Some web pages I was reading suggest the system should be using systemd by now, but I could not find a systemd config file for mythbackend. I did find a /etc/init/mythtv-backend.conf file, which I think suggests upstart is in use...? However, when I try to control the service like this:
sudo initctl stop mythtv-backend

I get:
initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refused

Even if I could control it, I'm not entirely sure how I should modify the /etc/init/mythtv-backend.conf file to ensure networks are up before starting the service (frankly, I'd just settle for a 10 second timeout or something simple).
Can anyone help?
UPDATE: I can confirm systemd is in use. By executing sudo systemctl stop mythtv-backend.service and then sudo systemctl start mythtv-backend.service, everything works. So I need to figure out how to delay the systemd service.
UPDATE 2: following the instructions on the wiki has not worked for me. I just see an error message in the log when I attempt to start/stop mythbackend.service.
Answer: I'm going to add this as an answer, even though I'm not 100% sure I'm correct. Feedback so very welcome.
The wiki page on using systemd with mythbackend suggests creating a file called /etc/systemd/system/mythbackend.service. However, I finally noticed that this did not match the name of the existing service file, /lib/systemd/system/mythtv-backend.service.
I decided to try and rename /etc/systemd/system/mythbackend.service to /etc/systemd/system/mythtv-backend.service. I moved the file, then had to jump through a few hoops, stopping/disabling the service, then re-enabling it again. Once I managed to enable it again without any error showing up, I restarted the machine and it is now accessible over the network.
The wiki contains this warning at the top:

I was very confused by the wording. It really should make it very clear to check /lib/systemd/system/ first to determine what file name you should use, then ensure you use the same name under /etc/systemd/system/.


Hanging drywall: How to shim 1.5"?

Question: I'm working on framing a wall where a sliding glass door once sat. In retrospect, I believe I should have used 2x6 lumber to frame the wall, rather than 2x4. While one side sits perfectly flush with the existing wall, the other side (shown in the picture) sits about 1.5" back from the existing wall.
Can I screw 2x4s horizontally to the framing to "shim" the drywall into the correct position?
Also, these are several different things hanging on the existing wall (some sort of cement shingle, tar paper, foam board, etc) Do I need to remove all of these prior to hanging drywall, or should I leave them as extra insulation?

Here is an up close view so you can see the gap between the framing and the existing "wall":

Any advice is appreciated.
Comment: Your image link for the close-up is broken.  Are you making up the thickness of the sheathing, siding and insulation or is the original wall framed in 2x6s?  Also, it's not clear why you're drywalling what looks like an exterior wall - is this a newly finished (formerly exterior) space?
Comment: Fixed privacy rights on the link to close-up. Should be viewable now. And I believe the original wall is 2x4, but it was originally exterior and has some sort of wood sheathing, tar paper, foam board and some kind of shingle. The wood sheathing and other things are what give it the extra 1.5" gap.
Answer: My thoughts the same about drywall @Comintern, to make up the 1.5 it would be easiest to attach 2x4's sideways.
If this is now a inside room I would remove the old exterior siding, However the "cement shingles"  look like the asbestos type commonly used you might want to have them tested prior to working with them for health reasons.
I don't think I would ever put drywall over the lap siding even with the sheet insulation if now an interior room. If this is still exposed to the elements you really should use exterior sheeting.
Comment: It was originally an exterior wall and the sliding glass door I removed opened up onto a porch. The porch was converted to a sunroom before I purchased the house, thus the wall is now an interior wall. I'm in the process of removing the siding and putting up drywall, but wasn't sure about the shingles, etc. I had planned to remove them as well, but wanted to make sure they weren't beneficial insulation as the sunroom is very well insulated.
Comment: Also, I think you're correct about asbestos shingles. Yikes. Had no clue. Thanks for the heads up.
Comment: Yep, from the close-ups it appears that the majority of the gap is from the old sheathing, siding, etc.  I'd take it down to the sheathing and then sheath the newly framed section out to the original wall plane.

Hanging drywall: How to shim 1.5"?


In C, I wrote a program to call an exe using system(). The exe asks for user input. How can I make my program provide the input?

Question: I've seen posts that are like this, but I couldn't find the exact answer to my question.
I wrote a program in C that calls another exe I wrote by saying system("./program_name");. The program that is called asks for user input, and based on what is input, displays one of three strings to the screen.
Once system("./program_name"); runs the program, is there some way I can also make my program provide the input? I want this program to be able to run the other one multiple times, by providing different inputs each time. Then, I would like the program to display which inputs caused string 2 to be output.
In other words, program 1 asks for input and displays String A, B, or C.
Program 2 runs program 1 several times with different inputs, and displays which inputs resulted in String B.
I'm stuck on being able to provide the input from my program.
Thanks in advance for your help!! :)
Answer: Instead of using system, you probably want to use popen (or, in Microsoft-land, _popen). This lets you open the child program and gives you a FILE * through which you can read the child's standard output, or write to the child' standard input (depending on whether you specify "r" or "w" as the open mode). Although non-standard, some reasonably recent versions allow both reading and writing (which it sounds like you'd really prefer).
If you can't do the latter, since you seem to be doing this on Windows, you can/could use CreateProcess to create the child with both input and output redirected. It's much more versatile, but also a lot more work.
Comment: Read-write can be problematic. If output of the child process is buffered, it can deadlock.
Comment: @Barmar: Unfortunately quite true. The standard library *should* recognize that when they're connected to pipes like this they aren't interactive, and therefore shouldn't buffer -- but that doesn't quite agree with actual experience.
Comment: I don't think there's any way for the standard library to tell that the two pipes are both connected to the same calling process.
Comment: @Barmar: It doesn't really need to -- it only buffer when they're interactive. If they're connected to different programs (e.g., via pipes) it's still fine to stop buffering.
Comment: It's the other way around: stdout is buffered when it's connected to a pipe or file, not buffered when it's connected to a terminal. Popen always uses a pipe, there's no way for the child to know that `rw` opens two pipes to the same program.
Comment: I can deal with only using write, so this is perfect, thank you so much! I had no idea popen existed, and it worked exactly how I wanted it to. I'm going to modify my program a bit so that the read option isn't needed. I'll also look into popen some more, and try to avoid read-write. Thanks again!!


What algorithm does Excel use to recalculate formulas?

Question: Are the formulas represented in a syntax tree then recalculated using a design pattern like the Visitor pattern? How would you go about reproducing the recalculation process in code?
Answer: Resolver One was a spreadsheet developed using IronPython.
Its source code has been released as Dirigible Spreadsheet. There used to be an article that described its overall algorithm:
Answer: Probably, as you say, one guess is that Excel creates a bunch of ASTs, one for each indipendent group of cells, where the leaves are the originating, static data, and the nodes are formulas.
Then it calculates the result for each node, with a post-order tree traversal algorithm.
You have to take into account leaf/node cancellation, partial recalculation, ecc. If I'm not wrong, I read somewhere that Excel could benefit of multicore processors to recalculate a sheet in parallel.
Answer:
Are the formulas represented in an AST then recalculated using a design pattern like the Visitor pattern?

You're thinking interpreter, not visitor. While treewalking using a visitor can be employed in conjunction with interpretation, employing an interpreter makes more sense here (hence the name). What this does is basically what friol wrote, i.e. traverse the tree in post-order and execute the function associated with each node.
Comment: Thanks - I have seen the Visitor pattern used to walk the AST, and thought that that was the most common method.  I'll check out the interpreter pattern as you suggested.


UITableView with large number of images

Question: I'm trying to make sample chat app.
As part of it I'd like to make sending of images. I store them outside of CoreData in Documents folder. I face the problem of slow scrolling of tableView, because some of images are extremely large (for ex user can send panorama image).
I've moved reading of files to background thread:
<code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

                UIImage *image = [UIImage imageWithContentsOfFile:message.imageAddress];

                dispatch_async(dispatch_get_main_queue(), ^{
                    rightImageCell.messageImageView.image = image;
                    [rightImageCell.messageImageView setNeedsDisplay];
                });

            });
</code>
But it has no effect.
Here is screenshot from profiler during scroll:
Comment: Maybe when storing the images you should also store a thumbnail version which can be used in the tableview.
Comment: @Nick I will use this option for sure, if I won't find any other solution. I believe whatsapp stores additional image for previeww
Answer: FastImageCache may be what you are needing. Note that this does not persists the images from web to use later, but it creates a memory image map with the resized images to display on screen.

Fast Image Cache is an efficient, persistent, and—above all—fast way to store and retrieve
  images in your iOS application. Part of any good iOS application's
  user experience is fast, smooth scrolling, and Fast Image Cache helps
  make this easier.
A significant burden on performance for graphics-rich applications
  like Path is image loading. The traditional method of loading
  individual images from disk is just too slow, especially while scrolling. Fast Image Cache was created specifically to solve this problem.
Answer: In the case of the code you supplied,  I suspect that the image is larger than the UIImageView in the cell.   That is triggering all the resizing work on the main thread because that is where the image is set.
To prevent that, you should resize the image to the size of the image view in the background thread.  Then when you dispatch to the main thread, the only work needed is just replacing the image in the image view.
The WWDC 2012 video "Building Concurrent User Interfaces on iOS" had great examples of this.
https://developer.apple.com/videos/wwdc/2012/
Answer: I faced a similar problem with CollectionViews that had really high resolution images.
The way I solved it was to pre-populate the images into an array and then simply using the index of the array to get the images. I also scaled them down to a thumbnail size before putting them into the array.
Since TableViews reuse cells, you dont want to use imageWithContentsOfFile:message in any method that is called when the TableView needs to reload its data (like when you scroll).
You might want to use imageNamed instead, which would cache the image and avoid reloading it over and over when the table cells scroll on and off the screen.
Here is a good resource: http://www.jorambarrez.be/blog/2012/04/19/ios-imagenamed-vs-imagewithcontentsoffile/
Comment: Thanks for sharing your experience. AFAIK imageNamed is used only for bundle images, so loaded images cannot be loaded with it.

UITableView with large number of images


How to configure Amazon Linux ec2 instance for java heap size?

Question: I created an ec2 instance which have java maxHeapSize = 2g by default. Then I deploy my spring boot application on it. I want to increase heap size to 3g.
I tried all this methods but no result
<code>1. Add in Elastic Beanstalk -> Configuration -> Software - > Environment properties -> _JAVA_OPTIONS = -Xms3g
2. Create Procfile.txt and write in it "web: java -Xms3g -jar project.jar". Zip it with .jar file and deploy on instance.
</code>
Is there any other method that I should try?
Comment: Are you running [Tomcat on Elastic Beanstalk](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/java-tomcat-platform.html)? See [Java with Tomcat platform options](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-specific.html#command-options-java).
Answer: Add xmx property in your dockerfile.
EX:
<code>$ java -Xmx3g your_jar
</code>
also, you can set heap size through env variables
by setting the environment variable JAVA_TOOL_OPTIONS in my ECS Task Definition like this:

Environment Variable
Value

JAVA_TOOL_OPTIONS
-XX:InitialHeapSize=1g -XX:MaxHeapSize=3g

I hope this helps!
also, you might make a startup script which can help to automate it.


Make request to Flask view from Flask-Script command

Question: I have a Flask view that returns some JSON data and want to get that same data in a Flask-Script command. I was going to use the Requests library but don't know what URL to use without hard-coding the host. How can I get the JSON data returned by the view?
@manager.command
def showdata():
    data = requests.get('/data-page')  # fails, needs full URL
    print(data.json())

Answer: When you're in your code, you don't need to make an external request. Use the test_client to make a request.
c = app.test_client()
r = c.get('/data-page')
data = json.loads(r.get_data(as_text=True))
print(data)

Ideally, extract the logic from the presentation in the view and just call a function rather than making any request at all.
# command
print(get_data())

# view
return jsonify(get_data())


How to change the color of below link on click of it?

Question: i have below code snippet. I am not getting how to change the color from red(FF0000) to black(any color) of below link on click of it?

   <fmt:message bundle="${link}" key="lnk_newScreen" />

EDIT2

ul.optionsDropDown {
  background: white;
  border: 1px solid #D1D0CE;
  border-width: 0 1px 1px;
  display: none;
  left: -15px;
  list-style: none;
  position: absolute;
  top: 12px;
  width: 135px;
  height: 90px;
  z-index: 9999;
}

ul.optionDropDown li {
  display: inline;
}

ul.optionsDropDown li a {
  display: inline;
  margin: 0;
  padding: 0px 5px;
  font-size: 11px;
  color: #05040B;
  text-decoration: none;
}

ul.optionsDropDown li a:hover {
  text-decoration: underline;
}

ul.optionsDropDown li a:visited{
  color: #000000;
}

 ul.optionsDropDown li a:active{
  color: #000000;
}

 </style>

   <fmt:message bundle="${link}" key="lnk_newScreen" />

Answer: You can do this via CSS. Insert the following in the head of your document or anywhere before the markup you posted:

Comment: i want as soon as i click it. As per your suggestion i did        function showNewScreen() {

Comment: I edited the answer to include a second line ('active') which will change the link color at the time the click happens. Please note that you should not embed this markup in your Javascript; you should move it out of the `showNewScreen()` function (indeed, from the `
Comment: it does not work. On click of link  , a new pop up opens. But parent window which has link does not get refreshed. I think  we have to do it explicity  in javascript
Answer: You should be styling with CSS, and not inline font tags.
Also, name and id should start with a-Z and not a number. The id="0" is invalid.
try:

   <fmt:message bundle="${link}" key="lnk_newScreen" />


One wall parallel with joists

Question: My house is Colonial rectangle. I have opened up one load-bearing wall that runs about 2/5 of the length between the den and the living room. With help and excellent advise, I put in a 90" header for a 6'8" opening (after putting up temporary braces on both sides to support the joists above). I feel confident about its integrity. Now I want to remove a wall that runs parallel with the joists and is 90 degrees to this wall. From all of my research, I am thinking that it is not a load-bearing wall. The roof is symmetrically consistent with the rectangular design. Being a newbie here - I'm casting a line out for opinions.
House is about 36' long and 25' wide rectangular. The wall is approx 14' with a 6' opening. Hoping to double the opening to 12' with 2' walls on each side. The wall is parallel with 16" centered joists above and below. I have already opened up a detected load-bearing wall with a 6'8" opening between Living Room and Den perpendicular to this wall. I have attached jpg images and a pdf sketch.

I just saw this when I cut away a spot of the drywall. 2x8 header is above the current opening. Does this indicate load-bearing?
Comment: Is the house 2 story? Is this on the first floor? What are the spans and spacing of the parallel joists? What is above the parallel wall? What is below the parallel wall? Is there a basement? Is there a footing or slab for support? Is there plywood or wood on this wall or just gypsum board/ plaster? Is there asbestos? Has the gypsum board/ plaster or insulation been tested? Are the joists below parallel too? Pictures would help?
Comment: How old is the home? Is it just built in the colonial style, or is it really a colonial, as in pretty old?
Comment: 2 story with basement. 16' centered joists. Wall is near center of the house on the main floor. Master bedroom wall above, basement finished bathroom below. 1/2" sheetrock. House built in 1972.
Comment: From the header you exposed and the position in the house of being near center, tells me that is a bearing wall. Are you sure the joists run parallel to that wall pictured??? Did you check both sides if that side presumably is? FWIW, it is a 2X10 header, quite hefty.
Comment: So sorry I've messed up on the format. I tried to load pictures with comments, but I couldn't find how it worked. The only way I found was by the answer mode.
Answer: There are exceptions, but typically walls parallel with the joists are non bearing. The exception will be if it is carrying a load from above, transferred down by another wall above it, carrying the roof or corner of a roof, or something like that. Also a point load from above can be brought down through a non-bearing wall.
Comment: Struc engineer here, every thing Jack said is accurate. + 'normally' the joists and roof rafters or trusses will span the shorter distance. HOWEVER. Gravity is only half the issue. The wall could be a shear wall, part of the lateral design. What's the overall dims on your house?
Comment: 36' X 25' rectangular.
Comment: @Ack I upvoted your answer. Expecially for bringing up the shear wall issue. However, if it was a shear wall, I would expect to see either diagonal strips or plywood in the wall. The picture of the header looks like a case of belt and suspenders to me. There should have been no need for a header over that existing opening.
Comment: @Robert Cline Thank you and good point, but what happened is that the CO added the pictures after I made my comment. Also, I disagree about the header, I'll respond to that in another comment on this topic
Comment: In my experiences, shear walls are needed in areas with heavy seismic activity or home with a lot of large window and door openings, like modernistic, or contemporary homes. Colonial style houses typically do not need shear walls, unless it is in a heavy occurrence seismic area, and that would be on the outside walls, not an interior wall so I would think.
Comment: FYI I'm a struc engineer. Don't forget about wind... And shear walls are absolutely needed for every home (unless we're getting into moment frames or other systems)
Answer: Ok, there is what I think is happening.
First, the answer is no, a header does not automatically mean that it is load bearing, for reasons I won't get into. It does mean that you can't yet rule out load bearing and further investigation is warranted.
Your joists are parallel per your statement. The span is 25'. That span is too much for solid  sawn lumber and a center beam would be required. That beam might bear on this header or a post in wall (it can't span 36'). Or your house is newer and using a manufactured joists such as TJI.
Based on the dimensions of your home, it is likely that this is not a shear wall. However, it very well could be.
And you have already removed wall that could also have been part of the lateral system. We can't look at this new wall as an independent completely separate item, it MUST be considered with all the changes to your home.
Much more information is needed to determine this one way or another with either a site visit or by reviewing the original plans.
Hire a local structural engineer for a review.

One wall parallel with joists


Ways of Entering New Vegas

Question: I'm generally curious as to how many legitimate ways there are to get into New Vegas at the beginning of the game.
For example, there is the obvious route of

 Entering Freeside and buying a pass/getting one from The King.

However, I was replaying the game, and it seems that I was able to enter The Strip by

 Saving the monorail at Camp McCarran, and then staying on the monorail, which then brought me to the Las Vegas Boulevard Station. I was then able to roam The Strip without ever entering Freeside.

Based on discussions with NPC's, these two routes are presented as the only ways of entering New Vegas.
I am curious to know if this second route was legitimate when I used it so early in the game (and not just a glitch based on my high reputation with the NCR - as I recall from in-game dialogue, the use of this method of transport is reserved for NCR VIP's only, and I believe I was only 'Accepted' by the NCR at the time).
Furthermore, what other legitimate ways (if any) exist to enter The Strip?
Comment: Former QA tester here: We always used the monorail as the fastest way to get to the strip -- it _is_ intended. Don't even need high rep, just an NCR uniform will suffice.
Comment: Whether or not something is intended is something only the devs know. All I can say is none of the patches or the 5 DLCs changed it.
Answer: Those are the only two entrances, but there are several ways to get past the securitron's credit check:

If you have 2000 caps, you pass the credit check and are allowed in. You don't lose the caps (that's what the casinos are for)- the robot just wants to know you're rich enough.
With 80 Science, you can reprogram the securitron to let you in.
Ralph will sell a fake passport if you have 50 Speech for 500 caps, or 375 with 50 barter
If you ask for a way to enter the Strip as your favour from The King, Ralph will give you the passport for free and without the check.
If you can somehow beat five securitrons, you can fight your way in. The gate is locked but the key can be looted from the securitron who first talks to you. This does give a lot of Strip infamy and turns the other securitrons inside hostile.

The monorail can be used with any positive NCR reputation, or if you disguise yourself as an NCR soldier.
Comment: I blasted my way into the Strip and the Securitrons on the actual Strip didn't seem to care lol They just kept telling me that I better behave and vendors talked me like I was hella sketchy lol

Ways of Entering New Vegas


Ethernet Cables and Coax Cables running outside house? How to Modify to Home Distribution Panel

Question: I want to build a Home Media Network for my new house that will have mass storage (probably about 16TB for movies and all that), that I can hardwire throughout the house using Ethernet ports, and then have separate Ethernet ports for my internet (wireless signal is not strong in our house as we have to use data from our cell phones thanks to a lack of other options).
I've basically went and mapped where I want things to go and how to get to those spots, but this is a new house build and unfortunately, my builder put the drywall up before structured cabling was able to go in, so here I am. Therein lies the issue because their electrician did the basic structured cabling of phone and TV, but I have no idea what goes where and how. See the attached picture of the various cables coming out the side of the house.
I figured this should've gone to a distribution panel and only had a single set of wires from each going outside, so

is what I have legitimate (for US Code),
if not, what can I do to correct it?
Can anyone tell me what it is thats coming out of the wall here? I figure that black is for TV, Blue is for Internet and White is phone, but I really have no idea.

Thanks for the input!

Comment: Also it's pretty normal to have the setup pictured for builder grade cable/internet pre-wire.  Wire tracers/toners are tools that are pretty inexpensively available for identifying which wire goes where.  I also agree with @CarlWitthoft when you add to this system, do it right. Fish wires that need to be fished, don't run ANY cables on the outside of the house to get from point A to point B , it will hurt resale value.
Comment: "Wireless is not strong..."  then get a different Wifi router, or add repeaters.   And aside from the need to use conduits for external wiring in general,  tossing wires and conduits all over the exterior will ruin your resale value. Do it the right way even if that requires professional help.
Comment: Also can you see those cables where they exit in the basement ceiling? (I.e. This same corner of the house, but inside) Is that are of the basement finished or unfinished?
Comment: Please add a picture showing the cut end of the cable. Right now my guesses are blue is a cat5/6 cable, the black is likely RG6 coax for TV, the white might also be RG6 since it comes out that same hole, or it might be more cat5/6
Comment: Not to mention, cause leaks.
Comment: yeah i'll be running the wires inside and fishing through the walls, definitely not going to be running the conduit externally.
Comment: If i get what youre saying, then instead of having just one Cable/TV connection going out of the house and then the rest of those being in series, the guy ran multiple lines to the outside of the house? So, wouldnt I then need a switch outside if these are going to individual jacks inside, or would I just be able to use one of the jacks as what is going to my modem and router? Wireless signal is junk because we have to use the Verizon Jetpack, which is pretty good, but the cell signal is weak where we are. Repeaters/extenders arent going to help with an already weak signal.
Comment: @J.Doe Wired ethernet cables in your house are also not going to help with a weak cell signal. Wireless ethernet (wifi) and wireless uplink (cell service) to the internet are entirely separate things that (unless your ISP is using 2.4 or 5ghz gear) have no relationship whatsoever.
Comment: @gregmac . As of now we have no ISP because there is no provider in our area, hence the Verizon Jetpack, which uses the 3G/4G signal from the cell towers and turns into a hotspot that you can use for computer internet. But I can hook the ethernet cables into that and let the Jetpack act as my modem and router. Again though, that is all contingent upon how good the signal is and when I use the Wifi from the hotspot, its terrible. Wired connection would result in less loss.
Answer: If this were my house, I'd figure out where those cables are on the other side of that wall, and pull them back into the house, patch the holes, and arrange connections inside.

Your telephone runs are going to be terminated together, for whatever landline service you get. The telephone provider should provide a Network connection jack.
Your TV lines will get connected to your service provider's equipment (when you get one) or antenna/amplifier/splitter.
Your Ethernet drops will get connected to a switch or router connected to your Internet providers equipment. (perhaps that cell box you mention)

The only outside gear should be that provided by the service providers, and they will bring wires inside the house to your connections.
The electrical codes really don't say much about low voltage wiring, which this all is.  You can run wires in walls, provide connection plates, etc.  Do it safely and sensibly.
To figure out what goes where, look into signal tracers as mentioned in other comments.
Answer: Almost assuredly, the white and black cables are your CATV and the blue cable is phone (not point out the obvious). Your CATV will be direct runs to each wall plate and the colors probably are designated for upstairs and downstairs.  You're telephone cabling is going to be in series, meaning that they just went from one jack to the next.   So if you look  inside the box of the jack located nearest the exterior entry point you will likely find the end of that cable.  But, since your telephone jacks are likely in series, it is not necessary to locate that cable, only to get a new cable into any one of the telephone wall boxes.
In addition this tool will be helpful in accomplishing this task.
Klein Scout Pro 2
Comment: It is standard practice in most phone companies, though not necessarily electrical contractors, to make each station (phone outlet) a home run to the SNI (Standard Network Interface). A blue jacket usually signifies a 4-pair twisted pair cat 5 cable, which would be a bit much for POTS, which is generally provided with relatively inexpensive cat 3 cable. It's pretty obvious from the OP's picture that this contractor really scrimped on the phone cabling, possibly because hard-wired telephones are quickly becoming archaic.


Given three customers arrive in the first hour, find probability third arrives in second half

Question: Assume customers arrive according to a Poisson process with rate $\lambda = 3$.
Given three customers arrive in the first hour, find the probability that the third customer arrives in the second half of the hour.
So that is if $X_3$ is the third arrival time: $P(X_3 \in [0.5,1] \mid N(1) = 3)$
and we have $X_3 \sim$ Gamma$(3,3)$.
To solve this I have cases : $\bigg \{X_1,X_2 \in [0,.5]$ and $X_3 \in [.5,1]\bigg\}$ or
$\bigg \{X_1 \in [0,.5]$ and $X_2,X_3 \in [.5,1]\bigg\}$ or $\bigg \{X_1,X_2, X_3 \in [.5,1] \bigg \}$
However, isn't there a way to solve this using the Uniform distribution?
Answer: I think the key to solving this problem is to identify the following relationship: $$\{N(1)=3\}=\{X_3\leq 1,X_4>1\}$$ This way we can say $$P\bigg(\frac{1}{2}\leq X_3 \leq 1\bigg|N(1)=3\bigg)=\frac{P\bigg(\frac{1}{2}\leq X_3 \leq 1,X_4>1\bigg)}{P(N(1)=3)}$$ Using the total law of probability, $$P\bigg(\frac{1}{2}\leq X_3 \leq 1,X_4>1\bigg)=\int_{1/2}^1P\bigg(\frac{1}{2}\leq X_3 \leq 1,X_4>1\bigg|X_3=t\bigg)f_{X_3}(t)dt$$ Since inter$-$arrival times are independent and $\sim \exp(3)$ we have $$P\bigg(\frac{1}{2}\leq X_3 \leq 1,X_4>1\bigg|X_3=t\bigg)=\int_{1-t}^{\infty}3e^{-3t}dt=e^{3t-3}$$ Using the fact that $X_3 \sim \text{Erlang}(3,3)$ and $N(1)\sim \text{Poisson}(3)$ we get $$P\bigg(\frac{1}{2}\leq X_3 \leq 1,X_4>1\bigg)=\int_{1/2}^1e^{3t-3}f_{X_3}(t)dt=\frac{63}{16e^3}$$ $$P(N(1)=3)=\frac{27}{6e^3}$$ Dividing these two gives us our desired probability: $$P\bigg(\frac{1}{2}\leq X_3 \leq 1\bigg|N(1)=3\bigg)=\frac{7}{8}$$
Answer: Given that exactly three events were observed in the first hour, the distribution of their event times are independent and uniform over that hour.  So the probability the third event occurs in the second half hour is equal to the complement of the probability that all three events occur in the first half hour.  But the probability of all three events occurring in the first half hour is simply $(1/2)^3 = 1/8$; therefore, the desired answer is $1 - 1/8 = 7/8$.
Comment: @oliverjones Think of it this way.  You pick three numbers uniformly at random from $[0,1]$.  That's your set of event times, which are IID uniform.  Then you sort them in increasing order.  The sorted list is your *observed* event times, which is also uniform but they're no longer independent of each other because they must be in order.  In particular, the third event must always be the largest, so if the third event does **not** occur in the second half hour, all of the events occur in the first half hour.
Comment: So if I were to change the situation to one occurring in the first half-hour and two in the second half hour, we would get the same result by a symmetrical argument, correct?
Comment: That is not quite correct because to say that the first event occurs in the first half-hour does not in itself say anything about whether the second and third events occur in the second half hour.  Analogously, in the original question, the desired probability is that the third event occurs in the second half hour, saying nothing about the times for first two events.  Your statement imposes an additional condition that the other events occur in the other half hour.
Comment: @oliverjones To illustrate:  if $(x_{(1)}, x_{(2)}, x_{(3)})$ are the event times of the first, second, and third events, such that $0 \le x_{(1)} \le x_{(2)} \le x_{(3)} \le 1$, then the outcome $(0.6, 0.7, 0.8)$ satisfies the original question's condition, as does $(0.1, 0.2, 0.8)$.  The symmetric situation would be $(0.2, 0.3, 0.4)$ and $(0.2, 0.8, 0.9)$, but only this last outcome would satisfy your condition that the first event occurs in the first half hour and the second and third events occur in the second half hour.
Comment: I think what confused me is the statement 'So the probability the third event occurs in the second half hour is equal to the complement of the probability that all three events occur in the first half hour. '. Is the complement of $_1,_2,_3 \in [0,5]$ that at least one occurs in the second half hour which forces the third event to be in the second half based off of ordering? Maybe it would make more sense to me if I find these probabilities using order statistics.
Comment: Okay thank you! That clears it up, didn't initially occur to me to think of them not only as uniformly distributed but also in terms of order statistics.


SQL Query Replace Text column as Hyperlink

Question: I have a table Products
ID | Productname |      Product_url                     |
+----+-----------+--------------------------------------+
|  1 | ShirtXS   | txthttps://www.product.com/shirt-xs  |
|  2 | TrousersM | txthttps://www.trousers.org/tM-sizeM |

Product_url is VARCHAR(512)
How to write SQL query to format Product_url column text value to Link ?
Basically, all values from Product_url field should become links with same link labels.
https://www.product.com/shirt-xs to Link
https://www.trousers.org/tM-sizeM to Link

ID   | Productname |  Poduct_url  |
+----+-------------+--------------+
|  1 | ShirtXS     |     Link     |
|  2 | TrousersM   |     Link     |

Comment: Is this `txt` exists before each link in product_url column? And one suggestion - format the HTML code within your page, but not in database, i.e. keep in database the exact link only. Tmr if you need to show something different than `Link` you have to update again the whole table
Comment: this "txt" prefix doesnt exits in columns, i've added txt to prevent stackoverflow autoformat links.
Answer: Basically you can use CONCAT() to add needed prefix and suffix around the URL, like:
UPDATE
    `products`
SET
    `product_url` = CONCAT('Link');

However, as I mentioned in my comment, better to keep the exact link only in your database and to format the HTML code within your front-end page.


User removes specific child element

Question: <textarea rows = "4" cols = "15" class = "sect"></textarea>
<textarea rows = "4" cols = "15" class = "sect"></textarea>
<textarea rows = "4" cols = "15" class = "sect"></textarea>
<textarea rows = "4" cols = "15" class = "sect"></textarea>

I want the user to double click on the element to remove it. So, if user double clicks on the 2nd "textarea" box, that specific element would be removed. My code above is as much as I have so far. Not sure what I'm doing wrong and very much appreciate your assistance.
Comment: Why are you testing to see if the dblclick event property equals an element?
Comment: DO you want jQuery solution or plain javascript solution?  You tagged the question with jQuery, but do not show any jQuery in your code example.
Answer: Wrap them all into a container, set the handler on the container and use the event.target.

    <textarea rows = "4" cols = 15" class = "sect"></textarea>
    <textarea rows = "4" cols = 15" class = "sect"></textarea>
    <textarea rows = "4" cols = 15" class = "sect"></textarea>
    <textarea rows = "4" cols = 15" class = "sect"></textarea>

var wrapper = document.querySelector('#wrapper');
wrapper.addEventListener('dblclick', function ( event ) {
    wrapper.removeChild(event.target);
});

Comment: Note the wrapper div is not necessary in this case (you could iterate the `sect` elements and attach handlers individually as done in OP's example), but certainly simplifies the code a bit for the straight javascript solution.
Comment: I really try to avoid adding individual handlers to elements if I can help it, since it scales louzy past a certain point, uses more memory and forces me to edit the loop if I want to mix different modules to use the same handler later on. For 4 elements it won't matter, but I consider it a good practice to use event bubbling to a direct parent whenever it's appropriate. It's equivalent to jquerys delegate `$(container).on(event, child, fn)` which is the faster handler according to the protected SO answer for direct vs delegate.
Answer: @Shilly has provided a good plain javascript answer.  A good jQuery solution (since you had jQuery tag on this question) could be:
$('.sect').on('dblclick', function() {
    $(this).remove();
});

Answer: If you are using pure javascript you can do this way:
var x = document.getElementsByClassName("sect");

for(var i = 0;i < x.length;i++){
  x[i].addEventListener("dblclick", function (e) {
      this.parentNode.removeChild(this);
  });
}

Answer: You should add an eventListener on each .sect element (or whatever you want) and remove the event.target:
Native JS:
var elts = document.querySelectorAll(".sect");
for (var i = 0; i < elts.length; i++) {
    var elt = elts[i];
    elt.addEventListener('dbclick', function(evt) {
        document.body.removeChild(evt.target);
    }
}

jQuery (since you tagged jQuery when I wrote the question):
$(document).on('dbclick', '.sect', function() {
    $(this).remove();
});

User removes specific child element


How to repair a broken patio corner?

Question: I've got a limestone patio. The builder apparently didn't support one corner very well and somebody stepped hard on it and a triangle about 1/2 square foot in size broke off. I imagine putting some sort of concrete underneath it but I'm not sure what product to use, or even if this is a good idea or if there's other things I should worry about.
EDIT: Here's a photo:
Comment: It's not 100% necessary, but would you mind posting photos? Always easier to visualize a solution
Comment: Not sure why I didn't think of that. Added.
Answer: I am really not sure what your patio looks like.  I am going to assume it sits on the ground.
It would be normal for a lot of the erosion of the patio to happen on the corners.  You have basically two options...

Compress ground.  You need to wet the ground around the area to make sure there are no gaps with weight.  The pavers shouldn't be hanging above ground at all.  If this is the case then you will have more that breaks.  An easy fix would be to get some fast setting quickcrete...  Build yourself a box to meet your needs - you will probably need 2 pieces of 2x6.  Fill box with the quickcrete and try to push the quickcrete under the adjacent paver piece if there is a gap.  Just level it out to fit your needs.  Pour slowly so you don't have to cup any out.
Remove the current piece.  Keep removing pieces until entire paver lays very flat on the ground with absolutely no gapping.  Add more dirt/rock and then compress and reinstall pavers.
Based on picture I would carefully knock off as much of the cement as possible inside the boxed corner - if that makes sense.  Really I don't understand the lip.  Maybe it looks good but will increase chance of stone cracking.  I would then refill with a quick set concrete.  It needs to be filled right.  You see yours is uneven probably helping the break.  I would then put that corner back on... I know you will have a little crack showing but taking a sheet out will be a pain.  I would then fill the crack with a knife grade epoxy - should be fine with limestone.  Since your color is lighter and very neutral I would not color the epoxy or it might stand out more.
Comment: Added a photo as I should have from the start. It's all on top of other masonry so this isn't quite applicable to my situation.
Comment: @Grum - see #3.  You can skip the epoxy if you get it to sit really flat and you don't notice the crack much.  If the crack doesn't line up right I would use something there.
Comment: By "lip" do you mean the overhang beyond the edge? Or do you mean the way it appears that it would sit on the edge? If the latter, it actually floats above the edges and there's some filler/moulding pieces that broke off too to fill in the gap, cosmetically.
Comment: Lip - I meant both - filler and overhang.
Answer: I would use a fiber reinforced concrete to repair the area that has broken away. You could go overboard and use a fiber-reinforced and polymer modified product like this too.
Comment: Would the broken corner need to be positively attached somehow to the other piece, beyond just floating, sort of, on the concrete?

How to repair a broken patio corner?


UIActionSheet display from Toolbar

Question: Have two issues one is showFromToolbar statement format warning issue and another is that in performAction method how i can display UIActionSheet.
ActionSheet from showFromToolbar UIBarButtonItem
when i use this statement
[ActionSheet showFromToolbar:(UIToolbar *)view];

On analyzing it shows warning for expected expression
UIActionSheet *ActionSheet = [[UIActionSheet alloc]
                             initWithTitle:@"Language Options"
                             delegate:nil
                             cancelButtonTitle:@"Cancel"
                             destructiveButtonTitle:nil
                             otherButtonTitles:@"Devanagari", @"English", nil];

ActionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;

[ActionSheet showFromToolbar:(UIToolbar *)view];

[ActionSheet release];

Button which displays ActionSheet
UIButton *pagecurlButton = [UIButton buttonWithType:UIButtonTypeCustom];

[pagecurlButton addTarget:self action:@selector(performAction:) forControlEvents:UIControlEventTouchUpInside];

pagecurlButton.frame = CGRectMake(0.1, 0.1, 30, 30);

UIImage *img = [UIImage imageNamed:@"pagecurl.png"];

[pagecurlButton setImage:img forState:UIControlStateNormal];

UIBarButtonItem *pagecurl = [[UIBarButtonItem alloc] initWithCustomView:pagecurlButton];

In performAction method how i can display actionsheet upon hiiting.
-(void)performAction:(id)sender

Comment: is the app targeted for iPad?
Comment: you need to pass in a UIToolbar instance or use a different method, maybe `[ActionSheet showInView:sender];`
Answer: I do not understand why you do this:
[ActionSheet showFromToolbar:(UIToolbar *)view];

It doesn't make any sense. If you want to present an UIActionSheet, you have to do this from a real view. You have five methods to do this:
– showFromTabBar:
– showFromToolbar:
– showInView:
– showFromBarButtonItem:animated:
– showFromRect:inView:animated:

In your case I would recommend using the third one - showInView:.
Answer: [actionSheet2 showFromToolbar:(UIToolbar *)self.view];

UIActionSheet display from Toolbar