How to use Prototypal Pattern to make an html5 rectangle for reuse

Question: I'm trying to understand Prototypal Inheritance using the Prototypal pattern by making a rectangle object and an instance of the rectangle. Seems easy, but I'm not getting it. The RectanglePrototype's method is not drawing the rectangle onto the canvas. If I use the same function as the method it works. Where am I going wrong? Also, I understand that I will need to make an initialization function, but I'm thinking I can do that later after I get the first basic steps down.
javascript:
<code>    window.onload = function () {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    var RectanglePrototype = {
        // Properties
        x: 0,
        y: 0,
        width: 100,
        height: 100,
        color: "white",

        // Method
        get:function (x, y, width, height, color) {
            context.translate(0 , 0);
            context.beginPath();
            context.rect(x, y, width, height);
            context.fillStyle = color;
            context.fill();
            return this.x, this.y, this.width, this.height, this.color;
        }
    };

    console.log(RectanglePrototype.get);

    // Instance of RectanglePrototype
    var rectangle1 = Object.create(RectanglePrototype);
        rectangle1.x = 200;
        rectangle1.y = 100;
        rectangle1.width = 300;
        rectangle1.height = 150;
        rectangle1.color = '#DBE89B';

    // Draw Rectangle Function
    function rect(x, y, width, height, color) {
        context.translate(0 , 0);
        context.beginPath();
        context.rect(x, y, width, height); // yLoc-canvas.height = -300
        context.fillStyle = color;
        context.fill();
    };

    rect(0, 450, 50, 50, '#F7F694');

}
</script>
</code>
Answer: Prototypes are extensions of objects that result from a constructor. Method lookups go through the object properties before looking into prototype.
I proper JS design, you would only add the non-function properties in your constructor.
<code>//Your constructor
function Rectangle(){
    // Properties
    this.x = 0;
    this.y = 0;
    this.width = 100;
    this.height = 100;
    this.color = 'red';
}
</code>
And then put the methods in your prototype:
<code>//I prefer the term 'draw'
Rectangle.prototype.draw = function(ctx){
    ctx.save();
    ctx.beginPath();
    ctx.rect(this.x, this.y, this.width, this.height);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.restore();
};
</code>
Then, to use in your project:
<code>var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

//List of your shapes to draw on the canvas
var shapes = [];

//Instance of Rectangle
var rectangle1 = new Rectangle();
    rectangle1.x = 200;
    rectangle1.y = 100;
    rectangle1.width = 300;
    rectangle1.height = 150;
    rectangle1.color = '#DBE89B';
    shapes.push(rectangle1);

//Draw your shapes
function draw(){
    window.requestAnimationFrame(draw);    //See MDN for proper usage, but always request next fram at the start of your draw loop!

    for(var i = 0; i<shapes.length; i++){
        shapes[i].draw(context);
    }
}
</code>
This is the 'proper' way of drawing to the canvas. For anything larger scale, please look into existing engines that do a looooot of hard work for you and have thought of everything so you don't have to. I have worked on such engines.
Comment: thank you for your response, but it seems you are using the classical model and I'm trying to understand the prototypal model or pattern. Yes, most likely I would use an engine or library in the future. I'm just trying to get an understanding of javascript.
Comment: @milkIt no he isn't; what makes you say that?
Comment: @Mathletics, I don't know javascript that well and I see the new keyword which I thought was reserved for classical model, and I don't see ojbect.create(). As mentioned, I'm learning and may very well be wrong.
Comment: Not only functions are looked up on the prototype, all properties are! And you can as well create non-function properties on the prototype, it's not bad habit!
Comment: @milkIt: Mathletics *is* using the Prototypal pattern. The fact that object prototypes are used in your code and Mathletic's code means both are implmentations of Prototypal inheritance. JavaScript can't use classical inheritance because the language doesn't have classes. It only has Constructor functions and Prototypes.
Comment: @GregBurghardt I didn't write any code, I think you mean Frederic Charette. In any case, yes, it's all prototype.
Comment: @milklt If you are looking to learn Javascript, I suggest you start doing your homework. Your question suggests that you haven't read about prototypes before posting, am I correct ?
Comment: @Bergi It is true. It can be useful for some specific cases. But that's for another class.
Comment: @Frederic Charette I appreciate the tip, and I have been reading about prototypes(this is [cool](http://www.objectplayground.com/)). I don't know what you are insinuating; however, I'm not expecting to become pro overnight, but eventually get better at Javascript. When I come to a problem I can not solve and have spent time on, I come here for help. Thank you for your help and your code write-up. It has taught me something new. Cheers!
Comment: @milklt Interesting link. I personally prefer Shelby Moore's approach to Javascript Inheritance: http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html


What is the implementation when + operator is used between two String Objects in Java?

Question: Java does not support user defined overloaded operators. Java does allow the use of using the + operator between two String Objects. When this happens, is there some internal/built in overloading to the + happening or what happens in order for two String objects to be added with the use of +?
Comment: read this https://atos.net/en/blog/will-applications-run-faster-java-9-10-11  .... and this https://www.baeldung.com/java-string-performance
Comment: BTW, the actual implementation wich is called in this situation has changed a few times and is meanwhile highly optimized in compiler and JIT, it is therefore not only easier to read, but usually also faster than dealing with StringyBuilder append yourself. The only exception to that is, if you have concatenation happening over multiple statements or across loop iterations.
Answer: There is no overloading of operator. The behavior of the + operator is well-defined in the Java Language Specification, section 15.18. Additive Operators:

The operators + and - are called the additive operators.

If the type of either operand of a + operator is String, then the operation is string concatenation.

Section 15.18.1. String Concatenation Operator + then goes on saying:

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.
Answer: "+" operator (in this context) is not "overloaded", it is pre-defined operator, called String Concatenation Operator.

15.18.1 String Concatenation Operator +

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.
The result of string concatenation is a reference to a String object that is the
concatenation of the two operand strings. The characters of the left-hand operand
precede the characters of the right-hand operand in the newly created string.

In other words, when Java sees
String res = stringObj + someObj;

it replaces the expression with code that constructs the resulting string by concatenating an existing string value with someObj.toString().
Reference: https://stackoverflow.com/a/29084397/11504153


Message display on top of other apps

Question: Please help me in showing popup in front of browser. I have used following code, but it's coming behind browser once I clicked a save button.
<code>JFrame frame;
frame = new JFrame("");
JOptionPane.showMessageDialog(frame, "Instance is already created");
</code>
Comment: Why is the frame created?  Why does the option pane show method not specify a parent component?  For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal, Complete, Verifiable Example).
Comment: i have no idea what you mean. None of this code seems relevnt to each other. Whats with the String? Doesn't seem to get used
Answer: You need to specify the window/frame as the first argument to show message dialog in front of that frame. So instead of passing null:
<code>    JOptionPane.showMessageDialog(null,
            "Instance is already created");
</code>
pass the parent Frame
Comment: I don't think passing the frame as argument will help if that frame is not visible..

Message display on top of other apps


Angular 7 - innerHTML - rendering HTML tags from DB

Question: I am creating a documentation tool, where you have the possibility to write a document (in contenteditable elements), where you can insert diferent kind of boxes and so on with a formatted style ( classnames ).
It is saved to mongoDB on upload, but when I am rendering the documents from the DB by innerHTML, the styles are only rendered on the elements in case I have the css definition on the TAG, and not on a CLASS.
For example
Works:
code {
 color: red;
}

Does not work:
.jcl-code {
 color: red;
}

I have the viewEncapsulation.None settled, and also made a safeHtml pipe to skip sanitizing.

Can you please give me some hints why it doesn't work with classes?
Many thanks!
Answer: you need to add :host ::ng-deep to your class
so :host ::ng-deep .jcl-code {...} as the necessary classes are not added automatically to HTML added via [innerHTML].
for more details and information about ::ng-deep and it's usage check https://stackoverflow.com/a/36265072/606104


pygame pixel processing is slow

Question: I'm trying to iterate through the numpy array and assigning a 0 - 255 value based on the distance to the mouse.
WIDTH and HEIGHT are in this case set to 400 and GRID[] is a numpy matrix with WIDTH and HEIGHT dimensions.
I'm using the window.set_at() function to draw each pixel on the screen with the color stored in the numpy matrix, I'm getting about 5 FPS.
Is there a more efficient way to handle this type of pixel processing,  or should I switch to something like c++ & SFML
    #update pixels
    for y in range(HEIGHT):
        for x in range(WIDTH):
            #get color based on distance to mouse; 0 -> 255
            mousePosition = pg.mouse.get_pos()
            dx = mousePosition[0] - x
            dy = mousePosition[1] - y
            d = math.sqrt(abs(dx ** 2 + dy ** 2))

            #constraining the distance value between 0 - 255
            c = min(max(d, 0), 255)

            GRID[x,y] = c

    #draw pixels
    for y in range(HEIGHT):
        for x in range(WIDTH):
            c = GRID[x,y]
            window.set_at((x, y), (c, c, c))

Comment: Surely you don't need to get the mouse-position again after updating each pixel? Can't you get it once, outside and before the loops? And if that works, you should be able to vectorise the whole thing.
Comment: This is a very "brute force" algorithm.  Do you have to check *every* pixel?  Perhaps you could somehow separate out the `x` and `y` component, so if the mouse only moves in one dimension, there's only O(N) iterations, rather than O(N²).  You can make some minor speedups, like: `(x * x)` always seems to be faster than `(x ** 2)`.  But it's the algorithm that's the real problem.  Maybe you could draw a bunch of circles around the mouse cursor - at least the circle algorithm will support axes of symmetry, etc.  A slow algorithm will be slow no matter what the language.
Answer:
pygame pixel processing is slow

Yes it is.  So don't process pixels.
Given your colour resolution of 256, this means we're really dealing with a bunch of coloured circles around the mouse cursor.  By considering only these circles, you're specifically not processing all those other pixels that can never be anything other than colour-zero.

The code below implements the program by drawing circles about the mouse cursor where the circle radius is the known distance.  So we're drawing a circle in the same "distance-colour".  Assuming the circle is drawn using the midpoint circle algorithm, this means that it only needs to calculate 1/8 of the pixels, and the rest are just quadrant (octant?) reflected about an axis of circle-symmetry.
import pygame
import random

# Window size
WINDOW_WIDTH      = 600
WINDOW_HEIGHT     = 600

###
### MAIN
###
pygame.init()
window  = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("Mouse Distance")

# Main loop
clock = pygame.time.Clock()
running = True
while running:
    time_now = pygame.time.get_ticks()
    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            running = False

    # Paint the screen in a gradient centred about the mouse
    window.fill( ( 0, 0, 0 ) )   # max distance
    mouse_pos = pygame.mouse.get_pos()

    for distance in range( 255 ):
        colour = ( 255-distance, 255-distance, 255-distance )
        pygame.draw.circle( window, colour, mouse_pos, distance, 2 )  # use a width of 2 so there's no "holes"

    pygame.display.flip()

    # Clamp FPS
    clock.tick(60)

pygame.quit()

I don't have time to make the change right now, but this example should draw to a surface, and then blit() that surface to the window for painting.  That way we only need to re-compute the surface when the mouse moves.
Comment: @importrandom - Nope, I didn't notice it was a certain way.
Comment: Does `pygame.HWSURFACE` make any difference for you? The [docs](https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode) say that the flag is obsolete in pygame 2. I had some trouble tinkering with the `OPENGL` flag so I discarded that approach.
Comment: @importrandom - I didn't know it was now obsolete.  Will edit.
Comment: @importrandom - I can't really tell.  I write answers on an old Linux VM (Ubuntu 18, pygame 1.9.2) running under windows, at work, answering while waiting for compiles.  So any sort of  "hardware" available to pygame is probably 2-levels abstracted.  :D
Comment: Was there a specific reason to invert the colour?
Comment: I'm confused, `DOUBLEBUF` is also obsolete, but I couldn't get `OPENGL` to work without it.
Answer: What constitutes fast enough?
Tidying up your code to create a minimal example with your 400x400 resolution:
import math
import time
import pygame
width, height = 400, 400

pygame.init()
screen = pygame.display.set_mode((width, height))
screen.fill(pygame.Color("black"))
clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Graphics
    # update pixels
    start = time.time()
    mx, my = pygame.mouse.get_pos()
    for y in range(height):
        for x in range(width):
            distance = math.sqrt( (mx - x)**2 + (my - y)**2 )  # 2.2 FPS 0.455s
            #constrain the distance value between 0 - 255
            c = min(max(distance, 0), 255)
            screen.set_at((x, y), (c, c, c))

    # Update Screen
    pygame.display.set_caption(f"FPS: {clock.get_fps():.1f} Pixel Processing {time.time() - start:.3f} s")
    pygame.display.update()
pygame.quit()

This results in 2.2 FPS on my PC.
The Python math module has a function that calculates the hypotenuse, so it's probably a little more optimised. Change the calculation to:
distance = math.hypot(mx - x, my - y)

This increases my frame rate by 50% to 3, probably still too slow.
We can be smarter about the pixels we modify, instead of clamping the distance to 255, fill the screen with white and then if the distance is greater than 255, don't change the pixel.
screen.fill(pygame.Color("white"))
for y in range(height):
    for x in range(width):
        distance = math.hypot(mx - x, my - y)
        if distance <= 255:  # don't set far pixels
            c = round(distance)
            screen.set_at((x, y), (c, c, c))

This increases my frame rate to 12 when the mouse is in the corner, 8 in the middle. Perhaps this is approaching usable.
If you look at the documentation for surface.set_at(), it says that using get_at() and set_at is too slow and recommends using PixelArray or SurfArray. So we can create a SurfArray:
surfarray = pygame.surfarray.pixels3d(screen)

Then to set the pixel values, we replace screen.set_at():
surfarray[x, y] = (c,c,c)

Surprisingly and unfortunately this doesn't change the frame rate significantly. Maybe this requires hardware acceleration.
I also tried manually locking the surface before iterating through the pixels as suggested in the docs, but this made no significant improvement.
So lets consider what we're doing, drawing the same circle wherever the mouse is every frame. It will be faster if we draw the circle once, and then blit it every frame centered on the mouse position. To create the circle, it's similar to what's already been done:
size = 255 * 2
dist_image = pygame.Surface((size, size), pygame.SRCALPHA)
for y in range(size):
    for x in range(size):
        distance = math.hypot(255 - x, 255 - y)
        if distance <= 255:
            c = round(distance)
            dist_image.set_at((x, y), (c, c, c))

Then our graphics update logic becomes:
screen.fill(pygame.Color("white"))
dist_rect =  dist_image.get_rect(center=pygame.mouse.get_pos())
screen.blit(dist_image, dist_rect)

This runs at 60 FPS (max) and takes almost no processing time:

pygame pixel processing is slow


Method of verifying answers

Question: I have been reading Velleman's How to prove it book and solving problems of the exercise in it.
What concerns me is that I cannot verify if actually my solutions are correct. The book has only solutions to selected problems.How do mathematicians verify that if their answer is correct ?
For example, one of their question is like this:

Analyze the logical forms of the following statements: (a) Alice and
  Bob are not both in the room. (b) Alice and Bob are both not in the
  room.

Now, I feel that both the statements are equivalent and have come up with this answer:

A = Alice is in the room. B = Bob is in the room.
(a) ¬(A ∧ B)
(b) ¬(A ∧ B)

But I'm not sure whether they are correct. And there may be lots of other problems like this. How to approach these situations generally ?
Answer: The statements are not equivalent.
For the first statement you can see that not both, this is the opposite as they're both in the room which would be $A\land B$ and negating that gives $\lnot(A\land B)$
For the second statement however, both not means that it has to be true for both of them not being in the room, so it is $(\lnot A) \land(\lnot B)=\lnot(A\lor B)$
Answer: Consider: (a) Alice and Bob are not both in the room. (b) Alice and Bob are both not in the room.

I feel that both the statements are equivalent ...

Really? Really?? What do you "feel" about (a*) Alice and Bob are not both boys vs (b*) Alice and Bob are both not boys? Or about (a**) Alice and Bob are not both top of the class vs  (b**) Alice and Bob are both not top of the class?
Think about it: if Alice is in the room and Bob outside, then (a) is true and (b) is false, so of course the claims are not equivalent ....

More generally, if you want to check your answers to exercises in Velleman, you will find a long series of blog posts starting here useful.

Method of verifying answers


Image height/width not saved using CKEditor and Full HTML input format

Question: I just upgraded a Drupal site from 5.22 to 6.22.  Everything is working except for one small problem.  I replaced FCKEditor with CKEditor using CKFinder to manage file uploads.
The problem is that when I insert an image into the CKEditor and adjust the width/height, it is not saved.
I am using Full HTML for the input format, so I don't understand why it's not working.
Answer: Looks like this might be a known issue. See this thread for info: http://drupal.org/node/731068


Why if 1 occurs somewhere in ternary expansion then that number is not belong to Cantor Set?

Question: I had read some articles about Cantor set and ternary expansion.
I come across method of Construction of Cantor set by removing middle third and taking infinite intersection of that set.
and there are at most 2 ternary exapsnsion of any number SO and in case there are 2 exapansion then there is one with no 1's.
Cantor Set as :
$C_0=[0,1]$
$C_1=[0,1/3]\cup [2/3,1]$
$C_2=[0,1/9]\cup [2/9,1/3]\cup[6/9,7/9]\cup [8/9,1]$
Cantor Set :
$C=\cap^{\infty}_0 C_n$

But I had one problem .If some element has only one ternary expansion and contain 1 then why it does not belong to Cantor set?

I am missing some argument . I am very thankful if some one  help me to find where I am missing?
Comment: How do you **define** the Cantor set?
Comment: @JoséCarlosSantos Sir, I had written the definition of Cantor Set that I followed
Answer: A number with a $1$ in the ternary representation of a number corresponds to a a "middle third" of some interval...
Look at how the ternary expansion works:  $0.1a_1\dots a_n\dots$ is necessarily in the middle third.
$0.01a_2\dots$ in the middle third of the first third.
$0.21a_2\dots$ in the middle third of the third third, etc...
This is because, in ternary,  $0.a_1\dots a_n\dots=\sum_{i=1}^\infty \frac{a_i}{3^i}$, where $a_i=0,1$ or $2\,\forall i$.
Comment: Yes.  Inspect the ternary expansion.


Dimensionality reduction method for uncorrelated data?

Question: In neuroscience it is very common to measure the reaction time (RT) of subjects. Based on the RT conclusions can be made about personal working memory capability, IQ etc.
So I have such data, which came from some neuroscience experiment. In this data I have 180  subjects from two groups  (90 subjects in each group) for simplicity let say boys and girls, and I have a set of 500 RTs for each subject. The difference between the mean RT of each group is statistically significant (t-test). Now, I would like to construct a classifier which will learn the differences between those two groups. I want the classifier to classify new subjects only based on their RT - and I'm talking specifically about classification of RT.
(A) I'm searching for dimensionality-reduction method which would fit to this case. ( I have tried PCA and it doesn't work well ). Not sure if PCA is the right thing here as there is no difference between the 100th and the 200th RT. Each RT is independent and there is no specific ordering - so there is not any co-variance here that PCA can capture. (right ?)
(B)  Which classifier is recommended in such case ?
Does anyone aware of such kind of work in general and specific for RT ? Any information on this would be appreciated.
Comment: This is a rephrase of a question I've posted here yesterday. (and excuse me for my not so good English)
Comment: So what do the 500 RTs mean? Are they repetitions of the same experiment? or are they executions of different experiments? Why does it "stand on its own" and "order has no meaning"?
Comment: Looks like there are still questions about what the experiment is. I presume in this experiment 90 "boys" and 90 "girls" were asked to give a response to 500 different stimuli (each) and the 500 stimuli were the same for the "boys" and the "girls" and their reaction time (RT) was recorded. So you have 180 samples with 500 features and one output. 500 features/dimensions is not that large, so are you trying to use PCA to identify the significant stimuli that you can use to discriminate between "boy" and "girl" outputs?
Comment: Yes, maybe PCA wasn't the right thing here - I must say that I didn't know that 500 is 'not that large':)  I have use PCA only for  dimension-reduction. As I don't believe that among 500 button presses (RT) there is a one that will be significant different from the others.
Answer: This description is closer to OK, but still you need to describe a lot of things in more detail.
Since you want to classify, it seems like what you want is LDA (Linear Discriminant Analysis) more than PCA. You want to "dimensionality reduction", possibly because you need to be able to describe the rule you obtain, but more importantly don't forget that you want something that helps you classify boys from girls.
The most important key step is that you will have to think of a sensible representation for your data that helps achieve this goal. Depending on this:

what do the 500 RTs mean? Are they repetitions of the same experiment? or
are they executions of different experiments? Why does it "stand on its own" and "order has no meaning"?

the representation would be significantly different.
Also when you say PCA does not work well, what exactly do you mean by that? It could be many things: does it give unacceptable accuracy on new data? or does it work reasonably well, just not as well as you had hoped?
What you say in your question (A), is not true you may be seeing the effects of a poor representation for your data.
Comment: yes you right my goal is classification but I thought I need to do some "dimensionality reduction" before the LDA because of the high dimension I have - 500 RT for each subject.
Comment: "stand on its own" - when you have many features for the same subject PCA assume ( if I understand it correctly..) that each feature has its own meaning (e.g. height, weight, size of shoes, age, sex, etc' etc' ) . where PCA seek to capture the variance along those features (i.e. the PCs) but here I have only one feature (the RT) with many instances (500)  of the same feature
Comment: "PCA does not work well" please ignore this comment it not so important. the main thing here that I do not know how to tackle this classification problem.
Answer: A simple discriminative classifier should train in seconds and generalize well after tuning l1 and l2 regularization parameters on a dataset of this size. There is no need to do dimensionality reduction.
If you still needed to do dimensionality reduction for whatever reason, you could use random projections, independent components analysis, autoencoders, or any number of nonlinear techniques which work well in the absence of obvious linear relationships on the data.
Comment: It should be noted that L1 and L2 regularizations are approaches to dimensionality reduction. But a user might not know it.  If any feature weight is reduced to 0, the dimension is effectively removed from the model. It's also fair to note that L2 regularization is pretty bad at this (i.e. setting a weight to exactly zero), compared to L1. (Hi Alexandre)
Comment: First thanks for the answer. Second, Do you think that methods such "bag of words" can also be useful in this case  ?


Restrict users to view custom form(s) without complete other formalities

Question: I wrote 3 custom forms using hook_menu() for resetting password. All forms have these functionalities.
Form # 1. On submit, sends OTP (code) after entering mobile number and redirect to form # 2
From # 2. On submit, validate OTP and redirect to form # 3
From # 3. The last form where user can enter password and confirm password and submit.
How to restrict user from accessing form#2 without submit form#1?
<code>                        AND
</code>
How to restrict user from accessing form#3 without submit form#2?
Answer: Check the referring page using <code>$_SERVER['HTTP_REFERER']</code> if it doesn't match the previous page either throw an error or redirect him to the first page.
Comment: Can you please explain it in detail and with an example. I've tried while it will not redirect to the form # 3 however redirect to form # 2 successfully.


Determine that 95% of all the requests took no longer than 1 second and automatically stop the test if they did

Question: I want to run a stress test by continuously increasing load until the response times become unacceptable. The condition that I need to check against is that 95% of all the requests take no longer than 1 second.

Can I determine this dynamically at runtime and if yes, how?
How can I stop the test when this condition is achieved?

I looked at the AutoStop Listener plugin, but it does not seem to have what I need for checking this condition.
Answer: The easiest is going for Taurus framework which provides flexible and powerful Pass/Fail Criteria subsystem
Example Taurus YAML file:
execution:
- scenario: simple

scenarios:
  simple:
    script: /path/to/your/test.jmx

reporting:
- module: passfail
  criteria:
  - p95.0>1s, stop as failed

In case if 95 percentile of all requests will exceed 1 second Taurus will stop the test and return non-zero exit status code which is kind of scripting/CI friendly approach.
In JMeter it is also possible with some JSR223 Scripting, you could periodically read the .jtl results file, calculate the percentile, check it against anticipated value, etc.
Comment: Yep, why not. The data is being flushed periodically into the file, if you want to always have "fresh" results you can set [`jmeter.save.saveservice.autoflush` JMeter Property](https://jmeter.apache.org/usermanual/properties_reference.html#results_file_config) to `true` via [*user.properties* file or `-J` command-line argument](https://jmeter.apache.org/usermanual/properties_reference.html)
Comment: Thanks Dimitri! I will definitely have a look at Taurus to see how it works and how it can help me. For the other solution, "periodically read the .jtl results file", can these results still be fetched if the file is still being written to by JMeter during script runtime?
Answer:
Updated the answer to fix a bug in the code and to improve the logging

This could be another solution.

Initialize the properties.
Add a SetUp Thread Group. Add a JSR223 Sampler to the SetUp Thread Group.
Then add the following code to initialize the properties.

props.put("total_requests","0")
props.put("total_requests_exceeding_limit","0")

Add a JSR223 Post Processor at the top level.

This will ensure the element is applied to all the samplers in the test plan

Add the following parameters to the JSR223 Post Processor

${__P(stop_test_exceeding_percentile_error,true)}  ${__P(percentage_limit,95)} ${__P(response_time_limit_in_seconds,1)}

Add the following script to the JSR223 Postprocessor.

long rampupTime=60000
long requestCountToStartChecking=50
long startTimeInMillis=vars.get("TESTSTART.MS").toLong()
long currentTimeInMillis = new Date().getTime()
long currentTestDurationInMillis=currentTimeInMillis-startTimeInMillis

log.info("currentTestDurationInMillis ${currentTestDurationInMillis}")

if(args[0].toBoolean() && currentTestDurationInMillis> rampupTime ){
    def total_requests_exceeding_limit=0
    def percentageOfRequestExceedingLimit=0

    int percentile_limit=args[1].toInteger()
    int response_time_limit_in_seconds=args[2].toInteger()

    long response_time_limit_in_milliseconds=response_time_limit_in_seconds*1000

    def totalRequests = props.get("total_requests").toInteger() + 1
    props.put("total_requests",totalRequests.toString())

    if(prev.getTime() > response_time_limit_in_milliseconds){
        total_requests_exceeding_limit= props.get("total_requests_exceeding_limit").toInteger() + 1
        percentageOfRequestExceedingLimit = ((total_requests_exceeding_limit/totalRequests)* 100).round()

        if (percentageOfRequestExceedingLimit> percentile_limit && totalRequests>requestCountToStartChecking) {
            log.info("Requests execeeding ${response_time_limit_in_milliseconds} has reached ${percentageOfRequestExceedingLimit}")
            log.info("Stopping the test")
            prev.setStopTest(true)
            log.info("Stopped the test")
        }
        props.put("total_requests_exceeding_limit",total_requests_exceeding_limit.toString())

    } else {
        total_requests_exceeding_limit= props.get("total_requests_exceeding_limit").toInteger()
        percentageOfRequestExceedingLimit = ( (total_requests_exceeding_limit/totalRequests)* 100).round()

    }

    log.info("totalRequests ${totalRequests} total_requests_exceeding_limit ${total_requests_exceeding_limit} percentageOfRequestExceedingLimit ${percentageOfRequestExceedingLimit} ")
} else {
    prev.setIgnore()
}

The script will ignore the samplers during the ramp-up time. Rampup period should be set in the script at the moment
The response time threshold, response percentage limit, etc can be configured through the properties/parameters
The percentage will be checked after a predefined number of requests from the ramp-up time to avoid test stopping immediately when the first response time is greater than the configured value.
The script can be improved further to wait for a pre-defined period with a response percentage exceeding the limit.
Need to handle the synchronization issues. You can use Inter-Thread communication plugin to ensure the same values are not read by different threads.
Comment: It's awesome that you wrote that! I tried your solution, but it does not seem to work as intended. In the GUI mode, I created a scenario with 2000 threads, a 2h script duration, a 2h ramp-up time for the whole script duration and 2 samplers under a random controller to test your script functionality. There is a discrepancy between the values printed in the logs and the values shown in the Aggregate Report. The aggregate report is showing the 95% line with well over 1000ms while the values from the log are not even close to 95%.
Comment: Let me check and get back to you.
Comment: We need to ignore the results during the ramp-up period. Also, the request counts to start checking the percentage moved to the nested if block. Improved the logging to display the total_requests_exceeding_limit and total_requests_exceeding_limit when the current request is not exceeding the limit.
Answer: For stopping test if one sampler was above 1 second use Duration Assertion with 1000 ms

tests that each response was received within a given amount of time

You can stop test if assertion failed:
In Thread group select Stop Test/Stop Test Now under Action to be taken after a sampler error

Determines what happens if a sampler error occurs, either because the sample itself failed or an assertion failed
Comment: Thanks, but I am interested in some way to evaluate all of the samplers at runtime, so that I can determine that 95% of them are above or below 1 second and based on that outcome stop or continue the test. The solution which you presented doesn't seem fit for my need.


Don't use htpasswd if coming from local host

Question: I have a development site that, for an additional layer of protection to keep preying eyes away, I have behind a htpasswd file. However, I'm getting tired of typing in the username and password when I'm running test on the server. So I thought it would be cool if I could check to see if the REMOTE_ADDR  = the Server's IP, to skip those lines in the htaccess file by doing the following
RewriteEngine on

RewriteCond %{REMOTE_ADDR} ^127.0.0.1 [OR]
RewriteCond %{REMOTE_ADDR} ^192.168.1.25
RewriteRule ^(.*)$ - [S=5]

AuthName "Protected Folder"
AuthType Basic
AuthUserFile /var/www/html/develSite/.htpasswd
Require valid-user

however, it is not skipping over the lines and thus prompting me still. I was hoping someone might lead me to what is missing.
Answer: Insted of mod_rewrite, you need to use the Satisfy directive:
Require valid-user
Allow from 127.0.0.1, 192.168.1.25
Satisfy Any

Comment: works with one minor correction; ips needed to be seperated by a space not a comma. thanks


Violin pizzicato with other fingers

Question: Usually, chords on the violin played using pizzicato are done using the index finger.
In this recording by Perlman of the Tchaikovsky Violin Concerto, however, he is shown to play the three successive pizzicato chords at the start of the third movement with his index, middle, and little fingers, respectively.
The question follows: are there any benefits to using fingers other than one's index when playing pizzicato?
Answer: I wouldn't suggest using your other fingers much when playing pizzicato. You should only use them when needed (like your example). You should try to use your index finger for pizzicato as much as possible, as it has more control compared to your other fingers (Your little finger being an example).
The only benefit from adding the other fingers to your pizzicato playing is that you will be able to play fast notes efficiently, but other than that there aren't many other advantages.
Answer: Outside of standard violin technique, you could maybe write double stops on non-adjacent strings. Those would probably require two fingers at once. I mean, it's kind of the same reason why most electric guitarists use only one pick: usually, only one finger is needed, and in the case of the violin, you have the added disadvantage of having to hold the bow as well. That's probably why it doesn't show up often.
Answer:
The question follows: are there any benefits to using fingers other
  than one's index when playing pizzicato?

When playing right hand pizzicato you have a choice. When playing left hand pizzicato you have less choice.
Here is a video on left hand pizzicato by violinist Vivien Hoffmann which makes some useful points. As she says in first position it is easier to pluck the open string with the fourth finger of the left hand than the first because the angle is better and the string is higher above the fingerboard. If the finger is held down then it is impossible to pluck the string with the first finger of the left hand.
Hoffman also makes a point which is relevant to right hand pizzicato when she warns against practising pizzicato for more than very short periods of time because of the danger of developing blisters on the fingers.
In the piece in the question Perlman plays three consecutive notes with right hand pizzicato. During practice if he always used the same finger then he would be much more likely to develop a blister on that finger. By using different fingers for each of the three notes he reduces the risk and extends the amount of time he can spend practising that section. In performance it then makes sense to play what you practice.

Violin pizzicato with other fingers


Any sensible way to use Hudson with TFS workspaces?

Question: I've been playing with Hudson and got the TFS source control integration running.  Problem is: it only allows you to specify a single folder as the source root.  We've got a lot of projects that share resources (including standard shared libraries).  If I could hard-link a folder like I could in source safe this wouldn't be an issue.  I can think of good solutions for other source control systems as well, but sadly I need to work with TFS, and I can't reorganize the folder structure.  Declaring things to be built from root would just be too slow.
Anyone any good ideas of how to solve this?
Comment: Can you check out from command line? Than just do the checkout yourself, as one of the build steps.
Comment: This might actually be a goer.  Of course, I'd probably end up writing a plugin for it... :)
Answer: I'm not familiar with TFS, but I took a quick look at Hudson's TFS plugin and it looks analagous to all the other VCS plugins.
Unless I'm missing something, you should be better off setting up multiple Hudson jobs, each with a different TFS source folder, to build each of your projects; you can use inter-job dependencies to control things like rebuilding dependent projects when a shared library changes.
Comment: Yeah, it's pretty much the same.  The problem's the lack of any way of linking folders in TFS.  Multiple jobs doesn't really work for me: we'd then have a radically different local build experience from the server one.  Multiply that by 200 to get an idea of the scale of the problem.
Comment: Man, am I glad I don't use Windows for development ;-)  If you're on Vista or Windows 7, could you alleviate things using symbolic links by way of the mklink command ?
Comment: Doesn't really help, sadly.  Amazingly annoying.  This is all part of my project to get rid of TFS, but TFS is fighting back.


Derivative with respect to multiple variables

Question: Is it true that, if both limits exist, then
$$\lim_{h \to 0} \frac{f(x + h, y + h) - f(x, y)}{h} \stackrel{?}{=} \lim_{h \to 0} \frac{f(x + h, y) + f(x, y + h) - 2 f(x, y)}{h} = \frac{\partial f}{\partial x} + \frac{\partial f}{\partial y}$$
?
If this isn't always true, are there some criteria such that the statement is true for all $f$ meeting the criteria?
Comment: I think there is a shortcut. Hint: your first limit is also $\frac{d}{dt}\Big|_{t=0}f(x+t,y+t)$. Can you use the chain rule to express this total derivative in terms of $\partial_x f$ and $\partial_y f$ ?
Answer: It's true if the function is differentiable, since by Taylor's theorem:
$$f(\boldsymbol{x}+\boldsymbol{h}) = f(\boldsymbol{x}) + df(\boldsymbol{x})\boldsymbol{h} + g(\boldsymbol{x} + \boldsymbol{h})\Vert \boldsymbol{h}\Vert$$
where $\underset{\boldsymbol{h}\rightarrow \boldsymbol{0}}{\lim} g(\boldsymbol{x} + \boldsymbol{h}) = 0$. That means that if you pick
$$\boldsymbol{h} = h\boldsymbol{c}$$
where $\boldsymbol{c}$ is the vector $\begin{pmatrix} 1 & 1 \end{pmatrix}^\top$, then
$$ f(\boldsymbol{x}+h\boldsymbol{c}) = f(\boldsymbol{x}) + h \cdot df(\boldsymbol{x})\boldsymbol{c} + g(\boldsymbol{x} + h\boldsymbol{c})\Vert h\boldsymbol{c}\Vert$$
Then you can formulate the limit:
$$ \underset{h \rightarrow 0}{\lim} \frac{f(\boldsymbol{x}+h\boldsymbol{c}) - f(\boldsymbol{x})}{h}$$
which you should find is equal to $df(\boldsymbol{x}) \boldsymbol{c}$ since $g(\boldsymbol{x} + h\boldsymbol{c})\rightarrow 0$ as $h\rightarrow 0$. If you consider $\boldsymbol{x} = \begin{pmatrix} x & y \end{pmatrix}^\top$, then you get the result for your case since $df$ is the Jacobian.


Office 365 global address list show entries by user/group

Question: I have active directory groups synced with my office 365 global address lists. I am trying to limit visibility of certain distribution groups to only be seen by certain users or groups.
Is there a way to set security permissions to limit who can see specific users or groups within the office 365 global address list?
Answer: Is it hybrid deployment? Or there is no Exchange on-premises server?
Based on my experience, we could user Address Book Policy (ABP) to GAL segregation. Address book policies (ABPs) lets admins segment users into specific groups to provide customized views of the organization's global address list (GAL). The goal of an ABP is to provide a simpler mechanism for GAL segmentation (also known as GAL segregation) in organizations that require multiple GALs. I would like to make it extremely clear that GAL Segmentation DOES NOT DELETE any mail enable objects. It just creates a filtered version of the GAL for the user.
Reference:
https://docs.microsoft.com/en-us/exchange/address-books/address-book-policies/address-book-policies
https://blog.kloud.com.au/2018/05/17/notes-from-the-field-enabling-gal-segmentation-in-exchange-online/
https://www.azure365pro.com/how-to-implement-address-book-policies-in-office-365exchange-20132016-effectively/


Configurando API Google Analytics

Question: Depois que você cria uma conta no Google Analytics, o Google te manda um código, esse código deve ser inserido na página index do site ou em todas as páginas relacionadas ao site ?
Answer: Caio, boa noite.
Esse snippet deve ser inserido em todas as páginas do seu site que você deseja mensurar. É recomendado que você insira dentro do head do site.
Eu sempre recomendo que utilize o Google Tag Manager(ou qualquer outro tag manager) para implementar as tags e fazer qualquer tipo de tagging, pois além de tornar o processo e manutenção mais simples, torna o carregamento assíncrono.

Configurando API Google Analytics


Array of strings as hash function key?

Question: Is it possible, in any language (it doesn't matter), to have a hash function which uses an array of strings as keys?
I mean something like this:
hash(["word1", "word2", ...]) = "element"

instead of the classical:
hash("word") = "element"

I need something like that because each word I would like to use as key could change the output element of the function. I've got a sequence of words and I want a specific output for that sequence (also the order may change the result).
Comment: you could concatenate the elements of the list and use the string-based function
Comment: Yes, but it is not advisable because arrays are mutable and mutable keys in hashes/dicts/maps can cause strange runtime errors.
Comment: @AbhinavSarkar I don't think the problem would be mutability.  In Java as long as you can implement hashCode and equals your object should be key worthy.  So you could use an ArrayList as a key, as long as your hashCode/equals assures the results you expect.
Comment: @gebuh http://stackoverflow.com/q/7842049/126916
Comment: @AbhinavSarkar: I don't think Alex is asking about a Java hash, but for a hash that is a function of the values of the array. So, for example, if you had two arrays with the same elements, in the same order, their Java hash should be different, whereas the function Alex wants should not.
Answer: Sure.  Any data structure at all can be hashed.  You only need to come up with a strict definition of equality and then ensure that hash(A) == hash(B) if A == B.  Suppose your definition is that [s1, s2, ..., sm] == [t1, t2, ..., tn] if and only if  m == n and si == ti for i = 1..m and further string s == t if and only if |s|==|t| and s[i]==t[i] for 0<=i<|s|. You can build a hash in a many, many ways:

Concatenate all the strings in the list and hash the result with any string hash function.
Do the same, adding separators such as commas (,)
Hash each string individually and xor the results.
Hash eash string individually, shift the previous hash value, and xor the new value into the hash.
Infinitely many more possibilities...

Tigorous definition of equality is important. If for example order doesn't matter in the lists or the string comparison is case-insensitive, then the hash function must still be designed to ensure hash(A) == hash(B) if A == B .  Getting this wrong will cause lookups to fail.
Java is one language that lets you define a hash function for any data type.  And in fact a library list of strings will work just fine as a key using the default hash function.
HashMap<ArrayList<String>, String> map = new HashMap<ArrayList<String>, String>();

ArrayList<String> key = new ArrayList<String>();
key.add("Hello");
key.add("World");

map.put(key, "It's me.");
// map now contains mapping ["Hello", "World"] -> "It's me."

Answer: Yes it is possible, but in most cases you will have to define your own hash function that translates an array into a hash-key. For example, in java, the array.hashCode() is based on the Object.hashCode() function which is based on the Reference itself and not the contents of the Object.
You may also have a look at Arrays.deepHashCode() function in java if you are interested in an implementation of a hashing function built on top of an array.
Comment: The other answer was better explained, but I want to thank you too! Your link would be very helpful!

Array of strings as hash function key?


Prove that a Linear Transformation is Normal, such that $T^2=T$

Question:
Let V be a finite  inner product space and $T:V\rightarrow V$ a linear transformation such that $$T^2=\frac{1}{2}(T+T^*)$$.
Prove that

$T$ is a "Normal Transformation", such that $$TT^*=T^*T$$
$T^2=T$

Proving the first statement isn't hard and I did it that way:
$T^*=2T^2-T$ $\Rightarrow TT^*=T(2T^2-T)=(2T^2-T)T=T^*T$
Therefore,  $TT^*=T^*T$.
However, proving the second statement was much harder, and I couldn't figure it out.
Thanks,
Alan
Comment: Is $V$ finite dimensional?
Comment: Yes. I will edit my post, thank you.
Answer: Once you know that $T$ is normal, then it has a basis of eigenvectors. An eigenvalue $\lambda$ must satisfy
$$
              \lambda^{2}=\frac{1}{2}(\lambda+\overline{\lambda})=\Re\lambda.
$$
The only way $\lambda^{2}$ is real is if $\lambda$ is real or is purely imaginary. However, $\lambda=ir$ for some real $r$ gives $-r^{2}=\Re(ir)=0$. So $\lambda$ must be real. Furthermore $\lambda^{2}=\Re\lambda=\lambda$, which means that $T^{2}=T$ also holds.


Changing the layout of user profile edit page

Question: I am working on a website based on Drupal Commons.
It uses Commons Profile Module to add extra fields to add user information.
I want to accomplish two tasks:

Change the layout of User Profile edit page i.e. : mysite/user/%user/edit.
Where do I make the changes. Should I create a new *.tpl.php file and if so, then where?
I want to fetch the User Information Fields added by the Commons Profile Module to the edit form.

Please provide a solution in which both these issues are taken care of.
Comment: Did the below answer worked for you?
Answer: I had to do this in the past and I went the module route.
Using Display Suite, Renderable Elements and Field Group I was able to fully change the layout of edit forms.

Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. Screencast
Renderable Elements enables you to register any forms and manage the
  display through an UI. It will also make (additional) elements
  available of existing entities on the manage forms/display screens or
  you can for example register the contact form and rearrange the fields
  through Field UI. Screencast
Field Group will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Edit: Also using Display Suite, you can add different views or blocks directly as fields to your node. So pulling fields from other entities shouldn't be a problem if you are good with views.
Comment: Back in 2013 I used DS, but I have also since switched to Panels. I use a combination of Chaos Tools and Panels. After enabling the Page Manager module (Chaos Tools) and Panels modules, you should be able to enable the User edit template in order to override the User Edit form

Also the following modules might be interesting for those that want to override everything with Panels pages: Page Manager Existing Pages, Panelizer, and Panels Everywhere
Comment: So far it works great. I use Panels Everywhere with the Radix theme (with a bootswatch subtheme). There are only a few modules where I have seen incompatibilities with Panels Everywhere. All have been patched aside from Authcache which can't lazy load panels when using Panels Everywhere.
Comment: Why not use panels instead of ds? I want to split edit profile page into vertical tabs with specific fields. For example Email Notification tab will have all fields or settings related to Emails. Similarly other tabs will have different user fields. Any idea how to achieve it?
Comment: Did you get the username, password and email field forms?
Comment: Does Panels Everywhere work without issues?
Comment: Thank you for sharing the Renderable Elements module. Just saw a video. I wonder what else is hidden in Drupal's module treasure.


Como fazer uma chamada de um arquivo que contem um formulário com ajax?

Question: Como eu chamo um arquivo que tem o conteudo do formulário das condições?
Html
SELECIONE UMA OPÇÃO
     <form>
      <input value="A" name="opcao" type="radio">opcao A
      <input value="B" name="opcao" type="radio">opcao B
      <input value="C" name="opcao2" type="radio">opcao C
      <input value="D" name="opcao2" type="radio">opcao D

                CONTEUDO DO FORMULARIO AQUI

     </form>

Script
$(document).ready(function() {

                    $('input[type="radio"]').change(function(event) {
                        var option1 = $('input[name="opcao"]').filter(':checked').val();
                        var option2 = $('input[name="opcao2"]').filter(':checked').val();
                        getForm(option1, option2)

                    });

                    // Traz o form com ajax
                    function getForm(option1, option2){
                        console.log(option1);
                        console.log(option2);

                        if ( (option1 == 'A') && (option2 == 'C') ) {
                            // Faz uma chamada ajax para trazer o formulario
                        }

                        if ( (option1 === 'A' && option2 === 'D') ) {
                            // Faz uma chamada ajax para trazer o formulario
                        }

                        if ( (option1 === 'B' && option2 === 'C') ) {
                            // Faz uma chamada ajax para trazer o formulario
                        }

                        if ( (option1 === 'B' && option2 === 'D') ) {
                            // Faz uma chamada ajax para trazer o formulario
                        }
                    }

                });

Answer: Você pode criar várias
s com diferentes formulários e exibir só os que você quer dentro do seu script. Por exemplo:
HTML

Script
if ( (option1 == 'A') && (option2 == 'C') ) {
    // Faz uma chamada ajax para trazer o formulario
    $('#form1').show();
}
if ( (option1 === 'A' && option2 === 'D') ) {
    // Faz uma chamada ajax para trazer o formulario
    $('#form2').show();
}

Comment: Assim eu sei chamar queria chamar um arquivo tipo.
Comment: O que exatamente voce quer retornar de acordo com cada condicao? Um formulario especifico pra cada opcao, ou um arquivo de configuracoes p/cada? seja mais especifico...


How can I use ffmpeg's swscale to convert from NV12 to RGB32?

Question: Say I have an NV12 frame in memory as an array of bytes. I know:

its Width and Height
its Stride (total width of a line including padding), which is the same for Y and UV components as per NV12 specification
I know where Y begins, U begins at Y + (Stride * Height), and V begins at U + 1 (interleaved with U).

Now this is what I have so far:
<code>SwsContext* context = sws_getContext(frameWidth, frameHeight, AV_PIX_FMT_NV12, frameWidth, frameHeight, AV_PIX_FMT_RGB32, 0, nullptr, nullptr, nullptr);
sws_scale(context,
</code>
So I don't know what the parameters to sws_scale should be:

srcSlice : a pointer to the array of bytes? It should apparently be a
pointer to a pointer, but what I have is just a single-dimensional
array of bytes.
srcStride : apparently expects an array of strides, but I have just one stride for the entire file. Should I pass an array with just
one element?
srcSliceY : an offset to the first byte I guess? Should be 0 then.
srcSliceH : the frame height I guess
dst : once again, pointer to a pointer, but my destination output is actually just another array of bytes...
dstStride : Width * 4 I guess?

Any help appreciated.
Answer: <code>/// uint8_t * Y;
/// uint8_t * out;

// 2 planes for NV12: Y and interleaved UV
uint8_t * data[2] = {Y, Y + Stride * Height};

// Strides for Y and UV
// U and V have Stride/2 bytes per line;
// Thus, we have 2 * Stride/2 bytes per line in UV plane
int linesize[2] = {Stride, Stride};

uint8_t * outData[1] = {out}; // RGB have one plane
int outLinesize[1] = {frameWidth*4}; // RGB32 Stride

sws_scale(context, data, linesize, 0, Height, outData, outLinesize);
</code>
Comment: Oh I found it: the "outLineSize" should be frameWidth * 4, not stride * 4. The stride can be larger than the width, if there is padding. This is what was causing the out-of-bounds memory access.
Comment: This makes sense, but it's failing with AccessViolationException... my output buffer is of length (Height * Stride * 4), so I don't get it.


How to print the value of an array instead of the key?

Question: I have the code below in a form builder for Drupal 7:
$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => array(
    0 => t('Blue'),
    1 => t('Yellow'),
  )
);

I need to print the selected value in hook_mail but I only get the key when I write:
function color_mail($key, &$message, $params) {
  global $user;
  $message['subject'] = 'Selected color is: ' . $params['color']
}

While what would make sense here would be to print the value, not the key. I tried $params['color']['#options']; too but it didn't work.
Any tip on how to make this work? I'm sure it's something simple I don't yet know about.
Answer: The form submission process will only actually keep hold of the array key (which is the value for the select element), so it won't be available to you in $params.
The usual method to handle this sort of thing is to provide a function to return the options:
function MYMODULE_colour_options() {
  return array(
    0 => t('Blue'),
    1 => t('Yellow'),
  );
}

Then in your form function you would use:
$form['color'] = array(
  '#type' => 'select',
  '#required' => TRUE,
  '#title' => t('Color:'),
  '#options' => MYMODULE_colour_options()
);

And in the message hook:
$colour_options = MYMODULE_colour_options();

$colour_string = 'Unknown';
if (isset($colour_options[$params['color']])) {
  $colour_string = $colour_options[$params['color']];
}

$message['subject'] = 'Selected color is: ' . $colour_string;


HTML/CSS Horizontal navigation submenu hover wrong displayed

Question: I am creating an HTML page with a horizontal navigation and vertical submenu. Everything is working fine, except the fact, that the hover on the submenu is displayed to the left of the actual menu item.
See my jsfiddle: https://jsfiddle.net/qmcte349/

/* Navigation */
nav ul {
 list-style: none;
 background-color: #444;
 text-align: center;
 padding: 0;
 margin: 0;
}

nav li {
 line-height: 40px;
 text-align: left;
 width: 13%;
 border-bottom: none;
 height: 50px;
 display: inline-block;
 margin-right: -4px;
}

nav a {
 font-size: .8em;
 text-decoration: none;
 color: #fff;
 display: block;
 padding-left: 15px;
 border-bottom: none;
}

nav a:hover {
 background-color: #8e2323;
}

nav a.active {
 background-color: #aaa;
 color: #444;
 cursor: default;
}

nav > ul > li {
 text-align: center;
}

nav > ul > li > a {
 padding-left: 0;
}

/* Sub Menus */

nav li ul {
 position: absolute;
 display: none;
 width: inherit;
}

nav li:hover ul {
 display: block;
}

nav li ul li {
 display: block;
}

Home

Verein

Chronik

Termine

Veranstaltungen

Übungen

Bilder und Videos

Links

Thank you for your suggestions!
Comment: Vote up for posting fiddle and making testing and answering easy.
Answer: Your problem goes from setting width to 13%. This way the li in the submenu also is 13% of its parrent width. Another issue you will see with margin-right: -4px; I suggest this code:
nav li {
    line-height: 40px;
    text-align: left;
    border-bottom: none;
    height: 50px;
    display: inline-block;
}

nav > ul > li {
    width: 13%;
  margin-right: -4px;
}

Set the things that are importaint for main menu (menu bar) only to it and not to its children.


Ruby on Rails apps return 504 error after some time

Question: On a shared hosting, I have several Ruby on Rails applications(5.0 and 5.2 with ruby 2.2 or 2.4), and some of them, after I start them and I access some pages, stop working and a 504 Gateway Time-out error occurs. I can see nothing in the log file when it happens or in the CPanel's Metrics - Errors section, and if I try to load more and more pages, I get the 504 error and the Physical Memory Usage on the server increases to 99%.
However, just some of the apps are blocking, and the others don't. And they do not have something special that could consume memory.
All of them have the version 3.12 of puma gem, but I tried to change it with 4, but nothing changed.
If I log in  the SSH console, when I run the command ps -aux something like this is displayed:
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
truesoft 17085  0.1  0.0 366116 22308 ?        S    11:29   0:00 lsphp
truesoft 25413  0.0  0.0  11228  1988 pts/0    Ss   08:11   0:00 -bash
truesoft 18492  0.0  0.0  51020  1664 pts/0    R+   11:30   0:00 ps -aux
truesoft  3525  0.5  0.2 268288 94924 ?        SNl  11:19   0:03 RACK: /home/truesoft/app1_which_works_fine/ (production)
truesoft 12526  1.2  0.2 268116 96808 ?        SNl  11:26   0:03 RACK: /home/truesoft/app2_which_works_fine/ (production)
truesoft 13773  1.5  0.2 250988 94000 ?        SNl  11:26   0:03 RACK: /home/truesoft/app3_which_works_fine/ (production)
truesoft 18029  4.1  0.3 287600 108072 ?       SN   11:30   0:01 RACK: /home/truesoft/app2_which_works_fine/ (production)
truesoft 18088 11.9  0.3 295860 118684 ?       SN   11:30   0:02 RACK: /home/truesoft/app2_which_works_fine/ (production)
truesoft 18266  0.0  0.2 294768 75004 ?        SN   11:30   0:00 RACK: /home/truesoft/app2_with_error/ (production)
truesoft 12413  0.0  0.2 359060 96356 ?        SNl  Dec18   0:49 RACK: /home/truesoft/app1_with_error/ (production)
truesoft 12444  0.0  0.2 359060 93172 ?        SN   Dec18   0:00 RACK: /home/truesoft/app1_with_error/ (production)
truesoft 24104  0.0  0.2 314648 82472 ?        SN   09:30   0:00 RACK: /home/truesoft/app3_with_error/ (production)
truesoft 25743  0.0  0.2 314648 82472 ?        SN   09:31   0:00 RACK: /home/truesoft/app3_with_error/ (production)
truesoft 31330  0.0  0.2 312456 83812 ?        SNl  09:34   0:03 RACK: /home/truesoft/app3_with_error/ (production)

There are processes that are hanged there for few days (see Dec18) or even more, and I have to kill them with -9.
I also ran  strace -tt -p 31330 on a process in the moment that I saw the page in the browser keeps loading for a long time, without result, and here is the output:
strace: Process 31330 attached
12:58:42.475820 select(8, [7], NULL, NULL, {0, 668936}) = 0 (Timeout)
12:58:43.148229 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:44.153079 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:45.158192 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:46.163095 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:47.168427 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:48.169276 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:49.174225 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:50.175233 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)
12:58:51.180778 select(8, [7], NULL, NULL, {1, 0}) = 0 (Timeout)

I noticed that the line with select(8, [7], NULL, NULL, {1, 0}) is repeating forever, each second.
This select seems to be a linux system call (see man).
I've installed the same applicaton on another hosting, and there it works fine. One thing different is that for ps -aux the COMMAND column displays
Passenger AppPreloader: /home/other_domain/app3_which_had_error_on_other_server (forking...)

I'm a beginner with linux and I don't know where to check what is wrong. Maybe somebody could give me some hints to see where to look. On my local machine, all the applications work fine, even in production mode.
Edit: After further investigations, I found that this is a deadlock issue described here: puma/puma#1184. However, setting eager_load, or thread_count to 1 doesn't help.
Answer: On the hosting server there was Litespeed installed, and it seems that when the app's rails version is 5.2, a deadlock occurs in the linux processes, and cause the 504 error.
There is an old post here:  https://www.litespeedtech.com/support/forum/threads/rails-2-2-cache_classes-problem.2493/ where the version 2.2 it is specified.
Without Litespeed, everything works fine.


UDP port scanner issues, C

Question: So I am trying to create a functional udp port scanner. The code I have so far seems to be missing something such maybe switch, use of iwreq or simply a linked list for the scanned ports, not sure. I am new to C programming so would appreciate any help.
<code>#include <erno.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <iwlib.h>
#include <wireless.h>

#define MAXSIZE 0

int main(){

struct timeval timesec;
int sockfd;
int ipleng;

int port= 1020;
struct hostent hostent;
struct sockaddr my_addre;
struct imcmphdr IC;
struct sockaddr_in my_addr;
struct ip ipp;
struct iw_range rang;
struct iwreq iwq;
char message="  ";
h_addr_list[0];

scan();
if(scan==NULL){
perror("scan not done");
exit(1);

}
int scan(){
ioctl(socket,SIOCSIWSCAN,&iwq);
iw_get_range_info(sockfd,wlan0,&rang);
  if(iw_get_range_info(sockfd, wlan0, &rang)>0){
    rang=1;
  }
   r=iw_get_range_info(sockfd,wlan0,&rang);
char serve [50];
int hlen;
int slen;
for(int i=0; port<r; i++){
if(hostt=getnameinfo(struct hostent  *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){

if(haddrinfo=getaddrinfo(struct hostent *host, MAXSIZE, host, hlen, serve,
slen, NULL)==NULL){
exit(1);
}
else{
printf("IP address");
addrlist=h_addr_list;
for(i=0; addrlist[i]>0; i++){
printf("host: %s\n", arrdlist[i],  hostt);
printf("server: %s\n", haddrinfo);

if(sockfd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))<0 {
   perror("socket not created");
   return -1;

if(rsock=sockfd(AF_INET, SOCK_RAW, IPPROTO_ICMP))<0){
    perror("socket fail");
    exit(1);
    else{

memset(&my_addr,0,sizeof(my_addr));
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(1020);
my_addr.sin_addr.s_addr=inet_addr();
my_addr.sin_addr(struct in_addr*)hostt->h_addr;

if(sendto(sockfd,MAXSIZE,0,0,(struct sockaddr*)&my_addre,sizeof(my_addre))
<0){
    perror("can't send");
    return -1;
   }
  }
 }
}
if(setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&host,sizeof(host))== -1){
    perror("setsockopt(SOL_BROADCAST)");
    return -1;
    else
        timesec.tv_sec=3;
     while(1);
    {
    FD_ISSET(&my_addr);
    FD_ZERO(&readfds);
    FD_SET(&rsock,&readfds);
    ipleng=ip->ip_hl<<2;
    if(select(rsock+1,&readfds,NULL,NULL,&timsec);
    for(;;){
        if(select(rsock+1,&readfds,NULL,NULL,&timesec){
        if(FD_ISSET(rsock,&readfds0{
            siz=read(rsock,(struct icmphdr*)&IC,sizeof(IC));
            if(siz=0){
                printf("can't read");
            }

         }

        }
  }
        ipp=(struct ip*)MAXSIZE;
        message=(struct icmp*)(MAXSIZE+ipleng);
        if(recvfrom(rsock,MAXSIZE,sizeof(MAXSIZE),NULL,my_addre,hlen)<0){
            perror("ICMP error");
            printf("port closed");
            if(message->icmp_type==ICMP_UNREACH)&&message->icmp_code==ICMP_UNREACH_PORT{
                exit(1);
            }
            else{
                if(message==0){
                    printf("p;ort open");
                    port=getservbyport(htons(addrlist[i], "port");
                    printf("udp port %d %s is open\n", addrlist[i], port->s_addr);
                    if(port==NULL){
                        printf("unknown");
                    }

                }

            }

          }

        }
       }

      }

    }

  }

  }
 }

fflush(sockfd);
return 0;

}
</code>
Comment: It is missing proper formatting at the very least.
Comment: Please go to [help] and find out how to ask and what to ask about. You may have a [mcve] but there is no clear problem statement as well as no description of the problem.  IOW, a little effort on your part is required.
Comment: `if(select(rsock+1,&readfds,NULL,NULL,&timsec);` <<-- Seems nonsensical. And: in the loop below it, you have to reinitialise your FD_SET before every select(), , since select() modifies it.
Comment: You can avoid a lot of unreadable indentation by not using this kind of code structure: `exit(1);
}
else{` #codingstyle avoiding this: ` }
                }
            }
          }
        }
       }
      }
    }
  }
  }
 }` at the end
Comment: There are many errors in your code as written.  I recommend you first try to format it in a C-ey way.  Then, start running the code through a compiler with warnings on.  On linux or mac, this would be "gcc -Wall filename.c". You'll get a lot of errors, but chip away at them!  Then, @Fabien's answer is a good starting point.  Good luck!
Comment: @wildplasser oh i thought select() might have been necessary :(
Comment: @EugeneSh yeah i hope that that will help things.
Comment: @Jeremy yeah it seems daunting to tackle these errors as im a newbie. but ill try.
Comment: @KevinDTimm the problem is there are several errors and not sure what is going on. I thought my code seemed similar to other udp scanners but it doesnt work :(
Comment: @cjj20 I'd start with a couple of things: indentation (!); In C, functions aren't defined inside other functions (like I think your scan() is); you misplaced your paren with `if(message->icmp_type==ICMP_UNREACH)&&message->icmp_code==ICMP_UNREACH_PORT{`;missing a paren in `if(select(rsock+1,&readfds,NULL,NULL,&timesec){`;  Generally, I'd try to compile/check as you go, so errors don't build up.
Comment: @Jeremy ohh the function issue I will have to read up on how its done in C. And i will correct the errors you mentioned. I just hope I can make the code somehow resemble a scanner
Answer: A thing like 'UDP port scanner' does not technically exist because UDP is stateless, so there is no connection.
Instead, what "UDP port scanners" do is send 'payloads' in order to try to get a response.
Basically a correct payload to test UDP 53 is a DNS request.
So you implement payloads, and you test all payloads on a port. Then you have a sort of UDP scanner.
Well I guess this does not answer your question but I hope it helps you perform a better scanner.
Comment: Thanks trying to get the code to send a packet to various ports and to detect which port respond with a icmp error but I will check out what you said.
Comment: On secured servers those ICMP packets are filtered while the expected UDP traffic won't be. That's why nmap will tell you `open|filtered` on those ports. Because he does not know if they are ICMP firewalled or open. Only a proper payload could tell. `nmap -sU -p 55555 18.104.22.168`
Comment: ok ill try that but the code seems so problematic (my code that is).

UDP port scanner issues, C


How can I allow a superclass method to return something else?

Question: Given two classes, Superclass and Subclass -
How can I use an allow on the Superclass to return something different?
#=> given `rspec` is in your $LOAD_PATH, this should be an SSCCE
require 'rspec'

class Superclass
  def superclass_method
    true
  end
end

class Subclass < Superclass
  def subclass_method
    superclass_method
  end
end

descriptor = RSpec.describe Subclass do
  describe '#subclass_method' do
    subject(:subclass) { described_class.new }

    let(:superclass) { spy('superclass') }

    before do
      stub_const('Superclass', superclass)
      allow(superclass).to receive(:superclass_method).and_return false
    end

    it 'should return false' do
      expect(subclass.subclass_method).to eq(false)
    end
  end
end

p descriptor.run

The output of p descriptor.run returns false for the above code (i.e., the test failed), while true is given when I change the expectation to expect(subclass.subclass_method).to eq(true).
I feel like I'm missing something simple here.
I've done some debugging and I see a few things:
subclass.subclass_method     #=> true
subclass.superclass_method   #=> true
superclass.superclass_method #=> false

I see that it's fine on the third line here, but I'm not sure how to return this when called from the Subclass
Answer: I was able to accomplish this without using a double on the Superclass at all!
I changed the description block to:
describe '#subclass_method' do
  subject(:subclass) { described_class.new }

  before do
    allow(subclass).to receive(:superclass_method).and_return(false)
  end

  it 'should return false' do
    expect(subclass.subclass_method).to eq(false)
  end
end

Instead of using spies and stubbing the constant for the Superclass, I was able to mock the superclass method within the context of the Subclass. ♂


Checking for diacritics with a regular expression

Question: Simple problem: an existing project allows me to add additional fields (with additional checks on those fields as regular expressions)  to support custom input forms. And I need to add a new form but cannot change how this project works. This form allows a visitor to enter his first and last name plus initials. So the RegEx ^[a-zA-Z.]*$ worked just fine for now.
Then someone noticed that it wouldn't accept diacritic characters as input. A Turkish name like Ömür was not accepted as valid. It needs to be accepted, though.
So I have two options:

Remove the check completely, which would allow users to enter garbage.
Write a regular expression that would also include diacritic letters but still no digits, spaces or other non-letters.

Since I cannot change the code of the project, I only have these two options. I would prefer option 2 but now wonder what the proper RegEx should be. (The project is written in C# 4.0.)
Comment: Leaving aside local regulation, if my name was "42 79" and someone put it in some poxy DB as "Fourtytwo Zeventynine", I would demand that they change their DB as it would be _formally_ incorrect. More to the point, people _do_ have multi-word family names (that might or might not be easy to capitalize) and family names with apostrophes in (common in Irish surnames) and a whole host of other things. Names are tough to validate.
Comment: What are you going to do about someone who legally changes the written form of their name to be the character sequence "42 79"? Some people do stupid stuff like that…
Comment: Well, someone named "42 79" would be entered as "Fourtytwo Zeventynine". :-) Besides, not all countries allow their citizens to be this stupid. :-)
Answer: You can use the specific Unicode escape for letters - \p{L} (this will include the A-Za-z ranges):
^[.\p{L}]*$

See on regularexpressions.info:

\p{L} or \p{Letter}
Matches a single Unicode code point that has the property "letter". See Unicode Character Properties in the tutorial for a complete list of properties. Each Unicode code point has exactly one property. Can be used inside character classes.
Comment: If you add `\p{L}` to the character class, you can remove `a-zA-Z`.
Comment: But `/^[.\p{L}]*$/.test("à") == false`
Comment: `\p{Letter}` didn't work for me, but `\p{L}` did, regarding usage of `java.util.regex.Pattern` (Java 8).
Comment: @Oded and supposed I would use word boundary plus `^[.\p{L}]*$`? My regex is `"\\b(" + escaped + ")\\b"`, but in this way I will not match words like `però`, `lì`, etc.
Comment: @Oded asked as a separate question here https://stackoverflow.com/questions/55050211/javascript-regex-to-match-boundaries-of-words-with-diacritics


Page region CSS class not applied

Question: I am working with Drupal 8.5-x, I am trying to render HTML with bootstrap classes, but I am having trouble. Here is my problem:
I have highlighted (region) and content (region). I am trying to add a
 with highlighted region but to no avail.
I have:
{# Highlighted #}
  {%
    set highlighted_classes = [
      page.sidebar_first and page.sidebar_second ? 'col-sm-6',
      page.sidebar_first and page.sidebar_second is empty ? 'col-sm-9 col-md-8',
      page.sidebar_second and page.sidebar_first is empty ? 'col-sm-12',
      page.sidebar_first is empty and page.sidebar_second is empty ? 'col-sm-12'
    ]
  %}

{# Content #}
  {%
    set content_classes = [
      page.sidebar_first and page.sidebar_second ? 'col-sm-6',
      page.sidebar_first and page.sidebar_second is empty ? 'col-sm-12 col-md-12',
      page.sidebar_second and page.sidebar_first is empty ? 'col-sm-12',
      page.sidebar_first is empty and page.sidebar_second is empty ? 'col-sm-12'
    ]
  %}

when rendered, I get

but I was expecting

I am lost as to where I could have gone wrong.
My info file is as follows:
    regions:
  navigation: 'Navigation'
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'
  sidebar_second: 'Secondary'
  footer_first: 'First Footer'
  footer_second: 'Second Footer'
  footer_third: 'Third Footer'
  footer_fourth: 'Fourth Footer'
  footer_fifth: 'Fifth Footer'
  page_top: 'Page top'
  page_bottom: 'Page bottom'

Any help?
Answer: Nevermind I read on attributes: https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
The attribute I was referencing 'highlighted_attributes' was blank. I just added a simpler solution, by referecing to the example of the API:
{% set classes = [ 'red', 'green', 'blue' ] %}

Page region CSS class not applied


jquery / javascript - listen for change in window orientation mode on mobile devices

Question: I'm wondering if there's some sort of cross-device method of listening for orientation mode changes on mobile devices with jquery / javascript?
Comment: Are you using any specific javascript mobile framework like JQTouch or JQueryMobile?
Answer: This question explains how to do it using plain javascript for iPhone and Android Detect rotation of Android phone in the browser with JavaScript
Answer: JQuerymobile has an orientationchange event, check out their website for more info and demo's.
Comment: If I could figure out a way to implement just certain features of jquery mobile, that'd be great, but including their entire suite of features is a bit much.


Google AdMob Unity: Only test ads work (in Unity Editor) but no real ads

Question: My admob account is linked to the app in play store, status "ready", AdMob app ID also added into ad settings in Unity, added in the real ad unit ID, test ad showing in Unity, waited a week...
Result: no real ads
My event is calling RequestAndLoadInterstitialAd() and ShowInterstitialAd(), which works in Unity with the test ad. I expected it to work once the test ad implemented successfully.
<code>    using UnityEngine.Events;
    using UnityEngine;
    using GoogleMobileAds.Api;
    using GoogleMobileAds.Common;
    using UnityEngine.UI;
    using System;
    using System.Collections.Generic;

    public class GoogleAdMobController : MonoBehaviour
    {
        private AppOpenAd appOpenAd;
        private BannerView bannerView;
        private InterstitialAd interstitialAd;
        private RewardedAd rewardedAd;
        private RewardedInterstitialAd rewardedInterstitialAd;
        private float deltaTime;
        private bool isShowingAppOpenAd;
        public UnityEvent OnAdLoadedEvent;
        public UnityEvent OnAdFailedToLoadEvent;
        public UnityEvent OnAdOpeningEvent;
        public UnityEvent OnAdFailedToShowEvent;
        public UnityEvent OnUserEarnedRewardEvent;
        public UnityEvent OnAdClosedEvent;
        public bool showFpsMeter = true;
        public Text fpsMeter;
        public Text statusText;

        #region UNITY MONOBEHAVIOR METHODS

        public void Start()
        {
            MobileAds.SetiOSAppPauseOnBackground(true);

            List<String> deviceIds = new List<String>() { AdRequest.TestDeviceSimulator };

            // Add some test device IDs (replace with your own device IDs).
    #if UNITY_IPHONE
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #elif UNITY_ANDROID
            deviceIds.Add("b77a5c561934e089)--a185c62eba2497c95197140e5282b27a");
    #endif

            // Configure TagForChildDirectedTreatment and test device IDs.
            RequestConfiguration requestConfiguration =
                new RequestConfiguration.Builder()
                .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.Unspecified)
                .SetTestDeviceIds(deviceIds).build();
            MobileAds.SetRequestConfiguration(requestConfiguration);

            // Initialize the Google Mobile Ads SDK.
            MobileAds.Initialize(HandleInitCompleteAction);
        }

        private void HandleInitCompleteAction(InitializationStatus initstatus)
        {
            // Callbacks from GoogleMobileAds are not guaranteed to be called on
            // main thread.
            // In this example we use MobileAdsEventExecutor to schedule these calls on
            // the next Update() loop.
            MobileAdsEventExecutor.ExecuteInUpdate(() =>
            {
                statusText.text = "Initialization complete";
            //  RequestBannerAd();
            });
        }

        private void Update()
        {
            if (showFpsMeter)
            {
                fpsMeter.gameObject.SetActive(true);
                deltaTime += (Time.deltaTime - deltaTime) * 0.1f;
                float fps = 1.0f / deltaTime;
                fpsMeter.text = string.Format("{0:0.} fps", fps);
            }
            else
            {
                fpsMeter.gameObject.SetActive(false);
            }
        }

        #endregion

        #region HELPER METHODS

        private AdRequest CreateAdRequest()
        {
            return new AdRequest.Builder()
                .AddKeyword("unity-admob-sample")
                .Build();
        }

        public void OnApplicationPause(bool paused)
        {
            // Display the app open ad when the app is foregrounded.
            if (!paused)
            {
                ShowAppOpenAd();
            }
        }

        #endregion

        #region BANNER ADS

        public void RequestBannerAd()
        {
            statusText.text = "Requesting Banner Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/6300978111";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/2934735716";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up banner before reusing
            if (bannerView != null)
            {
                bannerView.Destroy();
            }

            // Create a 320x50 banner at top of the screen
            bannerView = new BannerView(adUnitId, AdSize.SmartBanner, AdPosition.Top);

            // Add Event Handlers
            bannerView.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            bannerView.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            bannerView.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            bannerView.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load a banner ad
            bannerView.LoadAd(CreateAdRequest());
        }

        public void DestroyBannerAd()
        {
            if (bannerView != null)
            {
                bannerView.Destroy();
            }
        }

        #endregion

        #region INTERSTITIAL ADS

        public void RequestAndLoadInterstitialAd()
        {
            // statusText.text = "Requesting Interstitial Ad.";

    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-2334240444886107/9358512518";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/4411468910";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Clean up interstitial before using it
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
            interstitialAd = new InterstitialAd(adUnitId);

            // Add Event Handlers
            interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

            // Load an interstitial ad
            interstitialAd.LoadAd(CreateAdRequest());
        }

        public void ShowInterstitialAd()
        {
            if (interstitialAd.IsLoaded())
            {
                interstitialAd.Show();
            }
            else
            {
                statusText.text = "Interstitial ad is not ready yet";
            }
        }

        public void DestroyInterstitialAd()
        {
            if (interstitialAd != null)
            {
                interstitialAd.Destroy();
            }
        }

        #endregion

        #region REWARDED ADS

        public void RequestAndLoadRewardedAd()
        {
            statusText.text = "Requesting Rewarded Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/5224354917";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/1712485313";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // create new rewarded ad instance
            rewardedAd = new RewardedAd(adUnitId);

            // Add Event Handlers
            rewardedAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
            rewardedAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
            rewardedAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
            rewardedAd.OnAdFailedToShow += (sender, args) => OnAdFailedToShowEvent.Invoke();
            rewardedAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();
            rewardedAd.OnUserEarnedReward += (sender, args) => OnUserEarnedRewardEvent.Invoke();

            // Create empty ad request
            rewardedAd.LoadAd(CreateAdRequest());
        }

        public void ShowRewardedAd()
        {
            if (rewardedAd != null)
            {
                rewardedAd.Show();
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        public void RequestAndLoadRewardedInterstitialAd()
        {
            statusText.text = "Requesting Rewarded Interstitial Ad.";

            // These ad units are configured to always serve test ads.
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
                string adUnitId = "ca-app-pub-3940256099942544/5354046379";
    #elif UNITY_IPHONE
                string adUnitId = "ca-app-pub-3940256099942544/6978759866";
    #else
            string adUnitId = "unexpected_platform";
    #endif

            // Create an interstitial.
            RewardedInterstitialAd.LoadAd(adUnitId, CreateAdRequest(), (rewardedInterstitialAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "RewardedInterstitialAd load failed, error: " + error;
                    });
                    return;
                }
                this.rewardedInterstitialAd = rewardedInterstitialAd;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "RewardedInterstitialAd loaded";
                });
                // Register for ad events.
                this.rewardedInterstitialAd.OnAdDidPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial presented.";
                    });
                };
                this.rewardedInterstitialAd.OnAdDidDismissFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial dismissed.";
                    });
                    this.rewardedInterstitialAd = null;
                };
                this.rewardedInterstitialAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Rewarded Interstitial failed to present.";
                    });
                    this.rewardedInterstitialAd = null;
                };
            });
        }

        public void ShowRewardedInterstitialAd()
        {
            if (rewardedInterstitialAd != null)
            {
                rewardedInterstitialAd.Show((reward) => {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "User Rewarded: " + reward.Amount;
                    });
                });
            }
            else
            {
                statusText.text = "Rewarded ad is not ready yet.";
            }
        }

        #endregion

        #region APPOPEN ADS

        public void RequestAndLoadAppOpenAd()
        {
            statusText.text = "Requesting App Open Ad.";
    #if UNITY_EDITOR
            string adUnitId = "unused";
    #elif UNITY_ANDROID
            string adUnitId = "ca-app-pub-3940256099942544/3419835294";
    #elif UNITY_IPHONE
            string adUnitId = "ca-app-pub-3940256099942544/5662855259";
    #else
            string adUnitId = "unexpected_platform";
    #endif
            // create new app open ad instance
            AppOpenAd.LoadAd(adUnitId, ScreenOrientation.Portrait, CreateAdRequest(), (appOpenAd, error) =>
            {
                if (error != null)
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "AppOpenAd load failed, error: " + error;
                    });
                    return;
                }
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd loaded. Please background the app and return.";
                });
                this.appOpenAd = appOpenAd;
            });
        }

        public void ShowAppOpenAd()
        {
            if (isShowingAppOpenAd)
            {
                return;
            }
            if (appOpenAd == null)
            {
                return;
            }
            // Register for ad events.
            this.appOpenAd.OnAdDidDismissFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd dismissed.");
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdFailedToPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = false;
                var msg = args.AdError.GetMessage();
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    statusText.text = "AppOpenAd present failed, error: " + msg;
                    if (this.appOpenAd != null)
                    {
                        this.appOpenAd.Destroy();
                        this.appOpenAd = null;
                    }
                });
            };
            this.appOpenAd.OnAdDidPresentFullScreenContent += (sender, args) =>
            {
                isShowingAppOpenAd = true;
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd presented.");
                });
            };
            this.appOpenAd.OnAdDidRecordImpression += (sender, args) =>
            {
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    Debug.Log("AppOpenAd recorded an impression.");
                });
            };
            this.appOpenAd.OnPaidEvent += (sender, args) =>
            {
                string currencyCode = args.AdValue.CurrencyCode;
                long adValue = args.AdValue.Value;
                string suffix = "AppOpenAd received a paid event.";
                MobileAdsEventExecutor.ExecuteInUpdate(() => {
                    string msg = string.Format("{0} (currency: {1}, value: {2}", suffix, currencyCode, adValue);
                    statusText.text = msg;
                });
            };
            appOpenAd.Show();
        }

        #endregion

        #region AD INSPECTOR

        public void OpenAdInspector()
        {
            statusText.text = "Open Ad Inspector.";

            MobileAds.OpenAdInspector((error) =>
            {
                if (error != null)
                {
                    string errorMessage = error.GetMessage();
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector failed to open, error: " + errorMessage;
                    });
                }
                else
                {
                    MobileAdsEventExecutor.ExecuteInUpdate(() => {
                        statusText.text = "Ad Inspector closed.";
                    });
                }
            });
        }

        #endregion
    }
</code>
Answer: There were two things wrong. One, I was using my live adUnit ID not the test one. The second issue was I was calling the load and show methods at the same time which worked in Unity, but on Android it seems there needs to be more time for the ad to load.
What I did to get the test ads on mobile device:

Set up the test device like HTugsadK said https://support.google.com/admob/answer/9691433

Change the adUnitId in RequestAndLoadInterstitialAd() to the interstitial test ID from here https://developers.google.com/admob/unity/test-ads#add_your_test_device_programmatically
For production this should be changed back to the real adUnitId.

Change the end of the RequestAndLoadInterstitialAd() method and Invoke the show method with a 5 second delay. Now in your event you only have to call this method.
<code> public void RequestAndLoadInterstitialAd()
     {
         // statusText.text = "Requesting Interstitial Ad.";

 #if UNITY_EDITOR
         string adUnitId = "unused";
 #elif UNITY_ANDROID
         string adUnitId = "ca-app-pub-3940256099942544/1033173712";
 #elif UNITY_IPHONE
         string adUnitId = "ca-app-pub-3940256099942544/4411468910";
 #else
         string adUnitId = "unexpected_platform";
 #endif

         // Clean up interstitial before using it
         if (interstitialAd != null)
         {
             interstitialAd.Destroy();
         }
         interstitialAd = new InterstitialAd(adUnitId);

         // Add Event Handlers
         interstitialAd.OnAdLoaded += (sender, args) => OnAdLoadedEvent.Invoke();
         interstitialAd.OnAdFailedToLoad += (sender, args) => OnAdFailedToLoadEvent.Invoke();
         interstitialAd.OnAdOpening += (sender, args) => OnAdOpeningEvent.Invoke();
         interstitialAd.OnAdClosed += (sender, args) => OnAdClosedEvent.Invoke();

         // Load an interstitial ad
         interstitialAd.LoadAd(CreateAdRequest());
         Invoke("ShowInterstitialAd", 5);
     }
</code>
Answer: If your test device (You can add this from Admob) shows your ADs as expected you should be fine. After some requests, your game will start to show real ads. Admob does not give real ads immediately, it needs some request to show real ads. But as I say you have to be sure your test devices show ads correctly.

And I also recommend check compatible admob SDK and Unity versions. Because they have bugs sometimes. You can check it in Admob GitHub page.
You can check here:

https://github.com/googleads/googleads-mobile-unity/releases
Comment: Does Unity running the test ad count as correct configuration? I am having a lot of trouble setting up a test device (phone not pairing in android studio)
Comment: Yes it counts, but I recommend adding a test device from Admob, in Admod settings, there is a test device adding a tab, you can add your Android device as a test device without Android Studio. You can check: https://support.google.com/admob/answer/9691433
Comment: Thank you I did that now, the message at the bottom of my phone screen says "initialization complete" but I still don't see a test ad in the phone
Comment: If you don't see any test ad (especially interstitial or rewarded) in your phone (or any physical test device), that means there is a problem with your Ad's call, I recommend checking log messages from your device with Unity and Visual Studio debug tool. Just check your adfailed or loaded event triggers (OnLoaded, OnFailed ...). For more info: https://answers.unity.com/questions/1320966/android-debug-usb.html
Comment: There are no such messages in the debugger from Unity, like I said the test ad comes up in Unity. My phone is also not paired up to Visual Studio, it can't find it at all and USB debugging is enabled. This is ridiculous, thanks anyway
Answer: Here Is The Solution
<code>public void Start()
{
    // When true all events raised by GoogleMobileAds will be raised
    // on the Unity main thread. The default value is false.
    MobileAds.RaiseAdEventsOnUnityMainThread = true;
    // Initialize the Google Mobile Ads SDK.
    MobileAds.Initialize((initStatus) =>
    {
        Dictionary<string, AdapterStatus> map = initStatus.getAdapterStatusMap();
        foreach (KeyValuePair<string, AdapterStatus> keyValuePair in map)
        {
            string className = keyValuePair.Key;
            AdapterStatus status = keyValuePair.Value;
            switch (status.InitializationState)
            {
                case AdapterState.NotReady:
                    // The adapter initialization did not complete.
                    MonoBehaviour.print("Adapter: " + className + " not ready.");
                    break;
                case AdapterState.Ready:
                    // The adapter was successfully initialized.
                    MonoBehaviour.print("Adapter: " + className + " is initialized.");
                    break;
            }
        }

        // This callback is called once the MobileAds SDK is initialized.
        LoadRewardedAd();

    });
}
</code>
This Works For Me, Real ads Are Appearing now in mobile version
Comment: I copied this from here https://developers.google.com/admob/unity/mediate