text:
Q: Estimator for Pareto Distribution & Delta Method
Assume that $Y$ has a Pareto distribution with parameters ($\theta, t$ = 1). An estimator of $\theta$ is $\tilde{\theta}$ where $\bar{Y} = \frac{\tilde{\theta}t}{\tilde{\theta} - 1}$. Solve for $\tilde{\theta}$ and then use the delta method to derive the asymptotic distribution of $\sqrt{n}(\tilde{\theta} - \theta)$, assuming $\theta$ > 2.

A good place to begin, if I am correct, is to assume $\bar{Y}$ = $\frac{\theta t}{\theta - 1}$. From there, we can solve for $\tilde{\theta}$. Except, this doesn't necessarily get rid of our random variable. Additionally, I'm confused about how this relates to the delta method. As someone utterly lost, can I get any help for this? Thanks!

A: Since $t=1$,
$$\bar{Y} = \frac{\tilde{\theta}}{\tilde{\theta} - 1} \implies \tilde \theta = \frac {\bar Y}{\bar Y-1}$$
We know the limiting distribution of
$$\sqrt{n}\left(\bar Y - \frac{\theta}{\theta-1}\right)$$
since it is the sample mean. Then we need the Delta method to find the limiting distribution of $\sqrt{n}\left(\tilde \theta - \theta\right)$, since $\theta$ is a non-linear  function of $\bar Y$. The $g$ function here is $g(z) = z/(z-1)$.
I guess the rest are up to the OP.


text:
Q: Show that $|z+1| = 2\cos(\frac{\theta}{2})$ Show that $|z+1| = 2\cos(\frac{\theta}{2})$, $z = cis(\theta)$ and $z \in C$
Here is what I have managed to do:

*

*$r=1$

*$(z+1)^2 = (\cos(\theta)+i\sin(\theta)+1)^2$

*$(z+1)^2 = (\cos^2(\theta)+2(i\sin(\theta)+1)\cos(\theta)+(i\sin(\theta)+1)^2)$

*$(z+1)^2 = (\cos^2(\theta)+2i\sin(\theta)\cos(\theta)+2\cos(\theta)+(-\sin^2(\theta)+2i\sin(\theta)+1))$
What I wanted to do was to take the square root of both sides to get the absolute value, however, I need to simplify the right-hand side first. I need help with that part

A: Hints:

*

*Given a point $z = a + bi$ in the complex plane, the magnitude of $z$ is $|z| = \sqrt{a^2 + b^2}$, from the Pythagorean theorem. Plot the point $z + 1 = a + bi + 1 = [a + 1] + bi$ on the complex plane, and determine the magnitude $|z+1|$ from there. Replace $a = \cos\theta$ and $b = \sin\theta$.

*Use the half-angle formula for cosine: $\cos\left(\frac{\theta}{2}\right) = \pm \sqrt{\frac{1+\cos(\theta)}{2}}$.

A: note that
$z = \text{cis}(\theta)$ and $1 = \text{cis}(0)$,
you can rewrite the function as
$|\text{cis}(\theta)+\text{cis }(0)|$
use the identity that
$ \text{cis}(x+y) = \text{cis}(x) \ \text{cis}(y)$ with $\frac{\theta}{2}$ from $\theta$ and $0$

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Entity Framework Delete child table (relational ) data and update parent table I am using Entity Framework to update record

User (Parent)
Email (Child)

UserId
EmailId

UserName
UserId

EmailAddress

in Child table , One user has multiple email address. When a user is updating then delete all child data and save the parent and child data. I dont have any issue in adding and deleting User data.
Please note that I have only Users table DbSet is accessible. I am using some other projects DbContext
Private async Task updateUser(User _user){
var user = _configurationDbContext.Users
                .Include(x => x.Emails)
                .Where(x => x.UserId == _user.UserId)
                .FirstOrDefault();

user.Emails.RemoveAll(x => x.UserId  == _user.Id);

_configurationDbContext.Users.Update(_user);

return await _configurationDbContext.SaveChangesAsync();

}

I am getting the below error
InvalidOperationException: The instance of entity type 'Users' cannot be tracked because another instance with the same key value for {'UserId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
Can I know how to achieve this using Users DbSet

A: The problem is that you have two different instances of User pointing to the same UserId.
As a workaround you could probably do the following:
private async Task updateUser(User _user) {
    var user = _configurationDbContext.Users
                .Include(x => x.Emails)
                .Where(x => x.UserId == _user.UserId)
                .FirstOrDefault();

    _configurationDbContext.Entry(_user).State = EntityState.Detached;
    user.Emails.RemoveAll(x => x.UserId  == _user.Id);

    _configurationDbContext.Users.Update(user);

    return await _configurationDbContext.SaveChangesAsync();
}

Beware that changes to _user will no longer be tracked by EF automatically after calling _configurationDbContext.Entry(_user).State = EntityState.Detached;

A: Try this:
var user = _configurationDbContext.Users
                .Include(x => x.Emails)
                .Where(x => x.UserId == _user.UserId)
                .FirstOrDefault();

user.Emails.RemoveAll(x => x.UserId  == _user.Id);
// or you can try
user.Emails.Clear();

_configurationDbContext.Entry(user).CurrentValues.SetValues(_user);

return await _configurationDbContext.SaveChangesAsync()


text:
Q: What am I missing from this K&R sample? The following is an excerpt from a code sample in K&R's The C Programming Language (section 8.7):
typedef long Align;

union header {
    struct {
        union header *ptr;
        unsigned size;
    } s;
    Align x;
};

typedef union header Header;

And here is the explanatory excerpt:

To simplify alignment, all blocks are
  multiples of the header size, and the
  header is aligned properly. This is
  achieved by a union that contains the
  desired header structure and an
  instance of the most restrictive type,
  which we have arbitrarily made a long.

So, as I understand it, the idea is to ensure that a header instance takes up a number of bytes that is a multiple of sizeof(Align). The goal makes perfect sense to me.
But consider the case where long is 64 bits, int is 32 bits, and a pointer is 64 bits. In that case, header.s will be 64+32 = 96 bits. Thus, sizeof(header) will be 96 bits, which is not a multiple of 64 as intended.
In such a case, I suppose it would be necessary to define Align as something else (perhaps double). But I'm not quite sure whether I'm fully understanding what would dictate that choice for a particular architecture. Is it just the "biggest" type? And what if long is the biggest type - couldn't it fail to work in the way I described above?
Thanks

A: The compiler will adjust the size of header so that ptr, size, and x can all be retrieved efficiently from elements in a header[] array.  On most architectures, the presence of x means that sizeof(header) will be increased to a multiple of sizeof(long).

A: The size of a union is at least as large as the size of its largest member.  So, even if sizeof(s) is 12 and sizeof(long) is 8, as in your example, you will still have sizeof(header) >= 12.  Likewise, the alignment of a union is largest alignment of any of its members, so the presence of the long member ensures that the alignment of header is at least the alignment of long, which would be 8 in this case.
If you compile this code, you will almost certainly find that sizeof(header) is 16, not 12.  The reason is that if you have an array of header objects, the compiler needs to ensure that the alignment of any of the members is proper, and arrays are stored contiguously in memory.  In order to achieve that, the size needs to be a multiple of the alignment.  The compiler does that by adding an extra 4 bytes of padding to the end of a header object.

A: It has been a long time since I worked with structs. But, I did use them a fair bit.  The main principle was to arrange members in descending alignment size order.
At the time this was written, long would align on the largest addressing boundary.  I believe this is still the case, but I haven't followed hardware issues for a long time.  Some hardware was designed so that longs were not efficiently addressed unless their address aligned with the size of long.
I believe the intent is that header will align on the next efficient addressing boundary for a long.  This is hardware dependent.  If longs are efficiently addressable on 32 bit boundaries, then the struct will align appropriately.  If longs are only efficiently addressable on 64 bit boundaries, then the struct will consume 128 bits to align appropriately.

A: It's been a long time (way too long) since I read the K&R book, but I believe you are right. You would need to typedef Align to something at least the size of pointer on the platform in question + sizeof unsigned.
My guess is that when this was written (and last updated), 32-bit OS's reigned supreme and your scenario escaped the writers and editors. Of course, they are much smarter/wiser and I and I could be off the mark.

A: To be correct, sizeof(Align) must be greater or equal to sizeof(s). But today's compiler really don't care, and do the job for you.
#include <limits.h>
#include <stdio.h>

typedef long Align;

typedef union header {
    struct {
        union header *ptr;  /* 64 bits */
        unsigned size;    /* 32 bits */
    } s;                    /* subtotal 96 */
    Align x;                /* 64 bits -> should be greater than 96 */
} Header;                  /* total 128 bits */

typedef struct hair {
    union header *ptr;  /* 64 bits */
    unsigned size;      /* 32 bits */
} Hair;              /* subtotal 96 */

int main(void)
{
    Header u;
    Hair h;

    printf("char %ld bits, %ld bytes\n", sizeof(char)*CHAR_BIT,(sizeof(char)*CHAR_BIT)/8);
    printf("unsigned %ld bits, %ld bytes\n", sizeof(unsigned)*CHAR_BIT,(sizeof(unsigned)*CHAR_BIT)/8);
    printf("int %ld bits, %ld bytes\n", sizeof(int) * CHAR_BIT, (sizeof(int) * CHAR_BIT)/8);
    printf("long int %ld bits, %ld bytes\n", sizeof(long) * CHAR_BIT, (sizeof(long) * CHAR_BIT)/8);
    printf("long long int %ld bits, %ld bytes\n", sizeof(long long) * CHAR_BIT, (sizeof(long long) * CHAR_BIT)/8);
    printf("float %ld bits, %ld bytes\n", sizeof(float) * CHAR_BIT, (sizeof(float) * CHAR_BIT)/8);
    printf("double %ld bits, %ld bytes\n", sizeof(double) * CHAR_BIT, (sizeof(double) * CHAR_BIT)/8);
    printf("long double %ld bits, %ld bytes\n\n", sizeof(long double) * CHAR_BIT, (sizeof(long double) * CHAR_BIT)/8);
    printf("Header u %ld bits, %ld bytes\n", sizeof(u) * CHAR_BIT, (sizeof(u) * CHAR_BIT)/8);
    printf("Header *ptr %ld bits, %ld bytes\n", sizeof(u.s.ptr) * CHAR_BIT, (sizeof(u.s.ptr) * CHAR_BIT)/8);
    printf("Header size %ld bits, %ld bytes\n", sizeof(u.s.size) * CHAR_BIT, (sizeof(u.s.size) * CHAR_BIT)/8);
    printf("Header x %ld bits, %ld bytes\n\n", sizeof(u.x) * CHAR_BIT, (sizeof(u.x) * CHAR_BIT)/8);
    printf("Hair h %ld bits, %ld bytes\n", sizeof(h) * CHAR_BIT, (sizeof(h) * CHAR_BIT)/8);
    printf("Hair *ptr %ld bits, %ld bytes\n", sizeof(h.ptr) * CHAR_BIT, (sizeof(h.ptr) * CHAR_BIT)/8);
    printf("Hair size %ld bits, %ld bytes\n", sizeof(h.size) * CHAR_BIT, (sizeof(h.size) * CHAR_BIT)/8);
    return 0;
}

The output is:
$ ./union-limits
char 8 bits, 1 bytes
unsigned 32 bits, 4 bytes
int 32 bits, 4 bytes
long int 64 bits, 8 bytes
long long int 64 bits, 8 bytes
float 32 bits, 4 bytes
double 64 bits, 8 bytes
long double 128 bits, 16 bytes

Header u 128 bits, 16 bytes
Header *ptr 64 bits, 8 bytes
Header size 32 bits, 4 bytes
Header x 64 bits, 8 bytes

Hair h 128 bits, 16 bytes
Hair *ptr 64 bits, 8 bytes
Hair size 32 bits, 4 bytes

As you can see, Hair is the same size of Header. But for compilers that don't do the job, the correct is to use long double as Align.
Take care,
Beco.


text:
Q: How to calculate the approximate gradient of a series of points? The situation is this: a series of points are randomly located, a line is needed to represent the gradient of those points.
  ./
  /  .

.  /
   ./
   /  .
I am a programmer but not math expert, I need the method to find such a line. Can anyone give me some direction?
Thanks in advance.

A: There is a technique called "least squares linear fit." Those keywords should help you find a discussion in a textbook or on the web.


text:
Q: Slider JQuery UI - Suavizar movimiento He incluido el siguiente slider, pero no encuentro las opciones para que no se mueva con los steps, es decir, de un punto a otro de forma brusca al no haber muchos valores, sino que lo pueda mover de forma suave.
JSFiddle: https://jsfiddle.net/43tpdr6L/

var initialValue = 4;
var sliderTooltip = function(event, ui) {
  var curValue = ui.value || initialValue;
  var tooltip = '

' + curValue + 'años

';

  $('.ui-slider-handle').html(tooltip);

}
$(document).ready(function() {
  $("#gs1").slider({
    range: "min",
    min: 3,
    max: 8,
    value: initialValue,
    create: sliderTooltip,
    slide: sliderTooltip,
    animate: true
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.slider {
  text-align: center;
  margin-top: 100px;
}

.slider .plazo {
  display: inline-block;
  vertical-align: middle;
  font-family: 'Avenir-Heavy';
  color: #007BC6;
  font-size: 20px;
  margin-right: 10px;
}

.tooltip-slider {
  position: absolute;
  z-index: 1020;
  display: block;
  padding: 5px;
  font-size: 11px;
  visibility: visible;
  margin-top: -2px;
  bottom: 25px;
  left: 50%;
  transform: translate(-50%, 0);
}

.tooltip-slider .tooltip-arrow {
  bottom: 0;
  left: 50%;
  margin-left: -5px;
  position: absolute;
  z-index: 1;
  width: 20px;
  height: 20px;
  background-color: #4a4a4a;
  transform: rotate(45deg) translate(0%, 30%);
  transform-origin: center;
  border-radius: 4px;
}

.tooltip-inner {
  max-width: 200px;
  padding: 3px 10px;
  color: #ffffff;
  text-align: center;
  text-decoration: none;
  background-color: #4A4A4A;
  position: relative;
  z-index: 2;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

.tooltip-inner span {
  display: block;
  font-family: 'Avenir-Medium';
  font-size: 20px;
}

.tooltip-inner span.last {
  font-size: 16px;
}

.slider-anyos {
  display: inline-block;
  vertical-align: middle;
  position: relative;
}

.slider-anyos .anyos {
  position: absolute;
  left: 0;
  top: 100%;
  font-size: 20px;
  font-family: 'Avenir-Medium';
}

.slider-anyos .anyos.last {
  left: inherit;
  right: 0;
}

.ui-slider {
  background-color: #D8D8D8;
  border-radius: 100px;
  height: 6px;
  margin: 0;
  width: 560px;
  padding: 0px;
  border: 0 !important;
}

.ui-slider-handle {
  background: #ED6B51;
  border-bottom: 1px solid #a8a79f;
  border-right: 1px solid #a8a79f;
  height: 20px;
  width: 10px;
  margin: 0;
  padding: 0px;
  display: inline-block;
}

.ui-slider-range {
  height: 10px;
  border-bottom: 3px solid red;
  position: relative;
}

.ui-slider-range-min {
  background-color: #007BC6;
}

.ui-slider-handle {
  background: #007BC6 !important;
  border: 5px solid #fff !important;
  border-radius: 100px !important;
  box-shadow: 0 4px 8px 0px rgba(0, 0, 0, .2);
  height: 20px !important;
  width: 20px !important;
  padding: 0px !important;
  display: inline-block !important;
  top: -7px !important;
  outline: 0;
  cursor: pointer !important;
}

<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">

Plazo

3

8

He probado también con la opción steps: 0 pero no consigo.
¿Alguna idea que pueda aplicar?

A: Una idea rápida: Pon 10x veces mas valores, en tu caso, del 30 al 80 y luego en todos los usos lo divides por 10 y le haces un floor.
Ejemplo:

var initialValue = 4;
var sliderTooltip = function(event, ui) {
  var curValue = ui.value || initialValue;
  var tooltip = '

' + Math.floor(curValue/10) + 'años

';

  $('.ui-slider-handle').html(tooltip);

}
$(document).ready(function() {
  $("#gs1").slider({
    range: "min",
    min: 30,
    max: 80,
    value: initialValue,
    create: sliderTooltip,
    slide: sliderTooltip,
    animate: true
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.slider {
  text-align: center;
  margin-top: 100px;
}

.slider .plazo {
  display: inline-block;
  vertical-align: middle;
  font-family: 'Avenir-Heavy';
  color: #007BC6;
  font-size: 20px;
  margin-right: 10px;
}

.tooltip-slider {
  position: absolute;
  z-index: 1020;
  display: block;
  padding: 5px;
  font-size: 11px;
  visibility: visible;
  margin-top: -2px;
  bottom: 25px;
  left: 50%;
  transform: translate(-50%, 0);
}

.tooltip-slider .tooltip-arrow {
  bottom: 0;
  left: 50%;
  margin-left: -5px;
  position: absolute;
  z-index: 1;
  width: 20px;
  height: 20px;
  background-color: #4a4a4a;
  transform: rotate(45deg) translate(0%, 30%);
  transform-origin: center;
  border-radius: 4px;
}

.tooltip-inner {
  max-width: 200px;
  padding: 3px 10px;
  color: #ffffff;
  text-align: center;
  text-decoration: none;
  background-color: #4A4A4A;
  position: relative;
  z-index: 2;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

.tooltip-inner span {
  display: block;
  font-family: 'Avenir-Medium';
  font-size: 20px;
}

.tooltip-inner span.last {
  font-size: 16px;
}

.slider-anyos {
  display: inline-block;
  vertical-align: middle;
  position: relative;
}

.slider-anyos .anyos {
  position: absolute;
  left: 0;
  top: 100%;
  font-size: 20px;
  font-family: 'Avenir-Medium';
}

.slider-anyos .anyos.last {
  left: inherit;
  right: 0;
}

.ui-slider {
  background-color: #D8D8D8;
  border-radius: 100px;
  height: 6px;
  margin: 0;
  width: 560px;
  padding: 0px;
  border: 0 !important;
}

.ui-slider-handle {
  background: #ED6B51;
  border-bottom: 1px solid #a8a79f;
  border-right: 1px solid #a8a79f;
  height: 20px;
  width: 10px;
  margin: 0;
  padding: 0px;
  display: inline-block;
}

.ui-slider-range {
  height: 10px;
  border-bottom: 3px solid red;
  position: relative;
}

.ui-slider-range-min {
  background-color: #007BC6;
}

.ui-slider-handle {
  background: #007BC6 !important;
  border: 5px solid #fff !important;
  border-radius: 100px;
  box-shadow: 0 4px 8px 0px rgba(0, 0, 0, .2);
  height: 20px !important;
  width: 20px !important;
  padding: 0px !important;
  display: inline-block !important;
  top: -7px !important;
  outline: 0;
  cursor: pointer !important;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

Plazo

3

8

O quizá interese mas hacer un Math.round:

var initialValue = 4;
var sliderTooltip = function(event, ui) {
  var curValue = ui.value || initialValue;
  var tooltip = '

' + Math.round(curValue/10) + 'años

';

  $('.ui-slider-handle').html(tooltip);

}
$(document).ready(function() {
  $("#gs1").slider({
    range: "min",
    min: 30,
    max: 80,
    value: initialValue,
    create: sliderTooltip,
    slide: sliderTooltip,
    animate: true
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.slider {
  text-align: center;
  margin-top: 100px;
}

.slider .plazo {
  display: inline-block;
  vertical-align: middle;
  font-family: 'Avenir-Heavy';
  color: #007BC6;
  font-size: 20px;
  margin-right: 10px;
}

.tooltip-slider {
  position: absolute;
  z-index: 1020;
  display: block;
  padding: 5px;
  font-size: 11px;
  visibility: visible;
  margin-top: -2px;
  bottom: 25px;
  left: 50%;
  transform: translate(-50%, 0);
}

.tooltip-slider .tooltip-arrow {
  bottom: 0;
  left: 50%;
  margin-left: -5px;
  position: absolute;
  z-index: 1;
  width: 20px;
  height: 20px;
  background-color: #4a4a4a;
  transform: rotate(45deg) translate(0%, 30%);
  transform-origin: center;
  border-radius: 4px;
}

.tooltip-inner {
  max-width: 200px;
  padding: 3px 10px;
  color: #ffffff;
  text-align: center;
  text-decoration: none;
  background-color: #4A4A4A;
  position: relative;
  z-index: 2;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

.tooltip-inner span {
  display: block;
  font-family: 'Avenir-Medium';
  font-size: 20px;
}

.tooltip-inner span.last {
  font-size: 16px;
}

.slider-anyos {
  display: inline-block;
  vertical-align: middle;
  position: relative;
}

.slider-anyos .anyos {
  position: absolute;
  left: 0;
  top: 100%;
  font-size: 20px;
  font-family: 'Avenir-Medium';
}

.slider-anyos .anyos.last {
  left: inherit;
  right: 0;
}

.ui-slider {
  background-color: #D8D8D8;
  border-radius: 100px;
  height: 6px;
  margin: 0;
  width: 560px;
  padding: 0px;
  border: 0 !important;
}

.ui-slider-handle {
  background: #ED6B51;
  border-bottom: 1px solid #a8a79f;
  border-right: 1px solid #a8a79f;
  height: 20px;
  width: 10px;
  margin: 0;
  padding: 0px;
  display: inline-block;
}

.ui-slider-range {
  height: 10px;
  border-bottom: 3px solid red;
  position: relative;
}

.ui-slider-range-min {
  background-color: #007BC6;
}

.ui-slider-handle {
  background: #007BC6 !important;
  border: 5px solid #fff !important;
  border-radius: 100px;
  box-shadow: 0 4px 8px 0px rgba(0, 0, 0, .2);
  height: 20px !important;
  width: 20px !important;
  padding: 0px !important;
  display: inline-block !important;
  top: -7px !important;
  outline: 0;
  cursor: pointer !important;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

Plazo

3

8

A: Una cosa que podrías hacer es poner el step a un valor pequeño como .1 o .01, de ese modo la animación será más fluida (mientras menor sea el número más pasos habrá y más fluido se verá).
Entonces el problema es que el valor ya no es un número entero sino que tendrá decimales y eso no es lo que quieres que se muestre en el tooltip cuando se mueve el slider. Lo que harías entonces es que redondearías el valor (en mi ejemplo he redondeado hacia abajo usando floor round, pero podrías redondear usando round floor o ceil, el que mejor que venga).

Inicialmente usaba floor, pero entonces era dificil seleccionar el número 8. Usando round es más fácil seleccionar los valores de los extremos

Por último deberías crear un controlador del evento stop que hará que cuando se suelte el slider sí que salte al valor correspondiente (haciendo algo parecido al redondeo de arriba y asignando el nuevo valor con "value").
Aquí lo puedes ver funcionando:

var initialValue = 4;
var sliderTooltip = function(event, ui) {
  var curValue = Math.round(ui.value || initialValue);
  var tooltip = '

' + curValue + 'años

';

  $('.ui-slider-handle').html(tooltip);

}

var stopTooltip = function(event, ui) {
  var curValue = Math.round(ui.value || initialValue);
  $("#gs1").slider("value", curValue);
}

$(document).ready(function() {
  $("#gs1").slider({
    range: "min",
    min: 3,
    max: 8,
    value: initialValue,
    create: sliderTooltip,
    slide: sliderTooltip,
    stop: stopTooltip,
    animate: true,
    step:0.01
  });
});
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.slider {
  text-align: center;
  margin-top: 100px;
}

.slider .plazo {
  display: inline-block;
  vertical-align: middle;
  font-family: 'Avenir-Heavy';
  color: #007BC6;
  font-size: 20px;
  margin-right: 10px;
}

.tooltip-slider {
  position: absolute;
  z-index: 1020;
  display: block;
  padding: 5px;
  font-size: 11px;
  visibility: visible;
  margin-top: -2px;
  bottom: 25px;
  left: 50%;
  transform: translate(-50%, 0);
}

.tooltip-slider .tooltip-arrow {
  bottom: 0;
  left: 50%;
  margin-left: -5px;
  position: absolute;
  z-index: 1;
  width: 20px;
  height: 20px;
  background-color: #4a4a4a;
  transform: rotate(45deg) translate(0%, 30%);
  transform-origin: center;
  border-radius: 4px;
}

.tooltip-inner {
  max-width: 200px;
  padding: 3px 10px;
  color: #ffffff;
  text-align: center;
  text-decoration: none;
  background-color: #4A4A4A;
  position: relative;
  z-index: 2;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  border-radius: 4px;
}

.tooltip-inner span {
  display: block;
  font-family: 'Avenir-Medium';
  font-size: 20px;
}

.tooltip-inner span.last {
  font-size: 16px;
}

.slider-anyos {
  display: inline-block;
  vertical-align: middle;
  position: relative;
}

.slider-anyos .anyos {
  position: absolute;
  left: 0;
  top: 100%;
  font-size: 20px;
  font-family: 'Avenir-Medium';
}

.slider-anyos .anyos.last {
  left: inherit;
  right: 0;
}

.ui-slider {
  background-color: #D8D8D8;
  border-radius: 100px;
  height: 6px;
  margin: 0;
  width: 560px;
  padding: 0px;
  border: 0 !important;
}

.ui-slider-handle {
  background: #ED6B51;
  border-bottom: 1px solid #a8a79f;
  border-right: 1px solid #a8a79f;
  height: 20px;
  width: 10px;
  margin: 0;
  padding: 0px;
  display: inline-block;
}

.ui-slider-range {
  height: 10px;
  border-bottom: 3px solid red;
  position: relative;
}

.ui-slider-range-min {
  background-color: #007BC6;
}

.ui-slider-handle {
  background: #007BC6 !important;
  border: 5px solid #fff !important;
  border-radius: 100px !important;
  box-shadow: 0 4px 8px 0px rgba(0, 0, 0, .2);
  height: 20px !important;
  width: 20px !important;
  padding: 0px !important;
  display: inline-block !important;
  top: -7px !important;
  outline: 0;
  cursor: pointer !important;
}

<link rel="stylesheet" type="text/css" href="//code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">

Plazo

3

8


text:
Q: How do you write a function that returns the low and the top of the moving average for a specified number of candles in mql4? I hope someone guides me,
I want to calculate the lowest moving average level during a certain number of candles, as well as the highest moving average level during a certain number of candles.
That is, I want the moving average top and the moving average bottom, not the price.
How do I write a function that returns these values to me?
Thank you for your interest and help

A: You should try to attempt to write the code yourself, you will learn a lot more and get more help along the way when you hit any problems.
int startCandle=1;
int endCandle=100;
double highest=NULL, lowest=NULL;
for(int i=startCandle; i<=endCandle; i++)
{
   double ma=iMA(NULL, 0, 10, 0, MODE_SMA, PRICE_CLOSE, i);
   if(highest==NULL){highest=ma; lowest=highest;}
   if(ma>highest) highest=ma;
   if(ma<lowest) lowest=ma;
}


text:
Q: TypeError: Cannot read properties of undefined (reading 'length') JEST test I am trying to implement jest tests to my project but I have error while running test. The thing is that I dont really have length method in code that I am trying to test. It looks from like it occurs in styled-components. Is there any way to fix it or maybe I am interpreting it wrong?
test
import React from "react";
import { render, screen } from "@testing-library/react";
import ChatBubblesContainer from "./ChatBubblesContainer";

let chats = [];

const mockUseContext = jest.fn().mockImplementation(() => ({
  chats: [],
}));

React.useContext = mockUseContext;

describe("test", () => {
  test("render", () => {
    render(<ChatBubblesContainer />);
    expect(screen.getByTestId("bubbles-container")).toBeInTheDocument();
  });
});

error
TypeError: Cannot read properties of undefined (reading 'length')

      20 | describe("test", () => {
      21 |   test("render", () => {
    > 22 |     render(<ChatBubblesContainer />);
         |           ^
      23 |     expect(screen.getByTestId("bubbles-container")).toBeInTheDocument();
      24 |   });
      25 | });

      at charCodeAt (node_modules/styled-components/src/utils/hash.js:13:22)
      at e.hash [as generateAndInjectStyles] (node_modules/styled-components/src/models/ComponentStyle.js:80:53)
      at generateAndInjectStyles (node_modules/styled-components/src/models/StyledComponent.js:87:22)
      at node_modules/styled-components/src/models/StyledComponent.js:129:30
      at displayName (node_modules/styled-components/src/models/StyledComponent.js:247:14)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:16305:18)

A: this appears when the jest cannot identify some specific methods from specific methods use this code
jest.mock('PACKAGE NAME' , () => {
  MISSING VARIABLE OR FUNCTION IN ERROR DESCRIPTION : () =>  jest.fn();

})


text:
Q: Sorting element to the top of an array I'm trying to apply a custom sorting comparator to a gulp stream (so I don't have the ability to customize the array). I'm trying to sort everything alphabetically except for a single shared file, which should be sorted to the very top.
Running a simple jsbin test though, I'm seeing the same problem - the file I need at the top isn't sorting correctly.
var files = [
  'app/modules/t.css',
  'app/shared/dialogs/c.css',
  'app/shared/directives/m.css',
  'app/shared/scss/app.css',
  'app/shared/modals/a.css',
  'app/shared/modals/b.css'
];

files.sort(function(file1, file2) {
  var sort = 0;

  if (file1.indexOf('shared/scss') > -1) {
     sort = -1;
  } else {
     sort = file1.localeCompare(file2);
  }

  return sort;
});

The resulting output is incorrect, app/shared/scss/app.css has only moved up twice.
"app/modules/t.css"
"app/shared/dialogs/c.css"
"app/shared/directives/m.css"
"app/shared/scss/app.css"
"app/shared/modals/a.css"
"app/shared/modals/b.css"

Here's what I'm expecting:
"app/shared/scss/app.css"
"app/modules/t.css"
"app/shared/dialogs/c.css"
"app/shared/directives/m.css"
"app/shared/modals/a.css"
"app/shared/modals/b.css"

A: Well, file1 isn't the only variable that could contain app/shared/scss/app.css, there's also file2. In your sort function, you're only checking file1.
So, this sort function should behave the way you intended it to:
files.sort((file1, file2) => {
    let sort = 0, substring = "shared/scss";
    if (file1.includes(substring)) {
        sort = -1;
    }
    else if (file2.includes(substring)) {
        sort = 1;
    }
    else {
        sort = file1.localeCompare(file2);
    }
    return sort;
});

A: You're checking if file1 contains shared/scss, but you're not checking if file2 contains it. Add another condition, file2.indexOf('shared/scss') > -1, and if it's true, set sort to 1 to make file2 appear on the top.
var files = [
  'app/modules/t.css',
  'app/shared/dialogs/c.css',
  'app/shared/directives/m.css',
  'app/shared/scss/app.css',
  'app/shared/modals/a.css',
  'app/shared/modals/b.css'
];

files.sort(function(file1, file2) {
  var sort = 0;
  if (file1.indexOf('shared/scss') > -1) {
     sort = -1;
  } else if (file2.indexOf('shared/scss') > -1) {
     sort = 1;
  } else {
     sort = file1.localeCompare(file2);
  }

  return sort;
});

A: This is a proposal which moves 'shared/scss' to top.

var files = ['app/modules/t.css', 'app/shared/dialogs/c.css', 'app/shared/directives/m.css', 'app/shared/scss/app.css', 'app/shared/modals/a.css', 'app/shared/modals/b.css'];

files.sort(function (a, b) {
    var aa = +!a.match(/shared\/scss/),
        bb = +!b.match(/shared\/scss/);
    return aa - bb || a.localeCompare(b);
});
document.write('<pre> ' + JSON.stringify(files, 0, 4) + '</pre>');


text:
Q: Correct way to evaluate partial derivatives for a coordinate transform? This question occurred to me when thinking about differential geometry change of coordinates. Consider the system of equations:
\begin{align*}
p(x, y) = x + y &\qquad x(p, q) = p - q \\
q(x, y) = y &\qquad y(p, q) = q
\end{align*}
Now, if I wish to evaluate $\frac{dp}{dq}$, there are two evaluation strategies available for me:
\begin{align*}
\frac{dp}{dq} = \frac{d(x+y)}{dy} =
\frac{dx}{dy} + \frac{dy}{dy} = 0 + 1 = 1 \qquad (1)
\end{align*}
One the other hand, consider this evaluation:
\begin{align*}
\frac{dp}{dq} = \frac{dp}{dx}\frac{dx}{dq} + \frac{dp}{dy}\frac{dy}{dq} =
1  \cdot -1 + 1 \cdot 1 = 0 \qquad (2)
\end{align*}
Indeed, one can prove something much stronger: Let $p_i = f_i(x_1, x_2, \dots x_n)$. Now, the evaluation
\begin{align*}
\frac{dp_i}{dp_j}
= \sum_{k=0}^n \frac{dp_i}{dx_k} \frac{dx_k}{dp_j}
=
\left[\frac{dp_i}{dx_0} \dots \frac{dp_i}{dx_k} \dots  \frac{dp_i}{dx_n} \right] \cdot
  \left[ \frac{dx_0}{dp_j}  \dots \frac{dx_k}{dp_j} \dots \frac{dx_n}{dp_j}  \right]^T = (J \cdot J^{-1})_{ij} = \delta_{ij}
\end{align*}
where $J$ is the jacobian of the function $\vec p = f(\vec x)$, and $\delta_{ij}$ is the kronecker delta.
I'm puzzled as to which interpretation I should choose. Interpretation (2) is nice if I want to think of the sets of "co-ordinate systems" $\{ p_i \}$ as being linearly independent, just like the original $\{ x_i \}$ are, but I have no idea if this is legal.
I'd love an answer that explains to me when (1) is legal, when (2) is legal, and maybe go into more detail about the relationship with the Jacboian, and related geometric insights!

A: $(1)$ and $(2)$ do not make sense as written but I think we can make sense of the third calculation in the following, more general way: for convenience, work in $\mathbb R^2;\ $ the extension to $\mathbb R^n$ is obvious.
Fix $(x,y)\in \mathbb R^2,$ le $r^1,r^2$ be the standard coordinates on $\mathbb R^2$, so that $r^1:\mathbb R^2\to \mathbb R$ is projection on the first coordinate and $r^2:\mathbb R^2\to \mathbb R$ is projection on the second coordinate. (This is why, by the way, $\frac{\partial r^i}{\partial r^j}=\delta^i_j.)$
Let the diffeomorphism $\phi:\mathbb R^2\to \mathbb R^2$ be defined by $(p^1(x,y),p^2(x,y))$ Suppose $f:\mathbb R^2\to \mathbb R$ is smooth. We want to make sense of $\frac{\partial f}{\partial p^i}\Big|_p$ for $i=1,2.$ By itself, it has no intrinsic meaning. But $\frac{\partial (f\circ \phi^{-1})}{\partial r^i}\Big|_{\phi(p)}\ \textit{does}$ make sense: it is just the usual partial derivative of $f\circ \phi^{-1}$ at $\phi(p).$ So we $\textit{define}\ \frac{\partial f}{\partial p^i}\Big|_p$ to be  $\frac{\partial (f\circ \phi^{-1})}{\partial r^i}\Big|_{\phi(p)}.$ This may seem silly, but it's only because we are working in a Euclidean space $\mathbb R^2$. If we were considering a more abstract space, this definition would in some sense be forced.
Notice now that $p^i=r^i\circ \phi,$ so taking $f=p^i:\mathbb R^2\to \mathbb R$ we have
$\frac{\partial p^i}{\partial p^j}\Big|_p=\frac{\partial (p^i\circ \phi^{-1})}{\partial r^j}\Big|_{\phi(p)}=\frac{\partial (r^i\circ \phi \circ \phi^{-1})}{\partial r^j}\Big|_{\phi(p)}=\frac{\partial r^i}{\partial r^j}\Big|_{\phi(p)}=\delta^i_j.$
Now, your $\phi(x,y)=(x+y,y)$ is a diffeomorphism, so the above applies to it.
Final remark: it is precisely because of our definition of $\frac{\partial f}{\partial p^i}$ that we can manipulate these symbols "in the usual way.". Of course, $\phi^{-1}$ is also a diffeomorphism because $J(\phi)\neq 0$, so your chain rule calculation amounts to showing that the the Jacobian of the identity map is the identity matrix!

A: (1) is in a somewhat weird position because it is in effect using $\{x,q\}$ as the coordinate system and then treating $p$ as a function on $x$ and $q$. When you write $\frac{d(x+y)}{dy}=1$ (more typically written with a partial derivative $\frac{\partial(x+y)}{\partial y}=1$), you are computing this partial derivative keeping $x$ fixed.
(2) is the more typical way of interpreting $\frac{dp}{dq}$ (or $\frac{\partial p}{\partial q}$), because it is treating $p$ as a function of $p$ and $q$ (strictly, it's treating $p$ as a function of $x$ and $y$, which are themselves treated as functions of $p$ and $q$, but the actual function will not be affected). The partial derivative in $\frac{dx}{dq}$ or $\frac{dy}{dq}$ takes $p$ as fixed, and the derivative of $p$ when we $p$ to be fixed is of course 0.
One notation that I believe is more commonly used in physics may be helpful. We indicate the variable that is held fixed outside a pair of parentheses. In this case, (1) will be written as
$$\left(\frac{\partial p}{\partial q}\right)_x$$
while (2) will be written as
$$\left(\frac{\partial p}{\partial q}\right)_p$$

A: Coordinates transform according to the rule of differentials via the Jacobian matrix, for example in two dimensions:
\begin{align}
\epsilon & = \epsilon(x,y), \quad \Delta\epsilon = \frac{\partial\epsilon}{\partial x}\Delta x + \frac{\partial\epsilon}{\partial y} \Delta y \\
\eta & = \eta(x,y), \quad \Delta\eta = \frac{\partial\eta}{\partial x}\Delta x + \frac{\partial\eta}{\partial y} \Delta y
\end{align}
$$ J = \begin{bmatrix} \frac{\partial\epsilon}{\partial x} & \frac{\partial\epsilon}{\partial y} \\ \frac{\partial\eta}{\partial x} & \frac{\partial\eta}{\partial y} \end{bmatrix} $$
Let $f\colon \mathbb R^2 \to \mathbb R^2$ denote a coordinate transformation such that $f[(x,y)] = (\epsilon(x,y), \eta(x,y))$. Consider $\epsilon(x,y) = x + y,\, \eta(x,y) = y$. Its Jacobian is:
$$ J = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix} $$
Now consider a scalar field $\phi\colon \mathbb R^2 \to \mathbb R$. It transforms under the coordinate transformation as $\phi(x,y) \stackrel{f} \mapsto \phi'(\epsilon,\eta)$. Its gradient $\nabla_{(x,y)}\phi(x,y)$ transforms to $\nabla_{(\epsilon,\eta)}\phi(x,y)$ according to the chain rule:
\begin{align*}
\frac{\partial \phi}{\partial \epsilon} & = \frac{\partial \phi}{\partial x}\frac{\partial x}{\partial \epsilon} + \frac{\partial \phi}{\partial y}\frac{\partial y}{\partial \epsilon} \\
\frac{\partial \phi}{\partial \eta} & = \frac{\partial \phi}{\partial x}\frac{\partial x}{\partial \eta} + \frac{\partial \phi}{\partial y}\frac{\partial y}{\partial \eta}
\end{align*}
Now let $\phi = \epsilon$ or $\phi  = \eta$ and the computations follow along the line of $(2)$ in your question in the appropriate notation. For a geometric interpretation of the limiting behaviour of the change of coordinates with respect to their variables, this would also be equivalent to, for example, $\lim_\limits{\Delta \eta \to 0} \Delta\epsilon/\Delta\eta$ from the coordinate transformation rules shown in the beginning.
Note that you've treated $dp/dq = dp/dy$ in $(1)$, but $x$ and $y$ are independent while $x$ and $q$ are not (recall $x(x,y) = x,\, x(p,q) = p - q$), so $dx/dq \neq dx/dy$ and hence the treatment is incorrect because it doesn't follow the transformation rules.


text:
Q: Namespace declaration In the TypeScript documentation, namespaces are being called as internal TypeScript modules and for using them as reference inside individual files we have to add a ref header to the namespace such as: /// <reference path="Validation.ts" /> as mentioned in the documentation. However, we could also export and declare the namespace with: export declare namespace MyNameSpace and then import it into any other entity. Is there any reason we are being adviced to use header ref tag instead of export of namespace declaration.
After hearing the first answer regarding the order of compilation and runtime, I thought maybe it's better to provide an example, here is a simple greeting app that contains three mains files with declared namespace (which I doubt we even need to import when we want to use it within our application scope)
Filename: GreetingApp.ts

export declare namespace GreetingApp {}

Filename: Hello.ts

namespace GreetingApp {
    export class Hello {
        constructor(private name: string) {
            this.name = name.toLowerCase().charAt(0).toUpperCase() + name.substr(1).toLowerCase();
        }

        public toString(): string {
            return "Hello! " + this.name;
        }
    }
}

Filename: Bye.ts

namespace GreetingApp {
    export class Bye {
        constructor(private name: string) {
            this.name = name.toLowerCase().charAt(0).toUpperCase() + name.substr(1).toLowerCase();
        }

        public toString(): string {
            return "Goodbye! " + this.name;
        }
    }
}

Filename: UseCase.ts (Testfile to import and instantiate the objects)

import GreetingApp from './GreetingApp';

console.log(new GreetingApp.Hello('adam').toString());
console.log(new GreetingApp.Bye('adam').toString());

A: If you don't use export/import, then all your files run in the global scope, and if multiple files declare namespaces with the same name (as in the example you linked), the namespaces get merged.  This approach can be very convenient; it's used in the TypeScript compiler source code itself as well as in one of my projects.  (The TypeScript team claims that external modules are superior to namespaces, but I'll believe them when they migrate the compiler from namespaces to external modules!)  Note that /// <reference path="..."> serves two purposes: loading the declarations from the target file at compile time and ensuring that the target file is loaded before the current file at runtime.  You'll be able to leave out the /// <reference path="..."> if you meet both of the following conditions: you use a tsconfig.json file to ensure that all your files are loaded at compile time, and the runtime load order doesn't matter.  One of the most common reasons why runtime load order might matter is if you define a class and then extend it in a different file.
If you export and import the namespace, then you are using external modules, and if you declare two namespaces with the same name in different external modules, they won't merge.  One external module can contain a module augmentation that adds declarations to a namespace in another external module, but not runtime code.  So this is not as convenient as merging namespaces in files that run in the global scope.
Round 2
In UseCase.ts, I'm assuming you intended to import { GreetingApp } from './GreetingApp', because import GreetingApp from './GreetingApp' is giving me a compile error.  (If so, please update the question.)
Wow, you have found a crazy aspect of TypeScript name resolution that I was previously unaware of.  In this example, Hello.ts and Bye.ts are global files and not external modules (because they contain no top-level ES6 imports or exports), so both contribute to a GreetingApp namespace in the global scope, which has nothing to do with the GreetingApp namespace exported from GreetingApp.ts.
So what is happening in UseCase.ts?  As mentioned here, a TypeScript symbol can have one or more of the following meanings: value (including namespace of values), type, and "namespace" (meaning namespace of types).  The GreetingApp namespace in GreetingApp.ts has only a namespace meaning because it contains no values, while the global GreetingApp namespace has both a value meaning and a namespace meaning because it contains classes, which consist of both values (constructor functions) and types (instance types).
When a symbol is referenced, the context of the reference determines which of the three meanings is used: if you use X.Y as a value, the value meaning of X is used and its property Y is taken, while if you use X.Y as a type, the namespace meaning of X and the type meaning of Y within X are used.  Furthermore, shadowing of symbols works per-meaning!  When UseCase.ts imports GreetingApp from ./GreetingApp, it imports the only meaning that the GreetingApp in GreetingApp.ts has, which is a namespace meaning, shadowing the namespace meaning of the global GreetingApp.  The value meaning of the global GreetingApp is still visible and is used by the references to GreetingApp.Hello and GreetingApp.Bye.  However, you'll notice that if you try to declare a variable of type GreetingApp.Hello, it doesn't work, because that reference uses the namespace meaning of GreetingApp, which resolves to the empty namespace from GreetingApp.ts and not the global namespace.
I know this analysis is pretty technical, but I hope I've made clear that the example isn't working the way you probably thought it was (and I hope the next person confused by TypeScript's underdocumented shadowing behavior will find this thread in a web search).  The import and the entire GreetingApp.ts file are serving no purpose in the example.  If you delete both of them, you are left with the "global files with merged namespaces" approach to structuring your codebase that I described in the original answer.


text:
Q: Accessing Multidimensional array with Codeigniter Ok, In my Codeigniter project I am passing a multidimensional array to my view. The issue I am having is access the data in the array. I use print_r and var_dump to see the array and it is being passed correctly to the view but I am having the hardest time access the data within it! I get this error message, "Trying to access parameter of non-object". Any suggestions?!
Here is the controller: profile.php
    <?php
        class Profile extends CI_Controller {

            public function __construct(){
                parent::__construct();
                $this->load->library('session');

                //Get user data
                $this->load->model('user_model');

            }

            public function user_lookup(){
                //get usering users data
                $email = $this->session->userdata('email');
                //get profile users data
                $username = $this->uri->segment(2,0);

                $user = array(
                            'users' => $this->user_model->getUserData($email),
                            'profile' => $this->user_model->getUserDataWithUsername($username)
                        );

                $this->load->view('profile_view', $user);
            }

        }
    ?>

And here is the view that is recieving the data: profile_view.php
<!DOCTYPE html>
<html>
    <body>
        <?php
             print_r($users[0]);
        ?>
     </body>
 </html>

The output of my print_r statement is:
Array ( [hometown] => Las Vegas [email] => johnmy@gmail.com [university] => UC Berkley [first_name] => Pete [last_name] => Smith [date] => 1992 ) 1

A: Based on your code:
$this->load->view('profile_view', $user);

This mean that you supply array $user as view data. Therefore, on view $user is no longer exists.
You can only use it's element in view:
<?php
    echo $hometown;
    echo $email;
?>

If you want to use $user array in view, use this view load code in controller:
$this->load->view('profile_view', array('user' => $user ));

You can read more about Views in CodeIgniter.


text:
Q: How to remove part of string data from strings which are mutually dependent in java I have two string arrays in javascript like
var names = [name1, name2, name3, name4];
var values = [value1, value2, value3, value4];

I need to send these values to backend. And I am sending as follows
var nameString = "name1,name2,name3,name4";
var valuesString = "value1,value2,value3,value4";

Then i will iterate it over a map in java. My problem is if i want to remove name from name string, that corresponding value from valueString should also remove. How to do this in java side in an optimized way.
Ex: If i want to remove name3, then new strings should be like following:
  In Java side:
     String nameString = "name1,name2,name4";
     String valueString = "value1,value2,value4";

A: in javascript:
var data = {name1:value1, name2:value1, name3:value1, name4:value1};

(quoted if needed), the send the object as JSON, and parse it in java.
http://www.json.org/java/
i'm not a java dev, so in cant help you so much with specific code, but the method its the same for all languajes

A: in java you could do something like:
public static void main(String[] args) {
    String nameString = "name1,name2,name3,name4";
    String valueString = "value1,value2,value3,value4";

    nameString = removeSection(nameString, 2);
    valueString = removeSection(valueString, 2);

    System.out.println(nameString);
    System.out.println(valueString);

}

private static String removeSection(String val, int del){
    String[] a = val.split(",");
    String[] b = new String[a.length-1];

    System.arraycopy(a,0,b,0,del);
    System.arraycopy(a,del+1,b,del,a.length-1-del);

    val = arrayToString(b);

    return val;
}

private static String arrayToString(String[] a){
    String newStr = "";
    for (int i=0; i<a.length; i++) {
        if(i==0){
            newStr += a[i];
        }else{
            newStr += ","+a[i];
        }
    }
    return newStr;
}


text:
Q: Missing required arguments: aws_access_key_id, aws_secret_access_key on rake test I'm doing chapter 11 of hartle's tutorial.
When I ran heroku run rake db:migrate I got this error:
Missing required arguments: aws_access_key_id, aws_secret_access_key

I solved it with the answer in enter link description here and migrate successfully.but now when I run
bundle exec rake test

It gives me:
rake aborted!
ArgumentError: Missing required arguments: aws_access_key_id, aws_secret_access_key

This is my carrierwave file:
CarrierWave.configure do |config|
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => ENV['S3_KEY'],
    :aws_secret_access_key  => ENV['S3_SECRET'],
    :region                 => ENV['S3_REGION'],
    :endpoint               => ENV['S3_ENDPOINT']
  }

  if Rails.env.test? || Rails.env.development?
    config.storage = :file
    config.enable_processing = false
    config.root = "#{Rails.root}/tmp/uploads/#{DateTime.now.to_f}.#{rand(999)}.#{rand(999)}"
  else
    config.storage = :fog
  end

  config.cache_dir = "#{Rails.root}/tmp/uploads/#{DateTime.now.to_f}.#{rand(999)}.#{rand(999)}"
  config.fog_directory  = ENV['S3_BUCKET_NAME']
  config.fog_public     = false
  config.fog_attributes = {}
end

I tested the answer in enter link description here and it didn't work for me.

A: I would set these in the test helper:
ENV['S3_KEY'] = 'S3_KEY'
ENV['S3_SECRET'] = 'S3_SECRET'
ENV['S3_REGION'] = 'S3_REGION'
ENV['S3_ENDPOINT'] = 'S3_ENDPOINT'

Alternately, you can do
if ! Rails.env.test?
  config.fog_credentials = {
    :provider               => 'AWS',
    :aws_access_key_id      => ENV['S3_KEY'],
    :aws_secret_access_key  => ENV['S3_SECRET'],
    :region                 => ENV['S3_REGION'],
    :endpoint               => ENV['S3_ENDPOINT']
  }
end

But I think the first is better because it does not pollute your production code with test code.


text:
Q: How to pass a decimal value when making a post request in django? I am trying to make a post request to a third party application along with some data and the data also have a decimal value up to two points, which I am getting from database (order.amount) but after making the request getting error saying data is not serializable to json then i passed it as '"%s"' % round(order.amount,2) then also getting error post data is empty.Looking for suggestion to solve this problem.
    request = Transfer.request_transfer(beneId=beneficiary_id, amount=round((order.amount),2)
    transferId=transfer_identifier,remarks="Test transfer")

    getting error: decimal is not json serializable

    print('"%s"' % round((order.amount),2) #"5000.23"

    request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")

    getting error : PreconditionFailedError: Reason = Post data is empty or not a valid JSON:: response = {"status": "ERROR", "subCode": "412", "message": "Post data is empty or not a valid JSON"}

    but when hardcoding amount then it is working
    request = Transfer.request_transfer(beneId=beneficiary_id, amount= "5000.23" transferId=transfer_identifier,remarks="Test transfer")

A: Pay attention to this line,
print('"%s"' % round((order.amount),2) #"5000.23"

I guess you miss one thing: you're formatting your decimal value, but you do this with quotes, so your variable amount will contain "5000.23" string instead of 5000.23.
So, look:
request = Transfer.request_transfer(beneId=beneficiary_id, amount='"%s"' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")

you have amount='"5000.23"' and these quotes get in the way of serialization.
To fix it, just remove the additional quotes:
print('%s' % round((order.amount),2) # '5000.23'

request = Transfer.request_transfer(beneId=beneficiary_id, amount='%s' % round((order.amount),2) transferId=transfer_identifier,remarks="Test transfer")

A: The round function according to Python docs:

The return value is an integer if ndigits is omitted or None.
Otherwise the return value has the same type as number.

Hence round when passed a Decimal and ndigits will return a Decimal, hence passing amount=round((order.amount),2) will not do what you assume it does (converting to float or  int). Also converting Decimal to float implies a loss of precision which we don't want (The whole reason we would be using Decimal). To pass a Decimal value one would simply pass it as a string (Which of course implies we would need to perform some type casting at the client side if we want to perform arithmetic using it):
request = Transfer.request_transfer(
    beneId=beneficiary_id,
    amount=str(order.amount),
    transferId=transfer_identifier,
    remarks="Test transfer"
)


text:
Q: Retrieving slf4j log file in java I'm making a project backup java application, that needs to create a mail report and send it every day. My idea was to generate the body message, and to attach to the email the application log.
I'm using slf4j logger, and I don't know ho to automatically retrieve the log file path using the logger.
Using plain log4j seems to be easy, but I can't get out trying to retrieve it from the slf4j logger. Anyone faced this problem?

A: At the end this is what I did, and it seems to work fine.
Any review or comment will be appreciated!
private File getLogFile(){
    File file = null;
    Appender rightAppender = null;
    Enumeration<Appender> e = org.apache.log4j.Logger.getRootLogger().getAllAppenders();
    while(e.hasMoreElements()){
        Appender appender = (Appender)e.nextElement();
        if(appender instanceof FileAppender){
            rightAppender = appender;
        }
    }
    if(null != rightAppender){
        file = new File(((FileAppender)rightAppender).getFile());
    }
    return file;

}

A: There is no such thing as an SLF4J logger. SLF4J is a facade for another logging framework (log4j, commons-logging, java.util.Log, etc.). So an SLF4J logger is always just a wrapper around a logger in one of the supported frameworks. Look at how you configured the logger underneath.
So in your case, if you are using slf4j with log4j, consult your log4j.properties or log4j.xml as usual to find where your logs are. And if you haven't set up either of those files (or otherwise initialized log4j), you don't have logs.


text:
Q: Count string value? Hey, Im a newbie in cocoa and I have a string and I am trying to count how long it is.  I have been searching through Apples docs but I can't find anything.
NSString *word = @"word";
How would I figure out how many characters is in a string?
Thanks

A: This should do the trick:
[word length];


text:
Q: why An error is created when creating the token  public static void CreateToken()
    {

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("grant_type", "client_credentials");
        var UserPassJson = "{\"username\": \"mucode\",\"password\": \"mypassword\"}";

        HttpContent content = new StringContent(UserPassJson, Encoding.UTF8, "application/json");

        var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
        if (response.IsSuccessStatusCode)
        {
            var responseContent = response.Content;
            string responseString = responseContent.ReadAsStringAsync().Result;
            Console.WriteLine(responseString);
        }
    }

why response.IsSuccessStatusCode Showing status code 401? What causes the malfunction?
What action does cause success?

A: The documentation specifies that you should pass the username and password using basic authentication and that you should pass a form-encoded body containing grant_type=client_credentials.
At the moment your code adds grant_type as a header, and posts the username and password as a JSON object in the body.
Correcting your code to do it the way the documentation says, we get:
HttpClient client = new HttpClient();
byte[] authBytes = System.Text.Encoding.ASCII.GetBytes("mucode:mypassword");
string base64Auth = Convert.ToBase64String(authBytes);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64Auth);

HttpContent content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("grant_type", "client_credentials") });

var response = client.PostAsync(new Uri("https://api.sandbox.paypal.com/v1/oauth2/token"), content).Result;
if (response.IsSuccessStatusCode)
{
    var responseContent = response.Content;
    string responseString = responseContent.ReadAsStringAsync().Result;
    Console.WriteLine(responseString);
}

P.S. I recommend reading You're using HttpClient wrong and it is destabilizing your software and the follow-up You're (probably still) using HttpClient wrong and it is destabilizing your software. I also recommend making this method async and making the chain all the way up async too.


text:
Q: How To Get Safari History Domain Images Form Cache In Safari v10.1 I want to get images from safari which i show in my app. I have to differentiate all cache images domain wise, so before new update of mac os x12.4 and safari v10.1. i was getting images from below location
~/Library/Caches/com.apple.Safari/WebKitCache/Version
for example I was getting images of google.com from the location -:
~/Library/Caches/com.apple.Safari/WebKitCache/Version 9/Records/google.com
in this location OS was saving images by domain name's folder. But after update they have changed domain into a different string which is like this
~/Library/Caches/com.apple.Safari/WebKitCache/Version 9/Records/1A71C22C3069617815FB52ACDEB96918BD33D7DD
in this situation i cant specify images by domain name.
I tried every possibility for solving this problem so could anyone let me know if I can retrieve browsers cache images domain wise or Can I validate which image is cached by which domain.
What I was getting earlier - :

What I get later after update - :

Thanks in advance folks.

A: It seems that safari has been changed the format of naming convention for safari cache files. FYI we were on the same thing and we were finding a workaround  for this; Then we came to the conclusion like below - :
Safari maintains its history database on the below location - :
~/Library/Safari/History.db
Read this db. This database has a table named "history_visits" which holds the timestamp of triggered urls and its unique id
with this unique id you will find the triggered url in another table named "history_items"
find the cache images which matches the same timestamp according to the database.
if it matches then it may be the right image which you were looking.
Another important thing is -:
This is not the full proof solution of this problem to get the exact images according to the safari history, It just the solution which we came up with.


text:
Q: What is the need of EIPAssociation resource if we can directly associate EIP to an instance using Instance Property I was wondering the probable usage of EIPAssociation resource in Cloud Formation, though we can directly associate EIP with an EC2 instance using instance property of EIP & directly providing the instance reference.
Are there any specific issue in direct referencing instance via property & what would be the best practice to address this issue in cloud formation.

A: As far as I know, AWS::EC2::EIPAssociation allows you to achieve more than just EIP - Instance association that you would find in AWS::EC2::EIP.
One of the more notable case is that when you want to attach EIP to a specific network interface on a instance with multiple network interface


text:
Q: statically change specific UITableView cell height without reloading here's my issue:
I have a UITableView and in each cell I display some UILabels, like below:
----------------
|      "A"     |
----------------
|      "B"     |
----------------
|      "C"     |
----------------

Each cell is tap-able and when tap it pushes to another view to allow user to add some cell content. When user finish adding, the view pops back.
I want to see the UITable cell is statically updated with a new label that user added. For example, if user added some content to the first cell (previously with one label "a"), then after view pops back the cell should have two labels, which should look like:
----------------
|      "A"     |
|     "New"    |
----------------
|      "B"     |
----------------
|      "C"     |
----------------

I don't want to reload the entire table (which will drain data and lost previous cell position). Is there a way I can re-load this specific cell with new height/content? or statically adjust the cell-height?
Thank you

A: Yes you can reload particular cell in table view while relaoding the cell you can set cell height.
 NSArray* rowsToReload = [NSArray arrayWithObjects:self.selectdIndexPath, nil];
 [self.tableview reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];


text:
Q: STL map vs map Performance we know some compare function is used when inserting a new key.
which one is faster while accessing some key?
how much faster?
thanks

A: STL map is comparison based as it is based on a search tree internally. That means that a number of key comparisons are performed when inserting or search elements. Comparisons of integers can be performed in constant time. Comparisons of strings depend on the lengths of the strings and usually take longer.


text:
Q: Obtener un valor por defecto en un select mvc 5 He creado una vista parcial en el cual un objeto <select></select> es llenado desde una base de datos sql server mediante un for each. los valores que toman por ejm son:

1 Articulos de limpieza
2 Articulos de ferreteria
3 Frutas y Verduras...etc

Hasta ahí esta todo bien, pero cuando creo otra vista y llamo a este select no puedo ponerle un valor por defecto...La vista que he creado trae los datos de un articulo como su código, nombre, precio y tipo de articulo (que aparecen en la lista select)...Necesito que cuando llame a un articulo el tipo al que pertenece se seleccione de esta lista automáticamente
este es el codigo con el cual llamo a la lista
@Html.Action("BuscarArticuloLinea", "ArticuloLinea", New With
{.htmlAttributes = New With {.value = IdArticuloLinea}})

Gracias por su ayuda.

A: Puedes incluir el atributo html selected al elemento que quieras por defecto.
<option selected="selected">
 3
</option>


text:
Q: List users with the same IP I have this query,
SELECT * FROM users
WHERE user_ip IN (SELECT user_ip FROM users GROUP BY user_ip having count(*) > 1)
ORDER BY user_ip

This works to list all users which has at least 1 repeated IP with another user.
I need to order all users by total of repeated IP.
ex. this users table
id, username, ip
1, user1, 1.1.1.1
2, user2, 2.2.2.2
3, user3, 1.1.1.1
4, user4, 4.4.4.4
5, user5, 2.2.2.2
6, user6, 2.2.2.2

should print,
ip, username, total
2.2.2.2, user2, 3
2.2.2.2, user5, 3
2.2.2.2, user6, 3
1.1.1.1, user1, 2
1.1.1.1, user3, 2
4.4.4.4, user4, 1

A: Here is an approach which uses an INNER JOIN:
SELECT u1.ip, u1.username, u2.total
FROM users u1
INNER JOIN
(
    SELECT ip, COUNT(*) AS total
    FROM users
    GROUP BY ip
) u2
ON u1.ip = u2.ip
ORDER BY u2.total DESC

Click the link below for a running demo:
SQLFiddle

A: SELECT ip, username, count(*) total
FROM user_ip
WHERE ip in (
    SELECT ip
    FROM user_ip
    GROUP BY 1
    HAVING count(*) > 1
)
GROUP BY 1,2
ORDER BY 3 DESC,1,2

A: You can try:
SELECT `t`.ip, `t`.username, COUNT(`t2`.`id`) total
FROM `test` `t`
LEFT JOIN `test` `t2` ON `t2`.`ip`=`t`.`ip`
GROUP BY `t`.`id`
ORDER BY COUNT(`t2`.`id`) DESC

http://sqlfiddle.com/#!9/e5bb7/1/0


text:
Q: Specifying which object to get the super of Like the titles says, I want to specify the super of an NSArrayController, something along the lines of self = [super[NSArrayController] function], but have had no luck searching for this. Any ideas? Thanks in advance.
Edited to remove abstract examples as they're confusing people as to the nature of my question.
The purpose of this is to programmatically do what a simple binding of 'add' from an NSArrayController to an NSButton would do in IB. There are several arrayControllers in my application so I want to be able to specify which one I want to obtain the super of by code.
The reason I am looking for the super of an NSArrayController is because I am under the impression that one should address the model rather than the controller (NSArrayController) and my model is a Core Data model that I believe I could get to by using the super of an NSArrayController I specify by name. Perhaps there is a more direct way of adding to the data model.

A: You're asking a wrong question.
First, let's distinguish a class and an instance of the class. Note that there can be, and indeed often are, multiple instances of the same class.
A class C can be a subclass of another class A. Then A is the superclass of C. Suppose you have an instance c of the class C. Then, in the implementation of the methods of the class C, self stands for the instance of c itself, and super stands for the instance of c as an instance of its superclass A.  In a sense, an instance of the class C is also an instance of the class A.
Objects can have other relationships than being super or subclasses. For example, a class C can have in its interface an instance variable B* b; In this case, an instance c of the class C has a pointer to an instance  b of the class B. In this case, c is not an  instance of the class B.
The relationship between NSArrayController and the managed object context is one of the latter. An instance of NSArrayController contains a pointer to an instance of NSManagedObjectContext (moc).
So what you want to do is not to get the super of your NSArrayController. Instead, you want to get the moc associated to the NSArrayController. Now, how do you get it? To find it out, you open the reference in XCode or on the web at the Apple Developer Connection, see here. Do that right now. Go through the methods. You don't find one giving you the moc.
Then, you go to the top of that page, and follow the superclass of NSArrayController. See this reference of NSObjectController. Now, go through the list of the methods. You find -[NSObjectController managedObjectContext], which does the job!
In conclusion: if you want the moc associated to the NSArrayController, you just need to do
NSManagedObjectContext* moc= [arrayController managedObjectContext];

where arrayController is the instance of the NSArrayController you want to deal with. e.g. If you have multiple instances of NSArrayControllers in the nib, you should have multiple IBOutlets in the app delegate, say, arrayController1, arrayController2, etc. (which are very bad variable names).  Then you choose the one you want to deal with.


text:
Q: Re-use vmsplice buffer when not gifting to kernel I am trying to understand how vmsplice works, especially when it comes to buffer re-use. In the example below, I have passed no flag so normally vmsplice should be blocking and the kernel is not "gifted" the buffer. However, when the sleep is commented out, the output becomes completely unordered. What am I missing?
#define _GNU_SOURCE
#include <bits/types/struct_iovec.h>
#include <fcntl.h>
#include <unistd.h>

int main()
{
    char buffer[2] = "0\n";
    struct iovec iov;
    iov.iov_base = buffer;
    iov.iov_len = 2;
    while (1) {
        buffer[0] = (buffer[0] - '0' + 1) % 10 + '0';
        vmsplice(1,&iov,1,0);
        // When the sleep is commented, output becomes unordered.
        sleep(1);
    }
}

launch the code as:
gcc example.c
./a.out | cat #The pipe is mandatory for vmsplice

A: As far as I understand vmsplice, it will hand over the buffer (user memory) to the kernel, so the buffer can not be used anymore by the program.
In your case, your buffer is even not on the heap but on the stack. I wonder that it doesn't crash when the stack memory becomes invalid.


text:
Q: How to access data written in a socket without reading it I'm working on an embedded system having Linux.
A client thread is writing some data in the socket but what server thread is reading on the other side isn't the same as it was written. Which is causing the thread (and parent process)  to crash.
I'm new to networking and Linux.
I have dumped every piece of data which is being written, it's all fine.
The function trace in gdb shows the following information.
(gdb)
#0  0x00007f62be8e8670 in getenv () from /lib/libc.so.6
#1  0x00007f62be92057a in __libc_message () from /lib/libc.so.6
#2  0x00007f62be99f927 in __fortify_fail () from /lib/libc.so.6
#3  0x00007f62be99f8f0 in __stack_chk_fail () from /lib/libc.so.6
#4  0x0000000000406471 in reading (sockFd=15) at __line_number_in_the_program__
#5  0x793bcf318b18bb01 in ?? ()
#6  0x117d0300942ff567 in ?? ()
#7  0x0000000100000000 in ?? ()
..
..
..

It goes till #785 with some [random] address.
reading() is the function which processes the read data in the server thread.
I suspect there something going wrong inside the socket.
Is there any way to see the data which is in the sockets(client/server) buffer without reading it?
Or any other way to debug it further with gdb?
There are already some checks to handle the read data properly but those are also not helping.

A: You have a stack buffer overflow problem.  If you have never heard of the GCC stack protector, now is the time to look it up.  Whilst Wireshark is the obvious tool for looking at data in flight, this is not the locus of your problem.  Your server should be proof against any and all malicious data read from the network.  This is basic good server design and implementation practice.  You have a stack buffer overflow problem.


text:
Q: Stacked bar plot in subplots using pandas .plot() I created a hypothetical DataFrame containing 3 measurements for 20 experiments. Each experiment is associated with a Subject (3 possibilities).
import random

random.seed(42) #set seed
tuples = list(zip(*[list(range(20)),random.choices(['Jean','Marc','Paul'], k = 20)]))#index labels
index=pd.MultiIndex.from_tuples(tuples, names=['num_exp','Subject'])#index
test= pd.DataFrame(np.random.randint(0,100,size=(20, 3)),index=index,columns=['var1','var2','var3']) #DataFrame
test.head() #first lines

head
I succeeded in constructing stacked bar plots with the 3 measurements (each bar is an experiment) for each subject:
test.groupby('Subject').plot(kind='bar', stacked=True,legend=False) #plots

plot1 plot2 plot3
Now, I would like to put each plot (for each subject) in a subplot. If I use the "subplots" argument, it gives me the following :
test.groupby('Subject').plot(kind='bar', stacked=True,legend=False,subplots= True) #plot with subplot

plotsubplot1 plotsubplot2 plotsubplot3
It created a subplot for each measurment because they correspond to columns in my DataFrame.
I don't know how I could do otherwise because I need them as columns to create stacked bars.
So here is my question :
Is it possible to construct this kind of figure with stacked bar plots in subplots (ideally in an elegant way, without iterating) ?
Thanks in advance !

A: I solved my problem with a simple loop without using anything else than pandas .plot()
Pandas .plot() has an ax parameters for matplotlib axes object.
So, starting from the list of distinct subjects :
subj= list(dict.fromkeys(test.index.get_level_values('Subject')))

I define my subplots :
fig, axs = plt.subplots(1, len(subj))

Then, I have to iterate for each subplot :
 for a in range(len(subj)):
    test.loc[test.index.get_level_values('Subject') == subj[a]].unstack(level=1).plot(ax= axs[a], kind='bar', stacked=True,legend=False,xlabel='',fontsize=10) #Plot
    axs[a].set_title(subj[a],pad=0,fontsize=15) #title
    axs[a].tick_params(axis='y', pad=0,size=1) #yticks

And it works well ! :finalresult


text:
Q: How to split url in reactJs The full url is /login?redirect=shipping. I want to split it into two parts like this - /login?redirect and shipping. I need the second part of the url. that is shipping How can I do this in reactjs??

A: You can use useSearchParams from react-router-dom v6.
You can also use URLSearchParams (Provided by Browsers)
In your case it would be as follows:
import React from "react";
import { useSearchParams, useLocation } from "react-router-dom";

export const App = () => {
    const [searchParams, setSearchParams] = useSearchParams();
    const { search } = useLocation();

    console.log(searchParams.get("redirect"));

    // if it's more than 1 value for redirect i.e. redirect=shipping&redirect=shipped
    console.log(searchParams.getAll("redirect")); // will return array of value

    // you can use URLSearchParams also by passing search query
    console.log(new URLSearchParams(search).get("redirect"));
    // URLSearchParams is provided by Browser.
    return
Search Param
;
};

PS: Follow useSearchParams approach if using react and specifically react-router-dom V6 or else go for URLSearchParams


text:
Q: Bulk update Google Sheet with python Table I'm trying to pull data from a website, create a table, and then store that table in a Google spreadsheet. I have successfully copied the data from the site and can send data to google cell by cell. However, Google's API limits the number of requests, so I'm trying to work around it by sending the data in bulk rather than as single requests. Any ideas on how to do that? Here's a snippet of code showing what I have at the moment.
I tried creating a table to store the data, but I had trouble sending it to google sheets. I'm currently running Python 3 in PyCharm using Selenium for web browser automation.
for a in range(1,row_count + 1):
    for b in range(1,col_count + 1):
        final_path = first_part + str(a) + second_part + str(b) + third_part
        table_data = browser.find_element_by_xpath(final_path).text
        #print(table_data)
        sheetone.update_cell(a , b , table_data)

I want to scrape the website and temporarily store the data within my script then send all of the data out as a single request.
"message": "Quota exceeded for quota group 'WriteGroup' and limit 'USER-100s' of service 'sheets.googleapis.com' for consumer 'project_number:487815375845'.",
    "status": "RESOURCE_EXHAUSTED",

A: *

*You want to put the values to the Spreadsheet by one API call.

*You want to achieve this using gspread with python.

*You have already been able to put and get values for the Spreadsheet using Sheets API.

If my understanding is correct, how about this modification? In this modification, at first, the data is created in the for loop, and then, the created data is put to the Spreadsheet using update_cells.
Modified script:
data = []  # Added
for a in range(1,row_count + 1):
    for b in range(1,col_count + 1):
        final_path = first_part + str(a) + second_part + str(b) + third_part
        table_data = browser.find_element_by_xpath(final_path).text
        #print(table_data)
        data.append(gspread.models.Cell(a, b, table_data))  # Modified

sheetone.update_cells(data)  # Added

References:

*

*Updating Cells

*gspread.models.Cell(row, col, value='')
If I misunderstood your question and this was not the direction you want, I apologize.


text:
Q: Angularjs ngStorage watch localstorage variable in other controller/ browser tab I am using AngularJs and ngStorage to make a shopping cart. I want to keep data in local storage. When I add something from different browser tab I want to call my http method in the cart where cart is opened. I wanted to use $scope.$watch but it is not working :(
I was trying als to use helper value in localstorage, first controller:
$scope.$watch('counter', function(newValue, oldValue) {
    if(newValue === oldValue){
      return;
    }
    console.log(newValue);
});

$scope.deleteItem = function (item) {
    var index = $scope.storage.products.indexOf(item);
    $scope.storage.products.splice(index, 1);
    $scope.counter = 0;
}

Second Controller:
    $scope.addToCart = function(code) {
    var prod = {
        code: code,
        quantity: 1,
        color: 0,
        notes: '',
    };
    $scope.storage.products.push(prod);
    $scope.storage.counter=$scope.storage.counter+1;
    $scope.$apply();
}

How to observe/watch my localstorage value when it is modified in another browser tab?

A: Based on @stackg91 references adapted to your context: you can attach a handler to local storage and broadcast an event every time the storage is changed:
var app = angular.module('app',['ngResource','ngRoute','ngCookies']);

app.config(['$routeProvider',function($routeProvider){
    $routeProvider
        .when('/', {templateUrl: '/home.html', controller: 'myCtrl'})
        .otherwise({ redirectTo: '/' });
}]).run(['$rootScope', function($rootScope) {
// you might need to inject you storage module here
    if (window.addEventListener) {
      window.addEventListener("storage", handler, false);
    } else {
      window.attachEvent("onstorage", handler);
    };

    function handler(e) {
   // get the value from storage based on storage module you're using
      $rootScope.$broadcast('counterChanged',
localStorage.getItem('counter'));
    }
}]);

Then you can react to this event in any controller:
app.controller('firstController',['$scope', function($scope){
    $scope.addToCart = function(code) {
        var prod = {
            code: code,
            quantity: 1,
            color: 0,
            notes: '',
        };
        $scope.storage.products.push(prod);
        $scope.storage.counter=$scope.storage.counter+1;
        $scope.$apply();
    }

}]);

app.controller('myCtrl',['$scope', function($scope){
    $scope.$on('counterChanged', function(event, data) {
        // do things with the new counter
        console.log(data);
    });

}]);

A: Try this https://truongtx.me/2014/06/16/cross-tab-communication-using-html5-dom-storage/
Pretty good explanation for cross-tab communication with local/session storage
Every time the Localstorage is changed the Storage event is called.


text:
Q: What is the Ideal Approach for Creating a Custom Home Page? I need to create a custom home page for our SharePoint 2010 site. The rest of the site will use a separate template for all of the sub-pages.
Should I create a dedicated master page for the home page on its own? Also, what is the ideal way to apply this against the site? I have a lot of sub-sites, so does this mean I will have to set the home page master page to be the parent level item and then go change/update all of the sub-sites to use the other (sub-site) master page?

A: You can set a custom page as the landing / home page of your site by setting the relative URL of the page to the WelcomePage property of the root folder of the root web. Like:
using (SPSite site = new SPSite("http://server:port/"))
{
    SPWeb web = site.RootWeb;
    SPFolder rootFolder = web.RootFolder;
    rootFolder.WelcomePage = "Pages/YourCustomHomePage.aspx";
    rootFolder.Update();
}

If a user navigates to http://server:port/ they would be served http://server:port/Pages/YourCustomHomePage.aspx.
Whether or not you make a master page just for the home page depends on the design. If it's a different layout, with different branding, and a different structure you not only should make a separate master page, you probably must do so. You can always set the master page in the markup of your custom home page and leave the master page for the rest of your site (set at SPWeb.MasterUrl or SPWeb.CustomMasterUrl) alone.
One alternative to using a library within SharePoint to store the home page, is to use an application page in a folder under TEMPLATE\LAYOUTS instead. To do that requires you to set up a redirect page as explained in Redirect default.aspx or change default landing to page in _layouts folder?.
One reason for you to use an application page is if you need to use custom code behind as part of the requirements you have.


text:
Q: Scope of variables when calling function from find In a bash script I define a function that is called from find. The problem is that the scope of variables does not extend to the function. How do I access variables from the function? Here is an example:
variable="Filename:"

myfunction() {
    echo $variable $1
}

export -f myfunction

find . -type f -exec bash -c 'myfunction "{}"' \;

This will output filenames but without the string "Filename:".
Is there perhaps a better way to invoke a function from find such that it is called for every file that find finds, and variables are still defined?

A: Not an answer to your question, but do not do:
find . -type f -exec bash -c 'myfunction "{}"' \;

Beside the fact that it's not portable, it's also very dangerous, because the file names end up being interpreted by bash as shell code. Consider for instance what would happen if there was a file called $(rm -rf ~) down there. Write it:
find . -type f -exec bash -c 'myfunction "$1"' find+bash {} \;

Or even better (to avoid running one bash per file):
find . -type f -exec bash -c 'for file do
  myfunction "$file"; done' find+bash {} +

Now an answer to your question to be on topic:
You could do:
{ find . -type f -exec printf '%s\0' {} + | while IFS= read -ru3 -d '' file; do
  myfunction "$file"; done 3<&0 <&4 4<&-; } 4<&0

That way, you're calling myfunction within the current bash shell, so you don't need to export myfunction or run additional bash shells.
If your find supports the -print0 predicate (like GNU, busybox and some BSDs finds), you can replace -exec printf '%s\0' {} + with -print0

A: You could declare variable as an environment variable, i.e.,
export variable="Filename:"

A: I would do it as follow
#!/bin/bash

myfunction() {
    local var="Filename: "
    local file=$1
        echo "$var" "$file"
    }

export -f myfunction
    find . -type f -exec bash -c 'myfunction {}' \;

Declare vars as local and pass '{}' to the function which is $1 first positional parameter.

A: When you assign to a variable, it starts out as a shell variable. In order to get an environment variable that is passed to subprocesses, you need to export it.
variable="Filename:"
export variable

You can put the assignment on the same line as export: export variable="Filename:".
The variable will be visible to the shells started by find, but not the functions. In bash, you can also export functions. This possibility is not present in ksh, dash and other shells that are often used as sh because they are faster and leaner.
export -f myfunction    # bash only

Never use {} inside a string in find -exec … (or xargs …), unless you know that your file names are alphanumeric. If there are any special characters in the file names, they will be parsed as such by the inner shell. Instead, pass the file names on the shell's command line.
find . -type f -exec bash -c 'for x; do myfunction "$x"; done' _ {} +

With shells other than bash, define the function in the inner shell, or just put its code directly.
Alternatively, in bash, you can use recursive globbing instead of find. Beware that bash traverses symbolic links to directories.
variable="Filename:"
myfunction () { … }
shopt -s globstar dotglob
for x in **/*; do
  if [[ -f $x ]]; then myfunction "$x"; fi
done


text:
Q: Missing Component Pieces from a PCB This PCB is from a old Sharp 1999 TV I have been reverse engineering lately; also sorry for any bad images.  I have noticed that there are some "missing" components in the holes of: D4002, D4003, D4001, D4004, and C4002.  Are there certain components that were once in those holes as part of the design?

A: They could be parts that are used for a different TV or some other product, they could be parts that were in the original design, but later deemed unnecessary.  It could also be a cost saving measure (two parts in parallel in case two lower value parts were cheaper than a higher value part).
The board might work if you add those components back in, or it might stop working if those components are put in.  It is difficult to tell without reverse engineering the whole thing.


text:
Q: How to make a search list in Sencha Touch 2? Store already define Hi stackoverflow community,
Yes i know, other people have the same problem but they define the store in the same file, the example of sencha touch 2 works for me, but when I try to apply this code to mine I get this error:

Uncaught SyntaxError: Unexpected identifier Alertas.js:105 Uncaught
  Error: The following classes are not declared even if their files have
  been loaded: 'myMoney.view.Alertas'. Please check the source code of
  their corresponding files for possible typos: 'app/view/Alertas.js

I think that I need to call my store another way, but here's my question :
How to call a store already defined for a search list?
There is my code:
Ext.define('myMoney.view.Alertas',{
extend: 'Ext.navigation.View',
fullscreen: true,
scrollable: true,
styleHtmlContent: true,
xtype: 'alertas',

config: {
    title: 'Contactos',
    iconCls: 'bookmarks',

    items: [
        {
            xtype: 'list',
            grouped: true,
            ui: 'round',
            title: 'Contactos',
            fullscreen: true,
            itemTpl: '{title}',
            styleHtmlCls: true,
            //cls: 'x-contacts',
            store: 'Contactos',
            itemTpl: [
                '

',
                '{firstName} {lastName}',
                '{title}'
            ].join(''),

            items: [
                {
                    xtype: 'searchfield',
                    placeHolder: 'Buscar contacto...',
                    listeners: {
                        scope: this,
                        clearicontap: this.onSearchClearIconTap,
                        keyup: this.onSearchKeyUp
                    }
                },
            ]
        },
    ]
},

/**
 * Llamado cuando la barra de busqueda tiene un evento keyup
 */
onSearchKeyUp: function(field) {
    //Se obtiene el store y el valor del field
    var value = field.getValue(),
        //store = this.getStore();
            //NOW:
            store = Ext.data.StoreManager.lookup('Contactos');

    //se limpian los filtros actuales del store para comenzar la nueva busqueda
    store.clearFilter();

    //Verificamos que el valor tenga alguna  modificacion
    if (value) {
        //El usuario pudo haber introducido espacion en blanco,asi que los cortamos para poder recorrer todo el valor
        var searches = value.split(' '),
            regexps = [],
            i;

        //recorremos todo el valor
        for (i = 0; i < searches.length; i++) {
            //si no hay nada continuamos
            if (!searches[i]) continue;

            //Si encontramos algo creamos una expresion regular que es sensible a mayusculas
            regexps.push(new RegExp(searches[i], 'i'));
        }

        //Ahora se filtra el store
        //El metodo se pasara a cada record en el store
        store.filter(function(record) {
            var matched = [];

            //Iteramos a traves de cada expresion regular
            for (i = 0; i < regexps.length; i++) {
                var search = regexps[i],
                    didMatch = record.get('firstName').match(search) || record.get('lastName').match(search);

                //Si coincide el primer o ultimo nombre se coloca en la lista de los que coinciden
                matched.push(didMatch);
            }

            //Si nada se consigue no se retorna nada
            if (regexps.length > 1 && matched.indexOf(false) != -1) {
                return false;
            } else {
                //Si no se muestra lo que se encontro
                return matched[0];
            }
        });
    }
},
/**
 * Llamado cuando el usuario presiona el icono de 'x' en la barra de busqueda
 * Solo que quitan los filtros del store
 */
onSearchClearIconTap: function() {
    //this.getStore().clearFilter();
        //NOW:
        store = Ext.data.StoreManager.lookup('Contactos');
}
/**
 * Metodo llamado para tomar el store
 */
      //I DELETE THIS FUNCTION
/*getStore: function() {
        this.store = 'myMoney.store.Contactos'*/
}
});

A: please be careful with getters :)
getStore: function() {
        this.store = 'myMoney.store.Contactos'
}

I think it intended to return the store, not only to assign to class member.
onSearchKeyUp: function(field) {
    //Se obtiene el store y el valor del field
    var value = field.getValue(),
        store = this.getStore();  // undefined

variable store is always undefined...

A: You need to use the Ext.StoreManager, in order to use the specified store by id.
example:
with this store:
Ext.create('Ext.data.Store', {
    model: 'SomeModel',
    storeId: 'myStore'
});

Use
var store = Ext.data.StoreManager.lookup('myStore');

or use it in a view:
Ext.create('Ext.view.View', {
    store: 'myStore',
    // other configuration here
});

A: Above NeoMorfeo code is correct only thing in get store value
You need to use the Ext.StoreManager, in order to use the specified store by id.
example:
with this store:
Ext.create('Ext.data.Store', {
    model: 'SomeModel',
    storeId: 'myStore'
});

Use
var store =  Ext.getStore('myStore');

or use it in a view:
Ext.create('Ext.view.View', {
    store: 'myStore',
    // other configuration here
});


text:
Q: What element is the default scrollbar handler? Does every browser out there share any standard about what element is the default handler for displaying scrollbars? I'm really wondering how do they treat the rendering of <html> and <body> elements
Update:
For instance, if you have to reconstruct the DOM architecture where would you put the overflow: auto/scroll in the <html> or <body>?

A: Update:

For instance, if you have to reconstruct the DOM architecture where
  would you put the overflow: auto/scroll in the  or ?

As far as this is concerned, the HTML element is the one you're after.

Original Answer:
Scrollbar styling is browser dependant to some degree, and can only be controlled via CSS for Webkit browsers and IE, the alternative would be to utilise javascript plugins.
The one consistent control CSS has is whether to display scrollbars or not for a given element, using the overflow property.

The overflow CSS property specifies whether to clip content, render
  scroll bars or display overflow content of a block-level element.

Regarding your styling options, example implementations in CSS may be:
Internet Explorer
body{
  scrollbar-base-color: #C0C0C0;
  scrollbar-base-color: #C0C0C0;
  scrollbar-3dlight-color: #C0C0C0;
  scrollbar-highlight-color: #C0C0C0;
  scrollbar-track-color: #EBEBEB;
  scrollbar-arrow-color: black;
  scrollbar-shadow-color: #C0C0C0;
  scrollbar-dark-shadow-color: #C0C0C0;
}

Webkit
::-webkit-scrollbar { width: 3px; height: 3px;}
::-webkit-scrollbar-button {  background-color: #666; }
::-webkit-scrollbar-track {  background-color: #999;}
::-webkit-scrollbar-track-piece { background-color: #ffffff;}
::-webkit-scrollbar-thumb { height: 50px; background-color: #666; border-radius: 3px;}
::-webkit-scrollbar-corner { background-color: #999;}}
::-webkit-resizer { background-color: #666;}

As far as the default 'handler' is concerned, CSS is cascading so apply any rules to the top level for which you want all children to inherit those properties.
As far as the window scrollbars are concerned, you want to control these using the html element, as this is the element that always fills the viewport/content space.


text:
Q: React component prop throwing error typescript I'm trying to use a component on which I have defined the prop type like this
export type Props = {
  variant: "green" | "red" | "grey" | "yellow";
};

and the component is like this
const Tag: FC<Props> = (props) => {
  const { variant, ...rest } = props;

  return (
    <div
      {...rest}
      sx={{
        bg: variant,
      }}
    />
  );
};

Now when I try to consume this component like this
const statusColour: { [key: string]: string } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

const variant = statusColour[value]
          ? statusColour[value]
          : statusColour["default"];

<Tag variant={variant} />

I get this error on the variant attribute

Type 'string' is not assignable to type '"green" | "red" | "grey" | "yellow"'.ts(2322)

types.d.ts(2, 5): The expected type comes from property 'variant' which is declared here on type 'IntrinsicAttributes & TagProps & { children?: ReactNode; }'

(JSX attribute) variant: "green" | "red" | "grey" | "yellow"

Can somebody help me out on how to resolve it, thanks

A:
Type 'string' is not assignable to type '"green" | "red" | "grey" | "yellow"'.ts(2322)

This error means that any string of type string is not assignable to the union of specific strings "green" | "red" | "grey" | "yellow". This makes sense. "banana" is a string, but it should NOT be assignable to "apple" | "pear".
To fix it you need to tell the type of statusColor that it may only have values that are one of those specific strings.
So just make the values of your mapped type the same as the variant in Props.
const statusColour: { [key: string]: Props['variant'] } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

Playground

Or clean it up by making the variant union it's own type alias:
type MyVariant = "green" | "red" | "grey" | "yellow"

export type Props = {
  variant: MyVariant;
};

const statusColour: { [key: string]: MyVariant } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

Playground

A: so figured out my mistake. Basically, the variant prop expected something of type "green" | "red" | "grey" | "yellow"; but I was passing a string. To resolve it, this is what I did:
const statusColour: { [key: string]: string } = {
  running: "green",
  stopped: "red",
  idle: "grey",
  default: "green"
};

const variant = statusColour[value] as "green" | "red" | "grey" | "yellow"

<Tag variant={variant} />

I know this is not the best solution. So if somebody could post a better solution, that would be super helpful. Thanks


text:
Q: send Observer data to phtml file in Magento 2 I am trying to send Observer info into the block file. used the add to cart event as like below.
app/code/Vendor/Module/etc/events.xml
<?xml version="1.0"?>
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="checkout_cart_product_add_after">
      <observer name="event_observer_checkoutcartproductaddafterwe" instance="Vendor\Module\Observer\Checkoutcartproductaddafter" />
  </event>
</config>

Then
app/code/Vendor/Module/Observer/Checkoutcartproductaddafter.php
<?php
 namespace Vendor\Module\Observer;
 class Checkoutcartproductaddafter implements \Magento\Framework\Event\ObserverInterface
 {
  protected $layout;
  public function __construct(
    \Magento\Framework\View\Layout $layout)
   {
    $this->layout = $layout;
   }
  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    $event = $observer->getEvent();
    $eventData = $event->getData('quote_item');
    $item = ($eventData->getParentItem() ? $eventData->getParentItem() : $eventData);
    $product = $item->getProduct();
    $productId = $product->getId();
      $prepareJson = array(
             'Added To Cart' => array(
             'productId' => $productId,
             'productName' => $product->getName(),
          )
        );
     $block = $this->layout->createBlock('Vendor\Module\Block\Index\Index')->setTemplate('Vendor_Module::before-body-end.phtml')
        ->setObserverData($prepareJson)
        ->toHtml();
     }
   }

Vendor/Module/view/frontend/templates/before-body-end.phtml
<?php
 $jsonData = $block->getObserverData();
?>
<script id='test_script' type='text/javascript'>
  console.log('inside');
  var data = '<?php echo $jsonData; ?>';
  console.log('--data--',data);
</script>

From the above code I am able to pass the observer data into the phtml file, but I am trying to print the received info into the browser console.
Once printed in browser i have to send to a third party tool using javascript function.
The problem is whatever js is written That's not working. Please help me how can we achieve this. Thanks in Advance!!

A:
define same observer into  below event.

   <event name="controller_action_predispatch_catalog_product_view">
       <observer name="send_data2" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>
    <event name="checkout_cart_product_add_after">
       <observer name="send_data1" instance="Vendorename\Modulename\Observer\Yourfilename" />
   </event>

Add into your Observer file

protected $resultPageFactory;

public function __construct(
    .............................................................
    \Magento\Framework\View\Result\PageFactory $resultPageFactory,
    .............................................................

) {
    ................................................
    $this->resultPageFactory = $resultPageFactory;
    ...............................................
}
public function execute(\Magento\Framework\Event\Observer $observer)
{
    ob_start();
    $rowData = "your custom data"; // you can add object json array any kind of data
    $resultPage = $this->resultPageFactory->create();

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart');

    // retrieve quote items collection
    $itemsCollection = $cart->getQuote()->getItemsCollection();

    // get array of all items what can be display directly
    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    $data = [];
    $x = 0;
    foreach($itemsVisible as $item) {
        $data[$x]['name'] = $item->getName();
        $data[$x]['sku'] = $item->getSku();
        $data[$x]['qty'] = $item->getQty();
        $x++;
      }
    $phtml_data = json_encode($data);

    $block = $resultPage->getLayout()
            ->createBlock(\Vendorname\Modulename\Block\CustomBlock::class)
            ->setData('customdata', $phtml_data)
            ->setTemplate("Vendorname_Modulename::customdata.phtml")->toHtml();
    echo $block;
}

Add into your phtml file

<?php
$data = $block->getData('customdata');
print_r($data);
?>

<script type="text/javascript">
console.log("<?php echo $data; ?>");
</script>

I Hope This Helps You.