text:
Q: Where is Date roll is useful? I am reading Phobos docs. Sometimes I can't understand the logic of some methods.
Date roll

Adds the given number of years or months to this Date. A negative number will subtract. The difference between rolling and adding is that rolling does not affect larger units.

Maybe is Phobos is not good considered, maybe I do not understand where it's can be helpful.
If I am adding to 2013-07-01 for example 200 days I am expecting to get 2014 year, but not 2013.
Could anybody explain the logic?

A: roll is also present in Java.... the only time I remember ever using it in either language though was implementing a little date picker widget. There's separate fields for each thing: month, day, year, and you want the user to be able to spin through days without it incrementing month, since they are separate fields. (Suppose it is set to the 30th and they want to select the 1st. The quickest way might be to just hit the up arrow and let it roll over.)
There might be other uses, I just don't remember them right now. Even when I was implementing ical support a while ago (sadly, proprietary), I never used the roll method, but there might be potential for it there. ical is a standard for recurring events on calendars and there's some tricky things in there, and a few different ways you might implement it.
In the comment, you also ask why you can't add days. The reason is that adding days is pretty trivial and covered with the opBinary:
datetime += 5.days; // works

That does NOT work for months though, because months have a variable duration. That's where the add method comes in to help: suppose it is January 30 and you add one month. You might just add 31 days, since January has 31 days in it. That would land you on March 2 (I think, doing this in my head)... but Jan 30 + 1 month might also need to be Feb 28. Or maybe Feb 29. Suppose you are paying a monthly bill due at the end of the month, the number of days between those due dates will change.
The add method handles this and gives you the option to fall on the last day or to spill over into the next month.
Though, I'd kinda argue days don't have a static length either.... consider the DST transition. (Or leap seconds, but handling them would be nuts). Maybe we can ask JMD.

A: So, the short answer is that Adam is right, and roll is there specifically for handling date pickers and similar use cases, and add is there specifically to handle months and years, because Duration can't (since months and years don't convert to hecto-nanoseconds without knowing a starting point). But I'll take a stab at it a more in depth answer in case that clarifies things.
DateTime, Date, and TimeOfDay were designed for calendar-based operations. They have no relation to the system clock, they have no concept of time zone, and they hold the parts of the date/time as separate units (year, month, day, hour, etc.) internally. So, when you set the hour field on a DateTime, you are literally just adjusting one of DateTime's member variables. And when you add a Duration to them, that has to be split up to add to each unit individually and thus doing something like adding a Duration of 7 hours could increment more than just the hour field. e.g.
auto dt = DateTime(2015, 8, 2, 20, 0, 0);
dt += hours(7);
assert(dt == DateTime(2015, 8, 3, 3, 0, 0));

And since Duration holds its value internally in hecto-nanoseconds, you're not necessarily adding to a specific unit anyway. i.e. It's not like += hours(7) is specifically adding to the hour field. It's adding some number of hecto-nanoseconds to the whole DateTime and has to figure out how that affects each of the units rather than it affecting a specific unit. e.g.
auto dt = DateTime(2015, 8, 2, 20, 0, 0);
dt += hours(7) + minutes(5) + seconds(22);
assert(dt == DateTime(2015, 8, 3, 3, 5, 22));

roll on the other hand is specifically for adding to a specific unit without affecting any of the others. As Adam correctly determined, its primary use case was for spin controls and the like in date picker dialogs, where you end up adjusting a particular time unit by some amount, and you don't want to affect the other units, just the one that you're tweaking. So, if you add 7 hours, you don't end up with the day incrementing, just the hours.
auto dt = DateTime(2015, 8, 2, 20, 0, 0);
dt.roll!"hours"(7);
assert(dt == DateTime(2015, 8, 2, 3, 0, 0));

Now, things do get a bit funnier with months and years, because they don't have a fixed length. And that's why Duration does not support them. You can't say that x hecto-nanoseconds is equivalent to y months or z years. But while Duration doesn't make sense with regards to months or years, we still want to be able to add months and years to a Date or DateTime. So, we have add!"years" and add!"months" to handle that, and it allows you to control some of the oddities like whether adding 1 month to January 31st should end up at the end of February or the beginning of March (since there is no February 31st).
None of this takes any kind of time zone into account. It's purely dealing with calendar time. add and roll are purely calendar-based operations, and += as implemented on DateTime, Date, and TimeOfDay is a calendar-based operation. It is taking the years, months, days, etc. into account when it does its calculations (and can't do otherwise in their case, because the units are split out among their member variables).
And then we have SysTime. It's intended to represent the system's time (which does mean taking the time zone into account). However, the only way to avoid DST-related issues and the like is to always keep the time in UTC. So, SysTime always keeps its time internally in UTC (in hecto-nanoseconds) and uses a TimeZone object (LocalTime by default) to convert that to a particular time zone only when it needs to. This avoids all kinds of annoying time-related bugs. And anyone operating on the system's time should be using SysTime rather than DateTime, Date, or TimeOfDay.
So, when you add to a SysTime using +=, you're really just adding the hecto-nanoseconds from the Duration to the hecto-nanoseconds that SysTime uses internally. No calendar operations occur whatsoever (and if they did, you'd end up with lots of DST-related bugs). SysTime is not inherently calendar-based at all. In order to do any calendar operations, a SysTime's hecto-nanoseconds that it holds internally must be converted to whatever that represents in terms of a  date on the Gregorian calendar (using the TimeZone object to take the time zone into account).
However, in order to be user-friendly, SysTime provides many of the calendar-based properties and functions that DateTime does (e.g. the year, month, day, hour, etc. properties and the add and roll functions). To support that, it basically ends up converting to Date or DateTime internally to do them, which means taking the time zone into account and which potentially means introducing DST bugs if they're not used correctly. And in some cases, it's annoyingly inefficient. For example, if you have a SysTime variable called st
auto year = st.year;
auto month = st.month;
auto day = st.day;

converts st to Date three times, whereas it would have been more efficient to just convert to a Date explicitly and get the units from there. So, that user-friendliness is a bit of a double-edged sword.
Also, it raises the question that Adam raised about how adding and rolling deal with DST. roll and add on SysTime both deal with a Date or DateTime internally, and that takes DST into account, because converting from SysTime to Date or DateTime converts it from UTC to whatever its TimeZone object represents. So, roll and add operate on SysTime exactly how they'd operate on DateTime - because they're converting to DateTime and back again.
But as I already said, += on SysTime just adds the Duration to its UTC time. So, there is no way on a SysTime to add units smaller than months to it and take DST into account. You'd have explicitly convert to a DateTime, use += on that, and then convert it back to a SysTime, which is a bit ugly, but it's not something that you'd normally want. I suppose that we could make SysTime.add work with units smaller than months, but then you'd just end up with folks using that and ending up with DST-related bugs when they should have been using += but didn't understand the difference.
Really, at this point, I question that adding those calendar functions to SysTime was wise and that it's actually ultimately harming usability rather than helping as was intended. But I doubt that we could change it at this point - or more accurately, while we could change it, I question that deprecating those functions on SysTime and forcing folks to change their code would be worth the pain that it would cause. If I could redo it though, I'd seriously consider not putting any calendar-based operations on SysTime.
In any case, hopefully that wall of text was enlightening enough to be worth your time.


text:
Q: Self referencing interface This is the kind of thing I want to do:
Interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever)
}

so that classes implementing this must have a function that returns a list of their own type.
Is this even possible?
I know that - technically - a class implementing this could return a list of other classes which implement this, not necessarily the same class, but I can live with that even though it isn't ideal.
I have tried this, but I can't get the implementing class to correctly implement the method.

A: This is a normal solution. Consider you have interface IPerson and you want to access each parent of a person. So it would be reasonable to have interface declaration as following:
interface IPerson
{
    IList<IPerson> GetAllParents();
}

Now you are able to get parents of that parents and then get parents... Hope you got the idea. Such design is very flexible, because it allows to model deep dynamic structures using simple static models.
Implementation is very straight-forward:
class Person : IPerson
{
    IList<IPerson> parents;

    public Person(IList<IPerson> parents)
    {
        this.parents = parents;
    }

    public IList<IPerson> GetAllParents()
    {
        return parents;
    }
}

In some sense you need to create some Persons without parents (some kind of Adam and Eve) and then add childs by holding references to their parents. As you can see, my naive model can handle randomly deep family structures, while having very simple interface exposed outside.

A: Implementing this interface is straight forward:
public class MyInterfaceImpl : IMyInterface
{
    public List<IMyInterface> GetAll(string whatever)
    {
        return new List<IMyInterface> { new MyInterfaceImpl(), this };
    }
}

Please note that the method signature needs to be exactly the same, i.e. the return type has to be List<IMyInterface> and not List<MyInterfaceImpl>.
If you want the type in the list to be the same type as the class that implements the interface, you will have to use generics:
public interface IMyInterface<T> where T : IMyInterface<T>
{
    List<T> GetAll(string whatever)
}

public class MyInterfaceImpl : IMyInterface<MyInterfaceImpl>
{
    public List<MyInterfaceImpl> GetAll(string whatever)
    {
        return new List<MyInterfaceImpl > { new MyInterfaceImpl(), this };
    }
}

A: I don't see why interface could not reference itself - no problem with below.
interface ITest
{
    List<ITest> GetAll(string whatever);
}

class MyClass : ITest
{
    public List<ITest> GetAll(string whatever)
    {
        return new List<ITest>();
    }
}

A: This works for me:
public interface IMyInterface
{
    List<IMyInterface> GetAll(string whatever);
}

public class Program : IMyInterface
{
    public string Member { get; set; }

    public List<IMyInterface> GetAll(string whatever)
    {
        return new List<IMyInterface>()
            { new Program() { Member = whatever } };
    }

    static void Main(string[] args)
    {
        List<IMyInterface> all = new Program().GetAll("whatever");
        Console.WriteLine(all.Count);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: CakePHP 3.x beforeFind() callback, when it fire? I use CakePHP beforeFind() callback for my Tables ain this way:
public function beforeFind($event, $query, $options, $primary)
{
    // if ->applyOptions(['default' => false]) not use default conditions
    if(isset($options['default']) && $options['default'] == false){
        return $query;
    }

    $query->where(['visible' => 1]);

    $query->order(['sort' => 'ASC']);

    return $query;
}

And this is correct, BUT WHEN i try to retrieve my result sometimes it fired and sometimes no.
NO - I think that if i use table registry for get my table: TableRegistry::get('MyTable')->find()->first() its not fired.
YES - And if i use, from same controller, $this->Pages->find()->first() its fired!
Its work in this way only for me? Or for have the beforeFind() fired i need to do some additional stuff?

A: You need to make sure your fields are not ambiguous as part of your query. Try adding the name of the model in the where queries, otherwise you'll get PDOExceptions:
$query->where(['myModel.visible'=>1]);


text:
Q: AJAX - Function is called for every uploaded file I am using jquery-html5-uploader to upload files via AJAX, and I have following problem. When the file is uploaded, the*handleSuccess* function is being called - for every uploaded file. That is creating me a problem - when you click on image link is being inserted in textarea. In my case, for every file, the same number of links are being inserted. How can I call function only once, or remove all objects created and get only one object (or basically anything that can prevent this )?
Code:
function img_upload(url) {
    {
        var fileTemplate = "
";
        fileTemplate += "

";
        fileTemplate += "
{{filename}}
";
        fileTemplate += "Obriši Sliku";
        fileTemplate += "
";

        function slugify(text) {
            text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
            text = text.replace(/-/gi, "_");
            text = text.replace(/\s/gi, "-");
            return text;
        }
        $("#dropbox").html5Uploader({
            postUrl: url,
            onClientLoadStart: function (e, file) {
                var upload = $("#upload");
                if (upload.is(":hidden")) {
                    upload.show();
                }
                upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name))
            },
            onClientLoad: function (e, file) {
                $("#" + slugify(file.name))
                    .find(".preview")
                    .append("");

            },
            onServerLoad: function (e, file) {

            },
            onSuccess : function(e, file, data) {
            var id_slika = slugify(file.name)
            upload_folder = $('#upload');
            upload_folder.find('#' + id_slika).find('a').attr('data-id', data);

                var img_delete = $('.image_delete_tmp');
            handleSuccess(upload_folder);

                delete_image(img_delete, 'tmp');
            }
        });
    }
}

function handleSuccess() {
  var upload_folder = $('#upload');
  console.log(upload_folder.first());
  upload_folder.on('click', 'img', function(e){

    var $this = $(this),
    text = $this.parent().parent().find('a').data('id'),
    img = ('<img src="<?php echo IMG ?>pages/' +  text +  '" />');
    $("#page_srb").insertAtCursor(img);
    // element.remove();
    return false;

});
}

And this is what I get when I click on file (this is for 3 files):

A: it would be easy if this plugin supported something like onSuccessAll... but it doesn't by the look of it... if it's only the matter of displaying only one image, I would:
function handleSuccess() {
  var upload_folder = $('#upload');
  console.log(upload_folder.first());
  upload_folder.on('click', 'img', function(e){

    if ($(".onlyone").length < 1){
        var $this = $(this),
        text = $this.parent().parent().find('a').data('id'),
        img = ('<img class="onlyone" src="<?php echo IMG ?>pages/' +  text +  '" />');
        $("#page_srb").insertAtCursor(img);
        // element.remove();
        return false;
    }
});
}

so it checks if there are already elements with class onlyone and only if there isn't it will add image. However it means that image will be displayed from the first upload, not the last.


text:
Q: Unwind to another brach of segues in swift or Objective-C I have a scenario like this:
        /-> C -> D \
A -> B -            -> G (Contain values of D and F,
        \-> E -> F /

Basically at G I have a list of value produce by D and F, let us call D1 and F1.
To create a new value from G, I have to just unwind to B and user can either choose branch C or E and continue to the end G with value of D2 or F2, or he can pop back to A. Let us say the new value is F2, though ABEFG
Now I'm facing a problem, that is I want to edit the values at G, let us say D1.
I want to be able to pop back to D but also allow users pop back to C etc, but D is not in the workflow ABEFG.
My guess is that I have to back up to B and somehow prepare multiple segues up to D but I have no idea if this kind of workflow exists.

A: Apparently, there is no such way. The solution I found is

*

*Find the instance of B in navigationController!.viewControllers

*popToViewController B

*Initiate C & D from Main storyboard with identifier (they are already deallocated anyway)

*Setup some properties of C & D from D1

*pushViewController C & D


text:
Q: Two Y-Axes for Violin Plots? - R I am trying to visualize my data of biomass for various size classes at different sampling depths - depths are used multiple times for each size class.
I would like to use a violin plot or something similar, as I think it would be good to show the average Biomass at varying depths. However, I am unsure if that is possible with two continuous variables (depth, biomass).
Is there a possible way to visualize this data in violin plots? I have been trying to modify the below chunk of code with no luck. I have attempted grouping by SizeBin, coloring by SizeBin, etc. Any insight on code or alternatives is appreciated.
ggplot(data_frame, aes(x=Depth,
             y=Biomass,
             fill=SizeBin)) + geom_violin()

Depth
Biomass
SizeBin

1.5
6.86
A

2.5
3.51
A

2.5
2.45
A

1.5
0.80
B

2.5
1.34
B

A: You can try to split the violin plot.
Here's how to do it: https://r-charts.com/distribution/split-violin-plot/
Or this: Split violin plot with ggplot2
I personally really like those plots.


text:
Q: How to add two values from a pointer in function? My teacher said that I must add two complex numbers using a complex type. And I must add these numbers in a function. How to do that?
I create something like that, but I have warning when I use cppcheck
add.c:53:26: error: Uninitialized variable: a1 [uninitvar]
    double complex  z1 = a1 + b1*I;
                         ^
add.c:57:26: error: Uninitialized variable: a2 [uninitvar]
    double complex  z2 = a2 + b2*I;
                         ^
add.c:53:31: error: Uninitialized variable: b1 [uninitvar]
    double complex  z1 = a1 + b1*I;
                              ^
add.c:57:31: error: Uninitialized variable: b2 [uninitvar]
    double complex  z2 = a2 + b2*I;
                              ^
add.c:34:29: error: Uninitialized variable: c1 [uninitvar]
    double complex  csum1 = c1 + d1*I;
                            ^
add.c:34:34: error: Uninitialized variable: d1 [uninitvar]
    double complex  csum1 = c1 + d1*I;
                                 ^
add.c:52:15: error: Uninitialized variable: p [uninitvar]
    readZ(wz, p, q);
              ^
add.c:52:18: error: Uninitialized variable: q [uninitvar]
    readZ(wz, p, q);
                 ^
add.c:56:15: error: Uninitialized variable: r [uninitvar]
    readZ(wz, r, s);
              ^
add.c:56:18: error: Uninitialized variable: s [uninitvar]
    readZ(wz, r, s);
                 ^
add.c:59:18: error: Uninitialized variable: t [uninitvar]
    sumZ(p,q,r,s,t,u);
                 ^
add.c:59:20: error: Uninitialized variable: u [uninitvar]
    sumZ(p,q,r,s,t,u);

This is my code
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <complex.h>
#ifndef M_PI
    #define M_PI 3.14159265358979323846
#endif

void readZ(FILE *wp, double *a, double *b)
{
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,a,&c,b,&c,&c));

}
int writeZ(FILE *wp, double complex z)
{
    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}

void sumZ(double *a1, double *a2, double *b1, double *b2, double *c1, double *c2)
{
    *c1 = *a1 + *a2;
    *c2 = *b1 + *b2;
}

int main (int argc, char *argv[])
{
    FILE *wz, *wc;
    double a1, a2, b1, b2, c1, d1;
    double *p, *q, *r, *s, *t, *u;
    double complex  csum1 = c1 + d1*I;

    if (argc != 3) {
    printf("Wrong arguments number\n");
    printf("I should run this way:\n");
    printf("%s source result\n",argv[0]);
    exit(1);
    }

    if( (wz= fopen(argv[1],"r")) == NULL) {
        printf("Open error %s\n", argv[1]);
        exit(1);
    }
    if( (wc= fopen(argv[2], "w")) == NULL) {
        printf("Open error %s\n", argv[2]);
        exit(2);
    }

    readZ(wz, p, q);
    double complex  z1 = a1 + b1*I;
    writeZ(wc, z1);
    printf("%.2f, %.2f\n", creal(z1), cimag(z1));
    readZ(wz, r, s);
    double complex  z2 = a2 + b2*I;
    printf("%.2f, %.2f\n", creal(z2), cimag(z2));
    sumZ(p,q,r,s,t,u);
    printf("%.2f, %.2f\n", creal(csum1), cimag(csum1));

    return 0;
}

When I run my code like add.x data.txt result.txt I get a segmentation fault. He said that I can use references and pointers. I have no idea what I should do now.

A: There were a number of errors.
There were a lot of double * pointer variables [that were unitialized]. They aren't really needed. main can just pass down (e.g.) &a1 and &b1. Just because you were told to use pointers doesn't [necessarily] mean that you have to use pointer variables.
Also, pointers as arguments to a function are only needed for return values. Others can just use variables that are "pass by value". This simpilifies things a bit.
I had to guess at the correct function calls, based on an analysis of the code to determine your exact intent.
Your code was still trying to use separate double variables (e.g.) a1 and b1 to get z1 instead of using [mostly] double complex variables everywhere.
Also, it appears that the argument order for the call to sumZ were reversed.

Here's a version that is annotated with the bugs and fixes:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <complex.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

void
readZ(FILE *wp, double *a, double *b)
{
    char c;

#if 0
    assert(fscanf(wp, "%c%lg%c%lg%c%c", &c, a, &c, b, &c, &c));
#else
    assert(fscanf(wp, "%c%lg%c%lg%c%c", &c, a, &c, b, &c, &c));
#endif
}

int
writeZ(FILE *wp, double complex z)
{

    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}

// NOTE: not a bug exactly, but to simplify, b1/b2 and c1/c2 can be passed by
// value -- otherwise, mark them with "const" (e.g. const double *b1)
#if 0
void
sumZ(double *a1, double *a2, double *b1, double *b2, double *c1, double *c2)
{
    *c1 = *a1 + *a2;
    *c2 = *b1 + *b2;
}
#endif
#if 0
void
sumZ(double a1, double a2, double b1, double b2, double *c1, double *c2)
{
    *c1 = a1 + a2;
    *c2 = b1 + b2;
}
#endif
#if 1
void
sumZ(double complex a1, double complex b1, double complex *c1)
{
    *c1 = a1 + b1;
}
#endif

int
main(int argc, char *argv[])
{
    FILE *wz;
    FILE *wc;
    double a1;
    double a2;
    double b1;
    double b2;
// NOTE: with refactoring, these are now unused
#if 0
    double c1;
    double d1;
    double *p;
    double *q;
    double *r;
    double *s;
    double *t;
    double *u;
#endif
#if 0
    double csum1;
    double csum2;
#endif
// NOTE/BUG: c1 and d1 are _unitialized_
#if 0
    double complex csum1 = c1 + d1 * I;
#else
    double complex csum1;
#endif

    if (argc != 3) {
        printf("Wrong arguments number\n");
        printf("I should run this way:\n");
        printf("%s source result\n", argv[0]);
        exit(1);
    }

    if ((wz = fopen(argv[1], "r")) == NULL) {
        printf("Open error %s\n", argv[1]);
        exit(1);
    }
    if ((wc = fopen(argv[2], "w")) == NULL) {
        printf("Open error %s\n", argv[2]);
        exit(2);
    }

// NOTE/BUG: _pointers_ p and q are _unitialized_
#if 0
    readZ(wz, p, q);
#else
    readZ(wz, &a1, &b1);
#endif
// NOTE/BUG: a1 and b1 are _unitialized_ -- assume that above readZ needs to
// be changed
    double complex z1 = a1 + b1 * I;

    writeZ(wc, z1);
    printf("%.2f, %.2f\n", creal(z1), cimag(z1));

// NOTE/BUG: _pointers_ r and s are _unitialized_
#if 0
    readZ(wz, r, s);
#else
    readZ(wz, &a2, &b2);
#endif

// NOTE/BUG: a2 and b2 are _unitialized_ -- assume that above readZ needs to
    double complex z2 = a2 + b2 * I;
    printf("%.2f, %.2f\n", creal(z2), cimag(z2));

// NOTE/BUG: arguments are backwards if you want csum* to be the _sum_
#if 0
    sumZ(p, q, r, s, t, u);
#endif
#if 0
    sumZ(a1, b1, a2, b2, &csum1, &csum2);
#endif
#if 1
    sumZ(z1, z2, &csum1);
#endif

    printf("%.2f, %.2f\n", creal(csum1), cimag(csum1));

    fclose(wz);
    fclose(wc);

    return 0;
}

Here's a cleaned up version that changes readZ to return a double complex directly, which is [probably] closer to what was intended:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include <complex.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

void
readZ(FILE *wp, double complex *rtn)
{
    char c;
    double a;
    double b;

    assert(fscanf(wp, "%c%lg%c%lg%c%c", &c, &a, &c, &b, &c, &c));

    *rtn = a + b * I;
}

int
writeZ(FILE *wp, double complex z)
{

    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}

void
sumZ(double complex a1, double complex b1, double complex *c1)
{
    *c1 = a1 + b1;
}

int
main(int argc, char *argv[])
{
    FILE *wz;
    FILE *wc;
    double complex csum1;

    if (argc != 3) {
        printf("Wrong arguments number\n");
        printf("I should run this way:\n");
        printf("%s source result\n", argv[0]);
        exit(1);
    }

    if ((wz = fopen(argv[1], "r")) == NULL) {
        printf("Open error %s\n", argv[1]);
        exit(1);
    }
    if ((wc = fopen(argv[2], "w")) == NULL) {
        printf("Open error %s\n", argv[2]);
        exit(2);
    }

    double complex z1;
    readZ(wz, &z1);
    writeZ(wc, z1);
    printf("%.2f, %.2f\n", creal(z1), cimag(z1));

    double complex z2;
    readZ(wz, &z2);
    printf("%.2f, %.2f\n", creal(z2), cimag(z2));

    sumZ(z1, z2, &csum1);
    printf("%.2f, %.2f\n", creal(csum1), cimag(csum1));

    fclose(wz);
    fclose(wc);

    return 0;
}


text:
Q: 6 level cascading dropdown list using JSON array I have a JSON array with multiple objects that I want to incorporate with my drop-down list. Is it possible to create a 6-level cascading drop-down list which are dependent with each other? When the user choose a model, the different car models will populate the second dropdown list then the user will choose the car model and then the third to sixth dropdown list will then be populated by their respective year, color, price and transmission. I am new to javascript any help will be appreciated

 var json = [{
      "Model": "BMW",
      "Car_Model": "6-series Gran Turismo",
      "Year": "2018",
      "Color": "Orange",
      "Price": "$71,195",
   "Transmission": "Manual"
    },
    {
      "Model": "BMW",
      "Car_Model": "i8",
      "Year": "2019",
      "Color": "Black",
      "Price": "$148,495",
   "Transmission": "Manual"
    },
    {
      "Model": "BMW",
      "Car_Model": "M5",
      "Year": "2017",
      "Color": "Blue",
      "Price": "$103,595",
   "Transmission": "Automatic"
    },
    {
      "Model": "Toyota",
      "Car_Model": "Sedan",
      "Year": "2017",
      "Color": "White",
      "Price": "$102,510",
   "Transmission": "Manual"
    },
    {
      "Model": "Toyota",
      "Car_Model": "Camry",
      "Year": "2015",
      "Color": "Red",
      "Price": "$122,810",
   "Transmission": "Automatic"
    },
    {
      "Model": "Toyota",
      "Car_Model": "Corolla",
      "Year": "2016",
      "Color": "Blue",
      "Price": "$152,870",
   "Transmission": "Automatic"
    },
    {
      "Model": "Toyota",
      "Car_Model": "Hilux",
      "Year": "2018",
      "Color": "Black",
      "Price": "$258,695",
   "Transmission": "Manual"
    },
    {
      "Model": "Toyota",
      "Car_Model": "Vios",
      "Year": "2019",
      "Color": "Blue",
      "Price": "$198,615",
   "Transmission": "Automatic"
    },
    {
      "Model": "Hyundai",
      "Car_Model": "Elantra",
      "Year": "2017",
      "Color": "Black",
      "Price": "$152,590",
   "Transmission": "Manual"
    },
    {
      "Model": "Hyundai",
      "Car_Model": "Tucson",
      "Year": "2018",
      "Color": "Red",
      "Price": "$132,690",
   "Transmission": "Automatic"
    },
    {
      "Model": "Honda",
      "Car_Model": "Civic",
      "Year": "2016",
      "Color": "Blue",
      "Price": "$171,395",
   "Transmission": "Manual"
    },
    {
      "Model": "Honda",
      "Car_Model": "Accord",
      "Year": "2019",
      "Color": "Black",
      "Price": "$159,445",
   "Transmission": "Automatic"
    },
    {
      "Model": "Honda",
      "Car_Model": "CR-V",
      "Year": "2017",
      "Color": "White",
      "Price": "$193,675",
   "Transmission": "Manual"
    }
  ];

So far, this is what I have

var addOptionList = {
    A: ["6-series Gran Turismo", "i8", "M5"],
    B: ["Sedan", "Camry", "Corolla", "Hilux", "Vios"],
 C: ["Elantra", "Tucson"],
    D: ["Civic", "Accord", "CR-V"],

}

    function changecat(value) {
        if (value.length == 0) document.getElementById("car_model").innerHTML = "<option></option>";
        else {
            var catOptions = "";
            for (categoryId in addOptionList[value]) {
                catOptions += "<option>" + addOptionList[value][categoryId] + "</option>";
            }
            document.getElementById("car_model").innerHTML = catOptions;
        }
    }
MODEL:
      <select id="model" name="model" onchange="changecat(this.value);" >
          <option value="" selected="selected">Select Model...</option>
          <option value="A"> BMW </option>
          <option value="B"> Toyota </option>
          <option value="C"> Hyundai </option>
          <option value="D"> Honda </option>
        </select>
      </select>
CAR MODEL:
      <select ID="car_model" NAME="car_model">
      <option value="" selected="selected">Select Model First...</option>
   </select>
YEAR:
     <select ID="year" NAME="year">
     </select>
COLOR:
     <select id = "color" name = "color">
     </select>
PRICE:
     <select id = "price" name = "price">
     </select>
TRANSMISSION:
     <select id = "trnasmission" name = "transmission">
     </select>

A: Did i understand you right? if you selected one of those choices from the Model the following select box will also change depends on the json array data?
If yes check these lines of code:

  $(document).ready(function(){
    for(i=0;i<json.length;i++){
       $("#Model").append("<option value="+ json[i]["Model"] +">"+ json[i]["Model"] +"</option>");
       $("#Car_Model").append("<option value="+ json[i]["Model"] +">"+ json[i]["Car_Model"] +"</option>");
       $("#Year").append("<option value="+ json[i]["Model"] +">"+ json[i]["Year"] +"</option>");
       $("#Color").append("<option value="+ json[i]["Model"] +">"+ json[i]["Color"] +"</option>");
       $("#Price").append("<option value="+ json[i]["Model"] +">"+ json[i]["Price"] +"</option>");
       $("#Transmission").append("<option value="+ json[i]["Model"] +">"+ json[i]["Transmission"] +"</option>");
    }
  })

  $("#Model").change(function(){
      $("#Car_Model")[0].selectedIndex = $(this)[0].selectedIndex
       $("#Year")[0].selectedIndex = $(this)[0].selectedIndex
       $("#Color")[0].selectedIndex = $(this)[0].selectedIndex
       $("#Price")[0].selectedIndex = $(this)[0].selectedIndex
       $("#Transmission")[0].selectedIndex = $(this)[0].selectedIndex
  })

<select id="Model"></select>
<select id="Car_Model"></select>
<select id="Year"></select>
<select id="Color"></select>
<select id="Price"></select>
<select id="Transmission"></select>


text:
Q: How to retrieve certain database child and display inside the ListView How to retrieve/call userInfo from the following database, It is an authenticated user information

StudentInformation java class.

public class StudentInformation {

    String name;
    String ID;
    String studentID;
    String email;
    String phone_num;

    public StudentInformation() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getID() {
        return ID;
    }

    public void setID(String ID) {
        this.ID = ID;
    }

    public String getStudentID() {
        return studentID;
    }

    public void setStudentID(String studentID) {
        this.studentID = studentID;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone_num() {
        return phone_num;
    }

    public void setPhone_num(String phone_num) {
        this.phone_num = phone_num;
    }
}

I've tried a lot of method, but the ListView still display none and the app suddenly stopped.
public class StudentInfoActivity extends AppCompatActivity {

    //add Firebase Database stuff
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;
    private  String userID;

    ListView mListView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_info);

        mListView = (ListView) findViewById(R.id.listview);

        //declare the database reference object. This is what we use to access the database.
        //NOTE: Unless you are signed in, this will not be useable.
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    toastMessage("User Information");
                } else {}
                // ...
            }
        }; //end authlistener

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                showData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    } // end oncreate

    private void showData(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()){
        StudentInformation sInfo = new StudentInformation();

            sInfo.setName(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getName());
            sInfo.setID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getID());
            sInfo.setStudentID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getStudentID());
            sInfo.setEmail(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getEmail());
            sInfo.setPhone_num(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getPhone_num());

            ArrayList<String> array  = new ArrayList<>();
            array.add(sInfo.getName());
            array.add(sInfo.getID());
            array.add(sInfo.getStudentID());
            array.add(sInfo.getEmail());
            array.add(sInfo.getPhone_num());
            ArrayAdapter adapter = new     ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
        mListView.setAdapter(adapter);

        }
    } //end showdata

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    private void toastMessage(String message){
        Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
    }
} // end class

This is the code Im using. I've been wondering about the getchildren method, did I do something wrong in the code ?. Can anyone help me with this ?

A: To get the data please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInfoRef = rootRef.child("users").child(userID).child("userInfo");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String ID = ds.child("ID").getValue(String.class);
        String email = ds.child("email").getValue(String.class);
        String name = ds.child("name").getValue(String.class);
        String phone_num = ds.child("phone_num").getValue(String.class);
        String studentID = ds.child("studentID").getValue(String.class);
        Log.d("TAG", ID + " / " + email + " / " + name + " / " + phone_num + " / " + studentID);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
userInfoRef.addListenerForSingleValueEvent(eventListener);

A: You can go with FirebaseListAdapter .Here you won't have to manage any changes or attach listener and everything in the list gets updated when there is any change in server


text:
Q: INSERT INTO if NOT EXISTS or increment if EXISTS My question is. I have the table 'popular' with fields 'id', 'title', 'popularity' in MySQL. I need insert info into field "title", if info not exists or increment  value of 'popularity', if info exists. What is the best practice to do it?

A: INSERT ... ON DUPLICATE KEY UPDATE Syntax

A: INSERT INTO popular (title, popularity) VALUES (:the_title, 1)
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), popularity = popularity + 1

Make sure you have an unique constraint on title
id = LAST_INSERT_ID(id) allows you to get the id of the record you inserted/updated using LAST_INSERT_ID (or the equivalent function for your MySQL API). If you don't need the id you can remove it from the UPDATE list.

A: sample code:
if exists (select * from contact where name = @name) then
    select -1;
else
    insert into contact(name) values(@name);
    select last_insert_id();
end if;

reference:
http://ask.sqlservercentral.com/questions/88038/best-mysql-practice-to-insert-a-record-if-it-does.html
http://bugs.mysql.com/bug.php?id=19243
http://mikefenwick.com/blog/insert-into-database-or-return-id-of-duplicate-row-in-mysql/


text:
Q: windows phone 8.1 webview loaded document source code I need to get source code of web page which "loaded" on webview. Is there any way of doing this ?
I tried it on Windows Form Application. I can reach data easily with this :
webBrowser1.Document.Body.InnerText

But in windows phone 8.1 i can't do this.

A: Use InvokeScriptAsync method.
string html = await webBrowser1.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });

Answer based on Can I get the current HTML or Uri for the Metro WebView control?


text:
Q: button inside position fixed table structure cannot click after scrolling on android mobile I have a position: fixed; bottom: 0 table and have a button inside it.
It looks and works fine on a normal browser and ios browser.
However, if we try that table on Android Chrome browser, the button can be click when the url bar is shown, but after you scroll down a bit and make the url bar disappear. The button is no longer clickable anymore.
Here are my HTML structure and css :

.Wrapper {
  z-index: 10;
  height: 72px;
  width: 100%;
  position: fixed;
  top: inherit;
  bottom: 0;
  left: 0;
  right: 0;
}
 <Wrapper>

          Some text here
          <button type="button" onClick={this.clickFunction}>Click Me!</button>

  </Wrapper>


text:
Q: Ordering array by dependencies with perl Have an array of hashes,
my @arr = get_from_somewhere();

the @arr contents (for example) is:
@arr = (
  { id => "id2",    requires => 'someid', text => "another text2" },
  { id => "xid4",   requires => 'id2',    text => "text44" },
  { id => "someid", requires => undef,    text => "some text" },
  { id => "id2",    requires => 'someid', text => "another text2" },
  { id => "aid",    requires => undef,    text => "alone text" },
  { id => "id2",    requires => 'someid', text => "another text2" },
  { id => "xid3",   requires => 'id2',    text => "text33" },
);

need something like:
my $texts = join("\n",  get_ordered_texts(@arr) );

soo need write a sub what return the array of texts from the hashes, - in the dependent order, so from the above example need to get:
"some text",     #someid the id2 depends on it - so need be before id2
"another text2", #id2    the xid3 and xid4 depends on it - and it is depends on someid
"text44",        #xid4   the xid4 and xid3 can be in any order, because nothing depend on them
"text33",        #xid3   but need be bellow id2
"alone text",    #aid    nothing depends on aid and hasn't any dependencies, so this line can be anywhere

as you can see, in the @arr can be some duplicated "lines", ("id2" in the above example), need output only once any id.
Not providing any code example yet, because havent any idea how to start. ;(
Exists some CPAN module what can be used to the solution?
Can anybody points me to the right direction?

A: An interesting problem.
Here's my first round solution:
sub get_ordered_texts {
    my %dep_found;  # track the set of known dependencies
    my @sorted_arr; # output

    my $last_count = scalar @_; # infinite loop protection
    while (@_ > 0) {
        for my $value (@_) {

            # next unless we are ready for this text
            next if defined $value->{requires}
                and not $dep_found{ $value->{requires} };

            # Add to the sorted list
            push @sorted_arr, $value->{text};

            # Remember that we found it
            $dep_found{ $value->{id} }++;
        }

        if (scalar @_ == $last_count) die "some requirements don't exist or there is a dependency loop";
        $last_count = scalar @_;
    }

    return \@sorted_arr;
}

This is not terribly efficient and probably runs in O(n log n) time or something, but if you don't have a huge dataset, it's probably OK.

A: I would use a directed graph to represent the dependency tree and then walk the graph. I've done something very similiar using Graph.pm
Each of your hashes would be a graph vertex and the edge would represent the dependency.This has the added benefit of supporting more complex dependencies in the future as well as providing shortcut functions for working with the graph.

A: Using Graph:
use Graph qw( );

my @recs = (
   { id => "id2",    requires => 'someid', text => "another text2" },
   { id => "xid4",   requires => 'id2',    text => "text44" },
   { id => "someid", requires => undef,    text => "some text" },
   { id => "id2",    requires => 'someid', text => "another text2" },
   { id => "aid",    requires => undef,    text => "alone text" },
   { id => "id2",    requires => 'someid', text => "another text2" },
   { id => "xid3",   requires => 'id2',    text => "text33" },
);

sub get_ordered_recs {
   my %recs;
   my $graph = Graph->new();
   for my $rec (@_) {
      my ($id, $requires) = @{$rec}{qw( id requires )};

      $graph->add_vertex($id);
      $graph->add_edge($requires, $id) if $requires;

      $recs{$id} = $rec;
   }

   return map $recs{$_}, $graph->topological_sort();
}

my @texts = map $_->{text}, get_ordered_recs(@recs);

A: *

*you didn't say what to do of the dependencies are "independent" of each other.
E.g. id1 requires id2; id3 requires id4; id3 requires id5. What should the order be? (other than 1 before 2 and 3 before both 4/5)

*What you want is basically a BFS (Breadth First Search) of a tree (directed graph) of dependencies (or a forest depending on answers to #1 - the forest being a set of non-connected trees).
To do that:

*

*Find all of the root nodes (ids that don't have a requirement themselves)
You can easily do that by making a hash of ALL the IDs using grep on your data structure

*Put all those root modes into a starting array.

*Then implement BFS. If you need help implementing basic BFS using an array and a loop in Perl, ask a separate question. There may be a CPAN module but the algorithm/code is rather trivial (at least once you wrote it once :)


text:
Q: Setting dropdown values in Javascript I have a dropdown with following HTML.
<select name="custom_123" id="custom_123_123" class="custom form-control form-control-full form-select searchable  abcd-done" style="display: none;">
<option value="" selected="selected">None</option>
<option value="1">Alaska</option>
<option value="2">Newyork</option>
</select>

Alaska

I want to be able to select Newyork in the dropdown. For that, I am during the following.
var dropdown_id = document.querySelector('[id^="custom_123"]').id;
var dropdown_abcd = dropdown_id + 'abcd';
document.getElementById(dropdown_abcd).getElementsByClassName("abcd-single")[0].innerHTML = "Alaska";

But the same doesn't get applied. Can anyone help?

A: Here is an example based on your code:
const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';

Update on comment
If there are listeners on the select, here is an example on how to fire a change event.
const select = document.querySelector('[id^="custom_123"]');
select.value = 'Alaska';
select.dispatchEvent(new CustomEvent('change'));


text:
Q: Finding the (smallest) hypersphere that encloses a known ellipsoid without computing eigenvalues I am working on the problem of finding the (smallest) hypersphere that encloses a known ellipsoid, with possible equality on the ellipsoid's largest semi-axes, without computing any eigenvalues.  I am attempting to set about this as follows:
Let
$$
(\mathbf{x}-\mathbf{x}_0)^\intercal \mathbf{A}(\mathbf{x}-\mathbf{x}_0) = 1
$$
describe the ellipsoid, $E$, concerned.  To be explicit, $\mathbf{A}$ is symmetric positive definite and nonsingular.  Then by observing that
$$
r_0 := r(\mathbf{A}^{-1})
$$
where $r(\mathbf{A}^{-1})$ is the spectral radius of $\mathbf{A}^{-1}$, $\sqrt{r_0}$ represents the length of the largest semi-axis of $E$.  Therefore the hypersphere $C$ described by
$$
(\mathbf{x}-\mathbf{x}_0)^\intercal(\mathbf{x}-\mathbf{x}_0) = r_0
$$
is exactly the smallest hypersphere that encloses $E$ with equality occurring at the end-point of each semi-axis of $E$ having $r_0$ as its length.
Now, to avoid computing any eigenvalues I am considering the formula of Gelfand which states that for any matrix $\mathbf{M}$ and consistent matrix norm $\|\cdot\|$,
$$
r(\mathbf{M}) \leq \|\mathbf{M}^k\|^{\frac{1}{k}} =: n_k(\mathbf{M})
$$
for all $k$.  Therefore any hypersphere $C_k$ described by
$$
(\mathbf{x}-\mathbf{x}_0)^\intercal(\mathbf{x}-\mathbf{x}_0) = n_k(\mathbf{A}^{-1})
$$
encloses $E$, with $C_k = C$ in the case of Gelfand's limit
$$
r_0 = \lim_{k\rightarrow\infty} \left\| \left(\mathbf{A}^{-1}\right)^k \right\|^{\frac{1}{k}}.
$$
My questions therefore are:

*

*Is this approach a valid one as described?

*If so, what knowledge is there on the rate of convergence of Gelfand's limit, or better still, the error bounds, in terms of $k$, $\|\cdot\|$ and the form of $\mathbf{A}$?  And therefore,

*Is there an optimal matrix norm that achieves minimal error bound given the particular form of $\mathbf{A}$?


text:
Q: How can I print lua Bytecode without it being converted to its readable equivalent? How can I print bytecode (for example \122, equivalent to lower-case "z") without it converting to its readable equivalent?
Here is my code:
symbols = {
        forwardslash = "\47",
        backslash = "\92",
        andsymbol = "\38",
        starthing = "\42",
        hashtag = "\35",
        atsymbol = "\64",
        dot = "\46",
        comma = "\44",
        exclamation = "\33",
        questionmark = "\63",
        speechmark = "\34",
        invertedcomma = "\39",
        percent = "\37",
        dash = "\45",
        underscore = "\95",
        bracket1 = "\40",
        bracket2 = "\41",
        squarebracket1 = "\91",
        squarebracket2 = "\93",
        squiglybracket1 = "\123",
        squiglybracket2 = "\125"
};
print(symbols.bracket1)

Code image: https://imgur.com/Rtwdzfc

A: Use string.byte:
print(string.byte(symbols.bracket1)) -- prints: 40

For future reference I encourage you to first take a look at the String Manipulation and other chapters of Lua Reference Manual. It's a good piece of documentation, really.
Conversion from "\40" to "(" is due to how escape sequences are handled in Lua. Refer to Lexical Conventions or see batch example below:
print("(") -- prints: (
print("\40") -- prints: (
print(string.char(40)) -- prints: (

print(40) -- prints: 40
print(string.byte("(")) -- prints: 40
print(string.byte("\40")) -- prints: 40
print(string.format("%d", 40)) -- prints: 40

print("\\40") -- prints: \40
print(string.format("\\%d", 40)) -- prints: \40
print(string.format("\\%d", string.byte("("))) -- prints: \40
print(string.format("\\%d", string.byte("\40"))) -- prints: \40

A: Combining string.byte() with string.format() for the backslash...
for k,v in pairs(symbols)
 do
  print(k..'='..string.format("\"\\%s\"",string.byte(v)))
 end

Puts out...
hashtag="\35"
squiglybracket2="\125"
speechmark="\34"
forwardslash="\47"
squarebracket2="\93"
andsymbol="\38"
dash="\45"
squiglybracket1="\123"
exclamation="\33"
bracket2="\41"
backslash="\92"
starthing="\42"
dot="\46"
squarebracket1="\91"
atsymbol="\64"
comma="\44"
invertedcomma="\39"
bracket1="\40"
percent="\37"
underscore="\95"
questionmark="\63"


text:
Q: Current week in Caldroid calendar I am working with Caldroid for my project. By default, I have to display the current week in the gridView. When a user swipe to the right, it will display the next week, and when a user swipe to the left, it will display the previous week. How can I achieve this in Caldroid?

A: Caldroid does not support any method to show a week only. You have the following options

*

*Make your own calendar control

*Extend Caldroid to do so by modifying source code

*Use some other library such as RadCalendarView if it suits your need.


text:
Q: What does this recursive algorithm do? I have an algorithm :
def generate (last, cur):
   if (cur>100):
      print cur
   return generate(cur, last+cur)

I have two questions:

*

*What will this function print?

*And, how to modify this function, so that it prints original output but in reverse order?

A: If the function generate() is called with parameters 1,1, it prints the fibonacci series starting with the first value exceeding 100, that is 144
Output:
144
233
377
610
987
1597
.... till maximum stack depth is reached..

A: Okay, this prints fibonacci series.


text:
Q: How to remove specific array elements in javascript? I have this array

var array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12']

and I would like to remove elements that contain "-12" and "-0"
Expected Result = ['20-2', '319-2', '161-2', '320-2']
How can I achieve this expected result in javascript.

A: You can do this with .filter.
Example:
var array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12'];

var filtered = array.filter(item => !item.includes('-12') && !item.includes('-0'));

After executing this code, filtered becomes ['20-2', '319-2', '161-2', '320-2'].

A: You can use Array.filter method in combination with String.includes method.

Here is an example:

let array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12']

let newArray = array.filter((element) =>
        !element.includes('-12') && !element.includes('-0')
)

console.log(newArray)

A: This can be achieved using the Array.filter combined with String.includes methods. The Array.filter method creates a new Array with each item that results in a positive condition.

let array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12']

let filteredArray = array.filter(item => (!item.includes("-12")) && !item.includes("-0"))

console.log(filteredArray)

Reference:

*

*Array.filter

*String.includes

A: If you want to find "12" and "0" at any position in the string (being the first or the second number) you can use a regular expression with \b symbolising a word boundary:

var array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12','3-120','112-14','12-7'];

const res = array.filter(el=>![/\b0\b/,/\b12\b/].some(rx=>rx.test(el)));

console.log(res)

The word boundaries in the rx ensure that elements like '3-120','112-14' will not be removed from the result set.
Instead of using two regular expressions you can - for the given problem - combine the search requirements into one:

var array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12','3-120','112-14','12-7'];

const res = array.filter(el=>!/\b(?:0|12)\b/.test(el));

console.log(res)

And, of course, if you only want to remove the elements when the numbers 0 and 12 appear after the (last) "-", you can do the following:

var array = ['20-2', '319-2', '161-2', '320-2', '12-0', '575-12', '279-12', '280-12', '412-12', '423-12', '424-12', '425-12', '291-12', '0-12', '449-12','3-120','112-14','12-7'];

const res = array.filter(el=>!/-(?:0|12)$/.test(el));

console.log(res)


text:
Q: I need to compress the thumb images | PHP Hello Stackoverflowers,
I have successfully been able to compress the main uploaded image, but I don't know how to use the same function to compress the thumbnail.
The code main purpose is as follows:
1- Upload an image
2- Rename
3- Compress
4- Create thumbnail
5- Compress the thumbnail
My issue it with number 5, I don't know how to compress the thumbnail.
Below are my php and HTML code:
if (isset($_POST["submit"])) {
    if (is_array($_FILES)) {
        if ($_FILES['image']['size'] <= 5000000) {
            $file = $_FILES['image']['tmp_name'];

            $sourceProperties = getimagesize($file);
            $fileNewName = "[" . "999" . "]-" . time();
            $folderPath = "uploads/";
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $imageType = $sourceProperties[2];

            $data = getimagesize($file);
            $width = $data[0];
            $height = $data[1];

            switch ($imageType) {

                case IMAGETYPE_PNG:
                    $imageResourceId = imagecreatefrompng($file);
                    $targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
                    imagepng($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
                    break;

                case IMAGETYPE_GIF:
                    $imageResourceId = imagecreatefromgif($file);
                    $targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
                    imagegif($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
                    break;

                case IMAGETYPE_JPEG:
                    $imageResourceId = imagecreatefromjpeg($file);
                    $targetLayer = imageResize($imageResourceId, $sourceProperties[0], $sourceProperties[1]);
                    imagejpeg($targetLayer, $folderPath . $fileNewName . "_thump." . $ext);
                    break;

                default:
                    echo "Invalid Image type.";
                    exit;
                    break;
            }

            compressImage($file, $folderPath . $fileNewName . "." . $ext, 60);

            echo "Image Resize Successfully.";
        } else {
            echo "too big!";
        }
    }
}

// Compress image
function compressImage($source, $destination, $quality)
{

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg')
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif')
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png')
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);
}

function imageResize($imageResourceId, $width, $height)
{

    $targetWidth = (20 / 100) * $width;

    $targetHeight = (20 / 100) * $height;

    echo $targetWidth . " x " . $targetHeight . "
 ($width x $height)";

    $targetLayer = imagecreatetruecolor($targetWidth, $targetHeight);
    imagecopyresampled($targetLayer, $imageResourceId, 0, 0, 0, 0, $targetWidth, $targetHeight, $width, $height);

    return $targetLayer;
}

HTML

        <form method="post" enctype="multipart/form-data">
            <input type="file" name="image" />
            <input type="submit" name="submit" value="Submit" />
        </form>

    Reload Page

Please forgive my silly question as I believe it is a very simple question, but I just started developing using php, just few months ago.
Thank you in advance and I really appreciate your help.

A: This sounds like an XY-Problem; Because all you are doing is chaging the quality.
If you need low quality thumbnail-image, then set that setting directly while creating thumbnail-image, there is no need to create yet another file.
But if you insist on going on, then simply replace original thumbnail-image with the one created by compressImage function, like:
$newFilePath = $folderPath . $fileNewName . "." . $ext;
compressImage($file, $newFilePath, 60);

// Replace.
unlink($file);
rename($newFilePath, $file);


text:
Q: How to make hover effect not appear when pseudo-element is hovered on I want the hover effect (background change of pseudo-element to green) to only appear when the button is being hovered, however it also appears when the pseudo-element (green box) is hovered on.

button {
    box-sizing: border-box;

  background-color: blue;
  padding: 10px 20px;
  color: white;
  position: relative;
}

button::before {
  content: '';
  position: absolute;
  background-color: transparent;
  height: 20px;
  width: 100%;
  left: 0;
  bottom: -30px;
}

button:hover::before {
  background-color: green;
}
<button>
I am a button
</button>

A: You can achieve that by first setting the default state of the pseudo-element to hidden by setting the display property to display: none;.
On the hover event of the button element you can make it visible by updating the display property to display: block;
But if you loose mouse over from the button element it will be hidden again.
Hope this is not for some kind of drop-down menu, if so, this is not how you should go about doing it.

button {
    box-sizing: border-box;

  background-color: blue;
  padding: 10px 20px;
  color: white;
  position: relative;
}

button::before {
  content: '';
  position: absolute;
  background-color: transparent;
  height: 20px;
  width: 100%;
  left: 0;
  bottom: -30px;
  display: none;
}

button:hover::before {
  background-color: green;
  display: block;
}
<button>
I am a button
</button>

A: @nad by adding pointer-events: none; you can prevents all click and cursor events.

button {
    box-sizing: border-box;

  background-color: blue;
  padding: 10px 20px;
  color: white;
  position: relative;
}

button::before {
  content: '';
  position: absolute;
  background-color: transparent;
  height: 20px;
  width: 100%;
  left: 0;
  bottom: -30px;
  pointer-events: none;
}

button:hover::before {
  background-color: green;
}
<button>
I am a button
</button>


text:
Q: Help me find all sequences of real numbers that meet the following conditions For every integer $n$ where $n \geq 4$, find all such sequences of real numbers $a_1, a_2,..., a_n$, that: $$a_{i+1}^2 + a_{i+2}^2 + 2a_{i}a_{i+3} \leq 0$$ for every $$i=1,2,3,...,n$$ where $a_{n+t}=a_t$ for $t \in \lbrace 1,2,3 \rbrace$
I analyzed this problem in my mind and I know that there must be some sort of "circle" for which the conditions are met. The thing is I've no idea how to write it cleverly on paper.


text:
Q: storing and object in a array with spring server NOT WORKING I'm working on a school project to create an website for buying movie tickets. The website will take the info you put into the input boxes and create an object and store it in an array on a spring server. But when I try to store it nothing happens and something is not working as intended. What did I do wrong and how can I fix it?

$(() => {
    $("#kjop").click (() => {
        const film = $("#film");
        const antall = $("#antall")
        const fornavn = $("#forNavn");
        const etternavn = $("#etterNavn");
        const telefon = $("#telefornr");
        const epost = $("#epost");

        const billett = {
            film: film.val(),
            antall: antall.val(),
            fornavn: fornavn.val(),
            etternavn: etternavn.val(),
            telefon: telefon.val(),
            epost: epost.val(),
        };

        if (inputval(billett)) {
            $.post("/billett", billett, () => hent());

            film.val("");
            antall.val("");
            fornavn.val("");
            etternavn.val("");
            telefon.val("");
            epost.val("");
        } else {
            console.log("Mangler input");
        }

        $("#slettBilett").click(() => {
            $.ajax("/billett", {
                type: "DELETE",
                success: () => hent(),
                error: (jqXhr, textStatus, errorMessage) => console.log(errorMessage)
            });
        });
    });
});

const hent = () => $.get("/billett", billetter => utskrift (billetter));

const inputval => billett {
    if (billett.film === "") return false
    else if (billett.antall ==="") return false
    else if (billett.fornavn === "") return false
    else if (Billett.etternavn === "") return false
    else if (billett.telefon === "") return false
    else return billett.epost !== "";
}

const utskrift = billett => {
    let ut = "

" +
        "Film	antall	Navn	Etternavn	Telefonnr	Epost	" +
        "
";
    for (let b of billett) {
        ut += "
";
        ut += "" + b.film + "	" + b.antall + "	" + b.navn + "	" + b.etternavn + "	" + b.tlf + "	" + b.epost + "	";
        ut += "
";
    }
    ut += "
";
    $("#bestilt")
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Oblig 1</title>

Bestilling av kinobiletter

    Velg film:
    <select id="film">
        <option value="non">Velg film her</option>
        <option>Iron man</option>
        <option>Troya</option>
        <option>Avengers</option>
        <option>The green mile</option>
        <option>God father</option>
        <option>Fight club</option>
    </select>

    Antall <input type="text" id="antall" />

        Fornavn	 <input type="text" id="forNavn" />

        Etternavn	 <input type="text" id="etterNavn"/>

        Telefonnr	 <input type="text" id="telefornr"/>

        Epost	 <input type="text" id="epost"/>

<button onclick="kjop();">Kjøp Billet</button>

    Alle Billetter

<button onclick="slettBilett();">Slett alle billetter</button>

package com.example.demo;

import com.example.demo.billett;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;

@Repository
public class AppRepository {
    private final ArrayList<billett> billettliste = new ArrayList<>();

    public void leggInn(billett billett) {
        billettliste.add(billett);
    }

    public ArrayList<billett> hentAlle () {
        return billettliste;
    }

    public void slettBilett() {
        billettliste.clear();
    }
}
package com.example.demo;

import com.example.demo.billett;
import com.example.demo.AppRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
@RestController
@RequestMapping("/api/lagringserver/")
public class Controller {
    @Autowired
    AppRepository repo;

    @PostMapping("/billett")
    public void lagre(billett billett) {
                repo.leggInn(billett);
            }
    @GetMapping("/billett")
    public ArrayList<billett> hent() {
        return repo.hentAlle();
    }

    @DeleteMapping("/billett")
    public void slett() {
        repo.slettBilett();
    }
}

package com.example.demo;

public class billett {
    private String film;
    private String antall;
    private String fornavn;
    private String etternavn;
    private String telefon;
    private String epost;

        public billett (String film, String antall, String fornavn, String etternavn, String telefon, String epost) {
            this.film = film;
            this.antall= antall;
            this.fornavn = fornavn;
            this.etternavn = etternavn;
            this.telefon = telefon;
            this.epost = epost;
        }

        public String getFilm() {
            return film;
        }

        public void setFilm(String film){
            this.film = film;
        }
        public String getAntall(){
            return antall;
        }

        public void setAntall(String fornavn){
            this.antall = antall;
        }

        public String getFornavn(){
            return fornavn;
        }

        public void setFornavn(String fornavn){
            this.fornavn = fornavn;
        }
        public String getEtternavn(){
            return etternavn;
        }

        public void setEtternavn (String etternavn){
            this.etternavn = etternavn;
        }
        public String getTelefon(){
            return telefon;
        }

        public void setTelefon (String telefon){
            this.telefon = telefon;
        }
        public String getEpost(){
            return epost;
        }

        public void setepost (String epost){
            this.epost = epost;
        }

    }


text:
Q: Losing autowired attributes after executed the interceptor from Spring AOP After a lot of time waste trying to find a answer, I decided to post this doubt.
I have a class that I would like to intercept by the Spring AOP.
ObjectToBeProxied.java

package com.ee.beans;

@Service
@Component
@Transactional
public ObjectToBeProxied implements IObjectToBeProxied {
    @Autowired
    private ParameterValueService parameterValueService;

    public void doStuff() {
        // do something before the call
        getSelfRef().findEventParameterValue(new ParameterValueFilter());
        // do something after
    }

    @HandleException
    private Boolean findEventParameterValue(ParameterValueFilter parameterValueFilter) {
        ParameterValue parameterValue = getSelfRef().parameterValueService.findParametertValueByFilter(parameterValueFilter);
        return parameterValue.value();
    }

    private ObjectToBeProxied getSelfRef() {
        return (ObjectToBeProxied) AopContext.currentProxy();
    }
}

ExceptionHandlerAspect.java

package com.ee.aspects;

@Component
public class ExceptionHandlerAspect {

    private static Logger LOGGER = Logger.getLogger(ObjectToBeProxied.class);

    public Object handleAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // Handling the exception. Need to continue either the method throws a expcetion
        // but it need to be logged
        try {
            return joinPoint.proceed();
        } catch (Exception e) {
            // something to handle the exception
        }
        return null;
    }
}

Spring AOP configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true"/>

    <!-- Activates various annotations to be detected in bean classes -->
    <context:annotation-config/>
    <context:spring-configured />

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.ee.beans"/>

    <bean id="exceptionHandlerAspect" class="com.ee.aspects.ExceptionHandlerAspect" />

    <aop:config>
        <aop:aspect id="exceptionHandlerConfig" ref="exceptionHandlerAspect">

            <!-- Trata exceções lançadas -->
            <aop:pointcut id="exceptionHandlerAroundMethod" expression="execution(* com.ee.beans.ObjectToBeProxied.*(..)) && @annotation(com.ee.exceptions.HandleException)" />
            <aop:around pointcut-ref="exceptionHandlerAroundMethod" method="handleAround" />
        </aop:aspect>
    </aop:config>

When I call the method ObjectToBeProxied.doStuff(), ObjectToBeProxied.parameterValueService autowired is ok, not null.
But, when the aspect intercept the method call ObjectToBeProxied.findEventParameterValue(..) and execute the ExceptionHandlerAspect.handleAround(..), the ObjectToBeProxied.parameterValueService is not ok, it's null.
Debugging it, I can figure out that the Spring Aspect return the ObjectToBeProxied proxy after intercept it, but without the autowired attributes objects.
Where am I getting wrong?


text:
Q: i use Display.getsize(point) method and there occur an error: no suchmethoderror I write a demo of fragment, and under android 3.0, the method getWidth() and getHeigh() is deprecated. and i read the api, found that getSize(point) is the same with the two method ,so i try it .
  Display d = wm.getDefaultDisplay();
  int width=0;
  int height=0;
  Point point = new Point(width,height);
  d.getRealSize(point);

but when i run the app ,there occur an error,is there anybody found such problem?:
02-01 03:13:06.548: E/AndroidRuntime(558): FATAL EXCEPTION: main
02-01 03:13:06.548: E/AndroidRuntime(558): java.lang.NoSuchMethodError: android.view.Display.getRealSize
02-01 03:13:06.548: E/AndroidRuntime(558):  at com.demo.fragment.FragmentDemoActivity.onCreate(FragmentDemoActivity.java:33)
02-01 03:13:06.548: E/AndroidRuntime(558):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
02-01 03:13:06.548: E/AndroidRuntime(558):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1700)

A: The Display.getRealSize() method was added in API 17, which is Android 4.2. If you try to use it on a device below that, you will get a NoSuchMethodException as the method doesn't exist.
Display.getSize() was added in API 13, which is Android 3.2. You want to use the app on Android 3.0, which is API 11.
So for older devices, and even current ones (I am yet to hear of a deprecated method actually being removed from Android), you should use getWidth() and getHeight().
Or you could run the code in an if else statement, something like:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1){
    //Do something for API 17 only (4.2)
    //getRealSize()
}
else if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2){
    // Do something for API 13 and above , but below API 17 (API 17 will trigger the above block
    //getSize()
} else{
    // do something for phones running an SDK before Android 3.2 (API 13)
    //getWidth(), getHeight()
}

A: use this code for both older and new versions.
private static Point getDisplaySize(final Display display) {

final Point size= new Point();
try {
    display.getSize(size); /// will support new versions
} catch (java.lang.NoSuchMethodError ignore) { // Older versions
    size.x = display.getWidth();
    size.y = display.getHeight();
}
return size;

}


text:
Q: Redirection the target field should ensured its a valid request I have a logout button and when i click logout it is redirected to other site (http://rtfg.internal.com/LandingPage). The target makes sure the page gets redirected.
https://abc.internal.com/logout.html?target=http://rtfg.internal.com/LandingPage . I was thinking of the case where an attacker puts some link in the target and does some malicious attack . Is there a way to ensure we have a valid redirect and nothing unwanted is added to target field ?


text:
Q: Debug electron-forge app with VSCode I'm trying to debug my electron-forge project with VSCode (electron main process, not render) but getting erros everywhere. I installed electron-forge package with all dependencies and init my project.
I followed this instruction and my launch.json for VSCode was:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Electron Main",
            "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron-forge-vscode-win.cmd",
            "cwd": "${workspaceRoot}"
        }
    ]
}

But when I hit F5 in VSCode to debug, I got Attribute "runtimeExecutable" does not exist because electron-forge is installed globally so there is no such file in node_modules/.bin/ dir.
Then according to this I changed "runtimeExecutable" and my launch.json was as follows:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Electron Main",
            "runtimeExecutable": "electron-forge-vscode-win.cmd",
            "cwd": "${workspaceRoot}"
        }
    ]
}

The comand line was:

electron-forge-vscode-win.cmd --debug-brk=17423 --nolazy
√ Locating Application
√ Preparing native dependencies
√ Launching Application

But still nothig happened. My electron app started but didn't stop as --debug-brk argument supposed.
Next, I added one line to my launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "cwd": "${workspaceRoot}",
            "name": "Electron Main",
            "runtimeExecutable": "electron-forge-vscode-win.cmd",
            "protocol": "inspector"
        }
    ]
}

Launched with this command line:

electron-forge-vscode-win.cmd --inspect=11172 --debug-brk
√ Locating Application
√ Preparing native dependencies
√ Launching Application

Note: 11172 is a random port number
And now I'm getting this error: Cannot connect to runtime process, timeout after 10000 ms - (reason: Cannot connect to the target: connect ECONNREFUSED 127.0.0.1:11172).

A: I believe that you need to add
"protocol"="legacy"
To your launch config. This is with the assumption that you are using a Node version < 8.x

A: I've come to the conclusion that you cannot use VSCode to debug the main electron process if you use electron-forge or electron-compile. In both cases, the VSCode debugger ignores breakpoints. The BrowserWindow comes up directly and the following message appears in the VSCode debug console window:
Debugging with inspector protocol because a runtime executable is set.
c:\Users\paulk\OneDrive\dev\forge-debug/node_modules/.bin/electron.CMD --inspect=16988 --debug-brk .
Debugger listening on ws://127.0.0.1:16988/9cead160-c448-4b33-a8a2-2dff6f51ed59

Sometimes when I close the browser window, a breakpoint in the "close all windows" event handler is hit. After closing the window, the following message appears in the debug console:
Debugger attached.

Perhaps this indicates that the VSCode debugger does not attach until after the BrowserWindow closes.
I believe the problem originates with electron-compile, which eletron-forge uses. Perhaps it has something to do with compiling on the fly.
Use VSCode to debug a simple Electron app is a breeze. Further, plain Electron emits a different message in the debugger window:
Debugging with inspector protocol because a runtime executable is set.
c:\Users\paulk\OneDrive\dev\electron-quick-start/node_modules/.bin/electron.CMD --inspect=37884 --debug-brk .
Debugger listening on port 37884.
Warning: This is an experimental feature and could change at any time.

This indicates that plain Electron is using a different method of connecting to the debugger than does electron-compile.
It is a shame that electron-forge does not work with VSCode main process debugging. This makes it useless for me. Also, the developers of electron-forge and electron-compile do not seem to consider this a problem. It would be helpful to know what debuggers the developers of electron-forge and electron-compile and the users of these packages are using to debug main process code.

A: Just add 【"port": 11172】 in launch.json after protocol.


text:
Q: Is there a document tool for python? Like perldoc for perl, man for c.
Is there one for python?

A: Normally, you should use documentation strings:
def foo(bar):
   """ Applies the foo operation onto bar """
   # ...

You can then generate HTML (or other output formats) with pydoc or sphinx, or use the built-in help function to see them on live objects.
The documentation of the built-in modules is available online (also downloadable) or via help.

A: There is - its called: "pydoc". You can run it from shell, for example:
$ pydoc sys

will give you help about sys module. It can export help to html (pydoc -w) or spawn server with simple gui management:
$ pydoc -g

A: In the python shell, you can use the help built-in function (for example, here's the documentation of the os.path module):
>>> import os
>>> help(os.path)

Help on module posixpath:
NAME
      posixpath - Common operations on Posix pathnames.
FILE
      /usr/lib/python2.7/posixpath.py
MODULE DOCS
      http://docs.python.org/library/posixpath
DESCRIPTION
      Instead of importing this module directly, import os and refer to
      this module as os.path.  The "os.path" name is an alias for this
      module on Posix systems; on other systems (e.g. Mac, Windows),
      os.path provides the same operations in a manner specific to that
      platform, and is an alias to another module (e.g. macpath, ntpath).
Some of this can actually be useful on non-Posix systems too, e.g.
for manipulation of the pathname component of URLs.

FUNCTIONS
... ... ..


text:
Q: Convert emojione img html tag back to unicode I'm trying to create a function to replace all occurrences of  with emojione (not a fully word) in its class to its alt attribute, which contains the emoji unicode.
All  occorrences that don't have emojione in its class cannot be replaced.
What's wrong with my regex or code?
Thanks in advance!
Here is my code:

let input = $("#txInput")
let output = $("#txOutput")
let button = $("button")

input.text(
`
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

"
test 123

"

"
test 321

"

`
)

const emojioneImgToUnicode = function (txt) {
 let regex = /]+?>(?:<\/img>)*/g,
      matched,
      result = txt;
  while ((matched = regex.exec(result)) !== null) {
   result = result.replace(matched[0], matched[1]);
  }
  console.log(result);
  return result;
};

button.on("click", function() {
  let out = emojioneImgToUnicode(input.val());
  output.text(out);
});
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

div {
  padding: 10px 0;
}

textarea {
  width: 100%;
  height: 100px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

  <textarea id="txInput"></textarea>

<button>Convert</button>

  <textarea id="txOutput"></textarea>

A: You may use
.replace(/]*?\s)?class="[^">]*emojione)(?:[^>]*?\s)?alt="([^"]*)"[^>]*>(?:[^<]*<\/img>)?/gi, "$1")

See the regex demo.
Details

*

*]*?\s)?class="[^">]*emojione) -  positive lookaehead that make sure that immediately to the right of the current location, there is

*

*(?:[^>]*?\s)? - an optional sequence of any 0+ chars other than > and then a whitespace

*class=" - a literal substring

*[^">]*emojione - any 0+ chars other than " and > and then emojione (the word inside class is thus checked for presence)

*(?:[^>]*?\s)? - an optional sequence of any 0+ chars other than > and then a whitespace

*alt=" - a literal substring

*([^"]*) - Group 1 ($1 in the replacement pattern)

*"[^>]*>  - end of img tag: ", 0+ chars other than > and then >

*(?:[^<]*<\/img>)? - an optional sequence of

*

*[^<]* - 0+ chars other than <

*<\/img> - a  substring.

Here is the JS demo:

var html = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

"
test 123

"

"
test 321

"

`;
var rx = /]*?\s)?class="[^">]*emojione)(?:[^>]*?\s)?alt="([^"]*)"[^>]*>(?:[^<]*<\/img>)?/gi;
document.body.innerHTML = "
" + html.replace(rx, "$1") + "
";


text:
Q: Identifying identical graphs or adjacency matrices of graphs I was wondering if someone has a good idea for checking whether two graphs are the same (for example, based on an adjacency matrix). Ideally, in a computational efficient manner that can be done on large collections of small graphs (3-30 nodes)
To illustrate the probblem, depending on how I enumerate the different nodes in the same graph, the same nodes may appear in different places of the adjacency matrix. Or in other words, we have a many-to-one mapping scenario where many different adjacency matrix can encode the same graph.
For instance, assume I have a undirected, unweighted graph like this:

a) The adjacency matrix rotated, transposed, or otherwise modified could yield the same graph. Similar, changing the node numbering in the graph

would result in a adjacency matrix that has different entries as the one shown above but encodes the same graph:
$$
\begin{bmatrix}
0 & 1 & 0 & 0 & 0 & 0 \\
1 & 0 & 1 & 0 & 0 & 1 \\
0 & 1 & 0 & 0 & 1 & 1 \\
2 & 0 & 1 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 & 0 & 1 \\
0 & 1 & 1 & 1 & 1 & 0
\end{bmatrix}
$$
Do you know a way for checking whether two adjacency matrices encode the same graph?

A: Graph matching is the process of  finding a correspondence between the nodes and theedges of two graphs that satisfes some (more or less stringent) constraints ensuring that similar substructures in one graph are mapped to similar substructures in the other.
People usually divide the matching methods into two broad categories: the first contains exact matching methods that require a strict correspondence among the two objects being matched or at least among their subparts.The second category defines inexact matching methods, where a matching can occur even if the two graphs being compared are structurally different to some extent.
Most of the algorithms for exact graph matching are based on some form of tree search with backtracking.
For the case of inexact graph matching algorithms, the matching between two nodes that do not satisfy the edge-preservation requirements of the matching type is not forbidden. Instead, it is penalized by assigning to it a cost that may take into account other differences. So the algoriths must find a mapping that minimizes the matching cost.
There are many variations of both algorithms for both cases.
One faster possibility is to take a look at eigenvalue similarity, but keep in mind that this is not a correspondence. It may happen that graphs that are similar in terms of eigenvalues are not the same.
Some reviews of the problem may be found in:
1) THIRTY YEARS OF GRAPH MATCHING IN PATTERN RECOGNITION - International Journal of Pattern Recognition and Artificial Intelligence Vol. 18, No. 03, pp. 265-298 (2004) - D. CONTE, P. FOGGIA, C. SANSONE and M. VENTO (where I got most information above).
2) Algorithms for graph similarity
If you are a Python user, you may find routines here: Python functions measuring similarity using graph edit distance.


text:
Q: How to print every second digit in C My task is to print every second digit of given long in C.
My code looks like this:
long credit;
int mod, mod1, var;

int main(void)
{
    credit = get_long("n: \n");
    for (mod = -1; credit > 0; credit /= 10)
    {
        mod = credit % 10;
        for(mod1 = 1; mod1 <= mod; mod1+=2)
        {
            for (var = 1; var <= mod1; var++)
            {
                if(var == mod)
                {
                    printf("%i ", var);
                }
             }
         }
     }
     return 0;
}

Unfortunately it prints only odd numbers from given long. No matter how many even numbers is between.
I wonder if the way I have chosen (nesting for loops + if statement) is proper way of doing it.
NOTE: I am not looking for ready solution. I am looking for hints as I wouldl ike to discover solution on my own.

A: well, you can get the last digit by taking modulo 10 and then you can get rid of 2 digits by dividing the number by 100 and if you do this until the number is equal to 0 you get every second digit, like this:
x /= 10; //just offsetting it by one more digit (so you get even and not odd numbers)

while(x > 0)
{
    printf("%lld", x % 10);
    x /= 100;
}

A: The following code will solve the problem without so many loops.
#include <stdio.h>

#define BASE (10) /* fits any base between 2 and 16 */

#ifndef EVENS
#define EVENS 0
#endif

char *print_each_2nd(
        unsigned x,  /* value to extract digits. */
        char *buf,   /* buffer to use as workpad */
        size_t sz)   /* size of previous buffer  */
{
    buf += sz; /* we go backwards, from the end of the buffer */
    while (x) {
        int remainder = x % (BASE*BASE);

        if (!sz) {
            fprintf(stderr,
                    "Not enough buffer space\n");
            return NULL;
        }
#if EVENS
        remainder /= BASE;
#endif
        *--buf = "0123456789abcdef"[remainder % BASE];
        sz--;

        x /= BASE*BASE;
    }
    return buf;
} /* print_each_2nd */

int main()
{
    char workpad[20];

    unsigned number = 123456789;
    printf("original: %d, alternates: %s\n",
           number,
           print_each_2nd(number,
                   workpad, sizeof workpad));
} /* main */

Is a complete example that you can build and test.


text:
Q: Can I extend classes overwriting base class properties in ES6? I'm looking to do something like the following, purely with ES6/JS:
class ParentClass {
    prop = true;
    constructor() {
        console.log("Prop is", this.prop);
    }
}

class ChildClass extends ParentClass {
    prop = false;
    constructor() {
        super();
    }
}

const childClassInstance = new ChildClass();

//

"Prop is false"
Is this possible with ES6? Everything I've read/tried points at the context of the base constructor being what it was initialised with.

A: You could check in parent class if prop param is passed or not and use that value or default true value.

class ParentClass {
  constructor(prop) {
    this.prop = prop != undefined ? prop : true;
    console.log("Prop is", this.prop);
  }
}

class ChildClass extends ParentClass {
  constructor(...props) {
    super(...props);
  }
}

const one = new ChildClass(false);
const two = new ChildClass();


text:
Q: No module named 'psutil', although it is installed (MacOS) When I run my code that includes psutil module I encounter the following error:
Traceback (most recent call last):
  File "/Users/alek/Desktop/coloring/solver.py", line 4, in <module>
    from psutil import cpu_count
ModuleNotFoundError: No module named 'psutil'

Although, when trying to install the module in terminal, I can see the following
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
Requirement already satisfied: psutil in /opt/homebrew/lib/python3.9/site-packages (5.9.1)
DEPRECATION: Configuring installation scheme with distutils config files is deprecated and will no longer work in the near future. If you are using a Homebrew or Linuxbrew Python, please see discussion at https://github.com/Homebrew/homebrew-core/issues/76621
WARNING: There was an error checking the latest version of pip.

How should I ensure that the module is in the right environment and can be used by my program?
Thanks in advance!

A: try to upgrade it
sudo pip install --upgrade psutil

A: try to run this command in python shell:
import site
site.getsitepackages()

actually, it is trying to search psutil module in one of the Xcode path.
see if you have psutil in this path:
/Applications/Xcode_13.4.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/site-packages

if not add the psutil module here and it should work.
it worked for me.


text:
Q: I am trying to load my kernel from disk using BIOS 13h interrupt but for unknown reasons it fails even though the kernel gets loaded in RAM I am trying to make a bootloader and when I try to read my kernel from disk it shows:

Reading from disk failed!

I have checked all the registers to the function and they appear to be correct as suggested on wikipedia.
So I checked the memory address where the kernel is supposed to be loaded and found that it has been loaded correctly. Then I removed the error handling and tried to jump to the kernel location but it didn't execute.
So I tried running it on bochs and it does jump to the kernel location and executes that code, but I don't seem to see any results (I run it on qemu and debug on bochs)
Main file
[bits 16]
[org 0x7c00]

%define ENDL 0x0D, 0x0A, 0

start: jmp boot

%include "bootloader/out.asm"
%include "bootloader/disk.asm"

halt:
  hlt
  jmp halt

boot:
  xor ax, ax ;  sets ax to 0

  ; sets segments to 0
  mov ds, ax
  mov es, ax
  mov ss, ax

  mov si, wlcm_msg
  call print

  mov dh, 1
  mov bx, kernel
  call read_kernel
  jmp kernel

  jmp halt

wlcm_msg: db "Booted to 16 bit real mode", ENDL

times 510-($-$$) db 0
dw 0xaa55
kernel: db 0

Disk routines file
;
; @params:
;   dx(dl) - number of sectors to load
;   bx - loaction in ram to store the read data
;
read_kernel:
  pusha
  push dx

  mov ah, 02h
  mov al, dh ; sectors to read
  mov cl, 02h ; the sector to read 1 is our bootloader

 mov ch, 0
 mov dl, 0
 mov dh, 0

  int 13h
  jc read_err ; if carry flag is set then there is an error

  pop dx
  cmp al, dh  ; sector read count
  jne sector_err

  popa
  ret

read_err:
  mov si, read_err_msg
  call print
  mov dh, ah
  jmp halt

sector_err:
  mov si, sector_err_msg
  call print
  jmp halt

read_err_msg: db "Reading from disk failed!", ENDL
sector_err_msg: db "Incorrect number of sectors to read!", ENDL

Kernel
[bits 16]

%define ENDL 0x0D, 0x0A, 0

start: jmp main

main:

  mov ah, 9
  xor bh, bh
  mov cx, 1
  mov al, 'E'
  int 10h

  cli
  hlt

Build script
ASM = nasm

BOOT_SRC = bootloader/main.asm
KENREL_SRC = kernel/main.asm
BUILD_DIR = build

.PHONY: all clean create run debug

all: $(BUILD_DIR)/disk.img

$(BUILD_DIR)/disk.img: $(BUILD_DIR)/bootloader.bin $(BUILD_DIR)/kernel.bin
    dd if=/dev/zero of=$@ bs=512 count=2880
    dd if=$< of=$@ bs=512 conv=notrunc seek=0
    dd if=$(word 2,$^) of=$@ bs=512 conv=notrunc seek=1

$(BUILD_DIR)/bootloader.bin: $(BOOT_SRC) create
    $(ASM) -f bin $< -o $@

$(BUILD_DIR)/kernel.bin: $(KENREL_SRC) create
    $(ASM) -f bin $< -o $@

create:
    mkdir -p $(BUILD_DIR)

clean:
    rm -rf $(BUILD_DIR)/*

run: $(BUILD_DIR)/disk.img
    qemu-system-i386 -machine q35 -drive file=$<,format=raw

run_floppy: $(BUILD_DIR)/disk.img
    qemu-system-i386 -machine q35 -fda $<

debug: bochs_config $(BUILD_DIR)/disk.img
    bochs -f $<

I tried lots of ways to fix this but none seem to work, so I am pretty much convinced that this is an issue with my build script or the way I set up segments. I've found many questions with the same problem here, but I didn't really understand how that would apply here.

A: You have this line in your code:

mov ss, ax

The SS register is closely linked to the SP register. If SS changes, then the existing SP will 99.9% of the time not make sense in the new segment, so it needs to change too!
Add a line such as:
mov sp, 0x7C00

Since your bootloader is located in the region 0x7C00-0x7DFF, placing the stack at 0x7C00 (growing downwards) is the most common choice (but feel free to choose anything else that doesn't conflict with already existing data such as the interrupt table, the BDA or your own code).
Setting SP should be done in the next instruction after the mov ss, ax instruction, because the CPU disables interrupts briefly after it, so that you have time to set SP without interrupts corrupting the stack (this behavior is implemented on all x86 processors, save for a few old steppings of the ancient 8088, for which you have to enclose the stack pointer change in cli - sti).
If you already know that the machine you are working with has a 32-bit CPU (meaning you have access to EAX, EBX etc), you can also use the lss sp, [mem] instruction, which loads the SS:SP pair from the memory location in a single instruction. However, it could be best to avoid this in bootloader code because the machine's hardware might still be unknown at this stage in the boot process.


text:
Q: Распарсить текстовый файл Есть текстовый файл куда записываются логи, его строки имеют вид
INFO  10-04 22:09:10 DataLayer              11         Log                            - userId = 1050.
Нужно каким-то образом разбить эти строки на элементы стрингового массива, чтобы каждый элемент этого массива содержал нужную часть данных. И выглядел примерно так:
["Info"]["10-04 22:09:10"]["DataLayer"]["11"]["Log"]["- userId = 1050."] где [] - это каждый элемент массива, попробовал через Split(" ") - выдало 61 элемент, с кучей элементов содержащих просто пробелы. А мне нужно именно выделить слова, все усложняется тем, что в строке много пробелов, и разбивать по пробелам не правильно, так как есть обычные фразы, где пробел идет не в качестве разделителя столбиков, а как просто речевой пробел. Как это можно решить ?

A: У метода String.Split есть несколько перегрузок. В частности, кроме сепаратора, он принимает количество возвращаемых строк и опцию, исключающую пустые строки.
string text = @"INFO  10-04 22:09:10 DataLayer              11         Log                            - userId = 1050.";
var result = text.Split(new char[] { ' ' }, 7, StringSplitOptions.RemoveEmptyEntries);

Этот код даст почти то, что вам нужно. Только дата и время окажутся в разных элементах массива. Полагаю, это не станет проблемой для их использования.


text:
Q: Django Admin permission just for inlines I have a ModelAdmin (A) that is an inline of another ModelAdmin (B).
I'd like to give Admin permissions (add, change and delete) to a User (U) just for A.
I gave to user every rights he needs (i think): is_staff: True | can add, change, delete A.
The problem is that U can't see the inline A on the admin panel. If i give him also permissions for B it works but i don't want to let him to modify that model.
There is a sort of "readonly" for model B in these cases?

A: The admin interface is for editing, if you want to allow some users to edit model A but not model B add A as a ModelAdmin and allows only those users to manage(Add,Edit,Delete) Model A.
class AAdmin(admin.ModelAdmin):
    ...

class AInline(GenericTabularInline):
    model = A
    ...

class BAdmin(admin.ModelAdmin):
    inlines = [
        AInline,
    ]
    ...

admin.site.register(A, AAdmin)
admin.site.register(B, BAdmin)

a_user.user_permissions.add('my_app.add_a', 'my_app.change_a', 'my_app.delete_a')
b_user.user_permissions.add('my_app.add_b', 'my_app.change_b', 'my_app.delete_b')