text:
Q: How to specify custom density function for GeoHistogram? Bug introduced in 11.0.0 and persisting through 11.0.1 or later
 GeoHistrogram is new in 11.0

Using GeneralUtilities`PrintDefinitions on GeoHistogram to investigate specifying a custom density function I noticed that it will accept an argument with Function head for the hspec parameter. However, when called with such a function GeoHistogram appears to completely ignore it.
SeedRandom[341];
vals = GeoPosition@#[[;; 2]] -> Last@# & /@
   RandomVariate[MultinormalDistribution[{-27, 133, 50000},
     {{15, -.2, .5}, {-.2, 20, .8}, {.5, .8, 10000}}], 300];

Then, for example, if I want the Max value in the bin to be the height specification.
GeoHistogram[vals, Automatic, Function[{bins, vals}, Max/@vals]]

However, this gives an error for the density specification and returns the plot equivalent to if Automatic was selected for hspec.
How do you specify a custom density function for GeoHistogram?  I want to make use of much of the functionality of GeoHistogram but use my own density function.
I suspect I have the incorrect number of parameters or am returning an incorrect format from the function that is causing the error.
Update: Confirmed bug - [CASE:3719954]


text:
Q: Calculate area percentage of a polygon layer inside a polygon in ArcGIS There are two polygon layers,

*

*State boundaries of a country

*Soil class of the country with three classes

The soil class containing only 2 major classes and the 3rd soil class is unimportant(very small area).
How it is possible to calculate the area percentage of the 2 major soil class alone based on the state boundary ?
For example:

State
soil class1
soil class 2

State 1
53%
47%

State 2
55%
45%

After intersecting the two polygons how can I calculate only the area percentage of only two soil classes to 100% by excluding the 3rd soil class ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET Calendar I have a problem with calendar,I want to paint special days different color For example
On calendar
03.06.2011 Day--->blue
04.06.2011 day---->red
12.06.2011-04.07.2011  Days ----> yellow
More than one color I want to use selected day

A: You can use javascript to do that,
Refer to JSFiddle Here
You can add custom special day,
$(document).ready(function () {

    $('#calendar').fullCalendar({
        theme: true,
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultDate: '2014-07-04',
        editable: true,
        events: [{
            title: 'All Day Event',
            start: '2014-07-01'
        }, {
            title: 'Long Event',
            start: '2014-07-07',
            end: '2014-07-10'
        }, {
            id: 999,
            title: 'Repeating Event',
            start: '2014-07-09T16:00:00'
        }, {
            id: 999,
            title: 'Repeating Event',
            start: '2014-07-16T16:00:00'
        }, {
            title: 'Meeting',
            start: '2014-07-12T10:30:00',
            end: '2014-07-12T12:30:00'
        }, {
            title: 'Lunch',
            start: '2014-07-12T12:00:00'
        }, {
            title: 'Birthday Party',
            start: '2014-07-13T07:00:00'
        }, {
            title: 'Click for Google',
            url: 'http://google.com/',
            start: '2014-07-28'
        }],
        eventAfterAllRender: function (view) {
                //Use view.intervalStart and view.intervalEnd to find date range of holidays
                //Make ajax call to find holidays in range.
                var fourthOfJuly = moment('2014-07-04','YYYY-MM-DD');
                var holidays = [fourthOfJuly];
                var holidayMoment;
                for(var i = 0; i < holidays.length; i++) {
                    holidayMoment = holidays[i];
                    if (view.name == 'month') {
                        $("td[data-date=" + holidayMoment.format('YYYY-MM-DD') + "]").addClass('holiday');
                    } else if (view.name =='agendaWeek') {
                        var classNames = $("th:contains(' " + holidayMoment.format('M/D') + "')").attr("class");
                        if (classNames != null) {
                            var classNamesArray = classNames.split(" ");
                            for(var i = 0; i < classNamesArray.length; i++) {
                                if(classNamesArray[i].indexOf('fc-col') > -1) {
                                    $("td." + classNamesArray[i]).addClass('holiday');
                                    break;
                                }
                            }
                        }
                    } else if (view.name == 'agendaDay') {
                        if(holidayMoment.format('YYYY-MM-DD') == $('#calendar').fullCalendar('getDate').format('YYYY-MM-DD')) {
                            $("td.fc-col0").addClass('holiday');
                        };
                    }
                }
            }
    });

});

For changing the colour, you can edit background on .holiday in css file
body {
    margin: 0;
    padding: 50px 0 0 0;
    font-family:"Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
    font-size: 14px;
}
#calendar {
    width: 100%;
}
.holiday {
    background: lightgray;
}

Hope it can help you


text:
Q: Problema de update en Mysql Este es un cursor el cual busca actualizar las llaves primarias por otras, estas claves primarias tienen que tener los 2 primeros datos ED de editorial, y tomar los primeros 3 caracteres del pais, los primeros 3 caracteres del nombre y con un contador colocar un numero, pero no puedo lograr el objetivo porque la clave primaria tiene que ser de 10 digitos y cuando coloca el valor del 1 al 9 queda un espacio y no logro hacer que quede "EDMEXali01" por ejemplo si no que me da de resulatado "EDMEXali1" y si le pongo el 0 de forma manual en el concat() pues me da error porque cuando llega al 10 supera el limite de caracteres del char (10) ayuda...
delimiter //
create procedure c ()
begin
    declare ID char(10);
    declare p   varchar(30);
    declare n   varchar(30);
    declare ss   int ;
    declare fin integer default 0 ;
    declare coun cursor for select  count(*) from Editorial;
    declare cursor_n cursor for select substring(nombre,1,3)from Editorial;
    declare cursor_p cursor for select substring(pais,1,3 )from Editorial;
    declare cursor_s cursor for select codigo from Editorial ;
    declare continue handler for not found set fin =1;
    open cursor_p;
    open cursor_n;
    open cursor_s;
    open coun;
    Ciclo: loop
        fetch cursor_p into p ;
        fetch cursor_n into n;
        fetch cursor_s into ID;
        fetch coun into ss;
        if fin =1 then
            leave   Ciclo;
        end if;
        update libreria.Editorial set codigo = concat('ED',p,n,0+ss)
        where codigo = ID ;
         update libreria.Editorial set codigo = concat('ED',p,n,ss)
        where codigo = ID and  ss > 10;
    end loop Ciclo;
    close cursor_p ;
    close cursor_n ;
    close cursor_s ;
    close coun;
end //

A: En MySQL puedes usar ZEROFILL en las declaraciones, en cuyo caso te llenará con 0 a la izquierda los valores.
Sabiendo eso, puedes declarar ss así:
declare ss INT(2) ZEROFILL;


text:
Q: HTML to CSS link not working The link in my html file is not working. I'm not sure if it's something else, though. When I run the file, nothing appears on the screen. There are supposed to be five rectangles all different colors(you might be able to figure that out). This is probably a really easy fix, but I am a beginner and am in need of some quick help. Here is my html:
<!DOCTYPE html>

         <link rel="stylesheet" type="text/css" href="stylesheet.css">

And here is my CSS:
#play {
    background-color:#FF0000;
    height: 70%;
    width: 60%;
}

#create {
    background-color:#0000FF;
    position: relative;
    height: 28%;
    width: 60%;
    top:2%;
}

#yellow {
    background-color:#E2BE22;
    height: 28%;
    width: 39%;
    position: relative;
    left: 61%;
    bottom: 26%;
}

#green {
    background-color:#008800;
    position: relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 90%;
}

#purple {
    background-color:purple;
    position:relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 160%;
}

A: Nothing is shown because your body has zero size:
Just add this to your css:
body {
  width: 100vw;
  height: 100vh;
}

JsFiddle

html, body {
    width: 100vw;
    height: 100vh;
}

#play {
    background-color:#FF0000;
    height: 70%;
    width: 60%;
}

#create {
    background-color:#0000FF;
    position: relative;
    height: 28%;
    width: 60%;
    top:2%;
}

#yellow {
    background-color:#E2BE22;
    height: 28%;
    width: 39%;
    position: relative;
    left: 61%;
    bottom: 26%;
}

#green {
    background-color:#008800;
    position: relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 90%;
}

#purple {
    background-color:purple;
    position:relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 160%;
}

A: Set a height to your html and body element :
html, body { height: 100%; }

A: Currently, your HTML and BODY element don't have a height. You set the elements to a percentage of zero, wich is always zero.
You need to set the height to a relative standard. Try to set your HTML and BODY height, then you can use the code you wanted.

html, body {
  height:100%;
}

#play {
    background-color:#FF0000;
    height: 70%;
    width: 60%;
}

#create {
    background-color:#0000FF;
    position: relative;
    height: 28%;
    width: 60%;
    top:2%;
}

#yellow {
    background-color:#E2BE22;
    height: 28%;
    width: 39%;
    position: relative;
    left: 61%;
    bottom: 26%;
}

#green {
    background-color:#008800;
    position: relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 90%;
}

#purple {
    background-color:purple;
    position:relative;
    height: 34%;
    width: 39%;
    left: 61%;
    bottom: 160%;
}

A: I think you would not have set the height of body and html.
Add the following in you css
html, body{
  height: 100%;
  width: 100%;
}

A: Since you are giving height and width in percentage, you need to give height and width for body tag
For example:
body{
      height:100px; //either static or in percentage
      width:100px

    }

In css when you specify height or width in percentage, at least any one of its ancestor should have definite value for height/width


text:
Q: Insights on differential element I can solve a lot of integrals, differentiation problems, and their applications by dividing curves/ regions into infinitesimal elements and then integrating them.  But I don't have a clear physical interpretation of the differential element ($dx$ or anything) in Nature.  I am not convinced that because it is very small we can regard the $f(x)$ as constant as $dx$ changes.  Is there any physical and clear meaning for it? And if it is very small why do we not regard $f(x) dx =$ zero ?
I hope the question does not appear stupid and superficial to you.

A: Since you want a physical interpretation of the differential elements, I'll assume you know what mechanical work is.
The differential elements are not really infinitesimals.  That may have been how Newton and Leibniz thought about them, but in standard analysis today they are just linear functions.
Think about it this way.  Say you have a constant force field -- for instance the gravitational force field near the surface of the Earth is constant to a very good approximation.  Then consider a straight line segment -- positioned however you like -- in that force field.  Now we'll say that that line segment is actually the path followed by a particle through the Earth's gravitational field -- so just pick one side of the line segment to call the starting position and the other end to be the final position of the particle.
Then the situation looks (in $2$d) like:

Now the differential form $F_x(x,y)dx + F_y(x,y)dy$ is just a function which assigns to oriented line segments, like the one above, a number.  The $dx$ and $dy$ parts tell you by how much the $x$ and $y$ parts of the oriented line segment changes and the $F_x$ and $F_y$ are the $x$ and $y$ components of force at some point in each line segment.  It also scales linearly with the length of those oriented line segments -- thus it is a linear function of line segements.
In this case, $dx$ is the function which associates the (signed) number $x$ to any oriented line segment $x\hat x + y\hat y$ and $dy$ is the function which associates the (signed) number $y$ to any oriented line segment $x\hat x+ y\hat y$, and we can choose any point along the path as our point at which to evaluate $F_x$ and $F_y$.  Then the work due to gravity on this particle moving along the red path is $$W=F_x(x,y)dx + F_y(x,y)dy = mgy$$
Well, that was really easy, right.  But what happens when $F_x$ and $F_y$ are NOT constant?  Or when the path the particle follows is not a straight line -- but curved.  In both cases we do the same thing: we approximate the answer by very small oriented lines segments.  Then as we construct an approximation with smaller and smaller line segments our approximation should get better and better.
Here's a picture that might help you visualize what I mean.  In it the black curve is the actual path and the blue and red curves are made of line segments to approximate the path.  While the blue curve sort of approximates this sinewave, the red curve -- which has nearly $3$ times as many line segments -- follows the curve much more closely.

So for any partitioning we do of the curve, we end up with several oriented line segments at which to evaluate our differential form that we can then add to get an approximation for the work of the particle along the indicated path:
$$\text{Work} \approx \sum_i [F_x(x_i, y_i)dx_i + F_y(x_i, y_i)dy_i]$$
Then in the limit as the size of each line segment goes to zero (and assuming that everything is nice enough) we end up with the exact amount of work.  So differential forms aren't infinitesimals -- they're just functions which associate line segments with numbers.  Then integrals are defined as limits of sums of a differential form evaluated along many oriented line segments as the lengths of those line segments approach $0$.
Has that given you some intuition about what differential elements are?


text:
Q: Модель бутылки Очень надо нарисовать фигуру бутылки или вроде того в OpenGL.
A: *

*Нарисуйте на листе бумаги в клеточку профиль бутылки.

*Отбросьте одну половину (бутылка ведь симметричная?).

*Разбейте профиль на прямые отрезки опорными точками. В местах сильных изгибов точек нужно побольше, на гладких участках - поменьше.

*Поздравляю, вы произвели аппроксимацию кривой. Теперь определите координаты точек в удобной системе координат (с началом отсчета в центре донышка например).

*Забейте в программу массив координат опорных точек. Выделите еще один массив такой же размерности (назовем его временным), но оставьте его пустым.

*Теперь будем вращать наш профиль. Выберите количество граней у бутылки n. Тогда шаг поворота у нас будет 360/n градусов.

*Далее берёте по порядку координаты 2х соседних точек из массива, поворачиваете их на вышеупомянутый угол вокруг вертикальной оси, получаете 2 новые координаты. Рисуете полигон через эти 4 точки. 2 вычисленные координаты сохраняете во временный массив. Повторяете процедуру для всех отрезков. Т.к. во временном массиве будут результаты предыдущих вычислений, для всех отрезков кроме первого нужно будет рассчитывать только по одной точке. Когда все отрезки обработаны, меняем местами временный и основной массивы. Новый временный - очищаем.

*Повторяете пункт 7 для всех граней от 1 до n.

Если идти глубже, то правильнее сначала получить координаты все опорных вершин в виде 2х-мерного массива (чтобы не пересчитывать их каждый раз при отрисовке), а потом уже выводить в нужном месте.


text:
Q: PowerShell incorrectly reports failure when running docker-compose in a remote session I have this simple Docker Compose manifest
version: '2'
services:
  dummy:
    image: hello-world

When I run it locally, I get the expected behavior / output.
PS> docker-compose up -d; $?; $LASTEXITCODE
Creating network "temp_default" with the default driver
Creating temp_dummy_1 ...
Creating temp_dummy_1 ... done

True
0

When I run it remotely, I get an error creating the network.
[example.com]: PS> docker-compose up -d; $?; $LASTEXITCODE
docker-compose : Creating network "temp_default" with the default driver
At line:1 char:1
+ docker-compose up -d
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Creating networ... default driver:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

Creating temp_dummy_1 ...
Creating temp_dummy_1 ... done

False
0

However, the network is created just fine.
[example.com]: PS> docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
b170367ba141        temp_default        bridge              local

What's happening and how do I fix this? I need the command to succeed because I need to distinguish a good up from a bad one. As long as PowerShell thinks this is a failure, I can't make any progress. Can I depend on the docker-compose exit code?


text:
Q: JDK 1.6.0 update 45 does not install the "Public JRE" - why? I was trying to upgrade Java 1.6.0 to the latest update 45. I first uninstalled the previous version (update 43), but this time for some odd reason the JDK installer (jdk-6u45-windows-i586.exe) does not install the "Public JRE" as it normally does along with the JDK. It does not even list it as options (it only shows Development Tools and Source Code, but does not list "Public JRE").
When I thus subsequently tried to install the JRE separately (using jre-6u45-windows-i586.exe), I got the message that the JRE was already installed.
So, for some odd reason the JDK installer (as well as the JRE-installer) seem to believe that JRE 1.6.0 update 45 is already installed while it is NOT.
Any idea, how to convince it otherwise?
This is on Windows 7 (x64 Enterprise) and with the 32-bit Java version (the 64 bit version installed fine as usual. I need both versions for test purposes just to avoid that question...)

A: I'm at a loss to understand what your problem is.  The JDK install includes all of the tools and libraries that a JRE install contains.  Add the bin subdirectory on your shell's PATH environment variable and both the JRE tools and the other tools can be used.


text:
Q: SVN Batch file output linebreaks and formatting I am creating a simple 'post-commit' svn batch script, which will run when a member of our development team commits a build. This batch file sends off the resulting output to a slack service which spits it out to our team channel.
This all works without any problems, but I'd like to put in some bespoke formatting such as new lines and maybe bold text. It's a bit hard to read at present. Being able to break to a new line is the main thing that I'm after.  I've done a lot of searching, but can't seem to find the correct answer.
Does anyone have experience with this?
Here's the contents of  my script currently:
set one=%1
set rev=%2
set changes=svnlook changed %one% -r %rev%
set whatchanged=nothing

for /f "delims=" %%a in ('%changes%') do ( set whatchanged=%%a )

for /f "delims=-" %%i in ('%rev%') do (
SET rev=%%i
)

for /f "delims=" %%g in ('svnlook log %one% -r %rev%') do (
 SET comlog=%%g
)

for /f "delims=" %%i in ('svnlook author %one% -r %rev%') do (
 SET "author=%%i"
)

for /f "delims=" %%i in ('svnlook changed %one% -r %rev%') do (
 SET changed=%%i
)

powershell -Command "& Invoke-RestMethod -Uri 'our URL with a unique token goes here' -Method Post -Body (ConvertTo-Json @{text='%author% %rev% %one% %comlog% %whatchanged%'})"

REM  All checks passed, so allow the commit.
exit 0

The output currently looks like this:

liam.mcdonald 171 D:\Repositories\company

Here is another one:

U   Test/New Text Document.txt


text:
Q: To backup to XFS disc by imaging and file-system level I am interested in image the internal HDD and backup just the filesystem file as backups.
My external HDD is 2TB while 100 GB is only used in my internal HDD.
Both methods are welcome here.
Code and situation
$ ls -la /dev/sdb
brwx---rwx 1 root disk 8, 16 Jul 13 10:44 /dev/sdb
$ sudo chmod 777 /dev/sdb

I start the Backups program in GUI of Debian 8.1 which is probably Deja Dup.
I set the Buffalo 2TB disc the back file disc.
I run backup but I get this window about permission denied although I have 777 as permissions.

The command mount gives this output
/dev/sdb1 on /media/masi/_linuxDisc type xfs (rw,nosuid,nodev,relatime,attr2,inode64,noquota,uhelper=udisks2)

Changing permissions after mjturner's answer
$ ls -la /media/masi/_linuxDisc/
total 4
drwxr-xr-x  2 root root    6 Jul 12 19:42 .
drwxr-x---+ 3 root root 4096 Jul 13 10:44 ..
$ sudo chmod 755 /media/masi/_linuxDisc/
[sudo] password for masi:
$ ls -la /media/masi/_linuxDisc
total 4
drwxr-xr-x  2 root root    6 Jul 12 19:42 .
drwxr-x---+ 3 root root 4096 Jul 13 10:44 ..

which shows no effect of chmod. Why?
How can you set correct permissions for the backup in Debian 8.1?

A: To write to your removable disk, you need to change the permissions of the location where /dev/sdb is mounted and not the permissions of the /dev/sdb device itself.
I see from your mount output that it's mounted on /media/masi/_linuxDisc - change the permissions of that directory and then instruct Deja Dup to use that as your backup target. Don't instruct Deja Dup to use /dev/sdb as the backup target. Ideally, you should create a directory below /media/masi/_linuxDisc (eg, backups, adjust the permissions on that and then back up to /media/masi/_linuxDisc/backups).
For example:
$ su -
# cd /media/masi/_linuxDisc
# mkdir backups
# chmod backups 755

Note: only root can write to that new backups directory. If you're backing up an entire disk, you should run your backup as root so that all files are backed up correctly and permissions preserved. I don't know Deja Dup, but I assume that is possible.


text:
Q: Bypassing a custom login page I am demoing a web-application soon and would like to make the flow of my demo a little cleaner.
At the moment, when one clicks on a page, they get redirected to the login for this webpage. I'd like to do away with login page this for my demo.
Let's, as an example, take https://home.bt.com/login/loginform.
I want to add a link to my webpage which will, in the background, log me in as BT ID "User1" with password "securityDoesntMatterForDemos". This can all be hardcoded. The user should only see the webpage navigating them to the members area for this user (whatever page would be produced after an accepted login on this page).
What is the best way of accomplishing this safely and reliably?

A: I think the best way to accomplish this would be to have a short and simple webpage that you initially route to that is hosted on your machine. This webpage will use client side code(javascript) to send a request to your server's webservices requesting your authentication token with that username and password, upon receiving it, reroute to your website and hand off the authentication token in the same manner that your login page achieves this, be it in a cookie, local storage, etc etc
This will hide your login credentials from the live version without you having to change how the live version works.


text:
Q: Access и символ новой строки Делаю вставку из .NET в MS Access. Объединяю несколько строчек массива в единую строку через \n с помощью string.join().
Так вот, почему-то после добавления данных в ячейку Access- эти данные визуально смотрятся как-будто идут единой строкой. Однако, если скопировать их в NotePad++, то на самом деле- это 2 разные строки и в конце стоит символ CRLF.
В тоже время в конце строки появляется какой-то пробельный символ, который удалить нельзя, а сам символ имеет код 10.
Почему-то при вставке отформатированного XDocument таких проблем не возникает и видно многострочное форматирования.
Access неправильно интерптирует \n?

A: Хм... оказывается NotePad++ слишком умный и сам ставит недостающий символ.
Проблема решилась путем добавления Environment.NewLine, что эквивалентно \r\n


text:
Q: Java - How can I add rgb values in an if statement? recently I was thinking to make a game and I choose, for the making of the maps, to use an image. It's a normal image, like this:

I wanted for each red pixel (255, 0, 0) to draw black rectangles 32x32 with an if statement. I made this but I can't get the RGB working:
loadMap() Method:
public void loadMap(BufferedImage image) {
    int w = image.getWidth();
    int h = image.getHeight();

    for(int xx = 0; xx < w; xx++) {
        for(int yy = 0; yy < h; yy++) {
            int pixel = image.getRGB(xx, yy);
            int alpha = (pixel >> 24) & 0xff;
            int red = (pixel >> 16) & 0xff;
            int green = (pixel >> 8) & 0xff;
            int blue = pixel & 0xff;

            if(red == 255 && green == 0 && blue == 0)
                handler.addObject(new Wall(xx*32, yy*32, ID.Wall, this));

        }
    }
}

Wall Class:
public class Wall extends GameObject {

public Wall(int x, int y, ID id) {
    super(x, y, id);
}

public void update() {

}

public void render(Graphics g) {
    g.setColor(Color.black);
    g.fillRect(x, y, 32, 32);
}

public Rectangle getBounds() {
    return new Rectangle(x, y, 32, 32);
}
}

GameObject class:
public abstract class GameObject {

protected int x, y;
protected float speedX = 0, speedY = 0;
protected ID id;

public GameObject(int x, int y, ID id) {
    this.x = x;
    this.y = y;
    this.id = id;
}

public abstract void update();
public abstract void render(Graphics g);
public abstract Rectangle getBounds();

... //Getter's and Setter's
}

Can anyone explain what's happening, please? Am I doing something wrong?
Thanks in advance!
PS: I've checked the RGB values on the image and they are correct, but it still doesn't work :(

A: your image does not contain 0x00FF0000 it is rendered with different colors and anti-aliased. I found your image has these colors:
(217,0,0) // main red
(127,0,0) // main anti aliased red
( 63,0,0) // bleeded anti aliased red

So I would try this instead:
if ((red>120)&&(green==0)&&(blue==0)) ...;

I feel safer with the added () inside if conditions.
PS. it is refreshing to see Question from a low rep user that contains all the info we needed +1 for that


text:
Q: Use complex SVG in android studio I have a SVG file of a map. I can't convert with android studio I have this error : error while parsing svg .
I already convert it into png file but the quality deteriorates.
Or is it possible to convert .SVG to a list of draw functions with canvas.

A: Your text overlay contains characters that aren't UTF-8, which is typically the default if not specified.
This character is the first culprit â
Put this at the top of your svg document.
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
This may work in Android and it may not, but its a starting point. The first thing I would try to do is cut-up the SVG into smaller pieces and load it in square chunks because is huge. Its better to draw 30 smaller things than 1 big thing because you're suffocating the UI thread if you try to do it all at once.
Also Text in general doesn't seem to be support in the Android Studio importer
Last thing on the page ->
https://developer.android.com/studio/write/vector-asset-studio


text:
Q: using loops in stored procedures in sql server i have a stored procedure with 5 parameters.
@1,@2,@3,@4,@5

Five Columns
@a,@b,@c,@d,@e

One of them is of string types(@a) which contains "N" number of numeric values separated by coma(,).
ex:
@a= '1,2,3,4,5,6'
@b='a'
@c='f'
@d='g'
@e='h'

My requirement is to insert "N" number of rows .
The value of rest four parameter's will remain same for every row whereas the value of @a parameter will be fetched by splitting @a.
The table will look like the attached file

A: create table testtable(a int, b char, c char, d char, e char)
go

declare @a varchar(20)= '1,2,3,4,5,6,7,8,9'
declare @b varchar(20)='a'
declare @c varchar(20)='f'
declare @d varchar(20)='g'
declare @e varchar(20)='h'

INSERT testtable(a,b,c,d,e)
SELECT t.c.value('.', 'VARCHAR(2000)'), @b, @c, @d, @e
FROM (
    SELECT x = CAST('<t>' +
        REPLACE(@a, ',', '</t><t>') + '</t>' AS XML)
) a
CROSS APPLY x.nodes('/t') t(c)

select * from testtable


text:
Q: What is the preferred way to do a CSS rollover? When setting up a rollover effect in HTML, are there any benefits (or pitfalls) to doing it in CSS vs. JavaScript?  Are there any performance or code maintainability issues I should be aware of with either approach?

A: It will still work in CSS if the browser happens to have Javascript disabled.

A: CSS is fine for rollovers. They're implemented basically using the :hover pseudo-selector. Here's a really simple implementation:
a{
    background-image: url(non-hovered-state.png);
}
a:hover{
    background-image: url(hovered-state.png);
}

There are a few things you need to be aware of though:

*

*IE6 only supports :hover on <a> tags

*Images specified in CSS but not used on the page won't be loaded immediately (meaning the rollover state can take a second to appear first time)

The <a>-tags-only restriction is usually no problem, as you tend to want rollovers clickable. The latter however is a bit more of an issue. There is a technique called CSS Sprites that can prevent this problem, you can find an example of the technique in use to make no-preload rollovers.
It's pretty simple, the core principle is that you create an image larger than the element, set the image as a background image, and position it using background-position so only the bit you want is visible. This means that to show the hovered state, you just need to reposition the background - no extra files need to be loaded at all. Here's a quick-and-dirty example (this example assumes you have an element 20px high, and a background image containing both the hovered and non-hovered states - one on top of the other (so the image is 40px high)):
a{
    background-image: url(rollover-sprites.png);
    background-position: 0 0; /* Added for clarity */
    height: 20px;
}
a:hover{
    background-position: 0 -20px; /* move the image up 20px to show the hovered state below */
}

Note that using this 'sprites' technique means that you will be unable to use alpha-transparent PNGs with IE6 (as the only way IE6 has to render alpha-transparent PNGs properly uses a special image filter which don't support background-position)

A: Because it's an aspect of presentation, I'd say it's more standards based to do it with CSS.  It used to be done in Javascript, simply because we couldn't do it with CSS (old browsers suck, and I don't think :hover was even added until CSS 2).

A: Implementing a rollover with CSS uses the :hover pseudo-class to define the style of the target element when it is hovered over.  This works great in many browsers but not in IE6 where it only works well with the anchor tag (i.e. a:hover).  I used CSS hover to implement a tabbed navigation bar but had to use IE behaviors to get it working in IE6.

A: Yep, the best way to do this is css sprites. An annoying problem occurs in IE6, when browser make a request every time an element is hovered. To fix this, take a look here.

A: I'd stay on the CSS side of the house, but I've done very little Javascript.
CSS seems to be easier to standardize across browsers than Javascript, though that may be changing with the advent of Chrome's V8 and Firefox's upcoming new rendering tool.

A: Isn't there a mnemonic for remembering the sequence of declarations in CSS?


text:
Q: ignore-error on Common Lisp I'm trying to handle errors in Common Lisp easily, but I have some problems.
In particular, I have this function.
(defun function1 (m)
 (ignore-errors (and (condition-1) (condition-2))
   (format t "Error message")))

I just want that if some conditions fail into the
(and (condition-1) (condition-2))

it's shown the error message, otherwise just
T

How can I do?
There is a better way to handle this type of errors? I looking for something very simple.
Someone can do an example showing how to use ignore-error?
Thank you.

A: You can use HANDLER-CASE
CL-USER 101 > (handler-case (and (evenp 2)
                                 (oddp 1))
               (error (c)
                 (princ c)
                 (values)))
T

CL-USER 102 > (handler-case (and (evenp 2)
                                 (/ 3 0)
                                 (oddp 1))
               (error (c)
                 (princ c)
                 (values)))
Division-by-zero caused by / of (3 0).


text:
Q: Why is this counting down after reaching the target? I wanted to have a counter that only activates when actually on the screen. I've managed to mangle this together from other examples I've found.
HTML:

Scroll Down

200

CSS:
div {
   height:800px;
   background:red;
}
h1 {
   display:none;
}

Javascript:
$(window).scroll(function() {
    var hT = $('#scroll-to').offset().top,
        hH = $('#scroll-to').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    console.log((hT - wH), wS);
    if (wS > (hT + hH - wH)) {
        $('.count').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 4000,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now));
                }
            });
        });
    }
});

DEMO:
https://jsfiddle.net/76d57vjL/
The problem is, it reaches 200 and then counts back down to 0 but I want it to just stay at 200. I can't seem to figure out whats actually causing it though.

A: The problem was that you were creating more than 1 animation, so going back to 1 after starting the count, i fixed it with a flag, but probably you could make something with the heights to check that out.
Here's the fix with the flag: https://jsfiddle.net/uc0av8fh/
var flag = true;
$(window).scroll(function() {
$('#scroll-to');
   var hT = $('#scroll-to').offset().top,
       hH = $('#scroll-to').outerHeight(),
       wH = $(window).height(),
       wS = $(this).scrollTop();
    console.log((hT-wH) , wS);
   if (wS > (hT+hH-wH)){
    $('.count').each(function () {
      if(!flag) return;
      //console.log();
      flag = false;
      $(this).prop('Counter',0).animate({
          Counter: $(this).text()
      }, {
          duration: 4000,
          easing: 'swing',
          step: function (now) {
              $(this).text(Math.ceil(now));
              return 1;
          }
      });
    });
   }
});


text:
Q: XNA (3.1) DrawUserPrimitives and SpriteBatch alpha issues I'm making something with XNA 3.1, and I'm attempting to create 2D Ribbon trails using DrawUserPrimitives. My algorithm simply adds new vertices each frame (provided some movement occurs), and also iterates through the vertices and fades them out as it goes, removing unneeded ones. This works quite well, except that I'm using a SpriteBatch for a lot of the other graphics. Now, I'm drawing this entire screen to a RenderTarget2D (for various reasons, and I cannot avoid it), and I'm getting this odd alpha issue.
The issue I'm having looks like this:

This should be a white trail that fades out as it goes. Clearly this isn't happening. Instead it's fading to the clear colour of the graphics device. When drawing this trail, I suspend the SpriteBatch (by calling End(), followed by Begin() once the drawing is done), so that I can get the depth correct. The effect I'm using to draw the primitive is just a BasicEffect with nothing special in it, and the code to initialise the SpriteBatch is here:
        spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.SaveState);
        graphics.GraphicsDevice.RenderState.SeparateAlphaBlendEnabled = true;
        graphics.GraphicsDevice.RenderState.AlphaDestinationBlend = Blend.One;
        graphics.GraphicsDevice.RenderState.AlphaSourceBlend = Blend.SourceAlpha;
        graphics.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
        graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;

The settings after initialising the SpriteBatch ensure correct colouring for semi-transparency in the RenderTarget texture. My guess would be that something here is causing the issue, but I'm not sure what. If anyone could help me with this, I'd be very grateful.
Cheers.

A: Oh... I fixed it. Needed to swap out SaveStateMode.SaveState with SaveStateMode.None.
Still wondering why I can't get antialiasing on it, though...


text:
Q: $X=${(x,y)$\in \mathbb R^2: 2x^2+3y^2=1$}. Endow $\mathbb R^2$ with discrete topology, and $X$ with the subspace topology. Let $X={(x,y)\in \mathbb R^2: 2x^2+3y^2=1}$. Endow $\mathbb R^2$ with discrete topology, and $X$ with the subspace topology. Then:

A. $X$ is a compact subspace of $\mathbb R^2$ in this topology
B. $X$ is a connected subspace of $\mathbb R^2$ in this topology
C. $X$ is open subspace of $\mathbb R^2$ in this topology
D. None of this.

As singleton compact in $\mathbb R$ and f(x,y)=$2x^2+3y^2$ is continuous, so $X$ is compact. Is this right? So A is correct option?

A: You need to be careful with applying a polynomial saying it is continuous - the topology (and thus the notion of continuity) is very different from the usual one. It is a good exercise to try and show that a continuous map from a discrete space to $\mathbb{R}$ (with the usual topology) must be constant.
As for the exercise, the topology on $X$ is the discrete topology - Indeed, one needs to show that every singleton subset of $X$ is open in $X$, but it is already open in $\mathbb{R}^2$. (and $X$ is infinite)
Now, $X$ can't be compact - we can take all singletons as an open cover, which will have not finite subcover. Furthermore, $X$ cannot be connected - all singletons are both open and closed (and $X$ has more than one point)
We arrive at C - $X$ is open in $\mathbb{R}^2$ because every subset is - this is exactly the definition of the discrete topology : all sets are open.

A: For B: If you know the definition of connectedness this should be really easy with the discrete toplogy.
For C: Even more so

A: Define a metric $d$ on $X$ which is the discrete metric.
 So,$(X,d)$ maintains its discrete topology.
But,$X$ is not totally bounded with respect to the metric $d$.
So,$X$ is not compact.


text:
Q: Regex with backreference as repetition count Is there any way to construct a regex that would work as follows:

Match integer as group 1, then match \1 integers.

This (\d+)(\s+\d+){\1} unfortunetly isn't allowed, but I find it a good description of what i am trying to achive.

A: You can do something like this
var numbers = "3 7 6 5 4 3 2 1"; // list of numbers
var iter = numbers.split(" ")[0] // get first number
numbers = numbers.substr(iter.length+1) // chop off first number, and the space that follows it you can comment
var rex = new RegExp("(?:\\d(?: |$)){" + iter + "}","") // create regex
alert((numbers.match(rex)||[]).join("\n")) // a sample alert that joins the array to a string with an element on each line

Alternatively, if you want the first digit that defines the number of occurrences in the same array, a few changes make it possible
var numbers = "3 7 6 5 4 3 2 1"; // list of numbers
var iter = numbers.split(" ")[0] // get first number
var rex = new RegExp("(?:\\d(?: |$)){" + (+iter+1) + "}","") // create regex
alert((numbers.match(rex)||[]).join("\n")) // a sample alert that joins the array to a string with an element on each line

A: Thanks to @Kobi for the suggestion to use code callouts. It is indeed possible to build a dynamic length match using the last backreference. The code would look something like this:
$s = '3 4 5 6 7 8 9 10';
$s =~ /(\d+)\s+((??{"(\\s*\\d+){$^N}"}))/;
print "$1\n$2\n"

Prints
3
4 5 6


text:
Q: How to get run id from run name in MLflow To download artifacts from a run, you need run id. I get the run id from the UI as shown below.
Run id from the UI
But when I set the run name parameter, run id is not visible in the UI. How to find the run Id of a particular run in MLflow ?

A: The run id in mlflow is a random stamp id generated. I had the same problem because I wrote an mlflow decorator, which needed access to the run id after the run was finished to set tags.
The question is what do you want to do after you have the run id? Then the approach would need extra infos.
If you only want to get access to your latest run:
Use the mlflow.list_run_infos() function and insert the experiment_id, which you can get by the mlflow.get_experiment_by_name function of mlflow. I guess you know your experiment's id. Here is the list_run_infos function
def list_run_infos(
        self,
        experiment_id: str,
        run_view_type: int = ViewType.ACTIVE_ONLY,
        max_results: int = SEARCH_MAX_RESULTS_DEFAULT,
        order_by: Optional[List[str]] = None,
        page_token: Optional[str] = None,
    )

Then you should get a list of run objects. But, please read further:
In case you have multiple run objects in your experiment (that happens with several runs or even child runs from a parent run with Gridsearch and sklearn).
Loop through each! Runobject from the output of list__run_infos() and look at the end_time property of the Runobject. The endtime property is a UNIX timestamp. So even if you have a parent run or a single run, the highest UNIX timestamp in the end_time property will always be your last run (In case you didnt used several estimators in a loop in your experiment, that would require some refactoring). And by that you identify the appropriate RunObject.
Only then! you can access the Runtime Object's property: the run_id:
Here you can see the class of the run object from mlflow, keep in mind that you also need the exp_id again.
classmlflow.entities.RunInfo
(
    run_uuid,
    experiment_id,
    user_id,
    status,
    start_time,
    end_time,
    lifecycle_stage,
    artifact_uri=None,
    run_id=None
)

In case you need the specific code:
last_parent_run = set()
exp_id = mlflow.get_experiment_by_name("your_exp_name"].experiment_id

for item in mlflow.list_run_infos(exp_id):
    last_parent_run.add((item.__getattribute__("end_time"), item.__getattribute__("run_id")))

And then of course look for the maximum entry in your set
If you have any further questions just ask; i already tested my decorator with this and it works fine and keeps the main code of mlflow statements clean. Although its a little bit hacky, to access the run_id after the run.


text:
Q: Circuit Nodal Voltage I have a voltage divider feeding into an op-amp voltage follower buffer circuit. I'm trying to calculate the voltage level at the non-inverting input of the op-amp vs. the source voltage. The possible supply voltage is roughly in the range [0V, 5V].

First I tried using a simple voltage divider, so:
$$
V_A = R_2 / (R_1 + R_2) * V_S
$$
However, when I tried simulating this circuit in TINA-TI, the nodal voltages don't match those calculated.
I thought that was because the notion that there is no current flowing through the op-amp input wasn't truly non-zero, so I tried compensating for the op-amp input resistance and capacitance.

This time, the output voltage should be:
$$
V_A = (R_2 || R_3) / (R_1 + R_2||R_3) * V_S
$$
While this equation does match TINA-TI's simulation of the no op-amp circuit, it still doesn't match the op-amp circuit.
What else am I missing?
edit:
further information: I'm using the LMH6612 op-amp.
Suppose I want to target an output voltage of 2.5V. According to my first equation the required source voltage is ~2.82V. By recursively updating my simulation I calculated that the actual required source voltage is ~3.47V. Using the second circuit the required source voltage is closer, but only marginally at ~2.87V.

A: After further reading into non-ideal op-amp behavior it looks like it's actually the op-amp input bias current that's the culprit.
R1||R2 ~= 100kohm, which created about a 0.6V drop (close enough to what the difference was). Adding a resistor to the inverting input equivalent to R1||R2 fixed the problem.
Reference:
Practical Considerations: Bias current
The fixed circuit:


text:
Q: Image is hanging, what next? I was following the tutorial on Magma from the awesome Seaside book and at one point my image got stuck completely. I was in the debugger at that moment and I've tried to run "inspect it" on ToDoDB root part of the following snippet:
ToDoDB createDB.
ToDoDB commit: [ ToDoDB root add: ToDoItem new ].
ToDoDB release.

After that my image stopped responding to anything.
I'm kind of curious why Magma behaved that way on inspect action, but I'm more interested in learning what are my options for fixing this issue? Should I just throw out this image and start from scratch? Can I send some OS signal to the VM to kill the active thread or something? Smalltalk newbie here.

A: Sean has already answered, but you can find it also in the pharo collaborative book: http://book.pharo-project.org/book/TipsAndTricks/InterruptKey/
Just another remark where you say "Can I send some OS signal to the VM to kill the active thread or something? Smalltalk newbie here.". Notice that most Smalltalk dialects have what is called "green thread". That is, that from the OS point of view it is only one thread. Smalltalk inside manages itself the different process and the schedule about it. Check classes like Processor, Scheduler, etc. So...what I am saying that if you want to kill a thread from outside, you will kill the only thread, the whole VM ;)

A: Try sending an interrupt. See http://wiki.squeak.org/squeak/899 for the shortcut for your platform (i.e. underlying OS).
Also, you probably mean "throw out this image" instead of "this VM". Pharo By Example is a great free resource for Smalltalk basics like image vs. changes file vs. VM


text:
Q: Flutter how to show single value from List? I am trying to filter data from array and then need to just a single value from data. Its showing filtered data but need to know how can i show a single value from that data ?
class _ViewPostScreenState extends State<ViewPostScreen> {
List showPost;
String data;

  @override
  void initState(){
    super.initState();
    print(widget.id);
    showPost = posts.where((i) => i.id == widget.id).toList();
    data = showPost.toString();
    print(data);

  }

The response or print output of data is this I/flutter ( 7374): [{id: 0, authorName: Umaiz Khan, authorImageUrl: assets/images/user0.png, timeAgo: 5 min, imageUrl: assets/images/post0.jpg}]
I need to know how can I just show the authorName from this data?
something like this print(data.authorName); try to do like this but not working.
Here my data look like in other file
class Post {
  String authorName;
  String authorImageUrl;
  String timeAgo;
  String imageUrl;
  int id;

  Post({
    this.authorName,
    this.authorImageUrl,
    this.timeAgo,
    this.imageUrl,
    this.id,
  });

  @override
  String toString() {
    return '{id: $id, authorName: $authorName, authorImageUrl: $authorImageUrl, timeAgo: $timeAgo, imageUrl: $imageUrl}';
  }
}

final List<Post> posts = [
  Post(
    id: 0,
    authorName: 'Umaiz Khan',
    authorImageUrl: 'assets/images/user0.png',
    timeAgo: '5 min',
    imageUrl: 'assets/images/post0.jpg',
  ),
  Post(
    id: 1,
    authorName: 'Saad ahmed',
    authorImageUrl: 'assets/images/user1.png',
    timeAgo: '10 min',
    imageUrl: 'assets/images/post1.jpg',
  ),
  Post(
    id: 2,
    authorName: 'Hiba',
    authorImageUrl: 'assets/images/user4.png',
    timeAgo: '10 min',
    imageUrl: 'assets/images/post2.jpg',
  ),
];

A: Change String data to Post data
data = showPost[0];

A: You can always use this for loop when you want to fetch any list base on value of an object inside it, where in your case the widget.id should be equivalent to an id of a post
@override
  void initState() {
    super.initState();
    print(widget.id);

    Post getPost(int postID) {
      for (int i = 0; i < posts.length; i++) {
        if (posts.elementAt(i).id == postID) {
          return posts.elementAt(i);
        }
      }
      return null;
    }

    print(getPost(widget.id).authorName);
  }

I hope this help


text:
Q: Can I write file on SD Card With the new SDK 8.1 of Windows Phone is there a way to write file on SD Card ? Before we could only read. I have an idea to save file from my app on SD Card and this can be interesting for the Lumia 520 who have few memory.

A: More information about Data and Files you will find in the documentation. And as written here:

What you can access
Your app can only read and write files of file types that the app has registered to handle in the app manifest file.
Your app can also create and manage folders.

So if you had declared File Type Association - there shouldn't be a problem to write/read files.
Note also that your App can be installed on SD Card, then all its files will be located there.


text:
Q: Have I correctly solved this RLC problem?
Now I needed to find the transfer function as well as impulse response
$$\\ R=14\Omega \\ L=2H \\ \\ C=\frac{1}{12}F \\ In \ s-domain \\ R=14\Omega \\ L=sL=s\cdot 2=2s \\ \\ C=\frac{1}{sC}=\frac{1}{s\cdot \frac{1}{12}}=\frac{12}{s} \\ H(s)=\frac{Y(s)}{X(s)}=\frac{L+C}{R+L+C}=\frac{2s+\frac{12}{s}}{14+2s+\frac{12}{2}}=\frac{2s^{2}+12}{2s^{2}+14s+12} \\ L^{-1}[\frac{2s^{2}+12}{2s^{2}+14s+12}]=\delta (t)+\frac{7}{5}e^{-t}-\frac{42}{5}e^{-6t}$$


text:
Q: Insertion sort using Linked Integer Nodes Hey there I have been trying to get an insertion sort method to work for a class I'm taking and we have been told to use insertion sort to sort a linked list of integers without using the linked list class already in the Java libraries.
Here is my inner Node class I have made it only singly linked as i don't fully grasp the circular doubly linked list concept yet
public class IntNode
{
  public int value;
  public IntNode next;
}

And here is my insertion sort method in the IntList class
public IntList Insertion()
{
IntNode current = head;

while(current != null)
    {
    for(IntNode next = current; next.next != null; next = next.next)
        {
        if(next.value <= next.next.value)
            {
            int temp = next.value;
            next.value = next.next.value;
                next.next.value = temp;
            }
        }
    current = current.next;
    }
return this;
}

The problem I am having is it doesn't sort at all it runs through the loops fine but doesn't manipulate the values in the list at all can someone please explain to me what I have done wrong I am a beginner.

A: you need to start each time from the first Node in your list, and the loop should end with the tail of your list -1
like this
 public static IntList Insertion()
{
     IntNode current = head;
     IntNode tail = null;
     while(current != null&& tail != head )
     {
       IntNode next = current;
      for( ; next.next != tail;  next = next.next)
    {
    if(next.value <= next.next.value)
        {
        int temp = next.value;
        next.value = next.next.value;
            next.next.value = temp;
        }
    }
    tail = next;
   current = head;
  }
 return this;

}

A: The insertion operation only works if the list being inserted into is already sorted - otherwise you're just randomly swapping elements. To start out, remove an element from the original list and construct a new list out of it - this list only has one element, hence it is sorted. Now proceed to remove the remaining elements from the original list, inserting them into the new list as you go. At the end the original list will be empty and the new list will be sorted.

A: I agree with the Zim-Zam opinion also.
The loop invariant of insertion sort also specifies this: "the subarray which is in sorted order".
Below is the code, I implemented for insertion sorting in which I created another linked list that contains the element in sorted order:
Node newList=new Node();
        Node p = newList;
        Node temp=newList;
        newList.data=head.data;
        head=head.node;
        while(head!=null)
        {
            if(head.data<newList.data)
            {
                Node newTemp = new Node();
                newTemp.data=head.data;
                newTemp.node=newList;
                newList=newTemp;
                p=newList;
            }
            else
            {
                while(newList!=null && head.data>newList.data)
                {
                    temp=newList;
                    newList=newList.node;
                }
                Node newTemp = new Node();
                newTemp.data=head.data;
                temp.node=newTemp;
                newTemp.node=newList;
                newList=p;
            }

            head=head.node;
        }


text:
Q: TS Typings for Docker variable ENV error when using SSR I followed this tutorial to use env variable in Angular with docker
Everything seems quite easy to configure, however when I build my project, there is error
...\server\main.js:12952
apiUrl: $ENV.API_URL || "http://localhost:3000",
        ^
ReferenceError: $ENV is not defined

I suspect the src/typings.d.ts to be forgotten
src/typings.d.ts
declare var $ENV: Env;

interface Env {
  API_URL: string,
}

Should I modify the tsconfig files ? there is no clear documentation about it.

*

*tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
  "baseUrl": "./",
  "outDir": "./dist/out-tsc",
  "sourceMap": true,
  "declaration": false,
  "downlevelIteration": true,
  "experimentalDecorators": true,
  "moduleResolution": "node",
  "importHelpers": true,
  "target": "es2015",
  "module": "es2020",
  "lib": [
    "es2018",
    "dom"
  ]
 }
}

*tsconfig.app.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
  "outDir": "./out-tsc/app",
  "types": []
},
"files": [
  "src/main.ts",
  "src/polyfills.ts"
],
"include": [
  "src/**/*.d.ts"
]
}

*tsconfig.server.json
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
  "outDir": "./out-tsc/server",
  "target": "es2016",
  "types": [
    "node"
  ]
},
"files": [
  "src/main.server.ts",
  "server.ts"
],
"angularCompilerOptions": {
  "entryModule": "./src/app/app.server.module#AppServerModule"
}
}

*tsconfig.spec.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
  "outDir": "./out-tsc/spec",
  "types": [
    "jasmine"
  ]
},
"files": [
  "src/test.ts",
  "src/polyfills.ts"
],
"include": [
  "src/**/*.spec.ts",
]
}

Update
The custom webpack code
"projects": {
    "name-of-the-project": {
      //...
      "architect": {
        "build": {
          "builder":"@angular-builders/custom-webpack:browser"_,
          "options": {
            "customWebpackConfig": {
                "path":"custom-webpack.config.js"
            },
            //...
        //...
    }

custom-webpack.config.js
const webpack = require('webpack');

module.exports = {
  plugins: [
    new webpack.DefinePlugin({
      $ENV: {
        API_URL: JSON.stringify(process.env.API_URL)
      }
    })
  ]
};

UPDATE
I did all from scratch and the tutorial is working only without SSR (ng add @nguniversal/express-engine). After installing SSR the typings.d.ts is not taken into account anymore  :(
Step to reproduce the issue:
ng new app

follow tutorial listed in the first line of this post
create dockerfile
#stage 1
FROM node:latest as node
WORKDIR /app
COPY package*.json ./
RUN npm install
# SET ENVIRONMENT VARIABLES
ENV ENVIRONMENT=production1
ENV SomeAPIKey="This is not an API Key"
ENV SomeOtherAPIKey="This is not another API Key"
COPY . .
RUN npm run build --prod

#stage 2
FROM nginx:alpine

COPY --from=node /app/dist/app /usr/share/nginx/html

EXPOSE 80

Build docker :
docker build . test

Run docker :
docker run test

It works !!!
If now I add ng add @nguniversal/express-engine
I have to replace my dockerfile to take into account SSR but then I have this error :(
Compiled successfully.
/Users/xxx/Dev/app/dist/app/server/main.js:116
    environment: $ENV.ENVIRONMENT,
                 ^

ReferenceError: $ENV is not defined


text:
Q: Hibernate create subquery exists with association table I have a DB schema like this:
CREATE TABLE livraison ( /* delivery */
  id INTEGER PRIMARY KEY NOT NULL DEFAULT nextval("livraison_id_livraison_seq"
  /* others propertes */
)

CREATE TABLE article ( /* product */
  id INTEGER PRIMARY KEY NOT NULL DEFAULT  nextval("article_id_article_seq")
  /* others properties */
)

CREATE TABLE article_livre ( /* association table */
  id_article INTEGER NOT NULL REFERENCES article(id),
  id_livraison INTEGER NOT NULL REFERENCES livraison(id),
  rang INTEGER,
  PRIMARY KEY (id_article, id_livraison)
)

The entities classes are like this:
@Entity
@Table(name="livraion")
class Livraison { /* ... */ }

@Entity
@Table(name="article")
class Article { /* ... */ }

@Entity
@Table(name="article_livre")
@AssociaitonOverride({
  @AssociationOverride(name="id.article", joinColumns=@JoinColumn(name="id_article"),
  @AssociationOverride(name="id.livraison", joinColumns=@JoinColumn(name="id_livraison")
})
class ArticleLivre {
  /* ... */
  @EmbeddedId
  public ArticleLivrePK getId() { /* ... */ }
  /* ... */
}

@Embeddable
class ArticleLivrePK {
  /* ... */
  @ManyToOne
  public Article getArticle() { /* ... */ }

  @ManyToOne
  public Livraison getLivraison() { /* ... */ }
  /* ... */
}

The same product can be delivered multiple times (it's rented) so it can be in multiple deliveries.
I'm trying to execute a query like this example (HQL) with the Hibernate query builder:
SELECT *
FROM Livraison
WHERE /* restrictions on the Livraison entity */
AND EXISTS (
    SELECT id
    FROM ArticleLivre
    JOIN Article ON ArticleLivre.id.article = article.id
    WHERE ArticleLivre.id.livraison = Livraison.id
      /* AND restrictions on the Article entity */
  )

I'm using Hibernate 4.3.10 with Java 10 and PostgreSQL 9.1.9
So far my code looks like this:
Criteria search = session.createCriteria(Livraison.class);
DetachedCriteria articlesLivres = DetachedCriteria.forClass(ArticleLivre.class);
livraisonRestrictions.forEach(search::add);
articlesLivres.add(Restrictions.eqProperty("ArticleLivre.id.livraison", "Livraison.id"));
DetachedCriteria articles = articlesLivres.createCriteria("id.article");
articlesRestrictions.forEach(articles::add);
search.add(Subqueries.exists(articlesLivres.setProjection(Projections.property("ArtileLivre.rang"))));
List livraison = search.list();

When I run this code I have this error: org.hibernate.QueryException: could not resolve property: ArtileLivre.rang of: core.ArticleLivre.
I don't understand how to correct this error.


text:
Q: Validation of viewstate MAC failed I am currently receiving this error:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

I have found multiple solutions to this error. The solution we are currently using is to add a static MachineKey field at the machine level and to use static validation keys and decryption keys.
<MachineKey validationKey="" decryptionKey="" validation="SHA1" decruption="AES" />

Will this solution work for .NET 3.5? Is there a more elegant solution?

A: Is your web app hosted in a webfarm?
If so, the reason for this is that a page is rendered by server 1, and posted to server 2. Therefore, machine keys are different, and the validation failed.
It will work on ASP.NET 3.5 as well.


text:
Q: Pasting to vim from clipboard cuts off first few lines I'm using vim in terminal on OSX with a blank .vimrc file. I try to paste the following from my clipboard:
#!/bin/bash
set -e
set -o pipefail

npm run precommit

using
:set paste

but in vim, what's pasted (using cmd-v) is
et -e
set -o pipefail

npm run precommit

Anybody know what's wrong?

A: I had the same problem, the trick was to reset my terminal by typing 'reset' before running vim.

A: You have to enter into insert mode before you can edit the file, you can do this by pressing the i key.

A: If you're using vim on OSX, you can add the following to your .vimrc:
set clipboard+=unnamed
Once you have done this, vim will use the system clipboard to read from by default for pasting. This means that, instead of having to enter insert mode first you can simply use p to paste. It also means that if you yank within vim, it's available to paste elsewhere.
I haven't tested this on any other OS, so if anyone has please feel free to add a comment...


text:
Q: A Gronwall-type inequality. I want to derive a Gronwall-type inequality from the inequality below. Here all the functions are nonnegative, continuous and if you need some assumptions you may use that.
$$ f^2(t) \leqslant g^2(t) + \int_0^t (f(s) +c) f(s) ds  \;\;\;\; (t \in [0,T]) $$
So please help!

A: Consider the function
$$h(t):=\int_0^t f(s)e^{t-s}ds\,,$$
which solves the ODE $h'=h+f$ with $h(0)=0$, so $$h(t):=\int_0^t \Big(h(s)+f(s)\Big)ds\, .$$
Adding the term $-c\, h(t)$ to both sides, your inequality takes a more familiar form of a Gronwall inequality:
$$f(t)^2-c\;h(t)\le g(t)^2 + \int_0^t \Big(f(s)^2 -c\;h(s)       \Big)ds  $$
relative to the function $f(t)^2-c\; h(t)$.

A: Consider g=0, c=2, f(t)=t.
By the way, what did you mean by "if you need some assumptions?" Are there folks out there who prove things without them?


text:
Q: Passing nonce at admin menu link I'm trying to pass a nonce at the links created from my plugin using add_menu_page and add_submenu_page.
Of course this is invalid:
add_submenu_page(
 'my_dashboard',
 'Dashboard',
 'Dashboard',
 'manage_options',
 'my_dashboard&nonce-field=' . wp_create_nonce('my_action'),
 'show_dashboard'
);

as per the Codex, the slug should only include lowercase alphanumeric, dashes, and underscores characters.
So my question is, how could we pass nonce in the URL of the menu links a plugin creates?

A: WordPress do not accept nonce in the slug that you are trying to provide in the above code.
I mean in this line:
 'my_dashboard&nonce-field=' . wp_create_nonce('my_action'), 'show_dashboard'

I was facing the same issue like you are facing. As the admin menu already verified for specific users so we don't need to verify it again with nonce. Therefore, to skip that issue you can use that code at top of your file where you using $_GET or $_POST super global.
check_admin_referer(-1);

It will remove the warning for nonce verification.


text:
Q: API, showing results twice and not in correct order For the first time I'm creating a API to import data to a swift App (iOS)
But I get all my results twice and the results don't know where the belong or are in the wrong order...
I think it's because I have several tables I'm pulling from.
an example:
$sql = "SELECT * FROM node, field_data_body";
//Drupal tables
I have heard about the WHERE statement, but got no clue.

A: What you do is a implicit cross JOIN, as you select from multiple tables. Without using conditions in your WHERE clause, you had all combinations of those tables.
If your tables are fully separate/independent, you can create 2 different SELECT queries for each of tables.
Otherwise, if there is a relationship between them, you should select one of the JOIN types, that is most appropriate for your goal, and describe his relationship in query using WHERE conditions.
Lets assume that node table has "id" column, and field_data_body has "node_id" column. Then query can be the following:
SELECT * FROM node
LEFT JOIN field_data_body ON node.id = field_data_body.node_id

or the same
SELECT * FROM node
LEFT JOIN field_data_body WHERE node.id = field_data_body.node_id

Here is a good visual representations of SQL JOINs.

A: As far as I know it's recommended to use the Entity API to query data from Drupal, and here is a document, https://www.drupal.org/node/1343708
And you can also set up your query with View module, and set the output to JSON.
The third option could be using https://www.drupal.org/project/rest_server module.

A: Perhaps the tables node and field_data_body contain the same data? Your selecte * from statement would take everything, if it's not distinct.


text:
Q: undo continually vi I am using vi(not Vim) and I would like to continually undo the changes made. u works for a single command undo and Ufor a single line undo. But Is there a way to undo continuously like vim(I recall a command in vim can even undo changes by time!) in vi?
Thanks in Advance.
Edit:
I am using vi version 3.10

A: Repeat the undo, with the . key.

A: May not work in 3.1 version.
Undo continually things like stack-popping
u . . .

Suppose you write hello in insert -mode. Go to normal mode, write hallo and go to normal mode. Then type u ., you get hello. Type again . and you will get blank. You can reverse it by typing again u . . so you will get hello hallo. It is very easy to memorize because it works like stacks! I.e. undo repeat the last command repeat the last command where the repeat the last command can be undo. When you press u u, it does mean undo the last command: undo last command and the second u means undo the last command and in this case it is u.
Tested with Nvi Version 1.79 (10/23/96) The CSRG, University of California, Berkeley, OpenBSD. You can get the source here.


text:
Q: Error accessing data from an array in ruby on rails The error tells me that the method '[]' is not defined in the line 127
this is my code and Idon't see the error
def verificar_area archivo
bandera= false
Spreadsheet.client_encoding = 'UTF-8'
book = Spreadsheet.open archivo
@wk = book.worksheet 0

areas = ["Secundaria",
"Preparatoria",
"Universitario",
"Edad 11 a 15 años",
"Edad de 16 a 19 años",
"Solo estudian",
"Adolescentes que trabajan y estudian"]

(1 .. @wk.row_count).each do |index_renglon|
  @renglon_excel = @wk.rows[index_renglon]
  area=@renglon_excel[8]                        #This is the line 127
    if areas.include?(area)
      bandera=true
    else
      bandera=false
      break
    end #fin if
  end #fin for
  return bandera
end

the error in the browser is this

A: You are getting the error because @renglon_excel is nil for that specific iteration
@renglon_excel[8]

And you are trying to access with index of [8] on nil
To avoid this you can add a check
@renglon_excel = @wk.rows[index_renglon]
next unless @renglon_excel
area = @renglon_excel[8]


text:
Q: Managing notification in android notification tray I am using notification builder to display the custom notification. My concept is to display the latest record in the database as notification and I have done that. And I am recalling the notification function every one hour so that if any newly added data will be pushed as notification. Now the notification once clicked should not be displayed again when that method is called every hour(if there is no newly added data). Any way to do this?
public void CustomNotification(String title_notify,String image_notify) {
    // Using RemoteViews to bind custom layouts into Notification
    RemoteViews remoteViews = new RemoteViews(getPackageName(),
            R.layout.customnotification);

    // Set Notification Title
    String strtitle = title_notify;
    // Set Notification Text
    String strtext = "";

    // Open NotificationView Class on Notification Click
    Intent intent = new Intent(this, Notification_ListView.class);
    // Send data to NotificationView Class
    intent.putExtra("title", strtitle);

    intent.putExtra("location", location);
    intent.putExtra("text", strtext);
    intent.putExtra("user_id", user_id);
    intent.putExtra("country_id", country_id);
    // Open NotificationView.java Activity
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    bitmap = getBitmapFromURL(image_notify);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            // Set Icon
            .setSmallIcon(getNotificationIcon())
            // Set Ticker Message
            .setTicker("")
            // Dismiss Notification
            .setAutoCancel(true)
            // Set PendingIntent into Notification
            .setContentIntent(pIntent)
            // Set RemoteViews into Notification
            .setContent(remoteViews);

    // Locate and set the Image into customnotificationtext.xml ImageViews
    remoteViews.setImageViewBitmap(R.id.imagenotileft,bitmap);
    //remoteViews.setImageViewResource(R.id.imagenotiright,R.drawable.androidhappy);

    // Locate and set the Text into customnotificationtext.xml TextViews
    remoteViews.setTextViewText(R.id.title,strtitle);
    remoteViews.setTextViewText(R.id.text,strtext);

    // Create Notification Manager
    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    // Build Notification with Notification Manager
    notificationmanager.notify(0, builder.build());

}


text:
Q: Ввод прямоугольной матрицы без заведомо известной размерности в Python Задание:
Напишите программу, на вход которой подаётся прямоугольная матрица в виде последовательности строк, заканчивающихся строкой, содержащей только строку "end" (без кавычек)
Программа должна вывести матрицу того же размера, у которой каждый элемент в позиции i, j равен сумме элементов первой матрицы на позициях (i-1, j), (i+1, j), (i, j-1), (i, j+1). У крайних символов соседний элемент находится с противоположной стороны матрицы.
С алгоритмом суммы элементов я планирую справиться самостоятельно, но мне не хватает знаний языка чтобы реализовать сам ввод данных максимально лаконично и без лишних костылей
Пример ввода:

9 5 3
0 7 -1
-5 2 9
end

Пример вывода:

3 21 22
10 6 19
20 16 -1

A: Если без обработки ошибок:
mat = []
while True:
    s = input()
    if s == "end":
        break
    row = [int(x) for x in s.split()]
    mat.append(row)
print(mat)

1 2 3
4 5 6
end

>>[[1, 2, 3], [4, 5, 6]]

A: Дописал первый ответ, продолжение считает сумму всех соседей по вертикали и горизонтали.
    mat = []
    while True:
        s = input()
        if s == "end":
            break
        row = [int(x) for x in s.split()]
        mat.append(row)
    for i in range(len(mat)):
        for j in range(len(mat[i])):
            x = mat[i-1][j] + mat[i-len(mat)+1][j] + mat[i][j-1] + mat[i][j-len(mat[i])+1]
            print(x, end=' ')
        print()


text:
Q: Diferença de performance e situação de uso de tipos numéricos Gostaria de saber a diferença entre os tipos Long, Double, Float, Decimal e Int, levando em consideração de quando é o melhor uso em casos reais. Ex: "usa float em juros pois é...". E também a diferença de performance entre elas. Ex: "int tem performance melhor que long pois..."
Acho que é bem valida a pergunta, levando em consideração que muitas vezes usamos errado em nosso dia a dia, e por minima diferença de performance faça, é sempre interessante pensarmos nisso.

A: No .Net (assim como em várias outras linguagens), existe uma separação entre tipos inteiros e tipos racionais, então vou separar minha explicação desses tipos nessas duas categorias.
Tipos Inteiros
Existem vários tipos inteiros, novamente podem ser separados em dois grupos, os que aceitam valores negativos, e os que não aceitam valores negativos.
Aceitam Negativos (possuem sinal): Int32 é o mais comum, mas temos outros: Int16, Int64 (não existe Long, mas sim o alias long no C#, que é o mesmo que Int64) e SByte.
│ Tipo  ║ Bits ║           Mínimo           ║            Máximo         ║ Alias C# ║ Literal │
╞═══════╬══════╬════════════════════════════╬═══════════════════════════╬══════════╬═════════╡
│ SByte ║  8   ║ -128                       ║ 127                       ║  sbyte   ║         │
│ Int16 ║  16  ║ -32768                     ║ 32767                     ║  short   ║         │
│ Int32 ║  32  ║ -2.147.483.648             ║ 2.147.483.647             ║  int     ║    0    │
│ Int64 ║  64  ║ -9.223.372.036.854.775.808 ║ 9.223.372.036.854.775.807 ║  long    ║    0L   │
└───────╨──────╨────────────────────────────╨───────────────────────────╨──────────╨─────────┘

As letras que aparecem nos literais, podem ser maiúsculas ou minúsculas: 0L é o mesmo que 0l.
Aceitam valores positivos apenas (sem sinal):
│ Tipo   ║ Bits ║ Mínimo ║            Máximo          ║ Alias C# ║ Literal │
╞════════╬══════╬════════╬════════════════════════════╬══════════╬═════════╡
│ Byte   ║  8   ║   0    ║ 255                        ║  byte    ║         │
│ UInt16 ║  16  ║   0    ║ 65535                      ║  ushort  ║         │
│ UInt32 ║  32  ║   0    ║ 4.294.967.295              ║  uint    ║   0U    │
│ UInt64 ║  64  ║   0    ║ 18.446.744.073.709.551.615 ║  ulong   ║   0UL   │
└─────═──╨──────╨────────╨────────────────────────────╨──────────╨─────────┘

As letras que aparecem nos literais, podem ser maiúsculas ou minúsculas: 0UL é o mesmo que 0ul.
Em termos de uso desses tipos, não há grande diferença de performance no uso de variáveis locais ou parâmetros de métodos. Geralmente se usa o tipo Int32 (int) para esses usos, a não ser que os valores esperados excedam os limites do int, em cujo caso se usa Int64 (long).
Já o Byte (byte) só é usado mesmo para trabalhar com dados binários, nunca vi sendo usado em códigos que não sejam com este fim.
Os outros tipos, geralmente só são usados em estruturas de dados struct ou class muito longas, ou então em arrays, de forma que ocupem menos memória... mas isso só faria sentido mesmo em estruturas muito usadas, ou em arrays muito grandes mesmo, da ordem de milhões ou até mesmo bilhões de itens.
Além de tudo isso, vejo os tipos sem sinal (aqueles que só aceitam positivos) serem usados em operações bit-a-bit (chamadas comumente de bitwise), pela facilidade de se trabalhar com todos os bits dos mesmo, o que é mais difícil quando há o bit de sinal.
Tipos Racionais
Há apenas 3 desses no .Net: Single, Double e Decimal.
│   Tipo   ║     Single    ║      Double               ║      Decimal                            │
╞══════════╬═══════════════╬═══════════════════════════╬═════════════════════════════════════════╡
│ Alias C# ║     float     ║      double               ║      decimal                            │
│ Mínimo   ║ -3.402823e+38 ║  -1.7976931348623157e+308 ║ -79.228.162.514.264.337.593.543.950.335 │
│ Máximo   ║  3.402823e+38 ║   1.7976931348623157e+308 ║  79.228.162.514.264.337.593.543.950.335 │
│ Literal  ║    0f         ║   0.0  ou  0d             ║     0m                                  │
│ Base Exp.║    2          ║    2                      ║     10                                  │
└──────────╨───────────────╨───────────────────────────╨─────────────────────────────────────────┘

As letras que aparecem nos literais, podem ser maiúsculas ou minúsculas: 0M é o mesmo que 0m.
Os tipos de base 2 (Single e Double), são operados por instruções do próprio processador, em uma
unidade chamada de FPU (floating-point unit)... e que nos processadores atuais
são tão otimizados, que as operações matemáticas com pontos flutuantes chegam
a ser tão rápidas quanto com tipos inteiros.
Os tipos Single e Double são usados quando não há de se ter correspondência
exata com números decimais em uma fração. Exemplos: cálculos que envolvem a
física, usadas na engenharia ou nas simulações feitas em jogos, usam estes tipos.
Em termos de performance os tipos Single e Double são iguais nas máquinas
atuais, pois a FPU converte ambos internamente para 80-bits. Então a única vantagem
real em se usar Single é em termos de uso de memória.
O tipo Decimal existe para dar suporte a operações que devem ter correspondência
exata com frações decimais do mundo real, com quando trabalhando com valores
monetários... inclusive, acho que o M do literal vem de money (mas isso eu estou
especulando).
O tipo Decimal possui 128 bits, dos quais 96 são usados para representar o valor interno
chamado de mantissa, e os outros são usados para indicar um divisor de base 10...
é praticamente um expoente, igual o que existe para os de base 2, só que na base 10
e apenas negativos. Portanto, o Decimal não é capaz de representar números
tão grandes como o Single e o Double (pois esses dois aceitam expoentes positivos).
Em compensação, o tipo Decimal possui uma precisão absurdamente maior.
Em termos de performance, o tipo Decimal é muito ruim, se comparado aos tipos
de base-2, pois todas as operações matemáticas são feitas na ALU (Arithmetic logic unit),
e por isso são subdivididas em várias estapas de cálculos independemente da operação
sendo feita.

A: Basicamente precisão é a grande diferença entre eles:
Float: 7 Digitos (32 bit)
Double: 15-16 Digitos (64 bit)
Decimal: 28-29 Digitos (128 bit)
Decimais (decimal) tem muito mais precisão do que qualquer um dos outros, utilizado quase na totalidade das aplicações financeiras que requerem um grande grau de precisão. Em contra partida os Decimais (decimal) são muito mais lentos (chegando a 20x) do que double/float.


text:
Q: How to pass key value in one params in Spring REST I want to pass key value pair in Spring REST params using this command:
curl http://localhost:11004/room/page?pageNum=1\&pageSize=1\&params={"key":"value"} -H "token:1"|jq '.'

but the server side received params parameter by string like this:
params="key:value"

How to make the server side get key value pair?This is the server side model code:
public class PageQuery<T> {
    private Integer pageNum;
    private Integer pageSize;

    private T params;
}

This is the server side function:
public Response<PageBean<Room>> queryRoomByPage(PageQuery<Map<String,String>> request);

How should I tweak my request or server side code to make it possible?

A: Here pageNum=1\&pageSize=1\&params={"key":"value"} every part splits by & then it leads to your params="key:value" because here Map<String,String> you said to Spring that there is should be string at key and value
Example to change method input:
@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, @RequestParam("params") Map<String, String>

Do not use such a complicated HTTP query parameter as json, please use http body for this and await specific input JSON for which you have a specific description represented by java class
Better: do not use String, if your input can be represented as a specific business object, especially at Map. Neither HTTP client nor other engineers won't understand it, at least they "just know"


text:
Q: Running Task scheduler Laravel I am currently on a project which requires me to send emails to registered users, and i implemented the queuing method, it works fine when i am on my localhost running artisan commands. And i tried to step it up to use a development server Heroku, but i find it pretty hard to do. Went to the laravel docs and added the cron entry then scheduled my artisan command, but it does not still process.
//code
* * * * * php /path/to/artisan schedule:run 1>> /dev/null 2>&1

My questions are
1. Is the path/to actually suppose to be the path to my project i.e project folder name??
2. If not is there an alternative way to run this.
Thanks to you all

A: Yes, path to artisan is the full path to your project directory. This has the artisan executable in it.
I am not aware of another way to run the scheduler. Cron is a reliable way to do these types of things.


text:
Q: express js sendfile and download in react client I have express js as backend and react js as front end , in some route I have to send a file in response to requests I've done it like this :
return res.status(200).sendFile(path.resolve(`files/${product.fileName}`))

and the thing I have propblem with is that how should i handle this response in reactjs client ?
I loged the response and the body is :
body : ReadableStream
       locked : true

A: Can you use the send utility of express like this?
 var fs = require('fs-extra'); // import fs-extra package
 var buffer = fs.readFileSync(req.query.filepath);
 var bufferBase64 = new Buffer(buffer);
 res.status(200).send(bufferBase64);

In the React client, you can use react-file-download package.
import fileDownload from 'react-file-download';
fileDownload(response.data, "profilepic.jpg"); //This will download the file in browser.


text:
Q: Call to undefined function Zend\Mail\Header\iconv_mime_decode() Currently I'm developing an application with Zend Expressive.
I'm using zend-mail to send a register email.
However, here's the code:
<?php

namespace App\Mail\Service;

use Zend\Mail\Transport\Smtp;
use Zend\Mail\Transport\SmtpOptions;
use Zend\Mail\Message;

class MailService
{
    private $transport;
    private $options;

public function __construct() {
    $this->transport = new Smtp();
    $this->options =  new SmtpOptions([
        'name' => 'XXXXXX',
        'host' => 'XXXXXX',
        'port' => 587,
        'connection_class'  => 'plain',
        'connection_config' => [
            'username'  => 'XXXXXX',
            'password'  => 'XXXXXX',
            'ssl'       => 'tls'
        ],
    ]);
    $this->transport->setOptions($this->options);
}

public function sendRegisterMail($email)
{
    $message = new Message();
    $message->addFrom('XXXXXX', 'XXXXXX');
    $message->addTo($email);
    $message->setEncoding("UTF-8");
    $message->getHeaders()->addHeaderLine('Content-Type', 'text/plain; charset=UTF-8');
    $message->setSubject('Subject');
    $message->setBody('This is the Message Body');

    $this->transport->send($message);

}
}

?>

I got the above error message. ICONV is installed and working.
Here's the code for the call of this function:
public static function mimeDecodeValue($value)
{
    $decodedValue = iconv_mime_decode($value, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
    return $decodedValue;
}

Regards,
Unreality

A: enable extension=iconv.so in your php.ini file.


text:
Q: Combining multiple raster layers to make landcover map for Borneo I am currently making a landcover change map for a Kinabatangan, Sabah, Borneo for my undergrad dissertation. I downloaded landsat MSS and 8 images. These were pre-processed and both classified using unsupervised isodata classifications. Due to the restricted resolution I had to then use Google Earth Pro to delineate and map palm oil concessions (large palm oil sites) and smallholders (small farmers). I made polygons for each type and converted these to KML for GIS. These polygons were then changed to raster format so everything was the same. Both rasters were combined to make one palm oil layer. I standardised all the data e.g. all had the same projected coordinate system and cell size.
How do I combine my palm oil raster data with my 2014 landcover map (this was the only year the palm oil was seen)?
I essentially want three maps

*

*1973 Base landcover map, with these classes: Water; Forest and Non-forest

*2014 landcover map with combined palm oil data, with these classes: Water; Forest; Non-forest; Smallholders; Large Concessions

*1973 - 2014 Landcover change map, with these classes: Water; Forest; Non-forest; Smallholders; Large Concessions.
I have tried to use the raster calculator and also merge to new raster tools.
I have attached some pictures of what I am working on [1: Overview of map; 2: Overview of classes].

A: You can try to use the set of following commands which I found useful - using gdal library:
Creating list of rasters that are in folder:
dir /s/b/a *.tif > list.txt

Creating an image mosaic:
gdal_merge --optfile list.txt -o output_raster.tif

Compression of raster:
gdal_translate -co "COMPRESS=LZW" input_raster.tif output_raster.tif

Compression of rasters in a batch:
for %i in (*.tif) do gdal_translate -co "COMPRESS=LZW" %i compress_%i


text:
Q: Best way to aggregate with mongodb in variable json structure I have a number of reports that are built in the following json structure
Date/Country/Vendor where the Date/Country/Vendor are variables and the actual data is stored at the leaves of this json tree.
For example a simplified json would look at follows
 {
   "1/2/2001" :
   {
     "DE": {
            "Vendor A" : {
                          leaf data...
                          revenue:123213
                          }
            "Vendor B" : {
                          leaf data...
                          revenue:123213
                          }
            }
   }

Now, lets say I want to aggregate the revenue. Is there way fast way to do this with the Mongo's aggregation framework or am I tied to doing three nested for loops.
Thanks in advance,

A: If you could structure your JSON to this :
{
    "date": "1/2/2001",
    "country": "DE",
    "vendors": [
        {
            "vendor": "Vendor A",
            "leafdata": "xxx",
            "revenue": 123213
        },
        {
            "vendor": "Vendor b",
            "leafdata": "xxx",
            "revenue": 123213
        }
    ]
}

Then its easy with aggregation framework, you can have a query like following :
[{
    $unwind: '$vendors'
},
{
    $group: {
        _id: '$country',
        revenue: {
            $sum: '$vendors.revenue'
        }
    }
}]

This would give revenue for all countries that you have in your collection.
Note: I used date as string only, but i would recommend to use ISODate.

A: It looks like this feature in the agg framework is planned. See https://jira.mongodb.org/browse/SERVER-5947
You still have the ability to use map reduce.


text:
Q: ChainedSwapMove expects extra planning variable to be chained (when it comes from a CountableValueRange) I am using Optaplanner 7.38.0.Final
I have implemented a relatively simple model and I ran into some issues.
I have a planning entity called 'Visit' with a planning variable previousStandstill that follows pretty much the same pattern of the vehicle routing example, the anchor variable is 'Motorcycle' class so basically the optimization problem is to find the chain of visits for a given Motorcycle-Employee (fixed when solution is created the first time) that minimizes the time of all the routes for all the employees and serve all the visits.
The issue is that I want to break the chain from time to time to go back to the depot, I though that was unnecessary to create another class to make this breaks and I include a planning variable with a epoch second timestamp when the route restart is needed (the timestamps are between a relatively small range, startOfTrip on the code below).
Optaplanner is able to create the solver with the given xml configuration and if I create a break point on the score calculator I can inspect the vars and see that the construction heuristic is able to create a valid Visit chain and even set values of the timestamp variable.
But somehow after a few milliseconds the solver hits a NullPointerException when the org.optaplanner.core.impl.heuristic.selector.move.generic.chained.ChainedSwapMove constructor is called on the line 43 ( on the original source code of the given version above)
    public ChainedSwapMove(List<GenuineVariableDescriptor<Solution_>> variableDescriptorList,
            List<SingletonInverseVariableSupply> inverseVariableSupplyList, Object leftEntity, Object rightEntity) {
        super(variableDescriptorList, leftEntity, rightEntity);
        oldLeftTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size());
        oldRightTrailingEntityList = new ArrayList<>(inverseVariableSupplyList.size());
        for (SingletonInverseVariableSupply inverseVariableSupply : inverseVariableSupplyList) {
            oldLeftTrailingEntityList.add(inverseVariableSupply.getInverseSingleton(leftEntity));
            oldRightTrailingEntityList.add(inverseVariableSupply.getInverseSingleton(rightEntity));
        }
    }

it seems that the variable inverseVariableSupplyList contains a null reference ( it creates this null reference when it analyze the variableDescriptorList containing the regular non chained PlanningVariable )
package X;

import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.AnchorShadowVariable;
import org.optaplanner.core.api.domain.variable.InverseRelationShadowVariable;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
import org.optaplanner.core.api.domain.variable.PlanningVariableGraphType;

import javax.persistence.Transient;
import java.io.Serializable;
import java.time.LocalDateTime;

@PlanningEntity
public class OptimizingVisit implements OptimizingStandstill , Serializable {
    private static final long serialVersionUID = 9163651541108883957L;
    private ContinuousBranchTripSolution solution;
    private Order order;

    private Long startOfTrip;
    private Long start;
    private Long arrivalTime;
    private Long end;
    private Long travelDuration;
    private Long travelDistance;

    private OptimizingStandstill previousStandstill;

    private OptimizingVisit nextStandstill; //shadow variable
    private OptimizingDriver optimizingDriver;

    public OptimizingVisit() {
    }

    public OptimizingVisit(Order order, ContinuousBranchTripSolution solution) {
        this.order = order;
        this.solution = solution;
    }

    public Order getOrder() {
        return order;
    }

    public void setOrder(Order order) {
        this.order = order;
    }

    @AnchorShadowVariable(sourceVariableName = "previousStandstill")
    public OptimizingDriver getOptimizingDriver() {
        return optimizingDriver;
    }

    public void setOptimizingDriver(OptimizingDriver optimizingDriver) {
        this.optimizingDriver = optimizingDriver;
    }

    public Employee getDriver(){
        return this.getOptimizingDriver().getDriver();
    }

    @PlanningVariable( valueRangeProviderRefs = "startTimeCandidates" )
    public Long getStartOfTrip() {
        return startOfTrip;
    }

    public void setStartOfTrip(Long startOfTrip) {
        this.startOfTrip = startOfTrip;
    }

    public Long getTravelDuration() {
        return travelDuration;
    }

    public void setTravelDuration(Long travelDuration) {
        this.travelDuration = travelDuration;
    }

    public Long getTravelDistance() {
        return travelDistance;
    }

    public void setTravelDistance(Long travelDistance) {
        this.travelDistance = travelDistance;
    }

    @PlanningVariable( graphType = PlanningVariableGraphType.CHAINED , valueRangeProviderRefs = { "visitsRange" , "driversRange" } )
    public OptimizingStandstill getPreviousStandstill() {
        return previousStandstill;
    }

    public void setPreviousStandstill(OptimizingStandstill previousStandstill) {
        this.previousStandstill = previousStandstill;
    }

    @Override
    public OptimizingVisit getNextStandstill() {
        return nextStandstill;
    }

    @Override
    public void setNextStandstill(OptimizingVisit nextStandstill) {
        this.nextStandstill = nextStandstill;
    }

    @Override
    public Hexagon getHexagon() {
        return this.getOrder().getShippingAddress().getHexagon();
    }

    public TimeRange getTimeRange() {
        return new TimeRange( this.start , this.end );
    }

    /*Helper Methods*/
    public long getRecursiveStart(){
        if( this.getStartOfTrip() != null ) return this.getStartOfTrip() + 5*60;
        if( this.start != null ) return this.start;
        this.start = this.getPreviousStandstill().getRecursiveEnd();
        return this.start;
    }

    public long getRecursiveArrivalTime(){
        if( this.arrivalTime != null ) return this.arrivalTime;
        this.arrivalTime = this.getRecursiveStart() + solution.getDistanceBetweenHexagons( this.getPreviousStandstill().getHexagon() , this.getHexagon() ).getDuration();
        return this.arrivalTime;
    }

    @Override
    public long getRecursiveEnd(){
        if( this.end != null ) return this.end;
        this.end = this.getRecursiveArrivalTime() + TripsOptimizer.standByDuration;
        return this.end;
    }

    public boolean isEndOfTrip(){
        return this.getNextStandstill() == null || ( ( OptimizingVisit ) this.getNextStandstill()).getStartOfTrip() != null;
    }

    public long endOfTrip(){
        return this.getRecursiveEnd() + TripsOptimizer.standByDuration + solution.getDistanceBetweenHexagons( this.getHexagon() , this.getOptimizingDriver().getHexagon() ).getDuration();
    }

    @Override
    public void cleanTimes() {
        this.start = null;
        this.arrivalTime = null;
        this.end = null;
    }

    public long overlapWith( OptimizingVisit optimizingVisit ){
        if( this.getRecursiveStart() > optimizingVisit.getRecursiveEnd() ) return 0;
        if( this.getRecursiveEnd() < optimizingVisit.getRecursiveStart() ) return 0;

        OptimizingVisit firstEvent;
        OptimizingVisit lastEvent;
        if( this.getRecursiveStart() < optimizingVisit.getRecursiveStart() ){
            firstEvent = this;
            lastEvent = optimizingVisit;
        }else{
            firstEvent = optimizingVisit;
            lastEvent = this;
        }

        if( lastEvent.getRecursiveEnd() < firstEvent.getRecursiveEnd() ) return lastEvent.getRecursiveEnd() - lastEvent.getRecursiveStart();

        return  firstEvent.getRecursiveEnd() - lastEvent.getRecursiveStart();
    }

    public long getTimePenalization(){
        if( this.order == null ) return 0;

        long estimatedArrivalTime = this.getRecursiveArrivalTime();

        TimeRange orderTimeRange = this.getOrder().getTimeRange();

        if( estimatedArrivalTime > orderTimeRange.getEnd() ){
            double secondsOfDifference = estimatedArrivalTime - orderTimeRange.getEnd();

            return (long) Math.pow( secondsOfDifference , this.getOrder().isExpress() ? 2 : 1.5 );
        }

        if( estimatedArrivalTime > orderTimeRange.getStart() ) return 0;

        return (long) Math.pow( orderTimeRange.getStart() - estimatedArrivalTime , 2 );
    }

    @Transient
    public double getCarryOnCash() {
        if( this.order == null ) return 0;
        double r = 0;
        if( this.order.isOnAdvanceMode() ){
            for ( TransactionMatrix tm : this.order.getTransactionMatrix() ) {
                if( !PaymentMethodType.CASH.equals( tm.getPaymentMethodType() ) ) continue;
                r += tm.getAdvance();
            }
        }else{
            for ( TransactionMatrix tm : this.order.getTransactionMatrix() ) {
                if( !PaymentMethodType.CASH.equals( tm.getPaymentMethodType() ) ) continue;
                r += tm.getAmount();
            }
        }

        return r;
    }

    public long getEarlyOrLateSeconds(){
        TimeRange orderTimeRange = this.getOrder().getTimeRange();
        long arrivalTime = this.getRecursiveArrivalTime();
        long r = 0;
        if( arrivalTime < orderTimeRange.getStart() ) r += orderTimeRange.getStart() - arrivalTime;
        if( arrivalTime > orderTimeRange.getEnd() ) r += arrivalTime - orderTimeRange.getEnd();
        return r;
    }

    public long getContinuousOptimizationScore( ContinuousBranchTripSolution solution ) {
        return 0;
        /*if( !( this.getPreviousStandstill() instanceof OptimizingTrip ) ){
            return this.getTimePenalization();
        }
        double r = 0;
        OptimizingTrip trip = (OptimizingTrip) this.getPreviousStandstill();

        for ( DriverShift shift : solution.getDriverShifts() ){
            if( this.getOptimizingDriver().getDriver().computedIdHashCode() != shift.getDriver().computedIdHashCode() ) continue;
            long seconds = Math.max( 0 , trip.getEnd() - shift.getAvailableUntilAsEpochSeconds() );
            r += Math.pow( seconds * 2 , 2 );
        }

        r += 0.25d * Math.max( this.getCarryOnCash() - this.getOptimizingDriver().getDriver().getTrustLevel() , 0 );

        if ( trip.getStart() > solution.getStart() ) {
            r -= 0.5d * ( trip.getEnd() - solution.getStart() );
        }

        r += this.getTimePenalization();

        return (long) r;*/
    }

    @Override
    public String toString() {
        return String.format("OptimizingVisit{  %s  ,  %s  ,  %s  ,  %s , %s min early , %s min late  }",
                this.order.getNumber(),
                this.getOrder().getLowerBoundDelivery(),
                this.getPreviousStandstill() == null ? "" : LocalDateTime.ofEpochSecond( this.getRecursiveArrivalTime() , 0 , BitemporalModel.ZONE_OFFSET ),
                this.getOrder().getUpperBoundDelivery(),
                this.getPreviousStandstill() == null ? "" : Math.max( 0 , ( this.getOrder().getTimeRange().getStart() - this.getRecursiveArrivalTime() ) ) / 60,
                this.getPreviousStandstill() == null ? "" : Math.max( 0 , ( this.getRecursiveArrivalTime() - this.getOrder().getTimeRange().getEnd() ) ) / 60
        );
    }
}

A: We have recently fixed PLANNER-1961, the symptops of which bear remarkable similarity to your issue here. Please check out OptaPlanner 7.39.0.Final (when it's out) or later, chances are your problem will go away.


text:
Q: matplotlib pyplot UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure I have some problems related to plt.show() and I would describe the problem and what I tried.
#Problem
I am using python and plt.show() and those worked well until 4 hours before.
However, when I do plot something, suddenly
directory/plots/distance.py:119: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
  plt.show()

showed at the bottom of terminal.
#Trial 1
I searched google and add import matplotlib, matplotlib.use('TkAgg'), import matplotlib.pyplot as plt for obspy-plot Data.seed.
This worked for my coworker who shared server and had the same problem with me.
But it did not work for me but showed site-packages/matplotlib/pyplot.py", line 275, in switch_backend raise ImportError( ImportError: Cannot load backend 'TkAgg' which requires the 'tk' interactive framework, as 'headless' is currently running.
So I changed 'TkAgg' to 'Agg' but there was no error but also no plots.
#Trial2
I try to conda install -c conda-forge python3-tk and conda install -c anaconda tk (I cannot use pip or sudo).
But nothing changed related to the 'TkAgg' error.
#Trial3
I add import tkinter before 'TkAgg'part but nothing changed.
#So..
I think the matplotlib in my anaconda has something wrong but have no idea how to fix it.
(I still cannot understand why this problem occurs suddenly..)
Could you please let me know how to solve this problem?