问:
/usr/bin/ld: undefined reference to static library
I got the following cmake file:

```<code>cmake_minimum_required(VERSION 3.17)
project(blsbench2)

set(CMAKE_CXX_STANDARD 14)
set(SOURCE_FILES main.cpp)

INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/object_blstmp)

INCLUDE_DIRECTORIES(/usr/local/include/relic/)
LINK_DIRECTORIES(/usr/local/lib/)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 bls relic)
</code>```

And the following program

```<code>#include <iostream>
#include <bls.hpp>

using namespace bls;
using namespace std;

int main()
{
    std::cout << "Hello, World!" << std::endl;

    uint8_t seed[] = {0, 50, 6, 244, 24, 199, 1, 25, 52, 88, 192,
                      19, 18, 12, 89, 6, 220, 18, 102, 58, 209,
                      82, 12, 62, 89, 110, 182, 9, 44, 20, 254, 22};

    PrivateKey sk = PrivateKey::FromSeed(seed, sizeof(seed));
    PublicKey pk = sk.GetPublicKey();

    uint8_t msg[] = {100, 2, 254, 88, 90, 45, 23};

    Signature sig = sk.Sign(msg, sizeof(msg));

    return 0;
}
</code>```

I'm working with CLion and the setup above allows me to include the library and use function auto completion.

The problem arises when I try to start running the program.

```<code>/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `main':
/home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::FromSeed(unsigned char const*, unsigned long)'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:17: undefined reference to `bls::PrivateKey::GetPublicKey() const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:21: undefined reference to `bls::PrivateKey::Sign(unsigned char const*, unsigned long) const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `bls::Signature::~Signature()':
/home/ray/CLionProjects/blsbench2/../../Documents/projects/bls-signatures/src/signature.hpp:101: undefined reference to `bls::AggregationInfo::~AggregationInfo()'
collect2: error: ld returned 1 exit status
</code>```

I searched a bit on the internet and it said at a few places that this is due to the lack of .so files (might be mistaken here). However, the library builds a .a file which should be enough.

答:
This is due to how bls library is built.
bls::PrivateKey class is implemented in a file that is part of a blstmp static library.

You can link directly to the blstmp library instead of bls. This works : your program runs fine. But it's a bit hacky.

This is due to an issue with CMake : when you build a library A that depends on a static library B, the objects files of library B are not copied into library A. So your program that links to A should also link to B. There is a discussion about that on CMake's mailing list.

But this is an issue with bls library, it could be useful to report it to maintainer.

Body:
I got the following cmake file:

cmake_minimum_required(VERSION 3.17)
project(blsbench2)

set(CMAKE_CXX_STANDARD 14)
set(SOURCE_FILES main.cpp)

INCLUDE_DIRECTORIES(../../Documents/projects/bls-signatures/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/src)
LINK_DIRECTORIES(../../Documents/projects/bls-signatures/build/object_blstmp)

INCLUDE_DIRECTORIES(/usr/local/include/relic/)
LINK_DIRECTORIES(/usr/local/lib/)

add_executable(blsbench2 ${SOURCE_FILES})

TARGET_LINK_LIBRARIES(blsbench2 bls relic)

And the following program

#include <iostream>
#include <bls.hpp>

using namespace bls;
using namespace std;

int main()
{
    std::cout << "Hello, World!" << std::endl;

    uint8_t seed[] = {0, 50, 6, 244, 24, 199, 1, 25, 52, 88, 192,
                      19, 18, 12, 89, 6, 220, 18, 102, 58, 209,
                      82, 12, 62, 89, 110, 182, 9, 44, 20, 254, 22};

    PrivateKey sk = PrivateKey::FromSeed(seed, sizeof(seed));
    PublicKey pk = sk.GetPublicKey();

    uint8_t msg[] = {100, 2, 254, 88, 90, 45, 23};

    Signature sig = sk.Sign(msg, sizeof(msg));

    return 0;
}

I'm working with CLion and the setup above allows me to include the library and use function auto completion.

The problem arises when I try to start running the program.

/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `main':
/home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::FromSeed(unsigned char const*, unsigned long)'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:17: undefined reference to `bls::PrivateKey::GetPublicKey() const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:21: undefined reference to `bls::PrivateKey::Sign(unsigned char const*, unsigned long) const'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: /home/ray/CLionProjects/blsbench2/main.cpp:16: undefined reference to `bls::PrivateKey::~PrivateKey()'
/usr/bin/ld: CMakeFiles/blsbench2.dir/main.cpp.o: in function `bls::Signature::~Signature()':
/home/ray/CLionProjects/blsbench2/../../Documents/projects/bls-signatures/src/signature.hpp:101: undefined reference to `bls::AggregationInfo::~AggregationInfo()'
collect2: error: ld returned 1 exit status

I searched a bit on the internet and it said at a few places that this is due to the lack of .so files (might be mistaken here). However, the library builds a .a file which should be enough.


来源: stackexchange

问:
Cannot create a project using appcelerator through CLI or Appcelerator Studio
When I try to create a project either through the appc new command, or through the Appcelerator Studio I get an error. I have tried to uninstall and reinstall Appcelerator Studio a couple of times, but the errors do not change. The appc output is below, the error from the studio is the same:</p>

```<code>[INFO]  Creating app project
[INFO]  Template directory: /Users/<user>/Library/Application Support/Titanium/mobilesdk/osx/8.1.0.GA/templates/app/default
[INFO]  Writing tiapp.xml
[INFO]  Project created successfully in 163ms
An uncaught exception was thrown!
Unexpected end of JSON input
Unexpected end of JSON input
</code>```

答:
Please make sure you have the latest Appcelerator CLI installed using
npm i -g appcelerator

Alternatively, you can build via the Titanium Open Source CLI. You can install it with npm i -g titanium and run the app via ti build p ios|android.

ContentLicense: CC BY-SA 4.0

Body:
When I try to create a project either through the appc new command, or through the Appcelerator Studio I get an error. I have tried to uninstall and reinstall Appcelerator Studio a couple of times, but the errors do not change. The appc output is below, the error from the studio is the same:

[INFO]  Creating app project
[INFO]  Template directory: /Users/<user>/Library/Application Support/Titanium/mobilesdk/osx/8.1.0.GA/templates/app/default
[INFO]  Writing tiapp.xml
[INFO]  Project created successfully in 163ms
An uncaught exception was thrown!
Unexpected end of JSON input
Unexpected end of JSON input


问:
Still seem to have a gimbal-lock using quaternions
I maintain the position of an object using a reference quaternion ...

I rotate a reference quaternion from 2D x-y touch swipes using the following code ...

```<code>-(void)rotateViewOnX:(CGFloat)x andOnY:(CGFloat)y
{
    // x and y should be a simple Cartesian pixel movements ...
    // the screen swipe moved m pixels in the x direction and n pixels in the y direction ...

    // ignore micro movements ...
    if(abs(x) < 0.1 && abs(y) < 0.1)
        return;

    // ignore excessive movements ...
    if(abs(x) > VIEW_PORTAL_SIZE/3.0 || abs(y) > VIEW_PORTAL_SIZE/3.0)
        return;

    // simulate a very, very large trackball ...
    double radius = VIEW_PORTAL_SIZE/2.0;
    x = x/radius;
    y = y/radius;
    double z = sqrt(1 - x*x - y*y);
    Vector *trackball = [[Vector alloc] initWithX:x andY:y andZ:z];

    // use dot product to get the angle of rotation on the trackball
    double theta = acos([self.zReferenceVector dotProduct:trackball]);

    // use cross product to get the axis of rotation - convert to a unit vector
    // this is an autoreleased object ...
    Vector *rotationAxis = [[self.zReferenceVector crossProduct:trackball] normalise];

    // create a quaternion to represent the latest movement from the simulated trackball ...
    Quaternion *change = [[Quaternion alloc] initWithAngle:theta aroundVector:rotationAxis];
    [change unitise];

    // rotate the reference quaternion by this quaternion ...
    self.zReferenceQuaternion = [[change times:self.zReferenceQuaternion] times:[change inverse]];
    [self.zReferenceQuaternion unitise];

    // clean-up ...
    [trackball release]; trackball = nil;
    [change release]; change = nil;

    // and paint ...
    [self setNeedsDisplay];
}
</code>```

To rotate the object I apply the following code to each Vector point in the object ...

```<code>// align the cube to the rotated reference quaternion ...
v = [self.zReferenceQuaternion rotateVector:v];
</code>```

Which uses the following method ...

```<code>-(Vector*)rotateVector:(Vector*)v
{
    Quaternion *myInverse = [self inverse];
    Quaternion *pureQuat = [[Quaternion alloc] initWithValues:0.0 :v.x :v.y :v.z];
    Quaternion *step1 = [self times: pureQuat];
    Quaternion *step2 = [step1 times: myInverse];
    [pureQuat release];
    return [[[Vector alloc] initWithX:step2.x andY:step2.y andZ:step2.z] autorelease];
}
</code>```

My problem is that when the object is at around 180 degrees if I rotated it there in an x-direction I cannot move it in the y-direction. Conversely, if I rotated it there in the y-direction, at around 180 degrees rotated I cannot move it in the x-direction. Not sure what I am doing wrong!

Post script ...

In answer to the commentator, the entire Quaternion class, as it currently stands follows:

```<code>#import "Quaternion.h"

@implementation Quaternion

@synthesize w=_w;
@synthesize x=_x;
@synthesize y=_y;
@synthesize z=_z;

// ----- initialisers

// this is the designated initaliser for w, x, y, z ...
-(id) initWithValues:(double)a :(double)b :(double)c :(double)d
{
    self = [super init];
    if(self)
    {
        _w = a; //1
        _x = b; //i
        _y = c; //j
        _z = d; //k
    }
    return self;
}

-(id) initWithAngle:(double)angle aroundVector:(Vector*)vector
{
    // some preliminaries ...
    double halfAngle = angle / 2.0;
    double sinAngleOnTwo = sin(halfAngle); // do once
    Vector *v = [vector normalise];

    // calculate the quaternion ...
    double w = cos(halfAngle);
    double x = v.x * sinAngleOnTwo;
    double y = v.y * sinAngleOnTwo;
    double z = v.z * sinAngleOnTwo;

    // return result ...
    return [self initWithValues:w :x :y :z];
}

-(Quaternion*)copy
{
    Quaternion *a = self;
    return [[Quaternion alloc] initWithValues:a.w :a.x :a.y :a.z];
}

// ----- algebra

-(Quaternion*)conjugate
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w :-a.x :-a.y :-a.z ] autorelease];
}

-(Quaternion*)plus:(Quaternion*)b
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w+b.w :a.x+b.x :a.y+b.y :a.z+b.z] autorelease];
}

-(Quaternion*)minus:(Quaternion*)b
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w-b.w :a.x-b.x :a.y-b.y :a.z-b.z] autorelease];
}

-(Quaternion*)times:(Quaternion*) b
{
    Quaternion *a = self;
    double real = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z;
    double i = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y;
    double j = a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x;
    double k = a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w;
    return [[[Quaternion alloc] initWithValues:real :i :j :k] autorelease];
}

-(double)norm
{
    Quaternion *a = self;
    return a.w*a.w + a.x*a.x + a.y*a.y + a.z*a.z;
}

-(Quaternion*)inverse
{
    Quaternion *a = self;
    double n = [a norm];
    return [[[Quaternion alloc] initWithValues:a.w/n :-a.x/n :-a.y/n :-a.z/n] autorelease];
}

-(Quaternion*)divides:(Quaternion*) b
{
    Quaternion *a = self;
    return [[a inverse] times: b];
}

-(double)magnitude
{
    Quaternion *a = self;
    return sqrt([a norm]);
}

-(void)unitise
{
    double m = [self magnitude];
    self.w /= m;
    self.x /= m;
    self.y /= m;
    self.z /= m;
}

-(Quaternion*)unitQuaternion
{
    Quaternion *u = [[self copy] autorelease];
    [u unitise];
    return u;
}

-(Vector*)rotateVector:(Vector*)v
{
    Quaternion *vAsPureQuat = [[Quaternion alloc] initWithValues:0.0 :v.x :v.y :v.z];
    Quaternion *r = [[self times: vAsPureQuat] times:[self inverse]];
    [vAsPureQuat release];
    return [[[Vector alloc] initWithX:r.x andY:r.y andZ:r.z] autorelease];
}

// ----- misc

-(NSString*)toString
{
    Quaternion *a = self;
    return [NSString stringWithFormat:@"%f + %fi + %fj +%fk", a.w, a.x, a.y, a.z];
}

@end
</code>```

答:
I have discovered the error of my ways ...

It lay in the code that maintains the rotated reference quaternion ... I should not have been multiplying it by the inverse ... in the following code snippet, the buggy code from the above question has been commented out.

```<code>// rotate the zReferenceQuaternion quaternion by this change quaternion ...
//self.zReferenceQuaternion = [[change times:self.zReferenceQuaternion] times:[change inverse]];
self.zReferenceQuaternion = [change times:self.zReferenceQuaternion ];
[self.zReferenceQuaternion unitise];
</code>```

The movements are now accumulated in the self.zReferenceQuaternion iVar. No gimbal-lock like situation occurs on the screen moving the object around.

ContentLicense: CC BY-SA 3.0

Body:
I maintain the position of an object using a reference quaternion ...

I rotate a reference quaternion from 2D x-y touch swipes using the following code ...

-(void)rotateViewOnX:(CGFloat)x andOnY:(CGFloat)y
{
    // x and y should be a simple Cartesian pixel movements ...
    // the screen swipe moved m pixels in the x direction and n pixels in the y direction ...

    // ignore micro movements ...
    if(abs(x) < 0.1 && abs(y) < 0.1)
        return;

    // ignore excessive movements ...
    if(abs(x) > VIEW_PORTAL_SIZE/3.0 || abs(y) > VIEW_PORTAL_SIZE/3.0)
        return;

    // simulate a very, very large trackball ...
    double radius = VIEW_PORTAL_SIZE/2.0;
    x = x/radius;
    y = y/radius;
    double z = sqrt(1 - x*x - y*y);
    Vector *trackball = [[Vector alloc] initWithX:x andY:y andZ:z];

    // use dot product to get the angle of rotation on the trackball
    double theta = acos([self.zReferenceVector dotProduct:trackball]);

    // use cross product to get the axis of rotation - convert to a unit vector
    // this is an autoreleased object ...
    Vector *rotationAxis = [[self.zReferenceVector crossProduct:trackball] normalise];

    // create a quaternion to represent the latest movement from the simulated trackball ...
    Quaternion *change = [[Quaternion alloc] initWithAngle:theta aroundVector:rotationAxis];
    [change unitise];

    // rotate the reference quaternion by this quaternion ...
    self.zReferenceQuaternion = [[change times:self.zReferenceQuaternion] times:[change inverse]];
    [self.zReferenceQuaternion unitise];

    // clean-up ...
    [trackball release]; trackball = nil;
    [change release]; change = nil;

    // and paint ...
    [self setNeedsDisplay];
}

To rotate the object I apply the following code to each Vector point in the object ...

// align the cube to the rotated reference quaternion ...
v = [self.zReferenceQuaternion rotateVector:v];

Which uses the following method ...

-(Vector*)rotateVector:(Vector*)v
{
    Quaternion *myInverse = [self inverse];
    Quaternion *pureQuat = [[Quaternion alloc] initWithValues:0.0 :v.x :v.y :v.z];
    Quaternion *step1 = [self times: pureQuat];
    Quaternion *step2 = [step1 times: myInverse];
    [pureQuat release];
    return [[[Vector alloc] initWithX:step2.x andY:step2.y andZ:step2.z] autorelease];
}

My problem is that when the object is at around 180 degrees if I rotated it there in an x-direction I cannot move it in the y-direction. Conversely, if I rotated it there in the y-direction, at around 180 degrees rotated I cannot move it in the x-direction. Not sure what I am doing wrong!

Post script ...

In answer to the commentator, the entire Quaternion class, as it currently stands follows:

#import "Quaternion.h"

@implementation Quaternion

@synthesize w=_w;
@synthesize x=_x;
@synthesize y=_y;
@synthesize z=_z;

// ----- initialisers

// this is the designated initaliser for w, x, y, z ...
-(id) initWithValues:(double)a :(double)b :(double)c :(double)d
{
    self = [super init];
    if(self)
    {
        _w = a; //1
        _x = b; //i
        _y = c; //j
        _z = d; //k
    }
    return self;
}

-(id) initWithAngle:(double)angle aroundVector:(Vector*)vector
{
    // some preliminaries ...
    double halfAngle = angle / 2.0;
    double sinAngleOnTwo = sin(halfAngle); // do once
    Vector *v = [vector normalise];

    // calculate the quaternion ...
    double w = cos(halfAngle);
    double x = v.x * sinAngleOnTwo;
    double y = v.y * sinAngleOnTwo;
    double z = v.z * sinAngleOnTwo;

    // return result ...
    return [self initWithValues:w :x :y :z];
}

-(Quaternion*)copy
{
    Quaternion *a = self;
    return [[Quaternion alloc] initWithValues:a.w :a.x :a.y :a.z];
}

// ----- algebra

-(Quaternion*)conjugate
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w :-a.x :-a.y :-a.z ] autorelease];
}

-(Quaternion*)plus:(Quaternion*)b
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w+b.w :a.x+b.x :a.y+b.y :a.z+b.z] autorelease];
}

-(Quaternion*)minus:(Quaternion*)b
{
    Quaternion *a = self;
    return [[[Quaternion alloc] initWithValues:a.w-b.w :a.x-b.x :a.y-b.y :a.z-b.z] autorelease];
}

-(Quaternion*)times:(Quaternion*) b
{
    Quaternion *a = self;
    double real = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z;
    double i = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y;
    double j = a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x;
    double k = a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w;
    return [[[Quaternion alloc] initWithValues:real :i :j :k] autorelease];
}

-(double)norm
{
    Quaternion *a = self;
    return a.w*a.w + a.x*a.x + a.y*a.y + a.z*a.z;
}

-(Quaternion*)inverse
{
    Quaternion *a = self;
    double n = [a norm];
    return [[[Quaternion alloc] initWithValues:a.w/n :-a.x/n :-a.y/n :-a.z/n] autorelease];
}

-(Quaternion*)divides:(Quaternion*) b
{
    Quaternion *a = self;
    return [[a inverse] times: b];
}

-(double)magnitude
{
    Quaternion *a = self;
    return sqrt([a norm]);
}

-(void)unitise
{
    double m = [self magnitude];
    self.w /= m;
    self.x /= m;
    self.y /= m;
    self.z /= m;
}

-(Quaternion*)unitQuaternion
{
    Quaternion *u = [[self copy] autorelease];
    [u unitise];
    return u;
}

-(Vector*)rotateVector:(Vector*)v
{
    Quaternion *vAsPureQuat = [[Quaternion alloc] initWithValues:0.0 :v.x :v.y :v.z];
    Quaternion *r = [[self times: vAsPureQuat] times:[self inverse]];
    [vAsPureQuat release];
    return [[[Vector alloc] initWithX:r.x andY:r.y andZ:r.z] autorelease];
}

// ----- misc

-(NSString*)toString
{
    Quaternion *a = self;
    return [NSString stringWithFormat:@"%f + %fi + %fj +%fk", a.w, a.x, a.y, a.z];
}

@end

Body:
I have discovered the error of my ways ...

It lay in the code that maintains the rotated reference quaternion ... I should not have been multiplying it by the inverse ... in the following code snippet, the buggy code from the above question has been commented out.

// rotate the zReferenceQuaternion quaternion by this change quaternion ...
//self.zReferenceQuaternion = [[change times:self.zReferenceQuaternion] times:[change inverse]];
self.zReferenceQuaternion = [change times:self.zReferenceQuaternion ];
[self.zReferenceQuaternion unitise];

The movements are now accumulated in the self.zReferenceQuaternion iVar. No gimbal-lock like situation occurs on the screen moving the object around.


问:
Customizing Angular8 date picker arrow (top and bottom arrow)
I like to customize the Angular 8 date picker with top and bottom arrows. The default one is left and right arrow. How do I customize it.

Angular 8 date picker

答:
lets say selector of that button is .myButton. Use host selector to override the default style if you want for a specific component like

```<code>:host>>>.myButton {
   background-color: white;
}
</code>```

or specify this in your global styles.css

```<code>.myButton {
      background-color: white !important;
}
</code>```

Body:
lets say selector of that button is .myButton. Use host selector to override the default style if you want for a specific component like

:host>>>.myButton {
   background-color: white;
}

or specify this in your global styles.css

.myButton {
      background-color: white !important;
}


问:
How do I make my java application open a console/terminal window?
Is there any way I can make an executable .jar that will open up the command line when double clicked?

I'm making a text-based adventure game. As of right now it is just a maze with rooms. Eventually it is going to be much bigger and more in depth but for now I just want to get the basic structure down. Anyways, to make this work I've been getting output and input from the System.out.printf command and the java.util.Scanner. It's all working beautifully so far but I've realized I'm going to run into a problem when I try to send this to other people that don't know how or just don't want to run the program from the command line.

答:
I wrote a little snippet which uses a similar approach to Brandon Barajas' solution.
It supports Mac (untested), Linux (tested with xfce) and Windows (cmd) in one go (although you might need to customize the linux terminal commands, since there are many different ones).

https://github.com/Lartsch/java-selfconsole/

Really helpful in the following case:

you don't want the jar to have to be directly executed in a console

you can't use any custom made console / can't use any GUI library

you don't want to ship bridge starting files like sh, bat, ...

you simply want the jar to open itself in a console on double-click


问:
MySQL Group from quarters to periods
I have a table like this:

```<code>Person smallint(5)  act_time datetime
1   2020-05-29 07:00:00
1   2020-05-29 07:15:00
1   2020-05-29 07:30:00
2   2020-05-29 07:15:00
2   2020-05-29 07:30:00
1   2020-05-29 10:30:00
1   2020-05-29 10:45:00
</code>```

The table above is an example with 2 different persons and there is a row for each quarter they are at work...

What is the best way in MySQL to "convert" this table to another table where there is a column for "person", a column for "start" and one for "stop".

So the result is like:

```<code>Person  Start   Stop
1   2020-05-29 07:00:00   2020-05-29 07:45:00
2   2020-05-29 07:15:00   2020-05-29 07:45:00
1   2020-05-29 10:30:00   2020-05-29 11:00:00
</code>```

I have tried with a left join to the same original table but it didn't work...

Thanks.

Thanks for your reply. I have now tried it with the table above - and it unfortunately doesn't give that result...
My sql string is:

```<code>select person,min(act_time) start_date,max(act_time) end_date from (select t.*,row_number() over(order by act_time) rn1,row_number() over(partition by person order by act_time) rn2 from test t) t group by person, rn1 - rn2 order by min(act_time)

But the result it generates is:
1 29-05-2020 07:00:00 29-05-2020 07:15:00
2 29-05-2020 07:15:00 29-05-2020 07:15:00
1 29-05-2020 07:30:00 29-05-2020 07:30:00
2 29-05-2020 07:30:00 29-05-2020 07:30:00
1 29-05-2020 10:30:00 29-05-2020 10:45:00
</code>```

It should be like the result with 3 rows. So when there is a gap in more than 15 minutes between to rows with the same person it should create a new row.

答:
This is a gaps and islands problem. You can solve it with window functions (available in MySQL 8.0 only):

```<code>select
    person,
    min(act_date) start_date,
    max(act_date) end_date
from (
    select
        t.*,
        sum(act_date <> lag_act_date + interval 15 minute)
            over(partition by person order by act_date) grp
    from (
        select
            t.*,
            lag(act_date)
                over(partition by person order by act_date) lag_act_date
        from mytable t
    ) t
) t
group by person, grp
order by min(act_date)
</code>```

The idea is to build groups of adjacent records using a cumulative sum: every time there is a gap that is not 15 minutes, the sum increments.

Title: MySQL Group from quarters to periods

Body:
I have a table like this:

Person smallint(5)  act_time datetime
1   2020-05-29 07:00:00
1   2020-05-29 07:15:00
1   2020-05-29 07:30:00
2   2020-05-29 07:15:00
2   2020-05-29 07:30:00
1   2020-05-29 10:30:00
1   2020-05-29 10:45:00

The table above is an example with 2 different persons and there is a row for each quarter they are at work...

What is the best way in MySQL to "convert" this table to another table where there is a column for "person", a column for "start" and one for "stop".

So the result is like:

Person  Start   Stop
1   2020-05-29 07:00:00   2020-05-29 07:45:00
2   2020-05-29 07:15:00   2020-05-29 07:45:00
1   2020-05-29 10:30:00   2020-05-29 11:00:00

I have tried with a left join to the same original table but it didn't work...

Thanks.

Thanks for your reply. I have now tried it with the table above - and it unfortunately doesn't give that result...
My sql string is:

select person,min(act_time) start_date,max(act_time) end_date from (select t.*,row_number() over(order by act_time) rn1,row_number() over(partition by person order by act_time) rn2 from test t) t group by person, rn1 - rn2 order by min(act_time)

But the result it generates is:
1 29-05-2020 07:00:00 29-05-2020 07:15:00
2 29-05-2020 07:15:00 29-05-2020 07:15:00
1 29-05-2020 07:30:00 29-05-2020 07:30:00
2 29-05-2020 07:30:00 29-05-2020 07:30:00
1 29-05-2020 10:30:00 29-05-2020 10:45:00

It should be like the result with 3 rows. So when there is a gap in more than 15 minutes between to rows with the same person it should create a new row.

Body:
This is a gaps and islands problem. You can solve it with window functions (available in MySQL 8.0 only):

select
    person,
    min(act_date) start_date,
    max(act_date) end_date
from (
    select
        t.*,
        sum(act_date <> lag_act_date + interval 15 minute)
            over(partition by person order by act_date) grp
    from (
        select
            t.*,
            lag(act_date)
                over(partition by person order by act_date) lag_act_date
        from mytable t
    ) t
) t
group by person, grp
order by min(act_date)

The idea is to build groups of adjacent records using a cumulative sum: every time there is a gap that is not 15 minutes, the sum increments.


问:
How do I compute the non-client window size in WPF?
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21
</code>```

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18
</code>```

How do I compute the actual observed values by using SystemParameters?

答:
This is a C++/CLI answer, and it is NOT using SystemParameters, but I think this is a better approach to this problem, since it should be correct for any window.

In fact, the other answers are only valid for a resizable window, and one must create different cases for each of the available WindowStyles.

Since for every SystemParameters needed for these calculations there is a documented SM_CX* or SM_CY* value, I thought that, instead of re-inventing the wheel, one could simply use the WinAPI AdjustWindowRectEx function.

```<code>bool SetWindowClientArea(System::Windows::Window^ win, int width, int height) {
    System::Windows::Interop::WindowInteropHelper^ wi = gcnew System::Windows::Interop::WindowInteropHelper(win);
    wi->EnsureHandle();
    HWND win_HWND = (HWND)(wi->Handle.ToPointer());

    LONG winStyle = GetWindowLong(win_HWND, GWL_STYLE);
    LONG winExStyle = GetWindowLong(win_HWND, GWL_EXSTYLE);
    RECT r = { 0 };
    r.right = width;
    r.bottom = height;
    BOOL bres = AdjustWindowRectEx(&r, winStyle, FALSE, winExStyle);
    if (bres) {
        Double w = r.right - r.left;
        Double h = r.bottom - r.top;
        win->Width = w;
        win->Height = h;
    }

    return bres;
}
</code>```

One can easily convert the above code to C# using some more DllImports, or this can be dropped into a C++/CLI assembly if your project is already using one.

Body:
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18

How do I compute the actual observed values by using SystemParameters?

Body:
This is a C++/CLI answer, and it is NOT using SystemParameters, but I think this is a better approach to this problem, since it should be correct for any window.

In fact, the other answers are only valid for a resizable window, and one must create different cases for each of the available WindowStyles.

Since for every SystemParameters needed for these calculations there is a documented SM_CX* or SM_CY* value, I thought that, instead of re-inventing the wheel, one could simply use the WinAPI AdjustWindowRectEx function.

bool SetWindowClientArea(System::Windows::Window^ win, int width, int height) {
    System::Windows::Interop::WindowInteropHelper^ wi = gcnew System::Windows::Interop::WindowInteropHelper(win);
    wi->EnsureHandle();
    HWND win_HWND = (HWND)(wi->Handle.ToPointer());

    LONG winStyle = GetWindowLong(win_HWND, GWL_STYLE);
    LONG winExStyle = GetWindowLong(win_HWND, GWL_EXSTYLE);
    RECT r = { 0 };
    r.right = width;
    r.bottom = height;
    BOOL bres = AdjustWindowRectEx(&r, winStyle, FALSE, winExStyle);
    if (bres) {
        Double w = r.right - r.left;
        Double h = r.bottom - r.top;
        win->Width = w;
        win->Height = h;
    }

    return bres;
}

One can easily convert the above code to C# using some more DllImports, or this can be dropped into a C++/CLI assembly if your project is already using one.


问:
The color of and <input type="color"> element on a page DOESN'T match its value attribute
I am working on a personnal exercise where I create a small app to allow users to update colors of different parts of an SVG using the <input type = "color"> element.

The SVG I am playing with is a simple cloud drawings with writing in it. You can modify 3 parts: cloud's stroke color, cloud's fill color and writing's color.

See it live:

live: https://argonathmos.github.io/SVGfun/

code: https://github.com/argonathmos/SVGfun

It is a simple UI with 3 areas:

A Random button that applies random colors to each parts of the
SVG.

Three <input type="color"> element for each part of the SVG to
modify each colors by hand.

A Download button that allows the
user to export the SVG with the custom colors applyied to it.

Here is what I notice that bothers me and don't know how to fix yet:

When I click "random", the SVG colors are updated, as well as the value of the <input type="color"> elements, as well as the color of the  element on the page (ie the little squares color matches the colors of the associated SVG section).

When I apply a color individually through the <input type="color"> element the color of the SVG is updated as well as the value of the <input type="color"> element, and so is the color of the input color element on the page (the little square).

But If I click "random" after having already selected a color from the color picker by hand:
The SVG colors are updated, the value attribute of the <input type="color"> elements as well, but the color of the  element on the page doesn't update its stays the same as the previously hand picked color. (ie the little square color DOESN'T match the color of the associated SVG section eventhough the value attribute of the  element does.)

答:
Change strokeColorInput.setAttribute, fillColorInput.setAttribute, pathColorInput.setAttribute to:

```<code>strokeColorInput.value = strokeColor;
fillColorInput.value = fillColor;
pathColorInput.value = uniquePathcolor;
</code>```

as you are updating HTML values. .setAttribute is for CSS attribute values.

Body:
Change strokeColorInput.setAttribute, fillColorInput.setAttribute, pathColorInput.setAttribute to:

strokeColorInput.value = strokeColor;
fillColorInput.value = fillColor;
pathColorInput.value = uniquePathcolor;

as you are updating HTML values. .setAttribute is for CSS attribute values.


问:
How to re-render every time state changes with API call limit?
Edit: People from FUTURE: check out this video -

https://www.youtube.com/watch?v=FyxFSkh2wug
and the article provided by Leonardo.

I have a searchbar component and a stockchart component that are both children of the Parent component. I want to re-render the stockchart every time a key is entered in the search bar. I am new to react so please bear with my code.

I tried a shouldComponentUpdate and it made too many API calls. In the CorrectRender function, I tried to return the StockChart everytime ticker changed but it didn't work.

I've tried my best to describe the methods I wrote, please feel free to ask any questions.

This is the Parent component, I'm calling this inside App.js

```<code>import React, { Component } from 'react'
import StockChart from './StockChart';
import SearchBar from './SearchBar';

// Renders stockChart when value is entered
// I tried to re-render by using a current and previousTicker symbols but it didn't work.

function CorrectRender(props, oldtick) {
    const ticker = props.props;
    console.log("props", props)
    const previousTicker = props.oldtick;
    if (ticker.length > 0 && previousTicker !== ticker) {
        return <div>
            <p>{ticker}</p>
            <StockChart stockSymbol = {ticker} previousTicker={previousTicker}/>
        </div>
    }
    return null;
    }

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockSymbol: '',
            previousTicker: ''
        }
        this.callbackFunction = this.callbackFunction.bind(this);
    }

    shaveData(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            stockSymbol: value,
        });
    }

    callbackFunction(sS)  {
        this.setState({ previousTicker: this.state.stockSymbol});
        this.shaveData(sS);
    };

    render() {
        return (
            <div>
                <SearchBar parentCallback = {this.callbackFunction}/>
                <CorrectRender props={this.state.stockSymbol} oldtick={this.state.previousTicker}/>
            </div>
        )
    }
}

export default Parent;
</code>```

This is the SEARCHBAR component.

```<code>import React, { Component } from 'react';
import './SearchBar.css';

export class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            search: ' ',
            tickerList: [],
        }
    }

    // Get a list of tickers from an API, this is not the api call that is being overused
    // I want the data to show to the user as "Ticker, Company name" which is what the second (.then) is doing
    fetchTickers(stockSymbol) {
        const pointer = this;
        let arr = [];
        console.log(stockSymbol);
        let url = `https://ticker-2e1ica8b9.now.sh/keyword/${stockSymbol}`;

        fetch(url)
            .then( function(response) {
                return response.json();
            })
            .then ( function(data) {
                for (var key in data) {
                    arr.push(data[key]['symbol'] + ", "+ data[key]['name'])
                };

                pointer.setState({
                    tickerList: arr
                })
            }

            )
    }

    // this is for handling keys in the search bar and rendering new results based on the
    critera
    textChange = (e) => {
        const value = e.target.value;
        let arr = [];
        if (value.length > 0) {
            const regex = new RegExp(`^${value}`, 'i');
            this.fetchTickers(value);
            arr = this.state.tickerList.sort().filter(tick => regex.test(tick));
        }
        this.setState({
            tickerList: arr,
            search: value
        });
    }

    // This will be called when an option is chosen by user
    tickerChosen(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            search: value,
            tickerList: []
        });

    };

    // list of suggestions on user side based on criteria
    tickerSuggestions () {
        const { tickerList } = this.state;
        if (tickerList.length === 0) {
            return null;
        }
        return (
            <ul>
                {tickerList.map((ticker) => <li key={ticker} onClick={() =>  {this.props.parentCallback(ticker); this.tickerChosen(ticker);} }>{ticker}</li>)}
            </ul>
        )
    };

    render() {
        const { search } = this.state;
        return (
            <div className= 'SearchBar'>
                <input value = { search } onChange={this.textChange} type='text' />
                {this.tickerSuggestions()}

            </div>
        )
    }
}

export default SearchBar
</code>```

This is the StockChart component.

```<code>import React, { Component } from 'react';
import Plot from 'react-plotly.js';

class StockChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockXValues: [],
            stockYValues: [],
            stockSymbol: '',

        }
}

componentDidMount() {
    this.fetchStock();
}

fetchStock() {
    const pointer = this;
    const symbol = this.props.stockSymbol;

    const API_KEY = `X`;
    let API_Call = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&outputsize=compact&apikey=${API_KEY}`;

    let StockXValuesFunc = [];
    let StockYValuesFunc = [];

    fetch(API_Call)
        .then(
            function(response) {
                return response.json();
            }
        )
        .then(
            function(data) {
                console.log(data);

                for (var key in data['Time Series (Daily)']) {
                    StockXValuesFunc.push(key);
                    StockYValuesFunc.push(data['Time Series (Daily)']
                    [key]['4. close']);
                }
                pointer.setState({
                    stockXValues: StockXValuesFunc,
                    stockYValues: StockYValuesFunc,
                });

            }
        )

}
render() {
  return (
    <div>
        <h2>{this.props.stockSymbol}</h2>
        <Plot
            data={[
            {
                x: this.state.stockXValues,
                y: this.state.stockYValues,
                type: 'scatter',
                mode: 'lines+markers',
                marker: {color: 'red'},
            },
            ]}
            layout={ {width: 720, height: 440, title: 'Closing Price over the last 100 days'} }
        />
    </div>
  )
 }
}
</code>```

Export default StockChart;

答:
What you are looking for is Throttling or Debouncing

Throttling executes a given function after a specified amount of time has elapsed.

Debouncing enforces that a function will not be called again until a certain amount of time has passed since its last call.
In debouncing, it ignores all calls to a function and waits until the function has stopped being called for a specified amount of time.

To apply throttling or debouncing you can use npm packages underscore,lodash or rxjs.

Throttling Example

```<code>    // ...
import { throttle } from lodash;
class autocomp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            results: []
        }
       this.handleInputThrottled = throttle(this.handleInput, 100)
    }
    handleInput = evt => {
        const value = evt.target.value
        const filteredRes = data.filter((item)=> {
            // algorithm to search through the `data` array
        })
        this.setState({ results: filteredRes })
    }
    render() {
        let { results } = this.state;
        return (
            <div className='autocomp_wrapper'>
                <input placeholder="Enter your search.." onChange={this.handleInputThrottled} />
                <div>
                    {results.map(result=>{result})}
                </div>
            </div>
        );
    }
}
</code>```

Debouncing Example

```<code>    // ...
import { debounce } from 'lodash';
class autocomp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            results: []
        }
       this.handleInputThrottled = debounce(this.handleInput, 100)
    }
    handleInput = evt => {
        const value = evt.target.value
        const filteredRes = data.filter((item)=> {
            // algorithm to search through the `data` array
        })
        this.setState({ results: filteredRes })
    }
    render() {
        let { results } = this.state;
        return (
            <div className='autocomp_wrapper'>
                <input placeholder="Enter your search.." onChange={this.handleInputThrottled} />
                <div>
                    {results.map(result=>{result})}
                </div>
            </div>
        );
    }
}
</code>```

Body:
Edit: People from FUTURE: check out this video -

https://www.youtube.com/watch?v=FyxFSkh2wug
and the article provided by Leonardo.

I have a searchbar component and a stockchart component that are both children of the Parent component. I want to re-render the stockchart every time a key is entered in the search bar. I am new to react so please bear with my code.

I tried a shouldComponentUpdate and it made too many API calls. In the CorrectRender function, I tried to return the StockChart everytime ticker changed but it didn't work.

I've tried my best to describe the methods I wrote, please feel free to ask any questions.

This is the Parent component, I'm calling this inside App.js

import React, { Component } from 'react'
import StockChart from './StockChart';
import SearchBar from './SearchBar';

// Renders stockChart when value is entered
// I tried to re-render by using a current and previousTicker symbols but it didn't work.

function CorrectRender(props, oldtick) {
    const ticker = props.props;
    console.log("props", props)
    const previousTicker = props.oldtick;
    if (ticker.length > 0 && previousTicker !== ticker) {
        return

{ticker}

            <StockChart stockSymbol = {ticker} previousTicker={previousTicker}/>

    }
    return null;
    }

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockSymbol: '',
            previousTicker: ''
        }
        this.callbackFunction = this.callbackFunction.bind(this);
    }

    shaveData(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            stockSymbol: value,
        });
    }

    callbackFunction(sS)  {
        this.setState({ previousTicker: this.state.stockSymbol});
        this.shaveData(sS);
    };

    render() {
        return (

                <SearchBar parentCallback = {this.callbackFunction}/>
                <CorrectRender props={this.state.stockSymbol} oldtick={this.state.previousTicker}/>

        )
    }
}

export default Parent;

This is the SEARCHBAR component.

import React, { Component } from 'react';
import './SearchBar.css';

export class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            search: ' ',
            tickerList: [],
        }
    }

    // Get a list of tickers from an API, this is not the api call that is being overused
    // I want the data to show to the user as "Ticker, Company name" which is what the second (.then) is doing
    fetchTickers(stockSymbol) {
        const pointer = this;
        let arr = [];
        console.log(stockSymbol);
        let url = `https://ticker-2e1ica8b9.now.sh/keyword/${stockSymbol}`;

        fetch(url)
            .then( function(response) {
                return response.json();
            })
            .then ( function(data) {
                for (var key in data) {
                    arr.push(data[key]['symbol'] + ", "+ data[key]['name'])
                };

                pointer.setState({
                    tickerList: arr
                })
            }

            )
    }

    // this is for handling keys in the search bar and rendering new results based on the
    critera
    textChange = (e) => {
        const value = e.target.value;
        let arr = [];
        if (value.length > 0) {
            const regex = new RegExp(`^${value}`, 'i');
            this.fetchTickers(value);
            arr = this.state.tickerList.sort().filter(tick => regex.test(tick));
        }
        this.setState({
            tickerList: arr,
            search: value
        });
    }

    // This will be called when an option is chosen by user
    tickerChosen(value) {
        let value1 = value.split(`,`);
        value = value1[0];
        this.setState({
            search: value,
            tickerList: []
        });

    };

    // list of suggestions on user side based on criteria
    tickerSuggestions () {
        const { tickerList } = this.state;
        if (tickerList.length === 0) {
            return null;
        }
        return (

                {tickerList.map((ticker) =>
  {this.props.parentCallback(ticker); this.tickerChosen(ticker);} }>{ticker}
)}

        )
    };

    render() {
        const { search } = this.state;
        return (

                <input value = { search } onChange={this.textChange} type='text' />
                {this.tickerSuggestions()}

        )
    }
}

export default SearchBar

This is the StockChart component.

import React, { Component } from 'react';
import Plot from 'react-plotly.js';

class StockChart extends Component {
    constructor(props) {
        super(props);
        this.state = {
            stockXValues: [],
            stockYValues: [],
            stockSymbol: '',

        }
}

componentDidMount() {
    this.fetchStock();
}

fetchStock() {
    const pointer = this;
    const symbol = this.props.stockSymbol;

    const API_KEY = `X`;
    let API_Call = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${symbol}&outputsize=compact&apikey=${API_KEY}`;

    let StockXValuesFunc = [];
    let StockYValuesFunc = [];

    fetch(API_Call)
        .then(
            function(response) {
                return response.json();
            }
        )
        .then(
            function(data) {
                console.log(data);

                for (var key in data['Time Series (Daily)']) {
                    StockXValuesFunc.push(key);
                    StockYValuesFunc.push(data['Time Series (Daily)']
                    [key]['4. close']);
                }
                pointer.setState({
                    stockXValues: StockXValuesFunc,
                    stockYValues: StockYValuesFunc,
                });

            }
        )

}
render() {
  return (

{this.props.stockSymbol}

        <Plot
            data={[
            {
                x: this.state.stockXValues,
                y: this.state.stockYValues,
                type: 'scatter',
                mode: 'lines+markers',
                marker: {color: 'red'},
            },
            ]}
            layout={ {width: 720, height: 440, title: 'Closing Price over the last 100 days'} }
        />

  )
 }
}

Export default StockChart;

Body:
What you are looking for is Throttling or Debouncing

Throttling executes a given function after a specified amount of time has elapsed.

Debouncing enforces that a function will not be called again until a certain amount of time has passed since its last call.
In debouncing, it ignores all calls to a function and waits until the function has stopped being called for a specified amount of time.

To apply throttling or debouncing you can use npm packages underscore,lodash or rxjs.

Throttling Example

    // ...
import { throttle } from lodash;
class autocomp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            results: []
        }
       this.handleInputThrottled = throttle(this.handleInput, 100)
    }
    handleInput = evt => {
        const value = evt.target.value
        const filteredRes = data.filter((item)=> {
            // algorithm to search through the `data` array
        })
        this.setState({ results: filteredRes })
    }
    render() {
        let { results } = this.state;
        return (
            <div className='autocomp_wrapper'>
                <input placeholder="Enter your search.." onChange={this.handleInputThrottled} />
                <div>
                    {results.map(result=>{result})}
                </div>
            </div>
        );
    }
}

Debouncing Example

    // ...
import { debounce } from 'lodash';
class autocomp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            results: []
        }
       this.handleInputThrottled = debounce(this.handleInput, 100)
    }
    handleInput = evt => {
        const value = evt.target.value
        const filteredRes = data.filter((item)=> {
            // algorithm to search through the `data` array
        })
        this.setState({ results: filteredRes })
    }
    render() {
        let { results } = this.state;
        return (
            <div className='autocomp_wrapper'>
                <input placeholder="Enter your search.." onChange={this.handleInputThrottled} />
                <div>
                    {results.map(result=>{result})}
                </div>
            </div>
        );
    }
}


问:
A difficult SQL query: tag popularity for models with complex associations
I'm not even sure this is possible to do efficiently, but here's my problem:

I'm writing what's essentially a blog engine where a blog post and all replies to each blog post can tagged.

So, I could have a blog post tagged "stack", and a reply to that post tagged "overflow".

Right now, I'm trying to generate a list of the most popular tags when a user hits a special page in my application.  It should return not only the n most popular tags by descending number of blog posts, but also the number of blog posts associated with each tag, even if a reply in that post but not the post itself is tagged with that tag.

So, if BlogPost A is tagged with "foo", and a reply in BlogPost B is tagged with "foo", the popular tag summary should count that as two blog posts in total, even though BlogPost B is not technically tagged.

Here's a description of the tables/fields that might be relevant:

```<code>BlogPosts
| id     # Primary key for all tables, Rails-style

BlogComments
| id
| blog_post_id

Tags
| id
| name   # 'foo'

Taggings
| id
| tag_id
| blog_post_id
| blog_comment_id
</code>```

There's some denormalization in Taggings for the sake of convenience.  If someone tags BlogPost, it fills in the blog_post_id field, and blog_comment_id remains NULL.  If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id.

Is there some way to return a sorted list of the most popular tags in one or several SQL queries?  I'm thinking I might need to just run a computationally-expensive script every few minutes on a cron job and render the cached output instead of running this every time somebody hits the page...

Thanks!

答:
I may be missing something obvious but since you have "If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id", the following sql should do the trick. I'm assuming here that Tags.name here will be unique.

```<code>SELECT MIN(ts.tag_id), t.name, COUNT(ts.blog_post_id) as rank
FROM Taggings ts
    INNER JOIN Tags t ON ts.tag_id = t.id
GROUP BY t.name
ORDER BY COUNT(ts.blog_post_id) DESC
</code>```

Hope that's what your looking for.

OwnerDisplayName: O. Frabjous-Dey

ContentLicense: CC BY-SA 2.5

Body:
I'm not even sure this is possible to do efficiently, but here's my problem:

I'm writing what's essentially a blog engine where a blog post and all replies to each blog post can tagged.

So, I could have a blog post tagged "stack", and a reply to that post tagged "overflow".

Right now, I'm trying to generate a list of the most popular tags when a user hits a special page in my application.  It should return not only the n most popular tags by descending number of blog posts, but also the number of blog posts associated with each tag, even if a reply in that post but not the post itself is tagged with that tag.

So, if BlogPost A is tagged with "foo", and a reply in BlogPost B is tagged with "foo", the popular tag summary should count that as two blog posts in total, even though BlogPost B is not technically tagged.

Here's a description of the tables/fields that might be relevant:

BlogPosts
| id     # Primary key for all tables, Rails-style

BlogComments
| id
| blog_post_id

Tags
| id
| name   # 'foo'

Taggings
| id
| tag_id
| blog_post_id
| blog_comment_id

There's some denormalization in Taggings for the sake of convenience.  If someone tags BlogPost, it fills in the blog_post_id field, and blog_comment_id remains NULL.  If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id.

Is there some way to return a sorted list of the most popular tags in one or several SQL queries?  I'm thinking I might need to just run a computationally-expensive script every few minutes on a cron job and render the cached output instead of running this every time somebody hits the page...

Thanks!

Body:
I may be missing something obvious but since you have "If someone tags a comment to a post, it fills in both blog_post_id and blog_comment_id", the following sql should do the trick. I'm assuming here that Tags.name here will be unique.

SELECT MIN(ts.tag_id), t.name, COUNT(ts.blog_post_id) as rank
FROM Taggings ts
    INNER JOIN Tags t ON ts.tag_id = t.id
GROUP BY t.name
ORDER BY COUNT(ts.blog_post_id) DESC

Hope that's what your looking for.

OwnerDisplayName: Josh


问:
How to create a horizontal bar that stretches across screen but is not in the body tag?
Very basic question!

I have a background pattern that repeats itself throughout the body tag.  I would also like to have a top bar and bottom bar (head/footer) to repeat on the x axis - creating a nice sandwich style of solid color, pattern and solid color again for the background.

How can this be accomplished?

The bars need to be 100% width - which is why this isn't being done through the content wrapper or the header/footer div as they are set to 1000px wide.  The color bars should go across the entire screen.

答:
You should:

Ensure you have html, body { margin: 0; padding: 0 }

Add the #headerBar and #footerBar outside of your "content wrapper".

Something like this: http://jsfiddle.net/GDDA5/

```<code>html, body {
    margin: 0;
    padding: 0
}
#contentWrapper {
    width: 300px;
    margin: 0 auto;
    background: #ccc;
    height: 100px
}
#headerBar {
    height: 40px;
    background: blue
}
#footerBar {
    height: 40px;
    background: red
}
</code>```

Or if you would like the bars to stick to the viewport and be behind content: http://jsfiddle.net/GDDA5/3/

Body:
You should:

Ensure you have html, body { margin: 0; padding: 0 }

Add the #headerBar and #footerBar outside of your "content wrapper".

Something like this: http://jsfiddle.net/GDDA5/

html, body {
    margin: 0;
    padding: 0
}
#contentWrapper {
    width: 300px;
    margin: 0 auto;
    background: #ccc;
    height: 100px
}
#headerBar {
    height: 40px;
    background: blue
}
#footerBar {
    height: 40px;
    background: red
}

Or if you would like the bars to stick to the viewport and be behind content: http://jsfiddle.net/GDDA5/3/


问:
How to use vue-awesome-swiper component only on mobile grid
I have two bootstrap cols with content. On a large scale, cols are getting half of the row and on a mobile scale, cols are getting all row width and sitting one above another, like a typical grid. I want to use the vue-awesome-swiper on a mobile scale so that I can swipe columns instead of scrolling down to a bottom col. At the same time, I don't need swiper on a large scale, where columns fit one-row width. How can I rich it? How to use the vue-awesome-swiper component only on a mobile scale and don't use it on large one.
Some code to illustrate the case:

```<code><div class="row h-100">
   <div class="col gauche">
      <!-- Some content here -->
   </div>
   <div class="col gauche">
      <!-- Some content here -->
    </div>
</div>
</code>```

With swiper:

```<code><div class="row h-100">
   <swiper class="swiper">
     <swiper-slide>
       <div class="col gauche">
          <!-- Some content here -->
       </div>
     </swiper-slide>
     <swiper-slide>
       <div class="col gauche">
          <!-- Some content here -->
       </div>
     </swiper-slide>
   </swiper>
</div>
</code>```

答:
The simple solution to this problem (but not the prettiest), would be to use Bootstrap's display utilities, to define when your slider should show and when your columns should show.

The bad part about this solution is having to define your content twice.
Once for the normal columns, and once for the slides.

In the below example i "swap" at the md breakpoint, but you can change this to what fits your needs.

    <column-content :text="text"></column-content>

    <swiper>
      <swiper-slide v-for="{ text } in items" class="px-2">
        <column-content :text="text"></column-content>
      </swiper-slide>

    </swiper>

```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>Vue.use(VueAwesomeSwiper)

Vue.component('column-content', {
 template: '#column-content',
 props: ['text'],
 data() { return { text: '123'} }
})

new Vue({
  el: '#app',
  data() {
    return {
      items: [
       {
        text: 'Some Text 1'
       },
       {
        text: 'Some Text 2'
       },
      ]
    }
  }
})</code>```

<link href="https://unpkg.com/bootstrap@4.5.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/swiper@5.3.6/css/swiper.min.css" rel="stylesheet"/>

        <column-content :text="text"></column-content>

        <swiper>
          <swiper-slide v-for="{ text } in items" class="px-2">
           <column-content :text="text"></column-content>
          </swiper-slide>

        </swiper>

<template id="column-content">

   {{ text }}

</template>```

Body:
I have two bootstrap cols with content. On a large scale, cols are getting half of the row and on a mobile scale, cols are getting all row width and sitting one above another, like a typical grid. I want to use the vue-awesome-swiper on a mobile scale so that I can swipe columns instead of scrolling down to a bottom col. At the same time, I don't need swiper on a large scale, where columns fit one-row width. How can I rich it? How to use the vue-awesome-swiper component only on a mobile scale and don't use it on large one.
Some code to illustrate the case:

With swiper:

   <swiper class="swiper">
     <swiper-slide>

     </swiper-slide>
     <swiper-slide>

     </swiper-slide>
   </swiper>

Body:
The simple solution to this problem (but not the prettiest), would be to use Bootstrap's display utilities, to define when your slider should show and when your columns should show.

The bad part about this solution is having to define your content twice.
Once for the normal columns, and once for the slides.

In the below example i "swap" at the md breakpoint, but you can change this to what fits your needs.

<div class="row d-none d-md-flex">
  <div class="col-md-6" v-for="{ text } in items">
    <column-content :text="text"></column-content>
  </div>
</div>
<div class="row d-md-none">
  <div class="col-12">
    <swiper>
      <swiper-slide v-for="{ text } in items" class="px-2">
        <column-content :text="text"></column-content>
      </swiper-slide>
      <div class="swiper-pagination"  slot="pagination"></div>
    </swiper>
  </div>
</div>

Vue.use(VueAwesomeSwiper)

Vue.component('column-content', {
 template: '#column-content',
 props: ['text'],
 data() { return { text: '123'} }
})

new Vue({
  el: '#app',
  data() {
    return {
      items: [
       {
        text: 'Some Text 1'
       },
       {
        text: 'Some Text 2'
       },
      ]
    }
  }
})

<link href="https://unpkg.com/bootstrap@4.5.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/swiper@5.3.6/css/swiper.min.css" rel="stylesheet"/>

<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/swiper@5.3.6/js/swiper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-awesome-swiper"></script>

<div id="app">
  <div class="container">
    <div class="row d-none d-md-flex">
      <div class="col-md-6" v-for="{ text } in items">
        <column-content :text="text"></column-content>
      </div>
    </div>
    <div class="row d-md-none">
      <div class="col-12">
        <swiper>
          <swiper-slide v-for="{ text } in items" class="px-2">
           <column-content :text="text"></column-content>
          </swiper-slide>
          <div class="swiper-pagination"  slot="pagination"></div>
        </swiper>
      </div>
    </div>
  </div>
</div>

<template id="column-content">
 <div class="card">
  <div class="card-body">
   {{ text }}
  </div>
 </div>
</template>


问:
Too Many versions of python on my computer
I have too many versions of python on my computer. And, when I try to run my code, my module like pandas, selenium, etc said this error message:

ModuleNotFoundError: No module named 'pandas'.

I have pip and conda install everything but neither version of python works when I choose each of them in VS Code interpreter.

Do you have a solution to uninstall each version of python?

Command prompt:

答:
You need to define the versions of python

```<code>sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2
</code>```

Then you need to choose which version should be defined as default

```<code>sudo update-alternatives --set python /usr/bin/python3.6
</code>```

Alternatively, try pyenv pyenv to manage your python versions.

Body:
You need to define the versions of python

sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2

Then you need to choose which version should be defined as default

sudo update-alternatives --set python /usr/bin/python3.6

Alternatively, try pyenv pyenv to manage your python versions.


问:
NaN by Matrix Factorization
I implemented the matrix factorization using the SGD algorithm but I get frequently the NaN in the predicted matrix when I run it. When I run the algorithm on a very tiny (6 x 7) matrix, the number of times that the error appears is small. As I have moved to the Movie Lens data set I'm getting the error in all cells every time I run the algorithm. The only time that the error disappears in only some of the cells is when I set the optimization steps (no. of iterations) at 1.

    private static Matrix matrixFactorizationLarge (Matrix realRatingMatrix, Matrix factor_1, Matrix factor_2)
    {
        int features = (int) factor_1.getColumnCount();
        double learningRate = 0.02;
        double regularization = 0.02;
        int optimizationSteps = 10;
        Matrix predictedRatingMatrix = SparseMatrix.Factory.zeros(realRatingMatrix.getRowCount(), realRatingMatrix.getColumnCount());

        for (int step = 0; step < optimizationSteps; step++)
        {
            for (int row = 0; row < predictedRatingMatrix.getRowCount(); row++)
            {
                for (int col = 0; col < predictedRatingMatrix.getColumnCount(); col++)
                {
                    if (realRatingMatrix.getAsInt(row, col) > 0)
                    {
                        Matrix vector_1 = getRow(factor_1, row);
                        Matrix vector_2 = getColumn(factor_2, col);
                        predictedRatingMatrix.setAsDouble( ( Math.floor ( dotProduct(vector_1, vector_2) * 100 ) ) / 100, row, col);

                        for (int f = 0; f < features; f++)
                        {
                            factor_1.setAsDouble( ( Math.floor ( ( factor_1.getAsDouble(row, f) + ( learningRate * ( ( calculateDerivative(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col), factor_2.getAsDouble(f, col) ) ) - ( regularization * factor_1.getAsDouble(row, f) ) ) ) ) * 100 ) / 100), row, f);

                            factor_2.setAsDouble( ( Math.floor ( ( factor_2.getAsDouble(f, col) + ( learningRate * ( ( calculateDerivative(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col), factor_1.getAsDouble(row, f) ) ) - ( regularization * factor_2.getAsDouble(f, col) ) ) ) ) * 100 ) / 100), f, col);
                        }
                    }
                }
            }
        }

        return predictedRatingMatrix;
    }
```

<p>The related methods are as follows:</p>

<pre class="lang-java prettyprint-override"><code>
    private static double dotProduct (Matrix vector_A, Matrix vector_B)
    {
        double dotProduct = 0.0;

        for (int index = 0; index < vector_A.getColumnCount(); index++)
        {
            dotProduct =  dotProduct + ( vector_A.getAsDouble(0, index) * vector_B.getAsDouble(0, index) );
        }

        return dotProduct;
    }

    private static double errorOfDotProduct (double original, double dotProduct)
    {
        double error = 0.0;

        error = Math.pow( ( original - dotProduct ), 2 );

        return error;
    }

    private static double calculateDerivative(double realValue, double predictedValue, double value)
    {
        return ( 2 * (realValue - predictedValue) * (value) );
    }

    private static double calculateRMSE (Matrix realRatingMatrix, Matrix predictedRatingMatrix)
    {
        double rmse = 0.0;
        double summation = 0.0;

        for (int row = 0; row < realRatingMatrix.getRowCount(); row++)
        {
            for (int col = 0; col < realRatingMatrix.getColumnCount(); col++)
            {
                if (realRatingMatrix.getAsDouble(row, col) != 0)
                {
                    summation = summation + errorOfDotProduct(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col));
                }
            }
        }

        rmse = Math.sqrt(summation);

        return rmse;
    }

    private static Matrix csvToMatrixLarge (File csvFile)
    {

        Scanner inputStream;
        Matrix realRatingMatrix = SparseMatrix.Factory.zeros(610, 17000);
//      Matrix realRatingMatrix = SparseMatrix.Factory.zeros(6, 7);

        try
        {
            inputStream = new Scanner(csvFile);

            while (inputStream.hasNext()) {
                String ln = inputStream.next();
                String[] values = ln.split(",");

                double rating = Double.parseDouble(values[2]);
                int row = Integer.parseInt(values[0])-1;
                int col = Integer.parseInt(values[1])-1;

                if (col < 1000)
                {
                    realRatingMatrix.setAsDouble(rating, row, col);
                }
            }

            inputStream.close();
        }

        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        return realRatingMatrix;
    }

    private static Matrix createFactorLarge (long rows, long features)
    {
        Matrix factor = DenseMatrix.Factory.zeros(rows, features);

        return factor;
    }

    private static void fillInMatrixLarge (Matrix matrix)
    {
        for (int row = 0; row < matrix.getRowCount() ; row++)
        {
            for (int col = 0; col < matrix.getColumnCount(); col++)
            {
                double random = ThreadLocalRandom.current().nextDouble(5.1);
                matrix.setAsDouble( (Math.floor (random * 10 ) / 10), row, col);
            }
        }

//      return matrix;
    }

    private static Matrix getRow (Matrix matrix, int rowOfIntresst)
    {
        Matrix row = Matrix.Factory.zeros(1, matrix.getColumnCount());

        for (int col = 0; col < matrix.getColumnCount(); col++)
        {
            row.setAsDouble(matrix.getAsDouble(rowOfIntresst, col), 0, col);
        }

        return row;
    }

    private static Matrix getColumn (Matrix matrix, int colOfInteresst)
    {
        Matrix column = Matrix.Factory.zeros(1, matrix.getRowCount());

        for (int index = 0; index < matrix.getRowCount(); index++)
        {
            column.setAsDouble(matrix.getAsDouble(index, colOfInteresst), 0, index);   //column[row] = matrix[row][colOfInteresst];

        }

        return column;
    }
</code>```

What is causing the error as I don't divide with zero in the algorithm? And How can I solve it?

P.S. I'm using the Universal Matrix Library Package

答:
The key to avoid the Not a Number - NaN - error in matrix factorization is to choose the right learning rate. It is important to notice that the right learning rate is always determined in relation to the number of iterations. Below is an example which clarifies the problem:

```<code>No. Of Iterations: 3
Learning Rate: 0.02
Regularization Rate: 0.02
</code>```

We have the following factors as an example in iteration 1 before optimization:

Predicted Rating, row 4 col 2 : ( 4.96 * 1.26 ) + ( 4.9 * 2.25 ) = 17.27

After optimizing the factors we will get:

The row 4 and column 2 get optimized until we come back to them in iteration 2:

Predicted Rating, row 4 col 2: ( -2.31 * 233089.24 ) + ( -1.67 * -888.59 ) = -536952.2

Each cell in row 4 and column 2 get optimized. I will show the optimization steps for row 1 column 1:

```<code>-2.31 + 0.02 [ ( 2 ( 4 + 536952.2 ) ( 233089.24 ) ) - ( 0.02 * -2.31 ) ] =
-2.31 + 0.02 [ ( 2 * 536956.2 * 233089.24 ) - ( 0.02 * -2.31 ) ] =
-2.31 + 0.02 [ ( 250317425142.57 ) - ( 0.04 ) ] =
</code>```

As we can see, at this step we get a very big number for the derivative. The key point here is to choose the right learning rate. The learning rate determines the rate of approaching the minimum. If we make it too large we may miss the minimum by jumping over it and diverging to infinity.

```<code>-2.31 + 0.02 [ 250317425142,53 ] =
-2.31 + 5006348502,85 =
5006348500,54
</code>```

As the optimization continues we will get Infinity for this cell in the next iteration which leads to NaN error when it is added with a number.

By choosing a small learning rate we will avoid the error and swiftly reach the minimum point.

Title: NaN by Matrix Factorization

Body:
I implemented the matrix factorization using the SGD algorithm but I get frequently the NaN in the predicted matrix when I run it. When I run the algorithm on a very tiny (6 x 7) matrix, the number of times that the error appears is small. As I have moved to the Movie Lens data set I'm getting the error in all cells every time I run the algorithm. The only time that the error disappears in only some of the cells is when I set the optimization steps (no. of iterations) at 1.

    private static Matrix matrixFactorizationLarge (Matrix realRatingMatrix, Matrix factor_1, Matrix factor_2)
    {
        int features = (int) factor_1.getColumnCount();
        double learningRate = 0.02;
        double regularization = 0.02;
        int optimizationSteps = 10;
        Matrix predictedRatingMatrix = SparseMatrix.Factory.zeros(realRatingMatrix.getRowCount(), realRatingMatrix.getColumnCount());

        for (int step = 0; step < optimizationSteps; step++)
        {
            for (int row = 0; row < predictedRatingMatrix.getRowCount(); row++)
            {
                for (int col = 0; col < predictedRatingMatrix.getColumnCount(); col++)
                {
                    if (realRatingMatrix.getAsInt(row, col) > 0)
                    {
                        Matrix vector_1 = getRow(factor_1, row);
                        Matrix vector_2 = getColumn(factor_2, col);
                        predictedRatingMatrix.setAsDouble( ( Math.floor ( dotProduct(vector_1, vector_2) * 100 ) ) / 100, row, col);

                        for (int f = 0; f < features; f++)
                        {
                            factor_1.setAsDouble( ( Math.floor ( ( factor_1.getAsDouble(row, f) + ( learningRate * ( ( calculateDerivative(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col), factor_2.getAsDouble(f, col) ) ) - ( regularization * factor_1.getAsDouble(row, f) ) ) ) ) * 100 ) / 100), row, f);

                            factor_2.setAsDouble( ( Math.floor ( ( factor_2.getAsDouble(f, col) + ( learningRate * ( ( calculateDerivative(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col), factor_1.getAsDouble(row, f) ) ) - ( regularization * factor_2.getAsDouble(f, col) ) ) ) ) * 100 ) / 100), f, col);
                        }
                    }
                }
            }
        }

        return predictedRatingMatrix;
    }

The related methods are as follows:

    private static double dotProduct (Matrix vector_A, Matrix vector_B)
    {
        double dotProduct = 0.0;

        for (int index = 0; index < vector_A.getColumnCount(); index++)
        {
            dotProduct =  dotProduct + ( vector_A.getAsDouble(0, index) * vector_B.getAsDouble(0, index) );
        }

        return dotProduct;
    }

    private static double errorOfDotProduct (double original, double dotProduct)
    {
        double error = 0.0;

        error = Math.pow( ( original - dotProduct ), 2 );

        return error;
    }

    private static double calculateDerivative(double realValue, double predictedValue, double value)
    {
        return ( 2 * (realValue - predictedValue) * (value) );
    }

    private static double calculateRMSE (Matrix realRatingMatrix, Matrix predictedRatingMatrix)
    {
        double rmse = 0.0;
        double summation = 0.0;

        for (int row = 0; row < realRatingMatrix.getRowCount(); row++)
        {
            for (int col = 0; col < realRatingMatrix.getColumnCount(); col++)
            {
                if (realRatingMatrix.getAsDouble(row, col) != 0)
                {
                    summation = summation + errorOfDotProduct(realRatingMatrix.getAsDouble(row, col), predictedRatingMatrix.getAsDouble(row, col));
                }
            }
        }

        rmse = Math.sqrt(summation);

        return rmse;
    }

    private static Matrix csvToMatrixLarge (File csvFile)
    {

        Scanner inputStream;
        Matrix realRatingMatrix = SparseMatrix.Factory.zeros(610, 17000);
//      Matrix realRatingMatrix = SparseMatrix.Factory.zeros(6, 7);

        try
        {
            inputStream = new Scanner(csvFile);

            while (inputStream.hasNext()) {
                String ln = inputStream.next();
                String[] values = ln.split(",");

                double rating = Double.parseDouble(values[2]);
                int row = Integer.parseInt(values[0])-1;
                int col = Integer.parseInt(values[1])-1;

                if (col < 1000)
                {
                    realRatingMatrix.setAsDouble(rating, row, col);
                }
            }

            inputStream.close();
        }

        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }

        return realRatingMatrix;
    }

    private static Matrix createFactorLarge (long rows, long features)
    {
        Matrix factor = DenseMatrix.Factory.zeros(rows, features);

        return factor;
    }

    private static void fillInMatrixLarge (Matrix matrix)
    {
        for (int row = 0; row < matrix.getRowCount() ; row++)
        {
            for (int col = 0; col < matrix.getColumnCount(); col++)
            {
                double random = ThreadLocalRandom.current().nextDouble(5.1);
                matrix.setAsDouble( (Math.floor (random * 10 ) / 10), row, col);
            }
        }

//      return matrix;
    }

    private static Matrix getRow (Matrix matrix, int rowOfIntresst)
    {
        Matrix row = Matrix.Factory.zeros(1, matrix.getColumnCount());

        for (int col = 0; col < matrix.getColumnCount(); col++)
        {
            row.setAsDouble(matrix.getAsDouble(rowOfIntresst, col), 0, col);
        }

        return row;
    }

    private static Matrix getColumn (Matrix matrix, int colOfInteresst)
    {
        Matrix column = Matrix.Factory.zeros(1, matrix.getRowCount());

        for (int index = 0; index < matrix.getRowCount(); index++)
        {
            column.setAsDouble(matrix.getAsDouble(index, colOfInteresst), 0, index);   //column[row] = matrix[row][colOfInteresst];

        }

        return column;
    }

What is causing the error as I don't divide with zero in the algorithm? And How can I solve it?

P.S. I'm using the Universal Matrix Library Package

Body:
The key to avoid the Not a Number - NaN - error in matrix factorization is to choose the right learning rate. It is important to notice that the right learning rate is always determined in relation to the number of iterations. Below is an example which clarifies the problem:

No. Of Iterations: 3
Learning Rate: 0.02
Regularization Rate: 0.02

We have the following factors as an example in iteration 1 before optimization:

Predicted Rating, row 4 col 2 : ( 4.96 * 1.26 ) + ( 4.9 * 2.25 ) = 17.27

After optimizing the factors we will get:

The row 4 and column 2 get optimized until we come back to them in iteration 2:

Predicted Rating, row 4 col 2: ( -2.31 * 233089.24 ) + ( -1.67 * -888.59 ) = -536952.2

Each cell in row 4 and column 2 get optimized. I will show the optimization steps for row 1 column 1:

-2.31 + 0.02 [ ( 2 ( 4 + 536952.2 ) ( 233089.24 ) ) - ( 0.02 * -2.31 ) ] =
-2.31 + 0.02 [ ( 2 * 536956.2 * 233089.24 ) - ( 0.02 * -2.31 ) ] =
-2.31 + 0.02 [ ( 250317425142.57 ) - ( 0.04 ) ] =

As we can see, at this step we get a very big number for the derivative. The key point here is to choose the right learning rate. The learning rate determines the rate of approaching the minimum. If we make it too large we may miss the minimum by jumping over it and diverging to infinity.

-2.31 + 0.02 [ 250317425142,53 ] =
-2.31 + 5006348502,85 =
5006348500,54

As the optimization continues we will get Infinity for this cell in the next iteration which leads to NaN error when it is added with a number.

By choosing a small learning rate we will avoid the error and swiftly reach the minimum point.


问:
Is it actually possible to use generics when defining mappings in Orika?
I know about that type erasure and would prevent to use generics when defining mappings, as this question points out how to map generics objects with Orika?. But Orika FAQ, on the Are generics supported section, claims:

Yes. Orika includes special runtime support for the mapping of generic types via a special Type class which can be used to define the exact type elements of a templated type.

Ideally something like the following should work (supposing we can somehow maintain the class parameters at runtime through some Orika functionality):

```<code>     mapperFactory.classMap(Asset<T,K>.class, AssetDto<K>.class)
    .maybeSomeCustomization...
    .byDefault()
    .register();
</code>```

I was not able to find any example about the Type<?> class usage the Orika FAQ mentions.

答:
You can use the TypeBuilder API to retain the generic type information so that Orika can use it when performing the mapping.

Note that Java doesn't allow us to specify the type parameter in Class literals. For example, we can't write Asset<Book>.class. Furthermore, due to type erasure, we can't access the actual type parameter at runtime. In short raw types - i.e. Asset.class - don't provide enough information to Orika.

So firstly, we must create the generic types using TypeBuilder:

```<code>Type<Asset<Person>> sourceType = new TypeBuilder<Asset<Person>>() {}.build();
Type<AssetDto<Person>> targetType = new TypeBuilder<AssetDto<Person>>(){}.build();
</code>```

Then in the classMap invocation, we must use these types:

```<code>factory.classMap(sourceType, targetType).byDefault().register();
</code>```

Lastly, we can perform the mapping using these types:

```<code>factory.getMapperFacade().map(asset, sourceType, targetType);
</code>```

Read the following post for a detailed explanation of generics usage with Orika.

Body:
I know about that type erasure and would prevent to use generics when defining mappings, as this question points out how to map generics objects with Orika?. But Orika FAQ, on the Are generics supported section, claims:

Yes. Orika includes special runtime support for the mapping of generic types via a special Type class which can be used to define the exact type elements of a templated type.

Ideally something like the following should work (supposing we can somehow maintain the class parameters at runtime through some Orika functionality):

     mapperFactory.classMap(Asset<T,K>.class, AssetDto<K>.class)
    .maybeSomeCustomization...
    .byDefault()
    .register();

I was not able to find any example about the Type<?> class usage the Orika FAQ mentions.

Body:
You can use the TypeBuilder API to retain the generic type information so that Orika can use it when performing the mapping.

Note that Java doesn't allow us to specify the type parameter in Class literals. For example, we can't write Asset<Book>.class. Furthermore, due to type erasure, we can't access the actual type parameter at runtime. In short raw types - i.e. Asset.class - don't provide enough information to Orika.

So firstly, we must create the generic types using TypeBuilder:

Type<Asset<Person>> sourceType = new TypeBuilder<Asset<Person>>() {}.build();
Type<AssetDto<Person>> targetType = new TypeBuilder<AssetDto<Person>>(){}.build();

Then in the classMap invocation, we must use these types:

factory.classMap(sourceType, targetType).byDefault().register();

Lastly, we can perform the mapping using these types:

factory.getMapperFacade().map(asset, sourceType, targetType);

Read the following post for a detailed explanation of generics usage with Orika.


问:
col-lg-2 col-md-4 col-6 not working on bootstrap 4. At mobile view they appear with col-md-4 not col-6
```<code><div class="container">
  <div class="row space">
         <div class="col-sm-12 col-md-4 col-lg-2">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-sm-12 col-md-4 col-lg-2">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-6">
            <a href="#"><img src="" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
</div>
</div>
</code>```

This is the code and on large screens they appear col-2 but at medium and small they appear col-4.

答:
You are probably checking it on a different sized device. if you need to apply css for extra small devices use col-6(which is not there in your above code) instead of col-sm-6. or may be both as per your requirement. Please find the guidelines for using grid layout of bootstrap.

The Bootstrap 4 grid system has five classes:

```<code>.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)
</code>```

In your code,  you can do this.

```<code><div class="container">
  <div class="row space">
         <div class="col-lg-2 col-md-4 col-sm-6 col-6">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-lg-2 col-md-4  col-sm-6 col-6">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-lg-2 col-md-4  col-sm-6 col-6">
            <a href="#"><img src="" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
</div>
</div>
</code>```

Body:
                Description

                Description

                Description

This is the code and on large screens they appear col-2 but at medium and small they appear col-4.

Body:
You are probably checking it on a different sized device. if you need to apply css for extra small devices use col-6(which is not there in your above code) instead of col-sm-6. or may be both as per your requirement. Please find the guidelines for using grid layout of bootstrap.

The Bootstrap 4 grid system has five classes:

.col- (extra small devices - screen width less than 576px)
.col-sm- (small devices - screen width equal to or greater than 576px)
.col-md- (medium devices - screen width equal to or greater than 768px)
.col-lg- (large devices - screen width equal to or greater than 992px)
.col-xl- (xlarge devices - screen width equal to or greater than 1200px)

In your code,  you can do this.

<div class="container">
  <div class="row space">
         <div class="col-lg-2 col-md-4 col-sm-6 col-6">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-lg-2 col-md-4  col-sm-6 col-6">
            <a href="#"><img src="background.jpeg" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
        <div class="col-lg-2 col-md-4  col-sm-6 col-6">
            <a href="#"><img src="" class="img-thumbnail"></a>
            <p class="text-center">
                <label>Description</label>
            </p>
        </div>
</div>
</div>


问:
PHP braces { } replace <?php ?>?
I've seen in someones source code they load template.tpl and inside is ...value="{$phcode}"...
does {$phcode} replace <?php $phcode ?>

I don't find any reference in php manual.

答: No, {} doesn't replace <?php ?>, at least not as far as the PHP language is concerned.  It's possible that your template engine searches for things inside {} and then passes them to eval().

Title: PHP braces { } replace <?php ?>?


问:
Oneliner to create a dictionary from two lists in Python
I want to create this dictionary, but using one liner.

```<code>{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}
</code>```

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

```<code>dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension
</code>```

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

```<code># This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}
</code>```

答:
import itertools; {f'{goods}_last_{amount}': 'buy' for goods, amount in itertools.product(['apple','mango','banana'], ['kg','3kg','4kg','6kg'])}
```

Body:
I want to create this dictionary, but using one liner.

{'apple_last_6kg':'buy','mango_last_6kg':'buy','banana_last_6kg':'buy',
 'apple_last_4kg':'buy','mango_last_4kg':'buy','banana_last_4kg':'buy',
 'apple_last_3kg':'buy','mango_last_3kg':'buy','banana_last_3kg':'buy',
 'apple_last_kg':'buy','mango_last_kg':'buy','banana_last_kg':'buy'}

This is what I initially tried and got the error, though {**{'a':1},**{'b':2}} works perfectly and gives {'a':1,'b':2}, but using this formulation in dictionary comprehension gives error.:

dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
print(dic2)
File "<ipython-input-238-9332e6a46412>", line 29
    dic2 = {**{i+'_last_'+time:'buy' for i in ['apple','mango','banana']} for time in ['kg','3kg','4kg','6kg']}
          ^
SyntaxError: dict unpacking cannot be used in dict comprehension

I solved this like below, but I would like to have a one liner dictionay-comprehension like solution. Any suggestions?

# This solution is unelegant, so I don't want to use this.
dic2 = [{i+'_last_'+j:'buy' for i in ['apple','mango','banana']} for j in ['kg','3kg','4kg','6kg']]

new_dic = {}
for d in dic2:
    new_dic.update(d)
print(new_dic)
{'apple_last_3kg': 'buy','apple_last_4kg': 'buy','apple_last_6kg': 'buy',
 'apple_last_kg': 'buy','banana_last_3kg': 'buy','banana_last_4kg': 'buy',
 'banana_last_6kg': 'buy','banana_last_kg': 'buy','mango_last_3kg': 'buy',
 'mango_last_4kg': 'buy','mango_last_6kg': 'buy','mango_last_kg': 'buy'}


问:
How does Google Analytics track URL with trailing slash and without?
Saw in my analytics that the two URLs are tracked separately, one with trailing / and one without /. Is this the case of user inputting the URL without / which is already tracked upon pageload? </p>

答:
Yes, this may be the most plausible reason. This happens if the page can be both with or without trailing slashes.
You can fix it with a filter in Google Analytics view that rewrites the URL if it does not contain the trailing slashes.


问:
How to use gapi for sending email in Angular 9
I created once service in angular9 and call google api for sending email but it doesn't work. may someone help what should I do? I tried many other ways but no one of them worked.

```<code>sendEmail() {
    const scopes = [
      'https://www.googleapis.com/auth/gmail.send',
    ].join(' ');

    const message =
      "From: sample@gmail.com\r\n" +
      "To: sample2@gmail.com\r\n" +
      "Subject: As basic as it gets\r\n\r\n" +
      "This is the plain text body of the message.  Note the blank line between the header information and the body of the message.";

    const encodedMessage = btoa(message)

    const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

    gapi.load('client:auth2', () => {
      gapi.client.load('gmail', 'v1', () => {
        console.log('Loaded Gmail');
        gapi.client.init({
          apiKey: this.apiKey,
          discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
          client_id: this.clientId,
          immediate: true,
          scope: scopes
        }).then(res => {
          console.log('pop')
          return gapi.client.gmail.users.messages.send({
            userId: 'me',
            requestBody: {
              raw: reallyEncodedMessage
            }
          }).then(res => {
            console.log("done!", res)
          });
        })
      });
    });
  }
</code>```

response from gapi:

```<code>kind: "discovery#restDescription"
id: "gmail:v1"
name: "gmail"
version: "v1"
rootUrl: "https://www.googleapis.com/"
servicePath: "gmail/v1/users/"
batchPath: "batch/gmail/v1"
</code>```

...

答:
Following the JavaScript example on the Gmail api reference, you have to change your request:

From:

```<code>gapi.client.gmail.users.messages.send({
    userId: 'me',
    requestBody: {
        raw: reallyEncodedMessage
    }
})
</code>```

To:

```<code>gapi.client.gmail.users.messages.send({
    'userId': userId,
    'resource': {
      'raw': base64EncodedEmail
    }
  })

</code>```

If this doesn't solve it please comment on the answer or provide more information on the question.

Body:
I created once service in angular9 and call google api for sending email but it doesn't work. may someone help what should I do? I tried many other ways but no one of them worked.

sendEmail() {
    const scopes = [
      'https://www.googleapis.com/auth/gmail.send',
    ].join(' ');

    const message =
      "From: sample@gmail.com\r\n" +
      "To: sample2@gmail.com\r\n" +
      "Subject: As basic as it gets\r\n\r\n" +
      "This is the plain text body of the message.  Note the blank line between the header information and the body of the message.";

    const encodedMessage = btoa(message)

    const reallyEncodedMessage = encodedMessage.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')

    gapi.load('client:auth2', () => {
      gapi.client.load('gmail', 'v1', () => {
        console.log('Loaded Gmail');
        gapi.client.init({
          apiKey: this.apiKey,
          discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest'],
          client_id: this.clientId,
          immediate: true,
          scope: scopes
        }).then(res => {
          console.log('pop')
          return gapi.client.gmail.users.messages.send({
            userId: 'me',
            requestBody: {
              raw: reallyEncodedMessage
            }
          }).then(res => {
            console.log("done!", res)
          });
        })
      });
    });
  }

response from gapi:

kind: "discovery#restDescription"
id: "gmail:v1"
name: "gmail"
version: "v1"
rootUrl: "https://www.googleapis.com/"
servicePath: "gmail/v1/users/"
batchPath: "batch/gmail/v1"

...

Body:
Following the JavaScript example on the Gmail api reference, you have to change your request:

From:

gapi.client.gmail.users.messages.send({
    userId: 'me',
    requestBody: {
        raw: reallyEncodedMessage
    }
})

To:

gapi.client.gmail.users.messages.send({
    'userId': userId,
    'resource': {
      'raw': base64EncodedEmail
    }
  })

If this doesn't solve it please comment on the answer or provide more information on the question.


问:
How to get terminal window inside Visual Studio 2017 / 2019?
I was just reading this article - https://devblogs.microsoft.com/dotnet/visual-studio-2019-net-productivity-2/ and noticed in one of the GIF image, she is showing a terminal window inside VS editor itself. It looks like a fully fledged powershell window. How can we get that? Here is a screenshot.

答:
It is now available in VS 2019 version 16.6: https://devblogs.microsoft.com/visualstudio/the-powershell-you-know-and-love-now-with-a-side-of-visual-studio/

However, I still prefer Whack Whack since you can't seem to change the font size.